ServerJS/Modules/SecurableModules

< ServerJS‎ | Modules
Revision as of 02:27, 6 February 2009 by KrisKowal (talk | contribs)

This specification addresses how modules should be written in order to be interoperable among a class of module systems that can be both client and server side, secure or insecure, implemented today or supported by future systems with syntax extensions. These modules are offered privacy of their top scope, facility for importing singleton objects from other modules, and exporting their own API.

  1. A module receives a "require" function.
    1. The "require" function accepts a module identifier.
    2. "require" returns an object containing the exported API of the foreign module.
    3. If there is a dependency cycle, the foreign module may not have finished executing at the time it is required by one of its transitive dependencies; in this case, the object returned by "require" must contain at least the exports that the foreign module has prepared before the call to require that led to the current module's execution.
    4. If a requested module does not exist, returns "undefined".
    5. If the requested module cannot be returned, "require" throws an error.
  2. A module receives an "exports" object that it may add its exported API to as it executes.
  3. Interoperable modules must use the exports object as the only means of exporting, since an implementation may prevent tampering with any other object shared among modules.

Module Identifiers

  1. A module identifier is a String of "terms" delimited by forward slashes.
  2. A term must be a camelCase identifier, ".", or "..".
  3. The extension of the file corresponding to a module identifier must be inferred by loaders.
  4. Module identifiers may be "relative" or "absolute". A module identifier is "relative" if the first term is "." or "..".
  5. Absolute identifiers are resolved off the conceptual name space root. A loader may check multiple roots in a consistent order, like a PATH.
  6. Relative identifiers are resolved relative to the file in which "require" is called.


Security

To be interoperable with secure environments, a module must satisfy the following additional constraints:

  1. A module must not have any free variables apart from primordials ("Object", "Array", etc.), "require", and "exports".
  2. A module must not tamper with (assign to, assign to members of, delete, or otherwise mutate) the transitive primordials, the "require" object, or any object returned by "require".

Unspecified

This specification leaves the following important points of interoperability unspecified:

  1. Whether relative module identifiers are supported.
  2. Whether a PATH is supported by the module loader for resolving module identifiers.


Loaders

A prototype for a client-side module loader that supports modules that conform to this specification using PATH relative URL's or module relative URL's without making security guarantees is partially complete in the ["safe" branch of modules.js].

pmuellr posted a sample loader http://wiki.github.com/pmuellr/modjewel

Sample Code

// ==================================================================
// source code

//
// math.js
//
exports.add = function() {
  var sum = arguments[0];
  for (var i=1; i<arguments.length; i++) {
    sum += arguments[i];
  }
  return sum;
};

//
// increment.js
//
var add = require('math').add;
exports.increment = function(val) {
  return add(val, 1);
};

//
// program.js
//
var inc = require('increment').increment;
var a = 1;
inc(a); // 2


// ==================================================================
// browser code in development

// locked into on of these options
//
//  1) using a special XHR synchronous script loader and    
//     less than ideal error messages with strange line numbering
//
//  2) edit-compile-load-test cycle using the code below. Also
//     strange numbering in error messages that does not match
//     source files. Tools could make compile automatic but that
//     means tools are required and that is not the case in 
//     the current browser scripting world.


// ==================================================================
// compiled for production in browser

//
// library.js
//
var require = (function() {
  
  // memoized export objects
  var exportObjects = {}

  // don't want outsider redefining "require" and don't want
  // to use arguments.callee so name the function here.
  var require = function(name) {
    if (exportsObject.hasOwnProperty(name)) {
      return exportsObject[name];
    }
    var exports = {};
    // memoize before executing module for cyclic dependencies
    exportsObject[name] = exports;
    modules[name](require, exports);
    return exports;
  };
  
  return require;
})();

var run = function(name) {
  require(name); // doesn't return exports
};

var modules = {};

//
// compiledModules.js
//
modules["math"] = function(require, exports) {
  exports.add = function() {
    var sum = arguments[0];
    for (var i=1; i<arguments.length; i++) {
      sum += arguments[i];
    }
    return sum;
  };
};

modules["increment"] = function(require, exports) {
  var add = require('math').add;
  exports.increment = function(val) {
    add(val, 1);
  };
};

modules["program"] = function(require, exports) {
  var inc = require('increment').increment;
  var a = 1;
  inc(a); // 2
};

//
// html in document head
//
<script src="library.js" type="text/javascript"></script>
<script src="compiledModules.js" type="text/javascript"></script>
<script type="text/javascript">
  // You might not use use the window.onload property
  // but rather addEventListener/attachEvent.
  window.onload = function() {
    run("program");
  };
</script>

Browser Sharable as Written

It would be handy to be able to share modules "as written" with the browser loading the scripts with html script tags. I think the following source code allows this feature. The first and last lines of the modules would be idiomatic boilerplate for modules to be shared on both the client and server.

Note that "modules" is some global supplied on the browser's global object. "exports" is not a property of the browser's global object.

// ==================================================================
// source code

//
// math.js
//
var mod = function(require, exports) {

	exports.add = function() {
	  var sum = arguments[0];
	  for (var i=1; i<arguments.length; i++) {
	    sum += arguments[i];
	  }
	  return sum;
	};

};
if (exports) {f(require,exports);} else {modules["math"] = mod;}

//
// increment.js
//
var mod = function(require, exports) {

	var add = require('math').add;
	exports.increment = function(val) {
	  return add(val, 1);
	};
	
};
if (exports) {f(require,exports);} else {modules["increment"] = mod;}


//
// program.js
//
var inc = require('increment').increment;
var a = 1;
inc(a); // 2