<commit_before>describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace} = VueGL;
    const assert = chai.assert;
    const webgl = (() => {
        const canvas = document.createElement("canvas");
        let gl;
        try {
            gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
            return typeof gl.getSupportedExtensions === "function";
        } catch(e) {}
        return false;
    })();
    before(function() {
        if (!webgl) console.log("WebGL is not supported. Skip tests for the VglRenderer.");
    });
    beforeEach(function() {
        // Skip all tests when the WebGL is not supported.
        if (!webgl) {
            this.skip();
        }
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue(VglRenderer);
                assert.isObject(vm.vglCameras);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglCameras);
                vm.$refs.renderer.inst.forceContextLoss();
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue(VglRenderer);
                assert.isObject(vm.vglScenes);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglScenes);
                vm.$refs.renderer.inst.forceContextLoss();
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                const vm = new Vue(VglRenderer).$mount();
                assert.strictEqual(vm.$refs.rdr, vm.inst.domElement);
                vm.inst.forceContextLoss();
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().alpha);
                    vm.inst.forceContextLoss();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().alpha);
                    vm.inst.forceContextLoss();
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().depth);
                    vm.inst.forceContextLoss();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().depth);
                    vm.inst.forceContextLoss();
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().stencil);
                    vm.inst.forceContextLoss();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().stencil);
                    vm.inst.forceContextLoss();
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().antialias);
                    vm.inst.forceContextLoss();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().antialias);
                    vm.inst.forceContextLoss();
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().premultipliedAlpha);
                    vm.inst.forceContextLoss();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().premultipliedAlpha);
                    vm.inst.forceContextLoss();
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().preserveDrawingBuffer);
                    vm.inst.forceContextLoss();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().preserveDrawingBuffer);
                    vm.inst.forceContextLoss();
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.capabilities.logarithmicDepthBuffer);
                    vm.inst.forceContextLoss();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.capabilities.logarithmicDepthBuffer);
                    vm.inst.forceContextLoss();
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                    vm.inst.forceContextLoss();
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "lowp");
                    vm.inst.forceContextLoss();
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "mediump");
                    vm.inst.forceContextLoss();
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                    vm.inst.forceContextLoss();
                });
            });
        });
    });
    describe("When any properties are changed", function() {
        describe("Output canvas", function() {
            it("The canvas element should be replaced.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldCanvas = vm.$refs.rdr;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldCanvas, vm.$refs.rdr);
                        vm.inst.forceContextLoss();
                        done();
                    } catch(e) {
                        vm.inst.forceContextLoss();
                        done(e);
                    }
                });
            });
            it("The WebGLRenderer instance should be newly created.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldInst = vm.inst;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldInst, vm.inst);
                        vm.inst.forceContextLoss();
                        done();
                    } catch(e) {
                        vm.inst.forceContextLoss();
                        done(e);
                    }
                });
            });
            it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.strictEqual(vm.inst.domElement, vm.$refs.rdr);
                        vm.inst.forceContextLoss();
                        done();
                    } catch(e) {
                        vm.inst.forceContextLoss();
                        done(e);
                    }
                });
            });
        });
    });
});
<commit_msg>Destroy the vue instances at the end of each test.<commit_after>describe("VglRenderer component", function() {
    const {VglRenderer, VglNamespace} = VueGL;
    const assert = chai.assert;
    const webgl = (() => {
        const canvas = document.createElement("canvas");
        let gl;
        try {
            gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl");
            return typeof gl.getSupportedExtensions === "function";
        } catch(e) {}
        return false;
    })();
    before(function() {
        if (!webgl) console.log("WebGL is not supported. Skip tests for the VglRenderer.");
    });
    beforeEach(function() {
        // Skip all tests when the WebGL is not supported.
        if (!webgl) {
            this.skip();
        }
    });
    describe("Namespace injection", function() {
        describe("Should be able to access vglCameras", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue(VglRenderer);
                assert.isObject(vm.vglCameras);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglCameras);
                vm.$destroy();
            });
        });
        describe("Should be able to access vglScenes", function() {
            it("When the component is the root namespace.", function() {
                const vm = new Vue(VglRenderer);
                assert.isObject(vm.vglScenes);
            });
            it("When the component is a descendant of the other namespace.", function() {
                const vm = new Vue({
                    template: `<vgl-namespace><vgl-renderer ref="renderer" /></vgl-namespace>`,
                    components: {
                        VglNamespace,
                        VglRenderer
                    }
                }).$mount();
                assert.isObject(vm.$refs.renderer.vglScenes);
                vm.$destroy();
            });
        });
    });
    describe("Creating a renderer", function() {
        describe("Output canvas", function() {
            it("The domElement property of WebGLRenderer instance should be the Vue created canvas.", function() {
                const vm = new Vue(VglRenderer).$mount();
                assert.strictEqual(vm.$refs.rdr, vm.inst.domElement);
                vm.$destroy();
            });
        });
        describe("Context attributes", function() {
            describe("The alpha property should affect the alpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().alpha);
                    vm.$destroy();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {alpha: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().alpha);
                    vm.$destroy();
                });
            });
            describe("The disableDepth property should affect the depth attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().depth);
                    vm.$destroy();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableDepth: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().depth);
                    vm.$destroy();
                });
            });
            describe("The disableStencil property should affect the stencil attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().stencil);
                    vm.$destroy();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disableStencil: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().stencil);
                    vm.$destroy();
                });
            });
            describe("The antialias property should affect the antialias attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().antialias);
                    vm.$destroy();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {antialias: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().antialias);
                    vm.$destroy();
                });
            });
            describe("The disablePremultipliedAlpha property should affect the premultipliedAlpha attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().premultipliedAlpha);
                    vm.$destroy();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {disablePremultipliedAlpha: true}}).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().premultipliedAlpha);
                    vm.$destroy();
                });
            });
            describe("The preserveDrawingBuffer property should affect the preserveDrawingBuffer attribute.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.getContextAttributes().preserveDrawingBuffer);
                    vm.$destroy();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {preserveDrawingBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.getContextAttributes().preserveDrawingBuffer);
                    vm.$destroy();
                });
            });
        });
        describe("Capabilities", function() {
            describe("The logarithmicDepthBuffer property should affect the logarithmicDepthBuffer capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.isFalse(vm.inst.capabilities.logarithmicDepthBuffer);
                    vm.$destroy();
                });
                it("When the property is true.", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {logarithmicDepthBuffer: true}}).$mount();
                    assert.isTrue(vm.inst.capabilities.logarithmicDepthBuffer);
                    vm.$destroy();
                });
            });
            describe("The precision property should affect the precision capability.", function() {
                it("When the property is undefined (or false).", function() {
                    const vm = new Vue(VglRenderer).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                    vm.$destroy();
                });
                it("When the property is \"lowp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "lowp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "lowp");
                    vm.$destroy();
                });
                it("When the property is \"mediump\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "mediump"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "mediump");
                    vm.$destroy();
                });
                it("When the property is \"highp\".", function() {
                    const vm = new (Vue.extend(VglRenderer))({propsData: {precision: "highp"}}).$mount();
                    assert.strictEqual(vm.inst.capabilities.precision, "highp");
                    vm.$destroy();
                });
            });
        });
    });
    describe("When any properties are changed", function() {
        describe("Output canvas", function() {
            it("The canvas element should be replaced.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldCanvas = vm.$refs.rdr;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldCanvas, vm.$refs.rdr);
                        vm.$destroy();
                        done();
                    } catch(e) {
                        vm.$destroy();
                        done(e);
                    }
                });
            });
            it("The WebGLRenderer instance should be newly created.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                const oldInst = vm.inst;
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.notEqual(oldInst, vm.inst);
                        vm.$destroy();
                        done();
                    } catch(e) {
                        vm.$destroy();
                        done(e);
                    }
                });
            });
            it("The domElement property of WebGLRenderer instance should be the replaced canvas.", function(done) {
                const vm = new Vue(VglRenderer).$mount();
                vm.alpha = true;
                vm.$nextTick(() => {
                    try {
                        assert.strictEqual(vm.inst.domElement, vm.$refs.rdr);
                        vm.$destroy();
                        done();
                    } catch(e) {
                        vm.$destroy();
                        done(e);
                    }
                });
            });
        });
    });
});
<|endoftext|>


<commit_before>/**
* Copyright 2011 Microsoft 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.
*/

var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var assert = require('assert');
var pfx2pem = require('../../util/certificates/pkcs').pfx2pem;

exports.init = function (cli) {

  var log = cli.output;

  var account = cli.category('account');

  var config = cli.category('config')
        .description('Manage tool local settings');

  config.command('list')
        .whiteListPowershell()
        .description('Display config settings')
        .action(function (options) {
          log.info('Displaying config settings');

          var cfg = account.readConfig();

          log.table(cfg, function (row, name) {
            row.cell('Setting', name);
            row.cell('Value', cfg[name]);
          });
        });

  config.command('set <name> <value>')

        .usage('<name> <value>')

        .whiteListPowershell()
        .description('Change a config setting')
        .action(function (name, value, options) {
          var cfg = account.readConfig();
          if(name === 'endpoint') {
            endpointInfo = validateEndpoint(value);
            log.info('Setting \'port\' to value \'' + endpointInfo.endpointPort + '\'');
            cfg['port'] = endpointInfo.endpointPort;
            value = endpointInfo.endpointHost;
          }

          log.info('Setting \'' + name + '\' to value \'' + value + '\'');
          cfg[name] = value;
          account.writeConfig(cfg);
          log.info('Changes saved.');
        });

  var azurePath = path.join(homeFolder(), '.azure');
  var azureConfigPath = path.join(azurePath, 'config.json');

  config.readConfig = function () {
    var cfg = {};
    log.silly('Reading config', azureConfigPath);

    if (path.existsSync(azureConfigPath)) {
      try {
        cfg = JSON.parse(fs.readFileSync(azureConfigPath));
      } catch (err) {
        log.warn('Unable to read settings');
        cfg = {};
      }
      log.json('silly', cfg);
    }

    return cfg;
  };

  config.writeConfig = function (cfg) {
    if (!path.existsSync(azurePath)) {
      log.silly('Creating folder', azurePath);
      fs.mkdirSync(azurePath, 502); //0766
    }

    log.silly('Writing config', azureConfigPath);
    fs.writeFileSync(azureConfigPath, JSON.stringify(cfg));
  };

  config.clearConfig = function() {
    log.silly('Removing', azureConfigPath);
    if (path.existsSync(azureConfigPath)) {
      fs.unlinkSync(azureConfigPath);
      return true;
    }
  };

  // added temporarily for back-compat
  cli.category('account').readConfig = config.readConfig;
  cli.category('account').writeConfig = config.writeConfig;
  cli.category('account').clearConfig = config.clearConfig;

  // apply any persistant switches at load-time
  function applyGlobalSettings() {
    var cfg = config.readConfig();
    if (!cfg) {
      return;
    }

    if (cfg.labels === 'off') {
      log.format({ terse: true });
    }

    if (cfg.logo === 'off') {
      log.format({ logo: 'off' });
    } else {
      log.format({ logo: 'on' });
    }
  }

  applyGlobalSettings();

  function homeFolder() {
    if (process.env.HOME !== undefined) {
      return process.env.HOME;
    }

    if (process.env.HOMEDRIVE && process.env.HOMEPATH) {
      return process.env.HOMEDRIVE + process.env.HOMEPATH;
    }

    throw new Error('No HOME path available');
  }

  function validateEndpoint(endpoint) {
    var parts = endpoint.split('://');
    var hostname = parts[0];
    if(parts.length > 2){
      throw Error('Invalid Url');
    } else if (parts.length === 2) {
       if(!parts[0]) {
        throw Error('Invalid Url');
       }

       if((parts[0] !== 'https') && (parts[0] !== 'HTTPS')) {
          throw Error('Only https protocol supported in the endpoint');
       }

       hostname = parts[1];
    }

    var parts2 = (hostname).split('/');

    // Check url contain path(s) after the hostname if so error
    // This will handle in case if user pass endpoint value starting
    // with / char
    if(parts2.length > 2 || (parts2.length === 2 && parts2[1])) {
      throw Error('Invalid Url');
    }

    var parts3 = (parts2[0]).split(':');

    port = 443;
    // Check host name contain ':', if so only one and it should be
    // followed by a valid port number
    if(parts3.length > 2) {
      throw Error('Invalid Url');
    } else if(parts3.length === 2) {
      if(!parts3[1]) {
        throw Error('Invalid Url');
      }

      var intValue = parseInt(parts3[1], 10);
      if (intValue != parts3[1] || parts3[1] >= 65535) {
        throw Error('Port number should be a number with max limit 65535');
      }

      port = intValue;
    }

    return {endpointHost: parts3[0], endpointPort: port};
  }
};
<commit_msg>incorporated review comments for set endpoint functionality<commit_after>/**
* Copyright 2011 Microsoft 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.
*/

var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var assert = require('assert');
var pfx2pem = require('../../util/certificates/pkcs').pfx2pem;

exports.init = function (cli) {

  var log = cli.output;

  var account = cli.category('account');

  var config = cli.category('config')
        .description('Manage tool local settings');

  config.command('list')
        .whiteListPowershell()
        .description('Display config settings')
        .action(function (options) {
          log.info('Displaying config settings');

          var cfg = account.readConfig();

          log.table(cfg, function (row, name) {
            row.cell('Setting', name);
            row.cell('Value', cfg[name]);
          });
        });

  config.command('set <name> <value>')

        .usage('<name> <value>')

        .whiteListPowershell()
        .description('Change a config setting')
        .action(function (name, value, options) {
          var cfg = account.readConfig();
          if(name === 'endpoint') {
            endpointInfo = validateEndpoint(value);
            log.info('Setting \'port\' to value \'' + endpointInfo.endpointPort + '\'');
            cfg['port'] = endpointInfo.endpointPort;
            value = endpointInfo.endpointHost;
          }

          log.info('Setting \'' + name + '\' to value \'' + value + '\'');
          cfg[name] = value;
          account.writeConfig(cfg);
          log.info('Changes saved.');
        });

  var azurePath = path.join(homeFolder(), '.azure');
  var azureConfigPath = path.join(azurePath, 'config.json');

  config.readConfig = function () {
    var cfg = {};
    log.silly('Reading config', azureConfigPath);

    if (path.existsSync(azureConfigPath)) {
      try {
        cfg = JSON.parse(fs.readFileSync(azureConfigPath));
      } catch (err) {
        log.warn('Unable to read settings');
        cfg = {};
      }
      log.json('silly', cfg);
    }

    return cfg;
  };

  config.writeConfig = function (cfg) {
    if (!path.existsSync(azurePath)) {
      log.silly('Creating folder', azurePath);
      fs.mkdirSync(azurePath, 502); //0766
    }

    log.silly('Writing config', azureConfigPath);
    fs.writeFileSync(azureConfigPath, JSON.stringify(cfg));
  };

  config.clearConfig = function() {
    log.silly('Removing', azureConfigPath);
    if (path.existsSync(azureConfigPath)) {
      fs.unlinkSync(azureConfigPath);
      return true;
    }
  };

  // added temporarily for back-compat
  cli.category('account').readConfig = config.readConfig;
  cli.category('account').writeConfig = config.writeConfig;
  cli.category('account').clearConfig = config.clearConfig;

  // apply any persistant switches at load-time
  function applyGlobalSettings() {
    var cfg = config.readConfig();
    if (!cfg) {
      return;
    }

    if (cfg.labels === 'off') {
      log.format({ terse: true });
    }

    if (cfg.logo === 'off') {
      log.format({ logo: 'off' });
    } else {
      log.format({ logo: 'on' });
    }
  }

  applyGlobalSettings();

  function homeFolder() {
    if (process.env.HOME !== undefined) {
      return process.env.HOME;
    }

    if (process.env.HOMEDRIVE && process.env.HOMEPATH) {
      return process.env.HOMEDRIVE + process.env.HOMEPATH;
    }

    throw new Error('No HOME path available');
  }

  function validateEndpoint(endpoint) {
    var parts = endpoint.split('://');
    var hostname = parts[0];
    if(parts.length > 2){
      throw Error('Invalid Url');
    } else if (parts.length === 2) {
       if(!parts[0]) {
        throw Error('Invalid Url');
       }

       if((parts[0] !== 'https') && (parts[0] !== 'HTTPS')) {
          throw Error('Only https protocol supported in the endpoint');
       }

       hostname = parts[1];
    }

    var parts2 = hostname.split('/');

    // Check url contain path(s) after the hostname if so error
    // This will handle in case if user pass endpoint value starting
    // with / char
    if(parts2.length > 2 || (parts2.length === 2 && parts2[1])) {
      throw Error('Invalid Url');
    }

    var parts3 = (parts2[0]).split(':');

    port = 443;
    // Check host name contain ':', if so only one and it should be
    // followed by a valid port number
    if(parts3.length > 2) {
      throw Error('Invalid Url');
    } else if(parts3.length === 2) {
      if(!parts3[1]) {
        throw Error('Invalid Url');
      }

      var intValue = parseInt(parts3[1], 10);
      if (intValue != parts3[1] || parts3[1] < 1 || parts3[1] > 65535) {
        throw Error('Port number should be a number in the range [1, 65535]');
      }

      port = intValue;
    }

    return {endpointHost: parts3[0], endpointPort: port};
  }
};
<|endoftext|>


<commit_before>var gulp        = require('gulp'),
    prefix      = require('gulp-autoprefixer'),
    sass        = require('gulp-sass'),
    rename      = require('gulp-rename'),
    smaps       = require('gulp-sourcemaps'),
    csso        = require('gulp-csso'),
    changed     = require('gulp-changed'),
    cheerio     = require('gulp-cheerio'),
    svgmin      = require('gulp-svgmin'),
    svgstore    = require('gulp-svgstore'),
    fs          = require('fs'),
    path        = require('path'),
    svgSettings = require('./.svgorc.json');

// Config
var BROWSERS = [
        'ie >= 11',
        'edge >= 20',
        'ff >= 40',
        'chrome >= 35',
        'safari >= 8',
        'opera >= 35',
        'ios >= 8'
    ],
    SCSS = 'src/assets/scss/',
    CSS = 'demo/css',
    MINIFY = true,
    DEV = 'src/icons/development/**/*',
    PRO = 'src/icons/production/',
    SECTIONS = [
        'brands',
        'mdi',
        'primary-nav'
    ],
    VIEW = 'src/views',
    DEMO = 'demo/';
    VIEW = 'src/views';

function getFolders(dir){
    return fs.readdirSync(dir)
        .filter(function(file) {
            return fs.statSync(path.join(dir, file)).isDirectory();
        });
}

var render = function(layer){
    'use strict';

    var stream = gulp
        .src(SCSS + layer + '.scss')
        .pipe(smaps.init())
        .pipe(sass({
            precision: 10,
            onError: console.error.bind(console, 'Sass error:')
        }))
        .pipe(prefix(BROWSERS));

    if (MINIFY) {
        stream = stream
            .pipe(csso())
            .pipe(rename({
                suffix: '.min',
                extname: '.css'
            }));
    }

    stream = stream
        .pipe(smaps.write('./'))
        .pipe(gulp.dest(CSS));

    return stream;
};

gulp.task('svgo', function(){
    'use strict';
    var stream = gulp;
    for(var i=0; i < SECTIONS.length; i++){
        stream = stream.src(DEV + '/' + SECTIONS[i])
            .pipe(changed(PRO + '/' + SECTIONS[i]))
            .pipe(svgmin(svgSettings))
            .pipe(cheerio({
                run: function ($) {
                    $('[fill]').removeAttr('fill');
                    $('[fill-rule]').removeAttr('fill-rule');
                },
                parserOptions: { xmlMode: true }
            }))
            .pipe(gulp.dest(PRO + '/' + SECTIONS[i]));
    }

    return stream;

});

gulp.task('svg-store', function(){
    'use strict';
    var stream = gulp;
    for(var i=0; i < SECTIONS.length; i++){
        stream = stream.src(PRO + '/' + SECTIONS[i])
            .pipe(changed(VIEW + '/' + SECTIONS[i] + '.html'))
            .pipe(svgstore())
            .pipe(cheerio({
                run: function ($) {
                    $('xml').remove();
                    // $('!DOCTYPE').remove();
                    $('svg').attr('class',  SECTIONS[i]);
                    $('svg').attr('style',  'position: absolute; width: 0; height: 0;');
                },
                parserOptions: { xmlMode: true }
            }))
            .pipe(rename({
                basename: SECTIONS[i],
                extname: '.html'
            }))
            .pipe(gulp.dest(VIEW));
    }

    return stream;

});

var svgClean = function(type, src, dest){
    'use strict';

    var stream = gulp
        .src(src)
        .pipe(changed(PRO + type))
        .pipe(svgmin(svgSettings))
        .pipe(rename(function(path){
            path.dirname = '/';
            // remove usless prefix/suffix.
            if (type == 'mdi') {
                path.basename = path.basename.slice(3, -5);
            }
        }))

        .pipe(gulp.dest(dest)); // PRO + 'mdi/'

    return stream;

};

var svgTemp = function(type, src, dest){
    'use strict';
    var stream = gulp
        .src(src)
        .pipe(svgstore())
        .pipe(cheerio({
            run: function ($) {
                $('xml').remove();
                // $('!DOCTYPE').remove();
                $('svg').attr('class',  type);
                $('svg').attr('style',  'position: absolute; width: 0; height: 0;');
            },
            parserOptions: { xmlMode: true }
        }))
        .pipe(rename({
            basename: type,
            extname: '.html'
        }))
        .pipe(gulp.dest(dest));

    return stream;
};

gulp.task('css', function(){
    'use strict';
    render('style');
});

gulp.task('views', ['build'], function() {
    'use strict';
    var stream = gulp
        .src(VIEW + '/*.twig')
        .pipe(swig())
        .pipe(gulp.dest(DEMO));

    return stream;
});

gulp.task('watch', function(){
    'use strict';
    gulp.watch(SCSS + '**/*.scss', ['css']);
    gulp.watch(DEV, ['svgo', 'svg-store']);
    gulp.watch(VIEW + '*', ['views']);
});

gulp.task('serve', ['watch']);
gulp.task('default', ['css', 'svgo', 'svg-store', 'views', 'watch']);
<commit_msg>cleanup gulp settings<commit_after>var gulp        = require('gulp'),
    prefix      = require('gulp-autoprefixer'),
    sass        = require('gulp-sass'),
    rename      = require('gulp-rename'),
    smaps       = require('gulp-sourcemaps'),
    csso        = require('gulp-csso'),
    changed     = require('gulp-changed'),
    cheerio     = require('gulp-cheerio'),
    svgmin      = require('gulp-svgmin'),
    svgstore    = require('gulp-svgstore'),
    fs          = require('fs'),
    path        = require('path'),
    svgSettings = require('./.svgorc.json');

// Config
var BROWSERS = [
        'ie >= 11',
        'edge >= 20',
        'ff >= 40',
        'chrome >= 35',
        'safari >= 8',
        'opera >= 35',
        'ios >= 8'
    ],
    SCSS = 'src/assets/scss/',
    CSS = 'demo/css',
    MINIFY = true,
    DEV = 'src/icons/development/**/*',
    PRO = 'src/icons/production/',
    VIEW = 'src/views';

function getFolders(dir){
    return fs.readdirSync(dir)
        .filter(function(file) {
            return fs.statSync(path.join(dir, file)).isDirectory();
        });
}

var render = function(layer){
    'use strict';

    var stream = gulp
        .src(SCSS + layer + '.scss')
        .pipe(smaps.init())
        .pipe(sass({
            precision: 10,
            onError: console.error.bind(console, 'Sass error:')
        }))
        .pipe(prefix(BROWSERS));

    if (MINIFY) {
        stream = stream
            .pipe(csso())
            .pipe(rename({
                suffix: '.min',
                extname: '.css'
            }));
    }

    stream = stream
        .pipe(smaps.write('./'))
        .pipe(gulp.dest(CSS));

    return stream;
};

gulp.task('css', function(){
    'use strict';
    render('style');
});

});

gulp.task('svg-store', function(){
    'use strict';
    var stream = gulp;
    for(var i=0; i < SECTIONS.length; i++){
        stream = stream.src(PRO + '/' + SECTIONS[i])
            .pipe(changed(VIEW + '/' + SECTIONS[i] + '.html'))
            .pipe(svgstore())
            .pipe(cheerio({
                run: function ($) {
                    $('xml').remove();
                    // $('!DOCTYPE').remove();
                    $('svg').attr('class',  SECTIONS[i]);
                    $('svg').attr('style',  'position: absolute; width: 0; height: 0;');
                },
                parserOptions: { xmlMode: true }
            }))
            .pipe(rename({
                basename: SECTIONS[i],
                extname: '.html'
            }))
            .pipe(gulp.dest(VIEW));
    }

    return stream;

});

var svgClean = function(type, src, dest){
    'use strict';

    var stream = gulp
        .src(src)
        .pipe(changed(PRO + type))
        .pipe(svgmin(svgSettings))
        .pipe(rename(function(path){
            path.dirname = '/';
            // remove usless prefix/suffix.
            if (type == 'mdi') {
                path.basename = path.basename.slice(3, -5);
            }
        }))

        .pipe(gulp.dest(dest)); // PRO + 'mdi/'

    return stream;

};

var svgTemp = function(type, src, dest){
    'use strict';
    var stream = gulp
        .src(src)
        .pipe(svgstore())
        .pipe(cheerio({
            run: function ($) {
                $('xml').remove();
                // $('!DOCTYPE').remove();
                $('svg').attr('class',  type);
                $('svg').attr('style',  'position: absolute; width: 0; height: 0;');
            },
            parserOptions: { xmlMode: true }
        }))
        .pipe(rename({
            basename: type,
            extname: '.html'
        }))
        .pipe(gulp.dest(dest));

    return stream;
};

gulp.task('css', function(){
    'use strict';
    render('style');
});

gulp.task('views', ['build'], function() {
    'use strict';
    var stream = gulp
        .src(VIEW + '/*.twig')
        .pipe(swig())
        .pipe(gulp.dest(DEMO));

    return stream;
});

gulp.task('watch', function(){
    'use strict';
    gulp.watch(SCSS + '**/*.scss', ['css']);
    gulp.watch(DEV, ['svgo', 'svg-store']);
    gulp.watch(VIEW + '*', ['views']);
});

gulp.task('serve', ['watch']);
gulp.task('default', ['css', 'svgo', 'svg-store', 'views', 'watch']);
<|endoftext|>


<commit_before>var _sutil = CT.stream.util = {
	// for single channel av
	blob_to_b64: function(blob, cb) {
		blob ? _sutil.read(blob, cb) : cb();
	},
	b64_to_blob: function(b64, cb) {
		b64 ? fetch(b64.video || b64).then(function(res) {
			return res.blob();
		}).then(cb) : cb();
	},
	blob_to_buffer: function(blob, cb) {
		blob ? _sutil.read(blob, cb, true) : cb();
	},
	b64_to_buffer: function(b64, cb) {
		_sutil.b64_to_blob(b64, function(blob) {
			_sutil.blob_to_buffer(blob, cb);
		});
	},
	// some browsers may require separate audio/video
	blobs_to_b64s: function(blobs, cb) {
		_sutil.blob_to_b64(blobs.video, function(b64video) {
			_sutil.blob_to_b64(blobs.audio, function(b64audio) {
				cb({ video: b64video, audio: b64audio });
			});
		});
	},
	b64s_to_blobs: function(b64s, cb) {
		_sutil.b64_to_blob(b64s.video, function(vblob) {
			_sutil.b64_to_blob(b64s.audio, function(ablob) {
				cb({ video: vblob, audio: ablob });
			});
		});
	},
	blobs_to_buffers: function(blobs, cb) {
		_sutil.blob_to_buffer(blobs.video, function(videobuffer) {
			_sutil.blob_to_buffer(blobs.audio, function(audiobuffer) {
				cb({ video: videobuffer, audio: audiobuffer });
			});
		});
	},
	b64s_to_buffers: function(b64s, cb) {
		_sutil.b64s_to_blobs(b64s, function(blobs) {
			_sutil.blobs_to_buffers(blobs, cb);
		});
	},
	// core functions
	read: function(blob, cb, buffer) {
		var signature = "read" + (buffer ? "buffer" : "url"),
			fr = new FileReader();
		CT.log.startTimer(signature);
		fr.onloadend = function() {
			CT.log.endTimer(signature, fr.result.length || fr.result.byteLength);
			cb(fr.result);
		};
		buffer ? fr.readAsArrayBuffer(blob) : fr.readAsDataURL(blob);
	},
	update: function(signature, process, requiredInitChunk) {
		if (requiredInitChunk && !signature.endsWith("init")) {
			CT.memcache.blob.get(requiredInitChunk, function(d) {
				process(d);
				CT.memcache.blob.get(signature, process, CT.stream.opts.codecs.video);
			}, CT.stream.opts.codecs.video);
		} else
			CT.memcache.blob.get(signature, process, CT.stream.opts.codecs.video);
	},
	_recorder: function(ondata, onrecorder) {
		return function(stream) {
			var segment = 0, recorder = new MediaRecorder(stream, CT.stream.opts.mropts);
			recorder.ondataavailable = function(blobevent) {
				CT.log("ondataavailable!! " + blobevent.data.size);
				segment = (segment + 1) % CT.stream.opts.segments;
				!recorder._stopped && ondata &&
					ondata({ video: blobevent.data }, segment);
			};
			recorder.onerror = function(e) {
				CT.log("error! " + e.message);
			};
			recorder.reset = function() {
				CT.log("RESETTING RECORDER");
				recorder.stop();
				recorder.start(CT.stream.opts.chunk);
			};
			recorder.start(CT.stream.opts.chunk);
			onrecorder && onrecorder(recorder, stream);
		};
	},
	record: function(ondata, onrecorder, onfail, mediaType) {
		CT.log.startTimer("record", "(attempt)");
		navigator.mediaDevices[mediaType || "getUserMedia"]({
			video: true, audio: true
		}).then(_sutil._recorder(ondata, onrecorder))["catch"](onfail || function(err) {
			CT.log.endTimer("record", "got error: " + err);
		});
	}
};

CT.stream.util.fzn = {
	_: { vids: {} },
	video: function(channel, videoClass, onrefresh) {
		var _ = CT.stream.util.fzn._, vid = _.vids[channel] = new CT.stream.Video({
			frame: false,
			activeAudio: true,
			onrefresh: onrefresh,
			videoClass: videoClass,
			onreset: function() {
				_.bridge.error({
					channel: channel,
					requiredInitChunk: vid.receivedInitChunk
				});
			}
		});
		CT.stream.util.fzn.init();
		_.bridge && _.bridge.subscribe(channel);
		return vid;
	},
	init: function() {
		var _ = CT.stream.util.fzn._, v;
		if (_.bridge) return;
		document.head.appendChild(CT.dom.script("https://fzn.party/CT/bridge.js", null, null, function() {
			_.bridge = PMB.bridge({
				widget: "/stream/vidsrc.html",
				senders: ["subscribe", "error"],
				receivers: {
					clip: function(data) {
						_.vids[data.channel].bufferer(data.data);
					}
				}
			});
			for (v in _.vids)
				_.bridge.subscribe(v);
		}));
	}
};<commit_msg>stream.util.update(): mimeType codecs.video -> mropts.mimeType<commit_after>var _sutil = CT.stream.util = {
	// for single channel av
	blob_to_b64: function(blob, cb) {
		blob ? _sutil.read(blob, cb) : cb();
	},
	b64_to_blob: function(b64, cb) {
		b64 ? fetch(b64.video || b64).then(function(res) {
			return res.blob();
		}).then(cb) : cb();
	},
	blob_to_buffer: function(blob, cb) {
		blob ? _sutil.read(blob, cb, true) : cb();
	},
	b64_to_buffer: function(b64, cb) {
		_sutil.b64_to_blob(b64, function(blob) {
			_sutil.blob_to_buffer(blob, cb);
		});
	},
	// some browsers may require separate audio/video
	blobs_to_b64s: function(blobs, cb) {
		_sutil.blob_to_b64(blobs.video, function(b64video) {
			_sutil.blob_to_b64(blobs.audio, function(b64audio) {
				cb({ video: b64video, audio: b64audio });
			});
		});
	},
	b64s_to_blobs: function(b64s, cb) {
		_sutil.b64_to_blob(b64s.video, function(vblob) {
			_sutil.b64_to_blob(b64s.audio, function(ablob) {
				cb({ video: vblob, audio: ablob });
			});
		});
	},
	blobs_to_buffers: function(blobs, cb) {
		_sutil.blob_to_buffer(blobs.video, function(videobuffer) {
			_sutil.blob_to_buffer(blobs.audio, function(audiobuffer) {
				cb({ video: videobuffer, audio: audiobuffer });
			});
		});
	},
	b64s_to_buffers: function(b64s, cb) {
		_sutil.b64s_to_blobs(b64s, function(blobs) {
			_sutil.blobs_to_buffers(blobs, cb);
		});
	},
	// core functions
	read: function(blob, cb, buffer) {
		var signature = "read" + (buffer ? "buffer" : "url"),
			fr = new FileReader();
		CT.log.startTimer(signature);
		fr.onloadend = function() {
			CT.log.endTimer(signature, fr.result.length || fr.result.byteLength);
			cb(fr.result);
		};
		buffer ? fr.readAsArrayBuffer(blob) : fr.readAsDataURL(blob);
	},
	update: function(signature, process, requiredInitChunk) {
		var mt = CT.stream.opts.mropts.mimeType;
//		var mt = CT.stream.opts.codecs.vp9;
		if (requiredInitChunk && !signature.endsWith("init")) {
			CT.memcache.blob.get(requiredInitChunk, function(d) {
				process(d);
				CT.memcache.blob.get(signature, process, mt);
			}, mt);
		} else
			CT.memcache.blob.get(signature, process, mt);
	},
	_recorder: function(ondata, onrecorder) {
		return function(stream) {
			var segment = 0, recorder = new MediaRecorder(stream, CT.stream.opts.mropts);
			recorder.ondataavailable = function(blobevent) {
				CT.log("ondataavailable!! " + blobevent.data.size);
				segment = (segment + 1) % CT.stream.opts.segments;
				!recorder._stopped && ondata &&
					ondata({ video: blobevent.data }, segment);
			};
			recorder.onerror = function(e) {
				CT.log("error! " + e.message);
			};
			recorder.reset = function() {
				CT.log("RESETTING RECORDER");
				recorder.stop();
				recorder.start(CT.stream.opts.chunk);
			};
			recorder.start(CT.stream.opts.chunk);
			onrecorder && onrecorder(recorder, stream);
		};
	},
	record: function(ondata, onrecorder, onfail, mediaType) {
		CT.log.startTimer("record", "(attempt)");
		navigator.mediaDevices[mediaType || "getUserMedia"]({
			video: true, audio: true
		}).then(_sutil._recorder(ondata, onrecorder))["catch"](onfail || function(err) {
			CT.log.endTimer("record", "got error: " + err);
		});
	}
};

CT.stream.util.fzn = {
	_: { vids: {} },
	video: function(channel, videoClass, onrefresh) {
		var _ = CT.stream.util.fzn._, vid = _.vids[channel] = new CT.stream.Video({
			frame: false,
			activeAudio: true,
			onrefresh: onrefresh,
			videoClass: videoClass,
			onreset: function() {
				_.bridge.error({
					channel: channel,
					requiredInitChunk: vid.receivedInitChunk
				});
			}
		});
		CT.stream.util.fzn.init();
		_.bridge && _.bridge.subscribe(channel);
		return vid;
	},
	init: function() {
		var _ = CT.stream.util.fzn._, v;
		if (_.bridge) return;
		document.head.appendChild(CT.dom.script("https://fzn.party/CT/bridge.js", null, null, function() {
			_.bridge = PMB.bridge({
				widget: "/stream/vidsrc.html",
				senders: ["subscribe", "error"],
				receivers: {
					clip: function(data) {
						_.vids[data.channel].bufferer(data.data);
					}
				}
			});
			for (v in _.vids)
				_.bridge.subscribe(v);
		}));
	}
};<|endoftext|>


<commit_before>export {
  default
} from 'https://www.lactame.com/lib/molecular-formula/0.3.13/molecular-formula.js';
<commit_msg>update molecular-formula to 0.3.14<commit_after>export {
  default
} from 'https://www.lactame.com/lib/molecular-formula/0.3.14/molecular-formula.js';
<|endoftext|>


<commit_before>/*
 * runtime.js
 * Objective-J
 *
 * Created by Francisco Tolmasky.
 * Copyright 2008, 280 North, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

var CLS_CLASS           = 0x1,
    CLS_META            = 0x2,
    CLS_INITIALIZED     = 0x4,
    CLS_INITIALIZING    = 0x8;

#define CHANGEINFO(aClass, aSetInfoMask, aClearInfoMask) aClass.info = (aClass.info | (aSetInfoMask)) & ~(aClearInfoMask)
#define GETINFO(aClass, anInfoMask) (aClass.info & (anInfoMask))
#define SETINFO(aClass, anInfoMask) CHANGEINFO(aClass, anInfoMask, 0)
#define CLEARINFO(aClass, anInfoMask) CHANGEINFO(aClass, 0, anInfoMask)
#define ISMETA(aClass) (GETINFO(aClass, CLS_META))
#define GETMETA(aClass) (ISMETA(aClass) ? aClass : aClass.isa)
#define ISINITIALIZED(aClass) GETINFO(GETMETA(aClass), CLS_INITIALIZED)

function objj_ivar(/*String*/ aName, /*String*/ aType)
{
    this.name = aName;
    this.type = aType;
}

function objj_method(/*String*/ aName, /*IMP*/ anImplementation, /*String*/ types)
{
    this.name = aName;
    this.method_imp = anImplementation;
    this.types = types;
}

function objj_class()
{
    this.isa            = NULL;

    this.super_class    = NULL;
    this.sub_classes    = [];

    this.name           = NULL;
    this.info           = 0;
    this.ivars          = [];

    this.method_list    = [];
    this.method_hash    = {};

    this.method_store   = function() { };
    this.method_dtable  = this.method_store.prototype;

    this.allocator      = function() { };
    this.__address      = -1;
}

function objj_object()
{
    this.isa        = NULL;
    this.__address  = -1;
}

// Addressing Objects

var OBJECT_COUNT   = 0;

function _objj_generateObjectHash()
{
    return OBJECT_COUNT++;
}

#define _objj_generateObjectHash() (OBJECT_COUNT++)

// Working with Classes

function class_getName(/*Class*/ aClass)
{
    if (aClass == Nil)
        return "";

    return aClass.name;
}

function class_isMetaClass(/*Class*/ aClass)
{
    if (!aClass)
        return NO;

    return ISMETA(aClass);
}

function class_getSuperclass(/*Class*/ aClass)
{
    if (aClass == Nil)
        return Nil;

    return aClass.super_class;
}

function class_setSuperclass(/*Class*/ aClass, /*Class*/ aSuperClass)
{
    // FIXME: implement.
}

function class_isMetaClass(/*Class*/ aClass)
{
    return ISMETA(aClass);
}

function class_addIvar(/*Class*/ aClass, /*String*/ aName, /*String*/ aType)
{
    var thePrototype = aClass.allocator.prototype;

    if (typeof thePrototype[aName] != "undefined")
        return NO;

    aClass.ivars.push(new objj_ivar(aName, aType));
    thePrototype[aName] = NULL;

    return YES;
}

function class_addIvars(/*Class*/ aClass, /*Array*/ivars)
{
    var index = 0,
        count = ivars.length,
        thePrototype = aClass.allocator.prototype;

    for (; index < count; ++index)
    {
        var ivar = ivars[index],
            name = ivar.name;

        if (typeof thePrototype[name] === "undefined")
        {
            aClass.ivars.push(ivar);
            thePrototype[name] = NULL;
        }
    }
}

function class_copyIvarList(/*Class*/ aClass)
{
    return aClass.ivars.slice(0);
}

//#define class_copyIvarList(aClass) (aClass.ivars.slice(0))

#define METHOD_DISPLAY_NAME(aClass, aMethod) (ISMETA(aClass) ? '+' : '-') + " [" + class_getName(aClass) + ' ' + method_getName(aMethod) + ']'

function class_addMethod(/*Class*/ aClass, /*SEL*/ aName, /*IMP*/ anImplementation, /*String*/aType)
{
    if (aClass.method_hash[aName])
        return NO;

    var method = new objj_method(aName, anImplementation, aType);

    aClass.method_list.push(method);
    aClass.method_dtable[aName] = method;

    // Give this function a "pretty" name for the console.
    method.method_imp.displayName = METHOD_DISPLAY_NAME(aClass, method);

    // FIXME: Should this be done here?
    // If this is a root class...
    if (!ISMETA(aClass) && GETMETA(aClass).isa === GETMETA(aClass))
        class_addMethods(GETMETA(aClass), methods);

    return YES;
}

function class_addMethods(/*Class*/ aClass, /*Array*/ methods)
{
    var index = 0,
        count = methods.length,

        method_list = aClass.method_list,
        method_dtable = aClass.method_dtable;

    for (; index < count; ++index)
    {
        var method = methods[index];

        if (aClass.method_hash[method.name])
            continue;

        method_list.push(method);
        method_dtable[method.name] = method;

        // Give this function a "pretty" name for the console.
        method.method_imp.displayName = METHOD_DISPLAY_NAME(aClass, method);
    }

    // If this is a root class...
    if (!ISMETA(aClass) && GETMETA(aClass).isa === GETMETA(aClass))
        class_addMethods(GETMETA(aClass), methods);
}

function class_getInstanceMethod(/*Class*/ aClass, /*SEL*/ aSelector)
{
    if (!aClass || !aSelector)
        return NULL;

    var method = aClass.method_dtable[aSelector];

    return method ? method : NULL;
}

function class_getClassMethod(/*Class*/ aClass, /*SEL*/ aSelector)
{
    if (!aClass || !aSelector)
        return NULL;

    var method = GETMETA(aClass).method_dtable[aSelector];

    return method ? method : NULL;
}

function class_copyMethodList(/*Class*/ aClass)
{
    return aClass.method_list.slice(0);
}

function class_replaceMethod(/*Class*/ aClass, /*SEL*/ aSelector, /*IMP*/ aMethodImplementation)
{
    if (!aClass || !aSelector)
        return NULL;

    var method = aClass.method_dtable[aSelector],
        method_imp = NULL;

    if (method)
        method_imp = method.method_imp;

    method.method_imp = aMethodImplementation;

    return method_imp;
}

var _class_initialize = function(/*Class*/ aClass)
{
    var meta = GETMETA(aClass);

    if (GETINFO(aClass, CLS_META))
        aClass = objj_getClass(aClass.name);

    if (aClass.super_class && !ISINITIALIZED(aClass.super_class))
        _class_initialize(aClass.super_class);

    if (!GETINFO(meta, CLS_INITIALIZED) && !GETINFO(meta, CLS_INITIALIZING))
    {
        SETINFO(meta, CLS_INITIALIZING);

        objj_msgSend(aClass, "initialize");

        CHANGEINFO(meta, CLS_INITIALIZED, CLS_INITIALIZING);
    }
}

var _objj_forward = new objj_method("forward", function(self, _cmd)
{
    return objj_msgSend(self, "forward::", _cmd, arguments);
});

// I think this forward:: may need to be a common method, instead of defined in CPObject.
#define CLASS_GET_METHOD_IMPLEMENTATION(aMethodImplementation, aClass, aSelector)\
    if (!ISINITIALIZED(aClass))\
        _class_initialize(aClass);\
    \
    var method = aClass.method_dtable[aSelector];\
    \
    if (!method)\
        method = _objj_forward;\
    \
    aMethodImplementation = method.method_imp;

function class_getMethodImplementation(/*Class*/ aClass, /*SEL*/ aSelector)
{
    CLASS_GET_METHOD_IMPLEMENTATION(var implementation, aClass, aSelector);

    return implementation;
}

// Adding Classes

var GLOBAL_NAMESPACE    = window,
    REGISTERED_CLASSES  = {};

function objj_allocateClassPair(/*Class*/ superclass, /*String*/ aName)
{
    var classObject = new objj_class(),
        metaClassObject = new objj_class(),
        rootClassObject = classObject;

    // If we don't have a superclass, we are the root class.
    if (superclass)
    {
        rootClassObject = superclass;

        while (rootClassObject.superclass)
            rootClassObject = rootClassObject.superclass;

        // Give our current allocator all the instance variables of our super class' allocator.
        classObject.allocator.prototype = new superclass.allocator;

        // "Inheret" parent methods.
        classObject.method_store.prototype = new superclass.method_store;
        classObject.method_dtable = classObject.method_store.prototype;

        metaClassObject.method_store.prototype = new superclass.isa.method_store;
        metaClassObject.method_dtable = metaClassObject.method_store.prototype;

        // Set up the actual class hierarchy.
        classObject.super_class = superclass;
        metaClassObject.super_class = superclass.isa;
    }
    else
        classObject.allocator.prototype = new objj_object();

    classObject.isa = metaClassObject;
    classObject.name = aName;
    classObject.info = CLS_CLASS;
    classObject.__address = _objj_generateObjectHash();

    metaClassObject.isa = rootClassObject.isa;
    metaClassObject.name = aName;
    metaClassObject.info = CLS_META;
    metaClassObject.__address = _objj_generateObjectHash();

    return classObject;
}

function objj_registerClassPair(/*Class*/ aClass)
{
    GLOBAL_NAMESPACE[aClass.name] = aClass;
    REGISTERED_CLASSES[aClass.name] = aClass;
}

// Instantiating Classes

function class_createInstance(/*Class*/ aClass)
{
    if (!aClass)
        objj_exception_throw(new objj_exception(OBJJNilClassException, "*** Attempting to create object with Nil class."));

    var object = new aClass.allocator;

    object.__address = _objj_generateObjectHash();
    object.isa = aClass;

    return object;
}

// Opera 9.5.1 has a bug where prototypes "inheret" members from instances when "with" is used.
// Given that the Opera team is so fond of bug-testing instead of version-testing, we'll go
// ahead and do that.

var prototype_bug = function() { }

prototype_bug.prototype.member = false;

with (new prototype_bug())
    member = true;

// If the bug exists, go down the slow path.
if (new prototype_bug().member)
{

var fast_class_createInstance = class_createInstance;

class_createInstance = function(/*Class*/ aClass)
{
    var object = fast_class_createInstance(aClass);

    if (object)
    {
        var theClass = object.isa,
            actualClass = theClass;

        while (theClass)
        {
            var ivars = theClass.ivars;
                count = ivars.length;

            while (count--)
                object[ivars[count].name] = NULL;

            theClass = theClass.super_class;
        }

        object.isa = actualClass;
    }

    return object;
}

}

// Working with Instances

function object_getClassName(/*id*/ anObject)
{
    if (!anObject)
        return "";

    var theClass = anObject.isa;

    return theClass ? class_getName(theClass) : "";
}

//objc_getClassList
function objj_lookUpClass(/*String*/ aName)
{
    var theClass = REGISTERED_CLASSES[aName];

    return theClass ? theClass : Nil;
}

function objj_getClass(/*String*/ aName)
{
    var theClass = REGISTERED_CLASSES[aName];

    if (!theClass)
    {
        // class handler callback???
    }

    return theClass ? theClass : Nil;
}

//objc_getRequiredClass
function objj_getMetaClass(/*String*/ aName)
{
    var theClass = objj_getClass(aName);

    return GETMETA(theClass);
}

// Working with Instance Variables

function ivar_getName(anIvar)
{
    return anIvar.name;
}

function ivar_getTypeEncoding(anIvar)
{
    return anIvar.type;
}

// Sending Messages

function objj_msgSend(/*id*/ aReceiver, /*SEL*/ aSelector)
{
    if (aReceiver == nil)
        return nil;

    CLASS_GET_METHOD_IMPLEMENTATION(var implementation, aReceiver.isa, aSelector);

    return implementation.apply(aReceiver, arguments);
}

function objj_msgSendSuper(/*id*/ aSuper, /*SEL*/ aSelector)
{
    var super_class = aSuper.super_class;

    arguments[0] = aSuper.receiver;

    CLASS_GET_METHOD_IMPLEMENTATION(var implementation, super_class, aSelector);

    return implementation.apply(aSuper.receiver, arguments);
}

// Working with Methods

function method_getName(/*Method*/ aMethod)
{
    return aMethod.name;
}

function method_getImplementation(/*Method*/ aMethod)
{
    return aMethod.method_imp;
}

function method_setImplementation(/*Method*/ aMethod, /*IMP*/ anImplementation)
{
    var oldImplementation = aMethod.method_imp;

    aMethod.method_imp = anImplementation;

    return oldImplementation;
}

function method_exchangeImplementations(/*Method*/ lhs, /*Method*/ rhs)
{
    var lhs_imp = method_getImplementation(lhs),
        rhs_imp = method_getImplementation(rhs);

    method_setImplementation(lhs, rhs_imp);
    method_setImplementation(rhs, lhs_imp);
}

// Working with Selectors

function sel_getName(aSelector)
{
    return aSelector ? aSelector : "<null selector>";
}

function sel_getUid(/*String*/ aName)
{
    return aName;
}

function sel_isEqual(/*SEL*/ lhs, /*SEL*/ rhs)
{
    return lhs === rhs;
}

function sel_registerName(aName)
{
    return aName;
}
<commit_msg>Remove the need to call Function.apply for most objj_msgSends<commit_after>/*
 * runtime.js
 * Objective-J
 *
 * Created by Francisco Tolmasky.
 * Copyright 2008, 280 North, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 */

var CLS_CLASS           = 0x1,
    CLS_META            = 0x2,
    CLS_INITIALIZED     = 0x4,
    CLS_INITIALIZING    = 0x8;

#define CHANGEINFO(aClass, aSetInfoMask, aClearInfoMask) aClass.info = (aClass.info | (aSetInfoMask)) & ~(aClearInfoMask)
#define GETINFO(aClass, anInfoMask) (aClass.info & (anInfoMask))
#define SETINFO(aClass, anInfoMask) CHANGEINFO(aClass, anInfoMask, 0)
#define CLEARINFO(aClass, anInfoMask) CHANGEINFO(aClass, 0, anInfoMask)
#define ISMETA(aClass) (GETINFO(aClass, CLS_META))
#define GETMETA(aClass) (ISMETA(aClass) ? aClass : aClass.isa)
#define ISINITIALIZED(aClass) GETINFO(GETMETA(aClass), CLS_INITIALIZED)

function objj_ivar(/*String*/ aName, /*String*/ aType)
{
    this.name = aName;
    this.type = aType;
}

function objj_method(/*String*/ aName, /*IMP*/ anImplementation, /*String*/ types)
{
    this.name = aName;
    this.method_imp = anImplementation;
    this.types = types;
}

function objj_class()
{
    this.isa            = NULL;

    this.super_class    = NULL;
    this.sub_classes    = [];

    this.name           = NULL;
    this.info           = 0;
    this.ivars          = [];

    this.method_list    = [];
    this.method_hash    = {};

    this.method_store   = function() { };
    this.method_dtable  = this.method_store.prototype;

    this.allocator      = function() { };
    this.__address      = -1;
}

function objj_object()
{
    this.isa        = NULL;
    this.__address  = -1;
}

// Addressing Objects

var OBJECT_COUNT   = 0;

function _objj_generateObjectHash()
{
    return OBJECT_COUNT++;
}

#define _objj_generateObjectHash() (OBJECT_COUNT++)

// Working with Classes

function class_getName(/*Class*/ aClass)
{
    if (aClass == Nil)
        return "";

    return aClass.name;
}

function class_isMetaClass(/*Class*/ aClass)
{
    if (!aClass)
        return NO;

    return ISMETA(aClass);
}

function class_getSuperclass(/*Class*/ aClass)
{
    if (aClass == Nil)
        return Nil;

    return aClass.super_class;
}

function class_setSuperclass(/*Class*/ aClass, /*Class*/ aSuperClass)
{
    // FIXME: implement.
}

function class_isMetaClass(/*Class*/ aClass)
{
    return ISMETA(aClass);
}

function class_addIvar(/*Class*/ aClass, /*String*/ aName, /*String*/ aType)
{
    var thePrototype = aClass.allocator.prototype;

    if (typeof thePrototype[aName] != "undefined")
        return NO;

    aClass.ivars.push(new objj_ivar(aName, aType));
    thePrototype[aName] = NULL;

    return YES;
}

function class_addIvars(/*Class*/ aClass, /*Array*/ivars)
{
    var index = 0,
        count = ivars.length,
        thePrototype = aClass.allocator.prototype;

    for (; index < count; ++index)
    {
        var ivar = ivars[index],
            name = ivar.name;

        if (typeof thePrototype[name] === "undefined")
        {
            aClass.ivars.push(ivar);
            thePrototype[name] = NULL;
        }
    }
}

function class_copyIvarList(/*Class*/ aClass)
{
    return aClass.ivars.slice(0);
}

//#define class_copyIvarList(aClass) (aClass.ivars.slice(0))

#define METHOD_DISPLAY_NAME(aClass, aMethod) (ISMETA(aClass) ? '+' : '-') + " [" + class_getName(aClass) + ' ' + method_getName(aMethod) + ']'

function class_addMethod(/*Class*/ aClass, /*SEL*/ aName, /*IMP*/ anImplementation, /*String*/aType)
{
    if (aClass.method_hash[aName])
        return NO;

    var method = new objj_method(aName, anImplementation, aType);

    aClass.method_list.push(method);
    aClass.method_dtable[aName] = method;

    // Give this function a "pretty" name for the console.
    method.method_imp.displayName = METHOD_DISPLAY_NAME(aClass, method);

    // FIXME: Should this be done here?
    // If this is a root class...
    if (!ISMETA(aClass) && GETMETA(aClass).isa === GETMETA(aClass))
        class_addMethods(GETMETA(aClass), methods);

    return YES;
}

function class_addMethods(/*Class*/ aClass, /*Array*/ methods)
{
    var index = 0,
        count = methods.length,

        method_list = aClass.method_list,
        method_dtable = aClass.method_dtable;

    for (; index < count; ++index)
    {
        var method = methods[index];

        if (aClass.method_hash[method.name])
            continue;

        method_list.push(method);
        method_dtable[method.name] = method;

        // Give this function a "pretty" name for the console.
        method.method_imp.displayName = METHOD_DISPLAY_NAME(aClass, method);
    }

    // If this is a root class...
    if (!ISMETA(aClass) && GETMETA(aClass).isa === GETMETA(aClass))
        class_addMethods(GETMETA(aClass), methods);
}

function class_getInstanceMethod(/*Class*/ aClass, /*SEL*/ aSelector)
{
    if (!aClass || !aSelector)
        return NULL;

    var method = aClass.method_dtable[aSelector];

    return method ? method : NULL;
}

function class_getClassMethod(/*Class*/ aClass, /*SEL*/ aSelector)
{
    if (!aClass || !aSelector)
        return NULL;

    var method = GETMETA(aClass).method_dtable[aSelector];

    return method ? method : NULL;
}

function class_copyMethodList(/*Class*/ aClass)
{
    return aClass.method_list.slice(0);
}

function class_replaceMethod(/*Class*/ aClass, /*SEL*/ aSelector, /*IMP*/ aMethodImplementation)
{
    if (!aClass || !aSelector)
        return NULL;

    var method = aClass.method_dtable[aSelector],
        method_imp = NULL;

    if (method)
        method_imp = method.method_imp;

    method.method_imp = aMethodImplementation;

    return method_imp;
}

var _class_initialize = function(/*Class*/ aClass)
{
    var meta = GETMETA(aClass);

    if (GETINFO(aClass, CLS_META))
        aClass = objj_getClass(aClass.name);

    if (aClass.super_class && !ISINITIALIZED(aClass.super_class))
        _class_initialize(aClass.super_class);

    if (!GETINFO(meta, CLS_INITIALIZED) && !GETINFO(meta, CLS_INITIALIZING))
    {
        SETINFO(meta, CLS_INITIALIZING);

        objj_msgSend(aClass, "initialize");

        CHANGEINFO(meta, CLS_INITIALIZED, CLS_INITIALIZING);
    }
}

var _objj_forward = new objj_method("forward", function(self, _cmd)
{
    return objj_msgSend(self, "forward::", _cmd, arguments);
});

// I think this forward:: may need to be a common method, instead of defined in CPObject.
#define CLASS_GET_METHOD_IMPLEMENTATION(aMethodImplementation, aClass, aSelector)\
    if (!ISINITIALIZED(aClass))\
        _class_initialize(aClass);\
    \
    var method = aClass.method_dtable[aSelector];\
    \
    if (!method)\
        method = _objj_forward;\
    \
    aMethodImplementation = method.method_imp;

function class_getMethodImplementation(/*Class*/ aClass, /*SEL*/ aSelector)
{
    CLASS_GET_METHOD_IMPLEMENTATION(var implementation, aClass, aSelector);

    return implementation;
}

// Adding Classes

var GLOBAL_NAMESPACE    = window,
    REGISTERED_CLASSES  = {};

function objj_allocateClassPair(/*Class*/ superclass, /*String*/ aName)
{
    var classObject = new objj_class(),
        metaClassObject = new objj_class(),
        rootClassObject = classObject;

    // If we don't have a superclass, we are the root class.
    if (superclass)
    {
        rootClassObject = superclass;

        while (rootClassObject.superclass)
            rootClassObject = rootClassObject.superclass;

        // Give our current allocator all the instance variables of our super class' allocator.
        classObject.allocator.prototype = new superclass.allocator;

        // "Inheret" parent methods.
        classObject.method_store.prototype = new superclass.method_store;
        classObject.method_dtable = classObject.method_store.prototype;

        metaClassObject.method_store.prototype = new superclass.isa.method_store;
        metaClassObject.method_dtable = metaClassObject.method_store.prototype;

        // Set up the actual class hierarchy.
        classObject.super_class = superclass;
        metaClassObject.super_class = superclass.isa;
    }
    else
        classObject.allocator.prototype = new objj_object();

    classObject.isa = metaClassObject;
    classObject.name = aName;
    classObject.info = CLS_CLASS;
    classObject.__address = _objj_generateObjectHash();

    metaClassObject.isa = rootClassObject.isa;
    metaClassObject.name = aName;
    metaClassObject.info = CLS_META;
    metaClassObject.__address = _objj_generateObjectHash();

    return classObject;
}

function objj_registerClassPair(/*Class*/ aClass)
{
    GLOBAL_NAMESPACE[aClass.name] = aClass;
    REGISTERED_CLASSES[aClass.name] = aClass;
}

// Instantiating Classes

function class_createInstance(/*Class*/ aClass)
{
    if (!aClass)
        objj_exception_throw(new objj_exception(OBJJNilClassException, "*** Attempting to create object with Nil class."));

    var object = new aClass.allocator;

    object.__address = _objj_generateObjectHash();
    object.isa = aClass;

    return object;
}

// Opera 9.5.1 has a bug where prototypes "inheret" members from instances when "with" is used.
// Given that the Opera team is so fond of bug-testing instead of version-testing, we'll go
// ahead and do that.

var prototype_bug = function() { }

prototype_bug.prototype.member = false;

with (new prototype_bug())
    member = true;

// If the bug exists, go down the slow path.
if (new prototype_bug().member)
{

var fast_class_createInstance = class_createInstance;

class_createInstance = function(/*Class*/ aClass)
{
    var object = fast_class_createInstance(aClass);

    if (object)
    {
        var theClass = object.isa,
            actualClass = theClass;

        while (theClass)
        {
            var ivars = theClass.ivars;
                count = ivars.length;

            while (count--)
                object[ivars[count].name] = NULL;

            theClass = theClass.super_class;
        }

        object.isa = actualClass;
    }

    return object;
}

}

// Working with Instances

function object_getClassName(/*id*/ anObject)
{
    if (!anObject)
        return "";

    var theClass = anObject.isa;

    return theClass ? class_getName(theClass) : "";
}

//objc_getClassList
function objj_lookUpClass(/*String*/ aName)
{
    var theClass = REGISTERED_CLASSES[aName];

    return theClass ? theClass : Nil;
}

function objj_getClass(/*String*/ aName)
{
    var theClass = REGISTERED_CLASSES[aName];

    if (!theClass)
    {
        // class handler callback???
    }

    return theClass ? theClass : Nil;
}

//objc_getRequiredClass
function objj_getMetaClass(/*String*/ aName)
{
    var theClass = objj_getClass(aName);

    return GETMETA(theClass);
}

// Working with Instance Variables

function ivar_getName(anIvar)
{
    return anIvar.name;
}

function ivar_getTypeEncoding(anIvar)
{
    return anIvar.type;
}

// Sending Messages

function objj_msgSend(/*id*/ aReceiver, /*SEL*/ aSelector)
{
    if (aReceiver == nil)
        return nil;

    CLASS_GET_METHOD_IMPLEMENTATION(var implementation, aReceiver.isa, aSelector);

    switch(arguments.length)
    {
        case 2:
            return implementation(aReceiver, aSelector);
        case 3:
            return implementation(aReceiver, aSelector, arguments[2]);
        case 4:
            return implementation(aReceiver, aSelector, arguments[2], arguments[3]);
    }

    return implementation.apply(aReceiver, arguments);
}

function objj_msgSendSuper(/*id*/ aSuper, /*SEL*/ aSelector)
{
    var super_class = aSuper.super_class;

    arguments[0] = aSuper.receiver;

    CLASS_GET_METHOD_IMPLEMENTATION(var implementation, super_class, aSelector);

    return implementation.apply(aSuper.receiver, arguments);
}

// Working with Methods

function method_getName(/*Method*/ aMethod)
{
    return aMethod.name;
}

function method_getImplementation(/*Method*/ aMethod)
{
    return aMethod.method_imp;
}

function method_setImplementation(/*Method*/ aMethod, /*IMP*/ anImplementation)
{
    var oldImplementation = aMethod.method_imp;

    aMethod.method_imp = anImplementation;

    return oldImplementation;
}

function method_exchangeImplementations(/*Method*/ lhs, /*Method*/ rhs)
{
    var lhs_imp = method_getImplementation(lhs),
        rhs_imp = method_getImplementation(rhs);

    method_setImplementation(lhs, rhs_imp);
    method_setImplementation(rhs, lhs_imp);
}

// Working with Selectors

function sel_getName(aSelector)
{
    return aSelector ? aSelector : "<null selector>";
}

function sel_getUid(/*String*/ aName)
{
    return aName;
}

function sel_isEqual(/*SEL*/ lhs, /*SEL*/ rhs)
{
    return lhs === rhs;
}

function sel_registerName(aName)
{
    return aName;
}
<|endoftext|>


<commit_before>var path     = require('path');
var should   = require('chai').should();
var expect   = require('chai').expect;
var avisynth = require('../main');
var system   = require('../code/system');
var my       = require('../package.json');

// Since testing a command line script is a bunch of boilerplate, I'll abstract it.
function testCli(doneCallback, args, stdin, expectedCode, expectedOut, expectedErr) {
    // Note that while we use a shebang in the cli script and npm can wrap it in
    // shell scripts automatically, in this case we're running it by itself and
    // in Windows shebangs don't count. So we must explicitely run it through node.
    var cli = path.resolve(__dirname, '../cli.js');
    var args = [cli].concat(args);
    // Also note that we're reusing system's spawn because we're not masochists.
    system.spawn('node', args, __dirname, true, function(returnCode, stdout, stderr) {
        expect(returnCode).to.equal(expectedCode);
        // Note how expectedOut and expectedErr can be strings or validator functions.
        if (typeof expectedOut === 'string') {
            expect(stdout).to.equal(expectedOut);
        } else {
            expect(expectedOut(stdout)).to.equal(true);
        }
        if (typeof expectedErr === 'string') {
            expect(stderr).to.equal(expectedErr);
        } else {
            expect(expectedErr(stderr)).to.equal(true);
        }

        doneCallback();
    });
}

describe('Command-line interface', function() {
    this.timeout(10000); // All tests here shouldn't fail because of timeouts.

    describe('avisynth-js version', function() {
        it('should print the version number', function(done) {
            testCli(done, ['version'], null, 0, my.version + '\n', '');
        });
    });

    describe('avisynth-js help', function() {
        it('should print the help without warnings', function(done) {
            testCli(done, ['help'], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });

        it('should print help with warnings when a bad command is used', function(done) {
            testCli(done, ['feminism'], null, 1, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[4] !== 'Bad argument: "feminism"') ok = false;
                if (!/^Usage: /.test(lines[6])) ok = false;
                return ok;
            }, '');
        });

        it('should print help without warnings when no command is used', function(done) {
            testCli(done, [], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });
    });

    describe('avisynth-js info', function() {
        it('should return expected info (NTSC broadcast example)', function(done) {
            // Let's cook up a NTSC broadcast example.
            var script = new avisynth.Script();
            script.colorBarsHD(640, 480);
            script.assumeFPS('ntsc_film');
            script.trim(1, 1438);
            script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
            script.convertAudioTo16bit();
            script.convertToYV12();
            script.assumeFieldBased();
            script.assumeTFF();

            var info = {
                width         : 640,
                height        : 480,
                ratio         : '4:3',
                fps           : 23.976,
                fpsFraction   : '24000/1001',
                videoTime     : 59.9766,
                frameCount    : 1438,
                colorspace    : 'YV12',
                bitsPerPixel  : 12,
                interlaceType : 'field-based',
                fieldOrder    : 'TFF',
                channels      : 1,
                bitsPerSample : 16,
                sampleType    : 'int',
                audioTime     : 54.321,
                samplingRate  : 44056,
                sampleCount   : 2393166,
                blockSize     : 2
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return expected info (1080p production example)', function(done) {
            // Let's cook up a 1080p "production-grade" example.
            var script = new avisynth.Script();
            script.colorBarsHD(1920, 1080);
            script.assumeFPS(60);
            script.trim(1, 3600);
            script.code('AudioDub(Tone(60, 528, 48000, 6))');
            script.convertAudioToFloat();
            script.convertToYUY2();
            script.assumeFrameBased();

            var info = {
                width         : 1920,
                height        : 1080,
                ratio         : '16:9',
                fps           : 60,
                fpsFraction   : '60/1',
                videoTime     : 60,
                frameCount    : 3600,
                colorspace    : 'YUY2',
                bitsPerPixel  : 16,
                interlaceType : 'frame-based',
                fieldOrder    : 'BFF',
                channels      : 6,
                bitsPerSample : 32,
                sampleType    : 'float',
                audioTime     : 60,
                samplingRate  : 48000,
                sampleCount   : 2880000,
                blockSize     : 24
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return an error when no script is provided', function(done) {
            var args = ['info'];
            var msg = 'An Avisynth script path must be provided.\n';
            testCli(done, args, null, 2, msg, '');
        });

        it('should return an error when script does not exist', function(done) {
            var args = ['info', 'C:/miss1ng5cript.avs'];
            var msg = 'Script not found: "C:/miss1ng5cript.avs"\n';
            testCli(done, args, null, 3, msg, '');
        });

        it('should return an error when script has code errors', function(done) {
            var script = new avisynth.Script('Egalitarianism');
            var args = ['info', script.getPath()];
            testCli(done, args, null, 4, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[0] !== 'Avisynth script could not be processed:') ok = false;
                if (lines[1] !== "I don't know what 'Egalitarianism' means.") ok = false;
                return ok;
            }, '');
        });
    });
});
<commit_msg>Test for valid lint example<commit_after>var path     = require('path');
var should   = require('chai').should();
var expect   = require('chai').expect;
var avisynth = require('../main');
var system   = require('../code/system');
var my       = require('../package.json');

// Since testing a command line script is a bunch of boilerplate, I'll abstract it.
function testCli(doneCallback, args, stdin, expectedCode, expectedOut, expectedErr) {
    // Note that while we use a shebang in the cli script and npm can wrap it in
    // shell scripts automatically, in this case we're running it by itself and
    // in Windows shebangs don't count. So we must explicitely run it through node.
    var cli = path.resolve(__dirname, '../cli.js');
    var args = [cli].concat(args);
    // Also note that we're reusing system's spawn because we're not masochists.
    system.spawn('node', args, __dirname, true, function(returnCode, stdout, stderr) {
        expect(returnCode).to.equal(expectedCode);
        // Note how expectedOut and expectedErr can be strings or validator functions.
        if (typeof expectedOut === 'string') {
            expect(stdout).to.equal(expectedOut);
        } else {
            expect(expectedOut(stdout)).to.equal(true);
        }
        if (typeof expectedErr === 'string') {
            expect(stderr).to.equal(expectedErr);
        } else {
            expect(expectedErr(stderr)).to.equal(true);
        }

        doneCallback();
    });
}

describe('Command-line interface', function() {
    this.timeout(10000); // All tests here shouldn't fail because of timeouts.

    describe('avisynth-js version', function() {
        it('should print the version number', function(done) {
            testCli(done, ['version'], null, 0, my.version + '\n', '');
        });
    });

    describe('avisynth-js help', function() {
        it('should print the help without warnings', function(done) {
            testCli(done, ['help'], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });

        it('should print help with warnings when a bad command is used', function(done) {
            testCli(done, ['feminism'], null, 1, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[4] !== 'Bad argument: "feminism"') ok = false;
                if (!/^Usage: /.test(lines[6])) ok = false;
                return ok;
            }, '');
        });

        it('should print help without warnings when no command is used', function(done) {
            testCli(done, [], null, 0, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                lines.forEach(function(line) {
                    if (/^Bad argument: /.test(line)) ok = false;
                });
                if (!/^Usage: /.test(lines[4])) ok = false;
                return ok;
            }, '');
        });
    });

    describe('avisynth-js info', function() {
    });

    describe('avisynth-js info', function() {
        it('should return expected info (NTSC broadcast example)', function(done) {
            // Let's cook up a NTSC broadcast example.
            var script = new avisynth.Script();
            script.colorBarsHD(640, 480);
            script.assumeFPS('ntsc_film');
            script.trim(1, 1438);
            script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
            script.convertAudioTo16bit();
            script.convertToYV12();
            script.assumeFieldBased();
            script.assumeTFF();

            var info = {
                width         : 640,
                height        : 480,
                ratio         : '4:3',
                fps           : 23.976,
                fpsFraction   : '24000/1001',
                videoTime     : 59.9766,
                frameCount    : 1438,
                colorspace    : 'YV12',
                bitsPerPixel  : 12,
                interlaceType : 'field-based',
                fieldOrder    : 'TFF',
                channels      : 1,
                bitsPerSample : 16,
                sampleType    : 'int',
                audioTime     : 54.321,
                samplingRate  : 44056,
                sampleCount   : 2393166,
                blockSize     : 2
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return expected info (1080p production example)', function(done) {
            // Let's cook up a 1080p "production-grade" example.
            var script = new avisynth.Script();
            script.colorBarsHD(1920, 1080);
            script.assumeFPS(60);
            script.trim(1, 3600);
            script.code('AudioDub(Tone(60, 528, 48000, 6))');
            script.convertAudioToFloat();
            script.convertToYUY2();
            script.assumeFrameBased();

            var info = {
                width         : 1920,
                height        : 1080,
                ratio         : '16:9',
                fps           : 60,
                fpsFraction   : '60/1',
                videoTime     : 60,
                frameCount    : 3600,
                colorspace    : 'YUY2',
                bitsPerPixel  : 16,
                interlaceType : 'frame-based',
                fieldOrder    : 'BFF',
                channels      : 6,
                bitsPerSample : 32,
                sampleType    : 'float',
                audioTime     : 60,
                samplingRate  : 48000,
                sampleCount   : 2880000,
                blockSize     : 24
            };

            var args = ['info', script.getPath()];
            var infoJson = JSON.stringify(info, undefined, 4);
            testCli(done, args, null, 0, infoJson + '\n', '');
        });

        it('should return an error when no script is provided', function(done) {
            var args = ['info'];
            var msg = 'An Avisynth script path must be provided.\n';
            testCli(done, args, null, 2, msg, '');
        });

        it('should return an error when script does not exist', function(done) {
            var args = ['info', 'C:/miss1ng5cript.avs'];
            var msg = 'Script not found: "C:/miss1ng5cript.avs"\n';
            testCli(done, args, null, 3, msg, '');
        });

        it('should return an error when script has code errors', function(done) {
            var script = new avisynth.Script('Egalitarianism');
            var args = ['info', script.getPath()];
            testCli(done, args, null, 4, function(text) {
                var lines = text.split(/\r?\n/);
                var ok = true;
                if (lines[0] !== 'Avisynth script could not be processed:') ok = false;
                if (lines[1] !== "I don't know what 'Egalitarianism' means.") ok = false;
                return ok;
            }, '');
        });
    });

    describe('avisynth-js lint', function() {
        it('should return valid status for a valid script', function(done) {
            // Same NTSC broadcast example from before.
            var script = new avisynth.Script();
            script.colorBarsHD(640, 480);
            script.assumeFPS('ntsc_film');
            script.trim(1, 1438);
            script.code('AudioDub(Tone(54.321, 432, 44056, 1))');
            script.convertAudioTo16bit();
            script.convertToYV12();
            script.assumeFieldBased();
            script.assumeTFF();

            var args = ['lint', script.getPath()];
            var json = JSON.stringify({valid: true, message: null}, undefined, 4);
            testCli(done, args, null, 0, json + '\n', '');
        });
    });
});
<|endoftext|>