<commit_before>require('regenerator/runtime');
require('serviceworker-cache-polyfill');

var semver = require('semver');
var keyValueStore = require('../shared/db/keyValueStore');
var constants = require('../shared/util/constants');
var numSpriteCssFiles = constants.numSpriteCssFiles;
var range = require('lodash/utility/range');

// Using jake archibald's service worker "semver" style here
// Pattern here is "a.b.c"
// a: version-isolated change, don't let both versions run together
// b: new feature
// c: bug fix
var version = '1.0.5';

var staticContent = [
  '/',
  // TODO: shouldn't have to download twice, but this works considering manifest.json
  '/index.html?launcher=true',
  '/js/worker.js',
  '/js/main.js',
  '/manifest.json',
  '/favicon.ico',
  '/img/icon-48.png',
  '/img/icon-96.png',
  '/img/icon-144.png',
  '/img/icon-192.png'
];

if (process.env.NODE_ENV === 'development') {
  staticContent = staticContent.concat([
    '/vendor/mui.js',
    '/vendor/mui.css',
    '/css/style.css',
    '/js/critical.js',
    '/svg/search.svg',
    '/svg/search-active.svg',
    '/svg/ic_arrow_back_36px.svg'
  ]);
}

var webpContent = range(numSpriteCssFiles).map(i => `/css/sprites-webp-${i + 1}.css`);
var nonWebpContent = range(numSpriteCssFiles).map(i => `/css/sprites-${i + 1}.css`);

self.addEventListener('install', function install (event) {
  console.log('install');
  event.waitUntil((async () => {
    var activeVersionPromise = keyValueStore.get('active-version');
    var cache = await caches.open('pokedex-static-' + version);

    await cache.addAll(staticContent);

    var activeVersion = await activeVersionPromise;

    if (!activeVersion ||
        semver.parse(activeVersion).major === semver.parse(version).major) {
      // wrapping in an if while Chrome 40 is still around.
      if (self.skipWaiting) {
        self.skipWaiting();
      }
    }
  })());
});

self.onmessage = async function onmessage (event) {
  console.log('got message', event.data);
  if (event.data.type === 'supportsWebp') {
    var supportsWebp = event.data.value;
    var cache = await caches.open('pokedex-static-' + version);
    await cache.addAll(supportsWebp ? webpContent : nonWebpContent);
  }
};

var expectedCaches = [
  'pokedex-static-' + version
];

self.addEventListener('activate', function(event) {
  console.log('activate');
  event.waitUntil((async () => {
    // activate right now
    await self.clients.claim();
    // remove caches beginning "svgomg-" that aren't in
    // expectedCaches
    var cacheNames = await caches.keys();
    console.log('cacheNames', cacheNames);
    for (var cacheName of cacheNames) {
      if (!/^pokedex-static-/.test(cacheName)) {
        continue;
      }
      if (expectedCaches.indexOf(cacheName) == -1) {
        console.log('deleting', cacheName);
        await caches.delete(cacheName);
      }
    }

    await keyValueStore.set('active-version', version);
  })());
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(r => r || fetch(event.request))
  );
});<commit_msg>update service worker<commit_after>require('regenerator/runtime');
require('serviceworker-cache-polyfill');

var semver = require('semver');
var keyValueStore = require('../shared/db/keyValueStore');
var constants = require('../shared/util/constants');
var numSpriteCssFiles = constants.numSpriteCssFiles;
var range = require('lodash/utility/range');

// Using jake archibald's service worker "semver" style here
// Pattern here is "a.b.c"
// a: version-isolated change, don't let both versions run together
// b: new feature
// c: bug fix
var version = '1.0.6';

var staticContent = [
  '/',
  // TODO: shouldn't have to download twice, but this works considering manifest.json
  '/index.html?launcher=true',
  '/js/worker.js',
  '/js/main.js',
  '/manifest.json',
  '/favicon.ico',
  '/img/icon-48.png',
  '/img/icon-96.png',
  '/img/icon-144.png',
  '/img/icon-192.png'
];

if (process.env.NODE_ENV === 'development') {
  staticContent = staticContent.concat([
    '/vendor/mui.js',
    '/vendor/mui.css',
    '/css/style.css',
    '/js/critical.js',
    '/svg/search.svg',
    '/svg/search-active.svg',
    '/svg/ic_arrow_back_36px.svg'
  ]);
}

var webpContent = range(numSpriteCssFiles).map(i => `/css/sprites-webp-${i + 1}.css`);
var nonWebpContent = range(numSpriteCssFiles).map(i => `/css/sprites-${i + 1}.css`);

self.addEventListener('install', function install (event) {
  console.log('install');
  event.waitUntil((async () => {
    var activeVersionPromise = keyValueStore.get('active-version');
    var cache = await caches.open('pokedex-static-' + version);

    await cache.addAll(staticContent);

    var activeVersion = await activeVersionPromise;

    if (!activeVersion ||
        semver.parse(activeVersion).major === semver.parse(version).major) {
      // wrapping in an if while Chrome 40 is still around.
      if (self.skipWaiting) {
        self.skipWaiting();
      }
    }
  })());
});

self.onmessage = async function onmessage (event) {
  console.log('got message', event.data);
  if (event.data.type === 'supportsWebp') {
    var supportsWebp = event.data.value;
    var cache = await caches.open('pokedex-static-' + version);
    await cache.addAll(supportsWebp ? webpContent : nonWebpContent);
  }
};

var expectedCaches = [
  'pokedex-static-' + version
];

self.addEventListener('activate', function(event) {
  console.log('activate');
  event.waitUntil((async () => {
    // activate right now
    await self.clients.claim();
    // remove caches beginning "svgomg-" that aren't in
    // expectedCaches
    var cacheNames = await caches.keys();
    console.log('cacheNames', cacheNames);
    for (var cacheName of cacheNames) {
      if (!/^pokedex-static-/.test(cacheName)) {
        continue;
      }
      if (expectedCaches.indexOf(cacheName) == -1) {
        console.log('deleting', cacheName);
        await caches.delete(cacheName);
      }
    }

    await keyValueStore.set('active-version', version);
  })());
});

self.addEventListener('fetch', function(event) {
  event.respondWith(
    caches.match(event.request).then(r => r || fetch(event.request))
  );
});<|endoftext|>


<commit_before>'use strict'

var should = require("should");
var fs = require("fs-extra");
var Path = require("path");
var grunt = require("grunt");
var testFilePrefix = "test";
var testFileExtname = ".txt";
var testFileName = testFilePrefix+testFileExtname;
var testOutputPath = "./test/env/output";
var rotatedFilePattern = new RegExp("^test[.][0-9]{1,}[.]txt$");
var sandboxPath = "./test/env";

function createTestFile(done) {
  fs.writeFile(Path.join(sandboxPath, "test.txt"), "testing..", done);
}

function findMatch(pattern, path, done) {
  fs.readdir(path, function(err, files) {
    if(err) return done(err);

    for(var i = 0, ic = files.length;i<ic;i++) {
      var f = files[i];

      if(pattern.test(f)) return done(null, f);
    }

    done();
  });
}

describe("grunt-file-rotate test", function() {
  it("prepares test", function(done) {
    createTestFile(done);
  });

  it("rotates to the same directory", function(done) {
    grunt.util.spawn({
      cmd: "grunt",
      args: ["datesuffix:test1"],
      opts: {
        cwd: sandboxPath
      }
    }, function(err, out) {
      if(err) {
        grunt.fail.fatal(out.stdout);
        return done(err);
      }

      fs.exists(Path.join(sandboxPath, testFileName), function(exist) {
        try {
          exist.should.not.be.ok;

          findMatch(rotatedFilePattern, sandboxPath, function(err, name) {
            if(err) return done(err);
            try {
              should.exist(name);

              fs.unlink(Path.join(sandboxPath, name), done);
            } catch(err) {
              done(err);
            }
          });
        } catch(err) {
          done(err);
        }
      });
    });
  });

  it("prepares next test", function(done) {
    createTestFile(done);
  });

  it("rotates to a different directory", function(done) {
    grunt.util.spawn({
      cmd: "grunt",
      args: ["datesuffix:test2"],
      opts: {
        cwd: sandboxPath
      }
    }, function(err) {
      if(err) {
        grunt.fail.fatal(out.stdout);
        return done(err);
      }

      fs.exists(Path.join(sandboxPath, testFileName), function(exist) {
        try {
          exist.should.not.be.ok;

          findMatch(rotatedFilePattern, testOutputPath, function(err, name) {
            if(err) return done(err);
            try {
              should.exist(name);

              fs.unlink(Path.join(testOutputPath, name), done);
            } catch(err) {
              done(err);
            }
          });
        } catch(err) {
          done(err);
        }
      });
    });
  });

  it("prepares next test", function(done) {
    createTestFile(done);
  });

  it("rotates to a different directory and leave the original copy", function(done) {
    grunt.util.spawn({
      cmd: "grunt",
      args: ["datesuffix:test3"],
      opts: {
        cwd: sandboxPath
      }
    }, function(err) {
      if(err) {
        grunt.fail.fatal(out.stdout);
        return done(err);
      }

      fs.exists(Path.join(sandboxPath, testFileName), function(exist) {
        try {
          exist.should.be.ok;

          findMatch(rotatedFilePattern, testOutputPath, function(err, name) {
            if(err) return done(err);
            try {
              should.exist(name);

              fs.unlink(Path.join(testOutputPath, name), done);
            } catch(err) {
              done(err);
            }
          });
        } catch(err) {
          done(err);
        }
      });
    });
  });

  it("cleans up", function(done) {
    fs.unlink(Path.join(sandboxPath, testFileName), function(err) {
      if(err) return done(err);

      fs.remove(testOutputPath, done);
    });
  });
});<commit_msg>fix test failure output<commit_after>'use strict'

var should = require("should");
var fs = require("fs-extra");
var Path = require("path");
var grunt = require("grunt");
var testFilePrefix = "test";
var testFileExtname = ".txt";
var testFileName = testFilePrefix+testFileExtname;
var testOutputPath = "./test/env/output";
var rotatedFilePattern = new RegExp("^test[.][0-9]{1,}[.]txt$");
var sandboxPath = "./test/env";

function createTestFile(done) {
  fs.writeFile(Path.join(sandboxPath, "test.txt"), "testing..", done);
}

function findMatch(pattern, path, done) {
  fs.readdir(path, function(err, files) {
    if(err) return done(err);

    for(var i = 0, ic = files.length;i<ic;i++) {
      var f = files[i];

      if(pattern.test(f)) return done(null, f);
    }

    done();
  });
}

describe("grunt-file-rotate test", function() {
  it("prepares test", function(done) {
    createTestFile(done);
  });

  it("rotates to the same directory", function(done) {
    grunt.util.spawn({
      cmd: "grunt",
      args: ["datesuffix:test1"],
      opts: {
        cwd: sandboxPath
      }
    }, function(err, out) {
      if(err) {
        grunt.fail.fatal(out.stderr);
        return done(err);
      }

      fs.exists(Path.join(sandboxPath, testFileName), function(exist) {
        try {
          exist.should.not.be.ok;

          findMatch(rotatedFilePattern, sandboxPath, function(err, name) {
            if(err) return done(err);
            try {
              should.exist(name);

              fs.unlink(Path.join(sandboxPath, name), done);
            } catch(err) {
              done(err);
            }
          });
        } catch(err) {
          done(err);
        }
      });
    });
  });

  it("prepares next test", function(done) {
    createTestFile(done);
  });

  it("rotates to a different directory", function(done) {
    grunt.util.spawn({
      cmd: "grunt",
      args: ["datesuffix:test2"],
      opts: {
        cwd: sandboxPath
      }
    }, function(err) {
      if(err) {
        grunt.fail.fatal(out.stderr);
        return done(err);
      }

      fs.exists(Path.join(sandboxPath, testFileName), function(exist) {
        try {
          exist.should.not.be.ok;

          findMatch(rotatedFilePattern, testOutputPath, function(err, name) {
            if(err) return done(err);
            try {
              should.exist(name);

              fs.unlink(Path.join(testOutputPath, name), done);
            } catch(err) {
              done(err);
            }
          });
        } catch(err) {
          done(err);
        }
      });
    });
  });

  it("prepares next test", function(done) {
    createTestFile(done);
  });

  it("rotates to a different directory and leave the original copy", function(done) {
    grunt.util.spawn({
      cmd: "grunt",
      args: ["datesuffix:test3"],
      opts: {
        cwd: sandboxPath
      }
    }, function(err) {
      if(err) {
        grunt.fail.fatal(out.stderr);
        return done(err);
      }

      fs.exists(Path.join(sandboxPath, testFileName), function(exist) {
        try {
          exist.should.be.ok;

          findMatch(rotatedFilePattern, testOutputPath, function(err, name) {
            if(err) return done(err);
            try {
              should.exist(name);

              fs.unlink(Path.join(testOutputPath, name), done);
            } catch(err) {
              done(err);
            }
          });
        } catch(err) {
          done(err);
        }
      });
    });
  });

  it("cleans up", function(done) {
    fs.unlink(Path.join(sandboxPath, testFileName), function(err) {
      if(err) return done(err);

      fs.remove(testOutputPath, done);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';
angular.module('copayApp.services')
  .factory('uxLanguage', function languageService($log, lodash, gettextCatalog, amMoment, configService) {
    var root = {};

    root.currentLanguage = null;

    root.availableLanguages = [{
      name: 'English',
      isoCode: 'en',
    }, {
      name: 'Español',
      isoCode: 'es',
    }, {
      name: 'Français',
      isoCode: 'fr',
    }, {
      name: 'Italiano',
      isoCode: 'it',
    }, {
      name: 'Dutch',
      isoCode: 'nl',
    }, {
      name: 'Polski',
      isoCode: 'pl',
    }, {
      name: 'Deutsch',
      isoCode: 'de',
    }, {
      name: '日本語',
      isoCode: 'ja',
      useIdeograms: true,
    }, {
      name: '中文（简体）',
      isoCode: 'zh',
      useIdeograms: true,
    }, {
      name: 'Pусский',
      isoCode: 'ru',
    }, {
      name: 'Português',
      isoCode: 'pt',
    }];

    // }, {
    //   name: 'Český',
    //   isoCode: 'cs',
    // }

    root._detect = function(cb) {
      var userLang, androidLang;
      if (navigator && navigator.globalization) {

        navigator.globalization.getPreferredLanguage(function(preferedLanguage) {
          // works for iOS and Android 4.x
          userLang = preferedLanguage.value;
          userLang = userLang ? (userLang.split('-', 1)[0] || 'en') : 'en';
          // Set only available languages
          userLang = root.isAvailableLanguage(userLang);
          return cb(userLang);
        });
      } else {
        // Auto-detect browser language
        userLang = navigator.userLanguage || navigator.language;
        userLang = userLang ? (userLang.split('-', 1)[0] || 'en') : 'en';
        // Set only available languages
        userLang = root.isAvailableLanguage(userLang);
        return cb(userLang);
      }
    };

    root.isAvailableLanguage = function(userLang) {
      return lodash.find(root.availableLanguages, {
        'isoCode': userLang
      }) ? userLang : 'en';
    };

    root._set = function(lang) {
      $log.debug('Setting default language: ' + lang);
      gettextCatalog.setCurrentLanguage(lang);
      root.currentLanguage = lang;

      if (lang == 'zh') lang = lang + '-CN'; // Fix for Chinese Simplified
      amMoment.changeLocale(lang);
    };

    root.getCurrentLanguage = function() {
      return root.currentLanguage;
    };

    root.getCurrentLanguageName = function() {
      return root.getName(root.currentLanguage);
    };

    root.getCurrentLanguageInfo = function() {
      return lodash.find(root.availableLanguages, {
        'isoCode': root.currentLanguage
      });
    };

    root.getLanguages = function() {
      return root.availableLanguages;
    };

    root.init = function(cb) {
      configService.whenAvailable(function(config) {
        var userLang = config.wallet.settings.defaultLanguage;

        if (userLang && userLang != root.currentLanguage) {
          root._set(userLang);
        } else {
          root._detect(function(lang) {
            root._set(lang);
          });
        }
        if (cb) return cb();
      });
    };

    root.getName = function(lang) {
      return lodash.result(lodash.find(root.availableLanguages, {
        'isoCode': lang
      }), 'name');
    };

    return root;
  });
<commit_msg>Fix typo<commit_after>'use strict';
angular.module('copayApp.services')
  .factory('uxLanguage', function languageService($log, lodash, gettextCatalog, amMoment, configService) {
    var root = {};

    root.currentLanguage = null;

    root.availableLanguages = [{
      name: 'English',
      isoCode: 'en',
    }, {
      name: 'Español',
      isoCode: 'es',
    }, {
      name: 'Français',
      isoCode: 'fr',
    }, {
      name: 'Italiano',
      isoCode: 'it',
    }, {
      name: 'Nederlands',
      isoCode: 'nl',
    }, {
      name: 'Polski',
      isoCode: 'pl',
    }, {
      name: 'Deutsch',
      isoCode: 'de',
    }, {
      name: '日本語',
      isoCode: 'ja',
      useIdeograms: true,
    }, {
      name: '中文（简体）',
      isoCode: 'zh',
      useIdeograms: true,
    }, {
      name: 'Pусский',
      isoCode: 'ru',
    }, {
      name: 'Português',
      isoCode: 'pt',
    }];

    // }, {
    //   name: 'Český',
    //   isoCode: 'cs',
    // }

    root._detect = function(cb) {
      var userLang, androidLang;
      if (navigator && navigator.globalization) {

        navigator.globalization.getPreferredLanguage(function(preferedLanguage) {
          // works for iOS and Android 4.x
          userLang = preferedLanguage.value;
          userLang = userLang ? (userLang.split('-', 1)[0] || 'en') : 'en';
          // Set only available languages
          userLang = root.isAvailableLanguage(userLang);
          return cb(userLang);
        });
      } else {
        // Auto-detect browser language
        userLang = navigator.userLanguage || navigator.language;
        userLang = userLang ? (userLang.split('-', 1)[0] || 'en') : 'en';
        // Set only available languages
        userLang = root.isAvailableLanguage(userLang);
        return cb(userLang);
      }
    };

    root.isAvailableLanguage = function(userLang) {
      return lodash.find(root.availableLanguages, {
        'isoCode': userLang
      }) ? userLang : 'en';
    };

    root._set = function(lang) {
      $log.debug('Setting default language: ' + lang);
      gettextCatalog.setCurrentLanguage(lang);
      root.currentLanguage = lang;

      if (lang == 'zh') lang = lang + '-CN'; // Fix for Chinese Simplified
      amMoment.changeLocale(lang);
    };

    root.getCurrentLanguage = function() {
      return root.currentLanguage;
    };

    root.getCurrentLanguageName = function() {
      return root.getName(root.currentLanguage);
    };

    root.getCurrentLanguageInfo = function() {
      return lodash.find(root.availableLanguages, {
        'isoCode': root.currentLanguage
      });
    };

    root.getLanguages = function() {
      return root.availableLanguages;
    };

    root.init = function(cb) {
      configService.whenAvailable(function(config) {
        var userLang = config.wallet.settings.defaultLanguage;

        if (userLang && userLang != root.currentLanguage) {
          root._set(userLang);
        } else {
          root._detect(function(lang) {
            root._set(lang);
          });
        }
        if (cb) return cb();
      });
    };

    root.getName = function(lang) {
      return lodash.result(lodash.find(root.availableLanguages, {
        'isoCode': lang
      }), 'name');
    };

    return root;
  });
<|endoftext|>


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

/**
 * marked tests
 * Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/chjj/marked
 */

/**
 * Modules
 */

var fs = require('fs')
  , path = require('path')
  , marked = require('../');

/**
 * Load Tests
 */

function load() {
  var dir = __dirname + '/tests'
    , files = {}
    , list
    , file
    , i
    , l;

  list = fs
    .readdirSync(dir)
    .filter(function(file) {
      return path.extname(file) !== '.html';
    })
    .sort(function(a, b) {
      a = path.basename(a).toLowerCase().charCodeAt(0);
      b = path.basename(b).toLowerCase().charCodeAt(0);
      return a > b ? 1 : (a < b ? -1 : 0);
    });

  i = 0;
  l = list.length;

  for (; i < l; i++) {
    file = path.join(dir, list[i]);
    files[path.basename(file)] = {
      text: fs.readFileSync(file, 'utf8'),
      html: fs.readFileSync(file.replace(/[^.]+$/, 'html'), 'utf8')
    };
  }

  return files;
}

/**
 * Test Runner
 */

function runTests(engine, options) {
  if (typeof engine !== 'function') {
    options = engine;
    engine = null;
  }

  var engine = engine || marked
    , options = options || {}
    , files = options.files || load()
    , complete = 0
    , failed = 0
    , failures = []
    , keys = Object.keys(files)
    , i = 0
    , len = keys.length
    , filename
    , file
    , flags
    , text
    , html
    , j
    , l;

  if (options.marked) {
    marked.setOptions(options.marked);
  }

main:
  for (; i < len; i++) {
    filename = keys[i];
    file = files[filename];

    if (marked._original) {
      marked.defaults = marked._original;
      delete marked._original;
    }

    flags = filename.split('.').slice(1, -1);
    if (flags.length) {
      marked._original = marked.defaults;
      marked.defaults = {};
      Object.keys(marked._original).forEach(function(key) {
        marked.defaults[key] = marked._original[key];
      });
      flags.forEach(function(key) {
        var val = true;
        if (key.indexOf('no') === 0) {
          key = key.substring(2);
          val = false;
        }
        if (marked.defaults.hasOwnProperty(key)) {
          marked.defaults[key] = val;
        }
      });
    }

    try {
      text = engine(file.text).replace(/\s/g, '');
      html = file.html.replace(/\s/g, '');
    } catch(e) {
      console.log('%s failed.', filename);
      throw e;
    }

    j = 0;
    l = html.length;

    for (; j < l; j++) {
      if (text[j] !== html[j]) {
        failed++;
        failures.push(filename);

        text = text.substring(
          Math.max(j - 30, 0),
          Math.min(j + 30, text.length));

        html = html.substring(
          Math.max(j - 30, 0),
          Math.min(j + 30, html.length));

        console.log(
          '\n#%d. %s failed at offset %d. Near: "%s".\n',
          i + 1, filename, j, text);

        console.log('\nGot:\n%s\n', text.trim() || text);
        console.log('\nExpected:\n%s\n', html.trim() || html);

        if (options.stop) {
          break main;
        }

        continue main;
      }
    }

    complete++;
    console.log('#%d. %s completed.', i + 1, filename);
  }

  console.log('%d/%d tests completed successfully.', complete, len);
  if (failed) console.log('%d/%d tests failed.', failed, len);

  // Tests currently failing.
  if (~failures.indexOf('def_blocks.text')) {
    failed -= 1;
  }

  return !failed;
}

/**
 * Benchmark a function
 */

function bench(name, func) {
  var files = bench.files || load();

  if (!bench.files) {
    bench.files = files;

    // Change certain tests to allow
    // comparison to older benchmark times.
    fs.readdirSync(__dirname + '/new').forEach(function(name) {
      if (path.extname(name) === '.html') return;
      if (name === 'main.text') return;
      delete files[name];
    });

    files['backslash_escapes.text'] = {
      text: 'hello world \\[how](are you) today'
    };

    files['main.text'].text = files['main.text'].text.replace('* * *\n\n', '');
  }

  var start = Date.now()
    , times = 1000
    , keys = Object.keys(files)
    , i
    , l = keys.length
    , filename
    , file;

  while (times--) {
    for (i = 0; i < l; i++) {
      filename = keys[i];
      file = files[filename];
      func(file.text);
    }
  }

  console.log('%s completed in %dms.', name, Date.now() - start);
}

/**
 * Benchmark all engines
 */

function runBench(options) {
  var options = options || {};

  // Non-GFM, Non-pedantic
  marked.setOptions({
    gfm: false,
    tables: false,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: false
  });
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked', marked);

  // GFM
  marked.setOptions({
    gfm: true,
    tables: false,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: false
  });
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked (gfm)', marked);

  // Pedantic
  marked.setOptions({
    gfm: false,
    tables: false,
    breaks: false,
    pedantic: true,
    sanitize: false,
    smartLists: false
  });
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked (pedantic)', marked);

  // robotskirt
  try {
    bench('robotskirt', (function() {
      var rs = require('robotskirt');
      return function(text) {
        var parser = rs.Markdown.std();
        return parser.render(text);
      };
    })());
  } catch (e) {
    console.log('Could not bench robotskirt.');
  }

  // showdown
  try {
    bench('showdown (reuse converter)', (function() {
      var Showdown = require('showdown');
      var convert = new Showdown.converter();
      return function(text) {
        return convert.makeHtml(text);
      };
    })());
    bench('showdown (new converter)', (function() {
      var Showdown = require('showdown');
      return function(text) {
        var convert = new Showdown.converter();
        return convert.makeHtml(text);
      };
    })());
  } catch (e) {
    console.log('Could not bench showdown.');
  }

  // markdown.js
  try {
    bench('markdown.js', require('markdown').parse);
  } catch (e) {
    console.log('Could not bench markdown.js.');
  }
}

/**
 * A simple one-time benchmark
 */

function time(options) {
  var options = options || {};
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked', marked);
}

/**
 * Markdown Test Suite Fixer
 *   This function is responsible for "fixing"
 *   the markdown test suite. There are
 *   certain aspects of the suite that
 *   are strange or might make tests
 *   fail for reasons unrelated to
 *   conformance.
 */

function fix(options) {
  ['tests', 'original', 'new'].forEach(function(dir) {
    try {
      fs.mkdirSync(path.resolve(__dirname, dir), 0755);
    } catch (e) {
      ;
    }
  });

  // rm -rf tests
  fs.readdirSync(path.resolve(__dirname, 'tests')).forEach(function(file) {
    fs.unlinkSync(path.resolve(__dirname, 'tests', file));
  });

  // cp -r original tests
  fs.readdirSync(path.resolve(__dirname, 'original')).forEach(function(file) {
    var nfile = file;
    if (file.indexOf('hard_wrapped_paragraphs_with_list_like_lines.') === 0) {
      nfile = file.replace(/\.(text|html)$/, '.nogfm.$1');
    }
    fs.writeFileSync(path.resolve(__dirname, 'tests', nfile),
      fs.readFileSync(path.resolve(__dirname, 'original', file)));
  });

  // node fix.js
  var dir = __dirname + '/tests';

  fs.readdirSync(dir).filter(function(file) {
    return path.extname(file) === '.html';
  }).forEach(function(file) {
    var file = path.join(dir, file)
      , html = fs.readFileSync(file, 'utf8');

    // fix unencoded quotes
    html = html
      .replace(/='([^\n']*)'(?=[^<>\n]*>)/g, '=&__APOS__;$1&__APOS__;')
      .replace(/="([^\n"]*)"(?=[^<>\n]*>)/g, '=&__QUOT__;$1&__QUOT__;')
      .replace(/"/g, '"')
      .replace(/'/g, ''')
      .replace(/&__QUOT__;/g, '"')
      .replace(/&__APOS__;/g, '\'');

    // add heading id's
    html = html.replace(/<(h[1-6])>([^<]+)<\/\1>/g, function(s, h, text) {
      var id = text
        .replace(/'/g, '\'')
        .replace(/"/g, '"')
        .replace(/>/g, '>')
        .replace(/</g, '<')
        .replace(/&/g, '&');

      id = id.toLowerCase().replace(/[^\w]+/g, '-');

      return '<' + h + ' id="' + id + '">' + text + '</' + h + '>';
    });

    fs.writeFileSync(file, html);
  });

  // turn
 into

  fs.readdirSync(dir).forEach(function(file) {
    var file = path.join(dir, file)
      , text = fs.readFileSync(file, 'utf8');

    text = text.replace(/(<|<)hr\s*\/(>|>)/g, '$1hr$2');

    fs.writeFileSync(file, text);
  });

  // markdown does some strange things.
  // it does not encode naked `>`, marked does.
  (function() {
    var file = dir + '/amps_and_angles_encoding.html';
    var html = fs.readFileSync(file, 'utf8')
      .replace('6 > 5.', '6 > 5.');

    fs.writeFileSync(file, html);
  })();

  // cp new/* tests/
  fs.readdirSync(path.resolve(__dirname, 'new')).forEach(function(file) {
    fs.writeFileSync(path.resolve(__dirname, 'tests', file),
      fs.readFileSync(path.resolve(__dirname, 'new', file)));
  });
}

/**
 * Argument Parsing
 */

function parseArg(argv) {
  var argv = process.argv.slice(2)
    , options = {}
    , orphans = []
    , arg;

  function getarg() {
    var arg = argv.shift();

    if (arg.indexOf('--') === 0) {
      // e.g. --opt
      arg = arg.split('=');
      if (arg.length > 1) {
        // e.g. --opt=val
        argv.unshift(arg.slice(1).join('='));
      }
      arg = arg[0];
    } else if (arg[0] === '-') {
      if (arg.length > 2) {
        // e.g. -abc
        argv = arg.substring(1).split('').map(function(ch) {
          return '-' + ch;
        }).concat(argv);
        arg = argv.shift();
      } else {
        // e.g. -a
      }
    } else {
      // e.g. foo
    }

    return arg;
  }

  while (argv.length) {
    arg = getarg();
    switch (arg) {
      case '-f':
      case '--fix':
      case 'fix':
        options.fix = true;
        break;
      case '-b':
      case '--bench':
        options.bench = true;
        break;
      case '-s':
      case '--stop':
        options.stop = true;
        break;
      case '-t':
      case '--time':
        options.time = true;
        break;
      default:
        if (arg.indexOf('--') === 0) {
          opt = camelize(arg.replace(/^--(no-)?/, ''));
          if (!marked.defaults.hasOwnProperty(opt)) {
            continue;
          }
          options.marked = options.marked || {};
          if (arg.indexOf('--no-') === 0) {
            options.marked[opt] = typeof marked.defaults[opt] !== 'boolean'
              ? null
              : false;
          } else {
            options.marked[opt] = typeof marked.defaults[opt] !== 'boolean'
              ? argv.shift()
              : true;
          }
        } else {
          orphans.push(arg);
        }
        break;
    }
  }

  return options;
}

/**
 * Helpers
 */

function camelize(text) {
  return text.replace(/(\w)-(\w)/g, function(_, a, b) {
    return a + b.toUpperCase();
  });
}

/**
 * Main
 */

function main(argv) {
  var opt = parseArg();

  if (opt.fix) {
    return fix(opt);
  }

  if (opt.bench) {
    return runBench(opt);
  }

  if (opt.time) {
    return time(opt);
  }

  return runTests(opt);
}

/**
 * Execute
 */

if (!module.parent) {
  process.title = 'marked';
  process.exit(main(process.argv.slice()) ? 0 : 1);
} else {
  exports = main;
  exports.main = main;
  exports.runTests = runTests;
  exports.runBench = runBench;
  exports.load = load;
  exports.bench = bench;
  module.exports = exports;
}
<commit_msg>Remove redundant clamping.<commit_after>#!/usr/bin/env node

/**
 * marked tests
 * Copyright (c) 2011-2013, Christopher Jeffrey. (MIT Licensed)
 * https://github.com/chjj/marked
 */

/**
 * Modules
 */

var fs = require('fs')
  , path = require('path')
  , marked = require('../');

/**
 * Load Tests
 */

function load() {
  var dir = __dirname + '/tests'
    , files = {}
    , list
    , file
    , i
    , l;

  list = fs
    .readdirSync(dir)
    .filter(function(file) {
      return path.extname(file) !== '.html';
    })
    .sort(function(a, b) {
      a = path.basename(a).toLowerCase().charCodeAt(0);
      b = path.basename(b).toLowerCase().charCodeAt(0);
      return a > b ? 1 : (a < b ? -1 : 0);
    });

  i = 0;
  l = list.length;

  for (; i < l; i++) {
    file = path.join(dir, list[i]);
    files[path.basename(file)] = {
      text: fs.readFileSync(file, 'utf8'),
      html: fs.readFileSync(file.replace(/[^.]+$/, 'html'), 'utf8')
    };
  }

  return files;
}

/**
 * Test Runner
 */

function runTests(engine, options) {
  if (typeof engine !== 'function') {
    options = engine;
    engine = null;
  }

  var engine = engine || marked
    , options = options || {}
    , files = options.files || load()
    , complete = 0
    , failed = 0
    , failures = []
    , keys = Object.keys(files)
    , i = 0
    , len = keys.length
    , filename
    , file
    , flags
    , text
    , html
    , j
    , l;

  if (options.marked) {
    marked.setOptions(options.marked);
  }

main:
  for (; i < len; i++) {
    filename = keys[i];
    file = files[filename];

    if (marked._original) {
      marked.defaults = marked._original;
      delete marked._original;
    }

    flags = filename.split('.').slice(1, -1);
    if (flags.length) {
      marked._original = marked.defaults;
      marked.defaults = {};
      Object.keys(marked._original).forEach(function(key) {
        marked.defaults[key] = marked._original[key];
      });
      flags.forEach(function(key) {
        var val = true;
        if (key.indexOf('no') === 0) {
          key = key.substring(2);
          val = false;
        }
        if (marked.defaults.hasOwnProperty(key)) {
          marked.defaults[key] = val;
        }
      });
    }

    try {
      text = engine(file.text).replace(/\s/g, '');
      html = file.html.replace(/\s/g, '');
    } catch(e) {
      console.log('%s failed.', filename);
      throw e;
    }

    j = 0;
    l = html.length;

    for (; j < l; j++) {
      if (text[j] !== html[j]) {
        failed++;
        failures.push(filename);

        text = text.substring(j - 30, j + 30);

        html = html.substring(j - 30, j + 30);

        console.log(
          '\n#%d. %s failed at offset %d. Near: "%s".\n',
          i + 1, filename, j, text);

        console.log('\nGot:\n%s\n', text.trim() || text);
        console.log('\nExpected:\n%s\n', html.trim() || html);

        if (options.stop) {
          break main;
        }

        continue main;
      }
    }

    complete++;
    console.log('#%d. %s completed.', i + 1, filename);
  }

  console.log('%d/%d tests completed successfully.', complete, len);
  if (failed) console.log('%d/%d tests failed.', failed, len);

  // Tests currently failing.
  if (~failures.indexOf('def_blocks.text')) {
    failed -= 1;
  }

  return !failed;
}

/**
 * Benchmark a function
 */

function bench(name, func) {
  var files = bench.files || load();

  if (!bench.files) {
    bench.files = files;

    // Change certain tests to allow
    // comparison to older benchmark times.
    fs.readdirSync(__dirname + '/new').forEach(function(name) {
      if (path.extname(name) === '.html') return;
      if (name === 'main.text') return;
      delete files[name];
    });

    files['backslash_escapes.text'] = {
      text: 'hello world \\[how](are you) today'
    };

    files['main.text'].text = files['main.text'].text.replace('* * *\n\n', '');
  }

  var start = Date.now()
    , times = 1000
    , keys = Object.keys(files)
    , i
    , l = keys.length
    , filename
    , file;

  while (times--) {
    for (i = 0; i < l; i++) {
      filename = keys[i];
      file = files[filename];
      func(file.text);
    }
  }

  console.log('%s completed in %dms.', name, Date.now() - start);
}

/**
 * Benchmark all engines
 */

function runBench(options) {
  var options = options || {};

  // Non-GFM, Non-pedantic
  marked.setOptions({
    gfm: false,
    tables: false,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: false
  });
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked', marked);

  // GFM
  marked.setOptions({
    gfm: true,
    tables: false,
    breaks: false,
    pedantic: false,
    sanitize: false,
    smartLists: false
  });
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked (gfm)', marked);

  // Pedantic
  marked.setOptions({
    gfm: false,
    tables: false,
    breaks: false,
    pedantic: true,
    sanitize: false,
    smartLists: false
  });
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked (pedantic)', marked);

  // robotskirt
  try {
    bench('robotskirt', (function() {
      var rs = require('robotskirt');
      return function(text) {
        var parser = rs.Markdown.std();
        return parser.render(text);
      };
    })());
  } catch (e) {
    console.log('Could not bench robotskirt.');
  }

  // showdown
  try {
    bench('showdown (reuse converter)', (function() {
      var Showdown = require('showdown');
      var convert = new Showdown.converter();
      return function(text) {
        return convert.makeHtml(text);
      };
    })());
    bench('showdown (new converter)', (function() {
      var Showdown = require('showdown');
      return function(text) {
        var convert = new Showdown.converter();
        return convert.makeHtml(text);
      };
    })());
  } catch (e) {
    console.log('Could not bench showdown.');
  }

  // markdown.js
  try {
    bench('markdown.js', require('markdown').parse);
  } catch (e) {
    console.log('Could not bench markdown.js.');
  }
}

/**
 * A simple one-time benchmark
 */

function time(options) {
  var options = options || {};
  if (options.marked) {
    marked.setOptions(options.marked);
  }
  bench('marked', marked);
}

/**
 * Markdown Test Suite Fixer
 *   This function is responsible for "fixing"
 *   the markdown test suite. There are
 *   certain aspects of the suite that
 *   are strange or might make tests
 *   fail for reasons unrelated to
 *   conformance.
 */

function fix(options) {
  ['tests', 'original', 'new'].forEach(function(dir) {
    try {
      fs.mkdirSync(path.resolve(__dirname, dir), 0755);
    } catch (e) {
      ;
    }
  });

  // rm -rf tests
  fs.readdirSync(path.resolve(__dirname, 'tests')).forEach(function(file) {
    fs.unlinkSync(path.resolve(__dirname, 'tests', file));
  });

  // cp -r original tests
  fs.readdirSync(path.resolve(__dirname, 'original')).forEach(function(file) {
    var nfile = file;
    if (file.indexOf('hard_wrapped_paragraphs_with_list_like_lines.') === 0) {
      nfile = file.replace(/\.(text|html)$/, '.nogfm.$1');
    }
    fs.writeFileSync(path.resolve(__dirname, 'tests', nfile),
      fs.readFileSync(path.resolve(__dirname, 'original', file)));
  });

  // node fix.js
  var dir = __dirname + '/tests';

  fs.readdirSync(dir).filter(function(file) {
    return path.extname(file) === '.html';
  }).forEach(function(file) {
    var file = path.join(dir, file)
      , html = fs.readFileSync(file, 'utf8');

    // fix unencoded quotes
    html = html
      .replace(/='([^\n']*)'(?=[^<>\n]*>)/g, '=&__APOS__;$1&__APOS__;')
      .replace(/="([^\n"]*)"(?=[^<>\n]*>)/g, '=&__QUOT__;$1&__QUOT__;')
      .replace(/"/g, '"')
      .replace(/'/g, ''')
      .replace(/&__QUOT__;/g, '"')
      .replace(/&__APOS__;/g, '\'');

    // add heading id's
    html = html.replace(/<(h[1-6])>([^<]+)<\/\1>/g, function(s, h, text) {
      var id = text
        .replace(/'/g, '\'')
        .replace(/"/g, '"')
        .replace(/>/g, '>')
        .replace(/</g, '<')
        .replace(/&/g, '&');

      id = id.toLowerCase().replace(/[^\w]+/g, '-');

      return '<' + h + ' id="' + id + '">' + text + '</' + h + '>';
    });

    fs.writeFileSync(file, html);
  });

  // turn
 into

  fs.readdirSync(dir).forEach(function(file) {
    var file = path.join(dir, file)
      , text = fs.readFileSync(file, 'utf8');

    text = text.replace(/(<|<)hr\s*\/(>|>)/g, '$1hr$2');

    fs.writeFileSync(file, text);
  });

  // markdown does some strange things.
  // it does not encode naked `>`, marked does.
  (function() {
    var file = dir + '/amps_and_angles_encoding.html';
    var html = fs.readFileSync(file, 'utf8')
      .replace('6 > 5.', '6 > 5.');

    fs.writeFileSync(file, html);
  })();

  // cp new/* tests/
  fs.readdirSync(path.resolve(__dirname, 'new')).forEach(function(file) {
    fs.writeFileSync(path.resolve(__dirname, 'tests', file),
      fs.readFileSync(path.resolve(__dirname, 'new', file)));
  });
}

/**
 * Argument Parsing
 */

function parseArg(argv) {
  var argv = process.argv.slice(2)
    , options = {}
    , orphans = []
    , arg;

  function getarg() {
    var arg = argv.shift();

    if (arg.indexOf('--') === 0) {
      // e.g. --opt
      arg = arg.split('=');
      if (arg.length > 1) {
        // e.g. --opt=val
        argv.unshift(arg.slice(1).join('='));
      }
      arg = arg[0];
    } else if (arg[0] === '-') {
      if (arg.length > 2) {
        // e.g. -abc
        argv = arg.substring(1).split('').map(function(ch) {
          return '-' + ch;
        }).concat(argv);
        arg = argv.shift();
      } else {
        // e.g. -a
      }
    } else {
      // e.g. foo
    }

    return arg;
  }

  while (argv.length) {
    arg = getarg();
    switch (arg) {
      case '-f':
      case '--fix':
      case 'fix':
        options.fix = true;
        break;
      case '-b':
      case '--bench':
        options.bench = true;
        break;
      case '-s':
      case '--stop':
        options.stop = true;
        break;
      case '-t':
      case '--time':
        options.time = true;
        break;
      default:
        if (arg.indexOf('--') === 0) {
          opt = camelize(arg.replace(/^--(no-)?/, ''));
          if (!marked.defaults.hasOwnProperty(opt)) {
            continue;
          }
          options.marked = options.marked || {};
          if (arg.indexOf('--no-') === 0) {
            options.marked[opt] = typeof marked.defaults[opt] !== 'boolean'
              ? null
              : false;
          } else {
            options.marked[opt] = typeof marked.defaults[opt] !== 'boolean'
              ? argv.shift()
              : true;
          }
        } else {
          orphans.push(arg);
        }
        break;
    }
  }

  return options;
}

/**
 * Helpers
 */

function camelize(text) {
  return text.replace(/(\w)-(\w)/g, function(_, a, b) {
    return a + b.toUpperCase();
  });
}

/**
 * Main
 */

function main(argv) {
  var opt = parseArg();

  if (opt.fix) {
    return fix(opt);
  }

  if (opt.bench) {
    return runBench(opt);
  }

  if (opt.time) {
    return time(opt);
  }

  return runTests(opt);
}

/**
 * Execute
 */

if (!module.parent) {
  process.title = 'marked';
  process.exit(main(process.argv.slice()) ? 0 : 1);
} else {
  exports = main;
  exports.main = main;
  exports.runTests = runTests;
  exports.runBench = runBench;
  exports.load = load;
  exports.bench = bench;
  module.exports = exports;
}
<|endoftext|>


<commit_before>var crel = require('../'),
    test = require('tape');

// -- Test element creation --
test('Create an element with no arguments', function (t) {
    t.plan(2);

    var testElement = crel('div');

    t.ok(testElement instanceof HTMLElement,
        'element is an instance of `HTMLElement`');
    t.equal(testElement.tagName, 'DIV',
        'element is an instance of `div`');
});

test('Create an element with no arguments, using an invalid tag name', function (t) {
    t.plan(2);

    var testElement = crel('invalidtagname');

    t.ok(testElement instanceof HTMLUnknownElement,
        'element is an instance of `HTMLUnknownElement `');
    t.equal(testElement.tagName, 'INVALIDTAGNAME',
        'element is an instance of `invalidtagname`');
});

// -- Test attribute handling --
test('Create an element with simple attributes', function (t) {
    t.plan(2);

    var testElement = crel('div', {'class': 'test', id: 'test'});

    t.equal(testElement.className, 'test',
        'element has a `test` class');
    t.equal(testElement.getAttribute('id'), 'test',
        'element has a `test` id');
});

test('Add attributes to an already existing element', function (t) {
    t.plan(2);

    var testElement = document.createElement('div');
    crel(testElement, {'class': 'test', id: 'test'});

    t.equal(testElement.className, 'test',
        'element has a `test` class');
    t.equal(testElement.getAttribute('id'), 'test',
        'element has a `test` id');
});

test('Add an `onEvent` property to an element', function (t) {
    t.plan(1);

    var testElement = crel('button', {
        onclick: function () {
            t.pass('onClick event triggered');
        }
    });

    testElement.click();
});

// -- Test child node handling --
test('Create an element with a child element', function (t) {
    t.plan(2);

    var testElement = crel('div', document.createElement('p'));

    t.equal(testElement.childNodes.length, 1,
        'element has a child element');
    t.equal(testElement.childNodes[0].tagName, 'P',
        'child element is an instance of `p`');
});

test('Create an element with a child text node', function (t) {
    t.plan(2);

    var testElement = crel('div', document.createTextNode('test'));

    t.equal(testElement.childNodes.length, 1,
        'element has a child element');
    t.equal(testElement.childNodes[0].nodeType, 3,
        'child element is a text node');
});

test('Create an element with an array of children', function (t) {
    t.plan(6);
    // TODO: make these more compact / robust
    var testArray = [document.createElement('p'), document.createTextNode('I\'m a text node!'), 'I will be a text node!'];
    var testElement = crel('div', testArray);

    t.equal(testElement.childNodes.length, 3,
        'element has three children');
    t.equal(testElement.childNodes[0].tagName, 'P');
    t.equal(testElement.childNodes[1].nodeType, 3);
    t.equal(testElement.childNodes[1].textContent, 'I\'m a text node!');
    t.equal(testElement.childNodes[2].nodeType, 3);
    t.equal(testElement.childNodes[2].textContent, 'I will be a text node!');
});

test('Create an element with a deep array of children', function (t) {
    t.plan(6);
    // TODO: make these more compact / robust
    var testArray = [document.createElement('p'), document.createTextNode('I\'m a text node!'), 'I will be a text node!'];
    var testElement = crel('div', [[testArray]]);

    t.equal(testElement.childNodes.length, 3,
        'element has three children');
    t.equal(testElement.childNodes[0].tagName, 'P');
    t.equal(testElement.childNodes[1].nodeType, 3);
    t.equal(testElement.childNodes[1].textContent, 'I\'m a text node!');
    t.equal(testElement.childNodes[2].nodeType, 3);
    t.equal(testElement.childNodes[2].textContent, 'I will be a text node!');
});

// -- Test exposed methods --
test('Test that `isNode` is defined', function (t) {
    // Assign into a variable to help readability
    var isDefined = crel.isNode;

    t.plan(isDefined ? 2 : 1);

    t.ok(isDefined, '`isNode` is defined');

    if (isDefined) {
      // Do further tests
      t.test('Test `isNode` against various arguments', function (ts) {
          var testInputInvalid = ['', null, undefined, 'non-empty',
              42, 4.2, {'key': 'value'}, function () { return 'hi'; }];

          var testInputValid = [document,
              document.createElement('div'),
              document.createTextNode('test'),
              document.createElement('invalidtagname'),
              document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
              document.createElementNS('http://www.w3.org/1998/mathml', 'element')];

          ts.plan(testInputInvalid.lenght + testInputValid.lenght); // Test all values in arrays

          testInputInvalid.map(function (value) {
              ts.notOk(crel.isNode(value), '`' + value + '` is not a Node');
          });
          testInputValid.map(function (value) {
              ts.ok(crel.isNode(value), '`' + value + '` is a Node');
          });
      });
    }
});

test('Test that `isElement` is defined', function (t) {
    // Assign into a variable to help readability
    var isDefined = crel.isElement;

    t.plan(isDefined ? 2 : 1);

    t.ok(isDefined, '`isElement` is defined');

    if (isDefined) {
      // Do further tests
      t.test('Test `isElement` against various arguments', function (ts) {
          var testInputInvalid = ['', null, undefined, 'non-empty',
              42, 4.2, {'key': 'value'}, function () {},
              document.createTextNode('test'), document];

          var testInputValid = [document.createElement('div'),
              document.createElement('invalidtagname'),
              document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
              document.createElementNS('http://www.w3.org/1998/mathml', 'element')];

          ts.plan(testInputInvalid.lenght + testInputValid.lenght); // Test all values in arrays

          testInputInvalid.map(function (value) {
              ts.notOk(crel.isElement(value), '`' + value + '` is not an Element');
          });
          testInputValid.map(function (value) {
              ts.ok(crel.isElement(value), '`' + value + '` is an Element');
          });
      });
    }
});

// -- Test the Proxy API --
test('Test that the Proxy API is defined', function (t) {
    if (typeof Proxy === 'undefined') {
        t.plan(1)
        t.pass('Proxies are not supported in the current environment');
    } else {
        var proxyCrel = crel.proxy;

        t.plan(proxyCrel ? 2 : 1);

        t.ok(proxyCrel, 'The Proxy API is defined');

        if (proxyCrel) {
            // Do further tests
            t.test('Test that the Proxy API works', function (ts) {
                // I'm not proficient with proxies, so
                // TODO: Add #moar-tests
                ts.plan(4);

                var testElement = proxyCrel.div({'class': 'test'},
                    proxyCrel.span('test'));

                ts.equal(testElement.className, 'test');
                ts.equal(testElement.childNodes.length, 1);
                ts.equal(testElement.childNodes[0].tagName, 'SPAN');
                ts.equal(testElement.childNodes[0].textContent, 'test');
            });
        }
    }
});
<commit_msg>Tests: Add test for Crel modifying elements unprompted<commit_after>var crel = require('../'),
    test = require('tape');

// -- Test element creation --
test('Create an element with no arguments', function (t) {
    t.plan(2);

    var testElement = crel('div');

    t.ok(testElement instanceof HTMLElement,
        'element is an instance of `HTMLElement`');
    t.equal(testElement.tagName, 'DIV',
        'element is an instance of `div`');
});

test('Create an element with no arguments, using an invalid tag name', function (t) {
    t.plan(2);

    var testElement = crel('invalidtagname');

    t.ok(testElement instanceof HTMLUnknownElement,
        'element is an instance of `HTMLUnknownElement `');
    t.equal(testElement.tagName, 'INVALIDTAGNAME',
        'element is an instance of `invalidtagname`');
});

test('Crel doesn\'t modify existing elements if not instructed', function (t) {
    t.plan(1);

    var testElement = document.createElement('div');
    var testedElement = crel(testElement);

    t.ok(testElement.isSameNode(testedElement),
        'element is still the same');
});

// -- Test attribute handling --
test('Create an element with simple attributes', function (t) {
    t.plan(2);

    var testElement = crel('div', {'class': 'test', id: 'test'});

    t.equal(testElement.className, 'test',
        'element has a `test` class');
    t.equal(testElement.getAttribute('id'), 'test',
        'element has a `test` id');
});

test('Add attributes to an already existing element', function (t) {
    t.plan(2);

    var testElement = document.createElement('div');
    crel(testElement, {'class': 'test', id: 'test'});

    t.equal(testElement.className, 'test',
        'element has a `test` class');
    t.equal(testElement.getAttribute('id'), 'test',
        'element has a `test` id');
});

test('Add an `onEvent` property to an element', function (t) {
    t.plan(1);

    var testElement = crel('button', {
        onclick: function () {
            t.pass('onClick event triggered');
        }
    });

    testElement.click();
});

// -- Test child node handling --
test('Create an element with a child element', function (t) {
    t.plan(2);

    var testElement = crel('div', document.createElement('p'));

    t.equal(testElement.childNodes.length, 1,
        'element has a child element');
    t.equal(testElement.childNodes[0].tagName, 'P',
        'child element is an instance of `p`');
});

test('Create an element with a child text node', function (t) {
    t.plan(2);

    var testElement = crel('div', document.createTextNode('test'));

    t.equal(testElement.childNodes.length, 1,
        'element has a child element');
    t.equal(testElement.childNodes[0].nodeType, 3,
        'child element is a text node');
});

test('Create an element with an array of children', function (t) {
    t.plan(6);
    // TODO: make these more compact / robust
    var testArray = [document.createElement('p'), document.createTextNode('I\'m a text node!'), 'I will be a text node!'];
    var testElement = crel('div', testArray);

    t.equal(testElement.childNodes.length, 3,
        'element has three children');
    t.equal(testElement.childNodes[0].tagName, 'P');
    t.equal(testElement.childNodes[1].nodeType, 3);
    t.equal(testElement.childNodes[1].textContent, 'I\'m a text node!');
    t.equal(testElement.childNodes[2].nodeType, 3);
    t.equal(testElement.childNodes[2].textContent, 'I will be a text node!');
});

test('Create an element with a deep array of children', function (t) {
    t.plan(6);
    // TODO: make these more compact / robust
    var testArray = [document.createElement('p'), document.createTextNode('I\'m a text node!'), 'I will be a text node!'];
    var testElement = crel('div', [[testArray]]);

    t.equal(testElement.childNodes.length, 3,
        'element has three children');
    t.equal(testElement.childNodes[0].tagName, 'P');
    t.equal(testElement.childNodes[1].nodeType, 3);
    t.equal(testElement.childNodes[1].textContent, 'I\'m a text node!');
    t.equal(testElement.childNodes[2].nodeType, 3);
    t.equal(testElement.childNodes[2].textContent, 'I will be a text node!');
});

// -- Test exposed methods --
test('Test that `isNode` is defined', function (t) {
    // Assign into a variable to help readability
    var isDefined = crel.isNode;

    t.plan(isDefined ? 2 : 1);

    t.ok(isDefined, '`isNode` is defined');

    if (isDefined) {
      // Do further tests
      t.test('Test `isNode` against various arguments', function (ts) {
          var testInputInvalid = ['', null, undefined, 'non-empty',
              42, 4.2, {'key': 'value'}, function () { return 'hi'; }];

          var testInputValid = [document,
              document.createElement('div'),
              document.createTextNode('test'),
              document.createElement('invalidtagname'),
              document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
              document.createElementNS('http://www.w3.org/1998/mathml', 'element')];

          ts.plan(testInputInvalid.lenght + testInputValid.lenght); // Test all values in arrays

          testInputInvalid.map(function (value) {
              ts.notOk(crel.isNode(value), '`' + value + '` is not a Node');
          });
          testInputValid.map(function (value) {
              ts.ok(crel.isNode(value), '`' + value + '` is a Node');
          });
      });
    }
});

test('Test that `isElement` is defined', function (t) {
    // Assign into a variable to help readability
    var isDefined = crel.isElement;

    t.plan(isDefined ? 2 : 1);

    t.ok(isDefined, '`isElement` is defined');

    if (isDefined) {
      // Do further tests
      t.test('Test `isElement` against various arguments', function (ts) {
          var testInputInvalid = ['', null, undefined, 'non-empty',
              42, 4.2, {'key': 'value'}, function () {},
              document.createTextNode('test'), document];

          var testInputValid = [document.createElement('div'),
              document.createElement('invalidtagname'),
              document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
              document.createElementNS('http://www.w3.org/1998/mathml', 'element')];

          ts.plan(testInputInvalid.lenght + testInputValid.lenght); // Test all values in arrays

          testInputInvalid.map(function (value) {
              ts.notOk(crel.isElement(value), '`' + value + '` is not an Element');
          });
          testInputValid.map(function (value) {
              ts.ok(crel.isElement(value), '`' + value + '` is an Element');
          });
      });
    }
});

// -- Test the Proxy API --
test('Test that the Proxy API is defined', function (t) {
    if (typeof Proxy === 'undefined') {
        t.plan(1)
        t.pass('Proxies are not supported in the current environment');
    } else {
        var proxyCrel = crel.proxy;

        t.plan(proxyCrel ? 2 : 1);

        t.ok(proxyCrel, 'The Proxy API is defined');

        if (proxyCrel) {
            // Do further tests
            t.test('Test that the Proxy API works', function (ts) {
                // I'm not proficient with proxies, so
                // TODO: Add #moar-tests
                ts.plan(4);

                var testElement = proxyCrel.div({'class': 'test'},
                    proxyCrel.span('test'));

                ts.equal(testElement.className, 'test');
                ts.equal(testElement.childNodes.length, 1);
                ts.equal(testElement.childNodes[0].tagName, 'SPAN');
                ts.equal(testElement.childNodes[0].textContent, 'test');
            });
        }
    }
});
<|endoftext|>


<commit_before>/*
 * Copyright 2013-2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

/**
 * @module settings/js/widgets/view-widget
 */
define([
    'settings/js/widgets/aci-widget',
    'text!settings/templates/widgets/view-widget.html'
], function(AciWidget, template) {
    /**
     * @typedef ViewWidgetStrings
     * @desc Extends AciWidgetStrings
     * @property {string} referenceFieldLabel The label of the reference field dropdown
     * @property {string} referenceFieldBlank The error message to display when the reference field is blank
     * @property {string} referenceFieldPlaceholder Placeholder for the reference field input
     * @property {string} connector Label for the connector section
     * @property {string} viewingMode Label for the viewing mode dropdown
     */
    /**
     * @typedef ViewWidgetOptions
     * @desc Extends AciWidgetOptions
     * @property {ViewWidgetStrings} strings Strings for the widget
     */
    /**
     * @name module:settings/js/widgets/view-widget.ViewWidget
     * @desc Widget for configuring a View server
     * @constructor
     * @extends module:settings/js/widgets/aci-widget.AciWidget
     */
    return AciWidget.extend({

        /**
         * @typedef ViewWidgetTemplateParameters
         * @property {ViewWidgetStrings} strings Strings for the template
         */
        /**
         * @callback module:settings/js/widgets/view-widget.ViewWidget~ViewTemplate
         * @param {ViewWidgetTemplateParameters} parameters
         */
        /**
         * @desc Base template for the widget. Override if using Bootstrap 3
         * @type module:settings/js/widgets/view-widget.ViewWidget~ViewTemplate
         */
        viewTemplate: _.template(template),

        /**
         * @desc Renders the widget
         */
        render: function() {
            AciWidget.prototype.render.call(this);

            this.$('button[name="validate"]').parent().before(this.viewTemplate({
                strings: this.strings
            }));

            this.$('.connector-container').append(this.aciTemplate({
                strings: this.strings
            }));

            this.$modeSelect = this.$('.viewing-mode-input');

            this.$referenceField = this.$('[name="referenceField"]');

            // make sure we don't get the ones for connectors
            this.$host = this.$('input[name=host]').eq(0);
            this.$port = this.$('input[name=port]').eq(0);
            this.$protocol = this.$('select[name=protocol]').eq(0);

            this.$connectorHost = this.$('.connector-container input[name=host]');
            this.$connectorPort = this.$('.connector-container input[name=port]');
            this.$connectorProtocol = this.$('.connector-container select[name=protocol]');

            var toggleInputs = _.bind(function () {
                this.$('.connector-container').toggle(this.$modeSelect.val() === 'CONNECTOR');
                this.$('.field-form-group').toggle(this.$modeSelect.val() === 'FIELD');
            }, this);

            this.$modeSelect.on('input', toggleInputs);

            toggleInputs();
        },

        /**
         * @desc Updates the widget with new configuration
         * @param config The new config for the wizard
         */
        updateConfig: function(config) {
            AciWidget.prototype.updateConfig.apply(this, arguments);

            this.$modeSelect.val(config.viewingMode);
            this.$referenceField.val(config.referenceField);

            this.$connectorHost.val(config.connector.host);
            this.$connectorPort.val(config.connector.port);
            this.$connectorProtocol.val(config.connector.protocol);

            this.productTypeRegex = config.connector.productTypeRegex;
        },

        /**
         * @desc Returns the configuration for the widget
         * @returns The configuration for the widget
         */
        getConfig: function() {
            var config = AciWidget.prototype.getConfig.call(this);

            return _.extend({
                referenceField: this.$referenceField.val(),
                viewingMode: this.$modeSelect.val(),
                connector: {
                    host: this.$connectorHost.val(),
                    port: this.$connectorPort.val(),
                    productTypeRegex: this.productTypeRegex,
                    protocol: this.$connectorProtocol.val()
                }
            }, config);
        },

        /**
         * @desc Handles the results of server side validation
         */
        handleValidation: function(config, response) {
            if (_.isEqual(config, this.lastValidationConfig)) {
                if (response.data && response.data.validation === 'CONNECTOR_VALIDATION_ERROR') {
                    this.updateInputValidation(this.$('.connector-container .form-group'), false, this.getValidationFailureMessage(response.data.connectorValidation))
                }
                else if(response.data === "REFERENCE_FIELD_BLANK") {
                    this.updateInputValidation(this.$referenceField, false, this.strings.referenceFieldBlank);
                }
                else {
                    AciWidget.prototype.handleValidation.apply(this, arguments);
                }
            }
        },

        /**
         * @desc Validates the widget and applies formatting appropriately
         * @returns {boolean} False if
         *

         *
 Viewing mode is Reference, and the reference field is blank
         *
 Viewing mode is connector, and the connector host is blank or the port number is invalid
         *
 The view server settings are invalid
         *

         */
        validateInputs: function() {
            var isValid = AciWidget.prototype.validateInputs.apply(this, arguments);

            if (isValid) {
                var mode = this.$modeSelect.val();

                if (mode === 'FIELD') {
                    if (this.$referenceField.val() === '') {
                        this.updateInputValidation(this.$referenceField, false);
                        return false;
                    }
                }
                else if (mode === 'CONNECTOR') {
                    if (this.$connectorHost.val() === '') {
                        this.updateInputValidation(this.$connectorHost, false, this.strings.validateHostBlank);
                        return false;
                    }

                    var port = Number(this.$connectorPort.val());

                    if (port <= 0 || port > 65535) {
                        this.updateInputValidation(this.$connectorPort, false, this.strings.validatePortInvalid);
                        return false;
                    }

                    return true;
                }
            }

            return isValid;
        }
    });

});<commit_msg>[CCUK-2997] Toggle widget when updating config<commit_after>/*
 * Copyright 2013-2016 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

/**
 * @module settings/js/widgets/view-widget
 */
define([
    'settings/js/widgets/aci-widget',
    'text!settings/templates/widgets/view-widget.html'
], function(AciWidget, template) {
    /**
     * @typedef ViewWidgetStrings
     * @desc Extends AciWidgetStrings
     * @property {string} referenceFieldLabel The label of the reference field dropdown
     * @property {string} referenceFieldBlank The error message to display when the reference field is blank
     * @property {string} referenceFieldPlaceholder Placeholder for the reference field input
     * @property {string} connector Label for the connector section
     * @property {string} viewingMode Label for the viewing mode dropdown
     */
    /**
     * @typedef ViewWidgetOptions
     * @desc Extends AciWidgetOptions
     * @property {ViewWidgetStrings} strings Strings for the widget
     */
    /**
     * @name module:settings/js/widgets/view-widget.ViewWidget
     * @desc Widget for configuring a View server
     * @constructor
     * @extends module:settings/js/widgets/aci-widget.AciWidget
     */
    return AciWidget.extend({

        /**
         * @typedef ViewWidgetTemplateParameters
         * @property {ViewWidgetStrings} strings Strings for the template
         */
        /**
         * @callback module:settings/js/widgets/view-widget.ViewWidget~ViewTemplate
         * @param {ViewWidgetTemplateParameters} parameters
         */
        /**
         * @desc Base template for the widget. Override if using Bootstrap 3
         * @type module:settings/js/widgets/view-widget.ViewWidget~ViewTemplate
         */
        viewTemplate: _.template(template),

        /**
         * @desc Renders the widget
         */
        render: function() {
            AciWidget.prototype.render.call(this);

            this.$('button[name="validate"]').parent().before(this.viewTemplate({
                strings: this.strings
            }));

            this.$('.connector-container').append(this.aciTemplate({
                strings: this.strings
            }));

            this.$modeSelect = this.$('.viewing-mode-input');

            this.$referenceField = this.$('[name="referenceField"]');

            // make sure we don't get the ones for connectors
            this.$host = this.$('input[name=host]').eq(0);
            this.$port = this.$('input[name=port]').eq(0);
            this.$protocol = this.$('select[name=protocol]').eq(0);

            this.$connectorHost = this.$('.connector-container input[name=host]');
            this.$connectorPort = this.$('.connector-container input[name=port]');
            this.$connectorProtocol = this.$('.connector-container select[name=protocol]');

            this.$modeSelect.on('input', _.bind(this.toggleInputs, this));
        },

        toggleInputs: function() {
            this.$('.connector-container').toggle(this.$modeSelect.val() === 'CONNECTOR');
            this.$('.field-form-group').toggle(this.$modeSelect.val() === 'FIELD');
        },

        /**
         * @desc Updates the widget with new configuration
         * @param config The new config for the wizard
         */
        updateConfig: function(config) {
            AciWidget.prototype.updateConfig.apply(this, arguments);

            this.$modeSelect.val(config.viewingMode);
            this.$referenceField.val(config.referenceField);

            this.$connectorHost.val(config.connector.host);
            this.$connectorPort.val(config.connector.port);
            this.$connectorProtocol.val(config.connector.protocol);

            this.productTypeRegex = config.connector.productTypeRegex;

            this.toggleInputs();
        },

        /**
         * @desc Returns the configuration for the widget
         * @returns The configuration for the widget
         */
        getConfig: function() {
            var config = AciWidget.prototype.getConfig.call(this);

            return _.extend({
                referenceField: this.$referenceField.val(),
                viewingMode: this.$modeSelect.val(),
                connector: {
                    host: this.$connectorHost.val(),
                    port: this.$connectorPort.val(),
                    productTypeRegex: this.productTypeRegex,
                    protocol: this.$connectorProtocol.val()
                }
            }, config);
        },

        /**
         * @desc Handles the results of server side validation
         */
        handleValidation: function(config, response) {
            if (_.isEqual(config, this.lastValidationConfig)) {
                if (response.data && response.data.validation === 'CONNECTOR_VALIDATION_ERROR') {
                    this.updateInputValidation(this.$('.connector-container .form-group'), false, this.getValidationFailureMessage(response.data.connectorValidation))
                }
                else if(response.data === "REFERENCE_FIELD_BLANK") {
                    this.updateInputValidation(this.$referenceField, false, this.strings.referenceFieldBlank);
                }
                else {
                    AciWidget.prototype.handleValidation.apply(this, arguments);
                }
            }
        },

        /**
         * @desc Validates the widget and applies formatting appropriately
         * @returns {boolean} False if
         *

         *
 Viewing mode is Reference, and the reference field is blank
         *
 Viewing mode is connector, and the connector host is blank or the port number is invalid
         *
 The view server settings are invalid
         *

         */
        validateInputs: function() {
            var isValid = AciWidget.prototype.validateInputs.apply(this, arguments);

            if (isValid) {
                var mode = this.$modeSelect.val();

                if (mode === 'FIELD') {
                    if (this.$referenceField.val() === '') {
                        this.updateInputValidation(this.$referenceField, false);
                        return false;
                    }
                }
                else if (mode === 'CONNECTOR') {
                    if (this.$connectorHost.val() === '') {
                        this.updateInputValidation(this.$connectorHost, false, this.strings.validateHostBlank);
                        return false;
                    }

                    var port = Number(this.$connectorPort.val());

                    if (port <= 0 || port > 65535) {
                        this.updateInputValidation(this.$connectorPort, false, this.strings.validatePortInvalid);
                        return false;
                    }

                    return true;
                }
            }

            return isValid;
        }
    });

});<|endoftext|>


<commit_before>var chai = require('chai');
var muk = require('muk');
var expect = chai.expect;
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var log = require('../');
var utils = require('../lib/utils');

describe('base', function () {
  describe('case', function () {
    before(function () {
      muk(mkdirp, 'sync', function (){});
      muk(fs, 'createWriteStream', function (path) {
        return {
          write: function (content) {
            console.log('muk');
            return {
              content: content,
              path: path
            };
          }
        };
      });
      muk(utils, 'getIP', function () {
        return '192.168.999.999';
      });
      muk(Date, 'now', function () {
        return 1393810654681;
      });
    });
    after(function () {
      muk.restore();
    });
    it('1', function () {
      var Logger = log.Logger;
      var dir = path.join(__dirname, '../lib/log/production.log');
      var content = {
        "@timestamp":"2014-03-03T09:37:34+08:00",
        "@source": "192.168.999.999",
        "@fields": {
          "fromtype": "myApp",
          "totype": "25",
          "interface": "/interface",
          "param": "foo=bar&abc=baz"
        },
      };
      var result = Logger().to(25).interface('/interface').param({
        foo: 'bar',
        abc: 'baz'
      }).done();
      expect(result.path).to.be.deep.equal(dir);
      expect(JSON.parse(result.content)).to.be.deep.equal(content);
    });
  });
});
<commit_msg>update test<commit_after>var chai = require('chai');
var muk = require('muk');
var expect = chai.expect;
var fs = require('fs');
var path = require('path');
var mkdirp = require('mkdirp');
var log = require('../');
var utils = require('../lib/utils');

describe('base', function () {
  describe('case', function () {
    before(function () {
      muk(mkdirp, 'sync', function (){});
      muk(fs, 'createWriteStream', function (path) {
        return {
          write: function (content) {
            console.log('muk');
            return {
              content: content,
              path: path
            };
          }
        };
      });
      muk(utils, 'getIP', function () {
        return '192.168.999.999';
      });
      muk(Date, 'now', function () {
        return 1393810654681;
      });
    });
    after(function () {
      muk.restore();
    });
    it('mini', function () {
      var Logger = log.Logger;
      var dir = path.join(__dirname, '../lib/log/production.log');
      var content = {
        "@timestamp":"2014-03-03T09:37:34+08:00",
        "@source": "192.168.999.999",
        "@fields": {
          "fromtype": "myApp",
          "totype": "myApp"
        },
      };
      var result = Logger().done();
      expect(result.path).to.be.deep.equal(dir);
      expect(JSON.parse(result.content)).to.be.deep.equal(content);
    });
    it('with to, interface, param', function () {
      var Logger = log.Logger;
      var dir = path.join(__dirname, '../lib/log/production.log');
      var content = {
        "@timestamp":"2014-03-03T09:37:34+08:00",
        "@source": "192.168.999.999",
        "@fields": {
          "fromtype": "myApp",
          "totype": "25",
          "interface": "/interface",
          "param": "foo=bar&abc=baz"
        },
      };
      var result = Logger().to(25).interface('/interface').param({
        foo: 'bar',
        abc: 'baz'
      }).done();
      expect(result.path).to.be.deep.equal(dir);
      expect(JSON.parse(result.content)).to.be.deep.equal(content);
    });
    it('with string param', function () {
      var Logger = log.Logger;
      var dir = path.join(__dirname, '../lib/log/production.log');
      var content = {
        "@timestamp":"2014-03-03T09:37:34+08:00",
        "@source": "192.168.999.999",
        "@fields": {
          "fromtype": "myApp",
          "totype": "25",
          "interface": "/interface",
          "param": "check: it out"
        },
      };
      var result = Logger().to(25).interface('/interface').param('check: it out').done();
      expect(result.path).to.be.deep.equal(dir);
      expect(JSON.parse(result.content)).to.be.deep.equal(content);
    });
    it('with result', function () {
      var Logger = log.Logger;
      var dir = path.join(__dirname, '../lib/log/production.log');
      var content = {
        "@timestamp":"2014-03-03T09:37:34+08:00",
        "@source": "192.168.999.999",
        "@fields": {
          "fromtype": "myApp",
          "totype": "25",
          "interface": "/interface",
          "param": "foo=bar&abc=baz",
          "result": "{\"foo\":\"bar\"}"
        },
      };
      var result = Logger().to(25).interface('/interface').param({
        foo: 'bar',
        abc: 'baz'
      }).result({foo: "bar"}).done();
      expect(result.path).to.be.deep.equal(dir);
      expect(JSON.parse(result.content)).to.be.deep.equal(content);
    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var _ = require('lodash');
var fs = require('fs');
var gulp = require('gulp');
var gutil = require('gulp-util');
var path = require('path');
var test = require('tap').test;
var i18nextScanner = require('../');
var hash = require('sha1');
var table = require('text-table');

var customTransform = function _transform(file, enc, done) {
    var parser = this.parser;
    var extname = path.extname(file.path);
    var content = fs.readFileSync(file.path, enc);
    var parseResults = [
        ['Key', 'Value']
    ];

    gutil.log('parsing ' + JSON.stringify(file.relative) + ':');

    // Using i18next-text
    (function() {
        var results = content.match(/i18n\._\(("[^"]*"|'[^']*')\s*[\,\)]/igm) || '';
        _.each(results, function(result) {
            var key, value;
            var r = result.match(/i18n\._\(("[^"]*"|'[^']*')/);

            if (r) {
                value = _.trim(r[1], '\'"');

                // Replace double backslash with single backslash
                value = value.replace(/\\\\/g, '\\');
                value = value.replace(/\\\'/, '\'');

                key = hash(value); // returns a hash value as its default key

                parser.parse(key, value);
                parseResults.push([key, _.isUndefined(value) ? '' : value ]);
            }
        });
    }());

    // i18n function helper
    (function() {
        var results = content.match(/{{i18n\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')?([^}]*)}}/gm) || [];
        _.each(results, function(result) {
            var key, value;
            var r = result.match(/{{i18n\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')?([^}]*)}}/m) || [];

            if ( ! _.isUndefined(r[1])) {
                value = _.trim(r[1], '\'"');

                // Replace double backslash with single backslash
                value = value.replace(/\\\\/g, '\\');
                value = value.replace(/\\\'/, '\'');
            }

            var params = parser.parseHashArguments(r[2]);
            if (_.has(params, 'defaultKey')) {
                key = params['defaultKey'];
            }

            if (_.isUndefined(key) && _.isUndefined(value)) {
                return;
            }

            if (_.isUndefined(key)) {
                key = hash(value); // returns a hash value as its default key
            }

            parser.parse(key, value);
            parseResults.push([key, _.isUndefined(value) ? '' : value ]);
        });
    }());

    // i18n block helper
    (function() {
        var results = content.match(/{{#i18n\s*([^}]*)}}((?:(?!{{\/i18n}})(?:.|\n))*){{\/i18n}}/gm) || [];
        _.each(results, function(result) {
            var key, value;
            var r = result.match(/{{#i18n\s*([^}]*)}}((?:(?!{{\/i18n}})(?:.|\n))*){{\/i18n}}/m) || [];

            if ( ! _.isUndefined(r[2])) {
                value = _.trim(r[2], '\'"');
            }

            if (_.isUndefined(value)) {
                return;
            }

            key = hash(value); // returns a hash value as its default key

            parser.parse(key, value);
            parseResults.push([key, _.isUndefined(value) ? '' : value ]);
        });
    }());

    if (_.size(parseResults) > 1) {
        gutil.log('result of ' + JSON.stringify(file.relative) + ':\n' + table(parseResults, {'hsep': ' | '}));
    }

    done();
};

test('setup', function(t) {
    t.end();
});

test('teardown', function(t) {
    t.end();
});

test('Gulp usage', function(t) {
    var options = {
        lngs: ['en','de'],
        defaultValue: '__STRING_NOT_TRANSLATED__',
        resGetPath: 'i18n/__lng__/__ns__.json',
        resSetPath: 'i18n/__lng__/__ns__.savedMissing.json',
        nsseparator: ':', // namespace separator
        keyseparator: '.', // key separator
        interpolationPrefix: '__',
        interpolationSuffix: '__',
        ns: {
            namespaces: [
                'translation',
                'locale'
            ],
            defaultNs: 'translation'
        }
    };
    gulp.src('test/fixtures/modules/**/*.{js,hbs}')
        .pipe(i18nextScanner(options, customTransform))
        .pipe(gulp.dest('./output'))
        .on('end', function() {
            t.end();
        });
});
<commit_msg>Update test script<commit_after>'use strict';

var _ = require('lodash');
var fs = require('fs');
var gulp = require('gulp');
var gutil = require('gulp-util');
var path = require('path');
var test = require('tap').test;
var i18nextScanner = require('../');
var hash = require('sha1');
var table = require('text-table');

var customTransform = function _transform(file, enc, done) {
    var parser = this.parser;
    var extname = path.extname(file.path);
    var content = fs.readFileSync(file.path, enc);
    var results = [
        ['Key', 'Value']
    ];

    gutil.log('parsing ' + JSON.stringify(file.relative) + ':');

    // Using i18next-text
    (function() {
        var results = content.match(/i18n\._\(("[^"]*"|'[^']*')\s*[\,\)]/igm) || '';
        _.each(results, function(result) {
            var key, value;
            var r = result.match(/i18n\._\(("[^"]*"|'[^']*')/);

            if (r) {
                value = _.trim(r[1], '\'"');

                // Replace double backslash with single backslash
                value = value.replace(/\\\\/g, '\\');
                value = value.replace(/\\\'/, '\'');

                key = hash(value); // returns a hash value as its default key

                parser.parse(key, value);
                results.push([key, _.isUndefined(value) ? parser.options.defaultValue : value ]);
            }
        });
    }());

    // i18n function helper
    (function() {
        var results = content.match(/{{i18n\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')?([^}]*)}}/gm) || [];
        _.each(results, function(result) {
            var key, value;
            var r = result.match(/{{i18n\s+("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')?([^}]*)}}/m) || [];

            if ( ! _.isUndefined(r[1])) {
                value = _.trim(r[1], '\'"');

                // Replace double backslash with single backslash
                value = value.replace(/\\\\/g, '\\');
                value = value.replace(/\\\'/, '\'');
            }

            var params = parser.parseHashArguments(r[2]);
            if (_.has(params, 'defaultKey')) {
                key = params['defaultKey'];
            }

            if (_.isUndefined(key) && _.isUndefined(value)) {
                return;
            }

            if (_.isUndefined(key)) {
                key = hash(value); // returns a hash value as its default key
            }

            parser.parse(key, value);
            results.push([key, _.isUndefined(value) ? parser.options.defaultValue : value ]);
        });
    }());

    // i18n block helper
    (function() {
        var results = content.match(/{{#i18n\s*([^}]*)}}((?:(?!{{\/i18n}})(?:.|\n))*){{\/i18n}}/gm) || [];
        _.each(results, function(result) {
            var key, value;
            var r = result.match(/{{#i18n\s*([^}]*)}}((?:(?!{{\/i18n}})(?:.|\n))*){{\/i18n}}/m) || [];

            if ( ! _.isUndefined(r[2])) {
                value = _.trim(r[2], '\'"');
            }

            if (_.isUndefined(value)) {
                return;
            }

            key = hash(value); // returns a hash value as its default key

            parser.parse(key, value);
            results.push([key, _.isUndefined(value) ? parser.options.defaultValue : value ]);
        });
    }());

    if (_.size(results) > 1) {
        gutil.log('result of ' + JSON.stringify(file.relative) + ':\n' + table(results, {'hsep': ' | '}));
    }

    done();
};

test('setup', function(t) {
    t.end();
});

test('teardown', function(t) {
    t.end();
});

test('Gulp usage', function(t) {
    var options = {
        lngs: ['en','de'],
        defaultValue: '__STRING_NOT_TRANSLATED__',
        resGetPath: 'i18n/__lng__/__ns__.json',
        resSetPath: 'i18n/__lng__/__ns__.savedMissing.json',
        nsseparator: ':', // namespace separator
        keyseparator: '.', // key separator
        interpolationPrefix: '__',
        interpolationSuffix: '__',
        ns: {
            namespaces: [
                'translation',
                'locale'
            ],
            defaultNs: 'translation'
        }
    };
    gulp.src('test/fixtures/modules/**/*.{js,hbs}')
        .pipe(i18nextScanner(options, customTransform))
        .pipe(gulp.dest('./output'))
        .on('end', function() {
            t.end();
        });
});
<|endoftext|>


<commit_before>var assert = require('assert');
describe('Array', function () {
	describe('#indexOf()', function () {
		it('should return -1 when the value is not present', function () {
			assert.equal(-1, [1, 2, 3].indexOf(4));
		});
	});
	describe('#length', function () {
		it('Should return 3 when array length is 3', function () {
			assert.equal(3, [1, 2, 3].length);
		});
	});
});<commit_msg>[tests] Add tests<commit_after>import assert from 'assert';
import jsdom from 'mocha-jsdom';
import { SimpleFormCreatorWrapper } from '../src/index.js';

describe('Simple Form Creator', function () {
	jsdom();

	it('should create an expected DOM node', function () {
		const simpleform = SimpleFormCreatorWrapper({ 'formId': 'randomId' });
		assert.equal((simpleform.create()).outerHTML, '<form id="randomId" action="" method="post"></form>');
	});

	it('should return a string', function () {
		const simpleform = SimpleFormCreatorWrapper({});
		assert.equal(typeof simpleform.getRandomFormId(), 'string');
	});
});
<|endoftext|>


<commit_before>var test = require("tape")
var setTimeout = require("timers").setTimeout

var now = require("../index")
var seeded = require("../seed")

test("date", function (assert) {
    var ts = now()
    var ts2 = Date.now()
    assert.equal(ts, ts2)
    assert.end()
})

test("seeded", function (assert) {
    var time = seeded(40)
    var ts = time()

    within(assert, time(), 40, 5)
    setTimeout(function () {
        within(assert, time(), 90, 10)
        assert.end()
    }, 50)
})

function within(assert, a, b, offset) {
    assert.ok(a + offset > b)
    assert.ok(a - offset < b)
}
<commit_msg>make time tests deterministic<commit_after>var test = require("tape")
var setTimeout = require("timers").setTimeout

var now = require("../index")
var seeded = require("../seed")

test("date", function (assert) {
    var before = new Date().getTime()
    var ts = now()
    var after = new Date().getTime()
    assert.ok(before <= ts)
    assert.ok(after >= ts)
    assert.end()
})

test("seeded", function (assert) {
    var before = now()
    var time = seeded(40)
    var after = now()

    var bts = now()
    var ts = time()
    var ats = now()

    assert.ok(ts >= bts - before + 40)
    assert.ok(ts <= ats - after + 40)

    setTimeout(function () {
        var bts = now()
        var ts = time()
        var ats = now()

        assert.ok(ts >= bts - before + 40)
        assert.ok(ts <= ats - after + 40)

        assert.end()
    }, 50)
})
<|endoftext|>


<commit_before>/* Copyright 2017 Mozilla Foundation
 *
 * 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.
 */

import { BaseViewer } from './base_viewer';
import { shadow } from 'pdfjs-lib';

class PDFSinglePageViewer extends BaseViewer {
  constructor(options) {
    super(options);

    this.eventBus.on('pagesinit', (evt) => {
      // Since the pages are placed in a `DocumentFragment`, make sure that
      // the current page becomes visible upon loading of the document.
      this._ensurePageViewVisible();
    });
  }

  get _setDocumentViewerElement() {
    // Since we only want to display *one* page at a time when using the
    // `PDFSinglePageViewer`, we cannot append them to the `viewer` DOM element.
    // Instead, they are placed in a `DocumentFragment`, and only the current
    // page is displayed in the viewer (refer to `this._ensurePageViewVisible`).
    return shadow(this, '_setDocumentViewerElement', this._shadowViewer);
  }

  _resetView() {
    super._resetView();
    this._previousPageNumber = 1;
    this._shadowViewer = document.createDocumentFragment();
  }

  _ensurePageViewVisible() {
    let pageView = this._pages[this._currentPageNumber - 1];
    let previousPageView = this._pages[this._previousPageNumber - 1];

    let viewerNodes = this.viewer.childNodes;
    switch (viewerNodes.length) {
      case 0: // Should *only* occur on initial loading.
        this.viewer.appendChild(pageView.div);
        break;
      case 1: // The normal page-switching case.
        if (viewerNodes[0] !== previousPageView.div) {
          throw new Error(
            '_ensurePageViewVisible: Unexpected previously visible page.');
        }
        if (pageView === previousPageView) {
          break; // The correct page is already visible.
        }
        // Switch visible pages, and reset the viewerContainer scroll position.
        this._shadowViewer.appendChild(previousPageView.div);
        this.viewer.appendChild(pageView.div);

        this.container.scrollTop = 0;
        break;
      default:
        throw new Error(
          '_ensurePageViewVisible: Only one page should be visible at a time.');
    }
    this._previousPageNumber = this._currentPageNumber;
  }

  _scrollUpdate() {
    if (this._updateScrollDown) {
      this._updateScrollDown();
    }
    super._scrollUpdate();
  }

  _scrollIntoView({ pageDiv, pageSpot = null, pageNumber = null, }) {
    if (pageNumber) { // Ensure that `this._currentPageNumber` is correct.
      this._setCurrentPageNumber(pageNumber);
    }
    let scrolledDown = this._currentPageNumber >= this._previousPageNumber;
    let previousLocation = this._location;
    this._ensurePageViewVisible();

    super._scrollIntoView({ pageDiv, pageSpot, pageNumber, });

    // Since scrolling is tracked using `requestAnimationFrame`, update the
    // scroll direction during the next `this._scrollUpdate` invocation.
    this._updateScrollDown = () => {
      this.scroll.down = scrolledDown;
      delete this._updateScrollDown;
    };
    // If the scroll position doesn't change as a result of the `scrollIntoView`
    // call, ensure that rendering always occurs to avoid showing a blank page.
    setTimeout(() => {
      if (this._location === previousLocation) {
        if (this._updateScrollDown) {
          this._updateScrollDown();
        }
        this.update();
      }
    }, 0);
  }

  _getVisiblePages() {
    return this._getCurrentVisiblePage();
  }

  _updateHelper(visiblePages) { }

  get _isScrollModeHorizontal() {
    // The Scroll/Spread modes are never used in `PDFSinglePageViewer`.
    return shadow(this, '_isScrollModeHorizontal', false);
  }

  _updateScrollMode() { }

  _updateSpreadMode() { }
}

export {
  PDFSinglePageViewer,
};
<commit_msg>Try to simplify the `PDFSinglePageViewer._scrollIntoView` method slightly, by unconditionally ensuring that rendering always occurs<commit_after>/* Copyright 2017 Mozilla Foundation
 *
 * 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.
 */

import { BaseViewer } from './base_viewer';
import { shadow } from 'pdfjs-lib';

class PDFSinglePageViewer extends BaseViewer {
  constructor(options) {
    super(options);

    this.eventBus.on('pagesinit', (evt) => {
      // Since the pages are placed in a `DocumentFragment`, make sure that
      // the current page becomes visible upon loading of the document.
      this._ensurePageViewVisible();
    });
  }

  get _setDocumentViewerElement() {
    // Since we only want to display *one* page at a time when using the
    // `PDFSinglePageViewer`, we cannot append them to the `viewer` DOM element.
    // Instead, they are placed in a `DocumentFragment`, and only the current
    // page is displayed in the viewer (refer to `this._ensurePageViewVisible`).
    return shadow(this, '_setDocumentViewerElement', this._shadowViewer);
  }

  _resetView() {
    super._resetView();
    this._previousPageNumber = 1;
    this._shadowViewer = document.createDocumentFragment();
    this._updateScrollDown = null;
  }

  _ensurePageViewVisible() {
    let pageView = this._pages[this._currentPageNumber - 1];
    let previousPageView = this._pages[this._previousPageNumber - 1];

    let viewerNodes = this.viewer.childNodes;
    switch (viewerNodes.length) {
      case 0: // Should *only* occur on initial loading.
        this.viewer.appendChild(pageView.div);
        break;
      case 1: // The normal page-switching case.
        if (viewerNodes[0] !== previousPageView.div) {
          throw new Error(
            '_ensurePageViewVisible: Unexpected previously visible page.');
        }
        if (pageView === previousPageView) {
          break; // The correct page is already visible.
        }
        // Switch visible pages, and reset the viewerContainer scroll position.
        this._shadowViewer.appendChild(previousPageView.div);
        this.viewer.appendChild(pageView.div);

        this.container.scrollTop = 0;
        break;
      default:
        throw new Error(
          '_ensurePageViewVisible: Only one page should be visible at a time.');
    }
    this._previousPageNumber = this._currentPageNumber;
  }

  _scrollUpdate() {
    if (this._updateScrollDown) {
      this._updateScrollDown();
    }
    super._scrollUpdate();
  }

  _scrollIntoView({ pageDiv, pageSpot = null, pageNumber = null, }) {
    if (pageNumber) { // Ensure that `this._currentPageNumber` is correct.
      this._setCurrentPageNumber(pageNumber);
    }
    const scrolledDown = this._currentPageNumber >= this._previousPageNumber;

    this._ensurePageViewVisible();
    // Ensure that rendering always occurs, to avoid showing a blank page,
    // even if the current position doesn't change when the page is scrolled.
    this.update();

    super._scrollIntoView({ pageDiv, pageSpot, pageNumber, });

    // Since scrolling is tracked using `requestAnimationFrame`, update the
    // scroll direction during the next `this._scrollUpdate` invocation.
    this._updateScrollDown = () => {
      this.scroll.down = scrolledDown;
      this._updateScrollDown = null;
    };
  }

  _getVisiblePages() {
    return this._getCurrentVisiblePage();
  }

  _updateHelper(visiblePages) { }

  get _isScrollModeHorizontal() {
    // The Scroll/Spread modes are never used in `PDFSinglePageViewer`.
    return shadow(this, '_isScrollModeHorizontal', false);
  }

  _updateScrollMode() { }

  _updateSpreadMode() { }
}

export {
  PDFSinglePageViewer,
};
<|endoftext|>


<commit_before>define(function() {

  // Export
  return function(Prism) {

    Prism.languages.coffeescript = Prism.languages.extend('javascript', {
      'block-comment': /([#]{3}\s*\r?\n(.*\s*\r*\n*)\s*?\r?\n[#]{3})/g,
      'comment': /(\s|^)([#]{1}[^#^\r^\n]{2,}?(\r?\n|$))/g,
      'keyword': /\b(this|window|delete|class|extends|namespace|extend|ar|let|if|else|while|do|for|each|of|return|in|instanceof|new|with|typeof|try|catch|finally|null|undefined|break|continue)\b/g,
    });

    Prism.languages.insertBefore('coffeescript', 'keyword', {
      'function': {
        pattern: /[a-z|A-z]+\s*[:|=]\s*(\([.|a-z\s|,|:|{|}|\"|\'|=]*\))?\s*->/gi,
        inside: {
          'function-name': /[_?a-z-|A-Z-]+(\s*[:|=])| @[_?$?a-z-|A-Z-]+(\s*)| /g,
          'operator': /[-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\//g
        }
      },

      'class-name': {
        pattern: /(class\s+)[a-z-]+[\.a-z]*\s/gi,
        lookbehind: true
      },

      'attr-name': /[_?a-z-|A-Z-]+(\s*:)| @[_?$?a-z-|A-Z-]+(\s*)| /g
    });

  };

});
<commit_msg>Fix indentation of the Coffee Script grammar<commit_after>define(function() {
  return function(Prism) {
    Prism.languages.coffeescript = Prism.languages.extend('javascript', {
      'block-comment': /([#]{3}\s*\r?\n(.*\s*\r*\n*)\s*?\r?\n[#]{3})/g,
      'comment': /(\s|^)([#]{1}[^#^\r^\n]{2,}?(\r?\n|$))/g,
      'keyword': /\b(this|window|delete|class|extends|namespace|extend|ar|let|if|else|while|do|for|each|of|return|in|instanceof|new|with|typeof|try|catch|finally|null|undefined|break|continue)\b/g,
    });

    Prism.languages.insertBefore('coffeescript', 'keyword', {
      'function': {
        pattern: /[a-z|A-z]+\s*[:|=]\s*(\([.|a-z\s|,|:|{|}|\"|\'|=]*\))?\s*->/gi,
        inside: {
          'function-name': /[_?a-z-|A-Z-]+(\s*[:|=])| @[_?$?a-z-|A-Z-]+(\s*)| /g,
          'operator': /[-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\//g
        }
      },

      'class-name': {
        pattern: /(class\s+)[a-z-]+[\.a-z]*\s/gi,
        lookbehind: true
      },

      'attr-name': /[_?a-z-|A-Z-]+(\s*:)| @[_?$?a-z-|A-Z-]+(\s*)| /g
    });
  };
});
<|endoftext|>