forked from stealjs/steal
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsteal.js
2466 lines (2210 loc) · 68.9 KB
/
steal.js
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// steal is a resource loader for JavaScript. It is broken into the following parts:
//
// - Helpers - basic utility methods used internally
// - AOP - aspect oriented code helpers
// - Deferred - a minimal deferred implementation
// - Uri - methods for dealing with urls
// - Api - steal's API
// - Resource - an object that represents a resource that is loaded and run and has dependencies.
// - Type - a type systems used to load and run different types of resources
// - Packages - used to define packages
// - Extensions - makes steal pre-load a type based on an extension (ex: .coffee)
// - Mapping - configures steal to load resources in a different location
// - Startup - startup code
// - jQuery - code to make jQuery's readWait work
// - Error Handling - detect scripts failing to load
// - Has option - used to specify that one resources contains multiple other resources
// - Window Load - API for knowing when the window has loaded and all scripts have loaded
// - Interactive - Code for IE
// - Options -
(function( win, undefined ) {
// ## Helpers ##
// The following are a list of helper methods used internally to steal
var
// check that we have a document
doc = win.document,
docEl = doc && doc.documentElement,
// a jQuery-like $.each
each = function( o, cb ) {
var i, len;
// weak array detection, but we only use this internally so don't
// pass it weird stuff
if ( typeof o.length == 'number' ) {
for ( i = 0, len = o.length; i < len; i++ ) {
cb.call(o[i], i, o[i], o)
}
} else {
for ( i in o ) {
cb.call(o[i], i, o[i], o)
}
}
return o;
},
// adds the item to the array only if it doesn't currently exist
uniquePush = function(arr, item){
for(var i=0; i < arr.length; i++){
if(arr[i] == item){
return;
}
}
arr.push(item)
},
// if o is a string
isString = function( o ) {
return typeof o == "string";
},
// if o is a function
isFn = function( o ) {
return typeof o == "function";
},
// dummy function
noop = function() {},
// creates an element
createElement = function( nodeName ) {
return doc.createElement(nodeName)
},
// creates a script tag
scriptTag = function() {
var start = createElement("script");
start.type = "text/javascript";
return start;
},
// minify-able verstion of getElementsByTagName
getElementsByTagName = function( tag ) {
return doc.getElementsByTagName(tag);
},
// A function that returns the head element
// creates and caches the lookup for faster
// performance.
head = function() {
var hd = getElementsByTagName("head")[0];
if (!hd ) {
hd = createElement("head");
docEl.insertBefore(hd, docEl.firstChild);
}
// replace head so it runs fast next time.
head = function() {
return hd;
}
return hd;
},
// extends one object with another
extend = function( d, s ) {
// only extend if we have something to extend
s && each(s, function( k ) {
d[k] = s[k];
});
return d;
},
// makes an array of things, or a mapping of things
map = function( args, cb ) {
var arr = [];
each(args, function( i, str ) {
arr.push(cb ? (isString(cb) ? str[cb] : cb.call(str, str)) : str)
});
return arr;
},
// testing support for various browser behaviors
support = {
// does onerror work in script tags?
error: doc && (function() {
var script = scriptTag();
script.onerror = noop;
return isFn(script.onerror) || "onerror" in script
})(),
// If scripts support interactive ready state.
// This is tested later.
interactive: false,
// use attachEvent for event listening (IE)
attachEvent: doc && scriptTag().attachEvent
},
// a startup function that will be called when steal is ready
startup = noop,
// if oldsteal is an object
// we use it as options to configure steal
opts = typeof win.steal == "object" ? win.steal : {},
// adds a suffix to the url for cache busting
addSuffix = function( str ) {
if ( opts.suffix ) {
str = (str + '').indexOf('?') > -1 ? str + "&" + opts.suffix : str + "?" + opts.suffix;
}
return str;
},
endsInSlashRegex = /\/$/;
// ## AOP ##
// Aspect oriented programming helper methods are used to
// weave in functionality into steal's API.
// calls `before` before `f` is called.
// steal.complete = before(steal.complete, f)
// `changeArgs=true` makes before return the same args
function before(f, before, changeArgs) {
return changeArgs ?
function before_changeArgs() {
return f.apply(this, before.apply(this, arguments));
} : function before_args() {
before.apply(this, arguments);
return f.apply(this, arguments);
}
}
// returns a function that calls `after`
// after `f`
function after(f, after, changeRet) {
return changeRet ?
function after_CRet() {
return after.apply(this, [f.apply(this, arguments)].concat(map(arguments)));
} : function after_Ret() {
var ret = f.apply(this, arguments);
after.apply(this, arguments);
return ret;
}
}
// ## Deferred .63
var Deferred = function( func ) {
if (!(this instanceof Deferred)) return new Deferred();
this.doneFuncs = [];
this.failFuncs = [];
this.resultArgs = null;
this.status = "";
// check for option function: call it with this as context and as first
// parameter, as specified in jQuery api
func && func.call(this, this);
}
Deferred.when = function() {
var args = map(arguments);
if ( args.length < 2 ) {
var obj = args[0];
if ( obj && (isFn(obj.isResolved) && isFn(obj.isRejected)) ) {
return obj;
} else {
return Deferred().resolve(obj);
}
} else {
var df = Deferred(),
done = 0,
// resolve params: params of each resolve, we need to track down
// them to be able to pass them in the correct order if the master
// needs to be resolved
rp = [];
each(args, function( j, arg ) {
arg.done(function() {
rp[j] = (arguments.length < 2) ? arguments[0] : arguments;
if (++done == args.length ) {
df.resolve.apply(df, rp);
}
}).fail(function() {
df.reject(arguments);
});
});
return df;
}
}
var resolveFunc = function( type, status ) {
return function( context ) {
var args = this.resultArgs = (arguments.length > 1) ? arguments[1] : [];
return this.exec(context, this[type], args, status);
}
},
doneFunc = function( type, status ) {
return function() {
var self = this;
each(arguments, function( i, v, args ) {
if (!v ) return;
if ( v.constructor === Array ) {
args.callee.apply(self, v)
} else {
// immediately call the function if the deferred has been resolved
if ( self.status === status ) v.apply(this, self.resultArgs || []);
self[type].push(v);
}
});
return this;
}
};
extend(Deferred.prototype, {
resolveWith: resolveFunc("doneFuncs", "rs"),
rejectWith: resolveFunc("failFuncs", "rj"),
done: doneFunc("doneFuncs", "rs"),
fail: doneFunc("failFuncs", "rj"),
always: function() {
var args = map(arguments);
if ( args.length && args[0] ) this.done(args[0]).fail(args[0]);
return this;
},
then: function() {
var args = map(arguments);
// fail function(s)
if ( args.length > 1 && args[1] ) this.fail(args[1]);
// done function(s)
if ( args.length && args[0] ) this.done(args[0]);
return this;
},
isResolved: function() {
return this.status === "rs";
},
isRejected: function() {
return this.status === "rj";
},
reject: function() {
return this.rejectWith(this, arguments);
},
resolve: function() {
return this.resolveWith(this, arguments);
},
exec: function( context, dst, args, st ) {
if ( this.status !== "" ) return this;
this.status = st;
each(dst, function( i, d ) {
d.apply(context, args);
});
return this;
}
});
// ## HELPER METHODS FOR DEFERREDS
// Used to call a method on an object or resolve a
// deferred on it when a group of deferreds is resolved.
//
// whenEach(resources,"complete",resource,"execute")
var whenEach = function( arr, func, obj, func2 ) {
var deferreds = map(arr, func)
return Deferred.when.apply(Deferred, deferreds).then(function() {
if ( isFn(obj[func2]) ) {
obj[func2]()
} else {
obj[func2].resolve();
}
});
};
// ## URI ##
/**
* @class steal.URI
* A URL / URI helper for getting information from a URL.
*
* var uri = URI( "http://stealjs.com/index.html" )
* uri.path //-> "/index.html"
*/
var URI = function( url ) {
if ( this.constructor !== URI ) {
return new URI(url);
}
extend(this, URI.parse("" + url));
};
// the current url (relative to root, which is relative from page)
// normalize joins from this
//
extend(URI, {
// parses a URI into it's basic parts
parse: function( string ) {
var uriParts = string.split("?"),
uri = uriParts.shift(),
queryParts = uriParts.join("").split("#"),
protoParts = uri.split("://"),
parts = {
query: queryParts.shift(),
fragment: queryParts.join("#")
},
pathParts;
if ( protoParts[1] ) {
parts.protocol = protoParts.shift();
pathParts = protoParts[0].split("/");
parts.host = pathParts.shift();
parts.path = "/" + pathParts.join("/");
} else {
parts.path = protoParts[0];
}
return parts;
}
});
/**
* @attribute page
* The location of the page as a URI.
*
* steal.URI.page.protocol //-> "http"
*/
URI.page = URI(win.location && location.href);
/**
* @attribute cur
*
* The current working directory / path. Anything
* loaded relative will be loaded relative to this.
*/
URI.cur = URI();
/**
* @prototype
*/
extend(URI.prototype, {
dir: function() {
var parts = this.path.split("/");
parts.pop();
return URI(this.domain() + parts.join("/"))
},
filename: function() {
return this.path.split("/").pop();
},
ext: function() {
var filename = this.filename();
return~filename.indexOf(".") ? filename.split(".").pop() : "";
},
domain: function() {
return this.protocol ? this.protocol + "://" + this.host : "";
},
isCrossDomain: function( uri ) {
uri = URI(uri || win.location.href);
var domain = this.domain(),
uriDomain = uri.domain()
return (domain && uriDomain && domain != uriDomain) || this.protocol === "file" || (domain && !uriDomain);
},
isRelativeToDomain: function() {
return !this.path.indexOf("/");
},
hash: function() {
return this.fragment ? "#" + this.fragment : ""
},
search: function() {
return this.query ? "?" + this.query : ""
},
// like join, but returns a string
add: function( uri ) {
return this.join(uri) + '';
},
join: function( uri, min ) {
uri = URI(uri);
if ( uri.isCrossDomain(this) ) {
return uri;
}
if ( uri.isRelativeToDomain() ) {
return URI(this.domain() + uri)
}
// at this point we either
// - have the same domain
// - this has a domain but uri does not
// - both don't have domains
var left = this.path ? this.path.split("/") : [],
right = uri.path.split("/"),
part = right[0];
//if we are joining from a folder like cookbook/, remove the last empty part
if ( this.path.match(/\/$/) ) {
left.pop();
}
while ( part == ".." && left.length ) {
// if we've emptied out, folders, just break
// leaving any additional ../s
if (!left.pop() ) {
break;
}
right.shift();
part = right[0];
}
return extend(URI(this.domain() + left.concat(right).join("/")), {
query: uri.query
});
},
/**
* For a given path, a given working directory, and file location, update the
* path so it points to a location relative to steal's root.
*
* We want everything relative to steal's root so the same app can work in
* multiple pages.
*
* ./files/a.js = steals a.js
* ./files/a = a/a.js
* files/a = //files/a/a.js
* files/a.js = loads //files/a.js
*/
normalize: function( cur ) {
cur = cur ? cur.dir() : URI.cur.dir();
var path = this.path,
res = URI(path);
//if path is rooted from steal's root (DEPRECATED)
if (!path.indexOf("//") ) {
res = URI(path.substr(2));
} else if (!path.indexOf("./") ) { // should be relative
res = cur.join(path.substr(2));
}
// only if we start with ./ or have a /foo should we join from cur
else if ( this.isRelative() ) {
res = cur.join(this.domain() + path)
}
res.query = this.query;
return res;
},
isRelative: function() {
return /^[\.|\/]/.test(this.path)
},
// a min path from 2 urls that share the same domain
pathTo: function( uri ) {
uri = URI(uri);
var uriParts = uri.path.split("/"),
thisParts = this.path.split("/"),
result = [];
while ( uriParts.length && thisParts.length && uriParts[0] == thisParts[0] ) {
uriParts.shift();
thisParts.shift();
}
each(thisParts, function() {
result.push("../")
})
return URI(result.join("") + uriParts.join("/"));
},
mapJoin: function( url ) {
return this.join(URI(url).insertMapping());
},
// helper to go from jquery to jquery/jquery.js
addJS: function() {
var ext = this.ext();
if (!ext ) {
// if first character of path is a . or /, just load this file
if (!this.isRelative() ) {
this.path += "/" + this.filename();
}
this.path += ".js"
}
return this;
}
});
// create the steal function now to use as a namespace.
function steal() {
// convert arguments into an array
var args = map(arguments);
if ( args.length ) {
pending.push.apply(pending, args);
// steal.after is called everytime steal is called
// it kicks off loading these files
steal.after(args);
// return steal for chaining
}
return steal;
};
steal._id = Math.floor(1000 * Math.random());
// ## CONFIG ##
// stores the current config settings
var stealConfig = {
types: {},
ext: {},
env: "development",
loadProduction: true,
logLevel: 0
},
matchesId = function( loc, id ) {
if ( loc === "*" ) {
return true;
} else if ( id.indexOf(loc) === 0 ) {
return true;
}
};
/**
* `steal.config(config)` configures steal. Typically it it used
* in __stealconfig.js__. The available options are:
*
* - map - map an id to another id
* - paths - maps an id to a file
* - root - the path to the "root" folder
* - env - `"development"` or `"production"`
* - types - processor rules for various types
* - ext - behavior rules for extensions
* - urlArgs - extra queryString arguments
* - startFile - the file to load
*
* ## map
*
* Maps an id to another id with a certain scope of other ids. This can be
* used to use different modules within the same id or map ids to another id.
* Example:
*
* steal.config({
* map: {
* "*": {
* "jquery/jquery.js": "jquery"
* },
* "compontent1":{
* "underscore" : "underscore1.2"
* },
* "component2":{
* "underscore" : "underscore1.1"
* }
* }
* })
*
* ## paths
*
* Maps an id or matching ids to a url. Each mapping is specified
* by an id or part of the id to match and what that
* part should be replaced with.
*
* steal.config({
* paths: {
* // maps everything in a jquery folder like: `jquery/controller`
* // to http://cdn.com/jquery/controller/controller.com
* "jquery/" : "http://cdn.com/jquery/"
*
* // if path does not end with /, it matches only that id
* "jquery" : "https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"
* }
* })
*
* ## root
* ## env
*
* If production, does not load "ignored" scripts and loads production script. If development gives more warnings / errors.
*
* ## types
*
* The types option can specify how a type is loaded.
*
* ## ext
*
* The ext option specifies the default behavior if file is loaded with the
* specified extension. For a given extension, a file that configures the type can be given or
* an existing type. For example, for ejs:
*
* steal.config({ext: {"ejs": "can/view/ejs/ejs.js"}})
*
* This tells steal to make sure `can/view/ejs/ejs.js` is executed before any file with
* ".ejs" is executed.
*
* ## startFile
*/
steal.config = function( config ) {
if(!config){ // called as a getter, so just return
return stealConfig;
}
if(arguments.length === 1 && typeof config === "string"){ // called as a getter, so just return
return stealConfig[config];
}
for(var prop in config){
var value = config[prop]
// if it's a special function
steal.config[prop] ?
// run it
steal.config[prop](value) :
// otherwise set or extend
(typeof value == "object" && stealConfig[prop] ?
// extend
extend( stealConfig[prop], value) :
// set
stealConfig[prop] = value);
}
// redo all resources
each(resources, function( id, resource ) {
if ( resource.options.type != "fn" ) {
// TODO this is terrible
var buildType = resource.options.buildType;
resource.setOptions(resource.orig);
var newId = resource.options.id;
// this mapping is to move a config'd key
if ( id !== newId ) {
resources[newId] = resource;
// TODO: remove the old one ....
}
resource.options.buildType = buildType;
}
})
return stealConfig;
};
steal.config.startFile = function(startFile){
// make sure startFile and production look right
stealConfig.startFile = "" + URI(startFile).addJS()
if (!stealConfig.production ) {
stealConfig.production = URI(stealConfig.startFile).dir() + "/production.js";
}
}
/**
* Read or define the path relative URI's should be referenced from.
*
* window.location //-> "http://foo.com/site/index.html"
* steal.URI.root("http://foo.com/app/files/")
* steal.root.toString() //-> "../../app/files/"
*/
steal.config.root = function( relativeURI ) {
if ( relativeURI !== undefined ) {
var root = URI(relativeURI);
// the current folder-location of the page http://foo.com/bar/card
var cleaned = URI.page,
// the absolute location or root
loc = cleaned.join(relativeURI);
// cur now points to the 'root' location, but from the page
URI.cur = loc.pathTo(cleaned)
stealConfig.root = root;
return;
}
stealConfig.root = root || URI("");
}
steal.config.root("");
/**
* @function steal.id
*
* Given a resource id passed to `steal( resourceID, currentWorkingId )`, this function converts it to the
* final, unique id. This function can be overwritten
* to change how unique ids are defined, for example, to be more AMD-like.
*
* The following are the default rules.
*
* Given an ID:
*
* 1. Check the id has an extension like _.js_ or _.customext_. If it doesn't:
* 1. Check if the id is relative, meaning it starts with _../_ or _./_. If it is not, add
* "/" plus everything after the last "/". So `foo/bar` becomes `foo/bar/bar`
* 2. Add .js to the id.
* 2. Check if the id is relative, meaning it starts with _../_ or _./_. If it is relative,
* set the id to the id joined from the currentWorkingId.
* 3. Check the
*
*
* `steal.id()`
*/
// returns the "rootSrc" id, something that looks like requireJS
// for a given id/path, what is the "REAL" id that should be used
// this is where substituation can happen
steal.id = function( id, currentWorkingId, type ) {
// id should be like
var uri = URI(id);
uri = uri.addJS().normalize(currentWorkingId ? new URI(currentWorkingId) : null)
// check foo/bar
if (!type ) {
type = "js"
}
if ( type == "js" ) {
// if it ends with .js remove it ...
// if it ends
}
// check map config
var map = stealConfig.map || {};
// always run past
each(map, function( loc, maps ) {
// is the current working id matching loc
if ( matchesId(loc, currentWorkingId) ) {
// run maps
each(maps, function( part, replaceWith ) {
if (("" + uri).indexOf(part) == 0 ) {
uri = URI(("" + uri).replace(part, replaceWith))
}
})
}
})
return uri;
}
steal.amdToId = function(id, currentWorkingId, type){
var uri = URI(id);
uri = uri.normalize(currentWorkingId ? new URI(currentWorkingId) : null)
// check foo/bar
if (!type ) {
type = "js"
}
if ( type == "js" ) {
// if it ends with .js remove it ...
// if it ends
}
// check map config
var map = stealConfig.map || {};
// always run past
each(map, function( loc, maps ) {
// is the current working id matching loc
if ( matchesId(loc, currentWorkingId) ) {
// run maps
each(maps, function( part, replaceWith ) {
if (("" + uri).indexOf(part) == 0 ) {
uri = URI(("" + uri).replace(part, replaceWith))
}
})
}
})
return uri;
}
steal.config.shim = function(shims){
for(var id in shims){
var resource = Resource.make(id);
if(typeof shims[id] === "object"){
var needs = shims[id].deps || []
if(typeof shims[id].exports === "string"){
var exports = (function(_exports){
return function(){
return win[_exports];
}
})(shims[id].exports)
} else {
exports = shims[id].exports;
}
} else {
needs = shims[id];
}
(function(_resource, _needs){
_resource.options.needs = _needs;
})(resource, needs)
if(exports){
resource.exports = (function(_resource, _exports, _needs){
return function(){
var args = _needs.map(function(id){
return Resource.make(id).value;
})
_resource.value = _exports.apply(null, args)
return _resource.value
}
})(resource, exports, needs)
}
}
}
// for a given ID, where should I find this resource
/**
* `steal.idToUri( id, noJoin )` takes an id and returns a URI that
* is the location of the file. It uses the paths option of [steal.config].
* Passing true for `noJoin` does not join from the root URI.
*/
steal.idToUri = function( id, noJoin ) {
// this is normalize
var paths = stealConfig.paths || {},
path;
// always run past
each(paths, function( part, replaceWith ) {
path = ""+id;
// if path ends in / only check first part of id
if((endsInSlashRegex.test(part) && path.indexOf(part) == 0) ||
// or check if its a full match only
path === part){
id = URI(path.replace(part, replaceWith));
}
})
return noJoin ? id : stealConfig.root.join(id)
}
steal.amdIdToUri = function( id, noJoin ){
// this is normalize
var paths = stealConfig.paths || {},
path;
// always run past
each(paths, function( part, replaceWith ) {
path = ""+id;
// if path ends in / only check first part of id
if((endsInSlashRegex.test(part) && path.indexOf(part) == 0) ||
// or check if its a full match only
path === part){
id = URI(path.replace(part, replaceWith));
}
})
if( /(^|\/)[^\/\.]+$/.test(id) ){
id= URI(id+".js")
}
return id //noJoin ? id : stealConfig.root.join(id)
}
// This can't be added to the prototype using extend because
// then for some reason IE < 9 won't recognize it.
URI.prototype.toString = function() {
return this.domain() + this.path + this.search() + this.hash();
};
// temp add steal.File for backward compat
steal.File = steal.URI = URI;
// --- END URI
var pending = [],
s = steal,
id = 0;
/**
* @add steal
*/
// =============================== STATIC API ===============================
var page;
extend(steal, {
each: each,
extend: extend,
Deferred: Deferred,
// Currently used a few places
isRhino: win.load && win.readUrl && win.readFile,
/**
* @hide
* Makes options
* @param {Object} options
*/
makeOptions: function( options, curId ) {
// convert it to a uri
if (!options.id ) {
throw {
message: "no id",
options: options
}
}
options.id = options.toId ? options.toId(options.id, curId) : steal.id(options.id, curId);
// set the ext
options.ext = options.id.ext();
// Check if it's a configured needs
var configedExt = stealConfig.ext[options.ext];
// if we have something, but it's not a type
if ( configedExt && ! stealConfig.types[configedExt] ) {
if (!options.needs ) {
options.needs = [];
}
options.needs.push(configedExt);
}
return options;
},
/**
* Calls steal, but waits until all previous steals
* have completed loading until loading the
* files passed to the arguments.
*/
then: function() {
var args = map(arguments);
args.unshift(null)
return steal.apply(win, args);
},
/**
* `steal.bind( event, handler(eventData...) )` listens to
* events on steal. Typically these are used by various build processes
* to know when steal starts and finish loading resources and their
* dependencies. Listen to an event like:
*
* steal.bind('end', function(rootResource){
* rootResource.dependencies // the first stolen resources.
* })
*
* Steal supports the following events:
*
* - __start__ - steal has started loading a group of resources and their dependencies.
* - __end__ - steal has finished loading a group of resources and their dependencies.
* - __done__ - steal has finished loading the first set of resources and their dependencies.
* - __ready__ - after both steal's "done" event and the `window`'s onload event have fired.
*
* For example, the following html:
*
* @codestart html
* <script src='steal/steal.js'></script>
* <script>
* steal('can/control', function(){
* setTimeout(function(){
* steal('can/model')
* },200)
* })
* </script>
* @codeend
*
* Would fire:
*
* - __start__ - immediately after `steal('can/control')` is called
* - __end__ - after 'can/control', all of it's dependencies, and the callback function have executed and completed.
* - __done__ - fired after the first 'end' event.
* - __ready__ - fired after window.onload and the 'done' event
* - __start__ - immediately after `steal('can/model')` is called
* - __end__ - fired after 'can/model' and all of it's dependencies have fired.
*
*
*
* @param {String} event
* @param {Function} listener
*/
bind: function( event, listener ) {
if (!events[event] ) {
events[event] = []
}
var special = steal.events[event]
if ( special && special.add ) {
listener = special.add(listener);
}
listener && events[event].push(listener);
return steal;
},
/**
* `steal.one(eventName, handler(eventArgs...) )` works just like
* [steal.bind] but immediately unbinds after `handler` is called.
*/
one: function( event, listener ) {
return steal.bind(event, function() {
listener.apply(this, arguments);
steal.unbind(event, arguments.callee);
});
},
events: {},
/**
* `steal.unbind( eventName, handler )` removes an event listener on steal.
* @param {String} event
* @param {Function} listener
*/
unbind: function( event, listener ) {
var evs = events[event] || [],
i = 0;
while ( i < evs.length ) {
if ( listener === evs[i] ) {
evs.splice(i, 1);
} else {
i++;
}
}
},
trigger: function( event, arg ) {
var arr = events[event] || [];
// array items might be removed during each iteration (with unbind),
// so we iterate over a copy
each(map(arr), function( i, f ) {
f(arg);
})
},
/**
* @hide
* Creates resources and marks them as loading so steal doesn't try
* to load them.
*
* steal.has("foo/bar.js","zed/car.js");
*
* This is used when a file has other resources in it.
*/
has: function() {