<commit_before>'use strict';

var node = document.createElement('style');
node.innerHTML = '.siteLinks ul li:first-child,.siteLinks .languageSwitcher{display:none;}'; // hide redundant links in hamburger menu
node.innerHTML += '.topicSummary .content {display:none;}'; // hide wikipedia panel
node.innerHTML += '.topicSummary .relatedLibrarian.content,.topicSummary .relatedTopics.content,.topicSummary .researchGuides.content {display:block;}' // show relevant panels

// To add more CSS, use lines like this:
// node.innerHTML += '.selector { font-size: large }';

document.body.appendChild(node);

// BEGIN QUALTRICS - fresh from scratch Intercept
var qualtricsNode = document.createElement('div');
qualtricsNode.setAttribute('id', 'SI_1Fl2lq0f3xEqTkh');
document.body.appendChild(qualtricsNode);
(function(){var g=function(e,h,f,g){
this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g+ "&t=" + (new Date()).getTime();document.body&&document.body.appendChild(a)}};
this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
try{(new g(100,"r","QSI_S_SI_1Fl2lq0f3xEqTkh","//zn0ombvsv6b6ofgif-ucsf.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_SIID=SI_1Fl2lq0f3xEqTkh&Q_LOC="+encodeURIComponent(window.location.href))).start()}catch(i){}})();
// END QUALTRICS

// Fix off-campus login link to redirect to current search results after login.
// We're going to depend on Summon's dependence on jQuery here.
(function () {
  var waitingForInitialLoad = true;

  var fixBannerLink = function () {
    var links = $('.vpnBanner.customAuthBanner div a');
    if (waitingForInitialLoad && links.length === 0) {
      setTimeout(fixBannerLink, 100);
      return;
    } else {
      waitingForInitialLoad = false;
      window.addEventListener('hashchange', fixBannerLink);
    }

    links.each(function() {
      if (/^Off the UCSF network/.test(this.text)) {
        $(this).attr('ng-href', 'https://ucsf.idm.oclc.org/login?qurl=' + encodeURIComponent(location.href));
        $(this).attr('href', 'https://ucsf.idm.oclc.org/login?qurl=' + encodeURIComponent(location.href));
      }
    });
  }

  $().ready(fixBannerLink);
}());
<commit_msg>Update CSS to deal with 7/26 Summon UI update.<commit_after>'use strict';

// custom CSS

var node = document.createElement('style');

//node.innerHTML = '.siteLinks ul li:first-child,.siteLinks .languageSwitcher{display:none;}'; // hide redundant links in hamburger menu

// hide language switcher in hamburger menu
node.innerHTML = '.siteLinks .languageSwitcher{display:none;}';

// make Refworks text in VPN banner the same size as other text
node.innerHTML += '.vpnBanner .btn-link{font-size:inherit;}';

//give VPN banner links more breathing room
node.innerHTML += '.vpnBanner .list-inline>li{padding-left:8px;padding-right:8px;}'

// hide wikipedia panel
node.innerHTML += '.topicSummary .content {display:none;}';

// but show relevant panels
node.innerHTML += '.topicSummary .relatedLibrarian.content,.topicSummary .relatedTopics.content,.topicSummary .researchGuides.content {display:block;}'

// make PREVIEW toggle more prominent
node.innerHTML +='.togglePreview {display:inline-block;padding:.2em;background-color:#e5f1f8;} .togglePreview a {color:005380 !important;} .togglePreview.active,.togglePreview:hover{background-color:#007cbe;} .togglePreview.active a {color:#fff !important;} .togglePreview:after {border-top-color#005380 !important;} .togglePreview.active:after {border-bottom-color: #fff !important;}';

// To add more CSS, use lines like this:
// node.innerHTML += '.selector { font-size: large }';

document.body.appendChild(node);

// BEGIN QUALTRICS - fresh from scratch Intercept
var qualtricsNode = document.createElement('div');
qualtricsNode.setAttribute('id', 'SI_1Fl2lq0f3xEqTkh');
document.body.appendChild(qualtricsNode);
(function(){var g=function(e,h,f,g){
this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g+ "&t=" + (new Date()).getTime();document.body&&document.body.appendChild(a)}};
this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
try{(new g(100,"r","QSI_S_SI_1Fl2lq0f3xEqTkh","//zn0ombvsv6b6ofgif-ucsf.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_SIID=SI_1Fl2lq0f3xEqTkh&Q_LOC="+encodeURIComponent(window.location.href))).start()}catch(i){}})();
// END QUALTRICS

// Fix off-campus login link to redirect to current search results after login.
// We're going to depend on Summon's dependence on jQuery here.
(function () {
  var waitingForInitialLoad = true;

  var fixBannerLink = function () {
    var links = $('.vpnBanner.customAuthBanner div a');
    if (waitingForInitialLoad && links.length === 0) {
      setTimeout(fixBannerLink, 100);
      return;
    } else {
      waitingForInitialLoad = false;
      window.addEventListener('hashchange', fixBannerLink);
    }

    links.each(function() {
      if (/^Off the UCSF network/.test(this.text)) {
        $(this).attr('ng-href', 'https://ucsf.idm.oclc.org/login?qurl=' + encodeURIComponent(location.href));
        $(this).attr('href', 'https://ucsf.idm.oclc.org/login?qurl=' + encodeURIComponent(location.href));
      }
    });
  }

  $().ready(fixBannerLink);
}());
<|endoftext|>


<commit_before>'use strict';

const {
  _shouldCompileModules,
  _shouldIncludeHelpers,
  _shouldHandleTypeScript,
  _getExtensions,
  _parentName,
  _shouldHighlightCode,
} = require("./lib/babel-options-util");

const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const babel = require('@babel/core');
const path = require('path');
const getBabelOptions = require('./lib/get-babel-options');
const findApp = require('./lib/find-app');
const emberPlugins = require('./lib/ember-plugins');

const APP_BABEL_RUNTIME_VERSION = new WeakMap();

let count = 0;

module.exports = {
  name: 'ember-cli-babel',
  configKey: 'ember-cli-babel',
  // Note: This is not used internally for this addon, this is added for users to import this function for getting the ember specific
  // babel plugins. Eg: adding ember specific babel plugins in their babel.config.js.
  buildEmberPlugins: emberPlugins,

  init() {
    this._super.init && this._super.init.apply(this, arguments);

    let checker = new VersionChecker(this);
    let dep = checker.for('ember-cli', 'npm');

    if (dep.lt('2.13.0')) {
      throw new Error(`ember-cli-babel@7 (used by ${_parentName(this.parent)} at ${this.parent.root}) cannot be used by ember-cli versions older than 2.13, you used ${dep.version}`);
    }
  },

  buildBabelOptions(_config) {
    let config = _config || this._getAddonOptions();
    return getBabelOptions(config, this);
  },

  _debugTree() {
    if (!this._cachedDebugTree) {
      this._cachedDebugTree = require('broccoli-debug').buildDebugCallback(`ember-cli-babel:${_parentName(this.parent)}`);
    }

    return this._cachedDebugTree.apply(null, arguments);
  },

  /**
   * Default babel options
   * @param {*} config
   */
  _getDefaultBabelOptions(config = {}) {
     let emberCLIBabelConfig = config["ember-cli-babel"];
     let providedAnnotation;
     let throwUnlessParallelizable;
     let sourceMaps = false;
     let shouldCompileModules = _shouldCompileModules(config, this.project);

     if (emberCLIBabelConfig) {
       providedAnnotation = emberCLIBabelConfig.annotation;
       throwUnlessParallelizable = emberCLIBabelConfig.throwUnlessParallelizable;
     }

     if (config.babel && "sourceMaps" in config.babel) {
       sourceMaps = config.babel.sourceMaps;
     }

     let options = {
       annotation: providedAnnotation || `Babel: ${_parentName(this.parent)}`,
       sourceMaps,
       throwUnlessParallelizable,
       filterExtensions: _getExtensions(config, this.parent),
       plugins: []
     };

     if (shouldCompileModules) {
       options.moduleIds = true;
       options.getModuleId = require("./lib/relative-module-paths").getRelativeModulePath;
     }

     options.highlightCode = _shouldHighlightCode(this.parent);
     options.babelrc = false;
     options.configFile = false;

     return options;
  },

  transpileTree(inputTree, _config) {

    let config = _config || this._getAddonOptions();
    let description = `000${++count}`.slice(-3);
    let postDebugTree = this._debugTree(inputTree, `${description}:input`);
    let options = this._getDefaultBabelOptions(config);
    let output;

    const customAddonConfig = config['ember-cli-babel'];
    const shouldUseBabelConfigFile = customAddonConfig && customAddonConfig.useBabelConfig;

    if (shouldUseBabelConfigFile) {
      let babelConfig = babel.loadPartialConfig({
        root: this.parent.root,
        rootMode: 'root',
        envName: process.env.EMBER_ENV || process.env.BABEL_ENV || process.env.NODE_ENV || "development",
      });

      if (babelConfig.config === undefined) {
        // should contain the file that we used for the config,
        // if it is undefined then we didn't find any config and
        // should error

        throw new Error(
          "Missing babel config file in the project root. Please double check if the babel config file exists or turn off the `useBabelConfig` option in your ember-cli-build.js file."
        );
      }
      // If the babel config file is found, then pass the path into the options for the transpiler
      // parse and leverage the same.
      options = Object.assign({}, options, { configFile: babelConfig.config });
    } else {
      options = Object.assign({}, options, this.buildBabelOptions(config));
    }

    if (!shouldUseBabelConfigFile && this._shouldDoNothing(options)) {
      output = postDebugTree;
    } else {
      let BabelTranspiler = require('broccoli-babel-transpiler');
      let transpilationInput = postDebugTree;

      if (_shouldHandleTypeScript(config, this.parent)) {
        let Funnel = require('broccoli-funnel');
        let inputWithoutDeclarations = new Funnel(transpilationInput, { exclude: ['**/*.d.ts'] });
        transpilationInput = this._debugTree(inputWithoutDeclarations, `${description}:filtered-input`);
      }
      output = new BabelTranspiler(transpilationInput, options);
    }

    return this._debugTree(output, `${description}:output`);
  },

  setupPreprocessorRegistry(type, registry) {
    registry.add('js', {
      name: 'ember-cli-babel',
      ext: _getExtensions(this._getAddonOptions(), this.parent),
      toTree: (tree) => this.transpileTree(tree)
    });
  },

  _shouldIncludePolyfill() {
    let addonOptions = this._getAddonOptions();
    let customOptions = addonOptions['ember-cli-babel'];

    if (customOptions && 'includePolyfill' in customOptions) {
      return customOptions.includePolyfill === true;
    } else {
      return false;
    }
  },

  _importPolyfill(app) {
    let polyfillPath = 'vendor/babel-polyfill/polyfill.js';

    if (this.import) {  // support for ember-cli >= 2.7
      this.import(polyfillPath, { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import(polyfillPath, { prepend: true });
    } else {
      // eslint-disable-next-line no-console
      console.warn('Please run: ember install ember-cli-import-polyfill');
    }
  },

  _getHelperVersion() {
    if (!APP_BABEL_RUNTIME_VERSION.has(this.project)) {
      let checker = new VersionChecker(this.project);
      APP_BABEL_RUNTIME_VERSION.set(this.project, checker.for('@babel/runtime', 'npm').version);
    }

    return APP_BABEL_RUNTIME_VERSION.get(this.project);
  },

  _getHelpersPlugin() {
    return [
      [
        require.resolve('@babel/plugin-transform-runtime'),
        {
          version: this._getHelperVersion(),
          regenerator: false,
          useESModules: true
        }
      ]
    ]
  },

  treeForAddon() {
    // Helpers are a global config, so only the root application should bother
    // generating and including the file.
    let isRootBabel = this.parent === this.project;
    let shouldIncludeHelpers = isRootBabel && _shouldIncludeHelpers(this._getAppOptions(), this);

    if (!shouldIncludeHelpers) { return; }

    const path = require('path');
    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    const babelHelpersPath = path.dirname(require.resolve('@babel/runtime/package.json'));

    let babelHelpersTree = new Funnel(new UnwatchedDir(babelHelpersPath), {
      srcDir: 'helpers/esm',
      destDir: '@babel/runtime/helpers/esm'
    });

    return this.transpileTree(babelHelpersTree, {
      'ember-cli-babel': {
        // prevents the helpers from being double transpiled, and including themselves
        disablePresetEnv: true
      }
    });
  },

  treeForVendor() {
    if (!this._shouldIncludePolyfill()) return;

    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    let polyfillDir = path.dirname(require.resolve('@babel/polyfill/dist/polyfill'));

    let polyfillTree = new Funnel(new UnwatchedDir(polyfillDir), {
      destDir: 'babel-polyfill'
    });

    return polyfillTree;
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldIncludePolyfill()) {
      this._importPolyfill(app);
    }
  },

  isPluginRequired(pluginName) {
    let targets = this._getTargets();

    // if no targets are setup, assume that all plugins are required
    if (!targets) { return true; }

    const isPluginRequired = require('@babel/helper-compilation-targets').isRequired;
    return isPluginRequired(pluginName, targets);
  },

  _getAddonOptions() {
    let parentOptions = this.parent && this.parent.options;
    let appOptions = this.app && this.app.options;

    if (parentOptions) {
      let customAddonOptions = parentOptions['ember-cli-babel'];

      if (customAddonOptions && 'includeExternalHelpers' in customAddonOptions) {
        throw new Error('includeExternalHelpers is not supported in addon configurations, it is an app-wide configuration option');
      }
    }

    return parentOptions || appOptions || {};
  },

  _getAppOptions() {
    let app = findApp(this);

    return (app && app.options) || {};
  },

  _getTargets() {
    let targets = this.project && this.project.targets;

    let parser = require('@babel/helper-compilation-targets').default;
    if (typeof targets === 'object' && targets !== null) {
      // babel version 7.10.0 introduced a change that mutates the input:
      // https://github.com/babel/babel/pull/11500
      // copy the object to guard against it, otherwise subsequent calls to
      // _getTargets() will only have a mutated copy and lose all config from `config/targets.js`
      // in the host application.
      // PR to fix this upstream in babel: https://github.com/babel/babel/pull/11648
      const copy = clone(targets);
      return parser(copy);
    } else {
      return targets;
    }
  },

  /*
   * Used to discover if the addon's current configuration will compile modules
   * or not.
   *
   * @public
   * @method shouldCompileModules
   */
  shouldCompileModules() {
    return _shouldCompileModules(this._getAddonOptions(), this.project);
  },

  // detect if running babel would do nothing... and do nothing instead
  _shouldDoNothing(options) {
    return !options.sourceMaps && !options.plugins.length;
  }
};
<commit_msg>Avoid repeatedly checking the `ember-cli` version<commit_after>'use strict';

const {
  _shouldCompileModules,
  _shouldIncludeHelpers,
  _shouldHandleTypeScript,
  _getExtensions,
  _parentName,
  _shouldHighlightCode,
} = require("./lib/babel-options-util");

const VersionChecker = require('ember-cli-version-checker');
const clone = require('clone');
const babel = require('@babel/core');
const path = require('path');
const getBabelOptions = require('./lib/get-babel-options');
const findApp = require('./lib/find-app');
const emberPlugins = require('./lib/ember-plugins');

const APP_BABEL_RUNTIME_VERSION = new WeakMap();
const PROJECTS_WITH_VALID_EMBER_CLI = new WeakSet();

let count = 0;

module.exports = {
  name: 'ember-cli-babel',
  configKey: 'ember-cli-babel',
  // Note: This is not used internally for this addon, this is added for users to import this function for getting the ember specific
  // babel plugins. Eg: adding ember specific babel plugins in their babel.config.js.
  buildEmberPlugins: emberPlugins,

  init() {
    this._super.init && this._super.init.apply(this, arguments);

    if (!PROJECTS_WITH_VALID_EMBER_CLI.has(this.project)) {
      let checker = new VersionChecker(this);
      let dep = checker.for('ember-cli', 'npm');

      if (dep.lt('2.13.0')) {
        throw new Error(`ember-cli-babel@7 (used by ${_parentName(this.parent)} at ${this.parent.root}) cannot be used by ember-cli versions older than 2.13, you used ${dep.version}`);
      }

      PROJECTS_WITH_VALID_EMBER_CLI.add(this.project);
    }
  },

  buildBabelOptions(_config) {
    let config = _config || this._getAddonOptions();
    return getBabelOptions(config, this);
  },

  _debugTree() {
    if (!this._cachedDebugTree) {
      this._cachedDebugTree = require('broccoli-debug').buildDebugCallback(`ember-cli-babel:${_parentName(this.parent)}`);
    }

    return this._cachedDebugTree.apply(null, arguments);
  },

  /**
   * Default babel options
   * @param {*} config
   */
  _getDefaultBabelOptions(config = {}) {
     let emberCLIBabelConfig = config["ember-cli-babel"];
     let providedAnnotation;
     let throwUnlessParallelizable;
     let sourceMaps = false;
     let shouldCompileModules = _shouldCompileModules(config, this.project);

     if (emberCLIBabelConfig) {
       providedAnnotation = emberCLIBabelConfig.annotation;
       throwUnlessParallelizable = emberCLIBabelConfig.throwUnlessParallelizable;
     }

     if (config.babel && "sourceMaps" in config.babel) {
       sourceMaps = config.babel.sourceMaps;
     }

     let options = {
       annotation: providedAnnotation || `Babel: ${_parentName(this.parent)}`,
       sourceMaps,
       throwUnlessParallelizable,
       filterExtensions: _getExtensions(config, this.parent),
       plugins: []
     };

     if (shouldCompileModules) {
       options.moduleIds = true;
       options.getModuleId = require("./lib/relative-module-paths").getRelativeModulePath;
     }

     options.highlightCode = _shouldHighlightCode(this.parent);
     options.babelrc = false;
     options.configFile = false;

     return options;
  },

  transpileTree(inputTree, _config) {

    let config = _config || this._getAddonOptions();
    let description = `000${++count}`.slice(-3);
    let postDebugTree = this._debugTree(inputTree, `${description}:input`);
    let options = this._getDefaultBabelOptions(config);
    let output;

    const customAddonConfig = config['ember-cli-babel'];
    const shouldUseBabelConfigFile = customAddonConfig && customAddonConfig.useBabelConfig;

    if (shouldUseBabelConfigFile) {
      let babelConfig = babel.loadPartialConfig({
        root: this.parent.root,
        rootMode: 'root',
        envName: process.env.EMBER_ENV || process.env.BABEL_ENV || process.env.NODE_ENV || "development",
      });

      if (babelConfig.config === undefined) {
        // should contain the file that we used for the config,
        // if it is undefined then we didn't find any config and
        // should error

        throw new Error(
          "Missing babel config file in the project root. Please double check if the babel config file exists or turn off the `useBabelConfig` option in your ember-cli-build.js file."
        );
      }
      // If the babel config file is found, then pass the path into the options for the transpiler
      // parse and leverage the same.
      options = Object.assign({}, options, { configFile: babelConfig.config });
    } else {
      options = Object.assign({}, options, this.buildBabelOptions(config));
    }

    if (!shouldUseBabelConfigFile && this._shouldDoNothing(options)) {
      output = postDebugTree;
    } else {
      let BabelTranspiler = require('broccoli-babel-transpiler');
      let transpilationInput = postDebugTree;

      if (_shouldHandleTypeScript(config, this.parent)) {
        let Funnel = require('broccoli-funnel');
        let inputWithoutDeclarations = new Funnel(transpilationInput, { exclude: ['**/*.d.ts'] });
        transpilationInput = this._debugTree(inputWithoutDeclarations, `${description}:filtered-input`);
      }
      output = new BabelTranspiler(transpilationInput, options);
    }

    return this._debugTree(output, `${description}:output`);
  },

  setupPreprocessorRegistry(type, registry) {
    registry.add('js', {
      name: 'ember-cli-babel',
      ext: _getExtensions(this._getAddonOptions(), this.parent),
      toTree: (tree) => this.transpileTree(tree)
    });
  },

  _shouldIncludePolyfill() {
    let addonOptions = this._getAddonOptions();
    let customOptions = addonOptions['ember-cli-babel'];

    if (customOptions && 'includePolyfill' in customOptions) {
      return customOptions.includePolyfill === true;
    } else {
      return false;
    }
  },

  _importPolyfill(app) {
    let polyfillPath = 'vendor/babel-polyfill/polyfill.js';

    if (this.import) {  // support for ember-cli >= 2.7
      this.import(polyfillPath, { prepend: true });
    } else if (app.import) { // support ember-cli < 2.7
      app.import(polyfillPath, { prepend: true });
    } else {
      // eslint-disable-next-line no-console
      console.warn('Please run: ember install ember-cli-import-polyfill');
    }
  },

  _getHelperVersion() {
    if (!APP_BABEL_RUNTIME_VERSION.has(this.project)) {
      let checker = new VersionChecker(this.project);
      APP_BABEL_RUNTIME_VERSION.set(this.project, checker.for('@babel/runtime', 'npm').version);
    }

    return APP_BABEL_RUNTIME_VERSION.get(this.project);
  },

  _getHelpersPlugin() {
    return [
      [
        require.resolve('@babel/plugin-transform-runtime'),
        {
          version: this._getHelperVersion(),
          regenerator: false,
          useESModules: true
        }
      ]
    ]
  },

  treeForAddon() {
    // Helpers are a global config, so only the root application should bother
    // generating and including the file.
    let isRootBabel = this.parent === this.project;
    let shouldIncludeHelpers = isRootBabel && _shouldIncludeHelpers(this._getAppOptions(), this);

    if (!shouldIncludeHelpers) { return; }

    const path = require('path');
    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    const babelHelpersPath = path.dirname(require.resolve('@babel/runtime/package.json'));

    let babelHelpersTree = new Funnel(new UnwatchedDir(babelHelpersPath), {
      srcDir: 'helpers/esm',
      destDir: '@babel/runtime/helpers/esm'
    });

    return this.transpileTree(babelHelpersTree, {
      'ember-cli-babel': {
        // prevents the helpers from being double transpiled, and including themselves
        disablePresetEnv: true
      }
    });
  },

  treeForVendor() {
    if (!this._shouldIncludePolyfill()) return;

    const Funnel = require('broccoli-funnel');
    const UnwatchedDir = require('broccoli-source').UnwatchedDir;

    // Find babel-core's browser polyfill and use its directory as our vendor tree
    let polyfillDir = path.dirname(require.resolve('@babel/polyfill/dist/polyfill'));

    let polyfillTree = new Funnel(new UnwatchedDir(polyfillDir), {
      destDir: 'babel-polyfill'
    });

    return polyfillTree;
  },

  included: function(app) {
    this._super.included.apply(this, arguments);
    this.app = app;

    if (this._shouldIncludePolyfill()) {
      this._importPolyfill(app);
    }
  },

  isPluginRequired(pluginName) {
    let targets = this._getTargets();

    // if no targets are setup, assume that all plugins are required
    if (!targets) { return true; }

    const isPluginRequired = require('@babel/helper-compilation-targets').isRequired;
    return isPluginRequired(pluginName, targets);
  },

  _getAddonOptions() {
    let parentOptions = this.parent && this.parent.options;
    let appOptions = this.app && this.app.options;

    if (parentOptions) {
      let customAddonOptions = parentOptions['ember-cli-babel'];

      if (customAddonOptions && 'includeExternalHelpers' in customAddonOptions) {
        throw new Error('includeExternalHelpers is not supported in addon configurations, it is an app-wide configuration option');
      }
    }

    return parentOptions || appOptions || {};
  },

  _getAppOptions() {
    let app = findApp(this);

    return (app && app.options) || {};
  },

  _getTargets() {
    let targets = this.project && this.project.targets;

    let parser = require('@babel/helper-compilation-targets').default;
    if (typeof targets === 'object' && targets !== null) {
      // babel version 7.10.0 introduced a change that mutates the input:
      // https://github.com/babel/babel/pull/11500
      // copy the object to guard against it, otherwise subsequent calls to
      // _getTargets() will only have a mutated copy and lose all config from `config/targets.js`
      // in the host application.
      // PR to fix this upstream in babel: https://github.com/babel/babel/pull/11648
      const copy = clone(targets);
      return parser(copy);
    } else {
      return targets;
    }
  },

  /*
   * Used to discover if the addon's current configuration will compile modules
   * or not.
   *
   * @public
   * @method shouldCompileModules
   */
  shouldCompileModules() {
    return _shouldCompileModules(this._getAddonOptions(), this.project);
  },

  // detect if running babel would do nothing... and do nothing instead
  _shouldDoNothing(options) {
    return !options.sourceMaps && !options.plugins.length;
  }
};
<|endoftext|>


<commit_before>var ts = require('text-statistics')(),
    fs = require('fs')

var files = fs.readdirSync('./samples/')

files.forEach(function(file){
  console.log(file)
  var text = fs.readFileSync('./samples/'+file).toString()

  console.log('==================')
  console.log('Name: '+ file.split('.')[0])
  var syllables = ts.syllableCount(text)
  var grade = ts.fleschKincaidGradeLevel(text)
  console.log('grade: '+grade)
})
<commit_msg>added sentiment analysis<commit_after>var ts = require('text-statistics')(),
    fs = require('fs'),
    analyze = require('Sentimental').analyze

var files = fs.readdirSync('./samples/')

files.forEach(function(file){
  var text = fs.readFileSync('./samples/'+file).toString()

  console.log('==================')
  console.log('Name: '+ file.split('.')[0])
  var grade = ts.fleschKincaidGradeLevel(text)
  var sentiment = analyze(text).score
  console.log('grade: '+grade)
  console.log('sentiment: '+sentiment)
})
<|endoftext|>


<commit_before>#!/usr/bin/env node

// Write bytes received in stdin to a revved file path.
//
// Usage:
// ls *.png |rev-ls -r ./manifest.json
// find ./dist -type f -regextype posix-extended -regex ".*\.(png|svg)" |rev-ls -r ./dist/manifest.json

const fs = require('fs');
const path = require('path');
const commander = require('commander');
const revFile = require('rev-file');

const fileName = 'rev-data-[hash].file';
const revFileName = 'rev-manifest.json';

commander
  .option('-r, --manifest <filename>', 'Manifest file')
  .parse(process.argv);

/* Main */

process.stdin.resume();
process.stdin.setEncoding('utf8');

const timeID = setTimeout(() => {
  process.stdout.write('No data received from stdin!');
  commander.help();
  process.exit(1);
}, 2000);

var dataStdin = '';
process.stdin.on('data', function(data) {
  clearTimeout(timeID);
  dataStdin += data;
});

process.stdin.on('end', function() {
  if (dataStdin === '') {
    process.exit(1);
  }

  const files = dataStdin.split(/\s+/).filter(Boolean);
  const mapping = {};

  files.forEach((file) => {
    const fullPath = path.join(process.cwd(), file);
    const fullRevedPath = revFile.sync(fullPath);
    const revedFileOnly = path.relative(process.cwd(), fullRevedPath);

    mapping[file] = revedFileOnly;
    fs.createReadStream(file).pipe(fs.createWriteStream(fullRevedPath));

    process.stdout.write(`✔ ${file} -> ${revedFileOnly}\n`);
  });

  // build manifest
  if (commander.manifest) {
    const maniFullPath = path.join(process.cwd(), commander.manifest);
    fs.writeFileSync(maniFullPath, JSON.stringify(mapping, null, 2), 'utf8');
    process.stdout.write(`Write manifest into "${maniFullPath}".\n\n`);
  }
});
<commit_msg>Remove './' chars.<commit_after>#!/usr/bin/env node

// Write bytes received in stdin to a revved file path.
//
// Usage:
// ls *.png |rev-ls -r ./manifest.json
// find ./dist -type f -regextype posix-extended -regex ".*\.(png|svg)" |rev-ls -r ./dist/manifest.json

const fs = require('fs');
const path = require('path');
const commander = require('commander');
const revFile = require('rev-file');

const fileName = 'rev-data-[hash].file';
const revFileName = 'rev-manifest.json';

commander
  .option('-r, --manifest <filename>', 'Manifest file')
  .parse(process.argv);

/* Main */

process.stdin.resume();
process.stdin.setEncoding('utf8');

const timeID = setTimeout(() => {
  process.stdout.write('No data received from stdin!');
  commander.help();
  process.exit(1);
}, 2000);

var dataStdin = '';
process.stdin.on('data', function(data) {
  clearTimeout(timeID);
  dataStdin += data;
});

process.stdin.on('end', function() {
  if (dataStdin === '') {
    process.exit(1);
  }

  const files = dataStdin.split(/\s+/).filter(Boolean);
  const mapping = {};

  files.forEach((file) => {
    const fullPath = path.join(process.cwd(), file);
    const fullRevedPath = revFile.sync(fullPath);
    const revedFileOnly = path.relative(process.cwd(), fullRevedPath);

    // copy file
    fs.createReadStream(file).pipe(fs.createWriteStream(fullRevedPath));

    // add in mapping
    const removeDots = new RegExp(/^\.?\/?/);
    const file_ = file.replace(removeDots, '');
    const revedFileOnly_ = revedFileOnly.replace(removeDots, '');
    mapping[file_] = revedFileOnly_;

    process.stdout.write(`✔ ${file_} -> ${revedFileOnly_}\n`);
  });

  // build manifest
  if (commander.manifest) {
    const maniFullPath = path.join(process.cwd(), commander.manifest);
    fs.writeFileSync(maniFullPath, JSON.stringify(mapping, null, 2), 'utf8');
    process.stdout.write(`Write manifest into "${maniFullPath}".\n\n`);
  }
});
<|endoftext|>


<commit_before>var defined = require('defined');
var createDefaultStream = require('./lib/default_stream');
var Test = require('./lib/test');
var createResult = require('./lib/results');
var through = require('through');

var canEmitExit = typeof process !== 'undefined' && process
    && typeof process.on === 'function' && process.browser !== true
;
var canExit = typeof process !== 'undefined' && process
    && typeof process.exit === 'function'
;

var nextTick = typeof setImmediate !== 'undefined'
    ? setImmediate
    : process.nextTick
;

exports = module.exports = (function () {
    var harness;
    var lazyLoad = function () {
        return getHarness().apply(this, arguments);
    };

    lazyLoad.only = function () {
        return getHarness().only.apply(this, arguments);
    };

    lazyLoad.createStream = function (opts) {
        if (!opts) opts = {};
        if (!harness) {
            var output = through();
            getHarness({ stream: output, objectMode: opts.objectMode });
            return output;
        }
        return harness.createStream(opts);
    };

    lazyLoad.setNumbering = function () {
        return getHarness().setNumbering.apply(this, arguments);
    };

    lazyLoad.onPreTest = function () {
        return getHarness().onPreTest.apply(this, arguments);
    };

    lazyLoad.onFinish = function () {
        return getHarness().onFinish.apply(this, arguments);
    };

    lazyLoad.getHarness = getHarness

    return lazyLoad

    function getHarness (opts) {
        if (!opts) opts = {};
        opts.autoclose = !canEmitExit;
        if (!harness) harness = createExitHarness(opts);
        return harness;
    }
})();

function createExitHarness (conf) {
    if (!conf) conf = {};
    var harness = createHarness({
        autoclose: defined(conf.autoclose, false)
    });

    var stream = harness.createStream({ objectMode: conf.objectMode });
    var es = stream.pipe(conf.stream || createDefaultStream());
    if (canEmitExit) {
        es.on('error', function (err) { harness._exitCode = 1 });
    }

    var ended = false;
    stream.on('end', function () { ended = true });

    if (conf.exit === false) return harness;
    if (!canEmitExit || !canExit) return harness;

    var inErrorState = false;

    process.on('exit', function (code) {
        // let the process exit cleanly.
        if (code !== 0) {
            return
        }

        if (!ended) {
            var results = harness._results;
            var only = results._only;
            for (var i = 0; i < results.tests.length; i++) {
                var t = results.tests[i];
                if (only && t !== only) continue;
                t._exit();
            }
        }
        harness.close();
        process.exit(code || harness._exitCode);
    });

    return harness;
}

exports.createHarness = createHarness;
exports.Test = Test;
exports.test = exports; // tap compat
exports.test.skip = Test.skip;

var exitInterval;

function createHarness (conf_) {
    if (!conf_) conf_ = {};
    var results = createResult();
    if (conf_.autoclose !== false) {
        results.once('done', function () { results.close() });
    }

    var test = function (name, conf, cb) {
        var t = new Test(name, conf, cb);

        (function inspectCode (st) {
            st.on('test', function sub (st_) {
                inspectCode(st_);
            });
            st.on('result', function (r) {
                if (!r.ok && typeof r !== 'string') test._exitCode = 1
            });
        })(t);

        results.push(t);

        return t;
    };
    test._results = results;

    test.createStream = function (opts) {
        return results.createStream(opts);
    };

    test.setNumbering = function (testNumber) { // TBD: temporary
        results.setNumbering(testNumber);
    }

    test.onPreTest = function (cb) { // cb(title, unscheduled): title_or_null
        results.onPreTest = cb;
    };

    test.onFinish = function (cb) {
        results.on('done', cb);
    };

    var only = false;
    test.only = function () {
        if (only) throw new Error('there can only be one only test');
        only = true;
        var t = test.apply(null, arguments);
        results.only(t);
        return t;
    };
    test._exitCode = 0;

    test.close = function () { results.close() };

    return test;
}
<commit_msg>removed no-longer-necessary only-detection from test cleanup<commit_after>var defined = require('defined');
var createDefaultStream = require('./lib/default_stream');
var Test = require('./lib/test');
var createResult = require('./lib/results');
var through = require('through');

var canEmitExit = typeof process !== 'undefined' && process
    && typeof process.on === 'function' && process.browser !== true
;
var canExit = typeof process !== 'undefined' && process
    && typeof process.exit === 'function'
;

var nextTick = typeof setImmediate !== 'undefined'
    ? setImmediate
    : process.nextTick
;

exports = module.exports = (function () {
    var harness;
    var lazyLoad = function () {
        return getHarness().apply(this, arguments);
    };

    lazyLoad.only = function () {
        return getHarness().only.apply(this, arguments);
    };

    lazyLoad.createStream = function (opts) {
        if (!opts) opts = {};
        if (!harness) {
            var output = through();
            getHarness({ stream: output, objectMode: opts.objectMode });
            return output;
        }
        return harness.createStream(opts);
    };

    lazyLoad.setNumbering = function () {
        return getHarness().setNumbering.apply(this, arguments);
    };

    lazyLoad.onPreTest = function () {
        return getHarness().onPreTest.apply(this, arguments);
    };

    lazyLoad.onFinish = function () {
        return getHarness().onFinish.apply(this, arguments);
    };

    lazyLoad.getHarness = getHarness

    return lazyLoad

    function getHarness (opts) {
        if (!opts) opts = {};
        opts.autoclose = !canEmitExit;
        if (!harness) harness = createExitHarness(opts);
        return harness;
    }
})();

function createExitHarness (conf) {
    if (!conf) conf = {};
    var harness = createHarness({
        autoclose: defined(conf.autoclose, false)
    });

    var stream = harness.createStream({ objectMode: conf.objectMode });
    var es = stream.pipe(conf.stream || createDefaultStream());
    if (canEmitExit) {
        es.on('error', function (err) { harness._exitCode = 1 });
    }

    var ended = false;
    stream.on('end', function () { ended = true });

    if (conf.exit === false) return harness;
    if (!canEmitExit || !canExit) return harness;

    var inErrorState = false;

    process.on('exit', function (code) {
        // let the process exit cleanly.
        if (code !== 0) {
            return
        }

        if (!ended) {
            var results = harness._results;
            for (var i = 0; i < results.tests.length; i++) {
                results.tests[i]._exit();
            }
        }
        harness.close();
        process.exit(code || harness._exitCode);
    });

    return harness;
}

exports.createHarness = createHarness;
exports.Test = Test;
exports.test = exports; // tap compat
exports.test.skip = Test.skip;

var exitInterval;

function createHarness (conf_) {
    if (!conf_) conf_ = {};
    var results = createResult();
    if (conf_.autoclose !== false) {
        results.once('done', function () { results.close() });
    }

    var test = function (name, conf, cb) {
        var t = new Test(name, conf, cb);

        (function inspectCode (st) {
            st.on('test', function sub (st_) {
                inspectCode(st_);
            });
            st.on('result', function (r) {
                if (!r.ok && typeof r !== 'string') test._exitCode = 1
            });
        })(t);

        results.push(t);

        return t;
    };
    test._results = results;

    test.createStream = function (opts) {
        return results.createStream(opts);
    };

    test.setNumbering = function (testNumber) { // TBD: temporary
        results.setNumbering(testNumber);
    }

    test.onPreTest = function (cb) { // cb(title, unscheduled): title_or_null
        results.onPreTest = cb;
    };

    test.onFinish = function (cb) {
        results.on('done', cb);
    };

    var only = false;
    test.only = function () {
        if (only) throw new Error('there can only be one only test');
        only = true;
        var t = test.apply(null, arguments);
        results.only(t);
        return t;
    };
    test._exitCode = 0;

    test.close = function () { results.close() };

    return test;
}
<|endoftext|>


<commit_before>/*!
  JSON ABC | License: MIT.
*/

module.exports = {
  sort: sort,
  sortObj: sortObj,
  cleanJSON: cleanJSON
};

// Is a value an array?
function isArray (val) {
  return Object.prototype.toString.call(val) === '[object Array]';
}

// Is a value an Object?
function isPlainObject (val) {
  return Object.prototype.toString.call(val) === '[object Object]';
}

// Sorting Logic
function sortObj (un, noarray) {
  noarray = noarray || false;

  var or = {};

  if (isArray(un)) {
    // Sort or don't sort arrays
    if (noarray) {
      or = un;
    } else {
      or = un.sort();
    }

    or.forEach(function (v, i) {
      or[i] = sortObj(v);
    });
  } else if (isPlainObject(un)) {
    or = {};
    Object.keys(un).sort(function (a, b) {
      if (a.toLowerCase() < b.toLowerCase()) return -1;
      if (a.toLowerCase() > b.toLowerCase()) return 1;
      return 0;
    }).forEach(function (key) {
      or[key] = sortObj(un[key]);
    });
  } else {
    or = un;
  }

  return or;
}

// Remove trailing commas
function cleanJSON (input) {
  input = input.replace(/,[ \t\r\n]+}/g, '}');
  input = input.replace(/,[ \t\r\n]+\]/g, ']');
  return input;
}

// Sort the JSON (clean, parse, sort, stringify).
function sort (inputStr, noarray) {
  var output, obj, r;

  if (inputStr) {
    try {
      inputStr = cleanJSON(inputStr);
      obj = JSON.parse(inputStr);
      r = sortObj(obj, noarray);
      output = JSON.stringify(r, null, 4);
    } catch (ex) {
      console.error('jsonabc: Incorrect JSON object.', [], ex);
      throw ex;
    }
  }
  return output;
}

// End.
<commit_msg>Adds the missed noarray argument on the recursive cycle<commit_after>/*!
  JSON ABC | License: MIT.
*/

module.exports = {
  sort: sort,
  sortObj: sortObj,
  cleanJSON: cleanJSON
};

// Is a value an array?
function isArray (val) {
  return Object.prototype.toString.call(val) === '[object Array]';
}

// Is a value an Object?
function isPlainObject (val) {
  return Object.prototype.toString.call(val) === '[object Object]';
}

// Sorting Logic
function sortObj (un, noarray) {
  noarray = noarray || false;

  var or = {};

  if (isArray(un)) {
    // Sort or don't sort arrays
    if (noarray) {
      or = un;
    } else {
      or = un.sort();
    }

    or.forEach(function (v, i) {
      or[i] = sortObj(v, noarray);
    });
  } else if (isPlainObject(un)) {
    or = {};
    Object.keys(un).sort(function (a, b) {
      if (a.toLowerCase() < b.toLowerCase()) return -1;
      if (a.toLowerCase() > b.toLowerCase()) return 1;
      return 0;
    }).forEach(function (key) {
      or[key] = sortObj(un[key], noarray);
    });
  } else {
    or = un;
  }

  return or;
}

// Remove trailing commas
function cleanJSON (input) {
  input = input.replace(/,[ \t\r\n]+}/g, '}');
  input = input.replace(/,[ \t\r\n]+\]/g, ']');
  return input;
}

// Sort the JSON (clean, parse, sort, stringify).
function sort (inputStr, noarray) {
  var output, obj, r;

  if (inputStr) {
    try {
      inputStr = cleanJSON(inputStr);
      obj = JSON.parse(inputStr);
      r = sortObj(obj, noarray);
      output = JSON.stringify(r, null, 4);
    } catch (ex) {
      console.error('jsonabc: Incorrect JSON object.', [], ex);
      throw ex;
    }
  }
  return output;
}

// End.
<|endoftext|>


<commit_before>// http://left-shark.github.io/left-shark/left-shark.gif
(function() {
    var allElements = document.querySelectorAll('*');

    requestAnimationFrame(function loop(t) {
        // console.log(t);

        // requestAnimationFrame(loop);
    });

    var html = ('
' +
        '' +
        '' +
    '
');

    var container = document.createElement('div');
    container.innerHTML = html;
    document.body.appendChild(container);

    return true;
}());
<commit_msg>Animate background<commit_after>// http://left-shark.github.io/left-shark/left-shark.gif
(function() {
    var allElements = document.querySelectorAll('*');

    requestAnimationFrame(function loop(t) {
        document.body.style.background = 'rgba(0, 0, 255, ' + (t%1000)/1000 + ')';

        requestAnimationFrame(loop);
    });

    var html = ('
' +
        '' +
        '' +
    '
');

    var container = document.createElement('div');
    container.innerHTML = html;
    document.body.appendChild(container);

    return true;
}());
<|endoftext|>


<commit_before>var htmlparser = require("htmlparser");
var Radixer = require("radixer");
var radixer = new Radixer('abcdefghijklmnopqrstuvwxyz');
//refer to: http://code.tutsplus.com/articles/data-structures-with-javascript-tree--cms-23393
function traverseBF (nodes, root, callback) {
    var queue = [];
    queue.push({ node: nodes, parent: root });
    currentNode = queue.shift();
    while (currentNode) {
        var parent = callback(currentNode.node, currentNode.parent);
        if (currentNode.node.children) {
            for (var i = 0, length = currentNode.node.children.length; i < length; i++) {
                queue.push({ node: currentNode.node.children[i], parent: parent });
            }
        }
        currentNode = queue.shift();
    }

}

function createElement (node, parent, fnName) {
    let label = null
    let entry = null
    let exit = null
    let exit2 = null
    // create element
    let dom = ''
    dom += 'var ' + fnName + '=document.createElementNS("http://www.w3.org/2000/svg","' + node.name + '");'
    // only restore last one
    for (var i in node.attribs) {
        var attr = node.attribs[i]
        switch (i) {
            case 'data-label':
                label = attr
                break
            case 'data-entry':
                entry = attr
                break
            case 'data-exit':
                exit = attr
                break
            default:
                dom += fnName + '.setAttribute("' + i + '","' + attr + '");'
        }
    }
    // append to parent
    dom += parent + '.appendChild(' + fnName + ');'
    return {
        dom: dom,
        label: label,
        entry: entry,
        exit: exit,
    }
}
module.exports = function (source) {
    var handler = new htmlparser.DefaultHandler(function (error, dom) {
        if (error) {
        	throw new Error('Can`t parse svg.')
        } else {
        	// TODO: tell some to user
        }
    });
    var parser = new htmlparser.Parser(handler);
    parser.parseComplete(source);
    var domAST = handler.dom
    var rootSvg = domAST.filter(function(_) {
        return _.name === 'svg'
    })
    if (rootSvg.length !== 1) {
        throw new Error('Must only contain one svg, now find:' + rootSvg.length)
    }
    // function name, it should be increate when Declare another function
    var fnName = 0;
    var root = radixer.numberToString(fnName);
    var dom = 'var ' + root + '=document.createElementNS("http://www.w3.org/2000/svg","g");'
    // restore attr
    var entries = []
    var exits = []
    var labels = []
    fnName++;
    traverseBF(rootSvg[0], root, function (node, parent) {
        var name = radixer.numberToString(fnName);
        if (parent && node.type !== 'text') {
            el = createElement(node, parent, name);
            if (el.label) {
                labels.push('{el:' + name + ',attr:' + el.label + '}')
            }
            if (el.entry) {
                entries.push('{el:' + name + ',attr:' + el.entry + '}')
            }
            if (el.exit) {
                exits.push('{el:' + name + ',attr:' + el.exit + '}')
            }
            dom += el.dom;
            fnName++;
        }
        return name
    });
    return 'module.exports = function(){' + dom + 'return {' +
        '"root": ' + root + ',' +
        '"entries": [' + entries.join(',') + '],' +
        '"exits": [' + exits.join(',') + '],' +
        '"labels": [' + labels.join(',') + ']' +
        '}}';
};<commit_msg>[bug] string type attr can`t parse successfully<commit_after>var htmlparser = require("htmlparser");
var Radixer = require("radixer");
var radixer = new Radixer('abcdefghijklmnopqrstuvwxyz');
//refer to: http://code.tutsplus.com/articles/data-structures-with-javascript-tree--cms-23393
function traverseBF (nodes, root, callback) {
    var queue = [];
    queue.push({ node: nodes, parent: root });
    currentNode = queue.shift();
    while (currentNode) {
        var parent = callback(currentNode.node, currentNode.parent);
        if (currentNode.node.children) {
            for (var i = 0, length = currentNode.node.children.length; i < length; i++) {
                queue.push({ node: currentNode.node.children[i], parent: parent });
            }
        }
        currentNode = queue.shift();
    }

}

function createElement (node, parent, fnName) {
    let label = null
    let entry = null
    let exit = null
    let exit2 = null
    // create element
    let dom = ''
    dom += 'var ' + fnName + '=document.createElementNS("http://www.w3.org/2000/svg","' + node.name + '");'
    // only restore last one
    for (var i in node.attribs) {
        var attr = node.attribs[i]
        switch (i) {
            case 'data-label':
                label = attr
                break
            case 'data-entry':
                entry = attr
                break
            case 'data-exit':
                exit = attr
                break
            default:
                dom += fnName + '.setAttribute("' + i + '","' + attr + '");'
        }
    }
    // append to parent
    dom += parent + '.appendChild(' + fnName + ');'
    return {
        dom: dom,
        label: label,
        entry: entry,
        exit: exit,
    }
}
module.exports = function (source) {
    var handler = new htmlparser.DefaultHandler(function (error, dom) {
        if (error) {
        	throw new Error('Can`t parse svg.')
        } else {
        	// TODO: tell some to user
        }
    });
    var parser = new htmlparser.Parser(handler);
    parser.parseComplete(source);
    var domAST = handler.dom
    var rootSvg = domAST.filter(function(_) {
        return _.name === 'svg'
    })
    if (rootSvg.length !== 1) {
        throw new Error('Must only contain one svg, now find:' + rootSvg.length)
    }
    // function name, it should be increate when Declare another function
    var fnName = 0;
    var root = radixer.numberToString(fnName);
    var dom = 'var ' + root + '=document.createElementNS("http://www.w3.org/2000/svg","g");'
    // restore attr
    var entries = []
    var exits = []
    var labels = []
    fnName++;
    traverseBF(rootSvg[0], root, function (node, parent) {
        var name = radixer.numberToString(fnName);
        if (parent && node.type !== 'text') {
            el = createElement(node, parent, name);
            if (el.label) {
                labels.push('{el:' + name + ',attr:"' + el.label + '"}')
            }
            if (el.entry) {
                entries.push('{el:' + name + ',attr:"' + el.entry + '"}')
            }
            if (el.exit) {
                exits.push('{el:' + name + ',attr:"' + el.exit + '"}')
            }
            dom += el.dom;
            fnName++;
        }
        return name
    });
    return 'module.exports = function(){' + dom + 'return {' +
        '"root": ' + root + ',' +
        '"entries": [' + entries.join(',') + '],' +
        '"exits": [' + exits.join(',') + '],' +
        '"labels": [' + labels.join(',') + ']' +
        '}}';
};
<|endoftext|>


<commit_before>// Dependencies
var ReferenceParser = require("bible-reference-parser");

// Constants
const ALL_VERSES = require("./all-verses.json");
const ALL_BOOKS = require("./all-books.json");

/**
 * find
 * This function searches returns the objects from an array
 * that contains objects.
 *
 * @name find
 * @function
 * @param {Array} array The data array where the documents will be searched.
 * @param {Object} query A Mongo-like filter.
 * @return {Array} Documents that match the query.
 */
function find(array, query) {

    var col = array
      , res = []
      ;

    if (!col || !col.length || col.constructor !== Array) {
        return res;
    }

    itemsToFindForLoop:

    for (var i = 0; i < col.length; ++i) {
        var cItem = col[i];
        for (var f in query) {
            var fValue = query[f];
            if (typeof cItem[f] === "string" && typeof fValue === "string") {
                // a filter doesn't match to the query
                if (cItem[f] !== fValue) continue itemsToFindForLoop;
            } else if (typeof cItem[f] === "string" &&  fValue && fValue.constructor === Array) {
                // a filter doesn't match to the query
                if (fValue.indexOf(cItem[f]) === -1) continue itemsToFindForLoop;
            } else if (typeof cItem[f] === "string" &&  fValue && fValue.constructor === RegExp) {
                // a filter doesn't match to the query
                if (!fValue.test(cItem[f])) continue itemsToFindForLoop;
            }
        }

        res.push(cItem);
    }

    return res;
}

// Constructor
var RomanianBible = module.exports = {};

/**
 * getVerse
 * Fetches the verses that were requested in reference
 *
 *  e.g. Geneza 1:1    - returns one verse
 *    or Geneza 1:1,2  - returns two verses (1 and 2)
 *    or Geneza 1:1-10 - returns the verses 1 - 10
 *    or Geneza 1      - returns the whole chapter
 *
 * @name getVerse
 * @function
 * @param {String} reference Bible verse reference
 * @param {Function} callback The callback function
 * @return
 */
RomanianBible.getVerse = function (reference, callback) {

    // Parse reference
    if (typeof reference === "string") {
        var parsed = ReferenceParser(reference);
        if (!parsed) { return callback("Cannot parse the input."); }

        // Build the query
        var query = {
            bookname:   parsed.book
          , chapter:    parsed.chapter
          , verse:      parsed.verses
        };

        return RomanianBible.getVerse.call(this, query, callback);
    }

    // "ALL" is special
    if (reference.verse === "ALL") {
        delete query.verse;
    }

    // Send the response
    callback (null, find(ALL_VERSES, reference));
};

/**
 * getBooks
 * Returns an array with Bible books in Romanian
 *
 * @name getBooks
 * @function
 * @param {Function} callback The callback function
 * @return
 */
RomanianBible.getBooks = function (callback) {
    var books = [];
    for (var i = 0; i < ALL_BOOKS.length; ++i) {
        books.push(ALL_BOOKS[i].book);
    }
    callback(null, books);
};
<commit_msg>Fixed query for fetching verses<commit_after>// Dependencies
var ReferenceParser = require("bible-reference-parser");

// Constants
const ALL_VERSES = require("./all-verses.json");
const ALL_BOOKS = require("./all-books.json");

/**
 * find
 * This function searches returns the objects from an array
 * that contains objects.
 *
 * @name find
 * @function
 * @param {Array} array The data array where the documents will be searched.
 * @param {Object} query A Mongo-like filter.
 * @return {Array} Documents that match the query.
 */
function find(array, query) {

    var col = array
      , res = []
      ;

    if (!col || !col.length || col.constructor !== Array) {
        return res;
    }

    itemsToFindForLoop:

    for (var i = 0; i < col.length; ++i) {
        var cItem = col[i];
        for (var f in query) {
            var fValue = query[f];
            if (typeof cItem[f] === "string" && typeof fValue === "string") {
                // a filter doesn't match to the query
                if (cItem[f] !== fValue) continue itemsToFindForLoop;
            } else if (typeof cItem[f] === "string" &&  fValue && fValue.constructor === Array) {
                // a filter doesn't match to the query
                if (fValue.indexOf(cItem[f]) === -1) continue itemsToFindForLoop;
            } else if (typeof cItem[f] === "string" &&  fValue && fValue.constructor === RegExp) {
                // a filter doesn't match to the query
                if (!fValue.test(cItem[f])) continue itemsToFindForLoop;
            }
        }

        res.push(cItem);
    }

    return res;
}

// Constructor
var RomanianBible = module.exports = {};

/**
 * getVerse
 * Fetches the verses that were requested in reference
 *
 *  e.g. Geneza 1:1    - returns one verse
 *    or Geneza 1:1,2  - returns two verses (1 and 2)
 *    or Geneza 1:1-10 - returns the verses 1 - 10
 *    or Geneza 1      - returns the whole chapter
 *
 * @name getVerse
 * @function
 * @param {String} reference Bible verse reference
 * @param {Function} callback The callback function
 * @return
 */
RomanianBible.getVerse = function (reference, callback) {

    // Parse reference
    if (typeof reference === "string") {
        var parsed = ReferenceParser(reference);
        if (!parsed) { return callback("Cannot parse the input."); }

        // Build the query
        var query = {
            bookname:   parsed.book
          , chapter:    parsed.chapter
          , verse:      parsed.verses
        };

        return RomanianBible.getVerse.call(this, query, callback);
    }

    // Build the query
    var query = {
        bookname:   reference.bookname || reference.book
      , chapter:    reference.chapter
      , verse:      reference.verse || reference.verses
    };

    // "ALL" is special
    if (query.verse === "ALL") {
        delete query.verse;
    }

    var result = find(ALL_VERSES, query)

    // Send the response
    callback (null, result);
};

/**
 * getBooks
 * Returns an array with Bible books in Romanian
 *
 * @name getBooks
 * @function
 * @param {Function} callback The callback function
 * @return
 */
RomanianBible.getBooks = function (callback) {
    var books = [];
    for (var i = 0; i < ALL_BOOKS.length; ++i) {
        books.push(ALL_BOOKS[i].book);
    }
    callback(null, books);
};
<|endoftext|>


<commit_before>'use strict';

const path		= require('path');
const app		= require('koa')();
const swig		= require('koa-swig');
const body		= require('koa-buddy');
const router	= require('koa-router')();

function findChild(name, children) {
	for (let child of children) {
		if (child.name === name) {
			return child;
		}
	}
}

// Microsoft Outlook / Apple Mail
router.post('/Autodiscover/Autodiscover.xml', function *autodiscover() {
	this.set('Content-Type', 'application/xml');
	console.log(this.request.body);

	const request	= findChild('Request', this.request.body.root.children);
	const schema	= findChild('AcceptableResponseSchema', request.children);
	const email		= findChild('EMailAddress', request.children).content;
	const username	= email.split('@')[0];
	const domain	= email.split('@')[1];

	yield this.render('autodiscover', {
		schema: schema.content,
		email,
		username,
		domain
	});
});

// Thunderbird
router.get('/mail/config-v1.1.xml', function *autoconfig() {
	this.set('Content-Type', 'application/xml');
	yield this.render('autoconfig');
});

// iOS / Apple Mail (/email.mobileconfig?email=username@domain.com)
router.get('/email.mobileconfig', function *autoconfig() {
	const email = this.request.email;

	if (!email || !~email.indexOf('@')) {
		this.status = 400;

		return;
	}

	const domain	= email.split('@').pop();
	const filename	= `${domain}.mobileconfig`;

	this.set('Content-Type', 'application/x-apple-aspen-config; chatset=utf-8');
	this.set('Content-Disposition', `attachment; filename="${filename}"`);

	yield this.render('mobileconfig', {
		email,
		domain
	});
});

app.context.render = swig({
	root: path.join(__dirname, 'views'),
	autoescape: true,
	cache: 'memory',
	ext: 'xml'
});

app.use(function *fixContentType(next) {
	if (this.request.headers['content-type'] === 'text/xml') {
		this.request.headers['content-type'] = 'application/xml';
	}

	yield next;
});

app.use(body());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(process.env.PORT || 8000);
<commit_msg>Log headers/body for testing<commit_after>'use strict';

const path		= require('path');
const app		= require('koa')();
const swig		= require('koa-swig');
const body		= require('koa-buddy');
const router	= require('koa-router')();

function findChild(name, children) {
	for (let child of children) {
		if (child.name === name) {
			return child;
		}
	}
}

// Microsoft Outlook / Apple Mail
router.post('/Autodiscover/Autodiscover.xml', function *autodiscover() {
	this.set('Content-Type', 'application/xml');
	console.log(this.request.headers, this.request.body);

	const request	= findChild('Request', this.request.body.root.children);
	const schema	= findChild('AcceptableResponseSchema', request.children);
	const email		= findChild('EMailAddress', request.children).content;
	const username	= email.split('@')[0];
	const domain	= email.split('@')[1];

	yield this.render('autodiscover', {
		schema: schema.content,
		email,
		username,
		domain
	});
});

// Thunderbird
router.get('/mail/config-v1.1.xml', function *autoconfig() {
	this.set('Content-Type', 'application/xml');
	yield this.render('autoconfig');
});

// iOS / Apple Mail (/email.mobileconfig?email=username@domain.com)
router.get('/email.mobileconfig', function *autoconfig() {
	const email = this.request.email;

	if (!email || !~email.indexOf('@')) {
		this.status = 400;

		return;
	}

	const domain	= email.split('@').pop();
	const filename	= `${domain}.mobileconfig`;

	this.set('Content-Type', 'application/x-apple-aspen-config; chatset=utf-8');
	this.set('Content-Disposition', `attachment; filename="${filename}"`);

	yield this.render('mobileconfig', {
		email,
		domain
	});
});

app.context.render = swig({
	root: path.join(__dirname, 'views'),
	autoescape: true,
	cache: 'memory',
	ext: 'xml'
});

app.use(function *fixContentType(next) {
	if (this.request.headers['content-type'] === 'text/xml') {
		this.request.headers['content-type'] = 'application/xml';
	}

	yield next;
});

app.use(body());
app.use(router.routes());
app.use(router.allowedMethods());

app.listen(process.env.PORT || 8000);
<|endoftext|>


<commit_before>/** @module bigwheel */

var vm = require( 'bw-vm' ),
	viewmediator = require( 'bw-viewmediator' ),
	router = require( 'bw-router' ),
	on = require( 'dom-event' );
/**
 * When instantiating bigwheel you must pass in a setup function.
 *
 * In this function you may do any preparation that must be done for your
 * application such as creating a global Canvas element or something else.
 *
 * The setup function must either return a settings object for bigwheel or
 * this function must receive a callback which you will call with the settings
 * object. Furthermore you can pass back a promise from this settings function
 * which will receive the settings object.
 *
 * The following documents what can be passed in the settings object:
 * ```javascript
 * {
 * 	///// REQUIRED /////
 *
 * 	// routes defines all the routes for your website it can also define a
 * 	// 404 section which will be opened if the route is incorrect
 *  routes: {
 *
 * 		'/': someSection,
 * 		'/someOther': someOtherSection,
 * 		'404': sectionFourOhFour
 *  },
 *
 *  ///// OPTIONAL /////
 *  initSection: preSection, // this could be a section that is run always
 *  						 // before routes are even evaluated. This is
 *  						 // usefulf for site preloaders or landing pages
 *  						 // such as age verification (something the user
 *  						 // must see)
 *
 * 	autoResize: true, // by default this value is true. When this value is
 * 					  // true a resize listener is added to the window
 * 					  // whenever the window changes size it's width and
 * 					  // height is passed to all instantiated sections
 * 	postHash: '#!', // this string is appended before the route.
 * 					// by default it's value is '#!'
 * }
 * ```
 *
 * @class bigwheel
 * @param  {Function} settingsFunc This settings function will be used to
 * initialize bigwheel.
 */
function bigwheel( settingsFunc ) {

	if( !( this instanceof bigwheel ) )
		return new bigwheel( settingsFunc );

	this.settingsFunc = settingsFunc;
};

bigwheel.prototype = {

	/**
	 * init must be called to start the framework. This was done to allow for
	 * a developer to have full control of when bigwheel starts doing it's thing.
	 */
	init: function() {

		var onSettingComplete = function( settings ) {

			var s = this.s = settings;

			if( s === undefined )
				throw new Error( 'Your settings function must return a settings Object' );

			if( s.routes === undefined )
				throw new Error( 'Your settings object must define routes' );

			s.autoResize = s.autoResize === undefined ? true : s.autoResize;

			// setup the router
			this.onRouteCallBack = settings.onRoute;
			settings.routes.onRoute = this.show.bind( this );
			this.router = router( settings.routes );

			// setup the view manager
			this.vm = vm( this.s );

			if( s.autoResize ) {

				on( window, 'resize', this.onResize.bind( this ) );

				this.onResize();
			}

			if( s.initSection )
				this.show( s.initSection.bind( undefined, this.router.init.bind( this.router ) ) );
			else
				this.router.init();
		}.bind( this );

		var rVal = this.settingsFunc( onSettingComplete );

		if( rVal && rVal.then )
			rVal.then( onSettingComplete );
		else if( rVal && rVal.routes )
			onSettingComplete( rVal );
	},

	/**
	 * go can be called to go to another section.
	 *
	 * @param  {String} to This is the route you want to go to.
	 *
	 * @example
	 * ```javascript
	 * framework.go( '/landing' );
	 * ```
	 */
	go: function( to ) {

		this.router.go( to );
	},

	show: function( content, data ) {

		// this is the original router callback passed in
		if( this.onRouteCallBack )
			this.onRouteCallBack( content, data );

		// check if content is an array or function or object
		if( Array.isArray( content ) ) {

			var contents = [];

			for( var i = 0, len = content.length; i < len; i++ ) {

				if( typeof content[ i ] == 'object' )
					contents[ i ] = content[ i ];
				else if( typeof content[ i ] == 'function' )
					contents[ i ] = new content[ i ];
			}

			this.doShow( viewmediator.apply( undefined, contents ), data );
		} else if( typeof content == 'object' ) {

			this.doShow( content, data );
		} else if( typeof content == 'function' ) {

			this.doShow( new content, data );
		}
	},

	/**
	 * Resize can be called at any time. The values passed in for
	 * width and height will be passed to the currently instantiated
	 * sections.
	 *
	 * If `autoResize` was not passed in or it was true then resize
	 * will automatically be called when the window of the browser
	 * resizes.
	 *
	 * @param  {Number} w width value you'd like to pass to the sections
	 * @param  {Number} h height value you'd like to pass to the sections
	 */
	resize: function( w, h ) {

		this.vm.resize( w, h );
	},

	doShow: function( content, data ) {

		this.vm.show( content, data );
	},

	onResize: function() {

		this.resize( window.innerWidth, window.innerHeight );
	}
};

module.exports = bigwheel;<commit_msg>- Disabled going to same route<commit_after>/** @module bigwheel */

var vm = require( 'bw-vm' ),
	viewmediator = require( 'bw-viewmediator' ),
	router = require( 'bw-router' ),
	on = require( 'dom-event' );
/**
 * When instantiating bigwheel you must pass in a setup function.
 *
 * In this function you may do any preparation that must be done for your
 * application such as creating a global Canvas element or something else.
 *
 * The setup function must either return a settings object for bigwheel or
 * this function must receive a callback which you will call with the settings
 * object. Furthermore you can pass back a promise from this settings function
 * which will receive the settings object.
 *
 * The following documents what can be passed in the settings object:
 * ```javascript
 * {
 * 	///// REQUIRED /////
 *
 * 	// routes defines all the routes for your website it can also define a
 * 	// 404 section which will be opened if the route is incorrect
 *  routes: {
 *
 * 		'/': someSection,
 * 		'/someOther': someOtherSection,
 * 		'404': sectionFourOhFour
 *  },
 *
 *  ///// OPTIONAL /////
 *  initSection: preSection, // this could be a section that is run always
 *  						 // before routes are even evaluated. This is
 *  						 // usefulf for site preloaders or landing pages
 *  						 // such as age verification (something the user
 *  						 // must see)
 *
 * 	autoResize: true, // by default this value is true. When this value is
 * 					  // true a resize listener is added to the window
 * 					  // whenever the window changes size it's width and
 * 					  // height is passed to all instantiated sections
 * 	postHash: '#!', // this string is appended before the route.
 * 					// by default it's value is '#!'
 * }
 * ```
 *
 * @class bigwheel
 * @param  {Function} settingsFunc This settings function will be used to
 * initialize bigwheel.
 */
function bigwheel( settingsFunc ) {

	if( !( this instanceof bigwheel ) )
		return new bigwheel( settingsFunc );

	this.settingsFunc = settingsFunc;
};

bigwheel.prototype = {

	/**
	 * init must be called to start the framework. This was done to allow for
	 * a developer to have full control of when bigwheel starts doing it's thing.
	 */
	init: function() {

		var onSettingComplete = function( settings ) {

			var s = this.s = settings;

			if( s === undefined )
				throw new Error( 'Your settings function must return a settings Object' );

			if( s.routes === undefined )
				throw new Error( 'Your settings object must define routes' );

			s.autoResize = s.autoResize === undefined ? true : s.autoResize;

			// setup the router
			this.onRouteCallBack = settings.onRoute;
			settings.routes.onRoute = this.show.bind( this );
			this.router = router( settings.routes );

			// setup the view manager
			this.vm = vm( this.s );

			if( s.autoResize ) {

				on( window, 'resize', this.onResize.bind( this ) );

				this.onResize();
			}

			if( s.initSection )
				this.show( s.initSection.bind( undefined, this.router.init.bind( this.router ) ) );
			else
				this.router.init();
		}.bind( this );

		var rVal = this.settingsFunc( onSettingComplete );

		if( rVal && rVal.then )
			rVal.then( onSettingComplete );
		else if( rVal && rVal.routes )
			onSettingComplete( rVal );
	},

	/**
	 * go can be called to go to another section.
	 *
	 * @param  {String} to This is the route you want to go to.
	 *
	 * @example
	 * ```javascript
	 * framework.go( '/landing' );
	 * ```
	 */
	go: function( to ) {

		this.router.go( to );
	},

	show: function( content, data ) {

		if (data && data.route==this.lastRoute) return;
		// this is the original router callback passed in
		if( this.onRouteCallBack )
			this.onRouteCallBack( content, data );

		// check if content is an array or function or object
		if( Array.isArray( content ) ) {

			var contents = [];

			for( var i = 0, len = content.length; i < len; i++ ) {

				if( typeof content[ i ] == 'object' )
					contents[ i ] = content[ i ];
				else if( typeof content[ i ] == 'function' )
					contents[ i ] = new content[ i ];
			}

			this.doShow( viewmediator.apply( undefined, contents ), data );
		} else if( typeof content == 'object' ) {

			this.doShow( content, data );
		} else if( typeof content == 'function' ) {

			this.doShow( new content, data );
		}

		this.lastRoute = (data) ? data.route : undefined;
	},

	/**
	 * Resize can be called at any time. The values passed in for
	 * width and height will be passed to the currently instantiated
	 * sections.
	 *
	 * If `autoResize` was not passed in or it was true then resize
	 * will automatically be called when the window of the browser
	 * resizes.
	 *
	 * @param  {Number} w width value you'd like to pass to the sections
	 * @param  {Number} h height value you'd like to pass to the sections
	 */
	resize: function( w, h ) {

		this.vm.resize( w, h );
	},

	doShow: function( content, data ) {

		this.vm.show( content, data );
	},

	onResize: function() {

		this.resize( window.innerWidth, window.innerHeight );
	}
};

module.exports = bigwheel;<|endoftext|>