<commit_before>const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB

const isSupported = !!indexedDB

const DB_NAME = 'uppy-blobs'
const DB_VERSION = 1

function connect (dbName, name) {
  const request = indexedDB.open(dbName, DB_VERSION)
  return new Promise((resolve, reject) => {
    request.onupgradeneeded = (event) => {
      const db = event.target.result
      const store = db.createObjectStore(name, { keyPath: 'id' })
      store.transaction.oncomplete = () => {
        resolve(db)
      }
    }
    request.onsuccess = (event) => {
      resolve(event.target.result)
    }
    request.onerror = reject
  })
}

function waitForRequest (request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = (event) => {
      resolve(event.target.result)
    }
    request.onerror = reject
  })
}

class IndexedDBStore {
  constructor (core, opts) {
    this.opts = Object.assign({
      dbName: DB_NAME,
      storeName: 'default',
      maxFileSize: 10 * 1024 * 1024, // 10 MB
      maxTotalSize: 300 * 1024 * 1024 // 300 MB
    }, opts)

    this.name = this.opts.storeName
    this.ready = connect(this.opts.dbName, this.opts.storeName)
  }

  /**
   * List all file blobs currently in the store.
   */
  list () {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readonly')
      const request = transaction.objectStore(this.name).getAll()
      return waitForRequest(request)
    }).then((files) => {
      const result = {}
      files.forEach((file) => {
        result[file.id] = file
      })
      return result
    })
  }

  /**
   * Get one file blob from the store.
   */
  get (fileID) {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readonly')
      const request = transaction.objectStore(this.name).get(fileID)
      return waitForRequest(request)
    }).then((result) => result.data)
  }

  /**
   * Get the total size of all stored files.
   *
   * @private
   */
  getSize () {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readonly')
      const request = transaction.objectStore(this.name).openCursor()
      return new Promise((resolve, reject) => {
        let size = 0
        request.onsuccess = () => {
          const cursor = event.target.result
          if (cursor) {
            size += cursor.value.data.size
            cursor.continue()
          } else {
            resolve(size)
          }
        }
        request.onerror = () => {
          reject(new Error('Could not retrieve stored blobs size'))
        }
      })
    })
  }

  /**
   * Save a file in the store.
   */
  put (file) {
    if (file.data.size > this.opts.maxFileSize) {
      return Promise.reject(new Error('File is too big to store.'))
    }
    return this.getSize().then((size) => {
      if (size > this.opts.maxTotalSize) {
        return Promise.reject(new Error('No space left'))
      }
      return this.ready
    }).then((db) => {
      const transaction = db.transaction([this.name], 'readwrite')
      const request = transaction.objectStore(this.name).add({
        id: file.id,
        data: file.data
      })
      return waitForRequest(request)
    })
  }

  /**
   * Delete a file blob from the store.
   */
  delete (fileID) {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readwrite')
      const request = transaction.objectStore(this.name).delete(fileID)
      return waitForRequest(request)
    })
  }
}

IndexedDBStore.isSupported = isSupported

module.exports = IndexedDBStore
<commit_msg>restore: Fix undefined `event` reference<commit_after>const indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.OIndexedDB || window.msIndexedDB

const isSupported = !!indexedDB

const DB_NAME = 'uppy-blobs'
const DB_VERSION = 1

function connect (dbName, name) {
  const request = indexedDB.open(dbName, DB_VERSION)
  return new Promise((resolve, reject) => {
    request.onupgradeneeded = (event) => {
      const db = event.target.result
      const store = db.createObjectStore(name, { keyPath: 'id' })
      store.transaction.oncomplete = () => {
        resolve(db)
      }
    }
    request.onsuccess = (event) => {
      resolve(event.target.result)
    }
    request.onerror = reject
  })
}

function waitForRequest (request) {
  return new Promise((resolve, reject) => {
    request.onsuccess = (event) => {
      resolve(event.target.result)
    }
    request.onerror = reject
  })
}

class IndexedDBStore {
  constructor (core, opts) {
    this.opts = Object.assign({
      dbName: DB_NAME,
      storeName: 'default',
      maxFileSize: 10 * 1024 * 1024, // 10 MB
      maxTotalSize: 300 * 1024 * 1024 // 300 MB
    }, opts)

    this.name = this.opts.storeName
    this.ready = connect(this.opts.dbName, this.opts.storeName)
  }

  /**
   * List all file blobs currently in the store.
   */
  list () {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readonly')
      const request = transaction.objectStore(this.name).getAll()
      return waitForRequest(request)
    }).then((files) => {
      const result = {}
      files.forEach((file) => {
        result[file.id] = file
      })
      return result
    })
  }

  /**
   * Get one file blob from the store.
   */
  get (fileID) {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readonly')
      const request = transaction.objectStore(this.name).get(fileID)
      return waitForRequest(request)
    }).then((result) => result.data)
  }

  /**
   * Get the total size of all stored files.
   *
   * @private
   */
  getSize () {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readonly')
      const request = transaction.objectStore(this.name).openCursor()
      return new Promise((resolve, reject) => {
        let size = 0
        request.onsuccess = (event) => {
          const cursor = event.target.result
          if (cursor) {
            size += cursor.value.data.size
            cursor.continue()
          } else {
            resolve(size)
          }
        }
        request.onerror = () => {
          reject(new Error('Could not retrieve stored blobs size'))
        }
      })
    })
  }

  /**
   * Save a file in the store.
   */
  put (file) {
    if (file.data.size > this.opts.maxFileSize) {
      return Promise.reject(new Error('File is too big to store.'))
    }
    return this.getSize().then((size) => {
      if (size > this.opts.maxTotalSize) {
        return Promise.reject(new Error('No space left'))
      }
      return this.ready
    }).then((db) => {
      const transaction = db.transaction([this.name], 'readwrite')
      const request = transaction.objectStore(this.name).add({
        id: file.id,
        data: file.data
      })
      return waitForRequest(request)
    })
  }

  /**
   * Delete a file blob from the store.
   */
  delete (fileID) {
    return this.ready.then((db) => {
      const transaction = db.transaction([this.name], 'readwrite')
      const request = transaction.objectStore(this.name).delete(fileID)
      return waitForRequest(request)
    })
  }
}

IndexedDBStore.isSupported = isSupported

module.exports = IndexedDBStore
<|endoftext|>


<commit_before>import { addPriority } from './utils';

/**
 * Store and sort transitions
 *
 * @namespace @barba/core/transitions/store
 * @type {object}
 */
export default {
  /**
   * Rules for prioritazing transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _rules: [
    {
      name: 'namespace',
      type: 'strings',
    },
    {
      name: 'custom',
      type: 'function',
    },
  ],

  /**
   * All transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _all: [],

  /**
   * Appear transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _appear: [],

  /**
   * Page transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _page: [],

  /**
   * Debug mode, log matchong criteria for active transition
   *
   * @memberof @barba/core/transitions/store
   * @type {boolean}
   * @private
   */
  _debug: false,

  /**
   * To know if we should wait for next container before getting transition
   *
   * @memberof @barba/core/transitions/store
   * @type {boolean}
   */
  wait: false,

  /**
   * Check if appear transitions
   *
   * @memberof @barba/core/transitions/store
   * @returns {boolean} yes or not
   */
  get hasAppear() {
    return this._appear.length > 0;
  },

  /**
   * Init store
   *
   * @memberof @barba/core/transitions/store
   * @param {array} transitions array of transitions
   * @param {boolean} debug debug mode
   * @returns {store} this instance
   */
  init(transitions, debug) {
    this._debug = debug;

    if (transitions) {
      // TODO: add check for valid transitions? criteria? (appear || enter && leave)
      this._all = this._all.concat(transitions);
    }

    this._update();

    return this;
  },

  /**
   * Destroy store
   *
   * @memberof @barba/core/transitions/store
   * @returns {store} this instance
   */
  destroy() {
    this._active = undefined;
    this._debug = false;
    this._all = [];
    this._appear = [];
    this._page = [];
    this.wait = false;

    this._update();

    return this;
  },

  /**
   * Add rule or transition
   *
   * @memberof @barba/core/transitions/store
   * @param {string} type rule or transition
   * @param {object} data data
   * @returns {undefined}
   */
  add(type, data) {
    switch (type) {
      case 'rule':
        // TODO: check for valid rule
        this._rules.splice(data.position || 0, 0, data.value);
        break;
      case 'transition':
      default:
        // TODO: check for valid transition
        this._all.push(data);
        break;
    }

    this._update();
  },

  /**
   * Get active/matching transition
   *
   * @memberof @barba/core/transitions/store
   * @param {object} data transition data
   * @param {object} data.current current page
   * @param {object} data.next next page
   * @param {object} data.trigger transition trigger
   * @param {boolean} [appear=false] for appear transition
   * @returns {object} active transition
   */
  get(data, appear = false) {
    const transitions = appear ? this._appear : this._page;

    // All matching transition infos
    const matching = new Map();

    // Active = first of valid transitions
    // sorted by directions (from/to, from || to, …)
    const active = transitions.find(t => {
      let valid = true;
      const match = {};

      // Check rules
      this._rules.reverse().forEach(rule => {
        if (valid) {
          valid = this._check(t, rule, data, match);
          // From/to check, only for page transitions
          if (!appear) {
            if (t.from && t.to) {
              valid =
                this._check(t, rule, data, match, 'from') &&
                this._check(t, rule, data, match, 'to');
            }
            if (t.from && !t.to) {
              valid = this._check(t, rule, data, match, 'from');
            }
            if (!t.from && t.to) {
              valid = this._check(t, rule, data, match, 'to');
            }
          }
        }
      });

      matching.set(t, match);

      return valid;
    });
    // DEV transitions are now correctly sorted
    // .sort(byDirections);

    if (this._debug) {
      // Debug info to known criteria applied for matching transition
      // TODO: error/warn/info handler
      console.info('DEBUG', matching.get(active));
    }

    return active;
  },

  /**
   * Update store
   *
   * Reorder transition by priorities
   * Get wait transitions
   * Get appear transitions
   *
   * @memberof @barba/core/transitions/store
   * @returns {undefined}
   * @private
   */
  _update() {
    // Reorder by priorities
    this._all = this._all
      .map(addPriority(this._rules))
      .sort((a, b) => a.priority - b.priority)
      .reverse()
      .map(t => {
        delete t.priority;

        return t;
      });
    this._page = this._all.filter(t => t.enter || t.leave);
    this._appear = this._all.filter(t => t.appear);
    // If some "to" property, except if based on "route"
    // TODO: how to manage "t.to.route" from @barba/router ???
    this.wait = this._all.some(t => t.to && !t.to.route);
  },

  /**
   * Check if transition apply,
   * based on rule, page data and optional direction
   *
   * 1. transition has no rule "property":
   *    - always returns true
   * 2. transition has rule "property":
   *     - "strings" should be present on both side (transition + view) and match
   *     - "function" should return true
   *
   * @memberof @barba/core/transitions/store
   * @param {object} transition transition
   * @param {object} rule rule
   * @param {object} data transition data
   * @param {object} data.current current page
   * @param {object} data.next next page
   * @param {object} data.trigger transition trigger
   * @param {object} match debug object
   * @param {string} direction from | to
   * @returns {boolean} valid check or not
   * @private
   */
  _check(transition, rule, data, match, direction) {
    let isValid = true;
    let hasMatch = false;
    const t = transition;
    const { name, type } = rule;
    const base = direction ? t[direction] : t; // = t || t.from || t.to
    const page = direction === 'to' ? data.next : data.current; // = current || next
    const exist = direction ? base && base[name] : base[name];

    // If transition rule exists
    if (exist) {
      switch (type) {
        case 'strings':
        default: {
          // Array support
          const names = Array.isArray(base[name]) ? base[name] : [base[name]];

          // For matching, prop should be present on both sides and match
          if (page[name] && names.indexOf(page[name]) !== -1) {
            hasMatch = true;
          }
          // If transition prop is different from current, not valid
          if (!names.indexOf(page[name]) !== -1) {
            isValid = false;
          }
          break;
        }

        case 'function':
          if (base[name](data)) {
            hasMatch = true;
          } else {
            isValid = false;
          }
          break;
      }

      if (hasMatch) {
        if (direction) {
          match[direction] = match[direction] || {};
          match[direction][name] = t[direction][name];
        } else {
          match[name] = t[name];
        }
      }
    }

    return isValid;
  },
};
<commit_msg>refactor(core): :bug: fix wrong indexOf condition<commit_after>import { addPriority } from './utils';

/**
 * Store and sort transitions
 *
 * @namespace @barba/core/transitions/store
 * @type {object}
 */
export default {
  /**
   * Rules for prioritazing transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _rules: [
    {
      name: 'namespace',
      type: 'strings',
    },
    {
      name: 'custom',
      type: 'function',
    },
  ],

  /**
   * All transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _all: [],

  /**
   * Appear transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _appear: [],

  /**
   * Page transitions
   *
   * @memberof @barba/core/transitions/store
   * @type {array}
   * @private
   */
  _page: [],

  /**
   * Debug mode, log matchong criteria for active transition
   *
   * @memberof @barba/core/transitions/store
   * @type {boolean}
   * @private
   */
  _debug: false,

  /**
   * To know if we should wait for next container before getting transition
   *
   * @memberof @barba/core/transitions/store
   * @type {boolean}
   */
  wait: false,

  /**
   * Check if appear transitions
   *
   * @memberof @barba/core/transitions/store
   * @returns {boolean} yes or not
   */
  get hasAppear() {
    return this._appear.length > 0;
  },

  /**
   * Init store
   *
   * @memberof @barba/core/transitions/store
   * @param {array} transitions array of transitions
   * @param {boolean} debug debug mode
   * @returns {store} this instance
   */
  init(transitions, debug) {
    this._debug = debug;

    if (transitions) {
      // TODO: add check for valid transitions? criteria? (appear || enter && leave)
      this._all = this._all.concat(transitions);
    }

    this._update();

    return this;
  },

  /**
   * Destroy store
   *
   * @memberof @barba/core/transitions/store
   * @returns {store} this instance
   */
  destroy() {
    this._active = undefined;
    this._debug = false;
    this._all = [];
    this._appear = [];
    this._page = [];
    this.wait = false;

    this._update();

    return this;
  },

  /**
   * Add rule or transition
   *
   * @memberof @barba/core/transitions/store
   * @param {string} type rule or transition
   * @param {object} data data
   * @returns {undefined}
   */
  add(type, data) {
    switch (type) {
      case 'rule':
        // TODO: check for valid rule
        this._rules.splice(data.position || 0, 0, data.value);
        break;
      case 'transition':
      default:
        // TODO: check for valid transition
        this._all.push(data);
        break;
    }

    this._update();
  },

  /**
   * Get active/matching transition
   *
   * @memberof @barba/core/transitions/store
   * @param {object} data transition data
   * @param {object} data.current current page
   * @param {object} data.next next page
   * @param {object} data.trigger transition trigger
   * @param {boolean} [appear=false] for appear transition
   * @returns {object} active transition
   */
  get(data, appear = false) {
    const transitions = appear ? this._appear : this._page;

    // All matching transition infos
    const matching = new Map();

    // Active = first of valid transitions
    // sorted by directions (from/to, from || to, …)
    const active = transitions.find(t => {
      let valid = true;
      const match = {};

      // Check rules
      this._rules.reverse().forEach(rule => {
        if (valid) {
          valid = this._check(t, rule, data, match);
          // From/to check, only for page transitions
          if (!appear) {
            if (t.from && t.to) {
              valid =
                this._check(t, rule, data, match, 'from') &&
                this._check(t, rule, data, match, 'to');
            }
            if (t.from && !t.to) {
              valid = this._check(t, rule, data, match, 'from');
            }
            if (!t.from && t.to) {
              valid = this._check(t, rule, data, match, 'to');
            }
          }
        }
      });

      matching.set(t, match);

      return valid;
    });
    // DEV transitions are now correctly sorted
    // .sort(byDirections);

    if (this._debug) {
      // Debug info to known criteria applied for matching transition
      // TODO: error/warn/info handler
      console.info('DEBUG', matching.get(active));
    }

    return active;
  },

  /**
   * Update store
   *
   * Reorder transition by priorities
   * Get wait transitions
   * Get appear transitions
   *
   * @memberof @barba/core/transitions/store
   * @returns {undefined}
   * @private
   */
  _update() {
    // Reorder by priorities
    this._all = this._all
      .map(addPriority(this._rules))
      .sort((a, b) => a.priority - b.priority)
      .reverse()
      .map(t => {
        delete t.priority;

        return t;
      });
    this._page = this._all.filter(t => t.enter || t.leave);
    this._appear = this._all.filter(t => t.appear);
    // If some "to" property, except if based on "route"
    // TODO: how to manage "t.to.route" from @barba/router ???
    this.wait = this._all.some(t => t.to && !t.to.route);
  },

  /**
   * Check if transition apply,
   * based on rule, page data and optional direction
   *
   * 1. transition has no rule "property":
   *    - always returns true
   * 2. transition has rule "property":
   *     - "strings" should be present on both side (transition + view) and match
   *     - "function" should return true
   *
   * @memberof @barba/core/transitions/store
   * @param {object} transition transition
   * @param {object} rule rule
   * @param {object} data transition data
   * @param {object} data.current current page
   * @param {object} data.next next page
   * @param {object} data.trigger transition trigger
   * @param {object} match debug object
   * @param {string} direction from | to
   * @returns {boolean} valid check or not
   * @private
   */
  _check(transition, rule, data, match, direction) {
    let isValid = true;
    let hasMatch = false;
    const t = transition;
    const { name, type } = rule;
    const base = direction ? t[direction] : t; // = t || t.from || t.to
    const page = direction === 'to' ? data.next : data.current; // = current || next
    const exist = direction ? base && base[name] : base[name];

    // If transition rule exists
    if (exist) {
      switch (type) {
        case 'strings':
        default: {
          // Array support
          const names = Array.isArray(base[name]) ? base[name] : [base[name]];

          // For matching, prop should be present on both sides and match
          if (page[name] && names.indexOf(page[name]) !== -1) {
            hasMatch = true;
          }
          // If transition prop is different from current, not valid
          if (names.indexOf(page[name]) === -1) {
            isValid = false;
          }
          break;
        }

        case 'function':
          if (base[name](data)) {
            hasMatch = true;
          } else {
            isValid = false;
          }
          break;
      }

      if (hasMatch) {
        if (direction) {
          match[direction] = match[direction] || {};
          match[direction][name] = t[direction][name];
        } else {
          match[name] = t[name];
        }
      }
    }

    return isValid;
  },
};
<|endoftext|>


<commit_before>const markdownIt = require('markdown-it');
const markdownItAnchor = require('markdown-it-anchor');

const syntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight');
const toc = require('eleventy-plugin-toc');

const noOpShortCode = require('./shortcodes/NoOp.js');
const insertStyles = require('./transforms/insertStyles.js');

const isProduction = process.env.NODE_ENV === 'production';

module.exports = (eleventyConfig) => {
  eleventyConfig.setUseGitIgnore(false);
  eleventyConfig.setDataDeepMerge(true);

  eleventyConfig.addPassthroughCopy('assets');
  eleventyConfig.addWatchTarget('./dist/assets/css');

  eleventyConfig.addPairedShortcode('tip', noOpShortCode);

  eleventyConfig.setLibrary(
    'md',
    markdownIt().use(markdownItAnchor)
  )
  eleventyConfig.addPlugin(syntaxHighlight);
  eleventyConfig.addPlugin(toc);

  eleventyConfig.addTransform('insert-styles', insertStyles);

  return {
    markdownTemplateEngine: 'njk',
    dataTemplateEngine: 'njk',
    htmlTemplateEngine: 'njk',
    dir: {
      input: 'site',
      output: 'dist',
    },
  };
};<commit_msg>🐛 Watch for SASS changes instead of final CSS file<commit_after>const markdownIt = require('markdown-it');
const markdownItAnchor = require('markdown-it-anchor');

const syntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight');
const toc = require('eleventy-plugin-toc');

const noOpShortCode = require('./shortcodes/NoOp.js');
const insertStyles = require('./transforms/insertStyles.js');

const isProduction = process.env.NODE_ENV === 'production';

module.exports = (eleventyConfig) => {
  eleventyConfig.setUseGitIgnore(false);
  eleventyConfig.setDataDeepMerge(true);

  eleventyConfig.addPassthroughCopy('assets');
  eleventyConfig.addWatchTarget('./styles');

  eleventyConfig.addPairedShortcode('tip', noOpShortCode);

  eleventyConfig.setLibrary(
    'md',
    markdownIt().use(markdownItAnchor)
  )
  eleventyConfig.addPlugin(syntaxHighlight);
  eleventyConfig.addPlugin(toc);

  eleventyConfig.addTransform('insert-styles', insertStyles);

  return {
    markdownTemplateEngine: 'njk',
    dataTemplateEngine: 'njk',
    htmlTemplateEngine: 'njk',
    dir: {
      input: 'site',
      output: 'dist',
    },
  };
};<|endoftext|>


<commit_before>'use strict';

var Twit = require('twit');

var log = require('./log.js');

var listen = {
    new_twit: function () {
        return new Twit({
            consumer_key:        process.env.TWITTER_CONSUMER_KEY,
            consumer_secret:     process.env.TWITTER_CONSUMER_SECRET,
            access_token:        process.env.TWITTER_ACCESS_TOKEN,
            access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
        });
    },

    go: function () {
        var t = this.new_twit(),
            tw_user = 'adamcurry',
            tw_id;

        t.get('users/show', { 'screen_name': tw_user }, function (err, data, response) {
            if (err) {
                log.error('Twitter returned an error');
                log.error(response);
            } else {
                tw_id = data.id;
                log.debug('Looked up Twitter screen name: ' + tw_user);
                log.debug('Got ID: ' + tw_id);
            }
        });
    }
};
listen.go();
<commit_msg>Remove obsolete listen.js script to avoid confusion<commit_after><|endoftext|>


<commit_before>var PORT = 6112;
var HOST = '127.0.0.1';

var dgram = require('dgram');
var hex = require('hex');
var server = dgram.createSocket('udp4');

server.on('listening', function () {
	var address = server.address();
	console.log('UDP Server listening on ' + address.address + ":" + address.port);
});

server.on('message', function (message, remote) {
	console.log(remote.address + ':' + remote.port);
	hex(message);
});

server.bind(PORT, HOST);
<commit_msg>Delete listen.js<commit_after><|endoftext|>


<commit_before>/* global vfs */
import {
  TextureConfigurator, ArticlePackage,
  EditorSession,
  ArticleAPI, createEditorContext,
  VfsStorageClient, TextureArchive, InMemoryDarBuffer
} from 'substance-texture'

export default function setupTestArticleSession (opts = {}) {
  let config = new TextureConfigurator()
  config.import(ArticlePackage)
  // TODO: this could be a little easier
  let manuscriptConfig = config.getConfiguration('article.manuscript')

  // load the empty archive
  let storage = new VfsStorageClient(vfs, './data/')
  let archive = new TextureArchive(storage, new InMemoryDarBuffer(), {}, config)
  // ATTENTION: in case of the VFS loading is synchronous
  // TODO: make sure that this is always the case
  let archiveId = opts.archiveId || 'blank'
  archive.load(archiveId, () => {})
  let doc = archive.getDocument('manuscript')
  if (opts.seed) {
    // clear the body
    let body = doc.get('body')
    body.set('content', [])
    opts.seed(doc)
  }
  // NOTE: this indirection is necessary because we need to pass the context to parts of the context
  let contextProvider = {}
  let editorSession = new EditorSession('test-editor', doc, manuscriptConfig, contextProvider)
  let api = new ArticleAPI(editorSession, manuscriptConfig, archive)
  let context = Object.assign(createEditorContext(manuscriptConfig, editorSession), { api })
  // ... after the context is ready we can store it into the provider
  contextProvider.context = context

  return { context, editorSession, doc, archive, api }
}
<commit_msg>Fix test helper for setting up a test session.<commit_after>/* global vfs */
import {
  TextureConfigurator, ArticlePackage,
  EditorSession,
  ArticleAPI, createEditorContext,
  VfsStorageClient, TextureArchive, InMemoryDarBuffer
} from 'substance-texture'

export default function setupTestArticleSession (opts = {}) {
  let config = new TextureConfigurator()
  config.import(ArticlePackage)

  // load the empty archive
  let storage = new VfsStorageClient(vfs, './data/')
  let archive = new TextureArchive(storage, new InMemoryDarBuffer(), {}, config)
  // ATTENTION: in case of the VFS loading is synchronous
  // TODO: make sure that this is always the case
  let archiveId = opts.archiveId || 'blank'
  archive.load(archiveId, () => {})
  let doc = archive.getDocument('manuscript')
  if (opts.seed) {
    // clear the body
    let body = doc.get('body')
    body.set('content', [])
    opts.seed(doc)
  }
  // NOTE: this indirection is necessary because we need to pass the context to parts of the context
  let contextProvider = {}
  let editorSession = new EditorSession('test-editor', doc, config, contextProvider)
  let api = new ArticleAPI(editorSession, archive, config)
  let context = Object.assign(createEditorContext(config, editorSession), { api })
  // ... after the context is ready we can store it into the provider
  contextProvider.context = context

  return { context, editorSession, doc, archive, api }
}
<|endoftext|>


<commit_before>var spellcheck = require("../").spellCheckText;
var assert = require("power-assert");
describe("spellcheck-technical-word", function () {
    context("when found wrong word", function () {
        it("should return the array of results", function () {
            var results = spellcheck("git");
            assert(results.length > 0);
            var result = results.pop();
            assert.equal(result.actual, "git");
            assert.equal(result.expected, "Git");
        });
        it("should have padding{line,column}", function () {
            var results = spellcheck("git");
            var result = results.pop();
            assert(result.paddingLine === 0);
            assert(result.paddingColumn === 0);
        });
    });
    context("when not found wrong word", function () {
        it("should return empty array", function () {
            var results = spellcheck("word");
            assert(results.length === 0);
        });
        it("should return empty array in formal", function () {
            var results = spellcheck("This is a pen.");
            assert(results.length === 0);
        });
    });
    context("when an expected word includes the pattern", function () {
        it("finds wrong word", function () {
            var results = spellcheck("ベンダ");
            assert(results.length > 0);
            var result = results.pop();
            assert.equal(result.actual, "ベンダ");
            assert.equal(result.expected, "ベンダー");
        });
        it("finds wrong word", function () {
            var results = spellcheck("HTML Import");
            assert(results.length === 1);
            var result = results.pop();
            assert.equal(result.actual, "HTML Import");
            assert.equal(result.expected, "HTML Imports");
        });
        it("doesn't find correct word", function () {
            var results = spellcheck("ベンダー");
            assert(results.length === 0);
        });
        // ?? $1がexpectedだとnew RegExp(expected)で例外となるのでそれを避けられてるか
        it("expected is regexp characters, is safe", function () {
            var results = spellcheck("??あ");
            assert(results.length === 1);
            var result = results.pop();
            assert.equal(result.actual, "??あ");
            assert.equal(result.expected, "?? あ");
        });
    });
});
<commit_msg>fix: fix ignore rule itself<commit_after>var spellcheck = require("../").spellCheckText;
var assert = require("power-assert");
describe("spellcheck-technical-word", function () {
    context("when found wrong word", function () {
        it("should return the array of results", function () {
            var results = spellcheck("git");
            assert(results.length > 0);
            var result = results.pop();
            assert.equal(result.actual, "git");
            assert.equal(result.expected, "Git");
        });
        it("should have padding{line,column}", function () {
            var results = spellcheck("git");
            var result = results.pop();
            assert(result.paddingLine === 0);
            assert(result.paddingColumn === 0);
        });
    });
    context("when not found wrong word", function () {
        it("should return empty array", function () {
            var results = spellcheck("word");
            assert(results.length === 0);
        });
        it("should return empty array in formal", function () {
            var results = spellcheck("This is a pen.");
            assert(results.length === 0);
        });
    });
    context("when an expected word includes the pattern", function () {
        it("finds wrong word", function () {
            var results = spellcheck("ベンダ");
            assert(results.length > 0);
            var result = results.pop();
            assert.equal(result.actual, "ベンダ");
            assert.equal(result.expected, "ベンダー");
        });
        it("finds wrong word", function () {
            var results = spellcheck("HTML Import should be HTML Imports");
            assert(results.length === 1);
            var result = results.pop();
            assert.equal(result.actual, "HTML Import");
            assert.equal(result.expected, "HTML Imports");
        });
        it("doesn't find correct word", function () {
            var results = spellcheck("ベンダー");
            assert(results.length === 0);
        });
        // ?? $1がexpectedだとnew RegExp(expected)で例外となるのでそれを避けられてるか
        it("expected is regexp characters, is safe", function () {
            var results = spellcheck("??あ");
            assert(results.length === 1);
            var result = results.pop();
            assert.equal(result.actual, "??あ");
            assert.equal(result.expected, "?? あ");
        });
    });
});
<|endoftext|>


<commit_before>require("requirish")._(module);

var should = require("should");
var assert = require("better-assert");
var async = require("async");
var _ = require("underscore");
var util = require("util");

var opcua = require("index");
var OPCUAClient = opcua.OPCUAClient;
var StatusCodes = opcua.StatusCodes;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var browse_service = opcua.browse_service;
var NodeCrawler = opcua.NodeCrawler;

var redirectToFile = require("lib/misc/utils").redirectToFile;
var debugLog  = require("lib/misc/utils").make_debugLog(__filename);

var port = 2000;

var build_server_with_temperature_device = require("./helpers/build_server_with_temperature_device").build_server_with_temperature_device;
var perform_operation_on_client_session = require("./helpers/perform_operation_on_client_session").perform_operation_on_client_session;

describe("NodeCrawler",function(){

    // this test could be particularly slow on RapsberryPi or BeagleBoneBlack
    // so we set a big enough timeout
    if (process.arch === 'arm' ) {
       this.timeout(400000);
    }
    var server , client,temperatureVariableId,endpointUrl ;

    var port = 2001;
    before(function(done){
        // we use a different port for each tests to make sure that there is
        // no left over in the tcp pipe that could generate an error
        port+=1;
        server = build_server_with_temperature_device({ port:port},function() {
            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
            temperatureVariableId = server.temperatureVariableId;
            done();
        });
    });

    beforeEach(function(done){
        client = new OPCUAClient();
        done();
    });

    afterEach(function(done){
        client = null;
        done();
    });

    after(function(done){
        server.shutdown(done);
    });

    function MyDumpReference(reference) {
        function f(text,width) {
            return (text + "                                                     ").substring(0,width);
        }
        console.log("    referenceTypeId ",
                f(reference.referenceTypeId.displayText(),35).yellow +
                (  reference.isForward?" => ":" <= ") +
                f(reference.browseName.name,20).blue.bold +
                    "(" + reference.nodeId.displayText().cyan +")"
        );
    }
    function MyDumpReferences(index,references) {
        //xxx console.log(" xxxxxxxxxxxxxxxxx ",references);
        references.forEach(MyDumpReference);
    }

    it("should crawl for a complete tree",function(done) {

        redirectToFile("NodeCrawler_complete_tree.log", function (done) {

            perform_operation_on_client_session(client, endpointUrl, function (session, done) {

                var crawler = new NodeCrawler(session);

                var data = {};
                crawler.on("browsed", function (nodeElement, data) {

                    console.log("nodeElement ".yellow, nodeElement.browseName, nodeElement.nodeId.displayText());
                    var objectIndex = {  findObject: function (nodeId) {
                        return null;
                    }};
                    MyDumpReferences(objectIndex, nodeElement.references);

                }).on("end", function () {
                    console.log("Data ", data);
                }).on("error", function (err) {
                    done(err);
                });

                crawler.crawl("RootFolder", data, function (err) {

                    crawler.crawl("RootFolder", data, function (err) {
                        done();
                    });

                });

            }, done);
        },done);
    });
    it("should crawl for a complete tree with limited node per browse and read request",function(done) {

        perform_operation_on_client_session(client, endpointUrl, function (session, done) {

            // crawler 1 has no limit in the number of node inside Browse or Read request
            var crawler1 = new NodeCrawler(session);
            assert(crawler1.maxNodesPerRead === 0);
            assert(crawler1.maxNodesPerBrowse === 0);

            // crawler 2 has a limit of 3 nodes inside Browse or Read request
            var crawler2 = new NodeCrawler(session);
            crawler2.maxNodesPerRead = 3;
            crawler2.maxNodesPerBrowse = 3;

            var browsed_node1 = 0;
            var browsed_node2 = 0;
            crawler1.on("browsed", function (nodeElement, data) {
                browsed_node1++;
            });
            crawler2.on("browsed", function (nodeElement, data) {
                browsed_node2++;
            });
            var data1= {};
            crawler1.crawl("RootFolder", data1, function (err) {
                browsed_node1.should.be.greaterThan(10);
                browsed_node2.should.equal(0);

                console.log("-----------------------------");
                var data2= {};
                crawler2.crawl("RootFolder", data2, function (err) {
                    browsed_node2.should.be.greaterThan(10);

                    browsed_node1.should.eql(browsed_node2,"crawler1 and crawler2 should browse the same number of node");
                    done();
                });
            });
        },done);
    });

    it("should crawl one at a time",function(done){

        perform_operation_on_client_session(client,endpointUrl,function(session,done) {

            assert(_.isFunction(done));

            var crawler = new NodeCrawler(session);

            var nodeId = "RootFolder";

            crawler.read(nodeId, function (err, obj) {

                if (!err) {
                    obj.browseName.should.equal("Root");
                    obj.organizes.length.should.equal(3);
                    obj.organizes[0].browseName.should.eql("Objects");
                    obj.organizes[1].browseName.should.eql("Types");
                    obj.organizes[2].browseName.should.eql("Views");
                    obj.hasTypeDefinition.should.eql("FolderType");
                }
                done(err);
            });
        },done);
    });

    it("should crawl faster the second time",function(done){

        perform_operation_on_client_session(client,endpointUrl,function(session,done) {

            assert(_.isFunction(done));

            var crawler = new NodeCrawler(session);

            var nodeId = "RootFolder";

            var startTime = Date.now();

            console.log("----------------------");
            crawler.read(nodeId, function (err, obj) {

                var intermediateTime1 = Date.now();
                var duration1 = intermediateTime1 - startTime;

                console.log("----------------------");
                crawler.read(nodeId, function (err, obj) {
                    console.log("----------------------");
                    var intermediateTime2 = Date.now();
                    var duration2 = intermediateTime2 - intermediateTime1;

                    duration1.should.be.greaterThan(duration2);

                    done(err);
                });

            });
        },done);
    });

    it("should display a tree",function(done){
        var treeify = require('treeify');

        perform_operation_on_client_session(client,endpointUrl,function(the_session,callback) {

            var crawler = new NodeCrawler(the_session);
            crawler.on("browsed",function(element){
                //xx console.log("->",element.browseName.name,element.nodeId.toString());
            });
            var nodeId = "ObjectsFolder";
            console.log("now crawling object folder ...please wait...");
            crawler.read(nodeId, function (err, obj) {
                if (!err) {
                    treeify.asLines(obj, true, true, function (line) {
                        console.log(line);
                    });
                }
                callback(err);
            });

        },done);

    });

});
<commit_msg>increase test timeout<commit_after>require("requirish")._(module);

var should = require("should");
var assert = require("better-assert");
var async = require("async");
var _ = require("underscore");
var util = require("util");

var opcua = require("index");
var OPCUAClient = opcua.OPCUAClient;
var StatusCodes = opcua.StatusCodes;
var Variant = opcua.Variant;
var DataType = opcua.DataType;
var browse_service = opcua.browse_service;
var NodeCrawler = opcua.NodeCrawler;

var redirectToFile = require("lib/misc/utils").redirectToFile;
var debugLog  = require("lib/misc/utils").make_debugLog(__filename);

var port = 2000;

var build_server_with_temperature_device = require("./helpers/build_server_with_temperature_device").build_server_with_temperature_device;
var perform_operation_on_client_session = require("./helpers/perform_operation_on_client_session").perform_operation_on_client_session;

describe("NodeCrawler",function(){

    // this test could be particularly slow on RapsberryPi or BeagleBoneBlack
    // so we set a big enough timeout
    this.timeout((process.arch === 'arm' ? 400000 : 10000);

    var server , client,temperatureVariableId,endpointUrl ;

    var port = 2001;
    before(function(done){
        // we use a different port for each tests to make sure that there is
        // no left over in the tcp pipe that could generate an error
        port+=1;
        server = build_server_with_temperature_device({ port:port},function() {
            endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl;
            temperatureVariableId = server.temperatureVariableId;
            done();
        });
    });

    beforeEach(function(done){
        client = new OPCUAClient();
        done();
    });

    afterEach(function(done){
        client = null;
        done();
    });

    after(function(done){
        server.shutdown(done);
    });

    function MyDumpReference(reference) {
        function f(text,width) {
            return (text + "                                                     ").substring(0,width);
        }
        console.log("    referenceTypeId ",
                f(reference.referenceTypeId.displayText(),35).yellow +
                (  reference.isForward?" => ":" <= ") +
                f(reference.browseName.name,20).blue.bold +
                    "(" + reference.nodeId.displayText().cyan +")"
        );
    }
    function MyDumpReferences(index,references) {
        //xxx console.log(" xxxxxxxxxxxxxxxxx ",references);
        references.forEach(MyDumpReference);
    }

    it("should crawl for a complete tree",function(done) {

        redirectToFile("NodeCrawler_complete_tree.log", function (done) {

            perform_operation_on_client_session(client, endpointUrl, function (session, done) {

                var crawler = new NodeCrawler(session);

                var data = {};
                crawler.on("browsed", function (nodeElement, data) {

                    console.log("nodeElement ".yellow, nodeElement.browseName, nodeElement.nodeId.displayText());
                    var objectIndex = {  findObject: function (nodeId) {
                        return null;
                    }};
                    MyDumpReferences(objectIndex, nodeElement.references);

                }).on("end", function () {
                    console.log("Data ", data);
                }).on("error", function (err) {
                    done(err);
                });

                crawler.crawl("RootFolder", data, function (err) {

                    crawler.crawl("RootFolder", data, function (err) {
                        done();
                    });

                });

            }, done);
        },done);
    });
    it("should crawl for a complete tree with limited node per browse and read request",function(done) {

        perform_operation_on_client_session(client, endpointUrl, function (session, done) {

            // crawler 1 has no limit in the number of node inside Browse or Read request
            var crawler1 = new NodeCrawler(session);
            assert(crawler1.maxNodesPerRead === 0);
            assert(crawler1.maxNodesPerBrowse === 0);

            // crawler 2 has a limit of 3 nodes inside Browse or Read request
            var crawler2 = new NodeCrawler(session);
            crawler2.maxNodesPerRead = 3;
            crawler2.maxNodesPerBrowse = 3;

            var browsed_node1 = 0;
            var browsed_node2 = 0;
            crawler1.on("browsed", function (nodeElement, data) {
                browsed_node1++;
            });
            crawler2.on("browsed", function (nodeElement, data) {
                browsed_node2++;
            });
            var data1= {};
            crawler1.crawl("RootFolder", data1, function (err) {
                browsed_node1.should.be.greaterThan(10);
                browsed_node2.should.equal(0);

                console.log("-----------------------------");
                var data2= {};
                crawler2.crawl("RootFolder", data2, function (err) {
                    browsed_node2.should.be.greaterThan(10);

                    browsed_node1.should.eql(browsed_node2,"crawler1 and crawler2 should browse the same number of node");
                    done();
                });
            });
        },done);
    });

    it("should crawl one at a time",function(done){

        perform_operation_on_client_session(client,endpointUrl,function(session,done) {

            assert(_.isFunction(done));

            var crawler = new NodeCrawler(session);

            var nodeId = "RootFolder";

            crawler.read(nodeId, function (err, obj) {

                if (!err) {
                    obj.browseName.should.equal("Root");
                    obj.organizes.length.should.equal(3);
                    obj.organizes[0].browseName.should.eql("Objects");
                    obj.organizes[1].browseName.should.eql("Types");
                    obj.organizes[2].browseName.should.eql("Views");
                    obj.hasTypeDefinition.should.eql("FolderType");
                }
                done(err);
            });
        },done);
    });

    it("should crawl faster the second time",function(done){

        perform_operation_on_client_session(client,endpointUrl,function(session,done) {

            assert(_.isFunction(done));

            var crawler = new NodeCrawler(session);

            var nodeId = "RootFolder";

            var startTime = Date.now();

            console.log("----------------------");
            crawler.read(nodeId, function (err, obj) {

                var intermediateTime1 = Date.now();
                var duration1 = intermediateTime1 - startTime;

                console.log("----------------------");
                crawler.read(nodeId, function (err, obj) {
                    console.log("----------------------");
                    var intermediateTime2 = Date.now();
                    var duration2 = intermediateTime2 - intermediateTime1;

                    duration1.should.be.greaterThan(duration2);

                    done(err);
                });

            });
        },done);
    });

    it("should display a tree",function(done){
        var treeify = require('treeify');

        perform_operation_on_client_session(client,endpointUrl,function(the_session,callback) {

            var crawler = new NodeCrawler(the_session);
            crawler.on("browsed",function(element){
                //xx console.log("->",element.browseName.name,element.nodeId.toString());
            });
            var nodeId = "ObjectsFolder";
            console.log("now crawling object folder ...please wait...");
            crawler.read(nodeId, function (err, obj) {
                if (!err) {
                    treeify.asLines(obj, true, true, function (line) {
                        console.log(line);
                    });
                }
                callback(err);
            });

        },done);

    });

});
<|endoftext|>


<commit_before>describe('sandbox library - pm api', function () {
    this.timeout(1000 * 60);
    var Sandbox = require('../../../'),

        sampleContextData = {
            globals: [{
                key: 'var1',
                value: 'one'
            }, {
                key: 'var2',
                value: 2,
                type: 'number'
            }],
            environment: [{
                key: 'var1',
                value: 'one-env'
            }, {
                key: 'var2',
                value: 2.5,
                type: 'number'
            }]
        },
        context;

    beforeEach(function (done) {
        Sandbox.createContext({}, function (err, ctx) {
            context = ctx;
            done(err);
        });
    });

    afterEach(function () {
        context.dispose();
        context = null;
    });

    it('pm object should be in globals', function (done) {
        context.execute(`
            var assert = require('assert');
            assert.strictEqual(typeof pm, 'object');
        `, done);
    });

    describe('globals', function () {
        it('must be defined as VariableScope', function (done) {
            context.execute(`
                var assert = require('assert'),
                    VariableScope = require('postman-collection').VariableScope;
                assert.strictEqual(VariableScope.isVariableScope(pm.globals), true);
            `, done);
        });

        it('must be a readonly property', function (done) {
            context.execute(`
                var assert = require('assert'),
                    _globals;

                _globals = pm.globals;
                pm.globals = [];

                assert.strictEqual(pm.globals, _globals, 'property stays inchanged');
            `, done);
        });

        it('must forward global variables forwarded during execution', function (done) {
            context.execute(`
                var assert = require('assert');
                assert.strictEqual(pm.globals.get('var1'), 'one');
                assert.strictEqual(pm.globals.get('var2'), 2);
            `, {context: sampleContextData}, done);
        });

        it('must propagate updated globals from inside sandbox', function (done) {
            context.execute(`
                var assert = require('assert');

                assert.strictEqual(pm.globals.get('var1'), 'one');
                pm.globals.set('var1', 'one-one');
                assert.strictEqual(pm.globals.get('var1'), 'one-one');

            `, {context: sampleContextData}, function (err, exec) {
                expect(err).not.be.ok();
                expect(exec).be.ok();
                expect(exec.globals.values).eql([
                    {type: 'any', value: 'one-one', key: 'var1'},
                    {type: 'number', value: 2, key: 'var2'}
                ]);
                done();
            });
        });
    });

    describe('environment', function () {
        it('must be defined as VariableScope', function (done) {
            context.execute(`
                var assert = require('assert'),
                    VariableScope = require('postman-collection').VariableScope;
                assert.strictEqual(VariableScope.isVariableScope(pm.environment), true);
            `, done);
        });

        it('must be a readonly property', function (done) {
            context.execute(`
                var assert = require('assert'),
                    _environment;

                _environment = pm.globals;
                pm.globals = [];

                assert.strictEqual(pm.globals, _environment, 'property stays inchanged');
            `, done);
        });

        it('must forward environment variables forwarded during execution', function (done) {
            context.execute(`
                var assert = require('assert');
                assert.strictEqual(pm.environment.get('var1'), 'one-env');
                assert.strictEqual(pm.environment.get('var2'), 2.5);
            `, {context: sampleContextData}, done);
        });

        it('must propagate updated environment from inside sandbox', function (done) {
            context.execute(`
                var assert = require('assert');

                assert.strictEqual(pm.environment.get('var1'), 'one-env');
                pm.environment.set('var1', 'one-one-env');
                assert.strictEqual(pm.environment.get('var1'), 'one-one-env');

            `, {context: sampleContextData}, function (err, exec) {
                expect(err).not.be.ok();
                expect(exec).be.ok();
                expect(exec.environment.values).eql([
                    {type: 'any', value: 'one-one-env', key: 'var1'},
                    {type: 'number', value: 2.5, key: 'var2'}
                ]);
                done();
            });
        });
    });
});
<commit_msg>Added tests for checking request objects in sandbox (skipped ones stuck on sdk bug)<commit_after>describe('sandbox library - pm api', function () {
    this.timeout(1000 * 60);
    var Sandbox = require('../../../'),

        sampleContextData = {
            globals: [{
                key: 'var1',
                value: 'one'
            }, {
                key: 'var2',
                value: 2,
                type: 'number'
            }],
            environment: [{
                key: 'var1',
                value: 'one-env'
            }, {
                key: 'var2',
                value: 2.5,
                type: 'number'
            }]
        },
        context;

    beforeEach(function (done) {
        Sandbox.createContext({}, function (err, ctx) {
            context = ctx;
            done(err);
        });
    });

    afterEach(function () {
        context.dispose();
        context = null;
    });

    it('pm object should be in globals', function (done) {
        context.execute(`
            var assert = require('assert');
            assert.strictEqual(typeof pm, 'object');
        `, done);
    });

    describe('globals', function () {
        it('must be defined as VariableScope', function (done) {
            context.execute(`
                var assert = require('assert'),
                    VariableScope = require('postman-collection').VariableScope;
                assert.strictEqual(VariableScope.isVariableScope(pm.globals), true);
            `, done);
        });

        it('must be a readonly property', function (done) {
            context.execute(`
                var assert = require('assert'),
                    _globals;

                _globals = pm.globals;
                pm.globals = [];

                assert.strictEqual(pm.globals, _globals, 'property stays inchanged');
            `, done);
        });

        it('must forward global variables forwarded during execution', function (done) {
            context.execute(`
                var assert = require('assert');
                assert.strictEqual(pm.globals.get('var1'), 'one');
                assert.strictEqual(pm.globals.get('var2'), 2);
            `, {context: sampleContextData}, done);
        });

        it('must propagate updated globals from inside sandbox', function (done) {
            context.execute(`
                var assert = require('assert');

                assert.strictEqual(pm.globals.get('var1'), 'one');
                pm.globals.set('var1', 'one-one');
                assert.strictEqual(pm.globals.get('var1'), 'one-one');

            `, {context: sampleContextData}, function (err, exec) {
                expect(err).not.be.ok();
                expect(exec).be.ok();
                expect(exec.globals.values).eql([
                    {type: 'any', value: 'one-one', key: 'var1'},
                    {type: 'number', value: 2, key: 'var2'}
                ]);
                done();
            });
        });
    });

    describe('environment', function () {
        it('must be defined as VariableScope', function (done) {
            context.execute(`
                var assert = require('assert'),
                    VariableScope = require('postman-collection').VariableScope;
                assert.strictEqual(VariableScope.isVariableScope(pm.environment), true);
            `, done);
        });

        it('must be a readonly property', function (done) {
            context.execute(`
                var assert = require('assert'),
                    _environment;

                _environment = pm.globals;
                pm.globals = [];

                assert.strictEqual(pm.globals, _environment, 'property stays inchanged');
            `, done);
        });

        it('must forward environment variables forwarded during execution', function (done) {
            context.execute(`
                var assert = require('assert');
                assert.strictEqual(pm.environment.get('var1'), 'one-env');
                assert.strictEqual(pm.environment.get('var2'), 2.5);
            `, {context: sampleContextData}, done);
        });

        it('must propagate updated environment from inside sandbox', function (done) {
            context.execute(`
                var assert = require('assert');

                assert.strictEqual(pm.environment.get('var1'), 'one-env');
                pm.environment.set('var1', 'one-one-env');
                assert.strictEqual(pm.environment.get('var1'), 'one-one-env');

            `, {context: sampleContextData}, function (err, exec) {
                expect(err).not.be.ok();
                expect(exec).be.ok();
                expect(exec.environment.values).eql([
                    {type: 'any', value: 'one-one-env', key: 'var1'},
                    {type: 'number', value: 2.5, key: 'var2'}
                ]);
                done();
            });
        });
    });

    describe('request', function () {
        it('must be defined as sdk Request object', function (done) {
            context.execute(`
                var assert = require('assert'),
                    Request = require('postman-collection').Request;
                assert.strictEqual(Request.isRequest(pm.request), true);
            `, {
                context: {
                    request: 'https://postman-echo.com/get?foo=bar'
                }
            }, done);
        });

        it('must not be defined if request is missing in generic script target', function (done) {
            context.execute(`
                var assert = require('assert'),
                    Request = require('postman-collection').Request;
                assert.strictEqual(Request.isRequest(pm.request), undefined);
            `, done);
        });

        it.skip('must be defined in prerequest script even if request is missing in context', function (done) {
            context.execute({
                listen: 'prerequest',
                script: `
                var assert = require('assert'),
                    Request = require('postman-collection').Request;
                assert.strictEqual(Request.isRequest(pm.request), true);
            `
            }, done);
        });

        it.skip('must be defined in test script even if request is missing in context', function (done) {
            context.execute({
                listen: 'test',
                script: `
                var assert = require('assert'),
                    Request = require('postman-collection').Request;
                assert.strictEqual(Request.isRequest(pm.request), true);
            `
            }, done);
        });
    });
});
<|endoftext|>


<commit_before>import Backbone from 'backbone';
import { isUndefined } from 'underscore';
import ColorPicker from 'utils/ColorPicker';
import Input from './Input';

const $ = Backbone.$;
ColorPicker($);

export default Input.extend({
  template() {
    const ppfx = this.ppfx;
    return `

    `;
  },

  inputClass() {
    const ppfx = this.ppfx;
    return `${ppfx}field ${ppfx}field-color`;
  },

  holderClass() {
    return `${this.ppfx}input-holder`;
  },

  /**
   * Set value to the model
   * @param {string} val
   * @param {Object} opts
   */
  setValue(val, opts = {}) {
    const model = this.model;
    const def = model.get('defaults');
    const value = !isUndefined(val) ? val : !isUndefined(def) ? def : '';
    const inputEl = this.getInputEl();
    const colorEl = this.getColorEl();
    const valueClr = value != 'none' ? value : '';
    inputEl.value = value;
    colorEl.get(0).style.backgroundColor = valueClr;

    // This prevents from adding multiple thumbs in spectrum
    if (opts.fromTarget) {
      colorEl.spectrum('set', valueClr);
      this.noneColor = value == 'none';
    }
  },

  /**
   * Get the color input element
   * @return {HTMLElement}
   */
  getColorEl() {
    if (!this.colorEl) {
      const self = this;
      const ppfx = this.ppfx;
      var model = this.model;

      var colorEl = $(`<div class="${this.ppfx}field-color-picker"></div>`);
      var cpStyle = colorEl.get(0).style;
      var elToAppend = this.em && this.em.config ? this.em.config.el : '';
      var colorPickerConfig =
        (this.em && this.em.getConfig && this.em.getConfig('colorPicker')) ||
        {};
      const getColor = color => {
        let cl =
          color.getAlpha() == 1 ? color.toHexString() : color.toRgbString();
        return cl.replace(/ /g, '');
      };

      let changed = 0;
      let previousColor;
      this.$el.find(`[data-colorp-c]`).append(colorEl);
      colorEl.spectrum({
        containerClassName: `${ppfx}one-bg ${ppfx}two-color`,
        appendTo: elToAppend || 'body',
        maxSelectionSize: 8,
        showPalette: true,
        showAlpha: true,
        chooseText: 'Ok',
        cancelText: '⨯',
        palette: [],

        // config expanded here so that the functions below are not overridden
        ...colorPickerConfig,

        move(color) {
          const cl = getColor(color);
          cpStyle.backgroundColor = cl;
          model.setValueFromInput(cl, 0);
        },
        change(color) {
          changed = 1;
          const cl = getColor(color);
          cpStyle.backgroundColor = cl;
          model.setValueFromInput(0, 0); // for UndoManager
          model.setValueFromInput(cl);
          self.noneColor = 0;
        },
        show(color) {
          changed = 0;
          previousColor = getColor(color);
        },
        hide(color) {
          if (!changed && previousColor) {
            if (self.noneColor) {
              previousColor = '';
            }
            cpStyle.backgroundColor = previousColor;
            colorEl.spectrum('set', previousColor);
            model.setValueFromInput(previousColor, 0);
          }
        }
      });

      this.em &&
        this.em.on('component:selected', () => {
          changed = 1;
          colorEl.spectrum('hide');
        });

      this.colorEl = colorEl;
    }
    return this.colorEl;
  },

  render() {
    Input.prototype.render.call(this);
    // This will make the color input available on render
    this.getColorEl();
    return this;
  }
});
<commit_msg>Fix PropertyColorView tests<commit_after>import Backbone from 'backbone';
import { isUndefined } from 'underscore';
import ColorPicker from 'utils/ColorPicker';
import Input from './Input';

const $ = Backbone.$;
ColorPicker($);

export default Input.extend({
  template() {
    const ppfx = this.ppfx;
    return `

    `;
  },

  inputClass() {
    const ppfx = this.ppfx;
    return `${ppfx}field ${ppfx}field-color`;
  },

  holderClass() {
    return `${this.ppfx}input-holder`;
  },

  /**
   * Set value to the model
   * @param {string} val
   * @param {Object} opts
   */
  setValue(val, opts = {}) {
    const model = this.model;
    const def = model.get('defaults');
    const value = !isUndefined(val) ? val : !isUndefined(def) ? def : '';
    const inputEl = this.getInputEl();
    const colorEl = this.getColorEl();
    const valueClr = value != 'none' ? value : '';
    inputEl.value = value;
    colorEl.get(0).style.backgroundColor = valueClr;

    // This prevents from adding multiple thumbs in spectrum
    if (opts.fromTarget) {
      colorEl.spectrum('set', valueClr);
      this.noneColor = value == 'none';
    }
  },

  /**
   * Get the color input element
   * @return {HTMLElement}
   */
  getColorEl() {
    if (!this.colorEl) {
      const { em } = this;
      const self = this;
      const ppfx = this.ppfx;
      var model = this.model;

      var colorEl = $(`<div class="${this.ppfx}field-color-picker"></div>`);
      var cpStyle = colorEl.get(0).style;
      var elToAppend = em && em.config ? em.config.el : '';
      var colorPickerConfig =
        (em && em.getConfig && em.getConfig('colorPicker')) || {};
      const getColor = color => {
        let cl =
          color.getAlpha() == 1 ? color.toHexString() : color.toRgbString();
        return cl.replace(/ /g, '');
      };

      let changed = 0;
      let previousColor;
      this.$el.find(`[data-colorp-c]`).append(colorEl);
      colorEl.spectrum({
        containerClassName: `${ppfx}one-bg ${ppfx}two-color`,
        appendTo: elToAppend || 'body',
        maxSelectionSize: 8,
        showPalette: true,
        showAlpha: true,
        chooseText: 'Ok',
        cancelText: '⨯',
        palette: [],

        // config expanded here so that the functions below are not overridden
        ...colorPickerConfig,

        move(color) {
          const cl = getColor(color);
          cpStyle.backgroundColor = cl;
          model.setValueFromInput(cl, 0);
        },
        change(color) {
          changed = 1;
          const cl = getColor(color);
          cpStyle.backgroundColor = cl;
          model.setValueFromInput(0, 0); // for UndoManager
          model.setValueFromInput(cl);
          self.noneColor = 0;
        },
        show(color) {
          changed = 0;
          previousColor = getColor(color);
        },
        hide(color) {
          if (!changed && previousColor) {
            if (self.noneColor) {
              previousColor = '';
            }
            cpStyle.backgroundColor = previousColor;
            colorEl.spectrum('set', previousColor);
            model.setValueFromInput(previousColor, 0);
          }
        }
      });

      em &&
        em.on &&
        em.on('component:selected', () => {
          changed = 1;
          colorEl.spectrum('hide');
        });

      this.colorEl = colorEl;
    }
    return this.colorEl;
  },

  render() {
    Input.prototype.render.call(this);
    // This will make the color input available on render
    this.getColorEl();
    return this;
  }
});
<|endoftext|>


<commit_before>var defaults     = require('./utils/defaults');
var extend       = require('./utils/extend');
var inflector    = require('./utils/inflector');
var merge        = require('./utils/merge');
var mixin        = require('./utils/mixin');
var EventEmitter = require('events').EventEmitter;
var Model        = require('./Model');

// url
// sync
// fetch
// create
//
// set

var Collection = function(models, options) {
  mixin(this);

  options = options || {};

  this.length   = 0;
  this.models   = [];
  this._idCache = {};

  if (options.root) {
    this.root = options.root;
  }

  if (models) {
    this.add(models);
  }
};

Collection.extend = extend;

merge(Collection.prototype, EventEmitter.prototype, {
  model: Model,

  mixins: [],

  root: null,

  get: function(id) {
    return this._idCache[id];
  },

  at: function(index) {
    return this.models[index];
  },

  parse: function(response) {
    var parsed;

    if (response && this.root && response[this.root]) {
      parsed = response[this.root];
    } else {
      parsed = response;
    }

    if (!Array.isArray(parsed)) {
      parsed = [parsed];
    }

    return parsed;
  },

  dump: function(options) {
    var object = {};

    var models = this.models.map(function(model) {
      return merge({}, model.attributes);
    });

    if (options && options.rooted) {
      object[this.root] = models;

      return object;
    } else {
      return models;
    }
  },

  toJSON: function() {
    return this.dump.apply(this, arguments);
  },

  lookup: function(id, attributes) {
    var defaulted = defaults((attributes || {}), { id: id });

    this.add(defaulted);

    return this.get(id);
  },

  add: function(models, options) {
    var vivified, added = [];

    models  = this.parse(models);
    options = this._rootedOptions(options || {});

    models.forEach(function(attributes) {
      if (attributes instanceof this.model) {
        vivified = attributes;
      } else {
        vivified = new this.model(attributes, options);
      }

      if (!this.get(vivified.id)) {
        vivified.collection = this;

        this._storeModel(vivified);
        this._cacheModel(vivified);
        this.emit('add', vivified, this);

        added.push(vivified);
      }
    }, this);

    this.length = this.models.length;
    this.sort();

    return added;
  },

  remove: function(models, options) {
    options = options || {};

    if (!Array.isArray(models)) {
      models = [models];
    }

    models.forEach(function(model) {
      delete this._idCache[model.id];
      this.models.splice(this.models.indexOf(model), 1);

      model.emit('remove', model, this, options);
    }.bind(this));

    this.length = this.models.length;
  },

  sort: function(options) {
    options = options || {};

    if (this.comparitor) {
      this.models.sort(this.comparitor.bind(this));
    }

    if (this.comparitor && !options.silent) {
      this.emit('sort', this);
    }

    return this;
  },

  _storeModel: function(model) {
    this.models.push(model);
  },

  _cacheModel: function(model) {
    var idAttr = this.model.prototype.idAttribute;

    this._idCache[model.get(idAttr)] = model;
  },

  _rootedOptions: function(options) {
    if (this.root) {
      options.root = inflector.singularize(this.root);
    }

    return options;
  }
});

module.exports = Collection;
<commit_msg>Avoid using delete when removing models<commit_after>var defaults     = require('./utils/defaults');
var extend       = require('./utils/extend');
var inflector    = require('./utils/inflector');
var merge        = require('./utils/merge');
var mixin        = require('./utils/mixin');
var EventEmitter = require('events').EventEmitter;
var Model        = require('./Model');

// url
// sync
// fetch
// create
//
// set

var Collection = function(models, options) {
  mixin(this);

  options = options || {};

  this.length   = 0;
  this.models   = [];
  this._idCache = {};

  if (options.root) {
    this.root = options.root;
  }

  if (models) {
    this.add(models);
  }
};

Collection.extend = extend;

merge(Collection.prototype, EventEmitter.prototype, {
  model: Model,

  mixins: [],

  root: null,

  get: function(id) {
    return this._idCache[id];
  },

  at: function(index) {
    return this.models[index];
  },

  parse: function(response) {
    var parsed;

    if (response && this.root && response[this.root]) {
      parsed = response[this.root];
    } else {
      parsed = response;
    }

    if (!Array.isArray(parsed)) {
      parsed = [parsed];
    }

    return parsed;
  },

  dump: function(options) {
    var object = {};

    var models = this.models.map(function(model) {
      return merge({}, model.attributes);
    });

    if (options && options.rooted) {
      object[this.root] = models;

      return object;
    } else {
      return models;
    }
  },

  toJSON: function() {
    return this.dump.apply(this, arguments);
  },

  lookup: function(id, attributes) {
    var defaulted = defaults((attributes || {}), { id: id });

    this.add(defaulted);

    return this.get(id);
  },

  add: function(models, options) {
    var vivified, added = [];

    models  = this.parse(models);
    options = this._rootedOptions(options || {});

    models.forEach(function(attributes) {
      if (attributes instanceof this.model) {
        vivified = attributes;
      } else {
        vivified = new this.model(attributes, options);
      }

      if (!this.get(vivified.id)) {
        vivified.collection = this;

        this._storeModel(vivified);
        this._cacheModel(vivified);
        this.emit('add', vivified, this);

        added.push(vivified);
      }
    }, this);

    this.length = this.models.length;
    this.sort();

    return added;
  },

  remove: function(models, options) {
    options = options || {};

    if (!Array.isArray(models)) {
      models = [models];
    }

    models.forEach(function(model) {
      this._idCache[model.id] = undefined;
      this.models.splice(this.models.indexOf(model), 1);

      model.emit('remove', model, this, options);
    }.bind(this));

    this.length = this.models.length;
  },

  sort: function(options) {
    options = options || {};

    if (this.comparitor) {
      this.models.sort(this.comparitor.bind(this));
    }

    if (this.comparitor && !options.silent) {
      this.emit('sort', this);
    }

    return this;
  },

  _storeModel: function(model) {
    this.models.push(model);
  },

  _cacheModel: function(model) {
    var idAttr = this.model.prototype.idAttribute;

    this._idCache[model.get(idAttr)] = model;
  },

  _rootedOptions: function(options) {
    if (this.root) {
      options.root = inflector.singularize(this.root);
    }

    return options;
  }
});

module.exports = Collection;
<|endoftext|>


<commit_before>import createDebug from 'debug'
import log from './log'
import axios from 'axios'
import qs from 'qs'
import Mixpanel from 'mixpanel'

const debug = createDebug('dhm:Events')

export class Events {
  constructor ({console, gaTrackingId, mixpanelToken} = {}) {
    if (console) this.console = true
    this.gaTrackingId = gaTrackingId
    if (mixpanelToken) this.mixpanel = Mixpanel.init(mixpanelToken)
  }

  async track (e) {
    if (this.console) this.emitConsole(e)
    if (this.gaTrackingId) this.emitGoogleAnalytics(e)
    if (this.mixpanel) this.emitMixpanel(e)
  }

  emitConsole (event) {
    log.info({event}, 'event')
  }

  async emitGoogleAnalytics (event) {
    const {userId, category, action} = event
    if (!userId || !category || !action) return

    await axios.post('https://www.google-analytics.com/collect', {
      v: 1,
      tid: this.gaTrackingId,
      cid: userId,
      t: 'event',
      ec: category,
      ea: action
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      transformRequest: [(o) => qs.stringify(o)]
    })
  }

  async emitMixpanel (event) {
    const {userId, category, action, ...rest} = event
    if (!userId || !category || !action) return

    this.mixpanel.track(`${category}.${action}`, {
      distinct_id: userId,
      ...rest
    })
  }
}

export default new Events({
  console: true,
  gaTrackingId: process.env.GA_TRACKING_ID,
  mixpanelToken: process.env.MIXPANEL_TOKEN
})
<commit_msg>Fix style<commit_after>import axios from 'axios'
import qs from 'qs'
import Mixpanel from 'mixpanel'
import log from './log'

export class Events {
  constructor ({console, gaTrackingId, mixpanelToken} = {}) {
    if (console) this.console = true
    this.gaTrackingId = gaTrackingId
    if (mixpanelToken) this.mixpanel = Mixpanel.init(mixpanelToken)
  }

  async track (e) {
    if (this.console) this.emitConsole(e)
    if (this.gaTrackingId) this.emitGoogleAnalytics(e)
    if (this.mixpanel) this.emitMixpanel(e)
  }

  emitConsole (event) {
    log.info({event}, 'event')
  }

  async emitGoogleAnalytics (event) {
    const {userId, category, action} = event
    if (!userId || !category || !action) return

    await axios.post('https://www.google-analytics.com/collect', {
      v: 1,
      tid: this.gaTrackingId,
      cid: userId,
      t: 'event',
      ec: category,
      ea: action
    }, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      transformRequest: [(o) => qs.stringify(o)]
    })
  }

  async emitMixpanel (event) {
    const {userId, category, action, ...rest} = event
    if (!userId || !category || !action) return

    this.mixpanel.track(`${category}.${action}`, {
      distinct_id: userId,
      ...rest
    })
  }
}

export default new Events({
  console: true,
  gaTrackingId: process.env.GA_TRACKING_ID,
  mixpanelToken: process.env.MIXPANEL_TOKEN
})
<|endoftext|>


<commit_before>module.exports = {
  "env": {
    "browser": true,
    "commonjs": true,
    "node": true
  },
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 6
  },
  "extends": "eslint:recommended",
  "globals": [
    // browser
    "window", "document", "URL", "XMLHttpRequest",
    // browser / nodejs
    "console", "setTimeout", "setInterval", "clearInterval",
    // nodejs
    "global",
    // EcmaScript 6
    "Promise", "Map", "Set", "WeakMap",
    // commonjs
    "require", "module", "exports"
    //
  ].reduce((m, key)=>{m[key]=true;return m}, {}),
  "rules": {
    // 0 - off, 1 - warning, 2 - error
    "indent": ["error", 2, { "SwitchCase": 1, "MemberExpression": "off" }],
    "semi": [0, "never"],
    "comma-dangle": [2, "only-multiline"],
    "no-cond-assign": 2,
    "no-console": [2, { allow: ["warn", "info", "error", "assert"] }],
    "no-constant-condition": 2,
    "no-control-regex": 2,
    "no-debugger": 2,
    "no-dupe-args": 2,
    "no-dupe-keys": 2,
    "no-duplicate-case": 2,
    "no-empty": 1,
    "no-empty-character-class": 2,
    "no-ex-assign": 2,
    "no-extra-boolean-cast": 2,
    "no-extra-parens": 0,
    "no-extra-semi": 2,
    "no-func-assign": 2,
    "no-inner-declarations": 2,
    "no-invalid-regexp": 2,
    "no-irregular-whitespace": 2,
    "no-negated-in-lhs": 2,
    "no-obj-calls": 2,
    // turned of as we want to be able to use this.hasOwnProperty() for instance
    "no-prototype-builtins": 0,
    "no-regex-spaces": 2,
    "no-sparse-arrays": 0,
    "no-unexpected-multiline": 2,
    "no-unreachable": 2,
    "no-unsafe-finally": 2,
    "use-isnan": 2,
    "valid-jsdoc": 0,
    "valid-typeof": 2,
    "strict": 0, // [2, "safe"],

    // Best practices
    "accessor-pairs": 0,
    "array-callback-return": 2,
    "block-scoped-var": 2,
    "complexity": [0, 10],
    "consistent-return": 0,
    "curly": [2, "multi-line"],
    "default-case": 2,
    "dot-location": [2, 'property'],
    "dot-notation": 0,
    "eqeqeq": 2,
    "guard-for-in": 2,
    "no-alert": 2,
    "no-caller": 2,
    "no-case-declarations": 2,
    "no-div-regex": 2,
    "no-else-return": 0,
    "no-empty-function": 0,
    // if you want to check for undefined or null use lodash/isNil
    "no-eq-null": 2,
    "no-eval": 2,
    "no-extend-native": 2,
    "no-extra-bind": 2,
    "no-extra-label": 2,
    "no-fallthrough": 2,
    "no-floating-decimal": 2,
    "no-implicit-coercion": 2,
    "no-implicit-globals": 2,
    "no-implied-eval": 2,
    "no-invalid-this": 2,
    "no-iterator": 2,
    "no-labels": 2,
    "no-lone-blocks": 0,
    "no-loop-func": 2,
    "no-magic-numbers": 0,
    "no-multi-spaces": 2,
    "no-multi-str": 0,
    "no-native-reassign": 2,
    "no-new": 0,
    "no-new-func": 0,
    "no-new-wrappers": 2,
    "no-octal": 2,
    "no-octal-escape": 2,
    "no-param-reassign": 0,
    "no-proto": 2,
    "no-redeclare": 2,
    "no-return-assign": 2,
    "no-script-url": 2,
    "no-self-assign": 2,
    "no-self-compare": 2,
    "no-sequences": 2,
    "no-throw-literal": 2,
    "no-unmodified-loop-condition": 2,
    "no-unused-expressions": 2,
    "no-unused-labels": 2,
    "no-useless-call": 2,
    "no-useless-concat": 2,
    "no-useless-escape": 2,
    "no-void": 2,
    "no-warning-comments": 0,
    "no-with": 2,
    "radix": 2,
    "vars-on-top": 0,
    "wrap-iife": 2,
    "yoda": 0,
    // variables
    "init-declarations": 0,
    "no-catch-shadow": 2,
    "no-delete-var": 2,
    "no-label-var": 2,
    "no-restricted-globals": 2,
    "no-shadow": 0,
    "no-shadow-restricted-names": 2,
    "no-undef": 2,
    "no-undef-init": 2,
    "no-undefined": 0,
    "no-unused-vars": 2,
    "no-use-before-define": [2, { "functions": false, "classes": false }]
  }
};<commit_msg>Lint for es8<commit_after>module.exports = {
  "env": {
    "browser": true,
    "commonjs": true,
    "node": true
  },
  "parserOptions": {
    "sourceType": "module",
    "ecmaVersion": 8
  },
  "extends": "eslint:recommended",
  "globals": [
    // browser
    "window", "document", "URL", "XMLHttpRequest",
    // browser / nodejs
    "console", "setTimeout", "setInterval", "clearInterval",
    // nodejs
    "global",
    // EcmaScript 6
    "Promise", "Map", "Set", "WeakMap",
    // commonjs
    "require", "module", "exports"
    //
  ].reduce((m, key)=>{m[key]=true;return m}, {}),
  "rules": {
    // 0 - off, 1 - warning, 2 - error
    "indent": ["error", 2, { "SwitchCase": 1, "MemberExpression": "off" }],
    "semi": [0, "never"],
    "comma-dangle": [2, "only-multiline"],
    "no-cond-assign": 2,
    "no-console": [2, { allow: ["warn", "info", "error", "assert"] }],
    "no-constant-condition": 2,
    "no-control-regex": 2,
    "no-debugger": 2,
    "no-dupe-args": 2,
    "no-dupe-keys": 2,
    "no-duplicate-case": 2,
    "no-empty": 1,
    "no-empty-character-class": 2,
    "no-ex-assign": 2,
    "no-extra-boolean-cast": 2,
    "no-extra-parens": 0,
    "no-extra-semi": 2,
    "no-func-assign": 2,
    "no-inner-declarations": 2,
    "no-invalid-regexp": 2,
    "no-irregular-whitespace": 2,
    "no-negated-in-lhs": 2,
    "no-obj-calls": 2,
    // turned of as we want to be able to use this.hasOwnProperty() for instance
    "no-prototype-builtins": 0,
    "no-regex-spaces": 2,
    "no-sparse-arrays": 0,
    "no-unexpected-multiline": 2,
    "no-unreachable": 2,
    "no-unsafe-finally": 2,
    "use-isnan": 2,
    "valid-jsdoc": 0,
    "valid-typeof": 2,
    "strict": 0, // [2, "safe"],

    // Best practices
    "accessor-pairs": 0,
    "array-callback-return": 2,
    "block-scoped-var": 2,
    "complexity": [0, 10],
    "consistent-return": 0,
    "curly": [2, "multi-line"],
    "default-case": 2,
    "dot-location": [2, 'property'],
    "dot-notation": 0,
    "eqeqeq": 2,
    "guard-for-in": 2,
    "no-alert": 2,
    "no-caller": 2,
    "no-case-declarations": 2,
    "no-div-regex": 2,
    "no-else-return": 0,
    "no-empty-function": 0,
    // if you want to check for undefined or null use lodash/isNil
    "no-eq-null": 2,
    "no-eval": 2,
    "no-extend-native": 2,
    "no-extra-bind": 2,
    "no-extra-label": 2,
    "no-fallthrough": 2,
    "no-floating-decimal": 2,
    "no-implicit-coercion": 2,
    "no-implicit-globals": 2,
    "no-implied-eval": 2,
    "no-invalid-this": 2,
    "no-iterator": 2,
    "no-labels": 2,
    "no-lone-blocks": 0,
    "no-loop-func": 2,
    "no-magic-numbers": 0,
    "no-multi-spaces": 2,
    "no-multi-str": 0,
    "no-native-reassign": 2,
    "no-new": 0,
    "no-new-func": 0,
    "no-new-wrappers": 2,
    "no-octal": 2,
    "no-octal-escape": 2,
    "no-param-reassign": 0,
    "no-proto": 2,
    "no-redeclare": 2,
    "no-return-assign": 2,
    "no-script-url": 2,
    "no-self-assign": 2,
    "no-self-compare": 2,
    "no-sequences": 2,
    "no-throw-literal": 2,
    "no-unmodified-loop-condition": 2,
    "no-unused-expressions": 2,
    "no-unused-labels": 2,
    "no-useless-call": 2,
    "no-useless-concat": 2,
    "no-useless-escape": 2,
    "no-void": 2,
    "no-warning-comments": 0,
    "no-with": 2,
    "radix": 2,
    "vars-on-top": 0,
    "wrap-iife": 2,
    "yoda": 0,
    // variables
    "init-declarations": 0,
    "no-catch-shadow": 2,
    "no-delete-var": 2,
    "no-label-var": 2,
    "no-restricted-globals": 2,
    "no-shadow": 0,
    "no-shadow-restricted-names": 2,
    "no-undef": 2,
    "no-undef-init": 2,
    "no-undefined": 0,
    "no-unused-vars": 2,
    "no-use-before-define": [2, { "functions": false, "classes": false }]
  }
};<|endoftext|>


<commit_before>module.exports = {
    "env": {
        "browser": true,
        "es6": true,
		"amd" : true,
		"node" : true,
		"mocha": true
    },
    "globals": {
        "expect": true
    },
    "extends": "eslint:recommended",
    "rules": {
		"dot-location" : [ "error", "property" ],
		"linebreak-style": [ "error", "unix" ],
		"eqeqeq" : [ "error" ],
		"curly" : [ "error", "all" ],
		"dot-notation" : [ "error" ],
		"no-throw-literal" : [ "error" ],
		"no-useless-call" : [ "error" ],
		"no-unmodified-loop-condition": [ "error" ],
		"quote-props" : [ "error", "consistent" /*"as-needed"*/ ],
		"quotes": [ "error","double" ],
		"no-lonely-if" : [ "error" ],
		"semi": [ "error", "always" ],
		//STYLE
		"indent": [ "error", "tab", { "SwitchCase": 1 } ],
		"no-multi-spaces" : [ "error" ],
		"array-bracket-spacing" : [ "error" , "never" ],
		"block-spacing": [ "error", "always" ],
		"func-call-spacing" : [ "error", "never" ],
		"key-spacing" : [ "error", {"beforeColon" : true, "afterColon" : true} ],
		"brace-style": [ "error", "1tbs" ],
		"space-in-parens": [ "error", "never" ],
		"eol-last": [ "error", "always" ],
		"lines-between-class-members": [ "error", "always" ],
		"no-multiple-empty-lines": [ "error", { "max": 1, "maxEOF": 1, "maxBOF": 0} ],
		"no-unneeded-ternary": [ "error" ],
		"object-curly-spacing": [ "error" , "always" ],
		"space-unary-ops": [ "error" , { "words" : true, "nonwords" : false } ],
		"block-spacing" : ["error", "always"],
		"keyword-spacing" : ["error", { "before": true }],
		"space-before-function-paren": ["error", "never"],
		"comma-spacing": ["error", { "before": false, "after": true }],
        "space-before-blocks": ["error", "never"]
		// "one-var-declaration-per-line": [ "error" , "always" ],
		// "object-curly-newline": [ "error" , { "multiline": true }],
		// "array-bracket-newline": [ "error" , "always" ],
		// "no-use-before-define" : [ "error" ],
		// "valid-jsdoc": [ "error" ],
		// "lines-around-comment" : [ "error", {"beforeBlockComment": true} ],
		// "no-template-curly-in-string" : [ "error" ],
    }
};
<commit_msg>updating linting rules<commit_after>module.exports = {
    "env": {
        "browser": true,
        "es6": true,
		"amd" : true,
		"node" : true,
		"mocha": true
    },
    "globals": {
        "expect": true
    },
    "extends": "eslint:recommended",
    "rules": {
		"dot-location" : [ "error", "property" ],
		"linebreak-style": [ "error", "unix" ],
		"eqeqeq" : [ "error" ],
		"curly" : [ "error", "all" ],
		"dot-notation" : [ "error" ],
		"no-throw-literal" : [ "error" ],
		"no-useless-call" : [ "error" ],
		"no-unmodified-loop-condition": [ "error" ],
		"quote-props" : [ "error", "consistent" /*"as-needed"*/ ],
		"quotes": [ "error","double" ],
		"no-lonely-if" : [ "error" ],
		"semi": [ "error", "always" ],
		//STYLE
		"indent": [ "error", "tab", { "SwitchCase": 1 } ],
		"no-multi-spaces" : [ "error" ],
		"array-bracket-spacing" : [ "error" , "never" ],
		"block-spacing": [ "error", "always" ],
		"func-call-spacing" : [ "error", "never" ],
		"key-spacing" : [ "error", {"beforeColon" : true, "afterColon" : true} ],
		"brace-style": [ "error", "1tbs" ],
		"space-in-parens": [ "error", "never" ],
		"eol-last": [ "error", "always" ],
		"lines-between-class-members": [ "error", "always" ],
		"no-multiple-empty-lines": [ "error", { "max": 1, "maxEOF": 1, "maxBOF": 0} ],
		"no-unneeded-ternary": [ "error" ],
		"object-curly-spacing": [ "error" , "always" ],
		"space-unary-ops": [ "error" , { "words" : true, "nonwords" : false } ],
		"block-spacing" : ["error", "always"],
		"keyword-spacing" : ["error", { "before": true }],
		"space-before-function-paren": ["error", "never"],
		"comma-spacing": ["error", { "before": false, "after": true }],
        "space-before-blocks": ["error", { "functions": "never", "keywords": "never", "classes": "always" }]
		// "one-var-declaration-per-line": [ "error" , "always" ],
		// "object-curly-newline": [ "error" , { "multiline": true }],
		// "array-bracket-newline": [ "error" , "always" ],
		// "no-use-before-define" : [ "error" ],
		// "valid-jsdoc": [ "error" ],
		// "lines-around-comment" : [ "error", {"beforeBlockComment": true} ],
		// "no-template-curly-in-string" : [ "error" ],
    }
};
<|endoftext|>