Revert "Revert "Merge branch 'master' into browserify""

This reverts commit 68ab22d1c2ecbcc608fe9d3d6d2b207cd40ef139.

Conflicts:
        package.json


Project: http://git-wip-us.apache.org/repos/asf/cordova-js/repo
Commit: http://git-wip-us.apache.org/repos/asf/cordova-js/commit/51a5a39d
Tree: http://git-wip-us.apache.org/repos/asf/cordova-js/tree/51a5a39d
Diff: http://git-wip-us.apache.org/repos/asf/cordova-js/diff/51a5a39d

Branch: refs/heads/master
Commit: 51a5a39d2d85eca8802d8a8816adaad4f4df9546
Parents: 087412e
Author: Anis Kadri <[email protected]>
Authored: Wed Apr 30 15:09:15 2014 -0700
Committer: Anis Kadri <[email protected]>
Committed: Wed Apr 30 15:09:15 2014 -0700

----------------------------------------------------------------------
 Gruntfile.js                      |  13 ++
 package.json                      |   7 +-
 src/common/channel.js             |   1 +
 src/common/init_b.js              | 120 +++++++++++++++++
 src/cordova_b.js                  | 239 +++++++++++++++++++++++++++++++++
 tasks/compile-browserify.js       |  29 ++++
 tasks/lib/bundle-browserify.js    |  42 ++++++
 tasks/lib/packager-browserify.js  |  74 ++++++++++
 tasks/lib/require-tr.js           | 134 ++++++++++++++++++
 tasks/lib/write-license-header.js |  16 +++
 10 files changed, 674 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/Gruntfile.js
----------------------------------------------------------------------
diff --git a/Gruntfile.js b/Gruntfile.js
index a419aa0..5182572 100644
--- a/Gruntfile.js
+++ b/Gruntfile.js
@@ -33,6 +33,19 @@ module.exports = function(grunt) {
             "ubuntu": {},
             "browser": {}
         },
+        "compile-browserify": {
+            "amazon-fireos": {},
+            "android": {},
+            "blackberry10": {},
+            "ios": {},
+            "osx": {},
+            //"test": {},
+            "windows8": { useWindowsLineEndings: true },
+            "windowsphone": { useWindowsLineEndings: true },
+            "firefoxos": {},
+            "ubuntu": {},
+            "browser": {}
+        },
         clean: ['pkg'],
         jshint: {
             options: {

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/package.json
----------------------------------------------------------------------
diff --git a/package.json b/package.json
index 58f63d1..12a2212 100644
--- a/package.json
+++ b/package.json
@@ -42,7 +42,7 @@
     },
     {
       "name": "Anis Kadri",
-      "email": ""
+      "email": "[email protected]"
     },
     {
       "name": "Dan Silivestru",
@@ -60,5 +60,10 @@
     "grunt": "~0.4.1",
     "grunt-contrib-clean": "~0.4.1",
     "grunt-contrib-jshint": "~0.6.0"
+  },
+  "dependencies": {
+    "uglify-js": "2.4.x",
+    "browserify": "3.2.0",
+    "through": "2.3.4"
   }
 }

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/src/common/channel.js
----------------------------------------------------------------------
diff --git a/src/common/channel.js b/src/common/channel.js
index 653af15..f3d83df 100644
--- a/src/common/channel.js
+++ b/src/common/channel.js
@@ -235,6 +235,7 @@ channel.createSticky('onNativeReady');
 channel.createSticky('onCordovaReady');
 
 // Event to indicate that all automatically loaded JS plugins are loaded and 
ready.
+// FIXME remove this
 channel.createSticky('onPluginsReady');
 
 // Event to indicate that Cordova is ready

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/src/common/init_b.js
----------------------------------------------------------------------
diff --git a/src/common/init_b.js b/src/common/init_b.js
new file mode 100644
index 0000000..32c2068
--- /dev/null
+++ b/src/common/init_b.js
@@ -0,0 +1,120 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ *
+*/
+
+var channel = require('cordova/channel');
+var cordova = require('cordova');
+var platform = require('cordova/platform');
+
+var platformInitChannelsArray = [channel.onDOMContentLoaded, 
channel.onNativeReady];
+
+// setting exec
+cordova.exec = require('cordova/exec');
+
+function logUnfiredChannels(arr) {
+    for (var i = 0; i < arr.length; ++i) {
+        if (arr[i].state != 2) {
+            console.log('Channel not fired: ' + arr[i].type);
+        }
+    }
+}
+
+window.setTimeout(function() {
+    if (channel.onDeviceReady.state != 2) {
+        console.log('deviceready has not fired after 5 seconds.');
+        logUnfiredChannels(platformInitChannelsArray);
+        logUnfiredChannels(channel.deviceReadyChannelsArray);
+    }
+}, 5000);
+
+// Replace navigator before any modules are required(), to ensure it happens 
as soon as possible.
+// We replace it so that properties that can't be clobbered can instead be 
overridden.
+function replaceNavigator(origNavigator) {
+    var CordovaNavigator = function() {};
+    CordovaNavigator.prototype = origNavigator;
+    var newNavigator = new CordovaNavigator();
+    // This work-around really only applies to new APIs that are newer than 
Function.bind.
+    // Without it, APIs such as getGamepads() break.
+    if (CordovaNavigator.bind) {
+        for (var key in origNavigator) {
+            if (typeof origNavigator[key] == 'function') {
+                newNavigator[key] = origNavigator[key].bind(origNavigator);
+            }
+        }
+    }
+    return newNavigator;
+}
+if (window.navigator) {
+    window.navigator = replaceNavigator(window.navigator);
+}
+
+if (!window.console) {
+    window.console = {
+        log: function(){}
+    };
+}
+if (!window.console.warn) {
+    window.console.warn = function(msg) {
+        this.log("warn: " + msg);
+    };
+}
+
+// Register pause, resume and deviceready channels as events on document.
+channel.onPause = cordova.addDocumentEventHandler('pause');
+channel.onResume = cordova.addDocumentEventHandler('resume');
+channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready');
+
+// Listen for DOMContentLoaded and notify our channel subscribers.
+if (document.readyState == 'complete' || document.readyState == 'interactive') 
{
+    channel.onDOMContentLoaded.fire();
+} else {
+    document.addEventListener('DOMContentLoaded', function() {
+        channel.onDOMContentLoaded.fire();
+    }, false);
+}
+
+// _nativeReady is global variable that the native side can set
+// to signify that the native code is ready. It is a global since
+// it may be called before any cordova JS is ready.
+if (window._nativeReady) {
+    channel.onNativeReady.fire();
+}
+
+// Call the platform-specific initialization.
+platform.bootstrap && platform.bootstrap();
+
+/**
+ * Create all cordova objects once native side is ready.
+ */
+channel.join(function() {
+    
+    platform.initialize && platform.initialize();
+
+    // Fire event to notify that all objects are created
+    channel.onCordovaReady.fire();
+
+    // Fire onDeviceReady event once page has fully loaded, all
+    // constructors have run and cordova info has been received from native
+    // side.
+    channel.join(function() {
+        require('cordova').fireDocumentEvent('deviceready');
+    }, channel.deviceReadyChannelsArray);
+
+}, platformInitChannelsArray);

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/src/cordova_b.js
----------------------------------------------------------------------
diff --git a/src/cordova_b.js b/src/cordova_b.js
new file mode 100644
index 0000000..a00423c
--- /dev/null
+++ b/src/cordova_b.js
@@ -0,0 +1,239 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ *
+*/
+
+
+var channel = require('cordova/channel');
+var platform = require('cordova/platform');
+
+/**
+ * Intercept calls to addEventListener + removeEventListener and handle 
deviceready,
+ * resume, and pause events.
+ */
+var m_document_addEventListener = document.addEventListener;
+var m_document_removeEventListener = document.removeEventListener;
+var m_window_addEventListener = window.addEventListener;
+var m_window_removeEventListener = window.removeEventListener;
+
+/**
+ * Houses custom event handlers to intercept on document + window event 
listeners.
+ */
+var documentEventHandlers = {},
+    windowEventHandlers = {};
+
+document.addEventListener = function(evt, handler, capture) {
+    var e = evt.toLowerCase();
+    if (typeof documentEventHandlers[e] != 'undefined') {
+        documentEventHandlers[e].subscribe(handler);
+    } else {
+        m_document_addEventListener.call(document, evt, handler, capture);
+    }
+};
+
+window.addEventListener = function(evt, handler, capture) {
+    var e = evt.toLowerCase();
+    if (typeof windowEventHandlers[e] != 'undefined') {
+        windowEventHandlers[e].subscribe(handler);
+    } else {
+        m_window_addEventListener.call(window, evt, handler, capture);
+    }
+};
+
+document.removeEventListener = function(evt, handler, capture) {
+    var e = evt.toLowerCase();
+    // If unsubscribing from an event that is handled by a plugin
+    if (typeof documentEventHandlers[e] != "undefined") {
+        documentEventHandlers[e].unsubscribe(handler);
+    } else {
+        m_document_removeEventListener.call(document, evt, handler, capture);
+    }
+};
+
+window.removeEventListener = function(evt, handler, capture) {
+    var e = evt.toLowerCase();
+    // If unsubscribing from an event that is handled by a plugin
+    if (typeof windowEventHandlers[e] != "undefined") {
+        windowEventHandlers[e].unsubscribe(handler);
+    } else {
+        m_window_removeEventListener.call(window, evt, handler, capture);
+    }
+};
+
+function createEvent(type, data) {
+    var event = document.createEvent('Events');
+    event.initEvent(type, false, false);
+    if (data) {
+        for (var i in data) {
+            if (data.hasOwnProperty(i)) {
+                event[i] = data[i];
+            }
+        }
+    }
+    return event;
+}
+
+
+var cordova = {
+    version:CORDOVA_JS_BUILD_LABEL,
+    platformId:platform.id,
+    /**
+     * Methods to add/remove your own addEventListener hijacking on document + 
window.
+     */
+    addWindowEventHandler:function(event) {
+        return (windowEventHandlers[event] = channel.create(event));
+    },
+    addStickyDocumentEventHandler:function(event) {
+        return (documentEventHandlers[event] = channel.createSticky(event));
+    },
+    addDocumentEventHandler:function(event) {
+        return (documentEventHandlers[event] = channel.create(event));
+    },
+    removeWindowEventHandler:function(event) {
+        delete windowEventHandlers[event];
+    },
+    removeDocumentEventHandler:function(event) {
+        delete documentEventHandlers[event];
+    },
+    /**
+     * Retrieve original event handlers that were replaced by Cordova
+     *
+     * @return object
+     */
+    getOriginalHandlers: function() {
+        return {'document': {'addEventListener': m_document_addEventListener, 
'removeEventListener': m_document_removeEventListener},
+        'window': {'addEventListener': m_window_addEventListener, 
'removeEventListener': m_window_removeEventListener}};
+    },
+    /**
+     * Method to fire event from native code
+     * bNoDetach is required for events which cause an exception which needs 
to be caught in native code
+     */
+    fireDocumentEvent: function(type, data, bNoDetach) {
+        var evt = createEvent(type, data);
+        if (typeof documentEventHandlers[type] != 'undefined') {
+            if( bNoDetach ) {
+                documentEventHandlers[type].fire(evt);
+            }
+            else {
+                setTimeout(function() {
+                    // Fire deviceready on listeners that were registered 
before cordova.js was loaded.
+                    if (type == 'deviceready') {
+                        document.dispatchEvent(evt);
+                    }
+                    documentEventHandlers[type].fire(evt);
+                }, 0);
+            }
+        } else {
+            document.dispatchEvent(evt);
+        }
+    },
+    fireWindowEvent: function(type, data) {
+        var evt = createEvent(type,data);
+        if (typeof windowEventHandlers[type] != 'undefined') {
+            setTimeout(function() {
+                windowEventHandlers[type].fire(evt);
+            }, 0);
+        } else {
+            window.dispatchEvent(evt);
+        }
+    },
+
+    /**
+     * Plugin callback mechanism.
+     */
+    // Randomize the starting callbackId to avoid collisions after refreshing 
or navigating.
+    // This way, it's very unlikely that any new callback would get the same 
callbackId as an old callback.
+    callbackId: Math.floor(Math.random() * 2000000000),
+    callbacks:  {},
+    callbackStatus: {
+        NO_RESULT: 0,
+        OK: 1,
+        CLASS_NOT_FOUND_EXCEPTION: 2,
+        ILLEGAL_ACCESS_EXCEPTION: 3,
+        INSTANTIATION_EXCEPTION: 4,
+        MALFORMED_URL_EXCEPTION: 5,
+        IO_EXCEPTION: 6,
+        INVALID_ACTION: 7,
+        JSON_EXCEPTION: 8,
+        ERROR: 9
+    },
+
+    /**
+     * Called by native code when returning successful result from an action.
+     */
+    callbackSuccess: function(callbackId, args) {
+        try {
+            cordova.callbackFromNative(callbackId, true, args.status, 
[args.message], args.keepCallback);
+        } catch (e) {
+            console.log("Error in error callback: " + callbackId + " = "+e);
+        }
+    },
+
+    /**
+     * Called by native code when returning error result from an action.
+     */
+    callbackError: function(callbackId, args) {
+        // TODO: Deprecate callbackSuccess and callbackError in favour of 
callbackFromNative.
+        // Derive success from status.
+        try {
+            cordova.callbackFromNative(callbackId, false, args.status, 
[args.message], args.keepCallback);
+        } catch (e) {
+            console.log("Error in error callback: " + callbackId + " = "+e);
+        }
+    },
+
+    /**
+     * Called by native code when returning the result from an action.
+     */
+    callbackFromNative: function(callbackId, success, status, args, 
keepCallback) {
+        var callback = cordova.callbacks[callbackId];
+        if (callback) {
+            if (success && status == cordova.callbackStatus.OK) {
+                callback.success && callback.success.apply(null, args);
+            } else if (!success) {
+                callback.fail && callback.fail.apply(null, args);
+            }
+
+            // Clear callback if not expecting any more results
+            if (!keepCallback) {
+                delete cordova.callbacks[callbackId];
+            }
+        }
+    },
+    addConstructor: function(func) {
+        channel.onCordovaReady.subscribe(function() {
+            try {
+                func();
+            } catch(e) {
+                console.log("Failed to run constructor: " + e);
+            }
+        });
+    }
+};
+
+// FIXME hack: cordova iOS calls cordova.require()
+cordova.require = function(module) {
+  if(module === "cordova/exec") {
+    return cordova.exec;
+  }
+
+  return undefined;
+}
+
+window.cordova = module.exports = cordova;

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/tasks/compile-browserify.js
----------------------------------------------------------------------
diff --git a/tasks/compile-browserify.js b/tasks/compile-browserify.js
new file mode 100644
index 0000000..1d28510
--- /dev/null
+++ b/tasks/compile-browserify.js
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+*/
+var generate = require('./lib/packager-browserify');
+
+module.exports = function(grunt) {
+    grunt.registerMultiTask('compile-browserify', 'Packages cordova.js 
browserify style', function() {
+
+        var done = this.async();
+        var platformName = this.target;
+        var useWindowsLineEndings = this.data.useWindowsLineEndings;
+        generate(platformName, useWindowsLineEndings, done);
+    });
+}

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/tasks/lib/bundle-browserify.js
----------------------------------------------------------------------
diff --git a/tasks/lib/bundle-browserify.js b/tasks/lib/bundle-browserify.js
new file mode 100644
index 0000000..1d948fa
--- /dev/null
+++ b/tasks/lib/bundle-browserify.js
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF
+ * or more contributor license agreements.  See th
+ * distributed with this work for additional infor
+ * regarding copyright ownership.  The ASF license
+ * to you under the Apache License, Version 2.0 (t
+ * "License"); you may not use this file except in
+ * with the License.  You may obtain a copy of the
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to 
+ * software distributed under the License is distr
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+ * KIND, either express or implied.  See the Licen
+ * specific language governing permissions and lim
+ * under the License.
+ */
+var fs           = require('fs');
+var path         = require('path');
+var browserify   = require('browserify');
+var require_tr   = require('./require-tr');
+var root         = path.join(__dirname, '..', '..')
+
+
+module.exports = function bundle(platform, debug, commitId) {
+    require_tr.platform = platform;
+    // FIXME: need to find a way to void ignore missing
+    var b = browserify({debug: debug});
+    // XXX plugin_list is not present at this stage 
+    b.ignore(path.join(root, 'src', 'common', 'plugin_list'));
+
+    b.transform(require_tr.transform);
+
+    b.add(path.join(root, 'src', platform, 'exec.js'));
+    
+    b.add(path.join(root, 'src', platform, 'platform.js'));
+
+    b.add(path.join(root, 'src', 'scripts', 'bootstrap.js'));
+
+    return b;
+}

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/tasks/lib/packager-browserify.js
----------------------------------------------------------------------
diff --git a/tasks/lib/packager-browserify.js b/tasks/lib/packager-browserify.js
new file mode 100644
index 0000000..3e718c6
--- /dev/null
+++ b/tasks/lib/packager-browserify.js
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF
+ * or more contributor license agreements.  See th
+ * distributed with this work for additional infor
+ * regarding copyright ownership.  The ASF license
+ * to you under the Apache License, Version 2.0 (t
+ * "License"); you may not use this file except in
+ * with the License.  You may obtain a copy of the
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to 
+ * software distributed under the License is distr
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
+ * KIND, either express or implied.  See the Licen
+ * specific language governing permissions and lim
+ * under the License.
+ */
+var fs                 = require('fs');
+var path               = require('path');
+var util               = require('util');
+var bundle             = require('./bundle-browserify');
+var computeCommitId    = require('./compute-commit-id');
+var writeLicenseHeader = require('./write-license-header');
+
+
+module.exports = function generate(platform, useWindowsLineEndings, done) {
+    computeCommitId(function(commitId) {
+        var outReleaseFile, outReleaseFileStream,
+            outDebugFile, outDebugFileStream,
+            releaseBundle, debugBundle;
+        var time = new Date().valueOf();
+
+        var libraryRelease = bundle(platform, false, commitId);
+       // if we are using windows line endings, we will also add the BOM
+       // if(useWindowsLineEndings) {
+       //     libraryRelease = "\ufeff" + 
libraryRelease.split(/\r?\n/).join("\r\n");
+       // }
+       // var libraryDebug   = bundle(platform, true, commitId);
+
+        if (!fs.existsSync('pkg')) {
+            fs.mkdirSync('pkg');
+        }
+       // if(!fs.existsSync('pkg/debug')) {
+       //     fs.mkdirSync('pkg/debug');
+       // }
+
+        outReleaseFile = path.join('pkg', 'cordova.' + platform + '.js');
+        outReleaseFileStream = fs.createWriteStream(outReleaseFile);
+        
+        // write license header
+        writeLicenseHeader(outReleaseFileStream, platform, commitId);
+
+        releaseBundle = libraryRelease.bundle();
+
+        releaseBundle.pipe(outReleaseFileStream);
+
+        outReleaseFileStream.on('finish', function() {
+          var newtime = new Date().valueOf() - time;
+          console.log('generated cordova.' + platform + '.js @ ' + commitId + 
' in ' + newtime + 'ms');
+          done();
+        });
+
+       // outDebugFile = path.join('pkg', 'debug', 'cordova.' + platform + 
'-debug.js');
+       // outDebugFileStream = fs.createWriteStream(outDebugFile);
+       // debugBundle = libraryDebug.bundle();
+       // debugBundle.pipe(outDebugFileStream);
+
+       // outDebugFileStream.on('end', function() {
+       //   var newtime = new Date().valueOf() - time;
+       //   console.log('generated cordova.' + platform + '-debug.js @ ' + 
commitId + ' in ' + newtime + 'ms');
+       // });
+    });
+}

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/tasks/lib/require-tr.js
----------------------------------------------------------------------
diff --git a/tasks/lib/require-tr.js b/tasks/lib/require-tr.js
new file mode 100644
index 0000000..8964aee
--- /dev/null
+++ b/tasks/lib/require-tr.js
@@ -0,0 +1,134 @@
+/*
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ *
+*/
+
+/*
+ * This probably should live in plugman/cli world
+ * Transoforms old require calls to new node-style require calls
+ */
+
+var fs = require('fs');
+var path = require('path');
+var through = require('through');
+var UglifyJS = require('uglify-js');
+var root = fs.realpathSync(path.join(__dirname, '..', '..'));
+
+
+var requireTr = {
+
+  transform: function(file) {
+    var data = '';
+
+    function write(buf) {
+      data += buf;
+    }
+
+    function end() {
+      // getting rid of define and require properties of cordova
+     // if(file.match(/cordova.js$/)) {
+     //   data = data.replace(/ *(define:define|require:require),\n/, '');
+     // }
+      this.queue(_updateRequires(data));
+      this.queue(null);
+    }
+   
+    return through(write, end);
+  },
+  getModules: function() {
+    return this.modules;
+  },
+  addModule: function(module) {
+    if(!module || !module.symbol || !module.path) {
+      throw new Error("Can't add module without a symbol and a path");
+    }
+    this.modules.push(module);
+  },
+  platform: null,
+  modules: []
+    
+}
+
+/*
+ * visits AST and modifies all the require('cordova/*') and 
require('org.apache.cordova.*')
+ */
+function _updateRequires(code) {
+  
+  var ast = UglifyJS.parse(code);
+
+  var walker = new UglifyJS.TreeWalker(function(node) {
+
+    // check all function calls
+    if(node instanceof UglifyJS.AST_Call) {
+      // check if function call is a require('module') call
+      if(node.expression.name === "require" && node.args.length === 1) {
+        var module = node.args[0].value;
+        // make sure require only has one argument and that it starts with 
cordova (old style require.js) 
+        if(module !== undefined &&
+           module.indexOf("cordova") === 0) {
+          
+          // adding symbolList bullcrap
+          if(requireTr.symbolList && requireTr.symbolList.indexOf(module) === 
-1) {
+            requireTr.symbolList.push(module);
+          }
+
+          // require('cordova') -> cordova.js
+          if(module === "cordova") {
+            node.args[0].value = path.join(root, "src", "cordova_b");
+          // require('cordova/init') -> common/init
+          }  else if(module.match(/cordova\/init/)) {
+            node.args[0].value = module.replace(/cordova\/init/,
+                                    path.join(root, "src", "common", 
"init_b"));
+          // android and amazon-fireos have some special require's
+          } else if(module.match(/cordova\/(android|amazon-fireos)\/(.+)/)) {
+            node.args[0].value = 
module.replace(/cordova\/(android|amazon-fireos)\/(.+)/,
+                                    path.join(root, "src", "$1", "android", 
"$2"));
+          // require('cordova/exec') and require('cordova/platform') -> 
platform's exec/platform
+          } else if(module.match(/cordova\/(platform|exec)$/)) {
+            node.args[0].value = module.replace(/cordova\/(platform|exec)/,
+                                                path.join(root, "src", 
requireTr.platform, "$1"));
+          // require('cordova/anything') should be under common/
+          } else if(module.match(/cordova\/(.+)/)) {
+            node.args[0].value = module.replace(/cordova\/(.+)/,
+                                    path.join(root, "src", "common", "$1"));
+          }
+        } else if(module !== undefined && module.indexOf("org.apache.cordova") 
!== -1 ) {
+          var modules = requireTr.getModules();
+          for(var i = 0, j = modules.length ; i < j ; i++) {
+            if(module.match(modules[i].symbol)) {
+              node.args[0].value = modules[i].path;
+              break;
+            }
+          }
+        }
+      }
+    }
+  });
+
+  ast.walk(walker);
+
+  var stream = UglifyJS.OutputStream({beautify:true});
+
+  ast.print(stream);
+
+  return stream.toString();
+}
+
+
+module.exports = requireTr; 

http://git-wip-us.apache.org/repos/asf/cordova-js/blob/51a5a39d/tasks/lib/write-license-header.js
----------------------------------------------------------------------
diff --git a/tasks/lib/write-license-header.js 
b/tasks/lib/write-license-header.js
new file mode 100644
index 0000000..8b33cbd
--- /dev/null
+++ b/tasks/lib/write-license-header.js
@@ -0,0 +1,16 @@
+var path        = require('path');
+var util        = require('util');
+var fs          = require('fs');
+var licensePath = path.join(__dirname, '..', 'templates', 
'LICENSE-for-js-file.txt');
+
+module.exports = function(outStream, platform, commitId) {
+  // some poppycock 
+  var licenseText = util.format("/*\n *%s\n */\n", 
fs.readFileSync(licensePath, 'utf8').replace(/\n/g, "\n *"));
+
+  outStream.write("// Platform: " + platform + "\n", 'utf8');
+  outStream.write("// "  + commitId + "\n", 'utf8');
+  outStream.write(licenseText, 'utf8');
+  outStream.write("var CORDOVA_JS_BUILD_LABEL = '"  + commitId + "';\n", 
'utf8');
+  outStream.write("var define = {moduleMap: []};\n", 'utf8');
+
+}

Reply via email to