@nocobase/client-v2 2.0.0-alpha.20

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