ServerJS/Modules/SecurableModules

From MozillaWiki
< ServerJS‎ | Modules
Revision as of 21:25, 1 March 2009 by KrisKowal (talk | contribs) (Trimmed the securable modules proposal to its essential elements and organized the remaining content into sub-pages.)
Jump to navigation Jump to search

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.

Contract

Module Context

  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 the requested module cannot be returned, "require" must throw an error.
  2. A module receives an "exports" object that it may add its exported API to as it executes.
  3. modules must use the "exports" object as the only means of exporting.

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.

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.


Sample 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

Notes

Amendment Proposals

  1. Module Environment

Implementations