├── .gitignore ├── .hsdoc ├── docs └── quickstart.md ├── component.json ├── package.json ├── bower.json ├── LICENSE ├── spec ├── vendor │ ├── jasmine-1.3.1 │ │ ├── lib │ │ │ └── jasmine-1.3.1 │ │ │ │ ├── MIT.LICENSE │ │ │ │ ├── jasmine.css │ │ │ │ └── jasmine-html.js │ │ └── SpecRunner.html │ ├── underscore-1.5.2 │ │ └── underscore.js │ └── backbone-1.0.0 │ │ └── backbone.js ├── bucky.spec.coffee └── bucky.spec.js ├── Gruntfile.coffee ├── bucky.min.js ├── README.md ├── bucky.coffee └── bucky.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /.hsdoc: -------------------------------------------------------------------------------- 1 | name: "Bucky Client" 2 | source: "bucky.coffee" 3 | assets: "bucky.js" 4 | -------------------------------------------------------------------------------- /docs/quickstart.md: -------------------------------------------------------------------------------- 1 | ```javascript 2 | // Make sure you have included bucky.js or bucky.min.js on your page 3 | 4 | Bucky.setOptions({ 5 | host: "/bucky" 6 | }); 7 | 8 | Bucky.sendPagePerformance('my.app.here.page'); 9 | Bucky.requests.monitor('my.app.here.requests'); 10 | ``` 11 | -------------------------------------------------------------------------------- /component.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bucky", 3 | "repo": "HubSpot/bucky", 4 | "description": "Collect performance data from the client", 5 | "version": "0.2.8", 6 | "homepage": "http://github.hubspot.com/BuckyClient", 7 | "license": "MIT", 8 | "keywords": [ 9 | "client-side", 10 | "statistics", 11 | "data", 12 | "graphite" 13 | ], 14 | "scripts": [ 15 | "bucky.js" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bucky", 3 | "version": "0.2.8", 4 | "description": "Collect performance data from the client and node", 5 | "main": "./bucky.js", 6 | "dependencies": { 7 | "xmlhttprequest": "~1.6.0" 8 | }, 9 | "devDependencies": { 10 | "grunt-contrib-concat": "~0.3.0", 11 | "grunt-contrib-coffee": "~0.7.0", 12 | "grunt-cli": "~0.1.9", 13 | "grunt-contrib-uglify": "~0.2.4", 14 | "grunt": "~0.4.1", 15 | "grunt-contrib-jasmine": "~0.5.2", 16 | "grunt-contrib-watch": "~0.5.3", 17 | "coffee-script": "~1.6.3" 18 | }, 19 | "author": "Zack Bloom " 20 | } 21 | -------------------------------------------------------------------------------- /bower.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "bucky", 3 | "description": "Collect performance data from the client", 4 | "main": "bucky.js", 5 | "homepage": "http://github.hubspot.com/bucky", 6 | "author": "Zack Bloom ", 7 | "license": "MIT", 8 | "repository": { 9 | "type": "git", 10 | "url": "git@github.com:HubSpot/BuckyClient.git" 11 | }, 12 | "keywords": [ 13 | "client-side", 14 | "statistics", 15 | "data", 16 | "graphite", 17 | "bucky", 18 | "OpenTSDB" 19 | ], 20 | "ignore": [ 21 | "**/.*", 22 | "node_modules", 23 | "bower_components", 24 | "test", 25 | "tests" 26 | ] 27 | } 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2013 HubSpot, Inc. 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | 9 | -------------------------------------------------------------------------------- /spec/vendor/jasmine-1.3.1/lib/jasmine-1.3.1/MIT.LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008-2011 Pivotal Labs 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /Gruntfile.coffee: -------------------------------------------------------------------------------- 1 | module.exports = (grunt) -> 2 | grunt.initConfig 3 | pkg: grunt.file.readJSON("package.json") 4 | coffee: 5 | compile: 6 | files: 7 | 'bucky.js': 'bucky.coffee' 8 | 'spec/bucky.spec.js': 'spec/bucky.spec.coffee' 9 | 10 | watch: 11 | coffee: 12 | files: ['bucky.coffee', 'spec/bucky.spec.coffee'] 13 | tasks: ["coffee", "uglify"] 14 | 15 | uglify: 16 | options: 17 | banner: "/*! <%= pkg.name %> <%= pkg.version %> */\n" 18 | 19 | dist: 20 | src: 'bucky.js' 21 | dest: 'bucky.min.js' 22 | 23 | jasmine: 24 | options: 25 | specs: ['spec/bucky.spec.js'] 26 | src: [ 27 | 'spec/vendor/jquery-1.10.2/jquery.js', 28 | 'spec/vendor/underscore-1.5.2/underscore.js', 29 | 'spec/vendor/backbone-1.0.0/backbone.js', 30 | 'spec/vendor/sinon-1.7.3/sinon.js', 31 | 'bucky.js' 32 | ] 33 | 34 | grunt.loadNpmTasks 'grunt-contrib-watch' 35 | grunt.loadNpmTasks 'grunt-contrib-uglify' 36 | grunt.loadNpmTasks 'grunt-contrib-coffee' 37 | grunt.loadNpmTasks 'grunt-contrib-jasmine' 38 | 39 | grunt.registerTask 'default', ['coffee', 'uglify'] 40 | grunt.registerTask 'build', ['coffee', 'uglify', 'jasmine'] 41 | grunt.registerTask 'test', ['coffee', 'uglify', 'jasmine'] 42 | -------------------------------------------------------------------------------- /spec/vendor/jasmine-1.3.1/SpecRunner.html: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | Jasmine Spec Runner 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /spec/bucky.spec.coffee: -------------------------------------------------------------------------------- 1 | describe 'The Bucky Object', -> 2 | it 'should be defined', -> 3 | expect(Bucky).toBeDefined() 4 | 5 | it 'should itself be a client', -> 6 | expect(Bucky.send).toBeDefined() 7 | expect(Bucky.timer).toBeDefined() 8 | expect(Bucky.count).toBeDefined() 9 | expect(Bucky.requests).toBeDefined() 10 | 11 | it 'should create clients when called', -> 12 | expect(Bucky().send).toBeDefined() 13 | 14 | describe 'A Bucky Client', -> 15 | client = null 16 | 17 | beforeEach -> 18 | client = Bucky('prefix') 19 | 20 | it 'should have a send method', -> 21 | expect(client.send).toBeDefined() 22 | 23 | describe 'setOptions', -> 24 | it 'should set options', -> 25 | Bucky.setOptions 26 | host: '/test' 27 | 28 | expect(Bucky.options.host).toBe('/test') 29 | 30 | describe 'getFullUrl', -> 31 | it 'should add the hostname if the url starts with slash', -> 32 | expect(Bucky.requests.getFullUrl('/test', {hostname: 'host'})).toBe('host/test') 33 | 34 | describe 'urlToKey', -> 35 | utk = Bucky.requests.urlToKey 36 | 37 | it 'should convert slashes to dots', -> 38 | expect(utk('a/b/c')).toBe('a.b.c') 39 | 40 | it 'should add the method', -> 41 | expect(utk('x', 'GET')).toBe('x.get') 42 | 43 | it 'should strip leading and trailing slashes', -> 44 | expect(utk('/a/b/c/')).toBe('a.b.c') 45 | 46 | it 'should strip get parameters', -> 47 | url = '/contacts/53/lists/ajax/list/all/detail?properties=%5B%22firstname%22%2C%22lastname%22%2C%22photo%22%2C%22twitterhandle%22%2C%22twitterprofilephoto%22%2C%22website%22%2C%22company%22%2C%22lifecyclestage%22%2C%22city%22%2C%22state%22%2C%22twitterhandle%22%2C%22phone%22%2C%22email%22%5D&offset=0&vidOffset=0&count=100&recent=true' 48 | res = 'contacts.lists.ajax.list.all.detail' 49 | 50 | expect(utk(url)).toBe(res) 51 | 52 | it 'should strip url hashes', -> 53 | expect(utk('/test/abc#page')).toBe('test.abc') 54 | expect(utk('http://app.hubspot.com/analyze/landing-pages/#range=custom&frequency=weekly&start=03&end=06events')).toBe('app.hubspot.analyze.landing-pages') 55 | 56 | it 'should strip ids', -> 57 | expect(utk('test/33/test/3423421')).toBe('test.test') 58 | expect(utk('a/b/432;234;232334;23;23/c')).toBe('a.b.c') 59 | expect(utk('fdf/443_34223424_324')).toBe('fdf') 60 | expect(utk('/344-432/test')).toBe('test') 61 | 62 | it 'should strip .com and www.', -> 63 | expect(utk('http://www.google.com/test/site')).toBe('google.test.site') 64 | 65 | it 'should add the passed in root', -> 66 | expect(utk('test/as', null, 'root')).toBe('root.test.as') 67 | 68 | it 'should strip email addresses', -> 69 | expect(utk('test/page/zack@comnet.org/me')).toBe('test.page.me') 70 | 71 | it 'should strip domain names in the path', -> 72 | expect(utk('test/page/hubspot.com/me')).toBe('test.page.me') 73 | 74 | it 'should strip port numbers in the host', -> 75 | expect(utk('http://www.awesome.com:1337/test/page')).toBe('awesome.test.page') 76 | 77 | it 'should strip guids', -> 78 | expect(utk('https://app.hubspot.com/content/53/cta/clone/05abcf1a-b5e3-4e48-9817-c003ad16660a')).toBe('app.hubspot.content.cta.clone') 79 | 80 | it 'should strip hashes', -> 81 | expect(utk('https://app.hubspot.com/analyze/53/api/pages/v3/pages/bd61568a93fc45637b8dceca1a34551b46627d26?errorsDismissed=1')).toBe('app.hubspot.analyze.api.pages.v3.pages') 82 | expect(utk('https://app.hubspot.com/analyze/53/api/pages/v3/pages/098F6BCD4621D373CADE4E832627B4F6')).toBe('app.hubspot.analyze.api.pages.v3.pages') 83 | 84 | it 'should decode uri entities', -> 85 | expect(utk('test/it%20expect/it/to/work')).toBe('test.it.expect.it.to.work') 86 | 87 | it 'should convert colons to underscores', -> 88 | expect(utk('test/path:with:colons/yea')).toBe('test.path_with_colons.yea') 89 | 90 | describe 'send', -> 91 | server = null 92 | 93 | beforeEach -> 94 | server = sinon.fakeServer.create() 95 | server.autoRespond = true 96 | 97 | afterEach -> 98 | server.restore() 99 | 100 | it 'should send a datapoint', -> 101 | Bucky.send 'data.point', 4 102 | Bucky.flush() 103 | 104 | expect(server.requests.length).toBe(1) 105 | expect(server.requests[0].requestBody).toBe("data.point:4|g\n") 106 | 107 | it 'should send timers', -> 108 | Bucky.send 'data.1', 5, 'timer' 109 | Bucky.send 'data.2', 3, 'timer' 110 | Bucky.flush() 111 | 112 | expect(server.requests.length).toBe(1) 113 | 114 | expect(server.requests[0].requestBody).toBe("data.1:5|ms\ndata.2:3|ms\n") 115 | -------------------------------------------------------------------------------- /spec/bucky.spec.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | describe('The Bucky Object', function() { 3 | it('should be defined', function() { 4 | return expect(Bucky).toBeDefined(); 5 | }); 6 | it('should itself be a client', function() { 7 | expect(Bucky.send).toBeDefined(); 8 | expect(Bucky.timer).toBeDefined(); 9 | expect(Bucky.count).toBeDefined(); 10 | return expect(Bucky.requests).toBeDefined(); 11 | }); 12 | return it('should create clients when called', function() { 13 | return expect(Bucky().send).toBeDefined(); 14 | }); 15 | }); 16 | 17 | describe('A Bucky Client', function() { 18 | var client; 19 | client = null; 20 | beforeEach(function() { 21 | return client = Bucky('prefix'); 22 | }); 23 | return it('should have a send method', function() { 24 | return expect(client.send).toBeDefined(); 25 | }); 26 | }); 27 | 28 | describe('setOptions', function() { 29 | return it('should set options', function() { 30 | Bucky.setOptions({ 31 | host: '/test' 32 | }); 33 | return expect(Bucky.options.host).toBe('/test'); 34 | }); 35 | }); 36 | 37 | describe('getFullUrl', function() { 38 | return it('should add the hostname if the url starts with slash', function() { 39 | return expect(Bucky.requests.getFullUrl('/test', { 40 | hostname: 'host' 41 | })).toBe('host/test'); 42 | }); 43 | }); 44 | 45 | describe('urlToKey', function() { 46 | var utk; 47 | utk = Bucky.requests.urlToKey; 48 | it('should convert slashes to dots', function() { 49 | return expect(utk('a/b/c')).toBe('a.b.c'); 50 | }); 51 | it('should add the method', function() { 52 | return expect(utk('x', 'GET')).toBe('x.get'); 53 | }); 54 | it('should strip leading and trailing slashes', function() { 55 | return expect(utk('/a/b/c/')).toBe('a.b.c'); 56 | }); 57 | it('should strip get parameters', function() { 58 | var res, url; 59 | url = '/contacts/53/lists/ajax/list/all/detail?properties=%5B%22firstname%22%2C%22lastname%22%2C%22photo%22%2C%22twitterhandle%22%2C%22twitterprofilephoto%22%2C%22website%22%2C%22company%22%2C%22lifecyclestage%22%2C%22city%22%2C%22state%22%2C%22twitterhandle%22%2C%22phone%22%2C%22email%22%5D&offset=0&vidOffset=0&count=100&recent=true'; 60 | res = 'contacts.lists.ajax.list.all.detail'; 61 | return expect(utk(url)).toBe(res); 62 | }); 63 | it('should strip url hashes', function() { 64 | expect(utk('/test/abc#page')).toBe('test.abc'); 65 | return expect(utk('http://app.hubspot.com/analyze/landing-pages/#range=custom&frequency=weekly&start=03&end=06events')).toBe('app.hubspot.analyze.landing-pages'); 66 | }); 67 | it('should strip ids', function() { 68 | expect(utk('test/33/test/3423421')).toBe('test.test'); 69 | expect(utk('a/b/432;234;232334;23;23/c')).toBe('a.b.c'); 70 | expect(utk('fdf/443_34223424_324')).toBe('fdf'); 71 | return expect(utk('/344-432/test')).toBe('test'); 72 | }); 73 | it('should strip .com and www.', function() { 74 | return expect(utk('http://www.google.com/test/site')).toBe('google.test.site'); 75 | }); 76 | it('should add the passed in root', function() { 77 | return expect(utk('test/as', null, 'root')).toBe('root.test.as'); 78 | }); 79 | it('should strip email addresses', function() { 80 | return expect(utk('test/page/zack@comnet.org/me')).toBe('test.page.me'); 81 | }); 82 | it('should strip domain names in the path', function() { 83 | return expect(utk('test/page/hubspot.com/me')).toBe('test.page.me'); 84 | }); 85 | it('should strip port numbers in the host', function() { 86 | return expect(utk('http://www.awesome.com:1337/test/page')).toBe('awesome.test.page'); 87 | }); 88 | it('should strip guids', function() { 89 | return expect(utk('https://app.hubspot.com/content/53/cta/clone/05abcf1a-b5e3-4e48-9817-c003ad16660a')).toBe('app.hubspot.content.cta.clone'); 90 | }); 91 | it('should strip hashes', function() { 92 | expect(utk('https://app.hubspot.com/analyze/53/api/pages/v3/pages/bd61568a93fc45637b8dceca1a34551b46627d26?errorsDismissed=1')).toBe('app.hubspot.analyze.api.pages.v3.pages'); 93 | return expect(utk('https://app.hubspot.com/analyze/53/api/pages/v3/pages/098F6BCD4621D373CADE4E832627B4F6')).toBe('app.hubspot.analyze.api.pages.v3.pages'); 94 | }); 95 | it('should decode uri entities', function() { 96 | return expect(utk('test/it%20expect/it/to/work')).toBe('test.it.expect.it.to.work'); 97 | }); 98 | return it('should convert colons to underscores', function() { 99 | return expect(utk('test/path:with:colons/yea')).toBe('test.path_with_colons.yea'); 100 | }); 101 | }); 102 | 103 | describe('send', function() { 104 | var server; 105 | server = null; 106 | beforeEach(function() { 107 | server = sinon.fakeServer.create(); 108 | return server.autoRespond = true; 109 | }); 110 | afterEach(function() { 111 | return server.restore(); 112 | }); 113 | it('should send a datapoint', function() { 114 | Bucky.send('data.point', 4); 115 | Bucky.flush(); 116 | expect(server.requests.length).toBe(1); 117 | return expect(server.requests[0].requestBody).toBe("data.point:4|g\n"); 118 | }); 119 | return it('should send timers', function() { 120 | Bucky.send('data.1', 5, 'timer'); 121 | Bucky.send('data.2', 3, 'timer'); 122 | Bucky.flush(); 123 | expect(server.requests.length).toBe(1); 124 | return expect(server.requests[0].requestBody).toBe("data.1:5|ms\ndata.2:3|ms\n"); 125 | }); 126 | }); 127 | 128 | }).call(this); 129 | -------------------------------------------------------------------------------- /spec/vendor/jasmine-1.3.1/lib/jasmine-1.3.1/jasmine.css: -------------------------------------------------------------------------------- 1 | body { background-color: #eeeeee; padding: 0; margin: 5px; overflow-y: scroll; } 2 | 3 | #HTMLReporter { font-size: 11px; font-family: Monaco, "Lucida Console", monospace; line-height: 14px; color: #333333; } 4 | #HTMLReporter a { text-decoration: none; } 5 | #HTMLReporter a:hover { text-decoration: underline; } 6 | #HTMLReporter p, #HTMLReporter h1, #HTMLReporter h2, #HTMLReporter h3, #HTMLReporter h4, #HTMLReporter h5, #HTMLReporter h6 { margin: 0; line-height: 14px; } 7 | #HTMLReporter .banner, #HTMLReporter .symbolSummary, #HTMLReporter .summary, #HTMLReporter .resultMessage, #HTMLReporter .specDetail .description, #HTMLReporter .alert .bar, #HTMLReporter .stackTrace { padding-left: 9px; padding-right: 9px; } 8 | #HTMLReporter #jasmine_content { position: fixed; right: 100%; } 9 | #HTMLReporter .version { color: #aaaaaa; } 10 | #HTMLReporter .banner { margin-top: 14px; } 11 | #HTMLReporter .duration { color: #aaaaaa; float: right; } 12 | #HTMLReporter .symbolSummary { overflow: hidden; *zoom: 1; margin: 14px 0; } 13 | #HTMLReporter .symbolSummary li { display: block; float: left; height: 7px; width: 14px; margin-bottom: 7px; font-size: 16px; } 14 | #HTMLReporter .symbolSummary li.passed { font-size: 14px; } 15 | #HTMLReporter .symbolSummary li.passed:before { color: #5e7d00; content: "\02022"; } 16 | #HTMLReporter .symbolSummary li.failed { line-height: 9px; } 17 | #HTMLReporter .symbolSummary li.failed:before { color: #b03911; content: "x"; font-weight: bold; margin-left: -1px; } 18 | #HTMLReporter .symbolSummary li.skipped { font-size: 14px; } 19 | #HTMLReporter .symbolSummary li.skipped:before { color: #bababa; content: "\02022"; } 20 | #HTMLReporter .symbolSummary li.pending { line-height: 11px; } 21 | #HTMLReporter .symbolSummary li.pending:before { color: #aaaaaa; content: "-"; } 22 | #HTMLReporter .exceptions { color: #fff; float: right; margin-top: 5px; margin-right: 5px; } 23 | #HTMLReporter .bar { line-height: 28px; font-size: 14px; display: block; color: #eee; } 24 | #HTMLReporter .runningAlert { background-color: #666666; } 25 | #HTMLReporter .skippedAlert { background-color: #aaaaaa; } 26 | #HTMLReporter .skippedAlert:first-child { background-color: #333333; } 27 | #HTMLReporter .skippedAlert:hover { text-decoration: none; color: white; text-decoration: underline; } 28 | #HTMLReporter .passingAlert { background-color: #a6b779; } 29 | #HTMLReporter .passingAlert:first-child { background-color: #5e7d00; } 30 | #HTMLReporter .failingAlert { background-color: #cf867e; } 31 | #HTMLReporter .failingAlert:first-child { background-color: #b03911; } 32 | #HTMLReporter .results { margin-top: 14px; } 33 | #HTMLReporter #details { display: none; } 34 | #HTMLReporter .resultsMenu, #HTMLReporter .resultsMenu a { background-color: #fff; color: #333333; } 35 | #HTMLReporter.showDetails .summaryMenuItem { font-weight: normal; text-decoration: inherit; } 36 | #HTMLReporter.showDetails .summaryMenuItem:hover { text-decoration: underline; } 37 | #HTMLReporter.showDetails .detailsMenuItem { font-weight: bold; text-decoration: underline; } 38 | #HTMLReporter.showDetails .summary { display: none; } 39 | #HTMLReporter.showDetails #details { display: block; } 40 | #HTMLReporter .summaryMenuItem { font-weight: bold; text-decoration: underline; } 41 | #HTMLReporter .summary { margin-top: 14px; } 42 | #HTMLReporter .summary .suite .suite, #HTMLReporter .summary .specSummary { margin-left: 14px; } 43 | #HTMLReporter .summary .specSummary.passed a { color: #5e7d00; } 44 | #HTMLReporter .summary .specSummary.failed a { color: #b03911; } 45 | #HTMLReporter .description + .suite { margin-top: 0; } 46 | #HTMLReporter .suite { margin-top: 14px; } 47 | #HTMLReporter .suite a { color: #333333; } 48 | #HTMLReporter #details .specDetail { margin-bottom: 28px; } 49 | #HTMLReporter #details .specDetail .description { display: block; color: white; background-color: #b03911; } 50 | #HTMLReporter .resultMessage { padding-top: 14px; color: #333333; } 51 | #HTMLReporter .resultMessage span.result { display: block; } 52 | #HTMLReporter .stackTrace { margin: 5px 0 0 0; max-height: 224px; overflow: auto; line-height: 18px; color: #666666; border: 1px solid #ddd; background: white; white-space: pre; } 53 | 54 | #TrivialReporter { padding: 8px 13px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; overflow-y: scroll; background-color: white; font-family: "Helvetica Neue Light", "Lucida Grande", "Calibri", "Arial", sans-serif; /*.resultMessage {*/ /*white-space: pre;*/ /*}*/ } 55 | #TrivialReporter a:visited, #TrivialReporter a { color: #303; } 56 | #TrivialReporter a:hover, #TrivialReporter a:active { color: blue; } 57 | #TrivialReporter .run_spec { float: right; padding-right: 5px; font-size: .8em; text-decoration: none; } 58 | #TrivialReporter .banner { color: #303; background-color: #fef; padding: 5px; } 59 | #TrivialReporter .logo { float: left; font-size: 1.1em; padding-left: 5px; } 60 | #TrivialReporter .logo .version { font-size: .6em; padding-left: 1em; } 61 | #TrivialReporter .runner.running { background-color: yellow; } 62 | #TrivialReporter .options { text-align: right; font-size: .8em; } 63 | #TrivialReporter .suite { border: 1px outset gray; margin: 5px 0; padding-left: 1em; } 64 | #TrivialReporter .suite .suite { margin: 5px; } 65 | #TrivialReporter .suite.passed { background-color: #dfd; } 66 | #TrivialReporter .suite.failed { background-color: #fdd; } 67 | #TrivialReporter .spec { margin: 5px; padding-left: 1em; clear: both; } 68 | #TrivialReporter .spec.failed, #TrivialReporter .spec.passed, #TrivialReporter .spec.skipped { padding-bottom: 5px; border: 1px solid gray; } 69 | #TrivialReporter .spec.failed { background-color: #fbb; border-color: red; } 70 | #TrivialReporter .spec.passed { background-color: #bfb; border-color: green; } 71 | #TrivialReporter .spec.skipped { background-color: #bbb; } 72 | #TrivialReporter .messages { border-left: 1px dashed gray; padding-left: 1em; padding-right: 1em; } 73 | #TrivialReporter .passed { background-color: #cfc; display: none; } 74 | #TrivialReporter .failed { background-color: #fbb; } 75 | #TrivialReporter .skipped { color: #777; background-color: #eee; display: none; } 76 | #TrivialReporter .resultMessage span.result { display: block; line-height: 2em; color: black; } 77 | #TrivialReporter .resultMessage .mismatch { color: black; } 78 | #TrivialReporter .stackTrace { white-space: pre; font-size: .8em; margin-left: 10px; max-height: 5em; overflow: auto; border: 1px inset red; padding: 1em; background: #eef; } 79 | #TrivialReporter .finished-at { padding-left: 1em; font-size: .6em; } 80 | #TrivialReporter.show-passed .passed, #TrivialReporter.show-skipped .skipped { display: block; } 81 | #TrivialReporter #jasmine_content { position: fixed; right: 100%; } 82 | #TrivialReporter .runner { border: 1px solid gray; display: block; margin: 5px 0; padding: 2px 0 2px 10px; } 83 | -------------------------------------------------------------------------------- /bucky.min.js: -------------------------------------------------------------------------------- 1 | /*! bucky 0.2.8 */ 2 | (function(){var a,b,c,d,e,f,g,h=[].slice;e="undefined"!=typeof module&&null!==module&&!("undefined"!=typeof window&&null!==window?window.module:void 0),e?(a=require("xmlhttprequest").XMLHttpRequest,g=function(){var a;return a=process.hrtime(),1e3*(a[0]+a[1]/1e9)}):g=function(){var a,b;return null!=(a=null!=(b=window.performance)&&"function"==typeof b.now?b.now():void 0)?a:+new Date},d=+new Date,c=function(){var a,b,c,d,e,f,g;for(a=arguments[0],d=2<=arguments.length?h.call(arguments,1):[],f=0,g=d.length;g>f;f++){c=d[f];for(b in c)e=c[b],a[b]=e}return a},f=function(){var a,b;return a=1<=arguments.length?h.call(arguments,0):[],null!=("undefined"!=typeof console&&null!==console&&null!=(b=console.log)?b.call:void 0)?console.log.apply(console,a):void 0},f.error=function(){var a,b;return a=1<=arguments.length?h.call(arguments,0):[],null!=("undefined"!=typeof console&&null!==console&&null!=(b=console.error)?b.call:void 0)?console.error.apply(console,a):void 0},b=function(){var b,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I;if(n={host:"/bucky",maxInterval:3e4,aggregationInterval:5e3,decimalPrecision:3,sendLatency:!1,sample:1,active:!0},B={},!e&&(b="function"==typeof document.querySelector?document.querySelector("[data-bucky-host],[data-bucky-page],[data-bucky-requests]"):void 0))for(B={host:b.getAttribute("data-bucky-host"),pagePerformanceKey:b.getAttribute("data-bucky-page"),requestsKey:b.getAttribute("data-bucky-requests")},G=["pagePerformanceKey","requestsKey"],E=0,F=G.length;F>E;E++)q=G[E],"true"===(null!=(H=B[q])?H.toString().toLowerCase():void 0)||""===B[q]?B[q]=!0:"false"===(null!=(I=B[q])?I.toString().toLowerCase():void 0)&&(B[q]=null);return v=c({},n,B),k={timer:"ms",gauge:"g",counter:"c"},i=v.active,(C=function(){return i=v.active&&Math.random()k;k++)g=o[k],e=l.transforms.mapping[g],null!=e?"function"!=typeof e?(e instanceof RegExp&&(e=[e,""]),i=i.replace(e[0],e[1])):i=e(i,a,b,c):f.error("Bucky Error: Attempted to enable a mapping which is not defined: "+g);return i=decodeURIComponent(i),i=i.replace(/[^a-zA-Z0-9\-\.\/ ]+/g,"_"),j=d+i.replace(/[\/ ]/g,"."),j=j.replace(/(^\.)|(\.$)/g,""),j=j.replace(/\.com/,""),j=j.replace(/www\./,""),c&&(j=c+"."+j),b&&(j=j+"."+b.toLowerCase()),j=j.replace(/\.\./g,".")},getFullUrl:function(a,b){return null==b&&(b=document.location),/^\//.test(a)?b.hostname+a:/https?:\/\//i.test(a)?a:b.toString()+a},monitor:function(a){var b,d,e;return a&&a!==!0||(a=l.urlToKey(document.location.toString())+".requests"),d=this,b=function(b){var e,f,h,i,j,k,l,n;return l=b.type,n=b.url,f=b.event,i=b.request,h=b.readyStateTimes,j=b.startTime,null!=j?(e=g()-j,n=d.getFullUrl(n),k=d.urlToKey(n,l,a),m(k,e,"timer"),d.sendReadyStateTimes(k,h),null!=(null!=i?i.status:void 0)?(i.status>12e3?c(""+k+".0"):0!==i.status&&c(""+k+"."+i.status.toString().charAt(0)+"xx"),c(""+k+"."+i.status)):void 0):void 0},e=window.XMLHttpRequest,window.XMLHttpRequest=function(){var a,c,d,h,i,j;d=new e;try{h=null,c={},i=d.open,d.open=function(a,e,j){var k;try{c[0]=g(),d.addEventListener("readystatechange",function(){return c[d.readyState]=g()},!1),d.addEventListener("loadend",function(f){return null==d.bucky||d.bucky.track!==!1?b({type:a,url:e,event:f,startTime:h,readyStateTimes:c,request:d}):void 0},!1)}catch(l){k=l,f.error("Bucky error monitoring XHR open call",k)}return i.apply(d,arguments)},j=d.send,d.send=function(){return h=g(),j.apply(d,arguments)}}catch(k){a=k,f.error("Bucky error monitoring XHR",a)}return d}}},k=function(b){var c;return null==b&&(b=""),c=null!=a?a:"",c&&b&&(c+="."),b&&(c+=b),s(c)},e={send:m,count:c,timer:t,now:g,requests:l,sendPagePerformance:n,flush:p,setOptions:A,options:v,history:j,active:i};for(q in e)u=e[q],k[q]=u;return k},l=s(),v.pagePerformanceKey&&l.sendPagePerformance(v.pagePerformanceKey),v.requestsKey&&l.requests.monitor(v.requestsKey),l},"function"==typeof define&&define.amd?define(b):"object"==typeof exports?module.exports=b():window.Bucky=b()}).call(this); -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Bucky 2 | ===== 3 | 4 | Bucky is a client and server for sending performance data from the client into statsd+graphite, OpenTSDB, or any 5 | other stats aggregator of your choice. 6 | 7 | It can automatically measure how long your pages take to load, how long AJAX requests take and how long 8 | various functions take to run. Most importantly, it's taking the measurements on actual page loads, 9 | so the data has the potential to be much more valuable than in vitro measurements. 10 | 11 | If you already use statsd or OpenTSDB, you can get started in just a few minutes. If you're not 12 | collecting stats, you [should start](http://github.hubspot.com/BuckyServer/getting_started/choosing_a_stats_service/)! 13 | What gets measured gets managed. 14 | 15 | ### Server 16 | 17 | You can play with Bucky just using the client, but if you'd like to start collecting data, see the 18 | [Server Instructions](http://github.hubspot.com/BuckyServer/). 19 | 20 | ### Setup 21 | 22 | #### From The Client 23 | 24 | Include [bucky.js](https://raw.github.com/HubSpot/BuckyClient/v0.2.3/bucky.min.js) on your page, the only required config can be done right in the script tag: 25 | 26 | ```html 27 | 28 | ``` 29 | 30 | That config will automatically log the performance of your page and all the requests you make to a server running at 31 | /bucky. It will automatically decide the right key name based on the url of the page. If you'd like, you can also specify it manually: 32 | 33 | ```html 34 | 35 | ``` 36 | 37 | The `Bucky` object will be available globally, but there is nothing you need to call for basic usage. 38 | 39 | Bucky can also be loaded with AMD or Browserify (see the methods below). 40 | 41 | #### From Node 42 | 43 | ```bash 44 | npm install bucky 45 | ``` 46 | 47 | ```coffeescript 48 | bucky = require('bucky') 49 | ``` 50 | 51 | ### Configuring 52 | 53 | Before sending any data, call `setOptions` if you're not using the data- attribute based configuration: 54 | 55 | ```javascript 56 | Bucky.setOptions({ 57 | host: 'http://myweb.site:9999/bucky' 58 | }); 59 | ``` 60 | 61 | Some options you might be interested in: 62 | 63 | - `host`: Where we can reach your [Bucky server](http://github.com/HubSpot/BuckyServer), including the 64 | APP_ROOT. 65 | 66 | The Bucky server has a very liberal CORS config, so we should be able to connect to it even if 67 | it's on a different domain, but hosting it on the same domain and port will save you some preflight requests. 68 | 69 | - `active`: Should Bucky actually send data? Use this to disable Bucky during local dev for example. 70 | - `sample`: What fraction of clients should actually send data? Use to subsample your clients if you have 71 | too much data coming in. 72 | 73 | Take a look at [the source](http://github.com/HubSpot/BuckyClient/blob/master/bucky.coffee#L34) for a 74 | full list of options. 75 | 76 | #### Sending Page Performance 77 | 78 | Modern browsers log a bunch of page performance data, bucky includes a method for writing all of this in 79 | one go. It won't do anything on browsers which don't support the performance.timing api. Call it whenever, 80 | it will bind an event if the data isn't ready yet. 81 | 82 | ```coffeescript 83 | Bucky.sendPagePerformance('where.the.data.should.go') 84 | ``` 85 | 86 | Setting `data-bucky-page` triggers this automatically. 87 | 88 | The two most relevant stats provided are `responseEnd` which is the amount of time it took for the 89 | original page to be loaded and `domInteractive` which is the amount of time before the page has 90 | finished loaded and can be interacted with by the user. 91 | 92 | As a reminder: this data is browser specific, so it will likely skew lower than what users on 93 | old browsers see. 94 | 95 | If you're using Backbone, it might be a good idea to send your data based on route: 96 | 97 | ```coffeescript 98 | Backbone.history.on 'route', (router, route) -> 99 | # Will only send on the initial page load: 100 | Bucky.sendPagePerformance("some.location.page.#{ route }") 101 | ``` 102 | 103 | The data collected will look something like this: 104 | 105 | ```javascript 106 | pages.contactDetail.timing.connectEnd: "172.000|ms" 107 | pages.contactDetail.timing.connectStart: "106.000|ms" 108 | pages.contactDetail.timing.domComplete: "1029.000|ms" 109 | pages.contactDetail.timing.domContentLoadedEventEnd: "1019.000|ms" 110 | pages.contactDetail.timing.domContentLoadedEventStart: "980.000|ms" 111 | pages.contactDetail.timing.domInteractive: "980.000|ms" 112 | pages.contactDetail.timing.domLoading: "254.000|ms" 113 | pages.contactDetail.timing.domainLookupEnd: "106.000|ms" 114 | pages.contactDetail.timing.domainLookupStart: "106.000|ms" 115 | pages.contactDetail.timing.fetchStart: "103.000|ms" 116 | pages.contactDetail.timing.loadEventEnd: "1030.000|ms" 117 | pages.contactDetail.timing.loadEventStart: "1029.000|ms" 118 | pages.contactDetail.timing.navigationStart: "0.000|ms" 119 | pages.contactDetail.timing.requestStart: "173.000|ms" 120 | pages.contactDetail.timing.responseEnd: "243.000|ms" 121 | pages.contactDetail.timing.responseStart: "235.000|ms" 122 | pages.contactDetail.timing.secureConnectionStart: "106.000|ms" 123 | ``` 124 | 125 | A description of what each datapoint represents is included in [the spec](http://www.w3.org/TR/navigation-timing-2/#sec-PerformanceNavigationTiming). 126 | 127 | #### Sending AJAX Request Time 128 | 129 | Bucky can automatically log all ajax requests made by hooking into XMLHttpRequest and doing some transformations 130 | on the url to try and create a graphite key from it. Enable it as early in your app's load as is possible: 131 | 132 | ```coffeescript 133 | Bucky.requests.monitor('my.project.requests') 134 | ``` 135 | 136 | Setting `data-bucky-requests` calls this automatically. 137 | 138 | The data collected will look something like this for a GET request to 139 | `api.hubapi.com/automation/v2/workflows`: 140 | 141 | ```javascript 142 | contacts.web.prod.requests.api.hubapi.automation.v2.workflows.get: "656.794|ms" 143 | contacts.web.prod.requests.api.hubapi.automation.v2.workflows.get.2xx: "1|c" 144 | contacts.web.prod.requests.api.hubapi.automation.v2.workflows.get.200: "1|c" 145 | contacts.web.prod.requests.api.hubapi.automation.v2.workflows.get.headers: "436.737|ms" 146 | contacts.web.prod.requests.api.hubapi.automation.v2.workflows.get.receiving: "0.182|ms" 147 | contacts.web.prod.requests.api.hubapi.automation.v2.workflows.get.sending: "0.059|ms" 148 | contacts.web.prod.requests.api.hubapi.automation.v2.workflows.get.waiting: "206.035|ms" 149 | ``` 150 | 151 | #### Prefixing 152 | 153 | You can build a client which will prefix all of your datapoints by calling bucky as a function: 154 | 155 | ```coffeescript 156 | myBucky = Bucky('awesome.app.view') 157 | 158 | # You can then use all of the normal methods: 159 | myBucky.send('data.point', 5) 160 | ``` 161 | 162 | You can repeatedly call clients to add more prefixes: 163 | 164 | ```coffeescript 165 | contactsBucky = bucky('contacts') 166 | cwBucky = contactsBucky('web') 167 | 168 | cwBucky.send('x', 1) # Data goes in contacts.web.x 169 | ``` 170 | 171 | #### Counting Things 172 | 173 | By default `send` sends absolute values, this is rarely what you want when working from the client, incrementing 174 | a counter is usually more helpful: 175 | 176 | ```coffeescript 177 | bucky.count('my.awesome.thing') 178 | bucky.count('number.of.chips.eaten', 5) 179 | ``` 180 | 181 | #### Timing Things 182 | 183 | You can manually send ms durations using `timer.send`: 184 | 185 | ```coffeescript 186 | bucky.timer.send('timed.thing', 55) 187 | ``` 188 | 189 | Bucky includes a method to time async functions: 190 | 191 | ```coffeescript 192 | bucky.timer.time 'my.awesome.function', (done) -> 193 | asyncThingy -> 194 | done() 195 | ``` 196 | 197 | You can also manually start and stop your timer: 198 | 199 | ```coffeescript 200 | bucky.timer.start 'my.awesome.function' 201 | 202 | asyncThingy -> 203 | bucky.timer.stop 'my.awesome.function' 204 | ``` 205 | 206 | You can time synchronous functions as well: 207 | 208 | ```coffeescript 209 | bucky.timer.timeSync 'my.awesome.function', -> 210 | Math.sqrt(100) 211 | ``` 212 | 213 | The `time` and `timeSync` functions also accept a context and arguments to pass to the 214 | called function: 215 | 216 | ```coffeescript 217 | bucky.timer.timeSync 'my.render.function', @render, @, arg1, arg2 218 | ``` 219 | 220 | You can wrap existing functions using `wrap`: 221 | 222 | ```coffeescript 223 | func = bucky.timer.wrap('func.time', func) 224 | ``` 225 | 226 | It also supports a special syntax for methods: 227 | 228 | ```coffeescript 229 | class SomeClass 230 | render: bucky.timer.wrap('render') -> 231 | # Normal render stuff 232 | ``` 233 | 234 | Note that this wrapping does not play nice with CoffeeScript `super` calls. 235 | 236 | Bucky also includes a function for measuring the time since the navigationStart event was fired (the beginning of the request): 237 | 238 | ```coffeescript 239 | bucky.timer.mark('my.thing.happened') 240 | ``` 241 | 242 | It acts like a timer where the start is always navigation start. 243 | 244 | The stopwatch method allows you to begin a timer which can be stopped multiple times: 245 | 246 | ```coffeescript 247 | watch = bucky.stopwatch('some.prefix.if.you.want') 248 | ``` 249 | 250 | You can then call `watch.mark('key')` to send the time since the stopwatch started, or 251 | `watch.split('key')` to send the time since the last split. 252 | 253 | ### Sending Points 254 | 255 | If you want to send absolute values (rare from the client), you can use send directly. 256 | 257 | The one use we've had for this is sending `+new Date` from every client to get an idea 258 | of how skewed their clocks are. 259 | 260 | ```coffeescript 261 | Bucky.send 'my.awesome.datapoint', 2432.43434 262 | ``` 263 | 264 | ### Your Stats 265 | 266 | You can find your stats in the `stats` and `stats.timing` folders in graphite, or as written in OpenTSDB. 267 | 268 | ### Send Frequency 269 | 270 | Bucky will send your data in bulk from the client either five seconds after the last datapoint is added, or thirty seconds after 271 | the last send, whichever comes first. If you log multiple datapoints within this send frequency, the points will 272 | be averaged (and the appropriate frequency information will be sent to statsd) (with the exception of counters, they 273 | are incremented). This means that the max and min numbers you get from statsd actually represent the max and min 274 | 5-30 second bucket. Note that this is per-client, not for the entire bucky process (it's generally only important 275 | on the server where you might be pushing out many points with the same key). 276 | 277 | ### Bucky Object 278 | 279 | The Bucky object provides a couple extra properties you can access: 280 | 281 | - `Bucky.history`: The history of all datapoints ever sent. 282 | - `Bucky.active`: Is Bucky sending data? This can change if you change the `active` or `sample` settings. 283 | - `Bucky.flush()`: Send the Bucky queue immediately 284 | - `Bucky.timer.now()`: A clock based on the most precise time available (not guarenteed to be from the epoch) 285 | 286 | ### URL -> Key Transformation 287 | 288 | `request.monitor` attempts to automatically transform your urls into keys. It does a bunch of transformations 289 | with the goal of removing anything which will vary per-request, so you end up with stats per-endpoint. These 290 | tranformations include: 291 | 292 | - Stripping GUIDS, IDs, SHA1s, MD5s 293 | - Stripping email addresses 294 | - Stripping domains 295 | 296 | If you find these tranformations too invasive, or not invasive enough, you can modify them. 297 | 298 | ```javascript 299 | // You can diable tranforms with `.disable` 300 | Bucky.requests.transforms.disable('guid'); 301 | 302 | // You can enable transforms with `.enable` 303 | Bucky.requests.tranforms.enable('guid'); 304 | 305 | // `.enable` can also be used to add a new tranform: 306 | Bucky.requests.transforms.enable('my-ids', /[0-9]{4}-[0-9]{12}/g) 307 | 308 | // The third argument defines what the match is replaced with (rather than just eliminating it): 309 | Bucky.requests.transforms.enable('campaign', /campaigns\/\w{15}/ig, '/campaigns') 310 | 311 | // You can also just provide a function which takes in the url, and returns it modified: 312 | Bucky.request.transforms.enable('soup', function(url){ return url.split('').reverse().join(''); }) 313 | ``` 314 | 315 | Enabled tests will be added to the beginning of the `enabled` list, meaning they will be executed before 316 | any other tranform. Edit the `Bucky.requests.tranforms.enabled` array if you need more specific control. 317 | 318 | The order of the transforms is very important. If you, for example, were to run the `id` transform before 319 | the `guid` one, the `guid` transform wouldn't match any guid which began with a number (as the number would 320 | have already been stripped out, making the guid the wrong length). 321 | 322 | When you first enable request monitoring, it's a good idea to keep an eye on the Bucky logs to get 323 | an idea of what sort of data points are being created. 324 | 325 | ### App Server 326 | 327 | This project pushes data to the Bucky Server. 328 | 329 | [Server Documentation](http://github.hubspot.com/BuckyServer) 330 | 331 | 332 | -------------------------------------------------------------------------------- /bucky.coffee: -------------------------------------------------------------------------------- 1 | isServer = module? and not window?.module 2 | 3 | if isServer 4 | {XMLHttpRequest} = require('xmlhttprequest') 5 | 6 | now = -> 7 | time = process.hrtime() 8 | (time[0] + time[1] / 1e9) * 1000 9 | 10 | else 11 | now = -> 12 | window.performance?.now?() ? (+new Date) 13 | 14 | # This is used if we can't get the navigationStart time from 15 | # window.performance 16 | initTime = +new Date 17 | 18 | extend = (a, objs...) -> 19 | for obj in objs 20 | for key, val of obj 21 | a[key] = val 22 | a 23 | 24 | log = (msgs...) -> 25 | if console?.log?.call? 26 | console.log msgs... 27 | 28 | log.error = (msgs...) -> 29 | if console?.error?.call? 30 | console.error msgs... 31 | 32 | exportDef = -> 33 | defaults = 34 | # Where is the Bucky server hosted. This should be both the host and the APP_ROOT (if you've 35 | # defined one). This default assumes its at the same host as your app. 36 | # 37 | # Keep in mind that if you use a different host, CORS will come into play. 38 | host: '/bucky' 39 | 40 | # The max time we should wait between sends 41 | maxInterval: 30000 42 | 43 | # How long we should wait from getting the last datapoint 44 | # to do a send, if datapoints keep coming in eventually 45 | # the MAX_INTERVAL will trigger a send. 46 | aggregationInterval: 5000 47 | 48 | # How many decimal digits should we include in our 49 | # times? 50 | decimalPrecision: 3 51 | 52 | # Bucky can automatically report a datapoint of what its response time 53 | # is. This is useful because Bucky returns almost immediately, making 54 | # it's response time a good measure of the user's connection latency. 55 | sendLatency: false 56 | 57 | # Downsampling will cause Bucky to only send data 100*SAMPLE percent 58 | # of the time. It is used to reduce the amount of data sent to the backend. 59 | # 60 | # It's not done per datapoint, but per client, so you probably don't want to downsample 61 | # on node (you would be telling a percentage of your servers to not send data). 62 | sample: 1 63 | 64 | # Set to false to disable sends (in dev mode for example) 65 | active: true 66 | 67 | tagOptions = {} 68 | if not isServer 69 | $tag = document.querySelector?('[data-bucky-host],[data-bucky-page],[data-bucky-requests]') 70 | if $tag 71 | tagOptions = { 72 | host: $tag.getAttribute('data-bucky-host') 73 | 74 | # These are to allow you to send page peformance data without having to manually call 75 | # the methods. 76 | pagePerformanceKey: $tag.getAttribute('data-bucky-page') 77 | requestsKey: $tag.getAttribute('data-bucky-requests') 78 | } 79 | 80 | for key in ['pagePerformanceKey', 'requestsKey'] 81 | if tagOptions[key]?.toString().toLowerCase() is 'true' or tagOptions[key] is '' 82 | tagOptions[key] = true 83 | else if tagOptions[key]?.toString().toLowerCase() is 'false' 84 | tagOptions[key] = null 85 | 86 | options = extend {}, defaults, tagOptions 87 | 88 | TYPE_MAP = 89 | 'timer': 'ms' 90 | 'gauge': 'g' 91 | 'counter': 'c' 92 | 93 | ACTIVE = options.active 94 | do updateActive = -> 95 | ACTIVE = options.active and Math.random() < options.sample 96 | 97 | HISTORY = [] 98 | 99 | setOptions = (opts) -> 100 | extend options, opts 101 | 102 | if 'sample' of opts or 'active' of opts 103 | updateActive() 104 | 105 | options 106 | 107 | round = (num, precision=options.decimalPrecision) -> 108 | Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision) 109 | 110 | queue = {} 111 | enqueue = (path, value, type) -> 112 | return unless ACTIVE 113 | 114 | count = 1 115 | 116 | if path of queue 117 | # We have multiple of the same datapoint in this queue 118 | if type is 'counter' 119 | # Sum the queue 120 | value += queue[path].value 121 | else 122 | # If it's a timer or a gauge, calculate a running average 123 | count = queue[path].count ? count 124 | count++ 125 | 126 | value = queue[path].value + (value - queue[path].value) / count 127 | 128 | queue[path] = {value, type, count} 129 | 130 | do considerSending 131 | 132 | sendTimeout = null 133 | maxTimeout = null 134 | 135 | flush = -> 136 | clearTimeout sendTimeout 137 | clearTimeout maxTimeout 138 | 139 | maxTimeout = null 140 | sendTimeout = null 141 | 142 | do sendQueue 143 | 144 | considerSending = -> 145 | # We set two different timers, one which resets with every request 146 | # to try to get as many datapoints into each send, and another which 147 | # will force a send if too much time has gone by with continuous 148 | # points coming in. 149 | 150 | clearTimeout sendTimeout 151 | sendTimeout = setTimeout flush, options.aggregationInterval 152 | 153 | unless maxTimeout? 154 | maxTimeout = setTimeout flush, options.maxInterval 155 | 156 | makeRequest = (data) -> 157 | corsSupport = isServer or (window.XMLHttpRequest and (window.XMLHttpRequest.defake or 'withCredentials' of new window.XMLHttpRequest())) 158 | 159 | if isServer 160 | sameOrigin = true 161 | else 162 | match = /^(https?:\/\/[^\/]+)/i.exec options.host 163 | 164 | if match 165 | # FQDN 166 | 167 | origin = match[1] 168 | if origin is "#{ document.location.protocol }//#{ document.location.host }" 169 | sameOrigin = true 170 | else 171 | sameOrigin = false 172 | else 173 | # Relative URL 174 | 175 | sameOrigin = true 176 | 177 | sendStart = now() 178 | 179 | body = '' 180 | for name, val of data 181 | body += "#{ name }:#{ val }\n" 182 | 183 | if not sameOrigin and not corsSupport and window?.XDomainRequest? 184 | # CORS support for IE9 185 | req = new window.XDomainRequest 186 | else 187 | req = new (window?.XMLHttpRequest ? XMLHttpRequest) 188 | 189 | # Don't track this request with Bucky, as we'd be tracking our own 190 | # sends forever. The latency of this request is independently tracked 191 | # by updateLatency. 192 | req.bucky = {track: false} 193 | 194 | req.open 'POST', "#{ options.host }/v1/send", true 195 | 196 | req.setRequestHeader 'Content-Type', 'text/plain' 197 | 198 | req.addEventListener 'load', -> 199 | updateLatency(now() - sendStart) 200 | , false 201 | 202 | req.send body 203 | 204 | req 205 | 206 | sendQueue = -> 207 | if not ACTIVE 208 | log "Would send bucky queue" 209 | return 210 | 211 | out = {} 212 | for key, point of queue 213 | HISTORY.push 214 | path: key 215 | count: point.count 216 | type: point.type 217 | value: point.value 218 | 219 | unless TYPE_MAP[point.type]? 220 | log.error "Type #{ point.type } not understood by Bucky" 221 | continue 222 | 223 | value = point.value 224 | if point.type in ['gauge', 'timer'] 225 | value = round(value) 226 | 227 | out[key] = "#{ value }|#{ TYPE_MAP[point.type] }" 228 | 229 | if point.count isnt 1 230 | out[key] += "@#{ round(1 / point.count, 5) }" 231 | 232 | makeRequest out 233 | 234 | queue = {} 235 | 236 | latencySent = false 237 | updateLatency = (time) -> 238 | if options.sendLatency and not latencySent 239 | enqueue 'bucky.latency', time, 'timer' 240 | 241 | latencySent = true 242 | 243 | # We may be running on node where this process could be around for 244 | # a while, let's send latency updates every five minutes. 245 | setTimeout -> 246 | latencySent = false 247 | , 5*60*1000 248 | 249 | makeClient = (prefix='') -> 250 | buildPath = (path) -> 251 | if prefix?.length 252 | prefix + '.' + path 253 | else 254 | path 255 | 256 | send = (path, value, type='gauge') -> 257 | if not value? or not path? 258 | log.error "Can't log #{ path }:#{ value }" 259 | return 260 | 261 | enqueue buildPath(path), value, type 262 | 263 | timer = { 264 | TIMES: {} 265 | 266 | send: (path, duration) -> 267 | send path, duration, 'timer' 268 | 269 | time: (path, action, ctx, args...) -> 270 | timer.start path 271 | 272 | done = => 273 | timer.stop path 274 | 275 | args.splice(0, 0, done) 276 | action.apply(ctx, args) 277 | 278 | timeSync: (path, action, ctx, args...) -> 279 | timer.start path 280 | 281 | ret = action.apply(ctx, args) 282 | 283 | timer.stop path 284 | 285 | ret 286 | 287 | wrap: (path, action) -> 288 | if action? 289 | return (args...) -> 290 | timer.timeSync path, action, @, args... 291 | else 292 | return (action) -> 293 | return (args...) -> 294 | timer.timeSync path, action, @, args... 295 | 296 | start: (path) -> 297 | timer.TIMES[path] = now() 298 | 299 | stop: (path) -> 300 | if not timer.TIMES[path]? 301 | log.error "Timer #{ path } ended without having been started" 302 | return 303 | 304 | duration = now() - timer.TIMES[path] 305 | 306 | timer.TIMES[path] = undefined 307 | 308 | timer.send path, duration 309 | 310 | stopwatch: (prefix, start) -> 311 | # A timer that can be stopped multiple times 312 | 313 | # If a start time is passed in, it's assumed 314 | # to be millis since the epoch, not the special 315 | # start time `now` uses. 316 | if start? 317 | _now = -> +new Date 318 | else 319 | _now = now 320 | start = _now() 321 | 322 | last = start 323 | 324 | { 325 | mark: (path, offset=0) -> 326 | end = _now() 327 | 328 | if prefix 329 | path = prefix + '.' + path 330 | 331 | timer.send path, (end - start + offset) 332 | 333 | split: (path, offset=0) -> 334 | end = _now() 335 | 336 | if prefix 337 | path = prefix + '.' + path 338 | 339 | timer.send path, (end - last + offset) 340 | 341 | last = end 342 | } 343 | 344 | mark: (path, time) -> 345 | # A timer which always begins at page load 346 | 347 | time ?= +new Date 348 | 349 | start = timer.navigationStart() 350 | 351 | timer.send path, (time - start) 352 | 353 | navigationStart: -> 354 | window?.performance?.timing?.navigationStart ? initTime 355 | 356 | responseEnd: -> 357 | window?.performance?.timing?.responseEnd ? initTime 358 | 359 | now: -> 360 | now() 361 | } 362 | 363 | count = (path, count=1) -> 364 | send(path, count, 'counter') 365 | 366 | sentPerformanceData = false 367 | sendPagePerformance = (path) -> 368 | return false unless window?.performance?.timing? 369 | return false if sentPerformanceData 370 | 371 | if not path or path is true 372 | path = requests.urlToKey(document.location.toString()) + '.page' 373 | 374 | if document.readyState in ['uninitialized', 'loading'] 375 | # The data isn't fully ready until document load 376 | window.addEventListener? 'load', => 377 | setTimeout => 378 | sendPagePerformance.call(@, path) 379 | , 500 380 | , false 381 | 382 | return false 383 | 384 | sentPerformanceData = true 385 | 386 | start = window.performance.timing.navigationStart 387 | for key, time of window.performance.timing when typeof time is 'number' 388 | timer.send "#{ path }.#{ key }", (time - start) 389 | 390 | return true 391 | 392 | requests = { 393 | transforms: 394 | mapping: 395 | guid: /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ig 396 | sha1: /\/[0-9a-f]{40}/ig 397 | md5: /\/[0-9a-f]{32}/ig 398 | id: /\/[0-9;_\-]+/g 399 | email: /\/[^/]+@[^/]+/g 400 | domain: [/\/[^/]+\.[a-z]{2,3}\//ig, '/'] 401 | 402 | enabled: ['guid', 'sha1', 'md5', 'id', 'email', 'domain'] 403 | 404 | enable: (name, test, replacement='') -> 405 | if test? 406 | @mapping[name] = [test, replacement] 407 | 408 | @enabled.splice 0, 0, name 409 | 410 | disable: (name) -> 411 | for i, val of @enabled 412 | if val is name 413 | @enabled.splice i, 1 414 | return 415 | 416 | sendReadyStateTimes: (path, times) -> 417 | return unless times? 418 | 419 | codeMapping = 420 | 1: 'sending' 421 | 2: 'headers' 422 | 3: 'waiting' 423 | 4: 'receiving' 424 | 425 | diffs = {} 426 | last = null 427 | for code, time of times 428 | if last? and codeMapping[code]? 429 | diffs[codeMapping[code]] = time - last 430 | 431 | last = time 432 | 433 | for status, val of diffs 434 | timer.send "#{ path }.#{ status }", val 435 | 436 | urlToKey: (url, type, root) -> 437 | url = url.replace /https?:\/\//i, '' 438 | 439 | parsedUrl = /([^/:]*)(?::\d+)?(\/[^\?#]*)?.*/i.exec(url) 440 | host = parsedUrl[1] 441 | path = parsedUrl[2] ? '' 442 | 443 | for mappingName in requests.transforms.enabled 444 | mapping = requests.transforms.mapping[mappingName] 445 | 446 | if not mapping? 447 | log.error "Bucky Error: Attempted to enable a mapping which is not defined: #{ mappingName }" 448 | continue 449 | 450 | if typeof mapping is 'function' 451 | path = mapping path, url, type, root 452 | continue 453 | 454 | if mapping instanceof RegExp 455 | mapping = [mapping, ''] 456 | 457 | path = path.replace(mapping[0], mapping[1]) 458 | 459 | path = decodeURIComponent(path) 460 | 461 | path = path.replace(/[^a-zA-Z0-9\-\.\/ ]+/g, '_') 462 | 463 | stat = host + path.replace(/[\/ ]/g, '.') 464 | 465 | stat = stat.replace /(^\.)|(\.$)/g, '' 466 | stat = stat.replace /\.com/, '' 467 | stat = stat.replace /www\./, '' 468 | 469 | if root 470 | stat = root + '.' + stat 471 | 472 | if type 473 | stat = stat + '.' + type.toLowerCase() 474 | 475 | stat = stat.replace /\.\./g, '.' 476 | 477 | stat 478 | 479 | getFullUrl: (url, location=document.location) -> 480 | if /^\//.test(url) 481 | location.hostname + url 482 | else if not /https?:\/\//i.test(url) 483 | location.toString() + url 484 | else 485 | url 486 | 487 | monitor: (root) -> 488 | if not root or root is true 489 | root = requests.urlToKey(document.location.toString()) + '.requests' 490 | 491 | self = this 492 | done = ({type, url, event, request, readyStateTimes, startTime}) -> 493 | if startTime? 494 | dur = now() - startTime 495 | else 496 | return 497 | 498 | url = self.getFullUrl url 499 | stat = self.urlToKey url, type, root 500 | 501 | send(stat, dur, 'timer') 502 | 503 | self.sendReadyStateTimes stat, readyStateTimes 504 | 505 | if request?.status? 506 | if request.status > 12000 507 | # Most browsers return status code 0 for aborted/failed requests. IE returns 508 | # special status codes over 12000: http://msdn.microsoft.com/en-us/library/aa383770%28VS.85%29.aspx 509 | # 510 | # We'll track the 12xxx code, but also store it as a 0 511 | count("#{ stat }.0") 512 | 513 | else if request.status isnt 0 514 | count("#{ stat }.#{ request.status.toString().charAt(0) }xx") 515 | 516 | count("#{ stat }.#{ request.status }") 517 | 518 | _XMLHttpRequest = window.XMLHttpRequest 519 | window.XMLHttpRequest = -> 520 | req = new _XMLHttpRequest 521 | 522 | try 523 | startTime = null 524 | readyStateTimes = {} 525 | 526 | _open = req.open 527 | req.open = (type, url, async) -> 528 | try 529 | readyStateTimes[0] = now() 530 | 531 | req.addEventListener 'readystatechange', -> 532 | readyStateTimes[req.readyState] = now() 533 | , false 534 | 535 | req.addEventListener 'loadend', (event) -> 536 | if not req.bucky? or req.bucky.track isnt false 537 | done {type, url, event, startTime, readyStateTimes, request: req} 538 | , false 539 | catch e 540 | log.error "Bucky error monitoring XHR open call", e 541 | 542 | _open.apply req, arguments 543 | 544 | _send = req.send 545 | req.send = -> 546 | startTime = now() 547 | 548 | _send.apply req, arguments 549 | catch e 550 | log.error "Bucky error monitoring XHR", e 551 | 552 | req 553 | } 554 | 555 | nextMakeClient = (nextPrefix='') -> 556 | path = prefix ? '' 557 | path += '.' if path and nextPrefix 558 | path += nextPrefix if nextPrefix 559 | 560 | makeClient(path) 561 | 562 | exports = { 563 | send, 564 | count, 565 | timer, 566 | now, 567 | requests, 568 | sendPagePerformance, 569 | flush, 570 | setOptions, 571 | options, 572 | history: HISTORY, 573 | active: ACTIVE 574 | } 575 | 576 | for key, val of exports 577 | nextMakeClient[key] = val 578 | 579 | nextMakeClient 580 | 581 | client = makeClient() 582 | 583 | if options.pagePerformanceKey 584 | client.sendPagePerformance(options.pagePerformanceKey) 585 | 586 | if options.requestsKey 587 | client.requests.monitor(options.requestsKey) 588 | 589 | client 590 | 591 | if typeof define is 'function' and define.amd 592 | # AMD 593 | define exportDef 594 | else if typeof exports is 'object' 595 | # Node 596 | module.exports = exportDef() 597 | else 598 | # Global 599 | window.Bucky = exportDef() 600 | -------------------------------------------------------------------------------- /spec/vendor/jasmine-1.3.1/lib/jasmine-1.3.1/jasmine-html.js: -------------------------------------------------------------------------------- 1 | jasmine.HtmlReporterHelpers = {}; 2 | 3 | jasmine.HtmlReporterHelpers.createDom = function(type, attrs, childrenVarArgs) { 4 | var el = document.createElement(type); 5 | 6 | for (var i = 2; i < arguments.length; i++) { 7 | var child = arguments[i]; 8 | 9 | if (typeof child === 'string') { 10 | el.appendChild(document.createTextNode(child)); 11 | } else { 12 | if (child) { 13 | el.appendChild(child); 14 | } 15 | } 16 | } 17 | 18 | for (var attr in attrs) { 19 | if (attr == "className") { 20 | el[attr] = attrs[attr]; 21 | } else { 22 | el.setAttribute(attr, attrs[attr]); 23 | } 24 | } 25 | 26 | return el; 27 | }; 28 | 29 | jasmine.HtmlReporterHelpers.getSpecStatus = function(child) { 30 | var results = child.results(); 31 | var status = results.passed() ? 'passed' : 'failed'; 32 | if (results.skipped) { 33 | status = 'skipped'; 34 | } 35 | 36 | return status; 37 | }; 38 | 39 | jasmine.HtmlReporterHelpers.appendToSummary = function(child, childElement) { 40 | var parentDiv = this.dom.summary; 41 | var parentSuite = (typeof child.parentSuite == 'undefined') ? 'suite' : 'parentSuite'; 42 | var parent = child[parentSuite]; 43 | 44 | if (parent) { 45 | if (typeof this.views.suites[parent.id] == 'undefined') { 46 | this.views.suites[parent.id] = new jasmine.HtmlReporter.SuiteView(parent, this.dom, this.views); 47 | } 48 | parentDiv = this.views.suites[parent.id].element; 49 | } 50 | 51 | parentDiv.appendChild(childElement); 52 | }; 53 | 54 | 55 | jasmine.HtmlReporterHelpers.addHelpers = function(ctor) { 56 | for(var fn in jasmine.HtmlReporterHelpers) { 57 | ctor.prototype[fn] = jasmine.HtmlReporterHelpers[fn]; 58 | } 59 | }; 60 | 61 | jasmine.HtmlReporter = function(_doc) { 62 | var self = this; 63 | var doc = _doc || window.document; 64 | 65 | var reporterView; 66 | 67 | var dom = {}; 68 | 69 | // Jasmine Reporter Public Interface 70 | self.logRunningSpecs = false; 71 | 72 | self.reportRunnerStarting = function(runner) { 73 | var specs = runner.specs() || []; 74 | 75 | if (specs.length == 0) { 76 | return; 77 | } 78 | 79 | createReporterDom(runner.env.versionString()); 80 | doc.body.appendChild(dom.reporter); 81 | setExceptionHandling(); 82 | 83 | reporterView = new jasmine.HtmlReporter.ReporterView(dom); 84 | reporterView.addSpecs(specs, self.specFilter); 85 | }; 86 | 87 | self.reportRunnerResults = function(runner) { 88 | reporterView && reporterView.complete(); 89 | }; 90 | 91 | self.reportSuiteResults = function(suite) { 92 | reporterView.suiteComplete(suite); 93 | }; 94 | 95 | self.reportSpecStarting = function(spec) { 96 | if (self.logRunningSpecs) { 97 | self.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); 98 | } 99 | }; 100 | 101 | self.reportSpecResults = function(spec) { 102 | reporterView.specComplete(spec); 103 | }; 104 | 105 | self.log = function() { 106 | var console = jasmine.getGlobal().console; 107 | if (console && console.log) { 108 | if (console.log.apply) { 109 | console.log.apply(console, arguments); 110 | } else { 111 | console.log(arguments); // ie fix: console.log.apply doesn't exist on ie 112 | } 113 | } 114 | }; 115 | 116 | self.specFilter = function(spec) { 117 | if (!focusedSpecName()) { 118 | return true; 119 | } 120 | 121 | return spec.getFullName().indexOf(focusedSpecName()) === 0; 122 | }; 123 | 124 | return self; 125 | 126 | function focusedSpecName() { 127 | var specName; 128 | 129 | (function memoizeFocusedSpec() { 130 | if (specName) { 131 | return; 132 | } 133 | 134 | var paramMap = []; 135 | var params = jasmine.HtmlReporter.parameters(doc); 136 | 137 | for (var i = 0; i < params.length; i++) { 138 | var p = params[i].split('='); 139 | paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); 140 | } 141 | 142 | specName = paramMap.spec; 143 | })(); 144 | 145 | return specName; 146 | } 147 | 148 | function createReporterDom(version) { 149 | dom.reporter = self.createDom('div', { id: 'HTMLReporter', className: 'jasmine_reporter' }, 150 | dom.banner = self.createDom('div', { className: 'banner' }, 151 | self.createDom('span', { className: 'title' }, "Jasmine "), 152 | self.createDom('span', { className: 'version' }, version)), 153 | 154 | dom.symbolSummary = self.createDom('ul', {className: 'symbolSummary'}), 155 | dom.alert = self.createDom('div', {className: 'alert'}, 156 | self.createDom('span', { className: 'exceptions' }, 157 | self.createDom('label', { className: 'label', 'for': 'no_try_catch' }, 'No try/catch'), 158 | self.createDom('input', { id: 'no_try_catch', type: 'checkbox' }))), 159 | dom.results = self.createDom('div', {className: 'results'}, 160 | dom.summary = self.createDom('div', { className: 'summary' }), 161 | dom.details = self.createDom('div', { id: 'details' })) 162 | ); 163 | } 164 | 165 | function noTryCatch() { 166 | return window.location.search.match(/catch=false/); 167 | } 168 | 169 | function searchWithCatch() { 170 | var params = jasmine.HtmlReporter.parameters(window.document); 171 | var removed = false; 172 | var i = 0; 173 | 174 | while (!removed && i < params.length) { 175 | if (params[i].match(/catch=/)) { 176 | params.splice(i, 1); 177 | removed = true; 178 | } 179 | i++; 180 | } 181 | if (jasmine.CATCH_EXCEPTIONS) { 182 | params.push("catch=false"); 183 | } 184 | 185 | return params.join("&"); 186 | } 187 | 188 | function setExceptionHandling() { 189 | var chxCatch = document.getElementById('no_try_catch'); 190 | 191 | if (noTryCatch()) { 192 | chxCatch.setAttribute('checked', true); 193 | jasmine.CATCH_EXCEPTIONS = false; 194 | } 195 | chxCatch.onclick = function() { 196 | window.location.search = searchWithCatch(); 197 | }; 198 | } 199 | }; 200 | jasmine.HtmlReporter.parameters = function(doc) { 201 | var paramStr = doc.location.search.substring(1); 202 | var params = []; 203 | 204 | if (paramStr.length > 0) { 205 | params = paramStr.split('&'); 206 | } 207 | return params; 208 | } 209 | jasmine.HtmlReporter.sectionLink = function(sectionName) { 210 | var link = '?'; 211 | var params = []; 212 | 213 | if (sectionName) { 214 | params.push('spec=' + encodeURIComponent(sectionName)); 215 | } 216 | if (!jasmine.CATCH_EXCEPTIONS) { 217 | params.push("catch=false"); 218 | } 219 | if (params.length > 0) { 220 | link += params.join("&"); 221 | } 222 | 223 | return link; 224 | }; 225 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter); 226 | jasmine.HtmlReporter.ReporterView = function(dom) { 227 | this.startedAt = new Date(); 228 | this.runningSpecCount = 0; 229 | this.completeSpecCount = 0; 230 | this.passedCount = 0; 231 | this.failedCount = 0; 232 | this.skippedCount = 0; 233 | 234 | this.createResultsMenu = function() { 235 | this.resultsMenu = this.createDom('span', {className: 'resultsMenu bar'}, 236 | this.summaryMenuItem = this.createDom('a', {className: 'summaryMenuItem', href: "#"}, '0 specs'), 237 | ' | ', 238 | this.detailsMenuItem = this.createDom('a', {className: 'detailsMenuItem', href: "#"}, '0 failing')); 239 | 240 | this.summaryMenuItem.onclick = function() { 241 | dom.reporter.className = dom.reporter.className.replace(/ showDetails/g, ''); 242 | }; 243 | 244 | this.detailsMenuItem.onclick = function() { 245 | showDetails(); 246 | }; 247 | }; 248 | 249 | this.addSpecs = function(specs, specFilter) { 250 | this.totalSpecCount = specs.length; 251 | 252 | this.views = { 253 | specs: {}, 254 | suites: {} 255 | }; 256 | 257 | for (var i = 0; i < specs.length; i++) { 258 | var spec = specs[i]; 259 | this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom, this.views); 260 | if (specFilter(spec)) { 261 | this.runningSpecCount++; 262 | } 263 | } 264 | }; 265 | 266 | this.specComplete = function(spec) { 267 | this.completeSpecCount++; 268 | 269 | if (isUndefined(this.views.specs[spec.id])) { 270 | this.views.specs[spec.id] = new jasmine.HtmlReporter.SpecView(spec, dom); 271 | } 272 | 273 | var specView = this.views.specs[spec.id]; 274 | 275 | switch (specView.status()) { 276 | case 'passed': 277 | this.passedCount++; 278 | break; 279 | 280 | case 'failed': 281 | this.failedCount++; 282 | break; 283 | 284 | case 'skipped': 285 | this.skippedCount++; 286 | break; 287 | } 288 | 289 | specView.refresh(); 290 | this.refresh(); 291 | }; 292 | 293 | this.suiteComplete = function(suite) { 294 | var suiteView = this.views.suites[suite.id]; 295 | if (isUndefined(suiteView)) { 296 | return; 297 | } 298 | suiteView.refresh(); 299 | }; 300 | 301 | this.refresh = function() { 302 | 303 | if (isUndefined(this.resultsMenu)) { 304 | this.createResultsMenu(); 305 | } 306 | 307 | // currently running UI 308 | if (isUndefined(this.runningAlert)) { 309 | this.runningAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "runningAlert bar" }); 310 | dom.alert.appendChild(this.runningAlert); 311 | } 312 | this.runningAlert.innerHTML = "Running " + this.completeSpecCount + " of " + specPluralizedFor(this.totalSpecCount); 313 | 314 | // skipped specs UI 315 | if (isUndefined(this.skippedAlert)) { 316 | this.skippedAlert = this.createDom('a', { href: jasmine.HtmlReporter.sectionLink(), className: "skippedAlert bar" }); 317 | } 318 | 319 | this.skippedAlert.innerHTML = "Skipping " + this.skippedCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; 320 | 321 | if (this.skippedCount === 1 && isDefined(dom.alert)) { 322 | dom.alert.appendChild(this.skippedAlert); 323 | } 324 | 325 | // passing specs UI 326 | if (isUndefined(this.passedAlert)) { 327 | this.passedAlert = this.createDom('span', { href: jasmine.HtmlReporter.sectionLink(), className: "passingAlert bar" }); 328 | } 329 | this.passedAlert.innerHTML = "Passing " + specPluralizedFor(this.passedCount); 330 | 331 | // failing specs UI 332 | if (isUndefined(this.failedAlert)) { 333 | this.failedAlert = this.createDom('span', {href: "?", className: "failingAlert bar"}); 334 | } 335 | this.failedAlert.innerHTML = "Failing " + specPluralizedFor(this.failedCount); 336 | 337 | if (this.failedCount === 1 && isDefined(dom.alert)) { 338 | dom.alert.appendChild(this.failedAlert); 339 | dom.alert.appendChild(this.resultsMenu); 340 | } 341 | 342 | // summary info 343 | this.summaryMenuItem.innerHTML = "" + specPluralizedFor(this.runningSpecCount); 344 | this.detailsMenuItem.innerHTML = "" + this.failedCount + " failing"; 345 | }; 346 | 347 | this.complete = function() { 348 | dom.alert.removeChild(this.runningAlert); 349 | 350 | this.skippedAlert.innerHTML = "Ran " + this.runningSpecCount + " of " + specPluralizedFor(this.totalSpecCount) + " - run all"; 351 | 352 | if (this.failedCount === 0) { 353 | dom.alert.appendChild(this.createDom('span', {className: 'passingAlert bar'}, "Passing " + specPluralizedFor(this.passedCount))); 354 | } else { 355 | showDetails(); 356 | } 357 | 358 | dom.banner.appendChild(this.createDom('span', {className: 'duration'}, "finished in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s")); 359 | }; 360 | 361 | return this; 362 | 363 | function showDetails() { 364 | if (dom.reporter.className.search(/showDetails/) === -1) { 365 | dom.reporter.className += " showDetails"; 366 | } 367 | } 368 | 369 | function isUndefined(obj) { 370 | return typeof obj === 'undefined'; 371 | } 372 | 373 | function isDefined(obj) { 374 | return !isUndefined(obj); 375 | } 376 | 377 | function specPluralizedFor(count) { 378 | var str = count + " spec"; 379 | if (count > 1) { 380 | str += "s" 381 | } 382 | return str; 383 | } 384 | 385 | }; 386 | 387 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.ReporterView); 388 | 389 | 390 | jasmine.HtmlReporter.SpecView = function(spec, dom, views) { 391 | this.spec = spec; 392 | this.dom = dom; 393 | this.views = views; 394 | 395 | this.symbol = this.createDom('li', { className: 'pending' }); 396 | this.dom.symbolSummary.appendChild(this.symbol); 397 | 398 | this.summary = this.createDom('div', { className: 'specSummary' }, 399 | this.createDom('a', { 400 | className: 'description', 401 | href: jasmine.HtmlReporter.sectionLink(this.spec.getFullName()), 402 | title: this.spec.getFullName() 403 | }, this.spec.description) 404 | ); 405 | 406 | this.detail = this.createDom('div', { className: 'specDetail' }, 407 | this.createDom('a', { 408 | className: 'description', 409 | href: '?spec=' + encodeURIComponent(this.spec.getFullName()), 410 | title: this.spec.getFullName() 411 | }, this.spec.getFullName()) 412 | ); 413 | }; 414 | 415 | jasmine.HtmlReporter.SpecView.prototype.status = function() { 416 | return this.getSpecStatus(this.spec); 417 | }; 418 | 419 | jasmine.HtmlReporter.SpecView.prototype.refresh = function() { 420 | this.symbol.className = this.status(); 421 | 422 | switch (this.status()) { 423 | case 'skipped': 424 | break; 425 | 426 | case 'passed': 427 | this.appendSummaryToSuiteDiv(); 428 | break; 429 | 430 | case 'failed': 431 | this.appendSummaryToSuiteDiv(); 432 | this.appendFailureDetail(); 433 | break; 434 | } 435 | }; 436 | 437 | jasmine.HtmlReporter.SpecView.prototype.appendSummaryToSuiteDiv = function() { 438 | this.summary.className += ' ' + this.status(); 439 | this.appendToSummary(this.spec, this.summary); 440 | }; 441 | 442 | jasmine.HtmlReporter.SpecView.prototype.appendFailureDetail = function() { 443 | this.detail.className += ' ' + this.status(); 444 | 445 | var resultItems = this.spec.results().getItems(); 446 | var messagesDiv = this.createDom('div', { className: 'messages' }); 447 | 448 | for (var i = 0; i < resultItems.length; i++) { 449 | var result = resultItems[i]; 450 | 451 | if (result.type == 'log') { 452 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); 453 | } else if (result.type == 'expect' && result.passed && !result.passed()) { 454 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); 455 | 456 | if (result.trace.stack) { 457 | messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); 458 | } 459 | } 460 | } 461 | 462 | if (messagesDiv.childNodes.length > 0) { 463 | this.detail.appendChild(messagesDiv); 464 | this.dom.details.appendChild(this.detail); 465 | } 466 | }; 467 | 468 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SpecView);jasmine.HtmlReporter.SuiteView = function(suite, dom, views) { 469 | this.suite = suite; 470 | this.dom = dom; 471 | this.views = views; 472 | 473 | this.element = this.createDom('div', { className: 'suite' }, 474 | this.createDom('a', { className: 'description', href: jasmine.HtmlReporter.sectionLink(this.suite.getFullName()) }, this.suite.description) 475 | ); 476 | 477 | this.appendToSummary(this.suite, this.element); 478 | }; 479 | 480 | jasmine.HtmlReporter.SuiteView.prototype.status = function() { 481 | return this.getSpecStatus(this.suite); 482 | }; 483 | 484 | jasmine.HtmlReporter.SuiteView.prototype.refresh = function() { 485 | this.element.className += " " + this.status(); 486 | }; 487 | 488 | jasmine.HtmlReporterHelpers.addHelpers(jasmine.HtmlReporter.SuiteView); 489 | 490 | /* @deprecated Use jasmine.HtmlReporter instead 491 | */ 492 | jasmine.TrivialReporter = function(doc) { 493 | this.document = doc || document; 494 | this.suiteDivs = {}; 495 | this.logRunningSpecs = false; 496 | }; 497 | 498 | jasmine.TrivialReporter.prototype.createDom = function(type, attrs, childrenVarArgs) { 499 | var el = document.createElement(type); 500 | 501 | for (var i = 2; i < arguments.length; i++) { 502 | var child = arguments[i]; 503 | 504 | if (typeof child === 'string') { 505 | el.appendChild(document.createTextNode(child)); 506 | } else { 507 | if (child) { el.appendChild(child); } 508 | } 509 | } 510 | 511 | for (var attr in attrs) { 512 | if (attr == "className") { 513 | el[attr] = attrs[attr]; 514 | } else { 515 | el.setAttribute(attr, attrs[attr]); 516 | } 517 | } 518 | 519 | return el; 520 | }; 521 | 522 | jasmine.TrivialReporter.prototype.reportRunnerStarting = function(runner) { 523 | var showPassed, showSkipped; 524 | 525 | this.outerDiv = this.createDom('div', { id: 'TrivialReporter', className: 'jasmine_reporter' }, 526 | this.createDom('div', { className: 'banner' }, 527 | this.createDom('div', { className: 'logo' }, 528 | this.createDom('span', { className: 'title' }, "Jasmine"), 529 | this.createDom('span', { className: 'version' }, runner.env.versionString())), 530 | this.createDom('div', { className: 'options' }, 531 | "Show ", 532 | showPassed = this.createDom('input', { id: "__jasmine_TrivialReporter_showPassed__", type: 'checkbox' }), 533 | this.createDom('label', { "for": "__jasmine_TrivialReporter_showPassed__" }, " passed "), 534 | showSkipped = this.createDom('input', { id: "__jasmine_TrivialReporter_showSkipped__", type: 'checkbox' }), 535 | this.createDom('label', { "for": "__jasmine_TrivialReporter_showSkipped__" }, " skipped") 536 | ) 537 | ), 538 | 539 | this.runnerDiv = this.createDom('div', { className: 'runner running' }, 540 | this.createDom('a', { className: 'run_spec', href: '?' }, "run all"), 541 | this.runnerMessageSpan = this.createDom('span', {}, "Running..."), 542 | this.finishedAtSpan = this.createDom('span', { className: 'finished-at' }, "")) 543 | ); 544 | 545 | this.document.body.appendChild(this.outerDiv); 546 | 547 | var suites = runner.suites(); 548 | for (var i = 0; i < suites.length; i++) { 549 | var suite = suites[i]; 550 | var suiteDiv = this.createDom('div', { className: 'suite' }, 551 | this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, "run"), 552 | this.createDom('a', { className: 'description', href: '?spec=' + encodeURIComponent(suite.getFullName()) }, suite.description)); 553 | this.suiteDivs[suite.id] = suiteDiv; 554 | var parentDiv = this.outerDiv; 555 | if (suite.parentSuite) { 556 | parentDiv = this.suiteDivs[suite.parentSuite.id]; 557 | } 558 | parentDiv.appendChild(suiteDiv); 559 | } 560 | 561 | this.startedAt = new Date(); 562 | 563 | var self = this; 564 | showPassed.onclick = function(evt) { 565 | if (showPassed.checked) { 566 | self.outerDiv.className += ' show-passed'; 567 | } else { 568 | self.outerDiv.className = self.outerDiv.className.replace(/ show-passed/, ''); 569 | } 570 | }; 571 | 572 | showSkipped.onclick = function(evt) { 573 | if (showSkipped.checked) { 574 | self.outerDiv.className += ' show-skipped'; 575 | } else { 576 | self.outerDiv.className = self.outerDiv.className.replace(/ show-skipped/, ''); 577 | } 578 | }; 579 | }; 580 | 581 | jasmine.TrivialReporter.prototype.reportRunnerResults = function(runner) { 582 | var results = runner.results(); 583 | var className = (results.failedCount > 0) ? "runner failed" : "runner passed"; 584 | this.runnerDiv.setAttribute("class", className); 585 | //do it twice for IE 586 | this.runnerDiv.setAttribute("className", className); 587 | var specs = runner.specs(); 588 | var specCount = 0; 589 | for (var i = 0; i < specs.length; i++) { 590 | if (this.specFilter(specs[i])) { 591 | specCount++; 592 | } 593 | } 594 | var message = "" + specCount + " spec" + (specCount == 1 ? "" : "s" ) + ", " + results.failedCount + " failure" + ((results.failedCount == 1) ? "" : "s"); 595 | message += " in " + ((new Date().getTime() - this.startedAt.getTime()) / 1000) + "s"; 596 | this.runnerMessageSpan.replaceChild(this.createDom('a', { className: 'description', href: '?'}, message), this.runnerMessageSpan.firstChild); 597 | 598 | this.finishedAtSpan.appendChild(document.createTextNode("Finished at " + new Date().toString())); 599 | }; 600 | 601 | jasmine.TrivialReporter.prototype.reportSuiteResults = function(suite) { 602 | var results = suite.results(); 603 | var status = results.passed() ? 'passed' : 'failed'; 604 | if (results.totalCount === 0) { // todo: change this to check results.skipped 605 | status = 'skipped'; 606 | } 607 | this.suiteDivs[suite.id].className += " " + status; 608 | }; 609 | 610 | jasmine.TrivialReporter.prototype.reportSpecStarting = function(spec) { 611 | if (this.logRunningSpecs) { 612 | this.log('>> Jasmine Running ' + spec.suite.description + ' ' + spec.description + '...'); 613 | } 614 | }; 615 | 616 | jasmine.TrivialReporter.prototype.reportSpecResults = function(spec) { 617 | var results = spec.results(); 618 | var status = results.passed() ? 'passed' : 'failed'; 619 | if (results.skipped) { 620 | status = 'skipped'; 621 | } 622 | var specDiv = this.createDom('div', { className: 'spec ' + status }, 623 | this.createDom('a', { className: 'run_spec', href: '?spec=' + encodeURIComponent(spec.getFullName()) }, "run"), 624 | this.createDom('a', { 625 | className: 'description', 626 | href: '?spec=' + encodeURIComponent(spec.getFullName()), 627 | title: spec.getFullName() 628 | }, spec.description)); 629 | 630 | 631 | var resultItems = results.getItems(); 632 | var messagesDiv = this.createDom('div', { className: 'messages' }); 633 | for (var i = 0; i < resultItems.length; i++) { 634 | var result = resultItems[i]; 635 | 636 | if (result.type == 'log') { 637 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage log'}, result.toString())); 638 | } else if (result.type == 'expect' && result.passed && !result.passed()) { 639 | messagesDiv.appendChild(this.createDom('div', {className: 'resultMessage fail'}, result.message)); 640 | 641 | if (result.trace.stack) { 642 | messagesDiv.appendChild(this.createDom('div', {className: 'stackTrace'}, result.trace.stack)); 643 | } 644 | } 645 | } 646 | 647 | if (messagesDiv.childNodes.length > 0) { 648 | specDiv.appendChild(messagesDiv); 649 | } 650 | 651 | this.suiteDivs[spec.suite.id].appendChild(specDiv); 652 | }; 653 | 654 | jasmine.TrivialReporter.prototype.log = function() { 655 | var console = jasmine.getGlobal().console; 656 | if (console && console.log) { 657 | if (console.log.apply) { 658 | console.log.apply(console, arguments); 659 | } else { 660 | console.log(arguments); // ie fix: console.log.apply doesn't exist on ie 661 | } 662 | } 663 | }; 664 | 665 | jasmine.TrivialReporter.prototype.getLocation = function() { 666 | return this.document.location; 667 | }; 668 | 669 | jasmine.TrivialReporter.prototype.specFilter = function(spec) { 670 | var paramMap = {}; 671 | var params = this.getLocation().search.substring(1).split('&'); 672 | for (var i = 0; i < params.length; i++) { 673 | var p = params[i].split('='); 674 | paramMap[decodeURIComponent(p[0])] = decodeURIComponent(p[1]); 675 | } 676 | 677 | if (!paramMap.spec) { 678 | return true; 679 | } 680 | return spec.getFullName().indexOf(paramMap.spec) === 0; 681 | }; 682 | -------------------------------------------------------------------------------- /bucky.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | var XMLHttpRequest, exportDef, extend, initTime, isServer, log, now, 3 | __slice = [].slice; 4 | 5 | isServer = (typeof module !== "undefined" && module !== null) && !(typeof window !== "undefined" && window !== null ? window.module : void 0); 6 | 7 | if (isServer) { 8 | XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest; 9 | now = function() { 10 | var time; 11 | time = process.hrtime(); 12 | return (time[0] + time[1] / 1e9) * 1000; 13 | }; 14 | } else { 15 | now = function() { 16 | var _ref, _ref1; 17 | return (_ref = (_ref1 = window.performance) != null ? typeof _ref1.now === "function" ? _ref1.now() : void 0 : void 0) != null ? _ref : +(new Date); 18 | }; 19 | } 20 | 21 | initTime = +(new Date); 22 | 23 | extend = function() { 24 | var a, key, obj, objs, val, _i, _len; 25 | a = arguments[0], objs = 2 <= arguments.length ? __slice.call(arguments, 1) : []; 26 | for (_i = 0, _len = objs.length; _i < _len; _i++) { 27 | obj = objs[_i]; 28 | for (key in obj) { 29 | val = obj[key]; 30 | a[key] = val; 31 | } 32 | } 33 | return a; 34 | }; 35 | 36 | log = function() { 37 | var msgs, _ref; 38 | msgs = 1 <= arguments.length ? __slice.call(arguments, 0) : []; 39 | if ((typeof console !== "undefined" && console !== null ? (_ref = console.log) != null ? _ref.call : void 0 : void 0) != null) { 40 | return console.log.apply(console, msgs); 41 | } 42 | }; 43 | 44 | log.error = function() { 45 | var msgs, _ref; 46 | msgs = 1 <= arguments.length ? __slice.call(arguments, 0) : []; 47 | if ((typeof console !== "undefined" && console !== null ? (_ref = console.error) != null ? _ref.call : void 0 : void 0) != null) { 48 | return console.error.apply(console, msgs); 49 | } 50 | }; 51 | 52 | exportDef = function() { 53 | var $tag, ACTIVE, HISTORY, TYPE_MAP, client, considerSending, defaults, enqueue, flush, key, latencySent, makeClient, makeRequest, maxTimeout, options, queue, round, sendQueue, sendTimeout, setOptions, tagOptions, updateActive, updateLatency, _i, _len, _ref, _ref1, _ref2; 54 | defaults = { 55 | host: '/bucky', 56 | maxInterval: 30000, 57 | aggregationInterval: 5000, 58 | decimalPrecision: 3, 59 | sendLatency: false, 60 | sample: 1, 61 | active: true 62 | }; 63 | tagOptions = {}; 64 | if (!isServer) { 65 | $tag = typeof document.querySelector === "function" ? document.querySelector('[data-bucky-host],[data-bucky-page],[data-bucky-requests]') : void 0; 66 | if ($tag) { 67 | tagOptions = { 68 | host: $tag.getAttribute('data-bucky-host'), 69 | pagePerformanceKey: $tag.getAttribute('data-bucky-page'), 70 | requestsKey: $tag.getAttribute('data-bucky-requests') 71 | }; 72 | _ref = ['pagePerformanceKey', 'requestsKey']; 73 | for (_i = 0, _len = _ref.length; _i < _len; _i++) { 74 | key = _ref[_i]; 75 | if (((_ref1 = tagOptions[key]) != null ? _ref1.toString().toLowerCase() : void 0) === 'true' || tagOptions[key] === '') { 76 | tagOptions[key] = true; 77 | } else if (((_ref2 = tagOptions[key]) != null ? _ref2.toString().toLowerCase() : void 0) === 'false') { 78 | tagOptions[key] = null; 79 | } 80 | } 81 | } 82 | } 83 | options = extend({}, defaults, tagOptions); 84 | TYPE_MAP = { 85 | 'timer': 'ms', 86 | 'gauge': 'g', 87 | 'counter': 'c' 88 | }; 89 | ACTIVE = options.active; 90 | (updateActive = function() { 91 | return ACTIVE = options.active && Math.random() < options.sample; 92 | })(); 93 | HISTORY = []; 94 | setOptions = function(opts) { 95 | extend(options, opts); 96 | if ('sample' in opts || 'active' in opts) { 97 | updateActive(); 98 | } 99 | return options; 100 | }; 101 | round = function(num, precision) { 102 | if (precision == null) { 103 | precision = options.decimalPrecision; 104 | } 105 | return Math.round(num * Math.pow(10, precision)) / Math.pow(10, precision); 106 | }; 107 | queue = {}; 108 | enqueue = function(path, value, type) { 109 | var count, _ref3; 110 | if (!ACTIVE) { 111 | return; 112 | } 113 | count = 1; 114 | if (path in queue) { 115 | if (type === 'counter') { 116 | value += queue[path].value; 117 | } else { 118 | count = (_ref3 = queue[path].count) != null ? _ref3 : count; 119 | count++; 120 | value = queue[path].value + (value - queue[path].value) / count; 121 | } 122 | } 123 | queue[path] = { 124 | value: value, 125 | type: type, 126 | count: count 127 | }; 128 | return considerSending(); 129 | }; 130 | sendTimeout = null; 131 | maxTimeout = null; 132 | flush = function() { 133 | clearTimeout(sendTimeout); 134 | clearTimeout(maxTimeout); 135 | maxTimeout = null; 136 | sendTimeout = null; 137 | return sendQueue(); 138 | }; 139 | considerSending = function() { 140 | clearTimeout(sendTimeout); 141 | sendTimeout = setTimeout(flush, options.aggregationInterval); 142 | if (maxTimeout == null) { 143 | return maxTimeout = setTimeout(flush, options.maxInterval); 144 | } 145 | }; 146 | makeRequest = function(data) { 147 | var body, corsSupport, match, name, origin, req, sameOrigin, sendStart, val, _ref3; 148 | corsSupport = isServer || (window.XMLHttpRequest && (window.XMLHttpRequest.defake || 'withCredentials' in new window.XMLHttpRequest())); 149 | if (isServer) { 150 | sameOrigin = true; 151 | } else { 152 | match = /^(https?:\/\/[^\/]+)/i.exec(options.host); 153 | if (match) { 154 | origin = match[1]; 155 | if (origin === ("" + document.location.protocol + "//" + document.location.host)) { 156 | sameOrigin = true; 157 | } else { 158 | sameOrigin = false; 159 | } 160 | } else { 161 | sameOrigin = true; 162 | } 163 | } 164 | sendStart = now(); 165 | body = ''; 166 | for (name in data) { 167 | val = data[name]; 168 | body += "" + name + ":" + val + "\n"; 169 | } 170 | if (!sameOrigin && !corsSupport && ((typeof window !== "undefined" && window !== null ? window.XDomainRequest : void 0) != null)) { 171 | req = new window.XDomainRequest; 172 | } else { 173 | req = new ((_ref3 = typeof window !== "undefined" && window !== null ? window.XMLHttpRequest : void 0) != null ? _ref3 : XMLHttpRequest); 174 | } 175 | req.bucky = { 176 | track: false 177 | }; 178 | req.open('POST', "" + options.host + "/v1/send", true); 179 | req.setRequestHeader('Content-Type', 'text/plain'); 180 | req.addEventListener('load', function() { 181 | return updateLatency(now() - sendStart); 182 | }, false); 183 | req.send(body); 184 | return req; 185 | }; 186 | sendQueue = function() { 187 | var out, point, value, _ref3; 188 | if (!ACTIVE) { 189 | log("Would send bucky queue"); 190 | return; 191 | } 192 | out = {}; 193 | for (key in queue) { 194 | point = queue[key]; 195 | HISTORY.push({ 196 | path: key, 197 | count: point.count, 198 | type: point.type, 199 | value: point.value 200 | }); 201 | if (TYPE_MAP[point.type] == null) { 202 | log.error("Type " + point.type + " not understood by Bucky"); 203 | continue; 204 | } 205 | value = point.value; 206 | if ((_ref3 = point.type) === 'gauge' || _ref3 === 'timer') { 207 | value = round(value); 208 | } 209 | out[key] = "" + value + "|" + TYPE_MAP[point.type]; 210 | if (point.count !== 1) { 211 | out[key] += "@" + (round(1 / point.count, 5)); 212 | } 213 | } 214 | makeRequest(out); 215 | return queue = {}; 216 | }; 217 | latencySent = false; 218 | updateLatency = function(time) { 219 | if (options.sendLatency && !latencySent) { 220 | enqueue('bucky.latency', time, 'timer'); 221 | latencySent = true; 222 | return setTimeout(function() { 223 | return latencySent = false; 224 | }, 5 * 60 * 1000); 225 | } 226 | }; 227 | makeClient = function(prefix) { 228 | var buildPath, count, exports, nextMakeClient, requests, send, sendPagePerformance, sentPerformanceData, timer, val; 229 | if (prefix == null) { 230 | prefix = ''; 231 | } 232 | buildPath = function(path) { 233 | if (prefix != null ? prefix.length : void 0) { 234 | return prefix + '.' + path; 235 | } else { 236 | return path; 237 | } 238 | }; 239 | send = function(path, value, type) { 240 | if (type == null) { 241 | type = 'gauge'; 242 | } 243 | if ((value == null) || (path == null)) { 244 | log.error("Can't log " + path + ":" + value); 245 | return; 246 | } 247 | return enqueue(buildPath(path), value, type); 248 | }; 249 | timer = { 250 | TIMES: {}, 251 | send: function(path, duration) { 252 | return send(path, duration, 'timer'); 253 | }, 254 | time: function() { 255 | var action, args, ctx, done, path, 256 | _this = this; 257 | path = arguments[0], action = arguments[1], ctx = arguments[2], args = 4 <= arguments.length ? __slice.call(arguments, 3) : []; 258 | timer.start(path); 259 | done = function() { 260 | return timer.stop(path); 261 | }; 262 | args.splice(0, 0, done); 263 | return action.apply(ctx, args); 264 | }, 265 | timeSync: function() { 266 | var action, args, ctx, path, ret; 267 | path = arguments[0], action = arguments[1], ctx = arguments[2], args = 4 <= arguments.length ? __slice.call(arguments, 3) : []; 268 | timer.start(path); 269 | ret = action.apply(ctx, args); 270 | timer.stop(path); 271 | return ret; 272 | }, 273 | wrap: function(path, action) { 274 | if (action != null) { 275 | return function() { 276 | var args; 277 | args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; 278 | return timer.timeSync.apply(timer, [path, action, this].concat(__slice.call(args))); 279 | }; 280 | } else { 281 | return function(action) { 282 | return function() { 283 | var args; 284 | args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; 285 | return timer.timeSync.apply(timer, [path, action, this].concat(__slice.call(args))); 286 | }; 287 | }; 288 | } 289 | }, 290 | start: function(path) { 291 | return timer.TIMES[path] = now(); 292 | }, 293 | stop: function(path) { 294 | var duration; 295 | if (timer.TIMES[path] == null) { 296 | log.error("Timer " + path + " ended without having been started"); 297 | return; 298 | } 299 | duration = now() - timer.TIMES[path]; 300 | timer.TIMES[path] = void 0; 301 | return timer.send(path, duration); 302 | }, 303 | stopwatch: function(prefix, start) { 304 | var last, _now; 305 | if (start != null) { 306 | _now = function() { 307 | return +(new Date); 308 | }; 309 | } else { 310 | _now = now; 311 | start = _now(); 312 | } 313 | last = start; 314 | return { 315 | mark: function(path, offset) { 316 | var end; 317 | if (offset == null) { 318 | offset = 0; 319 | } 320 | end = _now(); 321 | if (prefix) { 322 | path = prefix + '.' + path; 323 | } 324 | return timer.send(path, end - start + offset); 325 | }, 326 | split: function(path, offset) { 327 | var end; 328 | if (offset == null) { 329 | offset = 0; 330 | } 331 | end = _now(); 332 | if (prefix) { 333 | path = prefix + '.' + path; 334 | } 335 | timer.send(path, end - last + offset); 336 | return last = end; 337 | } 338 | }; 339 | }, 340 | mark: function(path, time) { 341 | var start; 342 | if (time == null) { 343 | time = +(new Date); 344 | } 345 | start = timer.navigationStart(); 346 | return timer.send(path, time - start); 347 | }, 348 | navigationStart: function() { 349 | var _ref3, _ref4, _ref5; 350 | return (_ref3 = typeof window !== "undefined" && window !== null ? (_ref4 = window.performance) != null ? (_ref5 = _ref4.timing) != null ? _ref5.navigationStart : void 0 : void 0 : void 0) != null ? _ref3 : initTime; 351 | }, 352 | responseEnd: function() { 353 | var _ref3, _ref4, _ref5; 354 | return (_ref3 = typeof window !== "undefined" && window !== null ? (_ref4 = window.performance) != null ? (_ref5 = _ref4.timing) != null ? _ref5.responseEnd : void 0 : void 0 : void 0) != null ? _ref3 : initTime; 355 | }, 356 | now: function() { 357 | return now(); 358 | } 359 | }; 360 | count = function(path, count) { 361 | if (count == null) { 362 | count = 1; 363 | } 364 | return send(path, count, 'counter'); 365 | }; 366 | sentPerformanceData = false; 367 | sendPagePerformance = function(path) { 368 | var start, time, _ref3, _ref4, _ref5, 369 | _this = this; 370 | if ((typeof window !== "undefined" && window !== null ? (_ref3 = window.performance) != null ? _ref3.timing : void 0 : void 0) == null) { 371 | return false; 372 | } 373 | if (sentPerformanceData) { 374 | return false; 375 | } 376 | if (!path || path === true) { 377 | path = requests.urlToKey(document.location.toString()) + '.page'; 378 | } 379 | if ((_ref4 = document.readyState) === 'uninitialized' || _ref4 === 'loading') { 380 | if (typeof window.addEventListener === "function") { 381 | window.addEventListener('load', function() { 382 | return setTimeout(function() { 383 | return sendPagePerformance.call(_this, path); 384 | }, 500); 385 | }, false); 386 | } 387 | return false; 388 | } 389 | sentPerformanceData = true; 390 | start = window.performance.timing.navigationStart; 391 | _ref5 = window.performance.timing; 392 | for (key in _ref5) { 393 | time = _ref5[key]; 394 | if (typeof time === 'number') { 395 | timer.send("" + path + "." + key, time - start); 396 | } 397 | } 398 | return true; 399 | }; 400 | requests = { 401 | transforms: { 402 | mapping: { 403 | guid: /\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ig, 404 | sha1: /\/[0-9a-f]{40}/ig, 405 | md5: /\/[0-9a-f]{32}/ig, 406 | id: /\/[0-9;_\-]+/g, 407 | email: /\/[^/]+@[^/]+/g, 408 | domain: [/\/[^/]+\.[a-z]{2,3}\//ig, '/'] 409 | }, 410 | enabled: ['guid', 'sha1', 'md5', 'id', 'email', 'domain'], 411 | enable: function(name, test, replacement) { 412 | if (replacement == null) { 413 | replacement = ''; 414 | } 415 | if (test != null) { 416 | this.mapping[name] = [test, replacement]; 417 | } 418 | return this.enabled.splice(0, 0, name); 419 | }, 420 | disable: function(name) { 421 | var i, val, _ref3; 422 | _ref3 = this.enabled; 423 | for (i in _ref3) { 424 | val = _ref3[i]; 425 | if (val === name) { 426 | this.enabled.splice(i, 1); 427 | return; 428 | } 429 | } 430 | } 431 | }, 432 | sendReadyStateTimes: function(path, times) { 433 | var code, codeMapping, diffs, last, status, time, val, _results; 434 | if (times == null) { 435 | return; 436 | } 437 | codeMapping = { 438 | 1: 'sending', 439 | 2: 'headers', 440 | 3: 'waiting', 441 | 4: 'receiving' 442 | }; 443 | diffs = {}; 444 | last = null; 445 | for (code in times) { 446 | time = times[code]; 447 | if ((last != null) && (codeMapping[code] != null)) { 448 | diffs[codeMapping[code]] = time - last; 449 | } 450 | last = time; 451 | } 452 | _results = []; 453 | for (status in diffs) { 454 | val = diffs[status]; 455 | _results.push(timer.send("" + path + "." + status, val)); 456 | } 457 | return _results; 458 | }, 459 | urlToKey: function(url, type, root) { 460 | var host, mapping, mappingName, parsedUrl, path, stat, _j, _len1, _ref3, _ref4; 461 | url = url.replace(/https?:\/\//i, ''); 462 | parsedUrl = /([^/:]*)(?::\d+)?(\/[^\?#]*)?.*/i.exec(url); 463 | host = parsedUrl[1]; 464 | path = (_ref3 = parsedUrl[2]) != null ? _ref3 : ''; 465 | _ref4 = requests.transforms.enabled; 466 | for (_j = 0, _len1 = _ref4.length; _j < _len1; _j++) { 467 | mappingName = _ref4[_j]; 468 | mapping = requests.transforms.mapping[mappingName]; 469 | if (mapping == null) { 470 | log.error("Bucky Error: Attempted to enable a mapping which is not defined: " + mappingName); 471 | continue; 472 | } 473 | if (typeof mapping === 'function') { 474 | path = mapping(path, url, type, root); 475 | continue; 476 | } 477 | if (mapping instanceof RegExp) { 478 | mapping = [mapping, '']; 479 | } 480 | path = path.replace(mapping[0], mapping[1]); 481 | } 482 | path = decodeURIComponent(path); 483 | path = path.replace(/[^a-zA-Z0-9\-\.\/ ]+/g, '_'); 484 | stat = host + path.replace(/[\/ ]/g, '.'); 485 | stat = stat.replace(/(^\.)|(\.$)/g, ''); 486 | stat = stat.replace(/\.com/, ''); 487 | stat = stat.replace(/www\./, ''); 488 | if (root) { 489 | stat = root + '.' + stat; 490 | } 491 | if (type) { 492 | stat = stat + '.' + type.toLowerCase(); 493 | } 494 | stat = stat.replace(/\.\./g, '.'); 495 | return stat; 496 | }, 497 | getFullUrl: function(url, location) { 498 | if (location == null) { 499 | location = document.location; 500 | } 501 | if (/^\//.test(url)) { 502 | return location.hostname + url; 503 | } else if (!/https?:\/\//i.test(url)) { 504 | return location.toString() + url; 505 | } else { 506 | return url; 507 | } 508 | }, 509 | monitor: function(root) { 510 | var done, self, _XMLHttpRequest; 511 | if (!root || root === true) { 512 | root = requests.urlToKey(document.location.toString()) + '.requests'; 513 | } 514 | self = this; 515 | done = function(_arg) { 516 | var dur, event, readyStateTimes, request, startTime, stat, type, url; 517 | type = _arg.type, url = _arg.url, event = _arg.event, request = _arg.request, readyStateTimes = _arg.readyStateTimes, startTime = _arg.startTime; 518 | if (startTime != null) { 519 | dur = now() - startTime; 520 | } else { 521 | return; 522 | } 523 | url = self.getFullUrl(url); 524 | stat = self.urlToKey(url, type, root); 525 | send(stat, dur, 'timer'); 526 | self.sendReadyStateTimes(stat, readyStateTimes); 527 | if ((request != null ? request.status : void 0) != null) { 528 | if (request.status > 12000) { 529 | count("" + stat + ".0"); 530 | } else if (request.status !== 0) { 531 | count("" + stat + "." + (request.status.toString().charAt(0)) + "xx"); 532 | } 533 | return count("" + stat + "." + request.status); 534 | } 535 | }; 536 | _XMLHttpRequest = window.XMLHttpRequest; 537 | return window.XMLHttpRequest = function() { 538 | var e, readyStateTimes, req, startTime, _open, _send; 539 | req = new _XMLHttpRequest; 540 | try { 541 | startTime = null; 542 | readyStateTimes = {}; 543 | _open = req.open; 544 | req.open = function(type, url, async) { 545 | var e; 546 | try { 547 | readyStateTimes[0] = now(); 548 | req.addEventListener('readystatechange', function() { 549 | return readyStateTimes[req.readyState] = now(); 550 | }, false); 551 | req.addEventListener('loadend', function(event) { 552 | if ((req.bucky == null) || req.bucky.track !== false) { 553 | return done({ 554 | type: type, 555 | url: url, 556 | event: event, 557 | startTime: startTime, 558 | readyStateTimes: readyStateTimes, 559 | request: req 560 | }); 561 | } 562 | }, false); 563 | } catch (_error) { 564 | e = _error; 565 | log.error("Bucky error monitoring XHR open call", e); 566 | } 567 | return _open.apply(req, arguments); 568 | }; 569 | _send = req.send; 570 | req.send = function() { 571 | startTime = now(); 572 | return _send.apply(req, arguments); 573 | }; 574 | } catch (_error) { 575 | e = _error; 576 | log.error("Bucky error monitoring XHR", e); 577 | } 578 | return req; 579 | }; 580 | } 581 | }; 582 | nextMakeClient = function(nextPrefix) { 583 | var path; 584 | if (nextPrefix == null) { 585 | nextPrefix = ''; 586 | } 587 | path = prefix != null ? prefix : ''; 588 | if (path && nextPrefix) { 589 | path += '.'; 590 | } 591 | if (nextPrefix) { 592 | path += nextPrefix; 593 | } 594 | return makeClient(path); 595 | }; 596 | exports = { 597 | send: send, 598 | count: count, 599 | timer: timer, 600 | now: now, 601 | requests: requests, 602 | sendPagePerformance: sendPagePerformance, 603 | flush: flush, 604 | setOptions: setOptions, 605 | options: options, 606 | history: HISTORY, 607 | active: ACTIVE 608 | }; 609 | for (key in exports) { 610 | val = exports[key]; 611 | nextMakeClient[key] = val; 612 | } 613 | return nextMakeClient; 614 | }; 615 | client = makeClient(); 616 | if (options.pagePerformanceKey) { 617 | client.sendPagePerformance(options.pagePerformanceKey); 618 | } 619 | if (options.requestsKey) { 620 | client.requests.monitor(options.requestsKey); 621 | } 622 | return client; 623 | }; 624 | 625 | if (typeof define === 'function' && define.amd) { 626 | define(exportDef); 627 | } else if (typeof exports === 'object') { 628 | module.exports = exportDef(); 629 | } else { 630 | window.Bucky = exportDef(); 631 | } 632 | 633 | }).call(this); 634 | -------------------------------------------------------------------------------- /spec/vendor/underscore-1.5.2/underscore.js: -------------------------------------------------------------------------------- 1 | // Underscore.js 1.5.2 2 | // http://underscorejs.org 3 | // (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors 4 | // Underscore may be freely distributed under the MIT license. 5 | 6 | (function() { 7 | 8 | // Baseline setup 9 | // -------------- 10 | 11 | // Establish the root object, `window` in the browser, or `exports` on the server. 12 | var root = this; 13 | 14 | // Save the previous value of the `_` variable. 15 | var previousUnderscore = root._; 16 | 17 | // Establish the object that gets returned to break out of a loop iteration. 18 | var breaker = {}; 19 | 20 | // Save bytes in the minified (but not gzipped) version: 21 | var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; 22 | 23 | // Create quick reference variables for speed access to core prototypes. 24 | var 25 | push = ArrayProto.push, 26 | slice = ArrayProto.slice, 27 | concat = ArrayProto.concat, 28 | toString = ObjProto.toString, 29 | hasOwnProperty = ObjProto.hasOwnProperty; 30 | 31 | // All **ECMAScript 5** native function implementations that we hope to use 32 | // are declared here. 33 | var 34 | nativeForEach = ArrayProto.forEach, 35 | nativeMap = ArrayProto.map, 36 | nativeReduce = ArrayProto.reduce, 37 | nativeReduceRight = ArrayProto.reduceRight, 38 | nativeFilter = ArrayProto.filter, 39 | nativeEvery = ArrayProto.every, 40 | nativeSome = ArrayProto.some, 41 | nativeIndexOf = ArrayProto.indexOf, 42 | nativeLastIndexOf = ArrayProto.lastIndexOf, 43 | nativeIsArray = Array.isArray, 44 | nativeKeys = Object.keys, 45 | nativeBind = FuncProto.bind; 46 | 47 | // Create a safe reference to the Underscore object for use below. 48 | var _ = function(obj) { 49 | if (obj instanceof _) return obj; 50 | if (!(this instanceof _)) return new _(obj); 51 | this._wrapped = obj; 52 | }; 53 | 54 | // Export the Underscore object for **Node.js**, with 55 | // backwards-compatibility for the old `require()` API. If we're in 56 | // the browser, add `_` as a global object via a string identifier, 57 | // for Closure Compiler "advanced" mode. 58 | if (typeof exports !== 'undefined') { 59 | if (typeof module !== 'undefined' && module.exports) { 60 | exports = module.exports = _; 61 | } 62 | exports._ = _; 63 | } else { 64 | root._ = _; 65 | } 66 | 67 | // Current version. 68 | _.VERSION = '1.5.2'; 69 | 70 | // Collection Functions 71 | // -------------------- 72 | 73 | // The cornerstone, an `each` implementation, aka `forEach`. 74 | // Handles objects with the built-in `forEach`, arrays, and raw objects. 75 | // Delegates to **ECMAScript 5**'s native `forEach` if available. 76 | var each = _.each = _.forEach = function(obj, iterator, context) { 77 | if (obj == null) return; 78 | if (nativeForEach && obj.forEach === nativeForEach) { 79 | obj.forEach(iterator, context); 80 | } else if (obj.length === +obj.length) { 81 | for (var i = 0, length = obj.length; i < length; i++) { 82 | if (iterator.call(context, obj[i], i, obj) === breaker) return; 83 | } 84 | } else { 85 | var keys = _.keys(obj); 86 | for (var i = 0, length = keys.length; i < length; i++) { 87 | if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return; 88 | } 89 | } 90 | }; 91 | 92 | // Return the results of applying the iterator to each element. 93 | // Delegates to **ECMAScript 5**'s native `map` if available. 94 | _.map = _.collect = function(obj, iterator, context) { 95 | var results = []; 96 | if (obj == null) return results; 97 | if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context); 98 | each(obj, function(value, index, list) { 99 | results.push(iterator.call(context, value, index, list)); 100 | }); 101 | return results; 102 | }; 103 | 104 | var reduceError = 'Reduce of empty array with no initial value'; 105 | 106 | // **Reduce** builds up a single result from a list of values, aka `inject`, 107 | // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available. 108 | _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) { 109 | var initial = arguments.length > 2; 110 | if (obj == null) obj = []; 111 | if (nativeReduce && obj.reduce === nativeReduce) { 112 | if (context) iterator = _.bind(iterator, context); 113 | return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator); 114 | } 115 | each(obj, function(value, index, list) { 116 | if (!initial) { 117 | memo = value; 118 | initial = true; 119 | } else { 120 | memo = iterator.call(context, memo, value, index, list); 121 | } 122 | }); 123 | if (!initial) throw new TypeError(reduceError); 124 | return memo; 125 | }; 126 | 127 | // The right-associative version of reduce, also known as `foldr`. 128 | // Delegates to **ECMAScript 5**'s native `reduceRight` if available. 129 | _.reduceRight = _.foldr = function(obj, iterator, memo, context) { 130 | var initial = arguments.length > 2; 131 | if (obj == null) obj = []; 132 | if (nativeReduceRight && obj.reduceRight === nativeReduceRight) { 133 | if (context) iterator = _.bind(iterator, context); 134 | return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator); 135 | } 136 | var length = obj.length; 137 | if (length !== +length) { 138 | var keys = _.keys(obj); 139 | length = keys.length; 140 | } 141 | each(obj, function(value, index, list) { 142 | index = keys ? keys[--length] : --length; 143 | if (!initial) { 144 | memo = obj[index]; 145 | initial = true; 146 | } else { 147 | memo = iterator.call(context, memo, obj[index], index, list); 148 | } 149 | }); 150 | if (!initial) throw new TypeError(reduceError); 151 | return memo; 152 | }; 153 | 154 | // Return the first value which passes a truth test. Aliased as `detect`. 155 | _.find = _.detect = function(obj, iterator, context) { 156 | var result; 157 | any(obj, function(value, index, list) { 158 | if (iterator.call(context, value, index, list)) { 159 | result = value; 160 | return true; 161 | } 162 | }); 163 | return result; 164 | }; 165 | 166 | // Return all the elements that pass a truth test. 167 | // Delegates to **ECMAScript 5**'s native `filter` if available. 168 | // Aliased as `select`. 169 | _.filter = _.select = function(obj, iterator, context) { 170 | var results = []; 171 | if (obj == null) return results; 172 | if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context); 173 | each(obj, function(value, index, list) { 174 | if (iterator.call(context, value, index, list)) results.push(value); 175 | }); 176 | return results; 177 | }; 178 | 179 | // Return all the elements for which a truth test fails. 180 | _.reject = function(obj, iterator, context) { 181 | return _.filter(obj, function(value, index, list) { 182 | return !iterator.call(context, value, index, list); 183 | }, context); 184 | }; 185 | 186 | // Determine whether all of the elements match a truth test. 187 | // Delegates to **ECMAScript 5**'s native `every` if available. 188 | // Aliased as `all`. 189 | _.every = _.all = function(obj, iterator, context) { 190 | iterator || (iterator = _.identity); 191 | var result = true; 192 | if (obj == null) return result; 193 | if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context); 194 | each(obj, function(value, index, list) { 195 | if (!(result = result && iterator.call(context, value, index, list))) return breaker; 196 | }); 197 | return !!result; 198 | }; 199 | 200 | // Determine if at least one element in the object matches a truth test. 201 | // Delegates to **ECMAScript 5**'s native `some` if available. 202 | // Aliased as `any`. 203 | var any = _.some = _.any = function(obj, iterator, context) { 204 | iterator || (iterator = _.identity); 205 | var result = false; 206 | if (obj == null) return result; 207 | if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context); 208 | each(obj, function(value, index, list) { 209 | if (result || (result = iterator.call(context, value, index, list))) return breaker; 210 | }); 211 | return !!result; 212 | }; 213 | 214 | // Determine if the array or object contains a given value (using `===`). 215 | // Aliased as `include`. 216 | _.contains = _.include = function(obj, target) { 217 | if (obj == null) return false; 218 | if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1; 219 | return any(obj, function(value) { 220 | return value === target; 221 | }); 222 | }; 223 | 224 | // Invoke a method (with arguments) on every item in a collection. 225 | _.invoke = function(obj, method) { 226 | var args = slice.call(arguments, 2); 227 | var isFunc = _.isFunction(method); 228 | return _.map(obj, function(value) { 229 | return (isFunc ? method : value[method]).apply(value, args); 230 | }); 231 | }; 232 | 233 | // Convenience version of a common use case of `map`: fetching a property. 234 | _.pluck = function(obj, key) { 235 | return _.map(obj, function(value){ return value[key]; }); 236 | }; 237 | 238 | // Convenience version of a common use case of `filter`: selecting only objects 239 | // containing specific `key:value` pairs. 240 | _.where = function(obj, attrs, first) { 241 | if (_.isEmpty(attrs)) return first ? void 0 : []; 242 | return _[first ? 'find' : 'filter'](obj, function(value) { 243 | for (var key in attrs) { 244 | if (attrs[key] !== value[key]) return false; 245 | } 246 | return true; 247 | }); 248 | }; 249 | 250 | // Convenience version of a common use case of `find`: getting the first object 251 | // containing specific `key:value` pairs. 252 | _.findWhere = function(obj, attrs) { 253 | return _.where(obj, attrs, true); 254 | }; 255 | 256 | // Return the maximum element or (element-based computation). 257 | // Can't optimize arrays of integers longer than 65,535 elements. 258 | // See [WebKit Bug 80797](https://bugs.webkit.org/show_bug.cgi?id=80797) 259 | _.max = function(obj, iterator, context) { 260 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 261 | return Math.max.apply(Math, obj); 262 | } 263 | if (!iterator && _.isEmpty(obj)) return -Infinity; 264 | var result = {computed : -Infinity, value: -Infinity}; 265 | each(obj, function(value, index, list) { 266 | var computed = iterator ? iterator.call(context, value, index, list) : value; 267 | computed > result.computed && (result = {value : value, computed : computed}); 268 | }); 269 | return result.value; 270 | }; 271 | 272 | // Return the minimum element (or element-based computation). 273 | _.min = function(obj, iterator, context) { 274 | if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) { 275 | return Math.min.apply(Math, obj); 276 | } 277 | if (!iterator && _.isEmpty(obj)) return Infinity; 278 | var result = {computed : Infinity, value: Infinity}; 279 | each(obj, function(value, index, list) { 280 | var computed = iterator ? iterator.call(context, value, index, list) : value; 281 | computed < result.computed && (result = {value : value, computed : computed}); 282 | }); 283 | return result.value; 284 | }; 285 | 286 | // Shuffle an array, using the modern version of the 287 | // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). 288 | _.shuffle = function(obj) { 289 | var rand; 290 | var index = 0; 291 | var shuffled = []; 292 | each(obj, function(value) { 293 | rand = _.random(index++); 294 | shuffled[index - 1] = shuffled[rand]; 295 | shuffled[rand] = value; 296 | }); 297 | return shuffled; 298 | }; 299 | 300 | // Sample **n** random values from an array. 301 | // If **n** is not specified, returns a single random element from the array. 302 | // The internal `guard` argument allows it to work with `map`. 303 | _.sample = function(obj, n, guard) { 304 | if (arguments.length < 2 || guard) { 305 | return obj[_.random(obj.length - 1)]; 306 | } 307 | return _.shuffle(obj).slice(0, Math.max(0, n)); 308 | }; 309 | 310 | // An internal function to generate lookup iterators. 311 | var lookupIterator = function(value) { 312 | return _.isFunction(value) ? value : function(obj){ return obj[value]; }; 313 | }; 314 | 315 | // Sort the object's values by a criterion produced by an iterator. 316 | _.sortBy = function(obj, value, context) { 317 | var iterator = lookupIterator(value); 318 | return _.pluck(_.map(obj, function(value, index, list) { 319 | return { 320 | value: value, 321 | index: index, 322 | criteria: iterator.call(context, value, index, list) 323 | }; 324 | }).sort(function(left, right) { 325 | var a = left.criteria; 326 | var b = right.criteria; 327 | if (a !== b) { 328 | if (a > b || a === void 0) return 1; 329 | if (a < b || b === void 0) return -1; 330 | } 331 | return left.index - right.index; 332 | }), 'value'); 333 | }; 334 | 335 | // An internal function used for aggregate "group by" operations. 336 | var group = function(behavior) { 337 | return function(obj, value, context) { 338 | var result = {}; 339 | var iterator = value == null ? _.identity : lookupIterator(value); 340 | each(obj, function(value, index) { 341 | var key = iterator.call(context, value, index, obj); 342 | behavior(result, key, value); 343 | }); 344 | return result; 345 | }; 346 | }; 347 | 348 | // Groups the object's values by a criterion. Pass either a string attribute 349 | // to group by, or a function that returns the criterion. 350 | _.groupBy = group(function(result, key, value) { 351 | (_.has(result, key) ? result[key] : (result[key] = [])).push(value); 352 | }); 353 | 354 | // Indexes the object's values by a criterion, similar to `groupBy`, but for 355 | // when you know that your index values will be unique. 356 | _.indexBy = group(function(result, key, value) { 357 | result[key] = value; 358 | }); 359 | 360 | // Counts instances of an object that group by a certain criterion. Pass 361 | // either a string attribute to count by, or a function that returns the 362 | // criterion. 363 | _.countBy = group(function(result, key) { 364 | _.has(result, key) ? result[key]++ : result[key] = 1; 365 | }); 366 | 367 | // Use a comparator function to figure out the smallest index at which 368 | // an object should be inserted so as to maintain order. Uses binary search. 369 | _.sortedIndex = function(array, obj, iterator, context) { 370 | iterator = iterator == null ? _.identity : lookupIterator(iterator); 371 | var value = iterator.call(context, obj); 372 | var low = 0, high = array.length; 373 | while (low < high) { 374 | var mid = (low + high) >>> 1; 375 | iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid; 376 | } 377 | return low; 378 | }; 379 | 380 | // Safely create a real, live array from anything iterable. 381 | _.toArray = function(obj) { 382 | if (!obj) return []; 383 | if (_.isArray(obj)) return slice.call(obj); 384 | if (obj.length === +obj.length) return _.map(obj, _.identity); 385 | return _.values(obj); 386 | }; 387 | 388 | // Return the number of elements in an object. 389 | _.size = function(obj) { 390 | if (obj == null) return 0; 391 | return (obj.length === +obj.length) ? obj.length : _.keys(obj).length; 392 | }; 393 | 394 | // Array Functions 395 | // --------------- 396 | 397 | // Get the first element of an array. Passing **n** will return the first N 398 | // values in the array. Aliased as `head` and `take`. The **guard** check 399 | // allows it to work with `_.map`. 400 | _.first = _.head = _.take = function(array, n, guard) { 401 | if (array == null) return void 0; 402 | return (n == null) || guard ? array[0] : slice.call(array, 0, n); 403 | }; 404 | 405 | // Returns everything but the last entry of the array. Especially useful on 406 | // the arguments object. Passing **n** will return all the values in 407 | // the array, excluding the last N. The **guard** check allows it to work with 408 | // `_.map`. 409 | _.initial = function(array, n, guard) { 410 | return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n)); 411 | }; 412 | 413 | // Get the last element of an array. Passing **n** will return the last N 414 | // values in the array. The **guard** check allows it to work with `_.map`. 415 | _.last = function(array, n, guard) { 416 | if (array == null) return void 0; 417 | if ((n == null) || guard) { 418 | return array[array.length - 1]; 419 | } else { 420 | return slice.call(array, Math.max(array.length - n, 0)); 421 | } 422 | }; 423 | 424 | // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. 425 | // Especially useful on the arguments object. Passing an **n** will return 426 | // the rest N values in the array. The **guard** 427 | // check allows it to work with `_.map`. 428 | _.rest = _.tail = _.drop = function(array, n, guard) { 429 | return slice.call(array, (n == null) || guard ? 1 : n); 430 | }; 431 | 432 | // Trim out all falsy values from an array. 433 | _.compact = function(array) { 434 | return _.filter(array, _.identity); 435 | }; 436 | 437 | // Internal implementation of a recursive `flatten` function. 438 | var flatten = function(input, shallow, output) { 439 | if (shallow && _.every(input, _.isArray)) { 440 | return concat.apply(output, input); 441 | } 442 | each(input, function(value) { 443 | if (_.isArray(value) || _.isArguments(value)) { 444 | shallow ? push.apply(output, value) : flatten(value, shallow, output); 445 | } else { 446 | output.push(value); 447 | } 448 | }); 449 | return output; 450 | }; 451 | 452 | // Flatten out an array, either recursively (by default), or just one level. 453 | _.flatten = function(array, shallow) { 454 | return flatten(array, shallow, []); 455 | }; 456 | 457 | // Return a version of the array that does not contain the specified value(s). 458 | _.without = function(array) { 459 | return _.difference(array, slice.call(arguments, 1)); 460 | }; 461 | 462 | // Produce a duplicate-free version of the array. If the array has already 463 | // been sorted, you have the option of using a faster algorithm. 464 | // Aliased as `unique`. 465 | _.uniq = _.unique = function(array, isSorted, iterator, context) { 466 | if (_.isFunction(isSorted)) { 467 | context = iterator; 468 | iterator = isSorted; 469 | isSorted = false; 470 | } 471 | var initial = iterator ? _.map(array, iterator, context) : array; 472 | var results = []; 473 | var seen = []; 474 | each(initial, function(value, index) { 475 | if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) { 476 | seen.push(value); 477 | results.push(array[index]); 478 | } 479 | }); 480 | return results; 481 | }; 482 | 483 | // Produce an array that contains the union: each distinct element from all of 484 | // the passed-in arrays. 485 | _.union = function() { 486 | return _.uniq(_.flatten(arguments, true)); 487 | }; 488 | 489 | // Produce an array that contains every item shared between all the 490 | // passed-in arrays. 491 | _.intersection = function(array) { 492 | var rest = slice.call(arguments, 1); 493 | return _.filter(_.uniq(array), function(item) { 494 | return _.every(rest, function(other) { 495 | return _.indexOf(other, item) >= 0; 496 | }); 497 | }); 498 | }; 499 | 500 | // Take the difference between one array and a number of other arrays. 501 | // Only the elements present in just the first array will remain. 502 | _.difference = function(array) { 503 | var rest = concat.apply(ArrayProto, slice.call(arguments, 1)); 504 | return _.filter(array, function(value){ return !_.contains(rest, value); }); 505 | }; 506 | 507 | // Zip together multiple lists into a single array -- elements that share 508 | // an index go together. 509 | _.zip = function() { 510 | var length = _.max(_.pluck(arguments, "length").concat(0)); 511 | var results = new Array(length); 512 | for (var i = 0; i < length; i++) { 513 | results[i] = _.pluck(arguments, '' + i); 514 | } 515 | return results; 516 | }; 517 | 518 | // Converts lists into objects. Pass either a single array of `[key, value]` 519 | // pairs, or two parallel arrays of the same length -- one of keys, and one of 520 | // the corresponding values. 521 | _.object = function(list, values) { 522 | if (list == null) return {}; 523 | var result = {}; 524 | for (var i = 0, length = list.length; i < length; i++) { 525 | if (values) { 526 | result[list[i]] = values[i]; 527 | } else { 528 | result[list[i][0]] = list[i][1]; 529 | } 530 | } 531 | return result; 532 | }; 533 | 534 | // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**), 535 | // we need this function. Return the position of the first occurrence of an 536 | // item in an array, or -1 if the item is not included in the array. 537 | // Delegates to **ECMAScript 5**'s native `indexOf` if available. 538 | // If the array is large and already in sort order, pass `true` 539 | // for **isSorted** to use binary search. 540 | _.indexOf = function(array, item, isSorted) { 541 | if (array == null) return -1; 542 | var i = 0, length = array.length; 543 | if (isSorted) { 544 | if (typeof isSorted == 'number') { 545 | i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted); 546 | } else { 547 | i = _.sortedIndex(array, item); 548 | return array[i] === item ? i : -1; 549 | } 550 | } 551 | if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted); 552 | for (; i < length; i++) if (array[i] === item) return i; 553 | return -1; 554 | }; 555 | 556 | // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available. 557 | _.lastIndexOf = function(array, item, from) { 558 | if (array == null) return -1; 559 | var hasIndex = from != null; 560 | if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) { 561 | return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item); 562 | } 563 | var i = (hasIndex ? from : array.length); 564 | while (i--) if (array[i] === item) return i; 565 | return -1; 566 | }; 567 | 568 | // Generate an integer Array containing an arithmetic progression. A port of 569 | // the native Python `range()` function. See 570 | // [the Python documentation](http://docs.python.org/library/functions.html#range). 571 | _.range = function(start, stop, step) { 572 | if (arguments.length <= 1) { 573 | stop = start || 0; 574 | start = 0; 575 | } 576 | step = arguments[2] || 1; 577 | 578 | var length = Math.max(Math.ceil((stop - start) / step), 0); 579 | var idx = 0; 580 | var range = new Array(length); 581 | 582 | while(idx < length) { 583 | range[idx++] = start; 584 | start += step; 585 | } 586 | 587 | return range; 588 | }; 589 | 590 | // Function (ahem) Functions 591 | // ------------------ 592 | 593 | // Reusable constructor function for prototype setting. 594 | var ctor = function(){}; 595 | 596 | // Create a function bound to a given object (assigning `this`, and arguments, 597 | // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if 598 | // available. 599 | _.bind = function(func, context) { 600 | var args, bound; 601 | if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); 602 | if (!_.isFunction(func)) throw new TypeError; 603 | args = slice.call(arguments, 2); 604 | return bound = function() { 605 | if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments))); 606 | ctor.prototype = func.prototype; 607 | var self = new ctor; 608 | ctor.prototype = null; 609 | var result = func.apply(self, args.concat(slice.call(arguments))); 610 | if (Object(result) === result) return result; 611 | return self; 612 | }; 613 | }; 614 | 615 | // Partially apply a function by creating a version that has had some of its 616 | // arguments pre-filled, without changing its dynamic `this` context. 617 | _.partial = function(func) { 618 | var args = slice.call(arguments, 1); 619 | return function() { 620 | return func.apply(this, args.concat(slice.call(arguments))); 621 | }; 622 | }; 623 | 624 | // Bind all of an object's methods to that object. Useful for ensuring that 625 | // all callbacks defined on an object belong to it. 626 | _.bindAll = function(obj) { 627 | var funcs = slice.call(arguments, 1); 628 | if (funcs.length === 0) throw new Error("bindAll must be passed function names"); 629 | each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); }); 630 | return obj; 631 | }; 632 | 633 | // Memoize an expensive function by storing its results. 634 | _.memoize = function(func, hasher) { 635 | var memo = {}; 636 | hasher || (hasher = _.identity); 637 | return function() { 638 | var key = hasher.apply(this, arguments); 639 | return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments)); 640 | }; 641 | }; 642 | 643 | // Delays a function for the given number of milliseconds, and then calls 644 | // it with the arguments supplied. 645 | _.delay = function(func, wait) { 646 | var args = slice.call(arguments, 2); 647 | return setTimeout(function(){ return func.apply(null, args); }, wait); 648 | }; 649 | 650 | // Defers a function, scheduling it to run after the current call stack has 651 | // cleared. 652 | _.defer = function(func) { 653 | return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1))); 654 | }; 655 | 656 | // Returns a function, that, when invoked, will only be triggered at most once 657 | // during a given window of time. Normally, the throttled function will run 658 | // as much as it can, without ever going more than once per `wait` duration; 659 | // but if you'd like to disable the execution on the leading edge, pass 660 | // `{leading: false}`. To disable execution on the trailing edge, ditto. 661 | _.throttle = function(func, wait, options) { 662 | var context, args, result; 663 | var timeout = null; 664 | var previous = 0; 665 | options || (options = {}); 666 | var later = function() { 667 | previous = options.leading === false ? 0 : new Date; 668 | timeout = null; 669 | result = func.apply(context, args); 670 | }; 671 | return function() { 672 | var now = new Date; 673 | if (!previous && options.leading === false) previous = now; 674 | var remaining = wait - (now - previous); 675 | context = this; 676 | args = arguments; 677 | if (remaining <= 0) { 678 | clearTimeout(timeout); 679 | timeout = null; 680 | previous = now; 681 | result = func.apply(context, args); 682 | } else if (!timeout && options.trailing !== false) { 683 | timeout = setTimeout(later, remaining); 684 | } 685 | return result; 686 | }; 687 | }; 688 | 689 | // Returns a function, that, as long as it continues to be invoked, will not 690 | // be triggered. The function will be called after it stops being called for 691 | // N milliseconds. If `immediate` is passed, trigger the function on the 692 | // leading edge, instead of the trailing. 693 | _.debounce = function(func, wait, immediate) { 694 | var timeout, args, context, timestamp, result; 695 | return function() { 696 | context = this; 697 | args = arguments; 698 | timestamp = new Date(); 699 | var later = function() { 700 | var last = (new Date()) - timestamp; 701 | if (last < wait) { 702 | timeout = setTimeout(later, wait - last); 703 | } else { 704 | timeout = null; 705 | if (!immediate) result = func.apply(context, args); 706 | } 707 | }; 708 | var callNow = immediate && !timeout; 709 | if (!timeout) { 710 | timeout = setTimeout(later, wait); 711 | } 712 | if (callNow) result = func.apply(context, args); 713 | return result; 714 | }; 715 | }; 716 | 717 | // Returns a function that will be executed at most one time, no matter how 718 | // often you call it. Useful for lazy initialization. 719 | _.once = function(func) { 720 | var ran = false, memo; 721 | return function() { 722 | if (ran) return memo; 723 | ran = true; 724 | memo = func.apply(this, arguments); 725 | func = null; 726 | return memo; 727 | }; 728 | }; 729 | 730 | // Returns the first function passed as an argument to the second, 731 | // allowing you to adjust arguments, run code before and after, and 732 | // conditionally execute the original function. 733 | _.wrap = function(func, wrapper) { 734 | return function() { 735 | var args = [func]; 736 | push.apply(args, arguments); 737 | return wrapper.apply(this, args); 738 | }; 739 | }; 740 | 741 | // Returns a function that is the composition of a list of functions, each 742 | // consuming the return value of the function that follows. 743 | _.compose = function() { 744 | var funcs = arguments; 745 | return function() { 746 | var args = arguments; 747 | for (var i = funcs.length - 1; i >= 0; i--) { 748 | args = [funcs[i].apply(this, args)]; 749 | } 750 | return args[0]; 751 | }; 752 | }; 753 | 754 | // Returns a function that will only be executed after being called N times. 755 | _.after = function(times, func) { 756 | return function() { 757 | if (--times < 1) { 758 | return func.apply(this, arguments); 759 | } 760 | }; 761 | }; 762 | 763 | // Object Functions 764 | // ---------------- 765 | 766 | // Retrieve the names of an object's properties. 767 | // Delegates to **ECMAScript 5**'s native `Object.keys` 768 | _.keys = nativeKeys || function(obj) { 769 | if (obj !== Object(obj)) throw new TypeError('Invalid object'); 770 | var keys = []; 771 | for (var key in obj) if (_.has(obj, key)) keys.push(key); 772 | return keys; 773 | }; 774 | 775 | // Retrieve the values of an object's properties. 776 | _.values = function(obj) { 777 | var keys = _.keys(obj); 778 | var length = keys.length; 779 | var values = new Array(length); 780 | for (var i = 0; i < length; i++) { 781 | values[i] = obj[keys[i]]; 782 | } 783 | return values; 784 | }; 785 | 786 | // Convert an object into a list of `[key, value]` pairs. 787 | _.pairs = function(obj) { 788 | var keys = _.keys(obj); 789 | var length = keys.length; 790 | var pairs = new Array(length); 791 | for (var i = 0; i < length; i++) { 792 | pairs[i] = [keys[i], obj[keys[i]]]; 793 | } 794 | return pairs; 795 | }; 796 | 797 | // Invert the keys and values of an object. The values must be serializable. 798 | _.invert = function(obj) { 799 | var result = {}; 800 | var keys = _.keys(obj); 801 | for (var i = 0, length = keys.length; i < length; i++) { 802 | result[obj[keys[i]]] = keys[i]; 803 | } 804 | return result; 805 | }; 806 | 807 | // Return a sorted list of the function names available on the object. 808 | // Aliased as `methods` 809 | _.functions = _.methods = function(obj) { 810 | var names = []; 811 | for (var key in obj) { 812 | if (_.isFunction(obj[key])) names.push(key); 813 | } 814 | return names.sort(); 815 | }; 816 | 817 | // Extend a given object with all the properties in passed-in object(s). 818 | _.extend = function(obj) { 819 | each(slice.call(arguments, 1), function(source) { 820 | if (source) { 821 | for (var prop in source) { 822 | obj[prop] = source[prop]; 823 | } 824 | } 825 | }); 826 | return obj; 827 | }; 828 | 829 | // Return a copy of the object only containing the whitelisted properties. 830 | _.pick = function(obj) { 831 | var copy = {}; 832 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 833 | each(keys, function(key) { 834 | if (key in obj) copy[key] = obj[key]; 835 | }); 836 | return copy; 837 | }; 838 | 839 | // Return a copy of the object without the blacklisted properties. 840 | _.omit = function(obj) { 841 | var copy = {}; 842 | var keys = concat.apply(ArrayProto, slice.call(arguments, 1)); 843 | for (var key in obj) { 844 | if (!_.contains(keys, key)) copy[key] = obj[key]; 845 | } 846 | return copy; 847 | }; 848 | 849 | // Fill in a given object with default properties. 850 | _.defaults = function(obj) { 851 | each(slice.call(arguments, 1), function(source) { 852 | if (source) { 853 | for (var prop in source) { 854 | if (obj[prop] === void 0) obj[prop] = source[prop]; 855 | } 856 | } 857 | }); 858 | return obj; 859 | }; 860 | 861 | // Create a (shallow-cloned) duplicate of an object. 862 | _.clone = function(obj) { 863 | if (!_.isObject(obj)) return obj; 864 | return _.isArray(obj) ? obj.slice() : _.extend({}, obj); 865 | }; 866 | 867 | // Invokes interceptor with the obj, and then returns obj. 868 | // The primary purpose of this method is to "tap into" a method chain, in 869 | // order to perform operations on intermediate results within the chain. 870 | _.tap = function(obj, interceptor) { 871 | interceptor(obj); 872 | return obj; 873 | }; 874 | 875 | // Internal recursive comparison function for `isEqual`. 876 | var eq = function(a, b, aStack, bStack) { 877 | // Identical objects are equal. `0 === -0`, but they aren't identical. 878 | // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). 879 | if (a === b) return a !== 0 || 1 / a == 1 / b; 880 | // A strict comparison is necessary because `null == undefined`. 881 | if (a == null || b == null) return a === b; 882 | // Unwrap any wrapped objects. 883 | if (a instanceof _) a = a._wrapped; 884 | if (b instanceof _) b = b._wrapped; 885 | // Compare `[[Class]]` names. 886 | var className = toString.call(a); 887 | if (className != toString.call(b)) return false; 888 | switch (className) { 889 | // Strings, numbers, dates, and booleans are compared by value. 890 | case '[object String]': 891 | // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is 892 | // equivalent to `new String("5")`. 893 | return a == String(b); 894 | case '[object Number]': 895 | // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for 896 | // other numeric values. 897 | return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b); 898 | case '[object Date]': 899 | case '[object Boolean]': 900 | // Coerce dates and booleans to numeric primitive values. Dates are compared by their 901 | // millisecond representations. Note that invalid dates with millisecond representations 902 | // of `NaN` are not equivalent. 903 | return +a == +b; 904 | // RegExps are compared by their source patterns and flags. 905 | case '[object RegExp]': 906 | return a.source == b.source && 907 | a.global == b.global && 908 | a.multiline == b.multiline && 909 | a.ignoreCase == b.ignoreCase; 910 | } 911 | if (typeof a != 'object' || typeof b != 'object') return false; 912 | // Assume equality for cyclic structures. The algorithm for detecting cyclic 913 | // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. 914 | var length = aStack.length; 915 | while (length--) { 916 | // Linear search. Performance is inversely proportional to the number of 917 | // unique nested structures. 918 | if (aStack[length] == a) return bStack[length] == b; 919 | } 920 | // Objects with different constructors are not equivalent, but `Object`s 921 | // from different frames are. 922 | var aCtor = a.constructor, bCtor = b.constructor; 923 | if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && 924 | _.isFunction(bCtor) && (bCtor instanceof bCtor))) { 925 | return false; 926 | } 927 | // Add the first object to the stack of traversed objects. 928 | aStack.push(a); 929 | bStack.push(b); 930 | var size = 0, result = true; 931 | // Recursively compare objects and arrays. 932 | if (className == '[object Array]') { 933 | // Compare array lengths to determine if a deep comparison is necessary. 934 | size = a.length; 935 | result = size == b.length; 936 | if (result) { 937 | // Deep compare the contents, ignoring non-numeric properties. 938 | while (size--) { 939 | if (!(result = eq(a[size], b[size], aStack, bStack))) break; 940 | } 941 | } 942 | } else { 943 | // Deep compare objects. 944 | for (var key in a) { 945 | if (_.has(a, key)) { 946 | // Count the expected number of properties. 947 | size++; 948 | // Deep compare each member. 949 | if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break; 950 | } 951 | } 952 | // Ensure that both objects contain the same number of properties. 953 | if (result) { 954 | for (key in b) { 955 | if (_.has(b, key) && !(size--)) break; 956 | } 957 | result = !size; 958 | } 959 | } 960 | // Remove the first object from the stack of traversed objects. 961 | aStack.pop(); 962 | bStack.pop(); 963 | return result; 964 | }; 965 | 966 | // Perform a deep comparison to check if two objects are equal. 967 | _.isEqual = function(a, b) { 968 | return eq(a, b, [], []); 969 | }; 970 | 971 | // Is a given array, string, or object empty? 972 | // An "empty" object has no enumerable own-properties. 973 | _.isEmpty = function(obj) { 974 | if (obj == null) return true; 975 | if (_.isArray(obj) || _.isString(obj)) return obj.length === 0; 976 | for (var key in obj) if (_.has(obj, key)) return false; 977 | return true; 978 | }; 979 | 980 | // Is a given value a DOM element? 981 | _.isElement = function(obj) { 982 | return !!(obj && obj.nodeType === 1); 983 | }; 984 | 985 | // Is a given value an array? 986 | // Delegates to ECMA5's native Array.isArray 987 | _.isArray = nativeIsArray || function(obj) { 988 | return toString.call(obj) == '[object Array]'; 989 | }; 990 | 991 | // Is a given variable an object? 992 | _.isObject = function(obj) { 993 | return obj === Object(obj); 994 | }; 995 | 996 | // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp. 997 | each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) { 998 | _['is' + name] = function(obj) { 999 | return toString.call(obj) == '[object ' + name + ']'; 1000 | }; 1001 | }); 1002 | 1003 | // Define a fallback version of the method in browsers (ahem, IE), where 1004 | // there isn't any inspectable "Arguments" type. 1005 | if (!_.isArguments(arguments)) { 1006 | _.isArguments = function(obj) { 1007 | return !!(obj && _.has(obj, 'callee')); 1008 | }; 1009 | } 1010 | 1011 | // Optimize `isFunction` if appropriate. 1012 | if (typeof (/./) !== 'function') { 1013 | _.isFunction = function(obj) { 1014 | return typeof obj === 'function'; 1015 | }; 1016 | } 1017 | 1018 | // Is a given object a finite number? 1019 | _.isFinite = function(obj) { 1020 | return isFinite(obj) && !isNaN(parseFloat(obj)); 1021 | }; 1022 | 1023 | // Is the given value `NaN`? (NaN is the only number which does not equal itself). 1024 | _.isNaN = function(obj) { 1025 | return _.isNumber(obj) && obj != +obj; 1026 | }; 1027 | 1028 | // Is a given value a boolean? 1029 | _.isBoolean = function(obj) { 1030 | return obj === true || obj === false || toString.call(obj) == '[object Boolean]'; 1031 | }; 1032 | 1033 | // Is a given value equal to null? 1034 | _.isNull = function(obj) { 1035 | return obj === null; 1036 | }; 1037 | 1038 | // Is a given variable undefined? 1039 | _.isUndefined = function(obj) { 1040 | return obj === void 0; 1041 | }; 1042 | 1043 | // Shortcut function for checking if an object has a given property directly 1044 | // on itself (in other words, not on a prototype). 1045 | _.has = function(obj, key) { 1046 | return hasOwnProperty.call(obj, key); 1047 | }; 1048 | 1049 | // Utility Functions 1050 | // ----------------- 1051 | 1052 | // Run Underscore.js in *noConflict* mode, returning the `_` variable to its 1053 | // previous owner. Returns a reference to the Underscore object. 1054 | _.noConflict = function() { 1055 | root._ = previousUnderscore; 1056 | return this; 1057 | }; 1058 | 1059 | // Keep the identity function around for default iterators. 1060 | _.identity = function(value) { 1061 | return value; 1062 | }; 1063 | 1064 | // Run a function **n** times. 1065 | _.times = function(n, iterator, context) { 1066 | var accum = Array(Math.max(0, n)); 1067 | for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i); 1068 | return accum; 1069 | }; 1070 | 1071 | // Return a random integer between min and max (inclusive). 1072 | _.random = function(min, max) { 1073 | if (max == null) { 1074 | max = min; 1075 | min = 0; 1076 | } 1077 | return min + Math.floor(Math.random() * (max - min + 1)); 1078 | }; 1079 | 1080 | // List of HTML entities for escaping. 1081 | var entityMap = { 1082 | escape: { 1083 | '&': '&', 1084 | '<': '<', 1085 | '>': '>', 1086 | '"': '"', 1087 | "'": ''' 1088 | } 1089 | }; 1090 | entityMap.unescape = _.invert(entityMap.escape); 1091 | 1092 | // Regexes containing the keys and values listed immediately above. 1093 | var entityRegexes = { 1094 | escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'), 1095 | unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g') 1096 | }; 1097 | 1098 | // Functions for escaping and unescaping strings to/from HTML interpolation. 1099 | _.each(['escape', 'unescape'], function(method) { 1100 | _[method] = function(string) { 1101 | if (string == null) return ''; 1102 | return ('' + string).replace(entityRegexes[method], function(match) { 1103 | return entityMap[method][match]; 1104 | }); 1105 | }; 1106 | }); 1107 | 1108 | // If the value of the named `property` is a function then invoke it with the 1109 | // `object` as context; otherwise, return it. 1110 | _.result = function(object, property) { 1111 | if (object == null) return void 0; 1112 | var value = object[property]; 1113 | return _.isFunction(value) ? value.call(object) : value; 1114 | }; 1115 | 1116 | // Add your own custom functions to the Underscore object. 1117 | _.mixin = function(obj) { 1118 | each(_.functions(obj), function(name) { 1119 | var func = _[name] = obj[name]; 1120 | _.prototype[name] = function() { 1121 | var args = [this._wrapped]; 1122 | push.apply(args, arguments); 1123 | return result.call(this, func.apply(_, args)); 1124 | }; 1125 | }); 1126 | }; 1127 | 1128 | // Generate a unique integer id (unique within the entire client session). 1129 | // Useful for temporary DOM ids. 1130 | var idCounter = 0; 1131 | _.uniqueId = function(prefix) { 1132 | var id = ++idCounter + ''; 1133 | return prefix ? prefix + id : id; 1134 | }; 1135 | 1136 | // By default, Underscore uses ERB-style template delimiters, change the 1137 | // following template settings to use alternative delimiters. 1138 | _.templateSettings = { 1139 | evaluate : /<%([\s\S]+?)%>/g, 1140 | interpolate : /<%=([\s\S]+?)%>/g, 1141 | escape : /<%-([\s\S]+?)%>/g 1142 | }; 1143 | 1144 | // When customizing `templateSettings`, if you don't want to define an 1145 | // interpolation, evaluation or escaping regex, we need one that is 1146 | // guaranteed not to match. 1147 | var noMatch = /(.)^/; 1148 | 1149 | // Certain characters need to be escaped so that they can be put into a 1150 | // string literal. 1151 | var escapes = { 1152 | "'": "'", 1153 | '\\': '\\', 1154 | '\r': 'r', 1155 | '\n': 'n', 1156 | '\t': 't', 1157 | '\u2028': 'u2028', 1158 | '\u2029': 'u2029' 1159 | }; 1160 | 1161 | var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g; 1162 | 1163 | // JavaScript micro-templating, similar to John Resig's implementation. 1164 | // Underscore templating handles arbitrary delimiters, preserves whitespace, 1165 | // and correctly escapes quotes within interpolated code. 1166 | _.template = function(text, data, settings) { 1167 | var render; 1168 | settings = _.defaults({}, settings, _.templateSettings); 1169 | 1170 | // Combine delimiters into one regular expression via alternation. 1171 | var matcher = new RegExp([ 1172 | (settings.escape || noMatch).source, 1173 | (settings.interpolate || noMatch).source, 1174 | (settings.evaluate || noMatch).source 1175 | ].join('|') + '|$', 'g'); 1176 | 1177 | // Compile the template source, escaping string literals appropriately. 1178 | var index = 0; 1179 | var source = "__p+='"; 1180 | text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { 1181 | source += text.slice(index, offset) 1182 | .replace(escaper, function(match) { return '\\' + escapes[match]; }); 1183 | 1184 | if (escape) { 1185 | source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; 1186 | } 1187 | if (interpolate) { 1188 | source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; 1189 | } 1190 | if (evaluate) { 1191 | source += "';\n" + evaluate + "\n__p+='"; 1192 | } 1193 | index = offset + match.length; 1194 | return match; 1195 | }); 1196 | source += "';\n"; 1197 | 1198 | // If a variable is not specified, place data values in local scope. 1199 | if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; 1200 | 1201 | source = "var __t,__p='',__j=Array.prototype.join," + 1202 | "print=function(){__p+=__j.call(arguments,'');};\n" + 1203 | source + "return __p;\n"; 1204 | 1205 | try { 1206 | render = new Function(settings.variable || 'obj', '_', source); 1207 | } catch (e) { 1208 | e.source = source; 1209 | throw e; 1210 | } 1211 | 1212 | if (data) return render(data, _); 1213 | var template = function(data) { 1214 | return render.call(this, data, _); 1215 | }; 1216 | 1217 | // Provide the compiled function source as a convenience for precompilation. 1218 | template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}'; 1219 | 1220 | return template; 1221 | }; 1222 | 1223 | // Add a "chain" function, which will delegate to the wrapper. 1224 | _.chain = function(obj) { 1225 | return _(obj).chain(); 1226 | }; 1227 | 1228 | // OOP 1229 | // --------------- 1230 | // If Underscore is called as a function, it returns a wrapped object that 1231 | // can be used OO-style. This wrapper holds altered versions of all the 1232 | // underscore functions. Wrapped objects may be chained. 1233 | 1234 | // Helper function to continue chaining intermediate results. 1235 | var result = function(obj) { 1236 | return this._chain ? _(obj).chain() : obj; 1237 | }; 1238 | 1239 | // Add all of the Underscore functions to the wrapper object. 1240 | _.mixin(_); 1241 | 1242 | // Add all mutator Array functions to the wrapper. 1243 | each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { 1244 | var method = ArrayProto[name]; 1245 | _.prototype[name] = function() { 1246 | var obj = this._wrapped; 1247 | method.apply(obj, arguments); 1248 | if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0]; 1249 | return result.call(this, obj); 1250 | }; 1251 | }); 1252 | 1253 | // Add all accessor Array functions to the wrapper. 1254 | each(['concat', 'join', 'slice'], function(name) { 1255 | var method = ArrayProto[name]; 1256 | _.prototype[name] = function() { 1257 | return result.call(this, method.apply(this._wrapped, arguments)); 1258 | }; 1259 | }); 1260 | 1261 | _.extend(_.prototype, { 1262 | 1263 | // Start chaining a wrapped Underscore object. 1264 | chain: function() { 1265 | this._chain = true; 1266 | return this; 1267 | }, 1268 | 1269 | // Extracts the result from a wrapped and chained object. 1270 | value: function() { 1271 | return this._wrapped; 1272 | } 1273 | 1274 | }); 1275 | 1276 | }).call(this); 1277 | -------------------------------------------------------------------------------- /spec/vendor/backbone-1.0.0/backbone.js: -------------------------------------------------------------------------------- 1 | // Backbone.js 1.0.0 2 | 3 | // (c) 2010-2013 Jeremy Ashkenas, DocumentCloud Inc. 4 | // Backbone may be freely distributed under the MIT license. 5 | // For all details and documentation: 6 | // http://backbonejs.org 7 | 8 | (function(){ 9 | 10 | // Initial Setup 11 | // ------------- 12 | 13 | // Save a reference to the global object (`window` in the browser, `exports` 14 | // on the server). 15 | var root = this; 16 | 17 | // Save the previous value of the `Backbone` variable, so that it can be 18 | // restored later on, if `noConflict` is used. 19 | var previousBackbone = root.Backbone; 20 | 21 | // Create local references to array methods we'll want to use later. 22 | var array = []; 23 | var push = array.push; 24 | var slice = array.slice; 25 | var splice = array.splice; 26 | 27 | // The top-level namespace. All public Backbone classes and modules will 28 | // be attached to this. Exported for both the browser and the server. 29 | var Backbone; 30 | if (typeof exports !== 'undefined') { 31 | Backbone = exports; 32 | } else { 33 | Backbone = root.Backbone = {}; 34 | } 35 | 36 | // Current version of the library. Keep in sync with `package.json`. 37 | Backbone.VERSION = '1.0.0'; 38 | 39 | // Require Underscore, if we're on the server, and it's not already present. 40 | var _ = root._; 41 | if (!_ && (typeof require !== 'undefined')) _ = require('underscore'); 42 | 43 | // For Backbone's purposes, jQuery, Zepto, Ender, or My Library (kidding) owns 44 | // the `$` variable. 45 | Backbone.$ = root.jQuery || root.Zepto || root.ender || root.$; 46 | 47 | // Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable 48 | // to its previous owner. Returns a reference to this Backbone object. 49 | Backbone.noConflict = function() { 50 | root.Backbone = previousBackbone; 51 | return this; 52 | }; 53 | 54 | // Turn on `emulateHTTP` to support legacy HTTP servers. Setting this option 55 | // will fake `"PUT"` and `"DELETE"` requests via the `_method` parameter and 56 | // set a `X-Http-Method-Override` header. 57 | Backbone.emulateHTTP = false; 58 | 59 | // Turn on `emulateJSON` to support legacy servers that can't deal with direct 60 | // `application/json` requests ... will encode the body as 61 | // `application/x-www-form-urlencoded` instead and will send the model in a 62 | // form param named `model`. 63 | Backbone.emulateJSON = false; 64 | 65 | // Backbone.Events 66 | // --------------- 67 | 68 | // A module that can be mixed in to *any object* in order to provide it with 69 | // custom events. You may bind with `on` or remove with `off` callback 70 | // functions to an event; `trigger`-ing an event fires all callbacks in 71 | // succession. 72 | // 73 | // var object = {}; 74 | // _.extend(object, Backbone.Events); 75 | // object.on('expand', function(){ alert('expanded'); }); 76 | // object.trigger('expand'); 77 | // 78 | var Events = Backbone.Events = { 79 | 80 | // Bind an event to a `callback` function. Passing `"all"` will bind 81 | // the callback to all events fired. 82 | on: function(name, callback, context) { 83 | if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; 84 | this._events || (this._events = {}); 85 | var events = this._events[name] || (this._events[name] = []); 86 | events.push({callback: callback, context: context, ctx: context || this}); 87 | return this; 88 | }, 89 | 90 | // Bind an event to only be triggered a single time. After the first time 91 | // the callback is invoked, it will be removed. 92 | once: function(name, callback, context) { 93 | if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; 94 | var self = this; 95 | var once = _.once(function() { 96 | self.off(name, once); 97 | callback.apply(this, arguments); 98 | }); 99 | once._callback = callback; 100 | return this.on(name, once, context); 101 | }, 102 | 103 | // Remove one or many callbacks. If `context` is null, removes all 104 | // callbacks with that function. If `callback` is null, removes all 105 | // callbacks for the event. If `name` is null, removes all bound 106 | // callbacks for all events. 107 | off: function(name, callback, context) { 108 | var retain, ev, events, names, i, l, j, k; 109 | if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; 110 | if (!name && !callback && !context) { 111 | this._events = {}; 112 | return this; 113 | } 114 | 115 | names = name ? [name] : _.keys(this._events); 116 | for (i = 0, l = names.length; i < l; i++) { 117 | name = names[i]; 118 | if (events = this._events[name]) { 119 | this._events[name] = retain = []; 120 | if (callback || context) { 121 | for (j = 0, k = events.length; j < k; j++) { 122 | ev = events[j]; 123 | if ((callback && callback !== ev.callback && callback !== ev.callback._callback) || 124 | (context && context !== ev.context)) { 125 | retain.push(ev); 126 | } 127 | } 128 | } 129 | if (!retain.length) delete this._events[name]; 130 | } 131 | } 132 | 133 | return this; 134 | }, 135 | 136 | // Trigger one or many events, firing all bound callbacks. Callbacks are 137 | // passed the same arguments as `trigger` is, apart from the event name 138 | // (unless you're listening on `"all"`, which will cause your callback to 139 | // receive the true name of the event as the first argument). 140 | trigger: function(name) { 141 | if (!this._events) return this; 142 | var args = slice.call(arguments, 1); 143 | if (!eventsApi(this, 'trigger', name, args)) return this; 144 | var events = this._events[name]; 145 | var allEvents = this._events.all; 146 | if (events) triggerEvents(events, args); 147 | if (allEvents) triggerEvents(allEvents, arguments); 148 | return this; 149 | }, 150 | 151 | // Tell this object to stop listening to either specific events ... or 152 | // to every object it's currently listening to. 153 | stopListening: function(obj, name, callback) { 154 | var listeners = this._listeners; 155 | if (!listeners) return this; 156 | var deleteListener = !name && !callback; 157 | if (typeof name === 'object') callback = this; 158 | if (obj) (listeners = {})[obj._listenerId] = obj; 159 | for (var id in listeners) { 160 | listeners[id].off(name, callback, this); 161 | if (deleteListener) delete this._listeners[id]; 162 | } 163 | return this; 164 | } 165 | 166 | }; 167 | 168 | // Regular expression used to split event strings. 169 | var eventSplitter = /\s+/; 170 | 171 | // Implement fancy features of the Events API such as multiple event 172 | // names `"change blur"` and jQuery-style event maps `{change: action}` 173 | // in terms of the existing API. 174 | var eventsApi = function(obj, action, name, rest) { 175 | if (!name) return true; 176 | 177 | // Handle event maps. 178 | if (typeof name === 'object') { 179 | for (var key in name) { 180 | obj[action].apply(obj, [key, name[key]].concat(rest)); 181 | } 182 | return false; 183 | } 184 | 185 | // Handle space separated event names. 186 | if (eventSplitter.test(name)) { 187 | var names = name.split(eventSplitter); 188 | for (var i = 0, l = names.length; i < l; i++) { 189 | obj[action].apply(obj, [names[i]].concat(rest)); 190 | } 191 | return false; 192 | } 193 | 194 | return true; 195 | }; 196 | 197 | // A difficult-to-believe, but optimized internal dispatch function for 198 | // triggering events. Tries to keep the usual cases speedy (most internal 199 | // Backbone events have 3 arguments). 200 | var triggerEvents = function(events, args) { 201 | var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2]; 202 | switch (args.length) { 203 | case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return; 204 | case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return; 205 | case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return; 206 | case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return; 207 | default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); 208 | } 209 | }; 210 | 211 | var listenMethods = {listenTo: 'on', listenToOnce: 'once'}; 212 | 213 | // Inversion-of-control versions of `on` and `once`. Tell *this* object to 214 | // listen to an event in another object ... keeping track of what it's 215 | // listening to. 216 | _.each(listenMethods, function(implementation, method) { 217 | Events[method] = function(obj, name, callback) { 218 | var listeners = this._listeners || (this._listeners = {}); 219 | var id = obj._listenerId || (obj._listenerId = _.uniqueId('l')); 220 | listeners[id] = obj; 221 | if (typeof name === 'object') callback = this; 222 | obj[implementation](name, callback, this); 223 | return this; 224 | }; 225 | }); 226 | 227 | // Aliases for backwards compatibility. 228 | Events.bind = Events.on; 229 | Events.unbind = Events.off; 230 | 231 | // Allow the `Backbone` object to serve as a global event bus, for folks who 232 | // want global "pubsub" in a convenient place. 233 | _.extend(Backbone, Events); 234 | 235 | // Backbone.Model 236 | // -------------- 237 | 238 | // Backbone **Models** are the basic data object in the framework -- 239 | // frequently representing a row in a table in a database on your server. 240 | // A discrete chunk of data and a bunch of useful, related methods for 241 | // performing computations and transformations on that data. 242 | 243 | // Create a new model with the specified attributes. A client id (`cid`) 244 | // is automatically generated and assigned for you. 245 | var Model = Backbone.Model = function(attributes, options) { 246 | var defaults; 247 | var attrs = attributes || {}; 248 | options || (options = {}); 249 | this.cid = _.uniqueId('c'); 250 | this.attributes = {}; 251 | _.extend(this, _.pick(options, modelOptions)); 252 | if (options.parse) attrs = this.parse(attrs, options) || {}; 253 | if (defaults = _.result(this, 'defaults')) { 254 | attrs = _.defaults({}, attrs, defaults); 255 | } 256 | this.set(attrs, options); 257 | this.changed = {}; 258 | this.initialize.apply(this, arguments); 259 | }; 260 | 261 | // A list of options to be attached directly to the model, if provided. 262 | var modelOptions = ['url', 'urlRoot', 'collection']; 263 | 264 | // Attach all inheritable methods to the Model prototype. 265 | _.extend(Model.prototype, Events, { 266 | 267 | // A hash of attributes whose current and previous value differ. 268 | changed: null, 269 | 270 | // The value returned during the last failed validation. 271 | validationError: null, 272 | 273 | // The default name for the JSON `id` attribute is `"id"`. MongoDB and 274 | // CouchDB users may want to set this to `"_id"`. 275 | idAttribute: 'id', 276 | 277 | // Initialize is an empty function by default. Override it with your own 278 | // initialization logic. 279 | initialize: function(){}, 280 | 281 | // Return a copy of the model's `attributes` object. 282 | toJSON: function(options) { 283 | return _.clone(this.attributes); 284 | }, 285 | 286 | // Proxy `Backbone.sync` by default -- but override this if you need 287 | // custom syncing semantics for *this* particular model. 288 | sync: function() { 289 | return Backbone.sync.apply(this, arguments); 290 | }, 291 | 292 | // Get the value of an attribute. 293 | get: function(attr) { 294 | return this.attributes[attr]; 295 | }, 296 | 297 | // Get the HTML-escaped value of an attribute. 298 | escape: function(attr) { 299 | return _.escape(this.get(attr)); 300 | }, 301 | 302 | // Returns `true` if the attribute contains a value that is not null 303 | // or undefined. 304 | has: function(attr) { 305 | return this.get(attr) != null; 306 | }, 307 | 308 | // Set a hash of model attributes on the object, firing `"change"`. This is 309 | // the core primitive operation of a model, updating the data and notifying 310 | // anyone who needs to know about the change in state. The heart of the beast. 311 | set: function(key, val, options) { 312 | var attr, attrs, unset, changes, silent, changing, prev, current; 313 | if (key == null) return this; 314 | 315 | // Handle both `"key", value` and `{key: value}` -style arguments. 316 | if (typeof key === 'object') { 317 | attrs = key; 318 | options = val; 319 | } else { 320 | (attrs = {})[key] = val; 321 | } 322 | 323 | options || (options = {}); 324 | 325 | // Run validation. 326 | if (!this._validate(attrs, options)) return false; 327 | 328 | // Extract attributes and options. 329 | unset = options.unset; 330 | silent = options.silent; 331 | changes = []; 332 | changing = this._changing; 333 | this._changing = true; 334 | 335 | if (!changing) { 336 | this._previousAttributes = _.clone(this.attributes); 337 | this.changed = {}; 338 | } 339 | current = this.attributes, prev = this._previousAttributes; 340 | 341 | // Check for changes of `id`. 342 | if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; 343 | 344 | // For each `set` attribute, update or delete the current value. 345 | for (attr in attrs) { 346 | val = attrs[attr]; 347 | if (!_.isEqual(current[attr], val)) changes.push(attr); 348 | if (!_.isEqual(prev[attr], val)) { 349 | this.changed[attr] = val; 350 | } else { 351 | delete this.changed[attr]; 352 | } 353 | unset ? delete current[attr] : current[attr] = val; 354 | } 355 | 356 | // Trigger all relevant attribute changes. 357 | if (!silent) { 358 | if (changes.length) this._pending = true; 359 | for (var i = 0, l = changes.length; i < l; i++) { 360 | this.trigger('change:' + changes[i], this, current[changes[i]], options); 361 | } 362 | } 363 | 364 | // You might be wondering why there's a `while` loop here. Changes can 365 | // be recursively nested within `"change"` events. 366 | if (changing) return this; 367 | if (!silent) { 368 | while (this._pending) { 369 | this._pending = false; 370 | this.trigger('change', this, options); 371 | } 372 | } 373 | this._pending = false; 374 | this._changing = false; 375 | return this; 376 | }, 377 | 378 | // Remove an attribute from the model, firing `"change"`. `unset` is a noop 379 | // if the attribute doesn't exist. 380 | unset: function(attr, options) { 381 | return this.set(attr, void 0, _.extend({}, options, {unset: true})); 382 | }, 383 | 384 | // Clear all attributes on the model, firing `"change"`. 385 | clear: function(options) { 386 | var attrs = {}; 387 | for (var key in this.attributes) attrs[key] = void 0; 388 | return this.set(attrs, _.extend({}, options, {unset: true})); 389 | }, 390 | 391 | // Determine if the model has changed since the last `"change"` event. 392 | // If you specify an attribute name, determine if that attribute has changed. 393 | hasChanged: function(attr) { 394 | if (attr == null) return !_.isEmpty(this.changed); 395 | return _.has(this.changed, attr); 396 | }, 397 | 398 | // Return an object containing all the attributes that have changed, or 399 | // false if there are no changed attributes. Useful for determining what 400 | // parts of a view need to be updated and/or what attributes need to be 401 | // persisted to the server. Unset attributes will be set to undefined. 402 | // You can also pass an attributes object to diff against the model, 403 | // determining if there *would be* a change. 404 | changedAttributes: function(diff) { 405 | if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; 406 | var val, changed = false; 407 | var old = this._changing ? this._previousAttributes : this.attributes; 408 | for (var attr in diff) { 409 | if (_.isEqual(old[attr], (val = diff[attr]))) continue; 410 | (changed || (changed = {}))[attr] = val; 411 | } 412 | return changed; 413 | }, 414 | 415 | // Get the previous value of an attribute, recorded at the time the last 416 | // `"change"` event was fired. 417 | previous: function(attr) { 418 | if (attr == null || !this._previousAttributes) return null; 419 | return this._previousAttributes[attr]; 420 | }, 421 | 422 | // Get all of the attributes of the model at the time of the previous 423 | // `"change"` event. 424 | previousAttributes: function() { 425 | return _.clone(this._previousAttributes); 426 | }, 427 | 428 | // Fetch the model from the server. If the server's representation of the 429 | // model differs from its current attributes, they will be overridden, 430 | // triggering a `"change"` event. 431 | fetch: function(options) { 432 | options = options ? _.clone(options) : {}; 433 | if (options.parse === void 0) options.parse = true; 434 | var model = this; 435 | var success = options.success; 436 | options.success = function(resp) { 437 | if (!model.set(model.parse(resp, options), options)) return false; 438 | if (success) success(model, resp, options); 439 | model.trigger('sync', model, resp, options); 440 | }; 441 | wrapError(this, options); 442 | return this.sync('read', this, options); 443 | }, 444 | 445 | // Set a hash of model attributes, and sync the model to the server. 446 | // If the server returns an attributes hash that differs, the model's 447 | // state will be `set` again. 448 | save: function(key, val, options) { 449 | var attrs, method, xhr, attributes = this.attributes; 450 | 451 | // Handle both `"key", value` and `{key: value}` -style arguments. 452 | if (key == null || typeof key === 'object') { 453 | attrs = key; 454 | options = val; 455 | } else { 456 | (attrs = {})[key] = val; 457 | } 458 | 459 | // If we're not waiting and attributes exist, save acts as `set(attr).save(null, opts)`. 460 | if (attrs && (!options || !options.wait) && !this.set(attrs, options)) return false; 461 | 462 | options = _.extend({validate: true}, options); 463 | 464 | // Do not persist invalid models. 465 | if (!this._validate(attrs, options)) return false; 466 | 467 | // Set temporary attributes if `{wait: true}`. 468 | if (attrs && options.wait) { 469 | this.attributes = _.extend({}, attributes, attrs); 470 | } 471 | 472 | // After a successful server-side save, the client is (optionally) 473 | // updated with the server-side state. 474 | if (options.parse === void 0) options.parse = true; 475 | var model = this; 476 | var success = options.success; 477 | options.success = function(resp) { 478 | // Ensure attributes are restored during synchronous saves. 479 | model.attributes = attributes; 480 | var serverAttrs = model.parse(resp, options); 481 | if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); 482 | if (_.isObject(serverAttrs) && !model.set(serverAttrs, options)) { 483 | return false; 484 | } 485 | if (success) success(model, resp, options); 486 | model.trigger('sync', model, resp, options); 487 | }; 488 | wrapError(this, options); 489 | 490 | method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update'); 491 | if (method === 'patch') options.attrs = attrs; 492 | xhr = this.sync(method, this, options); 493 | 494 | // Restore attributes. 495 | if (attrs && options.wait) this.attributes = attributes; 496 | 497 | return xhr; 498 | }, 499 | 500 | // Destroy this model on the server if it was already persisted. 501 | // Optimistically removes the model from its collection, if it has one. 502 | // If `wait: true` is passed, waits for the server to respond before removal. 503 | destroy: function(options) { 504 | options = options ? _.clone(options) : {}; 505 | var model = this; 506 | var success = options.success; 507 | 508 | var destroy = function() { 509 | model.trigger('destroy', model, model.collection, options); 510 | }; 511 | 512 | options.success = function(resp) { 513 | if (options.wait || model.isNew()) destroy(); 514 | if (success) success(model, resp, options); 515 | if (!model.isNew()) model.trigger('sync', model, resp, options); 516 | }; 517 | 518 | if (this.isNew()) { 519 | options.success(); 520 | return false; 521 | } 522 | wrapError(this, options); 523 | 524 | var xhr = this.sync('delete', this, options); 525 | if (!options.wait) destroy(); 526 | return xhr; 527 | }, 528 | 529 | // Default URL for the model's representation on the server -- if you're 530 | // using Backbone's restful methods, override this to change the endpoint 531 | // that will be called. 532 | url: function() { 533 | var base = _.result(this, 'urlRoot') || _.result(this.collection, 'url') || urlError(); 534 | if (this.isNew()) return base; 535 | return base + (base.charAt(base.length - 1) === '/' ? '' : '/') + encodeURIComponent(this.id); 536 | }, 537 | 538 | // **parse** converts a response into the hash of attributes to be `set` on 539 | // the model. The default implementation is just to pass the response along. 540 | parse: function(resp, options) { 541 | return resp; 542 | }, 543 | 544 | // Create a new model with identical attributes to this one. 545 | clone: function() { 546 | return new this.constructor(this.attributes); 547 | }, 548 | 549 | // A model is new if it has never been saved to the server, and lacks an id. 550 | isNew: function() { 551 | return this.id == null; 552 | }, 553 | 554 | // Check if the model is currently in a valid state. 555 | isValid: function(options) { 556 | return this._validate({}, _.extend(options || {}, { validate: true })); 557 | }, 558 | 559 | // Run validation against the next complete set of model attributes, 560 | // returning `true` if all is well. Otherwise, fire an `"invalid"` event. 561 | _validate: function(attrs, options) { 562 | if (!options.validate || !this.validate) return true; 563 | attrs = _.extend({}, this.attributes, attrs); 564 | var error = this.validationError = this.validate(attrs, options) || null; 565 | if (!error) return true; 566 | this.trigger('invalid', this, error, _.extend(options || {}, {validationError: error})); 567 | return false; 568 | } 569 | 570 | }); 571 | 572 | // Underscore methods that we want to implement on the Model. 573 | var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit']; 574 | 575 | // Mix in each Underscore method as a proxy to `Model#attributes`. 576 | _.each(modelMethods, function(method) { 577 | Model.prototype[method] = function() { 578 | var args = slice.call(arguments); 579 | args.unshift(this.attributes); 580 | return _[method].apply(_, args); 581 | }; 582 | }); 583 | 584 | // Backbone.Collection 585 | // ------------------- 586 | 587 | // If models tend to represent a single row of data, a Backbone Collection is 588 | // more analagous to a table full of data ... or a small slice or page of that 589 | // table, or a collection of rows that belong together for a particular reason 590 | // -- all of the messages in this particular folder, all of the documents 591 | // belonging to this particular author, and so on. Collections maintain 592 | // indexes of their models, both in order, and for lookup by `id`. 593 | 594 | // Create a new **Collection**, perhaps to contain a specific type of `model`. 595 | // If a `comparator` is specified, the Collection will maintain 596 | // its models in sort order, as they're added and removed. 597 | var Collection = Backbone.Collection = function(models, options) { 598 | options || (options = {}); 599 | if (options.url) this.url = options.url; 600 | if (options.model) this.model = options.model; 601 | if (options.comparator !== void 0) this.comparator = options.comparator; 602 | this._reset(); 603 | this.initialize.apply(this, arguments); 604 | if (models) this.reset(models, _.extend({silent: true}, options)); 605 | }; 606 | 607 | // Default options for `Collection#set`. 608 | var setOptions = {add: true, remove: true, merge: true}; 609 | var addOptions = {add: true, merge: false, remove: false}; 610 | 611 | // Define the Collection's inheritable methods. 612 | _.extend(Collection.prototype, Events, { 613 | 614 | // The default model for a collection is just a **Backbone.Model**. 615 | // This should be overridden in most cases. 616 | model: Model, 617 | 618 | // Initialize is an empty function by default. Override it with your own 619 | // initialization logic. 620 | initialize: function(){}, 621 | 622 | // The JSON representation of a Collection is an array of the 623 | // models' attributes. 624 | toJSON: function(options) { 625 | return this.map(function(model){ return model.toJSON(options); }); 626 | }, 627 | 628 | // Proxy `Backbone.sync` by default. 629 | sync: function() { 630 | return Backbone.sync.apply(this, arguments); 631 | }, 632 | 633 | // Add a model, or list of models to the set. 634 | add: function(models, options) { 635 | return this.set(models, _.defaults(options || {}, addOptions)); 636 | }, 637 | 638 | // Remove a model, or a list of models from the set. 639 | remove: function(models, options) { 640 | models = _.isArray(models) ? models.slice() : [models]; 641 | options || (options = {}); 642 | var i, l, index, model; 643 | for (i = 0, l = models.length; i < l; i++) { 644 | model = this.get(models[i]); 645 | if (!model) continue; 646 | delete this._byId[model.id]; 647 | delete this._byId[model.cid]; 648 | index = this.indexOf(model); 649 | this.models.splice(index, 1); 650 | this.length--; 651 | if (!options.silent) { 652 | options.index = index; 653 | model.trigger('remove', model, this, options); 654 | } 655 | this._removeReference(model); 656 | } 657 | return this; 658 | }, 659 | 660 | // Update a collection by `set`-ing a new list of models, adding new ones, 661 | // removing models that are no longer present, and merging models that 662 | // already exist in the collection, as necessary. Similar to **Model#set**, 663 | // the core operation for updating the data contained by the collection. 664 | set: function(models, options) { 665 | options = _.defaults(options || {}, setOptions); 666 | if (options.parse) models = this.parse(models, options); 667 | if (!_.isArray(models)) models = models ? [models] : []; 668 | var i, l, model, attrs, existing, sort; 669 | var at = options.at; 670 | var sortable = this.comparator && (at == null) && options.sort !== false; 671 | var sortAttr = _.isString(this.comparator) ? this.comparator : null; 672 | var toAdd = [], toRemove = [], modelMap = {}; 673 | 674 | // Turn bare objects into model references, and prevent invalid models 675 | // from being added. 676 | for (i = 0, l = models.length; i < l; i++) { 677 | if (!(model = this._prepareModel(models[i], options))) continue; 678 | 679 | // If a duplicate is found, prevent it from being added and 680 | // optionally merge it into the existing model. 681 | if (existing = this.get(model)) { 682 | if (options.remove) modelMap[existing.cid] = true; 683 | if (options.merge) { 684 | existing.set(model.attributes, options); 685 | if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true; 686 | } 687 | 688 | // This is a new model, push it to the `toAdd` list. 689 | } else if (options.add) { 690 | toAdd.push(model); 691 | 692 | // Listen to added models' events, and index models for lookup by 693 | // `id` and by `cid`. 694 | model.on('all', this._onModelEvent, this); 695 | this._byId[model.cid] = model; 696 | if (model.id != null) this._byId[model.id] = model; 697 | } 698 | } 699 | 700 | // Remove nonexistent models if appropriate. 701 | if (options.remove) { 702 | for (i = 0, l = this.length; i < l; ++i) { 703 | if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model); 704 | } 705 | if (toRemove.length) this.remove(toRemove, options); 706 | } 707 | 708 | // See if sorting is needed, update `length` and splice in new models. 709 | if (toAdd.length) { 710 | if (sortable) sort = true; 711 | this.length += toAdd.length; 712 | if (at != null) { 713 | splice.apply(this.models, [at, 0].concat(toAdd)); 714 | } else { 715 | push.apply(this.models, toAdd); 716 | } 717 | } 718 | 719 | // Silently sort the collection if appropriate. 720 | if (sort) this.sort({silent: true}); 721 | 722 | if (options.silent) return this; 723 | 724 | // Trigger `add` events. 725 | for (i = 0, l = toAdd.length; i < l; i++) { 726 | (model = toAdd[i]).trigger('add', model, this, options); 727 | } 728 | 729 | // Trigger `sort` if the collection was sorted. 730 | if (sort) this.trigger('sort', this, options); 731 | return this; 732 | }, 733 | 734 | // When you have more items than you want to add or remove individually, 735 | // you can reset the entire set with a new list of models, without firing 736 | // any granular `add` or `remove` events. Fires `reset` when finished. 737 | // Useful for bulk operations and optimizations. 738 | reset: function(models, options) { 739 | options || (options = {}); 740 | for (var i = 0, l = this.models.length; i < l; i++) { 741 | this._removeReference(this.models[i]); 742 | } 743 | options.previousModels = this.models; 744 | this._reset(); 745 | this.add(models, _.extend({silent: true}, options)); 746 | if (!options.silent) this.trigger('reset', this, options); 747 | return this; 748 | }, 749 | 750 | // Add a model to the end of the collection. 751 | push: function(model, options) { 752 | model = this._prepareModel(model, options); 753 | this.add(model, _.extend({at: this.length}, options)); 754 | return model; 755 | }, 756 | 757 | // Remove a model from the end of the collection. 758 | pop: function(options) { 759 | var model = this.at(this.length - 1); 760 | this.remove(model, options); 761 | return model; 762 | }, 763 | 764 | // Add a model to the beginning of the collection. 765 | unshift: function(model, options) { 766 | model = this._prepareModel(model, options); 767 | this.add(model, _.extend({at: 0}, options)); 768 | return model; 769 | }, 770 | 771 | // Remove a model from the beginning of the collection. 772 | shift: function(options) { 773 | var model = this.at(0); 774 | this.remove(model, options); 775 | return model; 776 | }, 777 | 778 | // Slice out a sub-array of models from the collection. 779 | slice: function(begin, end) { 780 | return this.models.slice(begin, end); 781 | }, 782 | 783 | // Get a model from the set by id. 784 | get: function(obj) { 785 | if (obj == null) return void 0; 786 | return this._byId[obj.id != null ? obj.id : obj.cid || obj]; 787 | }, 788 | 789 | // Get the model at the given index. 790 | at: function(index) { 791 | return this.models[index]; 792 | }, 793 | 794 | // Return models with matching attributes. Useful for simple cases of 795 | // `filter`. 796 | where: function(attrs, first) { 797 | if (_.isEmpty(attrs)) return first ? void 0 : []; 798 | return this[first ? 'find' : 'filter'](function(model) { 799 | for (var key in attrs) { 800 | if (attrs[key] !== model.get(key)) return false; 801 | } 802 | return true; 803 | }); 804 | }, 805 | 806 | // Return the first model with matching attributes. Useful for simple cases 807 | // of `find`. 808 | findWhere: function(attrs) { 809 | return this.where(attrs, true); 810 | }, 811 | 812 | // Force the collection to re-sort itself. You don't need to call this under 813 | // normal circumstances, as the set will maintain sort order as each item 814 | // is added. 815 | sort: function(options) { 816 | if (!this.comparator) throw new Error('Cannot sort a set without a comparator'); 817 | options || (options = {}); 818 | 819 | // Run sort based on type of `comparator`. 820 | if (_.isString(this.comparator) || this.comparator.length === 1) { 821 | this.models = this.sortBy(this.comparator, this); 822 | } else { 823 | this.models.sort(_.bind(this.comparator, this)); 824 | } 825 | 826 | if (!options.silent) this.trigger('sort', this, options); 827 | return this; 828 | }, 829 | 830 | // Figure out the smallest index at which a model should be inserted so as 831 | // to maintain order. 832 | sortedIndex: function(model, value, context) { 833 | value || (value = this.comparator); 834 | var iterator = _.isFunction(value) ? value : function(model) { 835 | return model.get(value); 836 | }; 837 | return _.sortedIndex(this.models, model, iterator, context); 838 | }, 839 | 840 | // Pluck an attribute from each model in the collection. 841 | pluck: function(attr) { 842 | return _.invoke(this.models, 'get', attr); 843 | }, 844 | 845 | // Fetch the default set of models for this collection, resetting the 846 | // collection when they arrive. If `reset: true` is passed, the response 847 | // data will be passed through the `reset` method instead of `set`. 848 | fetch: function(options) { 849 | options = options ? _.clone(options) : {}; 850 | if (options.parse === void 0) options.parse = true; 851 | var success = options.success; 852 | var collection = this; 853 | options.success = function(resp) { 854 | var method = options.reset ? 'reset' : 'set'; 855 | collection[method](resp, options); 856 | if (success) success(collection, resp, options); 857 | collection.trigger('sync', collection, resp, options); 858 | }; 859 | wrapError(this, options); 860 | return this.sync('read', this, options); 861 | }, 862 | 863 | // Create a new instance of a model in this collection. Add the model to the 864 | // collection immediately, unless `wait: true` is passed, in which case we 865 | // wait for the server to agree. 866 | create: function(model, options) { 867 | options = options ? _.clone(options) : {}; 868 | if (!(model = this._prepareModel(model, options))) return false; 869 | if (!options.wait) this.add(model, options); 870 | var collection = this; 871 | var success = options.success; 872 | options.success = function(resp) { 873 | if (options.wait) collection.add(model, options); 874 | if (success) success(model, resp, options); 875 | }; 876 | model.save(null, options); 877 | return model; 878 | }, 879 | 880 | // **parse** converts a response into a list of models to be added to the 881 | // collection. The default implementation is just to pass it through. 882 | parse: function(resp, options) { 883 | return resp; 884 | }, 885 | 886 | // Create a new collection with an identical list of models as this one. 887 | clone: function() { 888 | return new this.constructor(this.models); 889 | }, 890 | 891 | // Private method to reset all internal state. Called when the collection 892 | // is first initialized or reset. 893 | _reset: function() { 894 | this.length = 0; 895 | this.models = []; 896 | this._byId = {}; 897 | }, 898 | 899 | // Prepare a hash of attributes (or other model) to be added to this 900 | // collection. 901 | _prepareModel: function(attrs, options) { 902 | if (attrs instanceof Model) { 903 | if (!attrs.collection) attrs.collection = this; 904 | return attrs; 905 | } 906 | options || (options = {}); 907 | options.collection = this; 908 | var model = new this.model(attrs, options); 909 | if (!model._validate(attrs, options)) { 910 | this.trigger('invalid', this, attrs, options); 911 | return false; 912 | } 913 | return model; 914 | }, 915 | 916 | // Internal method to sever a model's ties to a collection. 917 | _removeReference: function(model) { 918 | if (this === model.collection) delete model.collection; 919 | model.off('all', this._onModelEvent, this); 920 | }, 921 | 922 | // Internal method called every time a model in the set fires an event. 923 | // Sets need to update their indexes when models change ids. All other 924 | // events simply proxy through. "add" and "remove" events that originate 925 | // in other collections are ignored. 926 | _onModelEvent: function(event, model, collection, options) { 927 | if ((event === 'add' || event === 'remove') && collection !== this) return; 928 | if (event === 'destroy') this.remove(model, options); 929 | if (model && event === 'change:' + model.idAttribute) { 930 | delete this._byId[model.previous(model.idAttribute)]; 931 | if (model.id != null) this._byId[model.id] = model; 932 | } 933 | this.trigger.apply(this, arguments); 934 | } 935 | 936 | }); 937 | 938 | // Underscore methods that we want to implement on the Collection. 939 | // 90% of the core usefulness of Backbone Collections is actually implemented 940 | // right here: 941 | var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl', 942 | 'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select', 943 | 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 944 | 'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest', 945 | 'tail', 'drop', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 946 | 'isEmpty', 'chain']; 947 | 948 | // Mix in each Underscore method as a proxy to `Collection#models`. 949 | _.each(methods, function(method) { 950 | Collection.prototype[method] = function() { 951 | var args = slice.call(arguments); 952 | args.unshift(this.models); 953 | return _[method].apply(_, args); 954 | }; 955 | }); 956 | 957 | // Underscore methods that take a property name as an argument. 958 | var attributeMethods = ['groupBy', 'countBy', 'sortBy']; 959 | 960 | // Use attributes instead of properties. 961 | _.each(attributeMethods, function(method) { 962 | Collection.prototype[method] = function(value, context) { 963 | var iterator = _.isFunction(value) ? value : function(model) { 964 | return model.get(value); 965 | }; 966 | return _[method](this.models, iterator, context); 967 | }; 968 | }); 969 | 970 | // Backbone.View 971 | // ------------- 972 | 973 | // Backbone Views are almost more convention than they are actual code. A View 974 | // is simply a JavaScript object that represents a logical chunk of UI in the 975 | // DOM. This might be a single item, an entire list, a sidebar or panel, or 976 | // even the surrounding frame which wraps your whole app. Defining a chunk of 977 | // UI as a **View** allows you to define your DOM events declaratively, without 978 | // having to worry about render order ... and makes it easy for the view to 979 | // react to specific changes in the state of your models. 980 | 981 | // Creating a Backbone.View creates its initial element outside of the DOM, 982 | // if an existing element is not provided... 983 | var View = Backbone.View = function(options) { 984 | this.cid = _.uniqueId('view'); 985 | this._configure(options || {}); 986 | this._ensureElement(); 987 | this.initialize.apply(this, arguments); 988 | this.delegateEvents(); 989 | }; 990 | 991 | // Cached regex to split keys for `delegate`. 992 | var delegateEventSplitter = /^(\S+)\s*(.*)$/; 993 | 994 | // List of view options to be merged as properties. 995 | var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events']; 996 | 997 | // Set up all inheritable **Backbone.View** properties and methods. 998 | _.extend(View.prototype, Events, { 999 | 1000 | // The default `tagName` of a View's element is `"div"`. 1001 | tagName: 'div', 1002 | 1003 | // jQuery delegate for element lookup, scoped to DOM elements within the 1004 | // current view. This should be prefered to global lookups where possible. 1005 | $: function(selector) { 1006 | return this.$el.find(selector); 1007 | }, 1008 | 1009 | // Initialize is an empty function by default. Override it with your own 1010 | // initialization logic. 1011 | initialize: function(){}, 1012 | 1013 | // **render** is the core function that your view should override, in order 1014 | // to populate its element (`this.el`), with the appropriate HTML. The 1015 | // convention is for **render** to always return `this`. 1016 | render: function() { 1017 | return this; 1018 | }, 1019 | 1020 | // Remove this view by taking the element out of the DOM, and removing any 1021 | // applicable Backbone.Events listeners. 1022 | remove: function() { 1023 | this.$el.remove(); 1024 | this.stopListening(); 1025 | return this; 1026 | }, 1027 | 1028 | // Change the view's element (`this.el` property), including event 1029 | // re-delegation. 1030 | setElement: function(element, delegate) { 1031 | if (this.$el) this.undelegateEvents(); 1032 | this.$el = element instanceof Backbone.$ ? element : Backbone.$(element); 1033 | this.el = this.$el[0]; 1034 | if (delegate !== false) this.delegateEvents(); 1035 | return this; 1036 | }, 1037 | 1038 | // Set callbacks, where `this.events` is a hash of 1039 | // 1040 | // *{"event selector": "callback"}* 1041 | // 1042 | // { 1043 | // 'mousedown .title': 'edit', 1044 | // 'click .button': 'save' 1045 | // 'click .open': function(e) { ... } 1046 | // } 1047 | // 1048 | // pairs. Callbacks will be bound to the view, with `this` set properly. 1049 | // Uses event delegation for efficiency. 1050 | // Omitting the selector binds the event to `this.el`. 1051 | // This only works for delegate-able events: not `focus`, `blur`, and 1052 | // not `change`, `submit`, and `reset` in Internet Explorer. 1053 | delegateEvents: function(events) { 1054 | if (!(events || (events = _.result(this, 'events')))) return this; 1055 | this.undelegateEvents(); 1056 | for (var key in events) { 1057 | var method = events[key]; 1058 | if (!_.isFunction(method)) method = this[events[key]]; 1059 | if (!method) continue; 1060 | 1061 | var match = key.match(delegateEventSplitter); 1062 | var eventName = match[1], selector = match[2]; 1063 | method = _.bind(method, this); 1064 | eventName += '.delegateEvents' + this.cid; 1065 | if (selector === '') { 1066 | this.$el.on(eventName, method); 1067 | } else { 1068 | this.$el.on(eventName, selector, method); 1069 | } 1070 | } 1071 | return this; 1072 | }, 1073 | 1074 | // Clears all callbacks previously bound to the view with `delegateEvents`. 1075 | // You usually don't need to use this, but may wish to if you have multiple 1076 | // Backbone views attached to the same DOM element. 1077 | undelegateEvents: function() { 1078 | this.$el.off('.delegateEvents' + this.cid); 1079 | return this; 1080 | }, 1081 | 1082 | // Performs the initial configuration of a View with a set of options. 1083 | // Keys with special meaning *(e.g. model, collection, id, className)* are 1084 | // attached directly to the view. See `viewOptions` for an exhaustive 1085 | // list. 1086 | _configure: function(options) { 1087 | if (this.options) options = _.extend({}, _.result(this, 'options'), options); 1088 | _.extend(this, _.pick(options, viewOptions)); 1089 | this.options = options; 1090 | }, 1091 | 1092 | // Ensure that the View has a DOM element to render into. 1093 | // If `this.el` is a string, pass it through `$()`, take the first 1094 | // matching element, and re-assign it to `el`. Otherwise, create 1095 | // an element from the `id`, `className` and `tagName` properties. 1096 | _ensureElement: function() { 1097 | if (!this.el) { 1098 | var attrs = _.extend({}, _.result(this, 'attributes')); 1099 | if (this.id) attrs.id = _.result(this, 'id'); 1100 | if (this.className) attrs['class'] = _.result(this, 'className'); 1101 | var $el = Backbone.$('<' + _.result(this, 'tagName') + '>').attr(attrs); 1102 | this.setElement($el, false); 1103 | } else { 1104 | this.setElement(_.result(this, 'el'), false); 1105 | } 1106 | } 1107 | 1108 | }); 1109 | 1110 | // Backbone.sync 1111 | // ------------- 1112 | 1113 | // Override this function to change the manner in which Backbone persists 1114 | // models to the server. You will be passed the type of request, and the 1115 | // model in question. By default, makes a RESTful Ajax request 1116 | // to the model's `url()`. Some possible customizations could be: 1117 | // 1118 | // * Use `setTimeout` to batch rapid-fire updates into a single request. 1119 | // * Send up the models as XML instead of JSON. 1120 | // * Persist models via WebSockets instead of Ajax. 1121 | // 1122 | // Turn on `Backbone.emulateHTTP` in order to send `PUT` and `DELETE` requests 1123 | // as `POST`, with a `_method` parameter containing the true HTTP method, 1124 | // as well as all requests with the body as `application/x-www-form-urlencoded` 1125 | // instead of `application/json` with the model in a param named `model`. 1126 | // Useful when interfacing with server-side languages like **PHP** that make 1127 | // it difficult to read the body of `PUT` requests. 1128 | Backbone.sync = function(method, model, options) { 1129 | var type = methodMap[method]; 1130 | 1131 | // Default options, unless specified. 1132 | _.defaults(options || (options = {}), { 1133 | emulateHTTP: Backbone.emulateHTTP, 1134 | emulateJSON: Backbone.emulateJSON 1135 | }); 1136 | 1137 | // Default JSON-request options. 1138 | var params = {type: type, dataType: 'json'}; 1139 | 1140 | // Ensure that we have a URL. 1141 | if (!options.url) { 1142 | params.url = _.result(model, 'url') || urlError(); 1143 | } 1144 | 1145 | // Ensure that we have the appropriate request data. 1146 | if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) { 1147 | params.contentType = 'application/json'; 1148 | params.data = JSON.stringify(options.attrs || model.toJSON(options)); 1149 | } 1150 | 1151 | // For older servers, emulate JSON by encoding the request into an HTML-form. 1152 | if (options.emulateJSON) { 1153 | params.contentType = 'application/x-www-form-urlencoded'; 1154 | params.data = params.data ? {model: params.data} : {}; 1155 | } 1156 | 1157 | // For older servers, emulate HTTP by mimicking the HTTP method with `_method` 1158 | // And an `X-HTTP-Method-Override` header. 1159 | if (options.emulateHTTP && (type === 'PUT' || type === 'DELETE' || type === 'PATCH')) { 1160 | params.type = 'POST'; 1161 | if (options.emulateJSON) params.data._method = type; 1162 | var beforeSend = options.beforeSend; 1163 | options.beforeSend = function(xhr) { 1164 | xhr.setRequestHeader('X-HTTP-Method-Override', type); 1165 | if (beforeSend) return beforeSend.apply(this, arguments); 1166 | }; 1167 | } 1168 | 1169 | // Don't process data on a non-GET request. 1170 | if (params.type !== 'GET' && !options.emulateJSON) { 1171 | params.processData = false; 1172 | } 1173 | 1174 | // If we're sending a `PATCH` request, and we're in an old Internet Explorer 1175 | // that still has ActiveX enabled by default, override jQuery to use that 1176 | // for XHR instead. Remove this line when jQuery supports `PATCH` on IE8. 1177 | if (params.type === 'PATCH' && window.ActiveXObject && 1178 | !(window.external && window.external.msActiveXFilteringEnabled)) { 1179 | params.xhr = function() { 1180 | return new ActiveXObject("Microsoft.XMLHTTP"); 1181 | }; 1182 | } 1183 | 1184 | // Make the request, allowing the user to override any Ajax options. 1185 | var xhr = options.xhr = Backbone.ajax(_.extend(params, options)); 1186 | model.trigger('request', model, xhr, options); 1187 | return xhr; 1188 | }; 1189 | 1190 | // Map from CRUD to HTTP for our default `Backbone.sync` implementation. 1191 | var methodMap = { 1192 | 'create': 'POST', 1193 | 'update': 'PUT', 1194 | 'patch': 'PATCH', 1195 | 'delete': 'DELETE', 1196 | 'read': 'GET' 1197 | }; 1198 | 1199 | // Set the default implementation of `Backbone.ajax` to proxy through to `$`. 1200 | // Override this if you'd like to use a different library. 1201 | Backbone.ajax = function() { 1202 | return Backbone.$.ajax.apply(Backbone.$, arguments); 1203 | }; 1204 | 1205 | // Backbone.Router 1206 | // --------------- 1207 | 1208 | // Routers map faux-URLs to actions, and fire events when routes are 1209 | // matched. Creating a new one sets its `routes` hash, if not set statically. 1210 | var Router = Backbone.Router = function(options) { 1211 | options || (options = {}); 1212 | if (options.routes) this.routes = options.routes; 1213 | this._bindRoutes(); 1214 | this.initialize.apply(this, arguments); 1215 | }; 1216 | 1217 | // Cached regular expressions for matching named param parts and splatted 1218 | // parts of route strings. 1219 | var optionalParam = /\((.*?)\)/g; 1220 | var namedParam = /(\(\?)?:\w+/g; 1221 | var splatParam = /\*\w+/g; 1222 | var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g; 1223 | 1224 | // Set up all inheritable **Backbone.Router** properties and methods. 1225 | _.extend(Router.prototype, Events, { 1226 | 1227 | // Initialize is an empty function by default. Override it with your own 1228 | // initialization logic. 1229 | initialize: function(){}, 1230 | 1231 | // Manually bind a single named route to a callback. For example: 1232 | // 1233 | // this.route('search/:query/p:num', 'search', function(query, num) { 1234 | // ... 1235 | // }); 1236 | // 1237 | route: function(route, name, callback) { 1238 | if (!_.isRegExp(route)) route = this._routeToRegExp(route); 1239 | if (_.isFunction(name)) { 1240 | callback = name; 1241 | name = ''; 1242 | } 1243 | if (!callback) callback = this[name]; 1244 | var router = this; 1245 | Backbone.history.route(route, function(fragment) { 1246 | var args = router._extractParameters(route, fragment); 1247 | callback && callback.apply(router, args); 1248 | router.trigger.apply(router, ['route:' + name].concat(args)); 1249 | router.trigger('route', name, args); 1250 | Backbone.history.trigger('route', router, name, args); 1251 | }); 1252 | return this; 1253 | }, 1254 | 1255 | // Simple proxy to `Backbone.history` to save a fragment into the history. 1256 | navigate: function(fragment, options) { 1257 | Backbone.history.navigate(fragment, options); 1258 | return this; 1259 | }, 1260 | 1261 | // Bind all defined routes to `Backbone.history`. We have to reverse the 1262 | // order of the routes here to support behavior where the most general 1263 | // routes can be defined at the bottom of the route map. 1264 | _bindRoutes: function() { 1265 | if (!this.routes) return; 1266 | this.routes = _.result(this, 'routes'); 1267 | var route, routes = _.keys(this.routes); 1268 | while ((route = routes.pop()) != null) { 1269 | this.route(route, this.routes[route]); 1270 | } 1271 | }, 1272 | 1273 | // Convert a route string into a regular expression, suitable for matching 1274 | // against the current location hash. 1275 | _routeToRegExp: function(route) { 1276 | route = route.replace(escapeRegExp, '\\$&') 1277 | .replace(optionalParam, '(?:$1)?') 1278 | .replace(namedParam, function(match, optional){ 1279 | return optional ? match : '([^\/]+)'; 1280 | }) 1281 | .replace(splatParam, '(.*?)'); 1282 | return new RegExp('^' + route + '$'); 1283 | }, 1284 | 1285 | // Given a route, and a URL fragment that it matches, return the array of 1286 | // extracted decoded parameters. Empty or unmatched parameters will be 1287 | // treated as `null` to normalize cross-browser behavior. 1288 | _extractParameters: function(route, fragment) { 1289 | var params = route.exec(fragment).slice(1); 1290 | return _.map(params, function(param) { 1291 | return param ? decodeURIComponent(param) : null; 1292 | }); 1293 | } 1294 | 1295 | }); 1296 | 1297 | // Backbone.History 1298 | // ---------------- 1299 | 1300 | // Handles cross-browser history management, based on either 1301 | // [pushState](http://diveintohtml5.info/history.html) and real URLs, or 1302 | // [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange) 1303 | // and URL fragments. If the browser supports neither (old IE, natch), 1304 | // falls back to polling. 1305 | var History = Backbone.History = function() { 1306 | this.handlers = []; 1307 | _.bindAll(this, 'checkUrl'); 1308 | 1309 | // Ensure that `History` can be used outside of the browser. 1310 | if (typeof window !== 'undefined') { 1311 | this.location = window.location; 1312 | this.history = window.history; 1313 | } 1314 | }; 1315 | 1316 | // Cached regex for stripping a leading hash/slash and trailing space. 1317 | var routeStripper = /^[#\/]|\s+$/g; 1318 | 1319 | // Cached regex for stripping leading and trailing slashes. 1320 | var rootStripper = /^\/+|\/+$/g; 1321 | 1322 | // Cached regex for detecting MSIE. 1323 | var isExplorer = /msie [\w.]+/; 1324 | 1325 | // Cached regex for removing a trailing slash. 1326 | var trailingSlash = /\/$/; 1327 | 1328 | // Has the history handling already been started? 1329 | History.started = false; 1330 | 1331 | // Set up all inheritable **Backbone.History** properties and methods. 1332 | _.extend(History.prototype, Events, { 1333 | 1334 | // The default interval to poll for hash changes, if necessary, is 1335 | // twenty times a second. 1336 | interval: 50, 1337 | 1338 | // Gets the true hash value. Cannot use location.hash directly due to bug 1339 | // in Firefox where location.hash will always be decoded. 1340 | getHash: function(window) { 1341 | var match = (window || this).location.href.match(/#(.*)$/); 1342 | return match ? match[1] : ''; 1343 | }, 1344 | 1345 | // Get the cross-browser normalized URL fragment, either from the URL, 1346 | // the hash, or the override. 1347 | getFragment: function(fragment, forcePushState) { 1348 | if (fragment == null) { 1349 | if (this._hasPushState || !this._wantsHashChange || forcePushState) { 1350 | fragment = this.location.pathname; 1351 | var root = this.root.replace(trailingSlash, ''); 1352 | if (!fragment.indexOf(root)) fragment = fragment.substr(root.length); 1353 | } else { 1354 | fragment = this.getHash(); 1355 | } 1356 | } 1357 | return fragment.replace(routeStripper, ''); 1358 | }, 1359 | 1360 | // Start the hash change handling, returning `true` if the current URL matches 1361 | // an existing route, and `false` otherwise. 1362 | start: function(options) { 1363 | if (History.started) throw new Error("Backbone.history has already been started"); 1364 | History.started = true; 1365 | 1366 | // Figure out the initial configuration. Do we need an iframe? 1367 | // Is pushState desired ... is it available? 1368 | this.options = _.extend({}, {root: '/'}, this.options, options); 1369 | this.root = this.options.root; 1370 | this._wantsHashChange = this.options.hashChange !== false; 1371 | this._wantsPushState = !!this.options.pushState; 1372 | this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); 1373 | var fragment = this.getFragment(); 1374 | var docMode = document.documentMode; 1375 | var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); 1376 | 1377 | // Normalize root to always include a leading and trailing slash. 1378 | this.root = ('/' + this.root + '/').replace(rootStripper, '/'); 1379 | 1380 | if (oldIE && this._wantsHashChange) { 1381 | this.iframe = Backbone.$('