-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
617 lines (533 loc) · 17.8 KB
/
index.js
File metadata and controls
617 lines (533 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
/*
* needs.js
*
* (c) 2012-2017, Taka Kojima (taka@gigafied.com)
* Licensed under the MIT License
*
*/
;(function (root) {
var _loadQ = []
var _defineQ = []
var _loadedFiles = {}
var _modules = {}
var _head
// Used for checking circular dependencies.
var _dependencies = {}
// Used in various places, defined here for smaller file size
var _rem = ['require', 'exports', 'module']
// Configurable properties...
var _config = {}
var _baseUrl = ''
var _urlArgs = ''
var _waitSeconds = 10
var _paths = {}
function _isArray (a) {
return a instanceof Array
}
/**
* Normalizes a path/url, cleaning up duplicate slashes,
* takes care of `../` and `./` parts
*/
function _normalize (path, prevPath) {
// Replace any matches of "./" with "/"
path = path.replace(/(^|[^\.])(\.\/)/g, '$1') // eslint-disable-line no-useless-escape
// Replace any matches of "some/path/../" with "some/"
while (prevPath !== path) {
prevPath = path
path = path.replace(/([\w,\-]*[\/]{1,})([\.]{2,}\/)/g, '') // eslint-disable-line no-useless-escape
}
// Replace any matches of multiple "/" with a single "/"
return path.replace(/(\/{2,})/g, '/') // eslint-disable-line no-useless-escape
}
/**
* Similar to UNIX dirname, returns the parent path of another path.
*/
function _getContext (path) {
return path.substr(0, path.lastIndexOf('/'))
}
/**
* Given a path and context (optional), will normalize the url
* and convert a relative path to an absolute path.
*/
function _resolve (path, context) {
/**
* If the path does not start with a ".", it's relative
* to the base URL.
*/
context = (path.indexOf('.') < 0) ? '' : context
/**
* Never resolve "require", "module" and "exports" to absolute paths
* For plugins, only resolve the plugin path, not anything after the first "!"
*/
if (~_rem.indexOf(path) || ~path.indexOf('!')) {
// eslint-disable-next-line no-useless-escape
return path.replace(/([\d,\w,\s,\.\/]*)(?=\!)/, function ($0, $1) {
return _resolve($1, context)
})
}
return _normalize((context ? context + '/' : '') + path)
}
/**
* Loop through all of the items in _loadQ and if all modules in a given
* queue are defined, call the callback function associated with the queue.
*/
function _checkLoadQ (i, j, q, ready) {
for (i = _loadQ.length - 1; ~i && (q = _loadQ[i]); i--) {
ready = 1
for (j = q.m.length - 1; ~j && ready; j--) {
ready = _module(q.m[j])
}
if (ready) {
_loadQ.splice(i, 1)
require(q.m, q.cb)
}
}
}
/**
* Invokes the first anonymous item in _defineQ.
* Called from script.onLoad, and loader plugins .fromText() method.
*/
function _invokeAnonymousDefine (id, q) {
if (_defineQ.length) {
q = _defineQ.splice(0, 1)[0]
if (q) {
/**
* If the q is not null, it's an anonymous module and we have to invoke define()
* But first we need to tell the q which id to use, and set alreadyQed to true.
*/
q.splice(0, 0, id) // set the module id
q.splice(q.length, 0, 1) // set alreadyQed to true
define.apply(root, q)
}
}
}
/**
* Injects a script tag into the DOM
*/
function _inject (f, m, script, q, isReady, timeoutID) {
_head = _head || document.getElementsByTagName('head')[0]
script = document.createElement('script')
script.src = f
/**
* Bind to load events, we do it this way vs. addEventListener for IE support.
* No reason to use addEventListener() then fallback to script.onload, just always use script.onload
*/
script.onreadystatechange = script.onload = function () {
if (!script.readyState || script.readyState === 'complete' || script.readyState === 'loaded') {
clearTimeout(timeoutID)
script.onload = script.onreadystatechange = script.onerror = null
_invokeAnonymousDefine(m)
}
}
/**
* script.onerror gets called in two ways.
* The first, if a script request actually errors (i.e. a 404)
* The second, if a script takes more than X seconds to respond. Where X = _waitSeconds
*/
script.onerror = function (e) {
clearTimeout(timeoutID)
script.onload = script.onreadystatechange = script.onerror = null
throw new Error(f + ' failed to load.')
}
timeoutID = setTimeout(script.onerror, _waitSeconds * 1000)
// Prepend the script to document.head
_head.insertBefore(script, _head.firstChild)
return 1
}
/**
* Does all the loading of modules and plugins.
*/
function _load (modules, callback, context, i, q, m, f) {
q = {m: modules, cb: callback}
_loadQ.push(q)
for (i = 0; i < modules.length; i++) {
m = modules[i]
if (~m.indexOf('!')) {
/**
* If the module id has a "!"" in it, it's a plugin...
*/
_loadPluginModule(m, context, q, i)
continue
}
/**
* Otherwise, it's normal module, not a plugin. Inject the file into the DOM if
* the file has not been loaded yet and if the module is not yet defined.
*/
f = _getURL(m)
_loadedFiles[f] = (!_module(m) && !_loadedFiles[f]) ? _inject(f, m) : 1
}
}
/**
* Called by _load() and require() used for loading and getting plugin-type modules
*/
function _loadPluginModule (module, context, q, moduleIndex, definition, plugin, pluginPath) {
/**
* Set the plugin path. Plugins are stored differently than normal modules
* Essentially they are stored along with the context in a special "plugins"
* subpath. This allows modules to lookup plugins with the sync require("index!./foo:./bar") method
*/
pluginPath = (context ? context + '/' : '') + 'plugins/' + module.replace(/\//g, '_')
/*
* Update the path to this plugin in the queue
*/
if (q) {
q.m[moduleIndex] = pluginPath
}
module = module.split('!')
plugin = module.splice(0, 1)[0]
module = module.join('!')
/*
* Let's check to see if the module is already defined.
*/
definition = _module(pluginPath)
/*
* If the plugin is defined, no need to do anything else, so return.
* If q is null, return no matter what.
*/
if (!q || definition) {
return definition
}
/**
* Let's make sure the plugin is loaded before we do anything else.
*/
require(plugin, function (pluginModule) {
/**
* If the plugin module has a normalize() method defined, use it
*/
module = pluginModule.normalize
? pluginModule.normalize(module, function (path) {
return _resolve(path, context)
}) : _normalize(module)
function load (definition) {
_module(pluginPath, {exports: definition})
_checkLoadQ()
}
load.fromText = function (name, definition, dqL) {
/**
* Update the module path in the load queue with the newly computed module id
*/
q.m[moduleIndex] = pluginPath = name
/**
* Store the length of the define queue, to check against after the eval().
*/
dqL = _defineQ.length
/**
* Yes, eval/Function is bad, evil. I hate it, you hate it, but some plugins need it.
* If you don't have any plugins using fromText(), feel free to comment
* the entire load.fromText() out and re-minify the source.
* I use Function vs eval() because nothing executing through fromText() should need access
* to local vars, and Uglify does not mangle variables if it finds "eval()" in your code.
*/
new Function(definition)() // eslint-disable-line no-new-func
if (_defineQ.length - dqL) {
// Looks like there was a define call in the eval'ed text.
_invokeAnonymousDefine(pluginPath)
}
}
return pluginModule.load(
module,
require.localize(_getContext(plugin)),
load,
_config[plugin] || {}
)
})
}
/**
* Gets the module by `id`, otherwise if `def` is specified, define a new module.
*/
function _module (id, def, noExports, module) {
/**
* Always return back the id for "require", "module" and "exports",
* these are replaced by calling _swapValues
*/
if (~_rem.indexOf(id)) {
return id
}
/**
* If a definition was specified, set the module definition
*/
module = _modules[id] = def || _modules[id]
/**
* noExports is set to true from within define, to get back the full module object.
* If noExports != true, then we return the exports property of the module.
* If the module is not defined, return false
*/
return (module && module.exports) ? (noExports ? module : module.exports) : 0
}
/**
* Gets the URL for a module by `id`. Paths passed to _getURL must be absolute.
* To get URLs for relative paths use require.toUrl(id, context)
*/
function _getURL (id, prefix) {
/**
* If the path starts with a "/", or "http", it's an absolute URL
* If it's not an absolute URL, prefix the request with baseUrl
*/
prefix = (!id.indexOf('/') || !id.indexOf('http')) ? '' : _baseUrl
for (var p in _paths) {
id = id.replace(new RegExp('(^' + p + ')', 'g'), _paths[p])
}
return prefix + id + (id.indexOf('.') < 0 ? '.js' : '') + _urlArgs
}
/**
* Takes an array as the first argument, and an object as the second.
* Replaces any values found in the array, with values in the object.
*/
function _swapValues (a, s, j) {
for (var i in s) {
j = a.indexOf(i)
if (~j) {
a[j] = s[i]
}
}
return a
}
/**
* Stores dependencies for this module id.
* Also checks for any circular dependencies, if found, it defines those modules as empty objects temporarily
*/
function _resolveCircularReferences (id, dependencies, circulars, i, j, d, subDeps, sd, cid) {
_dependencies[id] = dependencies
/**
* Check for any dependencies that have circular references back to this module
*/
for (i = 0; i < dependencies.length; i++) {
d = dependencies[i]
subDeps = _dependencies[d]
if (subDeps) {
for (j = 0; j < subDeps.length; j++) {
sd = subDeps[j]
if (dependencies.indexOf(sd) < 0) {
if (sd !== id) {
dependencies.push(sd)
} else {
/**
* Circular reference detected, define circular
* references as empty modules to be defined later
*/
_module(d, {exports: {}})
}
}
}
}
}
}
/**
* Define modules. AMD-spec compliant.
*/
function define (id, dependencies, factory, alreadyQed, depsLoaded, module, facArgs, context, ri) {
if (typeof id !== 'string') {
/**
* No id means that this is an anonymous module,
* push it to a queue, to be defined upon onLoad
*/
factory = dependencies
dependencies = id
id = 0
_defineQ.push([dependencies, factory])
return
}
if (!_isArray(dependencies)) {
factory = dependencies
dependencies = []
}
if (!alreadyQed) {
/**
* ID was specified, so this is not an anonymous module,
* However, we still need to add an empty queue here to be cleaned up by onLoad
*/
_defineQ.push(0)
}
context = _getContext(id)
/**
* No dependencies, but the factory function is expecting arguments?
* This means that this is a CommonJS-type module...
*/
if (!dependencies.length && factory.length && typeof factory === 'function') {
/**
* Let's check for any references of sync-type require("moduleID")
*/
factory.toString()
.replace(/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg, '') // Remove any comments first
.replace(/(?:require)\(\s*["']([^'"\s]+)["']\s*\)/g, // Now check for any require("module") calls
function ($0, $1) {
if (dependencies.indexOf($1) < 0) {
/**
* We're not actually replacing anyting inside factory.toString(),
* but this is a nice, clean, convenient way to add any
* sync-type require() matches to the dependencies array.
*/
dependencies.push($1)
}
}
)
dependencies = (_rem.slice(0, factory.length)).concat(dependencies)
}
if (dependencies.length && !depsLoaded) {
/**
* Dependencies have not been loaded yet, so let's call require() to load them
* After the dependencies are loaded, reinvoke define() with depsLoaded set to true.
*/
_resolveCircularReferences(id, dependencies.slice(0))
require(dependencies, function () {
define(id, Array.prototype.slice.call(arguments, 0), factory, 1, 1)
}, context)
return
}
/**
* At this point, we know all dependencies have been loaded,
* and `dependencies` is an actually array of modules, not their ids
* Get the module if it has already been defined, otherwise let's create it
*/
module = _module(id, 0, 1)
module = module || {exports: {}}
module.id = id
module.url = _getURL(id)
if (typeof factory === 'function') {
/**
* If the factory is a function, we need to invoke it.
* First let's swap "require", "module" and "exports" with actual objects
*/
facArgs = _swapValues(
dependencies.length ? dependencies : (_rem.slice(0, factory.length)),
{
'require': require.localize(context),
'module': module,
'exports': module.exports
}
)
/**
* In some scenarios, the global require object might have slipped through,
* If so, replace it with a localized require.
*/
ri = facArgs.indexOf(require)
if (~ri) {
facArgs[ri] = require.localize(context)
}
/**
* If the function returns a value, then use that as the module definition
* Otherwise, assume the function modifies the exports object.
*/
module.exports = factory.apply(factory, facArgs) || module.exports
} else {
/**
* If the factory is not a function, set module.exports to whatever factory is
*/
module.exports = factory
}
/**
* Make the call to define the module.
*/
_module(id, module)
/**
* Clear the dependencies from the _dependencies object.
* _dependencies gets checked regularly to resolve circular dependencies
* and if this module had any circulars, they have already been resolved.
*/
delete _dependencies[id]
/**
* Now let's check the _loadQ
*/
_checkLoadQ()
}
/**
* Our define() function is an AMD implementation
*/
define.amd = {}
/**
* Asynchronously loads in js files for the modules specified.
* If all modules are already defined, the callback function is invoked immediately.
* If id(s) is specified but no callback function, attempt to get the module and
* return the module if it is defined, otherwise throw an Error.
*/
function require (ids, callback, context, plugins, i, modules) {
var plugin
if (!callback) {
/**
* If no callback is specified, then try to get the module by it's ID
*/
ids = _resolve(ids, context)
callback = _module(ids)
if (!callback) {
plugin = _loadPluginModule(ids, context)
if (plugin) return plugin
throw new Error(ids + ' is not defined.')
}
/**
* Otherwise return the module's definition.
*/
return callback
}
ids = (!_isArray(ids)) ? [ids] : ids
modules = []
for (i = 0; i < ids.length; i++) {
/**
* Convert all relative paths to absolute paths,
* Then check to see if the modules are already defined.
*/
ids[i] = _resolve(ids[i], context)
modules.push(_module(ids[i]))
}
if (~modules.indexOf(0)) {
/**
* If any one of the modules is not yet defined, we need to
* wait until the undefined module(s) are loaded, so call load() and return.
*/
_load(ids, callback, context)
return
}
/**
* Otherwise, we know all modules are already defined.
* Invoke the callback immediately, swapping "require" with the actual require function
*/
return callback.apply(root, _swapValues(modules, {'require': require}))
}
/**
* Configure NeedsJS, possible configuration properties are:
*
* - baseUrl
* - urlArgs
* - waitSeconds
*/
require.config = function (obj) {
_config = obj || {}
_baseUrl = _config.baseUrl || _baseUrl
// Add a trailing slash to baseUrl if needed.
_baseUrl += (_baseUrl && _baseUrl.charAt(_baseUrl.length - 1) !== '/') ? '/' : ''
_urlArgs = _config.urlArgs ? '?' + _config.urlArgs : _urlArgs
_waitSeconds = _config.waitSeconds || _waitSeconds
for (var p in _config.paths) {
_paths[p] = _config.paths[p]
}
}
/**
* Get a url for a relative id.
* You do not need to specify `context` if calling this from within a define() call,
* or a localized version of require()
*/
require.toUrl = function (id, context) {
return _getURL(_resolve(id, context))
}
/**
* Returns a localized version of require, so that modules do not need
* to specify their own id, when requiring relative modules, or resolving relative urls.
*/
require.localize = function (context) {
function localRequire (ids, callback) {
return require(ids, callback, context)
}
localRequire.toUrl = function (id) {
return require.toUrl(id, context)
}
return localRequire
}
/**
* Define global define/require methods, unless they are already defined.
*/
root.define = root.define || define
root.require = root.require || require
/**
* If we're in a browser environment use window as the root object
* Otherwise, assume we're in a CommonJS environment and use exports
*/
})(window || exports)