gloader/ 40755 0 0 0 11225123760 7524 5ustar 0 0 gloader/0.1.0/ 40755 0 0 0 11225123760 10160 5ustar 0 0 CONTRIBUTORS100644 0 0 0 11225123761 7773 0ustar 0 0 LICENCE100644 0 0 23676 11225123761 7230 0ustar 0 0 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS README100644 0 0 44523 11225123761 7115 0ustar 0 0 Creating Modules to Work With Gloader ---- Overview and Features ==== Gloader is a JavaScript module loader that was created for the BBC Glow project (think "glow" + "loader" = "gloader"). It will work, however, just as well with any JavaScript library that follows the same module pattern. There are several benefits to using Gloader versus simply including your JavaScript via script tags. The basic features of Gloader are: * Loads JavaScript modules either synchronously or asynchronously * Automatically loads all dependent modules in the dependancy chain * Automatically loads related CSS files for each module * Can automatically resolve module versions to the latest available * Works across servers, no same-server restrictions * Can sandbox loaded modules, keeping them out of the global namespace * Supports a very wide range of popular browsers The prerequisite to these benefits is that you write your code according to Glow's module pattern. Gloader's Idea of a "Module" ==== The JavaScript language does not include a module feature, but we can define our own modules in user code. Basically we are striving to have a chunk of related functionality in a self-contained package, a "module". Modules need to provide some metadata to the loader, including: what library they belong to, which version identifier describes them, and what other modules they depend on. Finally a module needs to define a function (called a "builder") that will build and return the module object itself. Gloader's Idea of a "Library" ==== A group of related modules are grouped together under a single library. The library itself is also a module, but what makes the library module special is that it can contain child modules. Every library must have exactly one library module. An Example of a Library Module ==== As explained previously a library is actually a special kind of module, and you must have exactly one library module in your library. Bearing that in mind, when creating a new library you should start with the library module. It will follow a pattern that looks like this: // how to create a library gloader.library({ name: "myLibrary", version: "1.0.0", builder: function () { // this is where you create your library module var myLibrary = {}; // <-- can be anything return myLibrary; } }); It is conventional that you use a variable-like name for your library but in fact the `name` can be any string containing any combination of characters except for the forward-slash character "/", which is reserved and has special meaning to Gloader. Likewise the `version` identifier can be any string containing any characters except for the forward-slash. However if you follow the convention of using a version identifier pattern like: `..` you will gain special functionality from Gloader in which it can automatically manage version updates for you (this will be discussed later). The `builder` function is where you actually create your library object. You can execute any code you like inside the builder, but it is recommended that you create a function-scoped object by using the `var` keyword as shown and then return a reference to it at the end of the builder function. Following this pattern will allow Gloader to "sandbox" your library so that people can eventually maintain multiple versions of a single library on the single page. An Example of a Module ==== Once you have a library you can proceed to attach modules to it. The process of defining a module is very similar to that of defining a library: // how to create a module gloader.module({ name: 'myLibrary.myModule', library: ['myLibrary', '1.0.0'], builder: function(myLibrary) { myLibrary.myModule = {}; } }); The difference is that a module must define what library (library name and library version) it belongs to. Notice that a module does not have it's own version identifier, instead modules always inherit their version identifiers from their library. Therefore this module, named "myLibrary.myModule", is version "1.0.0". As with the library module definition, the module definition has a builder function, however the builder for a module will always receive a single argument: the library object which was returned from the library's builder. To the library object and you can attach your module object. Dependencies ==== Any module definition can optionally list other modules as dependencies. For example, if you were to define a second module that depended on the module we defined in the previous section, it would be written like so: gloader.module({ name: 'myLibrary.myOtherModule', library: ['myLibrary', '1.0.0'], depends: [ ['myLibrary', '1.0.0', 'myLibrary.myModule'] ], builder: function(myLibrary) { myLibrary.myOtherModule = {}; } }); The `depends` option is an array of arrays: the inner arrays define the dependent library name, library version, and zero or more modules from that library. Variations on that could be written like so: // only need the library depends: [ ['myLibrary', '1.0.0'] ] // need several modules from the same library depends: [ ['myLibrary', '1.0.0', 'myLibrary.myModule', 'myLibrary.Etc'] ] //need modules from the several libraries depends: [ ['myLibrary', '1.0.0', 'myLibrary.myModule', 'myLibrary.Etc'], ['myOtherLibrary', '1.2.0', 'myOtherLibrary.myModule'] ] The File Map ==== When interacting with gloader you will refer to modules by their name and version, but in order for the source code to be found by gloader it must know where the corresponding file is found, this information is defined in the library file map. File Layout ==== It is recommended that you organise your files so that the entire library is contained below a single library folder (of course you may have as many sub folders as you wish within the library folder), and that you name the library folder the same as your library. So, to continue the example, I would place my library source files in a folder named `myLibrary`. It isn't necessary that each module be in a separate file, you can combine and mix modules within files as you please. This will be transparent to the users of your library of course because they will simply request the modules they want by name. Within the library folder you should have a map file named "map.js" which will allow gloader to find the requested module source code. Within the library folder you should have a single folder for each version of the library. These will have a name that corresponds exactly to the version identifier you used in your library definition. At a level just above the library folder will sit the gloader.js file itself. By using this convention in organising your files you can greatly simplify working with gloader. gloader.js myLibrary/ myLibrary/map.js myLibrary/1.0.0/ myLibrary/1.0.1/ Creating a Map File ==== As described previously, the map file allows you to define which modules are in which files. It is conventional to put a single module in a single file, but this is not a requirement, in fact the whole point of the map file is to allow you to combine modules together as you wish without your users ever needing to even know about it. For illustration purposes, assume we have laid our library source code out like so: myLibrary/map.js myLibrary/1.0.0/myLibrary.js myLibrary/1.0.0/myModule.js myLibrary/1.0.0/myOtherModule.js We would then need to write our map file so that it associates the modules with their corresponding files. In this case it would look like this: gloader.map.add( "myLibrary", { $version : "1.0.0", "myLibrary" : "{$base}myLibrary.js", "myLibrary.myModule" : "{$base}myModule.js", "myLibrary.myOtherModule" : "{$base}myOtherModule.js" } ); Notice that the general format is: "module name": "path to source code file" Now you should be able to see that by altering these values we can name our files whatever we like, and can even put multiple modules in the same file. Special Properties in Maps ==== In the preceding example you may have noticed some special properties that have names beginning with `$`. In a map definition any property that begins with the dollar-sign is special because its value can be interpolated inside other values. The `$base` property for example is, by default, the same directory where `gloader.js` lives plus the library name and version number. In this case the $base is, by default: mylibrary/{$version}/ Where does the value for $version come from? As you can see from the example map, we define the `$version` property in the map definition. So since we defined the $version to be `"1.0.0"`, the $base then becomes `"mylibrary/1.0.0/"` and the location of the myLibrary module then becomes `"mylibrary/1.0.0/myLibrary.js"`, which as it happens is exactly where we put it. Because the $base is built on the current location of the gloader.js file, you can safely move your library folder anywhere, and as long as it is in the same directory as gloader.js, everything will automatically continue to just work. Including a CSS File With a Module ==== If your JavaScript module requires a CSS file in order to work, you can add that to the appropriate map entry, and Gloader will automatically manage loading of that file as well. gloader.map.add( "myLibrary", { $version : "1.0.0", "myLibrary" : "{$base}myLibrary.js", "myLibrary.module" : ["{$base}module.js", "{$base}module.css"] } ); Adding More Versions to Your Map ==== If you release a new version of your library, this must be indicated in the map as well. However, if your new version has exactly the same file layout as the previous version you do not need to repeat all that information again, you only ever need to add what is different. So if your new version were named `1.0.1`, but the file layout was the same, you would only need to add a new version number: gloader.map.add( "myLibrary", { $version : "1.0.0", "myLibrary" : "{$base}myLibrary.js", "myLibrary.myModule" : "{$base}myModule.js", "myLibrary.myOtherModule" : "{$base}myOtherModule.js" }, { $version : "1.0.1" } ); In this case all the previous module to file mappings will be inherited by the new version, with of course the new version number substituted in the $base.As long as you don't change any module to file associations you can continue this pattern indefinitely, adding more versions as you go. Adding or Removing Modules From Your Map ==== It is likely that eventually you will want to add or remove module to your map. Any differences from the previous version must be indicated in your map definition. If you want to add a new module, but all the other modules are the same, only add the new module to your version: gloader.map.add( "myLibrary", { $version : "1.0.0", "myLibrary" : "{$base}myLibrary.js", "myLibrary.myModule" : "{$base}myModule.js", "myLibrary.myOtherModule" : "{$base}myOtherModule.js" }, { $version : "1.0.1" }, { $version : "1.2.0", "myLibrary.myNewModule" : "{$base}myNewModule.js" } ); On the other hand if you wish to remove an existing module from a version, you can indicate this by setting it's file location to `null`. For example, this is how you would indicate that the ill-considered "myLibrary.myNewModule" was later removed from the library in version 1.3.0: gloader.map.add( "myLibrary", { $version : "1.0.0", "myLibrary" : "{$base}myLibrary.js", "myLibrary.myModule" : "{$base}myLibrary/myModule.js", "myLibrary.myOtherModule" : "{$base}myLibrary/myOtherModule.js" }, { $version : "1.0.1" }, { $version : "1.2.0", "myLibrary.myNewModule" : "{$base}myLibrary/myNewModule.js" }, { $version : "1.3.0", "myLibrary.myNewModule" : null } ); Keeping the Map Up-To-Date ==== It is important that your map accurately reflect the current file-layout of your library. Because it isn't possible to see a directory listing from within JavaScript, Gloader is in essence blind to what files are in the library folder, and the map is the only way for it to know what's "out there". Every time you add a new version release to your library you must indicate this in the map, otherwise Gloader will be unaware of it and thus won't be able to load it. Including Gloader ==== Once you have defined your library and modules, and created a map, you are ready to utilise gloader to load your modules. In a web page, add a `script` tag with a `src` attribute that points to your gloader.js file. Inside that same tag, add a call to the `gloader.use()` method. This will initialise the global `gloader` object and will tell it to read the map data about your library. By default that map is assumed to be relative the gloader.js file, in a folder named after the library, and in a file named "map.js". If your map is actually somewhere else, you must indicate that like so: Loading Modules ==== Once you have initilised the `gloader` object, you can use it to load modules. To load just the library module, use a syntax like this: Or load specific modules like so: Getting the Latest Version ==== If you give your modules version identifiers that follow a pattern of three dotted integers, like 1.2.3, you can take advantage of Gloader's ability to automatically load the latest available version when you request a non-specific version of a module. For example if your web page requests version "1" of a module (without specifying the minor version), Gloader will find the version of that module with a major version of "1", and _the highest available minor version_. This system works for minor versions too, so requesting "1.2" will load the latest bugfix version with a major and minor version of "1.2". Of course if your specify a full version like "1.0.0" Gloader will load exactly that version. When Things Go Wrong ==== Even the best laid plans can sometimes suffer problems. If your module isn't appearing, even though you asked Gloader to load it, there are a few things you can try. Firstly, it isn't possible for Gloader to detect a 404 "Not Found" error from your server. In cases where a module is requested but it never arrives, Gloader will patiently wait forever, or at least long enough for your browser to give up. In these cases a look at FireBug's "Network" tab will tell you if one of your files is cannot be found. If you try to load a module which is not listed in your map file (for exampl if you misspelled the name), this is obviously a mistake that Gloader can detect immediately and you will see an error message like: 'The gloader map is missing a JavaScript filepath for the module: mispeld/1.0.0/myModule". Maps included are: myLibrary/map.js'. This tells you the path to the map from which Gloader is working, and the libraryname, version and module name which can't be found in that map. In some cases it might be useful to tell Gloader that it should not wait forever for modules which are not available from the server. You can provide a "onTimeout" option which is a callback function that will be executed whenever a requested module does not arrive in less than 20 seconds. If you think 20 seconds is too long to wait, you can also provide a "timeout" option, which is the number of milliseconds to wait before running the callback. Going Around Gloader ==== You may wish to write your modules so that they can be used with or without Gloader. If your users don't have the `gloader` object defined in their web page, then trying to call `gloader.library()` or `gloader.module()` is obviously not going to work. To accommodate this you could write your modules to check for the problem and work around it: (function() { var builder = function(myLibrary) { myLibrary.myModule = {}; }; if (typeof gloader != "undefined") { gloader.module({ name: 'myLibrary.myModule', library: ['myLibrary', '1.0.0'], builder: builder }); } else { builder(myLibrary); } })(); By using this pattern you allow your users to include your module via `gloader.load()` or optionally via a simple script tag. Of course, without Gloader's help it is left up to the user to manage loading of dependencies in the right order. for example, here we are assuming that a global object named `myLibrary` is defined already. There is a special error case that is worth mentioning here, and it arises when you have the `gloader` object defined in your webpage but try to include a module from your library by using a script tag anyway. In that case Gloader will still "receive" the module anyway, whether you intended it to or not (because `gloader` will be defined, the logic says it will get it's `module()` method called). In this case Gloader will notify you of the problem by throwing an error with a message that says so. the only remedy for this is to avoid the situation in teh first place by only loading modules via script tags before (or as an alternative to) you include Gloader on your page. gloader/0.1.0/gloader.debug.js100644 0 0 66513 11225123760 13350 0ustar 0 0 /* Copyright 2009 British Broadcasting Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** A module loader for Glow. */ (function(){ if (window.gloader) return; window.gloader = { _requests: [], // {gloader.Request} _modules: {}, // modId: {gloader.Module|undefined} _expects: {}, // modId: {Number} - module definitions that are expected but were not requested _extras: {}, // modId: {Object} - module definitions provided but not yet requested _errors: [], // {String} - used for testing purposes util: { /** Determine if a filepath could be the name of this file. */ getGloaderFile: function(filepath) { // the gloader file can have a few name variations, but will always start with "gloader" and end with ".js" (excluding possible querystring) if (filepath && /(^|^.*[\/\\])(gloader(\.[^\/\\]+)?\.js)(\?|$)/i.test(filepath)) { var dir = RegExp.$1; //// as a temporary fix to the problem of the gloader upgrade, remove any "cached/" from the dir if (dir) dir = dir.replace("cached/", ""); return { dir: dir, name: RegExp.$2 }; } return undefined; // the filepath is not possibly this file } }, /** Locations of all known module files. */ map: { /** Locations of known javascript files. */ js: {}, // modId: URL /** Locations of known stylesheet files. */ css: {}, // modId: URL /** Interpolate values in the given library definition. */ parse: function(libraryName, libraryVersions) { /*debug*///console.log("gloader.map.parse("+libraryName+", "+libraryVersions+")"); // create an empty library object to be returned at the end var lib = {name: libraryName, versions: []}; // keep track of the properties set in previous version definitions // like: {$someName: "someValue"} var scope = {}; // required scope properties // order controls order of interpolation // e.g. a $base can contain a {$version}, but not visa versa // $name means the library's name var scopeProps = ["$name", "$version", "$base"]; scopeProps.has = function(what) { // just a quick convenience method for (var i = 0; i < this.length; i++) { if (what == this[i]) return true; } return false; } // include user defined properties if (gloader.mapProps && gloader.mapProps[lib.name]) { for (var p in gloader.mapProps[lib.name]) { if (!scopeProps.has(p)) { // scopeProps items will be unique scopeProps.push(p); } } } // initialize the scope object for (var p = 0; p < scopeProps.length; p++) { scope[scopeProps[p]] = undefined; } scope.$name = lib.name; // set user-defined properties in scope if (gloader.mapProps && gloader.mapProps[lib.name]) { for (var p in gloader.mapProps[lib.name]) { scope[p] = gloader.mapProps[lib.name][p]; } } // loop over each version definition for (var i = 0; i < libraryVersions.length; i++) { var version = libraryVersions[i]; // add to or delete from the scope any version properties, for (var v in version) { // a value of type null means: "delete" from scope if (version[v] === null) { delete version[v]; delete scope[v]; } // a non-null value means: "add" (or overwrite) to scope else { if (v.indexOf("$") === 0) scope[v] = version[v]; // $values must be strings else if (typeof version[v] == "string") { version[v] = [version[v]]; // other values must be arrays scope[v] = version[v].slice(0); // copy } else if (typeof version[v].push != "undefined") { // already an array? scope[v] = version[v].slice(0); // copy; } else throw new Error("invalid type: "+typeof version[v]); } } // fill in any undefined version properties that were defined before for (var s in scope) { if (typeof version[s] == "undefined") { if (s.indexOf("$") === 0) version[s] = scope[s]; else version[s] = scope[s].slice(0); // copy } } // interpolate all {$var} strings in all version properties with $prop values for (var p = 0; p < scopeProps.length; p++) { var prop = scopeProps[p]; for (var vp = 0; vp < p; vp++) { var vprop = scopeProps[vp]; if (typeof version[vprop] == "undefined") version[prop] = scope[prop]; // this version does not redefine this property var patt = new RegExp('\\{\\'+vprop+'\\}', "g"); version[prop] = version[prop].replace(patt, version[vprop]); } } // interpolate all {$var} strings in all version items with $prop values for (vi in version) { if (vi.indexOf("$") === 0 ) continue; // these have already been interped for (var vii = 0; vii < version[vi].length; vii++) { for (var p = 0; p < scopeProps.length; p++) { var prop = scopeProps[p]; var patt = new RegExp('\\{\\'+prop+'\\}', "g"); version[vi][vii] = ""+version[vi][vii].replace(patt, ""+version[prop]); } } } lib.versions.push(version); } return lib; }, /** Populate this map with some library data. @param {String} libraryName The name of the library you are adding. @param {Object} ... One or more objects that define the files in the various versions of this library. */ add: function() { /*debug*///console.log("gloader.map.add("+arguments+")"); // note trick to convert arguments into an array (less the first item) var args = []; for (var i = 1; i < arguments.length; i++) { args.push(arguments[i]); } var lib = gloader.map.parse(arguments[0], args); // populate the js and css tables with the interpolated key/values: modId => src for (var i = 0; i < lib.versions.length; i++) { var version = lib.versions[i]; for (var p in version) { if (p.charAt(0) == "$") continue; // for gloader use only // modId like: libraryName/versionId/moduleName var modId = version.$name+"/"+version.$version+"/"+p; // note: can overwrite gloader.map.js[modId] = version[p][0]; gloader.map.css[modId] = version[p][1]; } } }, /** A map from elsewhere is included in this one. This must be synchronous. */ include: function(src) { /*debug*///console.log("gloader.map.include("+src+")"); if (gloader.map._include[src]) { // is already included so can skip doing so again return false } else { document.write('\n'); gloader.map._include[src] = true; return true; } }, _include: {}, // memoize /** Get the value of the latest minor version number of a library. */ latest: function(libName, v) { /*debug*///console.log("gloader.map.latest("+libName+", "+v+")"); if (gloader.map.$latest[libName+"/"+v]) { return gloader.map.$latest[libName+"/"+v]; } var result = v; var parts = v.split("."); // if the version is not fully specified if (parts.length < 3) { // if the version is in the format maj[.min] if ( parts[0] == parseInt(parts[0]) && (typeof parts[1] == "undefined" || parts[1] == parseInt(parts[1])) ) { var invalid = new RegExp("[a-zA-Z\-]"), latest = [parts[0], null, null], mod; for (mod in gloader.map.js) { var modParts = mod.split("/"); if (modParts[0] == libName && modParts[2] == libName && !invalid.test(modParts[1])) { var modVParts = modParts[1].split("."); if (modVParts[0] == parts[0]) { // same major if ( ( typeof parts[1] == "undefined" // no particular minor version was requested && // and either... ( latest[1] <= modVParts[1] // the current latest minor version is not more recent as this module || // or ( latest[1] == modVParts[1] // and the current latest minor version matches this module's minor version && latest[2] <= modVParts[2] // and the latest bug version is not more recent as this module's bug version ) ) ) || // or ( typeof parts[1] != "undefined" // a particular minor version was requested && parts[1] == modVParts[1] // and the requested minor version matches this module's minor version && latest[2] <= modVParts[2] // and the latest bug version is not more recent as this module's bug version ) ) { latest[1] = modVParts[1]; latest[2] = modVParts[2]; } } } } if (latest[2] != null) result = latest.join("."); } } gloader.map.$latest[libName+"/"+v] = result; return result; }, $latest: {} // memoize }, /** Give values to states that gloader can refer to. */ settings: { ns: "bbc.glow.gloader", get: function(name) { /*debug*///console.log("get("+name+")"); var n = " "+gloader.settings.ns+"."+name+"=" var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++) { if ((" "+cookies[i]).indexOf(n) > -1) { return unescape(cookies[i].split("=")[1]); } } }, set: function(name, value, path) { /*debug*///console.log("set("+name+", "+value+")"); var n = gloader.settings.ns+"."+name; document.cookie = n + "=" + escape(value) + "; path="+((path)? path : "/")+";"; }, clear: function(name, path) { /*debug*///console.log("clear("+name+")"); var d = new Date(); d.setTime(d.getTime() - 1); var n = gloader.settings.ns+"."+name; document.cookie = n + "=; path="+((path)? path : "/")+"; expires=Thu, 01-Jan-70 00:00:01 GMT;"; } }, // javascript:(function(){gloader.loadOverride()})(); loadOverride: function(version) { var current = gloader.settings.get("override"); version = version || prompt("Enter version", current ? current : ""); if (version === "") gloader.settings.clear("override"); else if (version !== null) gloader.settings.set("override", version); location.reload(); }, // javascript:(function(){gloader.loadDebug()})(); loadDebug: function() { gloader.settings.set("debug", "1"); location.reload(); }, // javascript:(function(){gloader.unloadDebug()})(); unloadDebug: function() { gloader.settings.clear("debug"); location.reload(); }, expect: function(srcFile) { /*debug*///console.log("expecting modules in "+srcFile); srcFile = ""+srcFile; var modsInFile = []; var modId; for (modId in gloader.map.js) { if (gloader.map.js[modId] == srcFile) { modsInFile.push(modId); gloader._expects[modId] = (gloader._expects[modId] || 0)+1; } } }, /** The user makes a request. */ load: function() { /*debug*///console.log("gloader.load(...)"); var r = {}; if (typeof arguments[arguments.length-1].length == "undefined") { r = arguments[arguments.length-1]; arguments.length--; } var newRequest = new gloader.Request(r); gloader._requests.push(newRequest); var mods = []; var override = gloader.settings.get("override"); for (var i = 0; i < arguments.length; i++) { if (override && arguments[i][0] == "glow") { // warn the user what we've done if (typeof console != "undefined" && console.log) console.log("Overriding version '"+arguments[i][1]+"' of glow to version '"+override+"'"); arguments[i][1] = override; } mods.push(arguments[i]); } var ids = gloader.toIds(mods); newRequest.args = []; for (var i = 0; i < ids.length; i++) { newRequest.include(ids[i]); if (ids[i].match(/\/[^.]+$/)) { newRequest.args.push(ids[i]); } } // if all the requested modules are already loaded we can short-circuit var waitCount = newRequest.waits.length; for (var i = 0; i < newRequest.waits.length; i++) { if ( gloader._modules[newRequest.waits[i]] && gloader._modules[newRequest.waits[i]].status == gloader.Module.IMPLEMENTED ) waitCount--; } if (waitCount > 0) { newRequest.status = gloader.Request.WAITING; gloader.request(ids, newRequest.async); gloader.resolve(); } else { /*debug*///console.info("skipping the download"); newRequest.complete(); } // ====> opera 9.2 always exits here, it evalualtes *all* code inline. }, /** We need some module files to complete a request. */ request: function(mIds, async) { /*debug*///console.log("gloader.request(["+mIds.join(",")+"], "+async+")"); for (var i = 0; i < mIds.length; i++) { if (gloader._extras[mIds[i]]) { // module was provided before it was requested gloader._modules[mIds[i]] = new gloader.Module(mIds[i]); var extra = gloader._extras[mIds[i]]; delete gloader._extras[mIds[i]]; gloader.provide(extra); } else if (!gloader._modules[mIds[i]]) { gloader._modules[mIds[i]] = new gloader.Module(mIds[i]); gloader._modules[mIds[i]].status = gloader.Module.REQUESTED; } } for (var m in gloader._modules) { if (gloader._modules[m].status < gloader.Module.IMPLEMENTED || gloader._modules[m].css) { gloader._modules[m].css = null; // the module was already fetched (asynchronously) and hasn't // yet arrived, but now is requested again synchronously, // in this case we must force the fetch to happen twice var force = (!async && gloader._modules[m].async == true && gloader._modules[m].status >= gloader.Module.FETCHED); gloader.fetch(gloader._modules[m], async, force); } } }, /** Inject a module file into this web page. */ fetch: function(m, async, force) { /*debug*///console.log("gloader.fetch("+m.id+", "+async+")"); gloader._modules[m.id].async = async; var cssSrc = gloader.map.css[m.id]; if (force || (cssSrc && !gloader._fetched[cssSrc])) { /*debug*///console.log("injecting css file: "+cssSrc); gloader._fetched[cssSrc] = 1; if (document) { var headElement; if (headElement = document.getElementsByTagName('head')[0]) { var link; if (link = document.createElement('link')) { link.href = cssSrc; link.rel = 'stylesheet'; link.type = 'text/css'; link.className = 'gloaded'; headElement.appendChild(link); } } else { document.write(''); } } } if (!force && gloader._modules[m.id].status >= gloader.Module.FETCHED) return false; gloader._modules[m.id].status = gloader.Module.FETCHED; var jsSrc = gloader.map.js[m.id]; if (!jsSrc) { var msg = "The gloader map is missing a JavaScript filepath for the module: "+m.id; var maps = []; for (var included_map in gloader.map._include) maps.push(included_map); msg += ".\rMaps included are: "+maps.join(", ")+"."; gloader._errors.push(msg); throw new Error(msg); } if (force || (jsSrc && !gloader._fetched[jsSrc])) { /*debug*///console.log("fetching js file: "+jsSrc); gloader._fetched[jsSrc] = 1; // given the source file, we should expect all the modules in that source file gloader.expect(jsSrc); if (async) { /*debug*///console.log("inject: "+jsSrc); var headElement = document.getElementsByTagName('head')[0]; var scriptElement = document.createElement('script'); scriptElement.type = 'text/javascript'; scriptElement.src = jsSrc; headElement.appendChild(scriptElement); } else { /*debug*///console.log("write: "+jsSrc); document.write('\n'); } } }, _fetched: { }, /** A module file has arrived (been provided). @param {object} m The module definition from the remote source file. */ provide: function(m) { /*debug*///console.log("gloader.provide("+m.library[0]+"/"+m.library[1]+"/"+m.name+")"); m.id = m.library[0]+"/"+m.library[1]+"/"+m.name; // modifying the module definition from the remote file if (!gloader._modules[m.id]) { // we got more modules than we requested gloader._extras[m.id] = m; return; } gloader._modules[m.id].status = gloader.Module.PROVIDED; gloader._modules[m.id].builder = m.builder; gloader._modules[m.id].builder.args = []; var d = gloader._modules[m.id].depends = (m.depends)? gloader.toIds(m.depends) : []; if (d.length > 0) { var includes = []; for (var i = 0; i < d.length; i++) { var requests = gloader.getRequests(m); var include = {async: true, ids: []}; for (var j = 0; j < requests.length; j++) { requests[j].include(d[i]); include.ids.push(d[i]); if (requests[j].async === false) { // are there any requests for this module that are sync? include.async = false; } } includes.push(include); if (d[i].match(/\/[^.]+$/)) { gloader._modules[m.id].builder.args.push(d[i]); } } for (var i = 0; i < includes.length; i++) { gloader.request(includes[i].ids, includes[i].async); } } else { // module is provided and has no depends gloader.implement(m); } gloader.resolve(); // ====> firefox, et al exit here. }, // check: are we expecting this module? warn user if they are including // a module via an inline script tag while gloader is defined _greet: function(modId) { if (gloader._expects[modId] > 0) { // were we expecting this module or not gloader._expects[modId]--; } else { var msg = "Unexpected module provided to gloader: "+modId; gloader._errors.push(msg); throw(msg); } }, /** Wrapper for provide() with some specialisation for modules. */ module: function(modDef) { /*debug*///console.log("gloader.module("+modDef.name+")"); var modId = modDef.library[0]+"/"+modDef.library[1]+"/"+modDef.name; gloader._greet(modId); if (!modDef.depends) modDef.depends = []; modDef.depends.unshift(modDef.library); // modules implicitly depend on their own library gloader.provide(modDef); }, /** Wrapper for provide() with some specialisation for libraries. */ library: function(modDef) { /*debug*///console.log("gloader.library("+modDef.name+")"); var modId = modDef.name+"/"+modDef.version+"/"+modDef.name; gloader._greet(modId); if (!modDef.depends) modDef.depends = []; modDef.library = [modDef.name, modDef.version]; // a library module is a member of its own library gloader.provide(modDef); }, /** All dependents for a given module are available now. We can implement the module. */ implement: function(module) { /*debug*///console.log("gloader.implement("+module.id+"), module.status is "+gloader._modules[module.id].status); if (gloader._modules[module.id].status != gloader.Module.PROVIDED) return; gloader._modules[module.id].status = gloader.Module.IMPLEMENTED; for (var i = 0; i < gloader._modules[module.id].builder.args.length; i++) { var argName = gloader._modules[module.id].builder.args[i]; gloader._modules[module.id].builder.args[i] = gloader._modules[module.builder.args[i]].implementation; gloader._modules[module.id].builder.args[i].name = argName; } gloader._modules[module.id].implementation = gloader._modules[module.id].builder.apply(null, gloader._modules[module.id].builder.args); for (var i = 0; i < gloader._requests.length; i++) { gloader._requests[i].release(module.id); } }, /** Follow chain of modules and dependents being released. */ resolve: function() { /*debug*///console.log("gloader.resolve()"); MODULES: for (var m in gloader._modules) { var module = gloader._modules[m]; if (module.status == gloader.Module.PROVIDED) { for (var j = 0; j < module.depends.length; j++) { var dModule = gloader._modules[module.depends[j]]; if (!dModule || dModule.status != gloader.Module.IMPLEMENTED) { continue MODULES; } } gloader.implement(module); gloader.resolve(); } } }, /** Find all requests to which a given module belong. */ getRequests: function(m) { /*debug*///console.log("gloader.getRequests("+m.id+")"); var requests = []; REQUESTS: for (var i = 0; i < gloader._requests.length; i++) { var request = gloader._requests[i]; for (var j = 0; j < request.waits.length; j++) { if (request.waits[j] == m.id) { requests.push(request); break REQUESTS; } } } return requests; }, /** Turn a nested array of module defs into a flat array of id strings. */ toIds: function(lib) { var result = []; for (var i = 0; i < lib.length; i++) { var mods = lib[i]; var libName = mods.shift(); // modifies array mods refers to var libVersion = mods.shift(); var libId = libName+"/"+gloader.map.latest(libName, libVersion); result.push(libId+"/"+libName); for (var j = 0; j < mods.length; j++) { result.push(libId+"/"+mods[j]); } } return result; } }; /** A request, made by the user, for one or more modules to be loaded. @constructor */ gloader.Request = function(r) { /*debug*///console.log("gloader.Request("+r+")"); this.waits = []; this.status = gloader.Request.INITIAL; // normalize synonyms if (r.onLoad) r.onload = r.onLoad; if (r.onTimeout) r.ontimeout = r.onTimeout; // is this module implicitly meant to set global variables (no sandbox)? if (!r.async && !r.onload) { this.setGlobal = true; } this.async = (typeof r.async != "undefined")? r.async : false; this.onload = r.onload; if (r.ontimeout) { if (typeof r.timeout == "undefined") r.timeout = 20000; // 20 seconds this.timeoutRef = setTimeout(r.ontimeout, r.timeout); } } gloader.Request.INITIAL = -1; gloader.Request.WAITING = 0; gloader.Request.COMPLETED = 1; /** Need to wait for another module before we can complete. */ gloader.Request.prototype.include = function(mId) { /*debug*///console.log("gloader.Request#include("+mId+")"); for (var i = 0; i < this.waits.length; i++) { if (this.waits[i] == mId) return; } this.waits.push(mId); } /** Some module we are waiting for has become available, check if we can complete. */ gloader.Request.prototype.release = function(mId) { /*debug*///console.log("gloader.Request#release("+mId+")"); var implementCount = 0; for (var i = 0; i < this.waits.length; i++) { var wModule = gloader._modules[this.waits[i]]; if (wModule && wModule.status == gloader.Module.IMPLEMENTED) { implementCount++; } } if (implementCount == this.waits.length) { this.complete(); } } /** All modules for a request are available now. We can complete the request. */ gloader.Request.prototype.complete = function() { /*debug*///console.log("gloader.Request#complete()"); if (this.setGlobal) { for (var i = 0; i < this.waits.length; i++) { var gModule = gloader._modules[this.waits[i]]; window[gModule.name] = gloader._modules[this.waits[i]].implementation } } if (this.status == gloader.Request.COMPLETED) return; this.status = gloader.Request.COMPLETED; if (this.timeoutRef) clearTimeout(this.timeoutRef); for (var i = 0; i < this.args.length; i++) { this.args[i] = gloader._modules[this.args[i]].implementation; } if (this.onload) this.onload.apply(null, this.args); } /** Represents a module that can be in any state of loaded. @constructor */ gloader.Module = function(mId) { this.id = mId; this.name = mId.split("/").pop(); this.status = gloader.Module.INITIAL; this.css = gloader.map.css[mId]; } gloader.Module.INITIAL = -1; gloader.Module.REQUESTED = 0; gloader.Module.FETCHED = 1; gloader.Module.PROVIDED = 2; gloader.Module.IMPLEMENTED = 3; // for modules that need to detect dom readiness, but get loaded too late... gloader.isReady = false; (function(){ var d = document; if (/*@cc_on!@*/false) { // polling for no errors if (typeof window.frameElement != 'undefined') { // we can't use doScroll to test if we're in an iframe... d.attachEvent("onreadystatechange", function() { if (d.readyState == "complete") { d.detachEvent("onreadystatechange", arguments.callee); gloader.isReady = true; } }); } else { (function () { try { // throws errors until after ondocumentready d.documentElement.doScroll('left'); } catch (e) { setTimeout(arguments.callee, 50); return; } // no errors gloader.isReady = true; })(); } } else if (typeof d.readyState != 'undefined') { var f = function() { /loaded|complete/.test(d.readyState) ? gloader.isReady = true : setTimeout(f, 10); }; f(); } else { var callback = function () { if (arguments.callee.fired) { return; } arguments.callee.fired = true; if (gloader) gloader.isReady = true; }; d.addEventListener("DOMContentLoaded", callback, false); var oldOnload = window.onload; window.onload = function () { if (oldOnload) { oldOnload(); } callback(); }; } })(); gloader.map.setProperties = function(libraryName, props) { /*debug*///console.log("gloader.map.setProperties("+libraryName+", "+props.toSource()+")"); if (typeof gloader.mapProps == "undefined") gloader.mapProps = {}; if (typeof gloader.mapProps[libraryName] == "undefined") gloader.mapProps[libraryName] = {}; for (var p in props) { gloader.mapProps[libraryName][p] = props[p]; } } gloader.use = function(name, opts) { /*debug*///console.log("gloader.use("+name+", "+opts+")") name = (name || "glow"); opts = (opts || {}); var properties = {}; for (var opts_name in opts) { var property_name = (opts_name.indexOf('$') == 0)? opts_name : '$'+opts_name; properties[property_name] = opts[opts_name]; } // default values properties.$debug = (properties.$debug || ""); properties.$base = (properties.$base || gloader._baseDir+name+"/{$version}/"); properties.$map = (properties.$map || gloader._baseDir+name+"/map.js"); gloader.map.setProperties( name, properties ); gloader.map.include(properties.$map); }; })(); // using Resig's "degrading script" pattern. // first script tag on the page with src=gloader.js wins. (function() { var scripts = document.getElementsByTagName("script"); for (var i = 0; i < scripts.length; i++) { // does this script tag look like it is pointing to gloader? var src = scripts[i].getAttribute("src"); var filespec = gloader.util.getGloaderFile(src); if (typeof filespec != "undefined") { gloader._baseDir = filespec.dir; // is the content of this script node non-empty? is so then eval the contents var gloaderScript = scripts[i].innerHTML; if (/\S/.test(gloaderScript)) { eval(gloaderScript); } // the user should have configured gloader by now, if not we configure it ourselves with defaults var mapped = false; for (var p in gloader.map._include) { mapped = true; continue; } if (!mapped) { gloader.use(); } // no maps mean the configuration didn't happen? break; } } })();gloader/0.1.0/gloader.js100644 0 0 35573 11225123761 12266 0ustar 0 0 /* Copyright 2009 British Broadcasting Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function(){if(window.gloader){return;}window.gloader={_requests:[],_modules:{},_expects:{},_extras:{},_errors:[],util:{getGloaderFile:function(filepath){if(filepath&&/(^|^.*[\/\\])(gloader(\.[^\/\\]+)?\.js)(\?|$)/i.test(filepath)){var dir=RegExp.$1;if(dir){dir=dir.replace("cached/","");}return{dir:dir,name:RegExp.$2};}return undefined;}},map:{js:{},css:{},parse:function(libraryName,libraryVersions){var lib={name:libraryName,versions:[]};var scope={};var scopeProps=["$name","$version","$base"];scopeProps.has=function(what){for(var i=0;i<\/script>\n');gloader.map._include[src]=true;return true;}},_include:{},latest:function(libName,v){if(gloader.map.$latest[libName+"/"+v]){return gloader.map.$latest[libName+"/"+v];}var result=v;var parts=v.split(".");if(parts.length<3){if(parts[0]==parseInt(parts[0])&&(typeof parts[1]=="undefined"||parts[1]==parseInt(parts[1]))){var invalid=new RegExp("[a-zA-Z-]"),latest=[parts[0],null,null],mod;for(mod in gloader.map.js){var modParts=mod.split("/");if(modParts[0]==libName&&modParts[2]==libName&&!invalid.test(modParts[1])){var modVParts=modParts[1].split(".");if(modVParts[0]==parts[0]){if((typeof parts[1]=="undefined"&&(latest[1]<=modVParts[1]||(latest[1]==modVParts[1]&&latest[2]<=modVParts[2])))||(typeof parts[1]!="undefined"&&parts[1]==modVParts[1]&&latest[2]<=modVParts[2])){latest[1]=modVParts[1];latest[2]=modVParts[2];}}}}if(latest[2]!=null){result=latest.join(".");}}}gloader.map.$latest[libName+"/"+v]=result;return result;},$latest:{}},settings:{ns:"bbc.glow.gloader",get:function(name){var n=" "+gloader.settings.ns+"."+name+"=";var cookies=document.cookie.split(";");for(var i=0;i-1){return unescape(cookies[i].split("=")[1]);}}},set:function(name,value,path){var n=gloader.settings.ns+"."+name;document.cookie=n+"="+escape(value)+"; path="+((path)?path:"/")+";";},clear:function(name,path){var d=new Date();d.setTime(d.getTime()-1);var n=gloader.settings.ns+"."+name;document.cookie=n+"=; path="+((path)?path:"/")+"; expires=Thu, 01-Jan-70 00:00:01 GMT;";}},loadOverride:function(version){var current=gloader.settings.get("override");version=version||prompt("Enter version",current?current:"");if(version===""){gloader.settings.clear("override");}else{if(version!==null){gloader.settings.set("override",version);}}location.reload();},loadDebug:function(){gloader.settings.set("debug","1");location.reload();},unloadDebug:function(){gloader.settings.clear("debug");location.reload();},expect:function(srcFile){srcFile=""+srcFile;var modsInFile=[];var modId;for(modId in gloader.map.js){if(gloader.map.js[modId]==srcFile){modsInFile.push(modId);gloader._expects[modId]=(gloader._expects[modId]||0)+1;}}},load:function(){var r={};if(typeof arguments[arguments.length-1].length=="undefined"){r=arguments[arguments.length-1];arguments.length--;}var newRequest=new gloader.Request(r);gloader._requests.push(newRequest);var mods=[];var override=gloader.settings.get("override");for(var i=0;i0){newRequest.status=gloader.Request.WAITING;gloader.request(ids,newRequest.async);gloader.resolve();}else{newRequest.complete();}},request:function(mIds,async){for(var i=0;i=gloader.Module.FETCHED);gloader.fetch(gloader._modules[m],async,force);}}},fetch:function(m,async,force){gloader._modules[m.id].async=async;var cssSrc=gloader.map.css[m.id];if(force||(cssSrc&&!gloader._fetched[cssSrc])){gloader._fetched[cssSrc]=1;if(document){var headElement;if(headElement=document.getElementsByTagName("head")[0]){var link;if(link=document.createElement("link")){link.href=cssSrc;link.rel="stylesheet";link.type="text/css";link.className="gloaded";headElement.appendChild(link);}}else{document.write('');}}}if(!force&&gloader._modules[m.id].status>=gloader.Module.FETCHED){return false;}gloader._modules[m.id].status=gloader.Module.FETCHED;var jsSrc=gloader.map.js[m.id];if(!jsSrc){var msg="The gloader map is missing a JavaScript filepath for the module: "+m.id;var maps=[];for(var included_map in gloader.map._include){maps.push(included_map);}msg+=".\rMaps included are: "+maps.join(", ")+".";gloader._errors.push(msg);throw new Error(msg);}if(force||(jsSrc&&!gloader._fetched[jsSrc])){gloader._fetched[jsSrc]=1;gloader.expect(jsSrc);if(async){var headElement=document.getElementsByTagName("head")[0];var scriptElement=document.createElement("script");scriptElement.type="text/javascript";scriptElement.src=jsSrc;headElement.appendChild(scriptElement);}else{document.write('