js.io /packages/jsio.js

Language Javascript Lines 784
MD5 Hash f74994e9275f8f188bf154a8cbba42bf
Repository https://github.com/skysbird/js.io.git View Raw File
| Open JSFiddle
  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
// Copyright (c) 2010
// Michael Carter (cartermichael@gmail.com)
// Martin Hunt (mghunt@gmail.com)
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// Initialization of js.io occurs in a closure, preventing local variables
// from entering the global scope.  During execution, the method `jsio` is
// added to the global scope.

;(function() {
	function init(cloneFrom) {
		// We expect this code to be minified before production use, so we may
		// write code slightly more verbosely than we otherwise would.
	
		// Should we parse syntax errors in the browser?
		var DEBUG = true;
	
		// Store a reference to the slice function for converting objects of
		// type arguments to type array.
		var SLICE = Array.prototype.slice;
	
		// js.io supports multiple JavaScript environments such as node.js and
		// most web browsers (IE, Firefox, WebKit).  The ENV object wraps 
		// any utility functions that contain environment-specific code (e.g.
		// reading a file using node's `fs` library or a browser's
		// `XMLHttpRequest`).  Running js.io in other JavaScript environments
		// is as easy as implementing an environment object that conforms to 
		// the abstract interface for an environment (provided below) and 
		// calling `jsio.setEnv()`.
		var ENV;
	
		// Checks if the last character in a string is `/`.
		var rexpEndSlash = /\/$/;
	
		// Creates an object containing metadata about a module.
		function makeModuleDef(path, baseMod, basePath) {
			var def = util.splitPath(path + '.js');
			if (baseMod) {
				def.baseMod = baseMod;
				def.basePath = basePath;
			}
			return def;
		}
	
		// Utility functions
		var util = {
				// `util.bind` returns a function that, when called, will execute
				// the method passed in with the provided context and any additional
				// arguments passed to `util.bind`.
				//       util.bind(obj, 'f', a) -> function() { return obj.f(a); }
				//       util.bind(obj, g, a, b, c) -> function() { return g.call(g, a, b, c); }
				bind: function(context, method/*, args... */) {
					var args = SLICE.call(arguments, 2);
					return function() {
						method = (typeof method == 'string' ? context[method] : method);
						return method.apply(context, args.concat(SLICE.call(arguments, 0)));
					};
				},
			
				// `util.addEndSlash` accepts a string.  That string is returned with a `/`
				// appended if the string did not already end in a `/`.
				addEndSlash: function(str) {
					return rexpEndSlash.test(str) ? str : str + '/';
				},
			
				// `util.removeEndSlash` accepts a string.  It removes a trailing `/` if
				// one is found.
				removeEndSlash: function(str) {
					return str.replace(rexpEndSlash, '');
				},
			
				// `util.makeRelativePath` accepts two paths (strings) and returns the first path
				// made relative to the second.  Note: this function needs some work.  It currently
				// handles the most common use cases, but may fail in unexpected edge cases.
				// 
				//  - Simple case: if `path` starts with `relativeTo`, then we can strip `path` 
				// off the `relativeTo` part and we're done.
				//
				//         util.makeRelativePath('abc/def/', 'abc') -> 'def'
				//
				//  - Harder case: `path` starts with some substring of `relativeTo`.  We want to remove this substring and then add `../` for each remaining segment of `relativeTo`.
				//
				//         util.makeRelativePath('abc/def/', 'abc/hij') -> '../def'
				//
				makeRelativePath: function(path, relativeTo) {
					var len = relativeTo.length;
					if (path.substring(0, len) == relativeTo) {
						/* Note: we're casting a boolean to an int by adding len to it */
						return path.slice((path.charAt(len) == '/') + len);
					}
				
					var sA = util.removeEndSlash(path).split('/'),
						sB = util.removeEndSlash(relativeTo).split('/'),
						i = 0;
				
					/* Count how many segments match. */
					while(sA[i] == sB[i]) { ++i; }
				
					if (i) {
						/* If at least some segments matched, remove them.  The result is our new path. */
						path = sA.slice(i).join('/');
					
						/* Prepend `../` for each segment remaining in `relativeTo`. */
						for (var j = sB.length - i; j > 0; --j) { path = '../' + path; }
					}
				
					return path;
				},
			
				// `buildPath` accepts an arbitrary number of string arguments to concatenate into a path.
				//     util.buildPath('a', 'b', 'c/', 'd/') -> 'a/b/c/d/'
				buildPath: function() {
					return util.resolveRelativePath(Array.prototype.join.call(arguments, '/'));
				},
			
				// `resolveRelativePath` removes relative path indicators.  For example:
				//     util.resolveRelativePath('a/../b') -> b
				resolveRelativePath: function(path) {
					/* If the path starts with a protocol, store it and remove it (add it
					   back later) so we don't accidently modify it. */
					var protocol = path.match(/^(\w+:\/\/)(.*)$/);
					if (protocol) { path = protocol[2]; }
				
					/* Remove multiple slashes and trivial dots (`/./ -> /`). */
					path = path.replace(/\/+/g, '/').replace(/\/\.\//g, '/');
				
					/* Loop to collapse instances of `../` in the path by matching a previous
					   path segment.  Essentially, we find substrings of the form `/abc/../`
					   where abc is not `.` or `..` and replace the substrings with `/`.
					   We loop until the string no longer changes since after collapsing all
					   possible instances once, we may have created more instances that can
					   be collapsed.
					*/
					var o;
					while((o = path) != (path = path.replace(/(^|\/)(?!\.?\.\/)([^\/]+)\/\.\.\//g, '$1'))) {}
					/* Don't forget to prepend any protocol we might have removed earlier. */
					return protocol ? protocol[1] + path : path;
				},
			
				resolveRelativeModule: function(modulePath, directory) {
					var result = [],
						parts = modulePath.split('.'),
						len = parts.length,
						relative = (len > 1 && !parts[0]),
						i = relative ? 0 : -1;
				
					while(++i < len) { result.push(parts[i] ? parts[i] : '..'); }
					return util.buildPath(relative ? directory : '', result.join('/'));
				},
				resolveModulePath: function(modulePath, directory) {
					// resolve relative paths
					if(modulePath.charAt(0) == '.') {
						return [makeModuleDef(util.resolveRelativeModule(modulePath, directory))];
					}
				
					// resolve absolute paths with respect to jsio packages/
					var pathSegments = modulePath.split('.'),
						baseMod = pathSegments[0],
						pathString = pathSegments.join('/');
				
					if (jsio.path.cache.hasOwnProperty(baseMod)) {
						return [makeModuleDef(util.buildPath(jsio.path.cache[baseMod], pathString))];
					}
				
					var out = [],
						paths = jsio.path.get(),
						len = paths.length;
					for (var i = 0; i < len; ++i) {
						out.push(makeModuleDef(util.buildPath(paths[i], pathString), baseMod, paths[i]));
					}
					return out;
				},
				splitPath: function(path) {
					var i = path.lastIndexOf('/') + 1;
					return {
						path: path,
						directory: path.substring(0, i),
						filename: path.substring(i)
					};
				}
			};
	
		var jsio = util.bind(this, importer, null, null, null);
		jsio.__util = util;
		jsio.__init__ = init;
		
		// explicitly use jsio.__srcCache to avoid obfuscation with closure compiler
		var sourceCache = jsio.__srcCache = {};
		if (cloneFrom && cloneFrom.__srcCache) { sourceCache = jsio.__srcCache = cloneFrom.__srcCache; }

		(function() {
			this.__filename = 'jsio.js';
			this.__preprocessors = {};
			this.__cmds = [];
			this.__jsio = this;
			this.__importer = importer;
			this.__modules = {preprocessors:{}};
		
			this.path = {
				set: function(path) { this.value = (typeof path == 'string' ? [path] : path); },
				get: function() { return this.value.slice(0); },
				add: function(path) {
					var v = this.value, len = v.length;
					for (var i = 0; i < len; ++i) {
						if (v[i] == path) { return; }
					}
					v.push(path);
				},
				remove: function(path) {
					var v = this.value, len = v.length;
					for (var i = 0; i < len; ++i) {
						if (v[i] == path) {
							v.splice(i, 1);
						}
					}
				},
				value: [],
				cache: {}
			};
		
			this.addPath = util.bind(this.path, 'add');
		
			this.setCachedSrc = function(path, src) { sourceCache[path] = { path: path, src: src }; }
			this.getCachedSrc = function(path) { return sourceCache[path]; }
		
			this.addPreprocessor = function(name, preprocessor) { this.__preprocessors[name] = preprocessor; }
			this.addCmd = function(processor) { this.__cmds.push(processor); }
		
			this.setEnv = function(envCtor) {
				if (!envCtor && cloneFrom) {
					ENV = cloneFrom.__env;
				} else if (typeof envCtor == 'string') {
					switch(envCtor) {
						case 'node':
							ENV = new ENV_node(util);
							break;
						case 'browser':
						default:
							ENV = new ENV_browser(util);
							break;
					}
				} else {
					ENV = new envCtor(util);
				}
			
				this.__env = ENV;
				this.__dir = ENV.getCwd();
				this.path.set(ENV.getPath());
			}
		}).call(jsio);
	
		if (cloneFrom) {
			jsio.setEnv();
		} else if (typeof process !== 'undefined' && process.version) {
			jsio.setEnv('node');
		} else if (typeof XMLHttpRequest != 'undefined' || typeof ActiveXObject != 'undefined') {
			jsio.setEnv('browser');
		}

		/*
		function ENV_abstract() {
			this.global = null;
			this.getCwd = function() {};
			this.getPath = function() {};
			this.eval = function(code, path) {};
			this.fetch = function(path) { return contentsOfPath; };
			this.log = function(args...) {};
		}
		*/
	
		function ENV_node() {
			var fs = require('fs'),
				sys = require('sys');
		
			this.name = 'node';
			this.global = GLOBAL;
			this.getCwd = process.cwd;
			this.log = function() {
				var msg;
				try {
					sys.error(msg = Array.prototype.map.call(arguments, function(a) {
						if ((a instanceof Error) && a.message) {
							return 'Error:' + a.message + '\nStack:' + a.stack + '\nArguments:' + a.arguments;
						}
						return typeof a == 'string' ? a : JSON.stringify(a);
					}).join(' '));
				} catch(e) {
					sys.error(msg = Array.prototype.join.call(arguments, ' ') + '\n');
				}
				return msg;
			}
		
			this.getPath = function() {
				var segments = __filename.split('/');
				segments.pop();
				return util.makeRelativePath(segments.join('/') || '.', this.getCwd());
			}
			this.eval = process.compile;
		
			this.fetch = function(path) {
				try { return fs.readFileSync(path, 'utf8'); } catch(e) {}
				return false;
			}
		
			this.require = require;
		}
	
		function ENV_browser() {
			var XHR = window.XMLHttpRequest || function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
				cwd = null,
				path = null;
		
			this.name = 'browser';
			this.global = window;
			this.global.jsio = jsio;
		
			this.log = function() {
				var args = SLICE.call(arguments, 0);
				if (typeof console != 'undefined' && console.log) {
					//for iOS mobile safari w/ debugger console enabled,
					//uncomment the following two lines for more useful
					//messages
					//console.log(args.join(' '));
					//return;
					
					if (console.log.apply) {
						console.log.apply(console, arguments);
					} else { // IE doesn't support log.apply, and the argument cannot be arguments - it must be an array
						console.log(args);
					}
				}
				return args.join(' ');
			}
		
			this.getCwd = function() {
				if(!cwd) {
					var loc = window.location, path = loc.pathname;
					cwd = loc.protocol + '//' + loc.host + path.substring(0, path.lastIndexOf('/') + 1);
				}
				return cwd;
			}
		
			this.getPath = function() {
				if(!path) {
					try {
						var filename = new RegExp('(.*?)' + jsio.__filename + '(\\?.*)?$'),
							scripts = document.getElementsByTagName('script');
					
						for (var i = 0, script; script = scripts[i]; ++i) {
							var result = script.src.match(filename);
							if (result) {
								path = result[1];
								if (/^[A-Za-z]*:\/\//.test(path)) { path = util.makeRelativePath(path, this.getCwd()); }
								break;
							}
						}
					} catch(e) {}
				
					if(!path) { path = '.'; }
				}
				return path;
			}
		
			this.debugPath = function(path) { return path; }

			// IE6 won't return an anonymous function from eval, so use the function constructor instead
			var rawEval = typeof eval('(function(){})') == 'undefined'
				? function(src, path) { return (new Function('return ' + src))(); }
				: function(src, path) { var src = src + '\n//@ sourceURL=' + path; return window.eval(src); };

			// provide an eval with reasonable debugging
			this.eval = function(code, path, origCode) {
				try {
					return rawEval(code, this.debugPath(path));
				} catch(e) {
					if(e instanceof SyntaxError) {
						ENV.log("a syntax error is preventing execution of " + path);
						if (DEBUG && this.checkSyntax) {
							this.checkSyntax(origCode, path);
						}
					}
					throw e;
				}
			}
		
			this.checkSyntax = function(code, path) {
				try {
					var syntax = jsio('import util.syntax', {suppressErrors: true, dontExport: true}),
						result = syntax(code);
					syntax.display(result, path);
				} catch(e) {}
			}
		
			this.fetch = function(path) {
				var xhr = new XHR();
				try {
					xhr.open('GET', path, false);
					xhr.send(null);
				} catch(e) {
					ENV.log('e:', e);
					return false; // firefox file://
				}
			
				if (xhr.status == 404 || // all browsers, http://
					xhr.status == -1100 || // safari file://
					// XXX: We have no way to tell in opera if a file exists and is empty, or is 404
					// XXX: Use flash?
					//(!failed && xhr.status == 0 && !xhr.responseText && EXISTS)) // opera
					false)
				{
					return false;
				}
			
				return xhr.responseText;
			}
		};
	
		var preprocessorCheck = /^"use (.*?)"\s*;\s*\n/,
			preprocessorFunc = /^(.+)\(.+\)$/,
			failedFetch = {};
	
		function findModule(possibilities, opts) {
			var src;
			for (var i = 0, possible; possible = possibilities[i]; ++i) {
				var path = possible.path,
					cachedVersion = sourceCache[path];
				
				if (cachedVersion) {
					possible.src = cachedVersion.src;
					return possible;
				}
			
				/*if (/^\.\//.test(path)) {
					// remove one path segment for each dot from the cwd 
					path = addEndSlash(ENV.getCwd()) + path;
				}*/
			
				src = ENV.fetch(path);
			
				if (src !== false) {
					possible.src = src;
					return possible;
				} else {
					failedFetch[path] = true;
				}
			}
		
			return false;
		}
	
		// load a module from a file
		function loadModule(fromDir, fromFile, modulePath, opts) {
			var possibilities = util.resolveModulePath(modulePath, fromDir);
			for (var i = 0, p; p = possibilities[i]; ++i) {
				var path = possibilities[i].path;
				if (!opts.reload && (path in jsio.__modules)) {
					return possibilities[i];
				}
				if (path in failedFetch) { possibilities.splice(i--, 1); }
			}
		
			if (!possibilities.length) {
				if (opts.suppressErrors) { return false; }
				var e = new Error('Module failed to load (again)');
				e.jsioLogged = true;
				throw e;
			}
		
			var moduleDef = findModule(possibilities, opts),
				match;
		
			if (!moduleDef) {
				if (opts.suppressErrors) { return false; }
				var paths = [];
				for (var i = 0, p; p = possibilities[i]; ++i) { paths.push(p.path); }
				throw new Error(fromDir + fromFile + ": \n\tcurrent directory: " + ENV.getCwd() + "\n\tlooked in:\n\t\t" + paths.join('\n\t\t') + '\n\tImport Stack:\n\t\t' + importStack.join('\n\t\t') + "\n\tError: requested import (" + modulePath + ") not found.");
			}
		
			moduleDef.friendlyPath = modulePath;
		
			if (moduleDef.baseMod && !(moduleDef.baseMod in jsio.path.cache)) {
				jsio.path.cache[moduleDef.baseMod] = moduleDef.basePath;
			}
		
			// the order here is somewhat arbitrary and might be overly restrictive (... or overly powerful)
			while (moduleDef.src.charAt(0) == '"' && (match = moduleDef.src.match(preprocessorCheck))) {
				moduleDef.src = moduleDef.src.substring(match[0].length - 1);
				applyPreprocessors(fromDir, moduleDef, match[1].split(','), opts);
			}
			
			if (opts.preprocessors) {
				applyPreprocessors(fromDir, moduleDef, opts.preprocessors, opts);
			}
			
			return moduleDef;
		}
	
		function applyPreprocessors(path, moduleDef, names, opts) {
			for (var i = 0, len = names.length; i < len; ++i) {
				p = getPreprocessor(names[i]);
				if (p) {
					p(path, moduleDef, opts);
				}
			}
		}
		
		function getPreprocessor(name) {
			return typeof name == 'function'
				? name
				: (jsio.__modules['preprocessors.' + name] 
					|| jsio('import preprocessors.' + name, {dontExport: true}));
		}
	
		function execModuleDef(context, moduleDef) {
			var code = "(function(_){with(_){delete _;return function $$" + moduleDef.friendlyPath.replace(/[\/.]/g, '_') + "(){" + moduleDef.src + "\n}}})";
			var fn = ENV.eval(code, moduleDef.path, moduleDef.src);
			fn = fn(context);
			fn.call(context.exports);
		};
		
		function resolveImportRequest(context, request, opts) {
			var cmds = jsio.__cmds,
				imports = [],
				result = false;
		
			for (var i = 0, imp; imp = cmds[i]; ++i) {
				if ((result = imp(context, request, opts, imports))) { break; }
			}
		
			if (result !== true) {
				throw new (typeof SyntaxError != 'undefined' ? SyntaxError : Error)(String(result || 'invalid jsio command: jsio(\'' + request + '\')'));
			}
		
			return imports;
		};
	
		function makeContext(ctx, modulePath, moduleDef, dontAddBase) {
			if (!ctx) { ctx = {}; }
			if (!ctx.exports) { ctx.exports = {}; }

			ctx.jsio = util.bind(this, importer, ctx, moduleDef.directory, moduleDef.filename);
			ctx.require = function(request, opts) {
				if (!opts) { opts = {}; }
				opts.dontExport = true;
				opts.suppressErrors = true;
			
				try {
					var ret = ctx.jsio(request, opts);
					if (ret === false) {
						// need this to trigger require attempt due to suppresserrors = true
						throw "module failed to load";
					} else {
						return ret;
					}
				} catch(e) {
					try {
						return require(request);
					} catch(e2) {
						ENV.log('Error loading request ' + request + ':');
						ENV.log(e);

						ENV.log('Also could not load using standard CommonJS');
						ENV.log(e2);

						throw e;
					}
				}
			};
		
			ctx.module = {id: modulePath, exports: ctx.exports};
			if (!dontAddBase && modulePath != 'base') {
				ctx.jsio('from base import *');
				ctx.logging.__create(modulePath, ctx);
			}
		
			// TODO: FIX for "trailing ." case
			ctx.jsio.__jsio = jsio;
			ctx.jsio.__env = jsio.__env;
			ctx.jsio.__dir = moduleDef.directory;
			ctx.jsio.__filename = moduleDef.filename;
			ctx.jsio.__path = modulePath;
			ctx.jsio.path = jsio.path;
			return ctx;
		};
		
		var importStack = [];
		function importer(boundContext, fromDir, fromFile, request, opts) {
			opts = opts || {};
			fromDir = fromDir || './';
			fromFile = fromFile || '<initial file>';
		
			// importer is bound to a module's (or global) context -- we can override this
			// by using opts.exportInto
			var exportInto = opts.exportInto || boundContext || ENV.global;
		
			// parse the import request(s)
			var imports = resolveImportRequest(exportInto, request, opts),
				numImports = imports.length,
				retVal = numImports > 1 ? {} : null;
		
			// import each requested item
			for(var i = 0; i < numImports; ++i) {
				var item = imports[i],
					modulePath = item.from,
					modules = jsio.__modules;
			
				try {
					var moduleDef = loadModule(fromDir, fromFile, modulePath, opts);
					if (moduleDef === false) { return false; }
				} catch(e) {
					if (!e.jsioLogged) {
						ENV.log('\nError loading module:\n\trequested:', modulePath, '\n\tfrom:', fromDir + fromFile, '\n\tfull request:', request, '\n');
						e.jsioLogged = true;
					}
					throw e;
				}
				
				importStack.push(importStack.length + ' : ' + moduleDef.friendlyPath + ' (' + moduleDef.path + ')');
				
				// eval any packages that we don't know about already
				var path = moduleDef.path;
				if(!(path in modules)) {
					var newContext = makeContext(opts.context, modulePath, moduleDef, item.dontAddBase);
					modules[path] = newContext.exports;
					if(item.dontUseExports) {
						var src = [';(function(){'], k = 1;
						for (var j in item['import']) {
							newContext.exports[j] = undefined;
							src[k++] = 'if(typeof '+j+'!="undefined"&&exports.'+j+'==undefined)exports.'+j+'='+j+';';
						}
						src[k] = '})();';
						moduleDef.src += src.join('');
					}
					execModuleDef(newContext, moduleDef);
					modules[path] = newContext.exports;
				}
				
				importStack.pop();
			
				var module = modules[path];
			
				// return the module if we're only importing one module
				if (numImports == 1) { retVal = module; }
			
				if (!opts.dontExport) {
					// add the module to the current context
					if (item.as) {
						// remove trailing/leading dots
						var as = item.as.match(/^\.*(.*?)\.*$/)[1],
							segments = as.split('.'),
							kMax = segments.length - 1,
							c = exportInto;
				
						// build the object in the context
						for(var k = 0; k < kMax; ++k) {
							var segment = segments[k];
							if (!segment) continue;
							if (!c[segment]) { c[segment] = {}; }
							c = c[segment];
						}
					
						c[segments[kMax]] = module;
				
						// there can be multiple module imports with this syntax (import foo, bar)
						if (numImports > 1) {
							retVal[as] = module;
						}
					} else if(item['import']) {
						// there can only be one module import with this syntax 
						// (from foo import bar), so retVal will already be set here
						if(item['import']['*']) {
							for(var k in modules[path]) { exportInto[k] = module[k]; }
						} else {
							try {
								for(var k in item['import']) { exportInto[item['import'][k]] = module[k]; }
							} catch(e) {
								ENV.log('module: ', modules);
								throw e;
							}
						}
					}
				}
			}
		
			return retVal;
		}
	
		// DEFINE SYNTAX FOR JSIO('cmd')
	
		// from myPackage import myFunc
		// external myPackage import myFunc
		jsio.addCmd(function(context, request, opts, imports) {
			var match = request.match(/^\s*(from|external)\s+([\w.$]+)\s+(import|grab)\s+(.*)$/);
			if(match) {
				imports.push({
					from: match[2],
					dontAddBase: match[1] == 'external',
					dontUseExports: match[3] == 'grab' || match[1] == 'external',
					'import': {}
				});
			
				match[4].replace(/\s*([\w.$*]+)(?:\s+as\s+([\w.$]+))?/g, function(_, item, as) {
					imports[0]['import'][item] = as || item;
				});
				return true;
			}
		});

		// import myPackage
		jsio.addCmd(function(context, request, opts, imports) {
			var match = request.match(/^\s*import\s+(.*)$/);
			if (match) {
				match[1].replace(/\s*([\w.$]+)(?:\s+as\s+([\w.$]+))?,?/g, function(_, fullPath, as) {
					imports.push(
						as ? {
							from: fullPath,
							as: as
						} : {
							from: fullPath,
							as: fullPath
						});
				});
				return true;
			}
		});

		// CommonJS syntax
		jsio.addCmd(function(context, request, opts, imports) {
		
			//		./../b -> ..b
			// 		../../b -> ...b
			// 		../b -> ..b
			// 		./b -> .b
		
			var match = request.match(/^\s*[\w.0-9$\/]+\s*$/);
			if (match) {
			
				var req = util.resolveRelativePath(match[0]),
					isRelative = req.charAt(0) == '.';
			
				req = req	
					// .replace(/^\//, '') // remove any leading slash
					.replace(/\.\.\//g, '.') // replace relative path indicators with dots
					.replace(/\.\//g, '')
					.replace(/\//g, '.'); // any remaining slashes are path separators

				imports[0] = { from: (isRelative ? '.' : '') + req };
				return true;
			}
		});
	
		jsio.install = function(){
			jsio('from base import *');
			GLOBAL['logger'] = logging.get('jsiocore');
		};
	
		jsio.clone = function() {
			var copy = jsio.__init__(jsio);
			if (ENV.name == 'browser') { window.jsio = jsio; }
			return copy;
		}

		return jsio;
	}
	jsio = init();
})();
Back to Top