├── .ruby-version
├── modules
├── a.js
├── b.js
└── c.js
├── app
├── styles
│ ├── main.css
│ └── sass
│ │ ├── main.scss
│ │ └── helpers
│ │ └── url64.rb
└── main.js
├── .gitignore
├── index-min.html
├── specs
├── DOMSpec.js
├── helpers
│ └── SpecHelper.js
├── SinonSpec.js
└── BasicSpec.js
├── README.md
├── index.html
├── LICENSE
├── package.json
├── Gruntfile.js
└── lib
└── require.js
/.ruby-version:
--------------------------------------------------------------------------------
1 | 1.9.3-p385
2 |
--------------------------------------------------------------------------------
/modules/a.js:
--------------------------------------------------------------------------------
1 | define(function(){
2 | return 'Module A loaded';
3 | });
--------------------------------------------------------------------------------
/modules/b.js:
--------------------------------------------------------------------------------
1 | define(function(){
2 | return 'Module B loaded';
3 | });
--------------------------------------------------------------------------------
/modules/c.js:
--------------------------------------------------------------------------------
1 | define(function(){
2 | return 'Module C loaded';
3 | });
--------------------------------------------------------------------------------
/app/styles/main.css:
--------------------------------------------------------------------------------
1 | body{border:10px solid blue}body p{border:10px solid green}
2 |
--------------------------------------------------------------------------------
/app/styles/sass/main.scss:
--------------------------------------------------------------------------------
1 | body {
2 | border: 10px solid blue;
3 | p {
4 | border: 10px solid green;
5 | }
6 | }
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | app/images
3 |
4 | # Below are Grunt generated files so I don't want to include them in the repo
5 | # They'll get recreated automatically by a user when they run Grunt via the CLI
6 | _SpecRunner.html
7 | .grunt/grunt-contrib-jasmine
8 | node_modules
--------------------------------------------------------------------------------
/app/main.js:
--------------------------------------------------------------------------------
1 | require.config({
2 | paths: {
3 | a: '../modules/a',
4 | b: '../modules/b',
5 | c: '../modules/c',
6 | jquery: '../lib/jquery'
7 | }
8 | });
9 |
10 | require(['a', 'b', 'c', 'jquery'], function (a, b, c, $) {
11 | console.log(a);
12 | console.log(b);
13 | console.log(c);
14 | console.log($);
15 | });
--------------------------------------------------------------------------------
/index-min.html:
--------------------------------------------------------------------------------
1 |
Grunt.js TestingThis is a paragraph of text

--------------------------------------------------------------------------------
/specs/DOMSpec.js:
--------------------------------------------------------------------------------
1 | describe('DOM', function(){
2 | beforeEach(function(){
3 | $('body').append('An injected DOM node
');
4 | });
5 |
6 | afterEach(function(){
7 | $('#js-injected').remove();
8 | });
9 |
10 | it('should insert some fixture data into the SpecRunner', function(){
11 | expect(document.getElementById('js-injected').innerHTML).toBe('An injected DOM node');
12 | });
13 | });
14 |
15 | describe('More DOM', function(){
16 | it('should remove our fixture data after tearDown', function(){
17 | expect(document.getElementById('js-injected')).toBeNull();
18 | });
19 | });
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Grunt-Boilerplate
2 |
3 | This is a project set-up using Grunt to take care of some standard tasks such as: compiling AMD based modules using RequireJS, watching/compiling Sass into CSS, watching/linting JS code and some other things such as running unit tests.
4 |
5 | ## Dependencies
6 |
7 | - `gem install image_optim`
8 |
9 | ## Help using Grunt
10 |
11 | - [Grunt Boilerplate](http://www.integralist.co.uk/posts/grunt-boilerplate.html)
12 | - [Using Grunts Config API](http://www.integralist.co.uk/posts/grunt-config.html)
13 |
14 | ## TODO:
15 |
16 | - Look at integrating Jasmine code coverage via `istanbul` plugin
17 | - Write custom task to clean `release` directory after RequireJS has run
18 | - Write custom task to rewrite html to use compiled JS files after successful release build
19 | - Write custom task for renaming un/optimised html files
20 |
--------------------------------------------------------------------------------
/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | Grunt.js Testing
7 |
8 |
9 |
10 |
11 | This is a paragraph of text
12 |
13 |
14 |
15 |
16 |
17 |
18 |
25 |
26 |
--------------------------------------------------------------------------------
/specs/helpers/SpecHelper.js:
--------------------------------------------------------------------------------
1 | beforeEach(function(){
2 | jasmine.addMatchers({
3 | toBeArray: function(){
4 | return {
5 | compare: function(actual, expected){
6 | return {
7 | pass: Object.prototype.toString.call(actual) === '[object Array]' ? true : false
8 | };
9 | }
10 | };
11 | }
12 | });
13 |
14 | jasmine.addMatchers({
15 | toBeNumber: function(){
16 | return {
17 | compare: function(actual, expected){
18 | return {
19 | pass: (/\d+/).test(actual)
20 | };
21 | }
22 | };
23 | }
24 | });
25 |
26 | jasmine.addMatchers({
27 | toBeNaN: function (expected) {
28 | return {
29 | compare: function(actual, expected){
30 | return {
31 | pass: isNaN(actual)
32 | };
33 | }
34 | };
35 | }
36 | });
37 | });
38 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2013 Mark McDonnell
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | this software and associated documentation files (the "Software"), to deal in
7 | the Software without restriction, including without limitation the rights to
8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | the Software, and to permit persons to whom the Software is furnished to do so,
10 | subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "Integralist",
3 | "version": "0.1.0",
4 | "description": "This is a project set-up using Grunt to take case of some standard tasks such as: compiling AMD based modules using RequireJS, watching/compiling Sass into CSS, watching/linting JS code and some other things such as running unit tests",
5 | "main": "Gruntfile.js",
6 | "dependencies": {},
7 | "devDependencies": {
8 | "grunt": "~0.4.1",
9 | "grunt-contrib-watch": "~0.4.4",
10 | "grunt-contrib-jshint": "~0.6.0",
11 | "grunt-contrib-uglify": "~0.2.2",
12 | "grunt-contrib-requirejs": "~0.4.1",
13 | "grunt-contrib-sass": "~0.3.0",
14 | "grunt-contrib-imagemin": "~0.1.4",
15 | "grunt-contrib-htmlmin": "~0.1.3",
16 | "grunt-contrib-jasmine": "~0.4.2",
17 | "grunt-template-jasmine-istanbul": "~0.3.0",
18 | "grunt-template-jasmine-requirejs": "~0.2.0",
19 | "grunt-contrib-connect": "~0.3.0",
20 | "load-grunt-tasks": "~0.6.0",
21 | "time-grunt": "~0.4.0"
22 | },
23 | "scripts": {
24 | "test": "echo \"Error: no test specified\" && exit 1"
25 | },
26 | "repository": {
27 | "type": "git",
28 | "url": "git@github.com:Integralist/Grunt-Boilerplate.git"
29 | },
30 | "keywords": [
31 | "Grunt",
32 | "JavaScript"
33 | ],
34 | "author": "Mark McDonnell",
35 | "license": "MIT"
36 | }
37 |
--------------------------------------------------------------------------------
/specs/SinonSpec.js:
--------------------------------------------------------------------------------
1 | describe('Sinon.js', function(){
2 | beforeEach(function(){
3 | this.obj = {
4 | doSomething: function(msg) {
5 | return 'Your message was: ' + msg;
6 | },
7 | add10: function(num) {
8 | return num + 10;
9 | },
10 | delegation: function(){ this.doSomething(); }
11 | };
12 | });
13 |
14 | afterEach(function(){
15 | this.obj = null;
16 | });
17 |
18 | it('should have access to the sinon library', function(){
19 | expect(sinon).toBeDefined();
20 | });
21 |
22 | it('should demonstate stub feature', function(){
23 | sinon.stub(this.obj, 'add10', function(num){ return 12; });
24 | expect(this.obj.add10(1)).not.toBe(11);
25 |
26 | sinon.stub(this.obj, 'doSomething').returns('Something else?');
27 | expect(this.obj.doSomething('test 1')).toBe('Something else?');
28 |
29 | this.obj.doSomething.restore();
30 | this.obj.add10.restore();
31 | });
32 |
33 | it('should demonstate mock feature', function(){
34 | var mock = sinon.mock(this.obj);
35 | mock.expects('doSomething').exactly(2);
36 |
37 | this.obj.delegation('Some Message');
38 | this.obj.doSomething('Some Other Message');
39 |
40 | mock.verify();
41 | mock.restore();
42 | });
43 | });
--------------------------------------------------------------------------------
/specs/BasicSpec.js:
--------------------------------------------------------------------------------
1 | describe('Basic', function(){
2 | it('should pass a single assertion without causing an error', function(){
3 | expect([]).toBeArray();
4 | });
5 |
6 | it('should let me test our AMD modules', function(){
7 | expect($).toBeDefined();
8 | });
9 | });
10 |
11 | describe('AJAX', function(){
12 | beforeEach(function(){
13 | // SET-UP FAKE XHR
14 | var requests = this.requests = [];
15 | this.ajax = sinon.useFakeXMLHttpRequest(); // replaces the native XHR/ActiveXObject
16 | this.ajax.onCreate = function(xhr) {
17 | requests.push(xhr);
18 | };
19 | });
20 |
21 | afterEach(function(){
22 | // RESTORE REAL XHR
23 | this.ajax.restore();
24 | });
25 |
26 | it('should demonstrate the Sinon mocking and spying functionality', function(){
27 | var spy = sinon.spy();
28 |
29 | $.ajax({
30 | url: '/Gruntfile.js',
31 | success: spy
32 | });
33 |
34 | this.requests[0].respond(200, { 'Content-Type': 'application/json' }, '[{ "id": 123, "comment": "Hey there" }]');
35 |
36 | expect(this.requests.length).toBeNumber();
37 | expect(this.requests.length).toBe(1);
38 | expect(this.requests[0].url).toEqual('/Gruntfile.js');
39 | expect(this.requests[0].method).toEqual('GET');
40 |
41 | expect(spy.called).toBeTruthy();
42 | expect(spy.callCount).toBe(1);
43 | expect(spy.calledWith([{ id: 123, comment: "Hey there" }])).toBeTruthy();
44 | });
45 | });
--------------------------------------------------------------------------------
/app/styles/sass/helpers/url64.rb:
--------------------------------------------------------------------------------
1 | require 'base64'
2 | require 'sass'
3 | require 'image_optim' # https://github.com/toy/image_optim
4 |
5 | module Sass::Script::Functions
6 | def url64(image)
7 | assert_type image, :String
8 |
9 | # compute file/path/extension
10 |
11 | base_path = '../../../' # from the current directory /app/styles/sass/helpers/
12 |
13 | root = File.expand_path(base_path, __FILE__)
14 | path = image.to_s[1, image.to_s.length-2]
15 | fullpath = File.expand_path(path, root)
16 | absname = File.expand_path(fullpath)
17 | ext = File.extname(path)
18 |
19 | # optimize image if it's a gif, jpg, png
20 | if ext.index(%r{\.(?:gif|jpg|png)}) != nil
21 | # homebrew link to pngcrush is outdated so need to avoid pngcrush for now
22 | # also homebrew doesn't support pngout so we ignore that too!
23 | # The following links show the compression settings...
24 | # https://github.com/toy/image_optim/blob/master/lib/image_optim/worker/advpng.rb
25 | # https://github.com/toy/image_optim/blob/master/lib/image_optim/worker/optipng.rb
26 | # https://github.com/toy/image_optim/blob/master/lib/image_optim/worker/jpegoptim.rb
27 | image_optim = ImageOptim.new(:pngcrush => false, :pngout => false, :advpng => {:level => 4}, :optipng => {:level => 7}, :jpegoptim => {:max_quality => 1})
28 |
29 | # we can lose the ! and the method will save the image to a temp directory, otherwise it'll overwrite the original image
30 | image_optim.optimize_image!(fullpath)
31 | end
32 |
33 | # base64 encode the file
34 | file = File.open(fullpath, 'rb') # read mode & binary mode
35 | filesize = File.size(file) / 1000 # seems to report the size as being 1kb smaller than it actually is (so if our limit is 32kb for IE8 then we need our limit to be 31kb)
36 | text = file.read
37 | file.close
38 |
39 | if filesize < 31 # we're avoiding IE8 32kb data uri size restriction
40 | text_b64 = Base64.encode64(text).gsub(/\r/,'').gsub(/\n/,'')
41 | contents = 'url(data:image/' + ext[1, ext.length-1] + ';base64,' + text_b64 + ')'
42 | else
43 | contents = 'url(' + image.to_s + ')' # if larger than 32kb then we'll just return the original image path url
44 | end
45 |
46 | Sass::Script::String.new(contents)
47 | end
48 |
49 | declare :url64, :args => [:string]
50 | end
--------------------------------------------------------------------------------
/Gruntfile.js:
--------------------------------------------------------------------------------
1 | module.exports = function (grunt) {
2 |
3 | /*
4 | Grunt installation:
5 | -------------------
6 | npm install -g grunt-cli
7 | npm install -g grunt-init
8 | npm init (creates a `package.json` file)
9 |
10 | Project Dependencies:
11 | ---------------------
12 | npm install grunt --save-dev
13 | npm install grunt-contrib-watch --save-dev
14 | npm install grunt-contrib-jshint --save-dev
15 | npm install grunt-contrib-uglify --save-dev
16 | npm install grunt-contrib-requirejs --save-dev
17 | npm install grunt-contrib-sass --save-dev
18 | npm install grunt-contrib-imagemin --save-dev
19 | npm install grunt-contrib-htmlmin --save-dev
20 | npm install grunt-contrib-connect --save-dev
21 | npm install grunt-contrib-jasmine --save-dev
22 | npm install grunt-template-jasmine-requirejs --save-dev
23 | npm install grunt-template-jasmine-istanbul --save-dev
24 | npm install load-grunt-tasks --save-dev
25 | npm install time-grunt --save-dev
26 |
27 | Simple Dependency Install:
28 | --------------------------
29 | npm install (from the same root directory as the `package.json` file)
30 |
31 | Gem Dependencies:
32 | -----------------
33 | gem install image_optim
34 | */
35 |
36 | // Displays the elapsed execution time of grunt tasks
37 | require('time-grunt')(grunt);
38 |
39 | // Load NPM Tasks
40 | require('load-grunt-tasks')(grunt, ['grunt-*', '!grunt-template-jasmine-istanbul', '!grunt-template-jasmine-requirejs']);
41 |
42 | // Project configuration.
43 | grunt.initConfig({
44 |
45 | // Store your Package file so you can reference its specific data whenever necessary
46 | pkg: grunt.file.readJSON('package.json'),
47 |
48 | /*
49 | uglify: {
50 | options: {
51 | banner: '/*! <%= pkg.name %> | <%= pkg.version %> | <%= grunt.template.today("yyyy-mm-dd") %> /\n'
52 | },
53 | dist: {
54 | src: './<%= pkg.name %>.js',
55 | dest: './<%= pkg.name %>.min.js'
56 | }
57 | },
58 | */
59 |
60 | // Used to connect to a locally running web server (so Jasmine can test against a DOM)
61 | connect: {
62 | test: {
63 | port: 8000
64 | }
65 | },
66 |
67 | jasmine: {
68 | run: {
69 | /*
70 | Note:
71 | In case there is a /release/ directory found, we don't want to run tests on that
72 | so we use the ! (bang) operator to ignore the specified directory
73 | */
74 | src: ['app/**/*.js', '!app/release/**'],
75 | options: {
76 | host: 'http://127.0.0.1:8000/',
77 | specs: 'specs/**/*Spec.js',
78 | helpers: ['specs/helpers/*Helper.js', 'specs/helpers/sinon.js'],
79 | template: require('grunt-template-jasmine-requirejs'),
80 | templateOptions: {
81 | requireConfig: {
82 | baseUrl: './app/',
83 | mainConfigFile: './app/main.js'
84 | }
85 | }
86 | }
87 | },
88 | coverage: {
89 | src: ['app/**/*.js', '!app/release/**'],
90 | options: {
91 | specs: 'specs/**/*Spec.js',
92 | template: require('grunt-template-jasmine-istanbul'),
93 | templateOptions: {
94 | coverage: 'bin/coverage/coverage.json',
95 | report: [
96 | {
97 | type: 'html',
98 | options: {
99 | dir: 'bin/coverage//html'
100 | }
101 | },
102 | {
103 | type: 'text-summary'
104 | }
105 | ],
106 | // 1. don't replace src for the mixed-in template with instrumented sources
107 | replace: false,
108 | template: require('grunt-template-jasmine-requirejs'),
109 | templateOptions: {
110 | requireConfig: {
111 | // 2. use the baseUrl you want
112 | baseUrl: './app/',
113 | // 3. pass paths of the sources being instrumented as a configuration option
114 | // these paths should be the same as the jasmine task's src
115 | // unfortunately, grunt.config.get() doesn't work because the config is just being evaluated
116 | config: {
117 | instrumented: {
118 | src: grunt.file.expand('./app/*.js')
119 | }
120 | },
121 | // 4. use this callback to read the paths of the sources being instrumented and redirect requests to them appropriately
122 | callback: function () {
123 | define('instrumented', ['module'], function (module) {
124 | return module.config().src;
125 | });
126 | require(['instrumented'], function (instrumented) {
127 | var oldLoad = requirejs.load;
128 | requirejs.load = function (context, moduleName, url) {
129 | // normalize paths
130 | if (url.substring(0, 1) === '/') {
131 | url = url.substring(1);
132 | } else if (url.substring(0, 2) === './') {
133 | url = url.substring(2);
134 | }
135 | // redirect
136 | if (instrumented.indexOf(url) > -1) {
137 | url = './.grunt/grunt-contrib-jasmine/' + url;
138 | }
139 | return oldLoad.apply(this, [context, moduleName, url]);
140 | };
141 | });
142 | }
143 | }
144 | }
145 | }
146 | }
147 | }
148 | },
149 |
150 | jshint: {
151 | /*
152 | Note:
153 | In case there is a /release/ directory found, we don't want to lint that
154 | so we use the ! (bang) operator to ignore the specified directory
155 | */
156 | files: ['Gruntfile.js', 'app/**/*.js', '!app/release/**', 'modules/**/*.js', 'specs/**/*Spec.js'],
157 | options: {
158 | curly: true,
159 | eqeqeq: true,
160 | immed: true,
161 | latedef: true,
162 | newcap: true,
163 | noarg: true,
164 | sub: true,
165 | undef: true,
166 | boss: true,
167 | eqnull: true,
168 | browser: true,
169 |
170 | globals: {
171 | // AMD
172 | module: true,
173 | require: true,
174 | requirejs: true,
175 | define: true,
176 |
177 | // Environments
178 | console: true,
179 |
180 | // General Purpose Libraries
181 | $: true,
182 | jQuery: true,
183 |
184 | // Testing
185 | sinon: true,
186 | describe: true,
187 | it: true,
188 | expect: true,
189 | beforeEach: true,
190 | afterEach: true
191 | }
192 | }
193 | },
194 |
195 | requirejs: {
196 | compile: {
197 | options: {
198 | baseUrl: './app',
199 | mainConfigFile: './app/main.js',
200 | dir: './app/release/',
201 | fileExclusionRegExp: /^\.|node_modules|Gruntfile|\.md|package.json/,
202 | // optimize: 'none',
203 | modules: [
204 | {
205 | name: 'main'
206 | // include: ['module'],
207 | // exclude: ['module']
208 | }
209 | ]
210 | }
211 | }
212 | },
213 |
214 | sass: {
215 | dist: {
216 | options: {
217 | style: 'compressed',
218 | require: ['./app/styles/sass/helpers/url64.rb']
219 | },
220 | expand: true,
221 | cwd: './app/styles/sass/',
222 | src: ['*.scss'],
223 | dest: './app/styles/',
224 | ext: '.css'
225 | },
226 | dev: {
227 | options: {
228 | style: 'expanded',
229 | debugInfo: true,
230 | lineNumbers: true,
231 | require: ['./app/styles/sass/helpers/url64.rb']
232 | },
233 | expand: true,
234 | cwd: './app/styles/sass/',
235 | src: ['*.scss'],
236 | dest: './app/styles/',
237 | ext: '.css'
238 | }
239 | },
240 |
241 | // `optimizationLevel` is only applied to PNG files (not JPG)
242 | imagemin: {
243 | png: {
244 | options: {
245 | optimizationLevel: 7
246 | },
247 | files: [
248 | {
249 | expand: true,
250 | cwd: './app/images/',
251 | src: ['**/*.png'],
252 | dest: './app/images/compressed/',
253 | ext: '.png'
254 | }
255 | ]
256 | },
257 | jpg: {
258 | options: {
259 | progressive: true
260 | },
261 | files: [
262 | {
263 | expand: true,
264 | cwd: './app/images/',
265 | src: ['**/*.jpg'],
266 | dest: './app/images/compressed/',
267 | ext: '.jpg'
268 | }
269 | ]
270 | }
271 | },
272 |
273 | htmlmin: {
274 | dist: {
275 | options: {
276 | removeComments: true,
277 | collapseWhitespace: true,
278 | removeEmptyAttributes: true,
279 | removeCommentsFromCDATA: true,
280 | removeRedundantAttributes: true,
281 | collapseBooleanAttributes: true
282 | },
283 | files: {
284 | // Destination : Source
285 | './index-min.html': './index.html'
286 | }
287 | }
288 | },
289 |
290 | // Run: `grunt watch` from command line for this section to take effect
291 | watch: {
292 | files: ['<%= jshint.files %>', '<%= jasmine.options.specs %>', '<%= sass.dev.src %>'],
293 | tasks: 'default'
294 | }
295 |
296 | });
297 |
298 | // Default Task
299 | grunt.registerTask('default', ['jshint', 'connect', 'jasmine', 'sass:dev']);
300 |
301 | // Unit Testing Task
302 | grunt.registerTask('test', ['connect', 'jasmine:run']);
303 |
304 | // Release Task
305 | grunt.registerTask('release', ['jshint', 'test', 'requirejs', 'sass:dist', 'imagemin', 'htmlmin']);
306 |
307 | /*
308 | Notes:
309 |
310 | When registering a new Task we can also pass in any other registered Tasks.
311 | e.g. grunt.registerTask('release', 'default requirejs'); // when running this task we also run the 'default' Task
312 |
313 | We don't do this above as we would end up running `sass:dev` when we only want to run `sass:dist`
314 | We could do it and `sass:dist` would run afterwards, but that means we're compiling sass twice which (although in our example quick) is extra compiling time.
315 |
316 | To run specific sub tasks then use a colon, like so...
317 | grunt sass:dev
318 | grunt sass:dist
319 | */
320 |
321 | };
322 |
--------------------------------------------------------------------------------
/lib/require.js:
--------------------------------------------------------------------------------
1 | /** vim: et:ts=4:sw=4:sts=4
2 | * @license RequireJS 2.1.2 Copyright (c) 2010-2012, The Dojo Foundation All Rights Reserved.
3 | * Available via the MIT or new BSD license.
4 | * see: http://github.com/jrburke/requirejs for details
5 | */
6 | //Not using strict: uneven strict support in browsers, #392, and causes
7 | //problems with requirejs.exec()/transpiler plugins that may not be strict.
8 | /*jslint regexp: true, nomen: true, sloppy: true */
9 | /*global window, navigator, document, importScripts, jQuery, setTimeout, opera */
10 |
11 | var requirejs, require, define;
12 | (function (global) {
13 | var req, s, head, baseElement, dataMain, src,
14 | interactiveScript, currentlyAddingScript, mainScript, subPath,
15 | version = '2.1.2',
16 | commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
17 | cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
18 | jsSuffixRegExp = /\.js$/,
19 | currDirRegExp = /^\.\//,
20 | op = Object.prototype,
21 | ostring = op.toString,
22 | hasOwn = op.hasOwnProperty,
23 | ap = Array.prototype,
24 | aps = ap.slice,
25 | apsp = ap.splice,
26 | isBrowser = !!(typeof window !== 'undefined' && navigator && document),
27 | isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
28 | //PS3 indicates loaded and complete, but need to wait for complete
29 | //specifically. Sequence is 'loading', 'loaded', execution,
30 | // then 'complete'. The UA check is unfortunate, but not sure how
31 | //to feature test w/o causing perf issues.
32 | readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
33 | /^complete$/ : /^(complete|loaded)$/,
34 | defContextName = '_',
35 | //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
36 | isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
37 | contexts = {},
38 | cfg = {},
39 | globalDefQueue = [],
40 | useInteractive = false;
41 |
42 | function isFunction(it) {
43 | return ostring.call(it) === '[object Function]';
44 | }
45 |
46 | function isArray(it) {
47 | return ostring.call(it) === '[object Array]';
48 | }
49 |
50 | /**
51 | * Helper function for iterating over an array. If the func returns
52 | * a true value, it will break out of the loop.
53 | */
54 | function each(ary, func) {
55 | if (ary) {
56 | var i;
57 | for (i = 0; i < ary.length; i += 1) {
58 | if (ary[i] && func(ary[i], i, ary)) {
59 | break;
60 | }
61 | }
62 | }
63 | }
64 |
65 | /**
66 | * Helper function for iterating over an array backwards. If the func
67 | * returns a true value, it will break out of the loop.
68 | */
69 | function eachReverse(ary, func) {
70 | if (ary) {
71 | var i;
72 | for (i = ary.length - 1; i > -1; i -= 1) {
73 | if (ary[i] && func(ary[i], i, ary)) {
74 | break;
75 | }
76 | }
77 | }
78 | }
79 |
80 | function hasProp(obj, prop) {
81 | return hasOwn.call(obj, prop);
82 | }
83 |
84 | function getOwn(obj, prop) {
85 | return hasProp(obj, prop) && obj[prop];
86 | }
87 |
88 | /**
89 | * Cycles over properties in an object and calls a function for each
90 | * property value. If the function returns a truthy value, then the
91 | * iteration is stopped.
92 | */
93 | function eachProp(obj, func) {
94 | var prop;
95 | for (prop in obj) {
96 | if (hasProp(obj, prop)) {
97 | if (func(obj[prop], prop)) {
98 | break;
99 | }
100 | }
101 | }
102 | }
103 |
104 | /**
105 | * Simple function to mix in properties from source into target,
106 | * but only if target does not already have a property of the same name.
107 | */
108 | function mixin(target, source, force, deepStringMixin) {
109 | if (source) {
110 | eachProp(source, function (value, prop) {
111 | if (force || !hasProp(target, prop)) {
112 | if (deepStringMixin && typeof value !== 'string') {
113 | if (!target[prop]) {
114 | target[prop] = {};
115 | }
116 | mixin(target[prop], value, force, deepStringMixin);
117 | } else {
118 | target[prop] = value;
119 | }
120 | }
121 | });
122 | }
123 | return target;
124 | }
125 |
126 | //Similar to Function.prototype.bind, but the 'this' object is specified
127 | //first, since it is easier to read/figure out what 'this' will be.
128 | function bind(obj, fn) {
129 | return function () {
130 | return fn.apply(obj, arguments);
131 | };
132 | }
133 |
134 | function scripts() {
135 | return document.getElementsByTagName('script');
136 | }
137 |
138 | //Allow getting a global that expressed in
139 | //dot notation, like 'a.b.c'.
140 | function getGlobal(value) {
141 | if (!value) {
142 | return value;
143 | }
144 | var g = global;
145 | each(value.split('.'), function (part) {
146 | g = g[part];
147 | });
148 | return g;
149 | }
150 |
151 | /**
152 | * Constructs an error with a pointer to an URL with more information.
153 | * @param {String} id the error ID that maps to an ID on a web page.
154 | * @param {String} message human readable error.
155 | * @param {Error} [err] the original error, if there is one.
156 | *
157 | * @returns {Error}
158 | */
159 | function makeError(id, msg, err, requireModules) {
160 | var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
161 | e.requireType = id;
162 | e.requireModules = requireModules;
163 | if (err) {
164 | e.originalError = err;
165 | }
166 | return e;
167 | }
168 |
169 | if (typeof define !== 'undefined') {
170 | //If a define is already in play via another AMD loader,
171 | //do not overwrite.
172 | return;
173 | }
174 |
175 | if (typeof requirejs !== 'undefined') {
176 | if (isFunction(requirejs)) {
177 | //Do not overwrite and existing requirejs instance.
178 | return;
179 | }
180 | cfg = requirejs;
181 | requirejs = undefined;
182 | }
183 |
184 | //Allow for a require config object
185 | if (typeof require !== 'undefined' && !isFunction(require)) {
186 | //assume it is a config object.
187 | cfg = require;
188 | require = undefined;
189 | }
190 |
191 | function newContext(contextName) {
192 | var inCheckLoaded, Module, context, handlers,
193 | checkLoadedTimeoutId,
194 | config = {
195 | waitSeconds: 7,
196 | baseUrl: './',
197 | paths: {},
198 | pkgs: {},
199 | shim: {},
200 | map: {},
201 | config: {}
202 | },
203 | registry = {},
204 | undefEvents = {},
205 | defQueue = [],
206 | defined = {},
207 | urlFetched = {},
208 | requireCounter = 1,
209 | unnormalizedCounter = 1;
210 |
211 | /**
212 | * Trims the . and .. from an array of path segments.
213 | * It will keep a leading path segment if a .. will become
214 | * the first path segment, to help with module name lookups,
215 | * which act like paths, but can be remapped. But the end result,
216 | * all paths that use this function should look normalized.
217 | * NOTE: this method MODIFIES the input array.
218 | * @param {Array} ary the array of path segments.
219 | */
220 | function trimDots(ary) {
221 | var i, part;
222 | for (i = 0; ary[i]; i += 1) {
223 | part = ary[i];
224 | if (part === '.') {
225 | ary.splice(i, 1);
226 | i -= 1;
227 | } else if (part === '..') {
228 | if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
229 | //End of the line. Keep at least one non-dot
230 | //path segment at the front so it can be mapped
231 | //correctly to disk. Otherwise, there is likely
232 | //no path mapping for a path starting with '..'.
233 | //This can still fail, but catches the most reasonable
234 | //uses of ..
235 | break;
236 | } else if (i > 0) {
237 | ary.splice(i - 1, 2);
238 | i -= 2;
239 | }
240 | }
241 | }
242 | }
243 |
244 | /**
245 | * Given a relative module name, like ./something, normalize it to
246 | * a real name that can be mapped to a path.
247 | * @param {String} name the relative name
248 | * @param {String} baseName a real name that the name arg is relative
249 | * to.
250 | * @param {Boolean} applyMap apply the map config to the value. Should
251 | * only be done if this normalization is for a dependency ID.
252 | * @returns {String} normalized name
253 | */
254 | function normalize(name, baseName, applyMap) {
255 | var pkgName, pkgConfig, mapValue, nameParts, i, j, nameSegment,
256 | foundMap, foundI, foundStarMap, starI,
257 | baseParts = baseName && baseName.split('/'),
258 | normalizedBaseParts = baseParts,
259 | map = config.map,
260 | starMap = map && map['*'];
261 |
262 | //Adjust any relative paths.
263 | if (name && name.charAt(0) === '.') {
264 | //If have a base name, try to normalize against it,
265 | //otherwise, assume it is a top-level require that will
266 | //be relative to baseUrl in the end.
267 | if (baseName) {
268 | if (getOwn(config.pkgs, baseName)) {
269 | //If the baseName is a package name, then just treat it as one
270 | //name to concat the name with.
271 | normalizedBaseParts = baseParts = [baseName];
272 | } else {
273 | //Convert baseName to array, and lop off the last part,
274 | //so that . matches that 'directory' and not name of the baseName's
275 | //module. For instance, baseName of 'one/two/three', maps to
276 | //'one/two/three.js', but we want the directory, 'one/two' for
277 | //this normalization.
278 | normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
279 | }
280 |
281 | name = normalizedBaseParts.concat(name.split('/'));
282 | trimDots(name);
283 |
284 | //Some use of packages may use a . path to reference the
285 | //'main' module name, so normalize for that.
286 | pkgConfig = getOwn(config.pkgs, (pkgName = name[0]));
287 | name = name.join('/');
288 | if (pkgConfig && name === pkgName + '/' + pkgConfig.main) {
289 | name = pkgName;
290 | }
291 | } else if (name.indexOf('./') === 0) {
292 | // No baseName, so this is ID is resolved relative
293 | // to baseUrl, pull off the leading dot.
294 | name = name.substring(2);
295 | }
296 | }
297 |
298 | //Apply map config if available.
299 | if (applyMap && (baseParts || starMap) && map) {
300 | nameParts = name.split('/');
301 |
302 | for (i = nameParts.length; i > 0; i -= 1) {
303 | nameSegment = nameParts.slice(0, i).join('/');
304 |
305 | if (baseParts) {
306 | //Find the longest baseName segment match in the config.
307 | //So, do joins on the biggest to smallest lengths of baseParts.
308 | for (j = baseParts.length; j > 0; j -= 1) {
309 | mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
310 |
311 | //baseName segment has config, find if it has one for
312 | //this name.
313 | if (mapValue) {
314 | mapValue = getOwn(mapValue, nameSegment);
315 | if (mapValue) {
316 | //Match, update name to the new value.
317 | foundMap = mapValue;
318 | foundI = i;
319 | break;
320 | }
321 | }
322 | }
323 | }
324 |
325 | if (foundMap) {
326 | break;
327 | }
328 |
329 | //Check for a star map match, but just hold on to it,
330 | //if there is a shorter segment match later in a matching
331 | //config, then favor over this star map.
332 | if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
333 | foundStarMap = getOwn(starMap, nameSegment);
334 | starI = i;
335 | }
336 | }
337 |
338 | if (!foundMap && foundStarMap) {
339 | foundMap = foundStarMap;
340 | foundI = starI;
341 | }
342 |
343 | if (foundMap) {
344 | nameParts.splice(0, foundI, foundMap);
345 | name = nameParts.join('/');
346 | }
347 | }
348 |
349 | return name;
350 | }
351 |
352 | function removeScript(name) {
353 | if (isBrowser) {
354 | each(scripts(), function (scriptNode) {
355 | if (scriptNode.getAttribute('data-requiremodule') === name &&
356 | scriptNode.getAttribute('data-requirecontext') === context.contextName) {
357 | scriptNode.parentNode.removeChild(scriptNode);
358 | return true;
359 | }
360 | });
361 | }
362 | }
363 |
364 | function hasPathFallback(id) {
365 | var pathConfig = getOwn(config.paths, id);
366 | if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
367 | removeScript(id);
368 | //Pop off the first array value, since it failed, and
369 | //retry
370 | pathConfig.shift();
371 | context.require.undef(id);
372 | context.require([id]);
373 | return true;
374 | }
375 | }
376 |
377 | //Turns a plugin!resource to [plugin, resource]
378 | //with the plugin being undefined if the name
379 | //did not have a plugin prefix.
380 | function splitPrefix(name) {
381 | var prefix,
382 | index = name ? name.indexOf('!') : -1;
383 | if (index > -1) {
384 | prefix = name.substring(0, index);
385 | name = name.substring(index + 1, name.length);
386 | }
387 | return [prefix, name];
388 | }
389 |
390 | /**
391 | * Creates a module mapping that includes plugin prefix, module
392 | * name, and path. If parentModuleMap is provided it will
393 | * also normalize the name via require.normalize()
394 | *
395 | * @param {String} name the module name
396 | * @param {String} [parentModuleMap] parent module map
397 | * for the module name, used to resolve relative names.
398 | * @param {Boolean} isNormalized: is the ID already normalized.
399 | * This is true if this call is done for a define() module ID.
400 | * @param {Boolean} applyMap: apply the map config to the ID.
401 | * Should only be true if this map is for a dependency.
402 | *
403 | * @returns {Object}
404 | */
405 | function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
406 | var url, pluginModule, suffix, nameParts,
407 | prefix = null,
408 | parentName = parentModuleMap ? parentModuleMap.name : null,
409 | originalName = name,
410 | isDefine = true,
411 | normalizedName = '';
412 |
413 | //If no name, then it means it is a require call, generate an
414 | //internal name.
415 | if (!name) {
416 | isDefine = false;
417 | name = '_@r' + (requireCounter += 1);
418 | }
419 |
420 | nameParts = splitPrefix(name);
421 | prefix = nameParts[0];
422 | name = nameParts[1];
423 |
424 | if (prefix) {
425 | prefix = normalize(prefix, parentName, applyMap);
426 | pluginModule = getOwn(defined, prefix);
427 | }
428 |
429 | //Account for relative paths if there is a base name.
430 | if (name) {
431 | if (prefix) {
432 | if (pluginModule && pluginModule.normalize) {
433 | //Plugin is loaded, use its normalize method.
434 | normalizedName = pluginModule.normalize(name, function (name) {
435 | return normalize(name, parentName, applyMap);
436 | });
437 | } else {
438 | normalizedName = normalize(name, parentName, applyMap);
439 | }
440 | } else {
441 | //A regular module.
442 | normalizedName = normalize(name, parentName, applyMap);
443 |
444 | //Normalized name may be a plugin ID due to map config
445 | //application in normalize. The map config values must
446 | //already be normalized, so do not need to redo that part.
447 | nameParts = splitPrefix(normalizedName);
448 | prefix = nameParts[0];
449 | normalizedName = nameParts[1];
450 | isNormalized = true;
451 |
452 | url = context.nameToUrl(normalizedName);
453 | }
454 | }
455 |
456 | //If the id is a plugin id that cannot be determined if it needs
457 | //normalization, stamp it with a unique ID so two matching relative
458 | //ids that may conflict can be separate.
459 | suffix = prefix && !pluginModule && !isNormalized ?
460 | '_unnormalized' + (unnormalizedCounter += 1) :
461 | '';
462 |
463 | return {
464 | prefix: prefix,
465 | name: normalizedName,
466 | parentMap: parentModuleMap,
467 | unnormalized: !!suffix,
468 | url: url,
469 | originalName: originalName,
470 | isDefine: isDefine,
471 | id: (prefix ?
472 | prefix + '!' + normalizedName :
473 | normalizedName) + suffix
474 | };
475 | }
476 |
477 | function getModule(depMap) {
478 | var id = depMap.id,
479 | mod = getOwn(registry, id);
480 |
481 | if (!mod) {
482 | mod = registry[id] = new context.Module(depMap);
483 | }
484 |
485 | return mod;
486 | }
487 |
488 | function on(depMap, name, fn) {
489 | var id = depMap.id,
490 | mod = getOwn(registry, id);
491 |
492 | if (hasProp(defined, id) &&
493 | (!mod || mod.defineEmitComplete)) {
494 | if (name === 'defined') {
495 | fn(defined[id]);
496 | }
497 | } else {
498 | getModule(depMap).on(name, fn);
499 | }
500 | }
501 |
502 | function onError(err, errback) {
503 | var ids = err.requireModules,
504 | notified = false;
505 |
506 | if (errback) {
507 | errback(err);
508 | } else {
509 | each(ids, function (id) {
510 | var mod = getOwn(registry, id);
511 | if (mod) {
512 | //Set error on module, so it skips timeout checks.
513 | mod.error = err;
514 | if (mod.events.error) {
515 | notified = true;
516 | mod.emit('error', err);
517 | }
518 | }
519 | });
520 |
521 | if (!notified) {
522 | req.onError(err);
523 | }
524 | }
525 | }
526 |
527 | /**
528 | * Internal method to transfer globalQueue items to this context's
529 | * defQueue.
530 | */
531 | function takeGlobalQueue() {
532 | //Push all the globalDefQueue items into the context's defQueue
533 | if (globalDefQueue.length) {
534 | //Array splice in the values since the context code has a
535 | //local var ref to defQueue, so cannot just reassign the one
536 | //on context.
537 | apsp.apply(defQueue,
538 | [defQueue.length - 1, 0].concat(globalDefQueue));
539 | globalDefQueue = [];
540 | }
541 | }
542 |
543 | handlers = {
544 | 'require': function (mod) {
545 | if (mod.require) {
546 | return mod.require;
547 | } else {
548 | return (mod.require = context.makeRequire(mod.map));
549 | }
550 | },
551 | 'exports': function (mod) {
552 | mod.usingExports = true;
553 | if (mod.map.isDefine) {
554 | if (mod.exports) {
555 | return mod.exports;
556 | } else {
557 | return (mod.exports = defined[mod.map.id] = {});
558 | }
559 | }
560 | },
561 | 'module': function (mod) {
562 | if (mod.module) {
563 | return mod.module;
564 | } else {
565 | return (mod.module = {
566 | id: mod.map.id,
567 | uri: mod.map.url,
568 | config: function () {
569 | return (config.config && getOwn(config.config, mod.map.id)) || {};
570 | },
571 | exports: defined[mod.map.id]
572 | });
573 | }
574 | }
575 | };
576 |
577 | function cleanRegistry(id) {
578 | //Clean up machinery used for waiting modules.
579 | delete registry[id];
580 | }
581 |
582 | function breakCycle(mod, traced, processed) {
583 | var id = mod.map.id;
584 |
585 | if (mod.error) {
586 | mod.emit('error', mod.error);
587 | } else {
588 | traced[id] = true;
589 | each(mod.depMaps, function (depMap, i) {
590 | var depId = depMap.id,
591 | dep = getOwn(registry, depId);
592 |
593 | //Only force things that have not completed
594 | //being defined, so still in the registry,
595 | //and only if it has not been matched up
596 | //in the module already.
597 | if (dep && !mod.depMatched[i] && !processed[depId]) {
598 | if (getOwn(traced, depId)) {
599 | mod.defineDep(i, defined[depId]);
600 | mod.check(); //pass false?
601 | } else {
602 | breakCycle(dep, traced, processed);
603 | }
604 | }
605 | });
606 | processed[id] = true;
607 | }
608 | }
609 |
610 | function checkLoaded() {
611 | var map, modId, err, usingPathFallback,
612 | waitInterval = config.waitSeconds * 1000,
613 | //It is possible to disable the wait interval by using waitSeconds of 0.
614 | expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
615 | noLoads = [],
616 | reqCalls = [],
617 | stillLoading = false,
618 | needCycleCheck = true;
619 |
620 | //Do not bother if this call was a result of a cycle break.
621 | if (inCheckLoaded) {
622 | return;
623 | }
624 |
625 | inCheckLoaded = true;
626 |
627 | //Figure out the state of all the modules.
628 | eachProp(registry, function (mod) {
629 | map = mod.map;
630 | modId = map.id;
631 |
632 | //Skip things that are not enabled or in error state.
633 | if (!mod.enabled) {
634 | return;
635 | }
636 |
637 | if (!map.isDefine) {
638 | reqCalls.push(mod);
639 | }
640 |
641 | if (!mod.error) {
642 | //If the module should be executed, and it has not
643 | //been inited and time is up, remember it.
644 | if (!mod.inited && expired) {
645 | if (hasPathFallback(modId)) {
646 | usingPathFallback = true;
647 | stillLoading = true;
648 | } else {
649 | noLoads.push(modId);
650 | removeScript(modId);
651 | }
652 | } else if (!mod.inited && mod.fetched && map.isDefine) {
653 | stillLoading = true;
654 | if (!map.prefix) {
655 | //No reason to keep looking for unfinished
656 | //loading. If the only stillLoading is a
657 | //plugin resource though, keep going,
658 | //because it may be that a plugin resource
659 | //is waiting on a non-plugin cycle.
660 | return (needCycleCheck = false);
661 | }
662 | }
663 | }
664 | });
665 |
666 | if (expired && noLoads.length) {
667 | //If wait time expired, throw error of unloaded modules.
668 | err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
669 | err.contextName = context.contextName;
670 | return onError(err);
671 | }
672 |
673 | //Not expired, check for a cycle.
674 | if (needCycleCheck) {
675 | each(reqCalls, function (mod) {
676 | breakCycle(mod, {}, {});
677 | });
678 | }
679 |
680 | //If still waiting on loads, and the waiting load is something
681 | //other than a plugin resource, or there are still outstanding
682 | //scripts, then just try back later.
683 | if ((!expired || usingPathFallback) && stillLoading) {
684 | //Something is still waiting to load. Wait for it, but only
685 | //if a timeout is not already in effect.
686 | if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
687 | checkLoadedTimeoutId = setTimeout(function () {
688 | checkLoadedTimeoutId = 0;
689 | checkLoaded();
690 | }, 50);
691 | }
692 | }
693 |
694 | inCheckLoaded = false;
695 | }
696 |
697 | Module = function (map) {
698 | this.events = getOwn(undefEvents, map.id) || {};
699 | this.map = map;
700 | this.shim = getOwn(config.shim, map.id);
701 | this.depExports = [];
702 | this.depMaps = [];
703 | this.depMatched = [];
704 | this.pluginMaps = {};
705 | this.depCount = 0;
706 |
707 | /* this.exports this.factory
708 | this.depMaps = [],
709 | this.enabled, this.fetched
710 | */
711 | };
712 |
713 | Module.prototype = {
714 | init: function (depMaps, factory, errback, options) {
715 | options = options || {};
716 |
717 | //Do not do more inits if already done. Can happen if there
718 | //are multiple define calls for the same module. That is not
719 | //a normal, common case, but it is also not unexpected.
720 | if (this.inited) {
721 | return;
722 | }
723 |
724 | this.factory = factory;
725 |
726 | if (errback) {
727 | //Register for errors on this module.
728 | this.on('error', errback);
729 | } else if (this.events.error) {
730 | //If no errback already, but there are error listeners
731 | //on this module, set up an errback to pass to the deps.
732 | errback = bind(this, function (err) {
733 | this.emit('error', err);
734 | });
735 | }
736 |
737 | //Do a copy of the dependency array, so that
738 | //source inputs are not modified. For example
739 | //"shim" deps are passed in here directly, and
740 | //doing a direct modification of the depMaps array
741 | //would affect that config.
742 | this.depMaps = depMaps && depMaps.slice(0);
743 |
744 | this.errback = errback;
745 |
746 | //Indicate this module has be initialized
747 | this.inited = true;
748 |
749 | this.ignore = options.ignore;
750 |
751 | //Could have option to init this module in enabled mode,
752 | //or could have been previously marked as enabled. However,
753 | //the dependencies are not known until init is called. So
754 | //if enabled previously, now trigger dependencies as enabled.
755 | if (options.enabled || this.enabled) {
756 | //Enable this module and dependencies.
757 | //Will call this.check()
758 | this.enable();
759 | } else {
760 | this.check();
761 | }
762 | },
763 |
764 | defineDep: function (i, depExports) {
765 | //Because of cycles, defined callback for a given
766 | //export can be called more than once.
767 | if (!this.depMatched[i]) {
768 | this.depMatched[i] = true;
769 | this.depCount -= 1;
770 | this.depExports[i] = depExports;
771 | }
772 | },
773 |
774 | fetch: function () {
775 | if (this.fetched) {
776 | return;
777 | }
778 | this.fetched = true;
779 |
780 | context.startTime = (new Date()).getTime();
781 |
782 | var map = this.map;
783 |
784 | //If the manager is for a plugin managed resource,
785 | //ask the plugin to load it now.
786 | if (this.shim) {
787 | context.makeRequire(this.map, {
788 | enableBuildCallback: true
789 | })(this.shim.deps || [], bind(this, function () {
790 | return map.prefix ? this.callPlugin() : this.load();
791 | }));
792 | } else {
793 | //Regular dependency.
794 | return map.prefix ? this.callPlugin() : this.load();
795 | }
796 | },
797 |
798 | load: function () {
799 | var url = this.map.url;
800 |
801 | //Regular dependency.
802 | if (!urlFetched[url]) {
803 | urlFetched[url] = true;
804 | context.load(this.map.id, url);
805 | }
806 | },
807 |
808 | /**
809 | * Checks is the module is ready to define itself, and if so,
810 | * define it.
811 | */
812 | check: function () {
813 | if (!this.enabled || this.enabling) {
814 | return;
815 | }
816 |
817 | var err, cjsModule,
818 | id = this.map.id,
819 | depExports = this.depExports,
820 | exports = this.exports,
821 | factory = this.factory;
822 |
823 | if (!this.inited) {
824 | this.fetch();
825 | } else if (this.error) {
826 | this.emit('error', this.error);
827 | } else if (!this.defining) {
828 | //The factory could trigger another require call
829 | //that would result in checking this module to
830 | //define itself again. If already in the process
831 | //of doing that, skip this work.
832 | this.defining = true;
833 |
834 | if (this.depCount < 1 && !this.defined) {
835 | if (isFunction(factory)) {
836 | //If there is an error listener, favor passing
837 | //to that instead of throwing an error.
838 | if (this.events.error) {
839 | try {
840 | exports = context.execCb(id, factory, depExports, exports);
841 | } catch (e) {
842 | err = e;
843 | }
844 | } else {
845 | exports = context.execCb(id, factory, depExports, exports);
846 | }
847 |
848 | if (this.map.isDefine) {
849 | //If setting exports via 'module' is in play,
850 | //favor that over return value and exports. After that,
851 | //favor a non-undefined return value over exports use.
852 | cjsModule = this.module;
853 | if (cjsModule &&
854 | cjsModule.exports !== undefined &&
855 | //Make sure it is not already the exports value
856 | cjsModule.exports !== this.exports) {
857 | exports = cjsModule.exports;
858 | } else if (exports === undefined && this.usingExports) {
859 | //exports already set the defined value.
860 | exports = this.exports;
861 | }
862 | }
863 |
864 | if (err) {
865 | err.requireMap = this.map;
866 | err.requireModules = [this.map.id];
867 | err.requireType = 'define';
868 | return onError((this.error = err));
869 | }
870 |
871 | } else {
872 | //Just a literal value
873 | exports = factory;
874 | }
875 |
876 | this.exports = exports;
877 |
878 | if (this.map.isDefine && !this.ignore) {
879 | defined[id] = exports;
880 |
881 | if (req.onResourceLoad) {
882 | req.onResourceLoad(context, this.map, this.depMaps);
883 | }
884 | }
885 |
886 | //Clean up
887 | delete registry[id];
888 |
889 | this.defined = true;
890 | }
891 |
892 | //Finished the define stage. Allow calling check again
893 | //to allow define notifications below in the case of a
894 | //cycle.
895 | this.defining = false;
896 |
897 | if (this.defined && !this.defineEmitted) {
898 | this.defineEmitted = true;
899 | this.emit('defined', this.exports);
900 | this.defineEmitComplete = true;
901 | }
902 |
903 | }
904 | },
905 |
906 | callPlugin: function () {
907 | var map = this.map,
908 | id = map.id,
909 | //Map already normalized the prefix.
910 | pluginMap = makeModuleMap(map.prefix);
911 |
912 | //Mark this as a dependency for this plugin, so it
913 | //can be traced for cycles.
914 | this.depMaps.push(pluginMap);
915 |
916 | on(pluginMap, 'defined', bind(this, function (plugin) {
917 | var load, normalizedMap, normalizedMod,
918 | name = this.map.name,
919 | parentName = this.map.parentMap ? this.map.parentMap.name : null,
920 | localRequire = context.makeRequire(map.parentMap, {
921 | enableBuildCallback: true,
922 | skipMap: true
923 | });
924 |
925 | //If current map is not normalized, wait for that
926 | //normalized name to load instead of continuing.
927 | if (this.map.unnormalized) {
928 | //Normalize the ID if the plugin allows it.
929 | if (plugin.normalize) {
930 | name = plugin.normalize(name, function (name) {
931 | return normalize(name, parentName, true);
932 | }) || '';
933 | }
934 |
935 | //prefix and name should already be normalized, no need
936 | //for applying map config again either.
937 | normalizedMap = makeModuleMap(map.prefix + '!' + name,
938 | this.map.parentMap);
939 | on(normalizedMap,
940 | 'defined', bind(this, function (value) {
941 | this.init([], function () { return value; }, null, {
942 | enabled: true,
943 | ignore: true
944 | });
945 | }));
946 |
947 | normalizedMod = getOwn(registry, normalizedMap.id);
948 | if (normalizedMod) {
949 | //Mark this as a dependency for this plugin, so it
950 | //can be traced for cycles.
951 | this.depMaps.push(normalizedMap);
952 |
953 | if (this.events.error) {
954 | normalizedMod.on('error', bind(this, function (err) {
955 | this.emit('error', err);
956 | }));
957 | }
958 | normalizedMod.enable();
959 | }
960 |
961 | return;
962 | }
963 |
964 | load = bind(this, function (value) {
965 | this.init([], function () { return value; }, null, {
966 | enabled: true
967 | });
968 | });
969 |
970 | load.error = bind(this, function (err) {
971 | this.inited = true;
972 | this.error = err;
973 | err.requireModules = [id];
974 |
975 | //Remove temp unnormalized modules for this module,
976 | //since they will never be resolved otherwise now.
977 | eachProp(registry, function (mod) {
978 | if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
979 | cleanRegistry(mod.map.id);
980 | }
981 | });
982 |
983 | onError(err);
984 | });
985 |
986 | //Allow plugins to load other code without having to know the
987 | //context or how to 'complete' the load.
988 | load.fromText = bind(this, function (text, textAlt) {
989 | /*jslint evil: true */
990 | var moduleName = map.name,
991 | moduleMap = makeModuleMap(moduleName),
992 | hasInteractive = useInteractive;
993 |
994 | //As of 2.1.0, support just passing the text, to reinforce
995 | //fromText only being called once per resource. Still
996 | //support old style of passing moduleName but discard
997 | //that moduleName in favor of the internal ref.
998 | if (textAlt) {
999 | text = textAlt;
1000 | }
1001 |
1002 | //Turn off interactive script matching for IE for any define
1003 | //calls in the text, then turn it back on at the end.
1004 | if (hasInteractive) {
1005 | useInteractive = false;
1006 | }
1007 |
1008 | //Prime the system by creating a module instance for
1009 | //it.
1010 | getModule(moduleMap);
1011 |
1012 | //Transfer any config to this other module.
1013 | if (hasProp(config.config, id)) {
1014 | config.config[moduleName] = config.config[id];
1015 | }
1016 |
1017 | try {
1018 | req.exec(text);
1019 | } catch (e) {
1020 | throw new Error('fromText eval for ' + moduleName +
1021 | ' failed: ' + e);
1022 | }
1023 |
1024 | if (hasInteractive) {
1025 | useInteractive = true;
1026 | }
1027 |
1028 | //Mark this as a dependency for the plugin
1029 | //resource
1030 | this.depMaps.push(moduleMap);
1031 |
1032 | //Support anonymous modules.
1033 | context.completeLoad(moduleName);
1034 |
1035 | //Bind the value of that module to the value for this
1036 | //resource ID.
1037 | localRequire([moduleName], load);
1038 | });
1039 |
1040 | //Use parentName here since the plugin's name is not reliable,
1041 | //could be some weird string with no path that actually wants to
1042 | //reference the parentName's path.
1043 | plugin.load(map.name, localRequire, load, config);
1044 | }));
1045 |
1046 | context.enable(pluginMap, this);
1047 | this.pluginMaps[pluginMap.id] = pluginMap;
1048 | },
1049 |
1050 | enable: function () {
1051 | this.enabled = true;
1052 |
1053 | //Set flag mentioning that the module is enabling,
1054 | //so that immediate calls to the defined callbacks
1055 | //for dependencies do not trigger inadvertent load
1056 | //with the depCount still being zero.
1057 | this.enabling = true;
1058 |
1059 | //Enable each dependency
1060 | each(this.depMaps, bind(this, function (depMap, i) {
1061 | var id, mod, handler;
1062 |
1063 | if (typeof depMap === 'string') {
1064 | //Dependency needs to be converted to a depMap
1065 | //and wired up to this module.
1066 | depMap = makeModuleMap(depMap,
1067 | (this.map.isDefine ? this.map : this.map.parentMap),
1068 | false,
1069 | !this.skipMap);
1070 | this.depMaps[i] = depMap;
1071 |
1072 | handler = getOwn(handlers, depMap.id);
1073 |
1074 | if (handler) {
1075 | this.depExports[i] = handler(this);
1076 | return;
1077 | }
1078 |
1079 | this.depCount += 1;
1080 |
1081 | on(depMap, 'defined', bind(this, function (depExports) {
1082 | this.defineDep(i, depExports);
1083 | this.check();
1084 | }));
1085 |
1086 | if (this.errback) {
1087 | on(depMap, 'error', this.errback);
1088 | }
1089 | }
1090 |
1091 | id = depMap.id;
1092 | mod = registry[id];
1093 |
1094 | //Skip special modules like 'require', 'exports', 'module'
1095 | //Also, don't call enable if it is already enabled,
1096 | //important in circular dependency cases.
1097 | if (!hasProp(handlers, id) && mod && !mod.enabled) {
1098 | context.enable(depMap, this);
1099 | }
1100 | }));
1101 |
1102 | //Enable each plugin that is used in
1103 | //a dependency
1104 | eachProp(this.pluginMaps, bind(this, function (pluginMap) {
1105 | var mod = getOwn(registry, pluginMap.id);
1106 | if (mod && !mod.enabled) {
1107 | context.enable(pluginMap, this);
1108 | }
1109 | }));
1110 |
1111 | this.enabling = false;
1112 |
1113 | this.check();
1114 | },
1115 |
1116 | on: function (name, cb) {
1117 | var cbs = this.events[name];
1118 | if (!cbs) {
1119 | cbs = this.events[name] = [];
1120 | }
1121 | cbs.push(cb);
1122 | },
1123 |
1124 | emit: function (name, evt) {
1125 | each(this.events[name], function (cb) {
1126 | cb(evt);
1127 | });
1128 | if (name === 'error') {
1129 | //Now that the error handler was triggered, remove
1130 | //the listeners, since this broken Module instance
1131 | //can stay around for a while in the registry.
1132 | delete this.events[name];
1133 | }
1134 | }
1135 | };
1136 |
1137 | function callGetModule(args) {
1138 | //Skip modules already defined.
1139 | if (!hasProp(defined, args[0])) {
1140 | getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
1141 | }
1142 | }
1143 |
1144 | function removeListener(node, func, name, ieName) {
1145 | //Favor detachEvent because of IE9
1146 | //issue, see attachEvent/addEventListener comment elsewhere
1147 | //in this file.
1148 | if (node.detachEvent && !isOpera) {
1149 | //Probably IE. If not it will throw an error, which will be
1150 | //useful to know.
1151 | if (ieName) {
1152 | node.detachEvent(ieName, func);
1153 | }
1154 | } else {
1155 | node.removeEventListener(name, func, false);
1156 | }
1157 | }
1158 |
1159 | /**
1160 | * Given an event from a script node, get the requirejs info from it,
1161 | * and then removes the event listeners on the node.
1162 | * @param {Event} evt
1163 | * @returns {Object}
1164 | */
1165 | function getScriptData(evt) {
1166 | //Using currentTarget instead of target for Firefox 2.0's sake. Not
1167 | //all old browsers will be supported, but this one was easy enough
1168 | //to support and still makes sense.
1169 | var node = evt.currentTarget || evt.srcElement;
1170 |
1171 | //Remove the listeners once here.
1172 | removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
1173 | removeListener(node, context.onScriptError, 'error');
1174 |
1175 | return {
1176 | node: node,
1177 | id: node && node.getAttribute('data-requiremodule')
1178 | };
1179 | }
1180 |
1181 | function intakeDefines() {
1182 | var args;
1183 |
1184 | //Any defined modules in the global queue, intake them now.
1185 | takeGlobalQueue();
1186 |
1187 | //Make sure any remaining defQueue items get properly processed.
1188 | while (defQueue.length) {
1189 | args = defQueue.shift();
1190 | if (args[0] === null) {
1191 | return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
1192 | } else {
1193 | //args are id, deps, factory. Should be normalized by the
1194 | //define() function.
1195 | callGetModule(args);
1196 | }
1197 | }
1198 | }
1199 |
1200 | context = {
1201 | config: config,
1202 | contextName: contextName,
1203 | registry: registry,
1204 | defined: defined,
1205 | urlFetched: urlFetched,
1206 | defQueue: defQueue,
1207 | Module: Module,
1208 | makeModuleMap: makeModuleMap,
1209 | nextTick: req.nextTick,
1210 |
1211 | /**
1212 | * Set a configuration for the context.
1213 | * @param {Object} cfg config object to integrate.
1214 | */
1215 | configure: function (cfg) {
1216 | //Make sure the baseUrl ends in a slash.
1217 | if (cfg.baseUrl) {
1218 | if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
1219 | cfg.baseUrl += '/';
1220 | }
1221 | }
1222 |
1223 | //Save off the paths and packages since they require special processing,
1224 | //they are additive.
1225 | var pkgs = config.pkgs,
1226 | shim = config.shim,
1227 | objs = {
1228 | paths: true,
1229 | config: true,
1230 | map: true
1231 | };
1232 |
1233 | eachProp(cfg, function (value, prop) {
1234 | if (objs[prop]) {
1235 | if (prop === 'map') {
1236 | mixin(config[prop], value, true, true);
1237 | } else {
1238 | mixin(config[prop], value, true);
1239 | }
1240 | } else {
1241 | config[prop] = value;
1242 | }
1243 | });
1244 |
1245 | //Merge shim
1246 | if (cfg.shim) {
1247 | eachProp(cfg.shim, function (value, id) {
1248 | //Normalize the structure
1249 | if (isArray(value)) {
1250 | value = {
1251 | deps: value
1252 | };
1253 | }
1254 | if ((value.exports || value.init) && !value.exportsFn) {
1255 | value.exportsFn = context.makeShimExports(value);
1256 | }
1257 | shim[id] = value;
1258 | });
1259 | config.shim = shim;
1260 | }
1261 |
1262 | //Adjust packages if necessary.
1263 | if (cfg.packages) {
1264 | each(cfg.packages, function (pkgObj) {
1265 | var location;
1266 |
1267 | pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
1268 | location = pkgObj.location;
1269 |
1270 | //Create a brand new object on pkgs, since currentPackages can
1271 | //be passed in again, and config.pkgs is the internal transformed
1272 | //state for all package configs.
1273 | pkgs[pkgObj.name] = {
1274 | name: pkgObj.name,
1275 | location: location || pkgObj.name,
1276 | //Remove leading dot in main, so main paths are normalized,
1277 | //and remove any trailing .js, since different package
1278 | //envs have different conventions: some use a module name,
1279 | //some use a file name.
1280 | main: (pkgObj.main || 'main')
1281 | .replace(currDirRegExp, '')
1282 | .replace(jsSuffixRegExp, '')
1283 | };
1284 | });
1285 |
1286 | //Done with modifications, assing packages back to context config
1287 | config.pkgs = pkgs;
1288 | }
1289 |
1290 | //If there are any "waiting to execute" modules in the registry,
1291 | //update the maps for them, since their info, like URLs to load,
1292 | //may have changed.
1293 | eachProp(registry, function (mod, id) {
1294 | //If module already has init called, since it is too
1295 | //late to modify them, and ignore unnormalized ones
1296 | //since they are transient.
1297 | if (!mod.inited && !mod.map.unnormalized) {
1298 | mod.map = makeModuleMap(id);
1299 | }
1300 | });
1301 |
1302 | //If a deps array or a config callback is specified, then call
1303 | //require with those args. This is useful when require is defined as a
1304 | //config object before require.js is loaded.
1305 | if (cfg.deps || cfg.callback) {
1306 | context.require(cfg.deps || [], cfg.callback);
1307 | }
1308 | },
1309 |
1310 | makeShimExports: function (value) {
1311 | function fn() {
1312 | var ret;
1313 | if (value.init) {
1314 | ret = value.init.apply(global, arguments);
1315 | }
1316 | return ret || (value.exports && getGlobal(value.exports));
1317 | }
1318 | return fn;
1319 | },
1320 |
1321 | makeRequire: function (relMap, options) {
1322 | options = options || {};
1323 |
1324 | function localRequire(deps, callback, errback) {
1325 | var id, map, requireMod;
1326 |
1327 | if (options.enableBuildCallback && callback && isFunction(callback)) {
1328 | callback.__requireJsBuild = true;
1329 | }
1330 |
1331 | if (typeof deps === 'string') {
1332 | if (isFunction(callback)) {
1333 | //Invalid call
1334 | return onError(makeError('requireargs', 'Invalid require call'), errback);
1335 | }
1336 |
1337 | //If require|exports|module are requested, get the
1338 | //value for them from the special handlers. Caveat:
1339 | //this only works while module is being defined.
1340 | if (relMap && hasProp(handlers, deps)) {
1341 | return handlers[deps](registry[relMap.id]);
1342 | }
1343 |
1344 | //Synchronous access to one module. If require.get is
1345 | //available (as in the Node adapter), prefer that.
1346 | if (req.get) {
1347 | return req.get(context, deps, relMap);
1348 | }
1349 |
1350 | //Normalize module name, if it contains . or ..
1351 | map = makeModuleMap(deps, relMap, false, true);
1352 | id = map.id;
1353 |
1354 | if (!hasProp(defined, id)) {
1355 | return onError(makeError('notloaded', 'Module name "' +
1356 | id +
1357 | '" has not been loaded yet for context: ' +
1358 | contextName +
1359 | (relMap ? '' : '. Use require([])')));
1360 | }
1361 | return defined[id];
1362 | }
1363 |
1364 | //Grab defines waiting in the global queue.
1365 | intakeDefines();
1366 |
1367 | //Mark all the dependencies as needing to be loaded.
1368 | context.nextTick(function () {
1369 | //Some defines could have been added since the
1370 | //require call, collect them.
1371 | intakeDefines();
1372 |
1373 | requireMod = getModule(makeModuleMap(null, relMap));
1374 |
1375 | //Store if map config should be applied to this require
1376 | //call for dependencies.
1377 | requireMod.skipMap = options.skipMap;
1378 |
1379 | requireMod.init(deps, callback, errback, {
1380 | enabled: true
1381 | });
1382 |
1383 | checkLoaded();
1384 | });
1385 |
1386 | return localRequire;
1387 | }
1388 |
1389 | mixin(localRequire, {
1390 | isBrowser: isBrowser,
1391 |
1392 | /**
1393 | * Converts a module name + .extension into an URL path.
1394 | * *Requires* the use of a module name. It does not support using
1395 | * plain URLs like nameToUrl.
1396 | */
1397 | toUrl: function (moduleNamePlusExt) {
1398 | var index = moduleNamePlusExt.lastIndexOf('.'),
1399 | ext = null;
1400 |
1401 | if (index !== -1) {
1402 | ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
1403 | moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
1404 | }
1405 |
1406 | return context.nameToUrl(normalize(moduleNamePlusExt,
1407 | relMap && relMap.id, true), ext);
1408 | },
1409 |
1410 | defined: function (id) {
1411 | return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
1412 | },
1413 |
1414 | specified: function (id) {
1415 | id = makeModuleMap(id, relMap, false, true).id;
1416 | return hasProp(defined, id) || hasProp(registry, id);
1417 | }
1418 | });
1419 |
1420 | //Only allow undef on top level require calls
1421 | if (!relMap) {
1422 | localRequire.undef = function (id) {
1423 | //Bind any waiting define() calls to this context,
1424 | //fix for #408
1425 | takeGlobalQueue();
1426 |
1427 | var map = makeModuleMap(id, relMap, true),
1428 | mod = getOwn(registry, id);
1429 |
1430 | delete defined[id];
1431 | delete urlFetched[map.url];
1432 | delete undefEvents[id];
1433 |
1434 | if (mod) {
1435 | //Hold on to listeners in case the
1436 | //module will be attempted to be reloaded
1437 | //using a different config.
1438 | if (mod.events.defined) {
1439 | undefEvents[id] = mod.events;
1440 | }
1441 |
1442 | cleanRegistry(id);
1443 | }
1444 | };
1445 | }
1446 |
1447 | return localRequire;
1448 | },
1449 |
1450 | /**
1451 | * Called to enable a module if it is still in the registry
1452 | * awaiting enablement. parent module is passed in for context,
1453 | * used by the optimizer.
1454 | */
1455 | enable: function (depMap, parent) {
1456 | var mod = getOwn(registry, depMap.id);
1457 | if (mod) {
1458 | getModule(depMap).enable();
1459 | }
1460 | },
1461 |
1462 | /**
1463 | * Internal method used by environment adapters to complete a load event.
1464 | * A load event could be a script load or just a load pass from a synchronous
1465 | * load call.
1466 | * @param {String} moduleName the name of the module to potentially complete.
1467 | */
1468 | completeLoad: function (moduleName) {
1469 | var found, args, mod,
1470 | shim = getOwn(config.shim, moduleName) || {},
1471 | shExports = shim.exports;
1472 |
1473 | takeGlobalQueue();
1474 |
1475 | while (defQueue.length) {
1476 | args = defQueue.shift();
1477 | if (args[0] === null) {
1478 | args[0] = moduleName;
1479 | //If already found an anonymous module and bound it
1480 | //to this name, then this is some other anon module
1481 | //waiting for its completeLoad to fire.
1482 | if (found) {
1483 | break;
1484 | }
1485 | found = true;
1486 | } else if (args[0] === moduleName) {
1487 | //Found matching define call for this script!
1488 | found = true;
1489 | }
1490 |
1491 | callGetModule(args);
1492 | }
1493 |
1494 | //Do this after the cycle of callGetModule in case the result
1495 | //of those calls/init calls changes the registry.
1496 | mod = getOwn(registry, moduleName);
1497 |
1498 | if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
1499 | if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
1500 | if (hasPathFallback(moduleName)) {
1501 | return;
1502 | } else {
1503 | return onError(makeError('nodefine',
1504 | 'No define call for ' + moduleName,
1505 | null,
1506 | [moduleName]));
1507 | }
1508 | } else {
1509 | //A script that does not call define(), so just simulate
1510 | //the call for it.
1511 | callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
1512 | }
1513 | }
1514 |
1515 | checkLoaded();
1516 | },
1517 |
1518 | /**
1519 | * Converts a module name to a file path. Supports cases where
1520 | * moduleName may actually be just an URL.
1521 | * Note that it **does not** call normalize on the moduleName,
1522 | * it is assumed to have already been normalized. This is an
1523 | * internal API, not a public one. Use toUrl for the public API.
1524 | */
1525 | nameToUrl: function (moduleName, ext) {
1526 | var paths, pkgs, pkg, pkgPath, syms, i, parentModule, url,
1527 | parentPath;
1528 |
1529 | //If a colon is in the URL, it indicates a protocol is used and it is just
1530 | //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
1531 | //or ends with .js, then assume the user meant to use an url and not a module id.
1532 | //The slash is important for protocol-less URLs as well as full paths.
1533 | if (req.jsExtRegExp.test(moduleName)) {
1534 | //Just a plain path, not module name lookup, so just return it.
1535 | //Add extension if it is included. This is a bit wonky, only non-.js things pass
1536 | //an extension, this method probably needs to be reworked.
1537 | url = moduleName + (ext || '');
1538 | } else {
1539 | //A module that needs to be converted to a path.
1540 | paths = config.paths;
1541 | pkgs = config.pkgs;
1542 |
1543 | syms = moduleName.split('/');
1544 | //For each module name segment, see if there is a path
1545 | //registered for it. Start with most specific name
1546 | //and work up from it.
1547 | for (i = syms.length; i > 0; i -= 1) {
1548 | parentModule = syms.slice(0, i).join('/');
1549 | pkg = getOwn(pkgs, parentModule);
1550 | parentPath = getOwn(paths, parentModule);
1551 | if (parentPath) {
1552 | //If an array, it means there are a few choices,
1553 | //Choose the one that is desired
1554 | if (isArray(parentPath)) {
1555 | parentPath = parentPath[0];
1556 | }
1557 | syms.splice(0, i, parentPath);
1558 | break;
1559 | } else if (pkg) {
1560 | //If module name is just the package name, then looking
1561 | //for the main module.
1562 | if (moduleName === pkg.name) {
1563 | pkgPath = pkg.location + '/' + pkg.main;
1564 | } else {
1565 | pkgPath = pkg.location;
1566 | }
1567 | syms.splice(0, i, pkgPath);
1568 | break;
1569 | }
1570 | }
1571 |
1572 | //Join the path parts together, then figure out if baseUrl is needed.
1573 | url = syms.join('/');
1574 | url += (ext || (/\?/.test(url) ? '' : '.js'));
1575 | url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
1576 | }
1577 |
1578 | return config.urlArgs ? url +
1579 | ((url.indexOf('?') === -1 ? '?' : '&') +
1580 | config.urlArgs) : url;
1581 | },
1582 |
1583 | //Delegates to req.load. Broken out as a separate function to
1584 | //allow overriding in the optimizer.
1585 | load: function (id, url) {
1586 | req.load(context, id, url);
1587 | },
1588 |
1589 | /**
1590 | * Executes a module callack function. Broken out as a separate function
1591 | * solely to allow the build system to sequence the files in the built
1592 | * layer in the right sequence.
1593 | *
1594 | * @private
1595 | */
1596 | execCb: function (name, callback, args, exports) {
1597 | return callback.apply(exports, args);
1598 | },
1599 |
1600 | /**
1601 | * callback for script loads, used to check status of loading.
1602 | *
1603 | * @param {Event} evt the event from the browser for the script
1604 | * that was loaded.
1605 | */
1606 | onScriptLoad: function (evt) {
1607 | //Using currentTarget instead of target for Firefox 2.0's sake. Not
1608 | //all old browsers will be supported, but this one was easy enough
1609 | //to support and still makes sense.
1610 | if (evt.type === 'load' ||
1611 | (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
1612 | //Reset interactive script so a script node is not held onto for
1613 | //to long.
1614 | interactiveScript = null;
1615 |
1616 | //Pull out the name of the module and the context.
1617 | var data = getScriptData(evt);
1618 | context.completeLoad(data.id);
1619 | }
1620 | },
1621 |
1622 | /**
1623 | * Callback for script errors.
1624 | */
1625 | onScriptError: function (evt) {
1626 | var data = getScriptData(evt);
1627 | if (!hasPathFallback(data.id)) {
1628 | return onError(makeError('scripterror', 'Script error', evt, [data.id]));
1629 | }
1630 | }
1631 | };
1632 |
1633 | context.require = context.makeRequire();
1634 | return context;
1635 | }
1636 |
1637 | /**
1638 | * Main entry point.
1639 | *
1640 | * If the only argument to require is a string, then the module that
1641 | * is represented by that string is fetched for the appropriate context.
1642 | *
1643 | * If the first argument is an array, then it will be treated as an array
1644 | * of dependency string names to fetch. An optional function callback can
1645 | * be specified to execute when all of those dependencies are available.
1646 | *
1647 | * Make a local req variable to help Caja compliance (it assumes things
1648 | * on a require that are not standardized), and to give a short
1649 | * name for minification/local scope use.
1650 | */
1651 | req = requirejs = function (deps, callback, errback, optional) {
1652 |
1653 | //Find the right context, use default
1654 | var context, config,
1655 | contextName = defContextName;
1656 |
1657 | // Determine if have config object in the call.
1658 | if (!isArray(deps) && typeof deps !== 'string') {
1659 | // deps is a config object
1660 | config = deps;
1661 | if (isArray(callback)) {
1662 | // Adjust args if there are dependencies
1663 | deps = callback;
1664 | callback = errback;
1665 | errback = optional;
1666 | } else {
1667 | deps = [];
1668 | }
1669 | }
1670 |
1671 | if (config && config.context) {
1672 | contextName = config.context;
1673 | }
1674 |
1675 | context = getOwn(contexts, contextName);
1676 | if (!context) {
1677 | context = contexts[contextName] = req.s.newContext(contextName);
1678 | }
1679 |
1680 | if (config) {
1681 | context.configure(config);
1682 | }
1683 |
1684 | return context.require(deps, callback, errback);
1685 | };
1686 |
1687 | /**
1688 | * Support require.config() to make it easier to cooperate with other
1689 | * AMD loaders on globally agreed names.
1690 | */
1691 | req.config = function (config) {
1692 | return req(config);
1693 | };
1694 |
1695 | /**
1696 | * Execute something after the current tick
1697 | * of the event loop. Override for other envs
1698 | * that have a better solution than setTimeout.
1699 | * @param {Function} fn function to execute later.
1700 | */
1701 | req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
1702 | setTimeout(fn, 4);
1703 | } : function (fn) { fn(); };
1704 |
1705 | /**
1706 | * Export require as a global, but only if it does not already exist.
1707 | */
1708 | if (!require) {
1709 | require = req;
1710 | }
1711 |
1712 | req.version = version;
1713 |
1714 | //Used to filter out dependencies that are already paths.
1715 | req.jsExtRegExp = /^\/|:|\?|\.js$/;
1716 | req.isBrowser = isBrowser;
1717 | s = req.s = {
1718 | contexts: contexts,
1719 | newContext: newContext
1720 | };
1721 |
1722 | //Create default context.
1723 | req({});
1724 |
1725 | //Exports some context-sensitive methods on global require.
1726 | each([
1727 | 'toUrl',
1728 | 'undef',
1729 | 'defined',
1730 | 'specified'
1731 | ], function (prop) {
1732 | //Reference from contexts instead of early binding to default context,
1733 | //so that during builds, the latest instance of the default context
1734 | //with its config gets used.
1735 | req[prop] = function () {
1736 | var ctx = contexts[defContextName];
1737 | return ctx.require[prop].apply(ctx, arguments);
1738 | };
1739 | });
1740 |
1741 | if (isBrowser) {
1742 | head = s.head = document.getElementsByTagName('head')[0];
1743 | //If BASE tag is in play, using appendChild is a problem for IE6.
1744 | //When that browser dies, this can be removed. Details in this jQuery bug:
1745 | //http://dev.jquery.com/ticket/2709
1746 | baseElement = document.getElementsByTagName('base')[0];
1747 | if (baseElement) {
1748 | head = s.head = baseElement.parentNode;
1749 | }
1750 | }
1751 |
1752 | /**
1753 | * Any errors that require explicitly generates will be passed to this
1754 | * function. Intercept/override it if you want custom error handling.
1755 | * @param {Error} err the error object.
1756 | */
1757 | req.onError = function (err) {
1758 | throw err;
1759 | };
1760 |
1761 | /**
1762 | * Does the request to load a module for the browser case.
1763 | * Make this a separate function to allow other environments
1764 | * to override it.
1765 | *
1766 | * @param {Object} context the require context to find state.
1767 | * @param {String} moduleName the name of the module.
1768 | * @param {Object} url the URL to the module.
1769 | */
1770 | req.load = function (context, moduleName, url) {
1771 | var config = (context && context.config) || {},
1772 | node;
1773 | if (isBrowser) {
1774 | //In the browser so use a script tag
1775 | node = config.xhtml ?
1776 | document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
1777 | document.createElement('script');
1778 | node.type = config.scriptType || 'text/javascript';
1779 | node.charset = 'utf-8';
1780 | node.async = true;
1781 |
1782 | node.setAttribute('data-requirecontext', context.contextName);
1783 | node.setAttribute('data-requiremodule', moduleName);
1784 |
1785 | //Set up load listener. Test attachEvent first because IE9 has
1786 | //a subtle issue in its addEventListener and script onload firings
1787 | //that do not match the behavior of all other browsers with
1788 | //addEventListener support, which fire the onload event for a
1789 | //script right after the script execution. See:
1790 | //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
1791 | //UNFORTUNATELY Opera implements attachEvent but does not follow the script
1792 | //script execution mode.
1793 | if (node.attachEvent &&
1794 | //Check if node.attachEvent is artificially added by custom script or
1795 | //natively supported by browser
1796 | //read https://github.com/jrburke/requirejs/issues/187
1797 | //if we can NOT find [native code] then it must NOT natively supported.
1798 | //in IE8, node.attachEvent does not have toString()
1799 | //Note the test for "[native code" with no closing brace, see:
1800 | //https://github.com/jrburke/requirejs/issues/273
1801 | !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
1802 | !isOpera) {
1803 | //Probably IE. IE (at least 6-8) do not fire
1804 | //script onload right after executing the script, so
1805 | //we cannot tie the anonymous define call to a name.
1806 | //However, IE reports the script as being in 'interactive'
1807 | //readyState at the time of the define call.
1808 | useInteractive = true;
1809 |
1810 | node.attachEvent('onreadystatechange', context.onScriptLoad);
1811 | //It would be great to add an error handler here to catch
1812 | //404s in IE9+. However, onreadystatechange will fire before
1813 | //the error handler, so that does not help. If addEvenListener
1814 | //is used, then IE will fire error before load, but we cannot
1815 | //use that pathway given the connect.microsoft.com issue
1816 | //mentioned above about not doing the 'script execute,
1817 | //then fire the script load event listener before execute
1818 | //next script' that other browsers do.
1819 | //Best hope: IE10 fixes the issues,
1820 | //and then destroys all installs of IE 6-9.
1821 | //node.attachEvent('onerror', context.onScriptError);
1822 | } else {
1823 | node.addEventListener('load', context.onScriptLoad, false);
1824 | node.addEventListener('error', context.onScriptError, false);
1825 | }
1826 | node.src = url;
1827 |
1828 | //For some cache cases in IE 6-8, the script executes before the end
1829 | //of the appendChild execution, so to tie an anonymous define
1830 | //call to the module name (which is stored on the node), hold on
1831 | //to a reference to this node, but clear after the DOM insertion.
1832 | currentlyAddingScript = node;
1833 | if (baseElement) {
1834 | head.insertBefore(node, baseElement);
1835 | } else {
1836 | head.appendChild(node);
1837 | }
1838 | currentlyAddingScript = null;
1839 |
1840 | return node;
1841 | } else if (isWebWorker) {
1842 | //In a web worker, use importScripts. This is not a very
1843 | //efficient use of importScripts, importScripts will block until
1844 | //its script is downloaded and evaluated. However, if web workers
1845 | //are in play, the expectation that a build has been done so that
1846 | //only one script needs to be loaded anyway. This may need to be
1847 | //reevaluated if other use cases become common.
1848 | importScripts(url);
1849 |
1850 | //Account for anonymous modules
1851 | context.completeLoad(moduleName);
1852 | }
1853 | };
1854 |
1855 | function getInteractiveScript() {
1856 | if (interactiveScript && interactiveScript.readyState === 'interactive') {
1857 | return interactiveScript;
1858 | }
1859 |
1860 | eachReverse(scripts(), function (script) {
1861 | if (script.readyState === 'interactive') {
1862 | return (interactiveScript = script);
1863 | }
1864 | });
1865 | return interactiveScript;
1866 | }
1867 |
1868 | //Look for a data-main script attribute, which could also adjust the baseUrl.
1869 | if (isBrowser) {
1870 | //Figure out baseUrl. Get it from the script tag with require.js in it.
1871 | eachReverse(scripts(), function (script) {
1872 | //Set the 'head' where we can append children by
1873 | //using the script's parent.
1874 | if (!head) {
1875 | head = script.parentNode;
1876 | }
1877 |
1878 | //Look for a data-main attribute to set main script for the page
1879 | //to load. If it is there, the path to data main becomes the
1880 | //baseUrl, if it is not already set.
1881 | dataMain = script.getAttribute('data-main');
1882 | if (dataMain) {
1883 | //Set final baseUrl if there is not already an explicit one.
1884 | if (!cfg.baseUrl) {
1885 | //Pull off the directory of data-main for use as the
1886 | //baseUrl.
1887 | src = dataMain.split('/');
1888 | mainScript = src.pop();
1889 | subPath = src.length ? src.join('/') + '/' : './';
1890 |
1891 | cfg.baseUrl = subPath;
1892 | dataMain = mainScript;
1893 | }
1894 |
1895 | //Strip off any trailing .js since dataMain is now
1896 | //like a module name.
1897 | dataMain = dataMain.replace(jsSuffixRegExp, '');
1898 |
1899 | //Put the data-main script in the files to load.
1900 | cfg.deps = cfg.deps ? cfg.deps.concat(dataMain) : [dataMain];
1901 |
1902 | return true;
1903 | }
1904 | });
1905 | }
1906 |
1907 | /**
1908 | * The function that handles definitions of modules. Differs from
1909 | * require() in that a string for the module should be the first argument,
1910 | * and the function to execute after dependencies are loaded should
1911 | * return a value to define the module corresponding to the first argument's
1912 | * name.
1913 | */
1914 | define = function (name, deps, callback) {
1915 | var node, context;
1916 |
1917 | //Allow for anonymous modules
1918 | if (typeof name !== 'string') {
1919 | //Adjust args appropriately
1920 | callback = deps;
1921 | deps = name;
1922 | name = null;
1923 | }
1924 |
1925 | //This module may not have dependencies
1926 | if (!isArray(deps)) {
1927 | callback = deps;
1928 | deps = [];
1929 | }
1930 |
1931 | //If no name, and callback is a function, then figure out if it a
1932 | //CommonJS thing with dependencies.
1933 | if (!deps.length && isFunction(callback)) {
1934 | //Remove comments from the callback string,
1935 | //look for require calls, and pull them into the dependencies,
1936 | //but only if there are function args.
1937 | if (callback.length) {
1938 | callback
1939 | .toString()
1940 | .replace(commentRegExp, '')
1941 | .replace(cjsRequireRegExp, function (match, dep) {
1942 | deps.push(dep);
1943 | });
1944 |
1945 | //May be a CommonJS thing even without require calls, but still
1946 | //could use exports, and module. Avoid doing exports and module
1947 | //work though if it just needs require.
1948 | //REQUIRES the function to expect the CommonJS variables in the
1949 | //order listed below.
1950 | deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
1951 | }
1952 | }
1953 |
1954 | //If in IE 6-8 and hit an anonymous define() call, do the interactive
1955 | //work.
1956 | if (useInteractive) {
1957 | node = currentlyAddingScript || getInteractiveScript();
1958 | if (node) {
1959 | if (!name) {
1960 | name = node.getAttribute('data-requiremodule');
1961 | }
1962 | context = contexts[node.getAttribute('data-requirecontext')];
1963 | }
1964 | }
1965 |
1966 | //Always save off evaluating the def call until the script onload handler.
1967 | //This allows multiple modules to be in a file without prematurely
1968 | //tracing dependencies, and allows for anonymous module support,
1969 | //where the module name is not known until the script onload event
1970 | //occurs. If no context, use the global queue, and get it processed
1971 | //in the onscript load callback.
1972 | (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
1973 | };
1974 |
1975 | define.amd = {
1976 | jQuery: true
1977 | };
1978 |
1979 |
1980 | /**
1981 | * Executes the text. Normally just uses eval, but can be modified
1982 | * to use a better, environment-specific call. Only used for transpiling
1983 | * loader plugins, not for plain JS modules.
1984 | * @param {String} text the text to execute/evaluate.
1985 | */
1986 | req.exec = function (text) {
1987 | /*jslint evil: true */
1988 | return eval(text);
1989 | };
1990 |
1991 | //Set up with config info.
1992 | req(cfg);
1993 | }(this));
1994 |
--------------------------------------------------------------------------------