<commit_before>/**
 * Copyright (c) 2017 AriyaLabs, LLC. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

module.exports = {
  'rules': {
    // The rules below are listed in the order they appear on the eslint
    // rules page. All rules are listed to make it easier to keep in sync
    // as new ESLint rules are added.
    // http://eslint.org/docs/rules/
    // - Rules in the `eslint:recommended` ruleset that aren't listed but commented out (so
    //   they don't override a base ruleset).
    // - Rules that are recommended but contradict Pier 1 Imports
    //   are explicitly set to the Pier 1 Imports value.

    // Possible Errors
    // http://eslint.org/docs/rules/#possible-errors
    // ---------------------------------------------
    // 'no-cond-assign': 2,
    'no-console': 1,
    // '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-character-class': 2,
    // 'no-empty': 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-obj-calls': 2,
    // 'no-prototype-builtins': 0,
    // 'no-regex-spaces': 2,
    // 'no-sparse-arrays': 2,
    // 'no-template-curly-in-string': 0,
    // 'no-unexpected-multiline': 2,
    // 'no-unreachable': 2,
    // 'no-unsafe-finally': 2,
    // 'no-unsafe-negation': 0,
    // 'use-isnan': 2
    // 'valid-jsdoc': [
    //   1, {
    //     requireParamDescription: false,
    //     requireReturnDescription: false,
    //     requireReturn: false,
    //     prefer: { returns: 'return' },
    //   }
    // ],
    // 'valid-typeof': 2

    // Best Practices
    // http://eslint.org/docs/rules/#best-practices
    // --------------------------------------------

    // 'accessor-pairs': 0,
    // 'array-callback-return': 0,
    // 'block-scoped-var': 0,
    // 'class-methods-use-this': 0,
    // 'complexity': 0,
    // 'consistent-return': 0
    // 'curly': 0,
    // 'default-case': 0,
    // 'dot-location': 0,
    // 'dot-notation': 0,
    'eqeqeq': 2,
    'guard-for-in': 2,
    // 'no-alert': 0,
    'no-caller': 2,
    // 'no-case-declarations': 2,
    // 'no-div-regex': 0,
    // 'no-else-return': 0,
    // 'no-empty-function': 0,
    // 'no-empty-pattern': 2,
    // 'no-eq-null': 0,
    // 'no-eval': 0,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    // 'no-extra-label': 0,
    // 'no-fallthrough': 2,
    // 'no-floating-decimal': 0,
    // 'no-global-assign': 0,
    'no-implicit-coercion': 2,
    // 'no-implicit-globals': 0,
    // 'no-implied-eval': 0,
    'no-invalid-this': 1,
    // 'no-iterator': 0,
    // 'no-labels': 0,
    // 'no-lone-blocks': 0,
    // 'no-loop-func': 0,
    // 'no-magic-numbers': 0,
    'no-multi-spaces': 2,
    'no-multi-str': 0,
    // 'no-new-func': 0,
    'no-new-wrappers': 2,
    // 'no-new': 0,
    // 'no-octal-escape': 0,
    // 'no-octal': 2,
    'no-param-reassign': 2,
    // 'no-proto': 0,
    // 'no-redeclare': 2,
    // 'no-return-assign': 0,
    // 'no-script-url': 0,
    // 'no-self-assign': 2,
    // 'no-self-compare': 0,
    // 'no-sequences': 0,
    'no-throw-literal': 2,
    // 'no-unmodified-loop-condition': 0,
    // 'no-unused-expressions': 0,
    // 'no-unused-labels': 2,
    // 'no-useless-call': 0,
    // 'no-useless-concat': 0,
    // 'no-useless-escape': 0,
    // 'no-void': 0,
    // 'no-warning-comments': 0,
    'no-with': 2,
    // 'radix': 0,
    // 'vars-on-top': 0,
    // 'wrap-iife': 0,
    // 'yoda': 0,

    // Strict Mode
    // http://eslint.org/docs/rules/#strict-mode
    // -----------------------------------------
    // 'script': 0,

    // Variables
    // http://eslint.org/docs/rules/#variables
    // ---------------------------------------
    // 'init-declarations': 0,
    // 'no-catch-shadow': 0,
    // 'no-delete-var': 2,
    // 'no-label-var': 0,
    // 'no-restricted-globals': 0,
    // 'no-shadow-restricted-names': 0,
    // 'no-shadow': 0,
    // 'no-undef-init': 0,
    // 'no-undef': 2,
    // 'no-undefined': 0,
    'no-unused-vars': [
      1, {
        'vars': 'local',
        'args': 'none',
        'varsIgnorePattern': 'execute',
      },
    ],
    // 'no-use-before-define': 0,

    // Node.js and CommonJS
    // http://eslint.org/docs/rules/#nodejs-and-commonjs
    // -------------------------------------------------
    // 'callback-return': 0,
    // 'global-require': 0,
    // 'handle-callback-err': 0,
    // 'no-mixed-requires': 0,
    // 'no-new-require': 0,
    // 'no-path-concat': 0,
    // 'no-process-env': 0,
    // 'no-process-exit': 0,
    // 'no-restricted-modules': 0,
    // 'no-restricted-properties': 0,
    // 'no-sync': 0,

    // Stylistic Issues
    // http://eslint.org/docs/rules/#stylistic-issues
    // ----------------------------------------------
    'array-bracket-spacing': [2, 'never'],
    // 'block-spacing': 0,
    'brace-style': 0,
    'camelcase': [2, { properties: 'always' }],
    'comma-dangle': [2, {
      'arrays': 'always-multiline',
      'objects': 'always-multiline',
      'imports': 'always-multiline',
      'exports': 'always-multiline',
      'functions': 'always-multiline',
    }],
    'comma-spacing': 2,
    'comma-style': 2,
    'computed-property-spacing': 2,
    // 'consistent-this': 0,
    'eol-last': 2,
    'func-call-spacing': 2,
    // 'func-name-matching': 0,
    // 'func-names': 0,
    // 'func-style': 0,
    // 'id-blacklist': 0,
    // 'id-length': 0,
    // 'id-match': 0,
    'indent': [
      2,
      2,
      { "SwitchCase": 1 }
    ],
    // 'jsx-quotes': 0,
    'key-spacing': 2,
    'keyword-spacing': 2,
    // 'line-comment-position': 0,
    'linebreak-style': 0,
    // 'lines-around-comment': 0,
    // 'lines-around-directive': 0,
    // 'max-depth': 0,
    'max-len': 0,
    // 'max-lines': 0,
    // 'max-nested-callbacks': 0,
    // 'max-params': 0,
    // 'max-statements-per-line': 0,
    // 'max-statements': 0,
    // 'multiline-ternary': 0,
    'new-cap': [
      2, {
        'newIsCap': true,
        'capIsNew': false,
        'properties': true,
      },
    ],
    // 'new-parens': 0,
    // 'newline-after-var': 0,
    // 'newline-before-return': 0,
    // 'newline-per-chained-call': 0,
    'no-array-constructor': 2,
    // 'no-bitwise': 0,
    // 'no-continue': 0,
    // 'no-inline-comments': 0,
    // 'no-lonely-if': 0,
    // 'no-mixed-operators': 0,
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, { max: 2 }],
    // 'no-negated-condition': 0,
    // 'no-nested-ternary': 0,
    'no-new-object': 2,
    // 'no-plusplus': 0,
    // 'no-restricted-syntax': 0,
    'no-tabs': 2,
    // 'no-ternary': 0,
    // 'no-trailing-spaces': 0,
    // 'no-underscore-dangle': 0,
    // 'no-unneeded-ternary': 0,
    // 'no-whitespace-before-property': 0,
    // 'object-curly-newline': 0,
    'object-curly-spacing': [2, 'always'],
    // 'object-property-newline': 0,
    'one-var-declaration-per-line': [2, 'always'],
    'one-var': "off",
    // 'operator-assignment': 0,
    // 'operator-linebreak': 0,
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'consistent'],
    'quotes': [
      2,
      'single', { allowTemplateLiterals: true },
    ],
    // 'require-jsdoc': [
    //   1, {
    //     require: {
    //       FunctionDeclaration: true,
    //       MethodDefinition: true,
    //       ClassDeclaration: true,
    //     },
    //   }
    // ],
    'semi-spacing': 2,
    'semi': 2,
    // 'sort-keys': 0,
    // 'sort-vars': 0,
    'space-before-blocks': 2,
    'space-before-function-paren': [
      2, {
        'anonymous': 'always',
        'named': 'never',
        'asyncArrow': 'never',
      },
    ],
    // 'space-in-parens': 0,
    // 'space-infix-ops': 0,
    // 'space-unary-ops': 0,
    'spaced-comment': 0,
    // 'unicode-bom': 0,
    // 'wrap-regex': 0,

    // ECMAScript 6
    // http://eslint.org/docs/rules/#ecmascript-6
    // ------------------------------------------
    // 'arrow-body-style': 0,
    'arrow-parens': [2, 'always'],
    // 'arrow-spacing': 0,
    // 'constructor-super': 2,
    'generator-star-spacing': [2, 'after'],
    // 'no-class-assign': 0,
    // 'no-confusing-arrow': 0,
    // 'no-const-assign': 0,
    // 'no-dupe-class-members': 0,
    // 'no-duplicate-imports': 0,
    'no-new-symbol': 2,
    // 'no-restricted-imports': 0,
    // 'no-this-before-super': 2,
    // 'no-useless-computed-key': 0,
    // 'no-useless-constructor': 0,
    // 'no-useless-rename': 0,
    // 'no-var': 0,
    // 'object-shorthand': 0,
    // 'prefer-arrow-callback': 0,
    // 'prefer-const': 0,
    // 'prefer-numeric-literals': 0,
    // 'prefer-reflect': 0,
    // 'prefer-rest-params': 0,
    // 'prefer-spread': 0,
    // 'prefer-template': 0,
    // 'require-yield': 2,
    // 'rest-spread-spacing': 0,
    // 'sort-imports': 0,
    // 'symbol-description': 0,
    // 'template-curly-spacing': 0,
    'yield-star-spacing': [2, 'after'],
  },
  'plugins': [
    'eslint-plugin-react',
    'eslint-plugin-mocha',
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'jsx': true,
    },
  },
  'env': {
    'browser': true,
    'commonjs': true,
    'es6': true,
    'jquery': true,
    'mocha': true,
    'node': true,
  },
  'globals': {},
  'parser': 'babel-eslint',
};
<commit_msg>Relaxed arrow-parens<commit_after>/**
 * Copyright (c) 2017 AriyaLabs, LLC. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

'use strict';

module.exports = {
  'rules': {
    // The rules below are listed in the order they appear on the eslint
    // rules page. All rules are listed to make it easier to keep in sync
    // as new ESLint rules are added.
    // http://eslint.org/docs/rules/
    // - Rules in the `eslint:recommended` ruleset that aren't listed but commented out (so
    //   they don't override a base ruleset).
    // - Rules that are recommended but contradict Pier 1 Imports
    //   are explicitly set to the Pier 1 Imports value.

    // Possible Errors
    // http://eslint.org/docs/rules/#possible-errors
    // ---------------------------------------------
    // 'no-cond-assign': 2,
    'no-console': 1,
    // '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-character-class': 2,
    // 'no-empty': 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-obj-calls': 2,
    // 'no-prototype-builtins': 0,
    // 'no-regex-spaces': 2,
    // 'no-sparse-arrays': 2,
    // 'no-template-curly-in-string': 0,
    // 'no-unexpected-multiline': 2,
    // 'no-unreachable': 2,
    // 'no-unsafe-finally': 2,
    // 'no-unsafe-negation': 0,
    // 'use-isnan': 2
    // 'valid-jsdoc': [
    //   1, {
    //     requireParamDescription: false,
    //     requireReturnDescription: false,
    //     requireReturn: false,
    //     prefer: { returns: 'return' },
    //   }
    // ],
    // 'valid-typeof': 2

    // Best Practices
    // http://eslint.org/docs/rules/#best-practices
    // --------------------------------------------

    // 'accessor-pairs': 0,
    // 'array-callback-return': 0,
    // 'block-scoped-var': 0,
    // 'class-methods-use-this': 0,
    // 'complexity': 0,
    // 'consistent-return': 0
    // 'curly': 0,
    // 'default-case': 0,
    // 'dot-location': 0,
    // 'dot-notation': 0,
    'eqeqeq': 2,
    'guard-for-in': 2,
    // 'no-alert': 0,
    'no-caller': 2,
    // 'no-case-declarations': 2,
    // 'no-div-regex': 0,
    // 'no-else-return': 0,
    // 'no-empty-function': 0,
    // 'no-empty-pattern': 2,
    // 'no-eq-null': 0,
    // 'no-eval': 0,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    // 'no-extra-label': 0,
    // 'no-fallthrough': 2,
    // 'no-floating-decimal': 0,
    // 'no-global-assign': 0,
    'no-implicit-coercion': 2,
    // 'no-implicit-globals': 0,
    // 'no-implied-eval': 0,
    'no-invalid-this': 1,
    // 'no-iterator': 0,
    // 'no-labels': 0,
    // 'no-lone-blocks': 0,
    // 'no-loop-func': 0,
    // 'no-magic-numbers': 0,
    'no-multi-spaces': 2,
    'no-multi-str': 0,
    // 'no-new-func': 0,
    'no-new-wrappers': 2,
    // 'no-new': 0,
    // 'no-octal-escape': 0,
    // 'no-octal': 2,
    'no-param-reassign': 2,
    // 'no-proto': 0,
    // 'no-redeclare': 2,
    // 'no-return-assign': 0,
    // 'no-script-url': 0,
    // 'no-self-assign': 2,
    // 'no-self-compare': 0,
    // 'no-sequences': 0,
    'no-throw-literal': 2,
    // 'no-unmodified-loop-condition': 0,
    // 'no-unused-expressions': 0,
    // 'no-unused-labels': 2,
    // 'no-useless-call': 0,
    // 'no-useless-concat': 0,
    // 'no-useless-escape': 0,
    // 'no-void': 0,
    // 'no-warning-comments': 0,
    'no-with': 2,
    // 'radix': 0,
    // 'vars-on-top': 0,
    // 'wrap-iife': 0,
    // 'yoda': 0,

    // Strict Mode
    // http://eslint.org/docs/rules/#strict-mode
    // -----------------------------------------
    // 'script': 0,

    // Variables
    // http://eslint.org/docs/rules/#variables
    // ---------------------------------------
    // 'init-declarations': 0,
    // 'no-catch-shadow': 0,
    // 'no-delete-var': 2,
    // 'no-label-var': 0,
    // 'no-restricted-globals': 0,
    // 'no-shadow-restricted-names': 0,
    // 'no-shadow': 0,
    // 'no-undef-init': 0,
    // 'no-undef': 2,
    // 'no-undefined': 0,
    'no-unused-vars': [
      1, {
        'vars': 'local',
        'args': 'none',
        'varsIgnorePattern': 'execute',
      },
    ],
    // 'no-use-before-define': 0,

    // Node.js and CommonJS
    // http://eslint.org/docs/rules/#nodejs-and-commonjs
    // -------------------------------------------------
    // 'callback-return': 0,
    // 'global-require': 0,
    // 'handle-callback-err': 0,
    // 'no-mixed-requires': 0,
    // 'no-new-require': 0,
    // 'no-path-concat': 0,
    // 'no-process-env': 0,
    // 'no-process-exit': 0,
    // 'no-restricted-modules': 0,
    // 'no-restricted-properties': 0,
    // 'no-sync': 0,

    // Stylistic Issues
    // http://eslint.org/docs/rules/#stylistic-issues
    // ----------------------------------------------
    'array-bracket-spacing': [2, 'never'],
    // 'block-spacing': 0,
    'brace-style': 0,
    'camelcase': [2, { properties: 'always' }],
    'comma-dangle': [2, {
      'arrays': 'always-multiline',
      'objects': 'always-multiline',
      'imports': 'always-multiline',
      'exports': 'always-multiline',
      'functions': 'always-multiline',
    }],
    'comma-spacing': 2,
    'comma-style': 2,
    'computed-property-spacing': 2,
    // 'consistent-this': 0,
    'eol-last': 2,
    'func-call-spacing': 2,
    // 'func-name-matching': 0,
    // 'func-names': 0,
    // 'func-style': 0,
    // 'id-blacklist': 0,
    // 'id-length': 0,
    // 'id-match': 0,
    'indent': [
      2,
      2,
      { "SwitchCase": 1 }
    ],
    // 'jsx-quotes': 0,
    'key-spacing': 2,
    'keyword-spacing': 2,
    // 'line-comment-position': 0,
    'linebreak-style': 0,
    // 'lines-around-comment': 0,
    // 'lines-around-directive': 0,
    // 'max-depth': 0,
    'max-len': 0,
    // 'max-lines': 0,
    // 'max-nested-callbacks': 0,
    // 'max-params': 0,
    // 'max-statements-per-line': 0,
    // 'max-statements': 0,
    // 'multiline-ternary': 0,
    'new-cap': [
      2, {
        'newIsCap': true,
        'capIsNew': false,
        'properties': true,
      },
    ],
    // 'new-parens': 0,
    // 'newline-after-var': 0,
    // 'newline-before-return': 0,
    // 'newline-per-chained-call': 0,
    'no-array-constructor': 2,
    // 'no-bitwise': 0,
    // 'no-continue': 0,
    // 'no-inline-comments': 0,
    // 'no-lonely-if': 0,
    // 'no-mixed-operators': 0,
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, { max: 2 }],
    // 'no-negated-condition': 0,
    // 'no-nested-ternary': 0,
    'no-new-object': 2,
    // 'no-plusplus': 0,
    // 'no-restricted-syntax': 0,
    'no-tabs': 2,
    // 'no-ternary': 0,
    // 'no-trailing-spaces': 0,
    // 'no-underscore-dangle': 0,
    // 'no-unneeded-ternary': 0,
    // 'no-whitespace-before-property': 0,
    // 'object-curly-newline': 0,
    'object-curly-spacing': [2, 'always'],
    // 'object-property-newline': 0,
    'one-var-declaration-per-line': [2, 'always'],
    'one-var': "off",
    // 'operator-assignment': 0,
    // 'operator-linebreak': 0,
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'consistent'],
    'quotes': [
      2,
      'single', { allowTemplateLiterals: true },
    ],
    // 'require-jsdoc': [
    //   1, {
    //     require: {
    //       FunctionDeclaration: true,
    //       MethodDefinition: true,
    //       ClassDeclaration: true,
    //     },
    //   }
    // ],
    'semi-spacing': 2,
    'semi': 2,
    // 'sort-keys': 0,
    // 'sort-vars': 0,
    'space-before-blocks': 2,
    'space-before-function-paren': [
      2, {
        'anonymous': 'always',
        'named': 'never',
        'asyncArrow': 'never',
      },
    ],
    // 'space-in-parens': 0,
    // 'space-infix-ops': 0,
    // 'space-unary-ops': 0,
    'spaced-comment': 0,
    // 'unicode-bom': 0,
    // 'wrap-regex': 0,

    // ECMAScript 6
    // http://eslint.org/docs/rules/#ecmascript-6
    // ------------------------------------------
    // 'arrow-body-style': 0,
    'arrow-parens': [1, 'always'],
    // 'arrow-spacing': 0,
    // 'constructor-super': 2,
    'generator-star-spacing': [2, 'after'],
    // 'no-class-assign': 0,
    // 'no-confusing-arrow': 0,
    // 'no-const-assign': 0,
    // 'no-dupe-class-members': 0,
    // 'no-duplicate-imports': 0,
    'no-new-symbol': 2,
    // 'no-restricted-imports': 0,
    // 'no-this-before-super': 2,
    // 'no-useless-computed-key': 0,
    // 'no-useless-constructor': 0,
    // 'no-useless-rename': 0,
    // 'no-var': 0,
    // 'object-shorthand': 0,
    // 'prefer-arrow-callback': 0,
    // 'prefer-const': 0,
    // 'prefer-numeric-literals': 0,
    // 'prefer-reflect': 0,
    // 'prefer-rest-params': 0,
    // 'prefer-spread': 0,
    // 'prefer-template': 0,
    // 'require-yield': 2,
    // 'rest-spread-spacing': 0,
    // 'sort-imports': 0,
    // 'symbol-description': 0,
    // 'template-curly-spacing': 0,
    'yield-star-spacing': [2, 'after'],
  },
  'plugins': [
    'eslint-plugin-react',
    'eslint-plugin-mocha',
  ],
  'parserOptions': {
    'ecmaFeatures': {
      'jsx': true,
    },
  },
  'env': {
    'browser': true,
    'commonjs': true,
    'es6': true,
    'jquery': true,
    'mocha': true,
    'node': true,
  },
  'globals': {},
  'parser': 'babel-eslint',
};
<|endoftext|>


<commit_before>/***
 * dpd-neo4j
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013 Alexander Forselius
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

var Resource = require('deployd/lib/resource')
  , httpUtil = require('deployd/lib/util/http')
  , Script = require('deployd/lib/script')
  , neo4j = require('neo4j')
  , util = require('util')
  , path = require('path');
function Neo4JResource() {
  Resource.apply(this, arguments);
  if (this.config.username && this.config.url && this.config.password) {
    this.db = new neo4j.GraphDatabase(this.config.url,       this.config.username, this.config.password);

  }
}
util.inherits(Neo4JResource, Resource);

Neo4JResource.label = "Neo4J";
Neo4JResource.events = ["get", "match", "post"];

Neo4JResource.basicDashboard = {
  settings: [{
      name: 'url'
    , type: 'string'
  }, {
      name: 'username'
    , type: 'string'
  }, {
      name: 'password'
    , type: 'string'
  }
  ]
};

module.exports = Neo4JResource;

Neo4JResource.prototype.clientGeneration = true;

Neo4JResource.prototype.handle = function (ctx, next) {
  var parts = ctx.url.split('/').filter(function(p) { return p; });

  var result = {};

  var domain = {
      url: ctx.url
    , parts: parts
    , query: ctx.query
    , body: ctx.body
    , 'this': result
    , setResult: function(val) {
      result = val;
    }
  };
  console.log(this.events);
  if (ctx.method === "POST") {
      var node =this.db.createNode(ctx.body);
      node.save(function (err, node) {
        if (err) ctx.done(err, {statusCode: 400});
        ctx.done(err, {statusCode: 200, node: node.data});
      });
  } else if (ctx.method === "GET") {

    this.db.readNode(parts[0], function (err, node) {
      console.log("T");
       if (err) ctx.done({statusCode: 400}, {statusCode: 200, node:node});
      ctx.done(err, {statusCode: 200, node:node.data});
    });
  } else {
    next();
  }

};
<commit_msg>Added entity split<commit_after>/***
 * dpd-neo4j
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2013 Alexander Forselius
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 **/

var Resource = require('deployd/lib/resource')
  , httpUtil = require('deployd/lib/util/http')
  , Script = require('deployd/lib/script')
  , neo4j = require('neo4j')
  , util = require('util')
  , path = require('path');
function Neo4JResource() {
  Resource.apply(this, arguments);
  if (this.config.username && this.config.url && this.config.password) {
    this.db = new neo4j.GraphDatabase(this.config.url,       this.config.username, this.config.password);

  }
}
util.inherits(Neo4JResource, Resource);

Neo4JResource.label = "Neo4J";
Neo4JResource.events = ["get", "match", "post"];

Neo4JResource.basicDashboard = {
  settings: [{
      name: 'url'
    , type: 'string'
  }, {
      name: 'username'
    , type: 'string'
  }, {
      name: 'password'
    , type: 'string'
  }
  ]
};

module.exports = Neo4JResource;

Neo4JResource.prototype.clientGeneration = true;

Neo4JResource.prototype.handle = function (ctx, next) {
  var parts = ctx.url.split('/').filter(function(p) { return p; });

  var result = {};

  var domain = {
      url: ctx.url
    , parts: parts
    , query: ctx.query
    , body: ctx.body
    , 'this': result
    , setResult: function(val) {
      result = val;
    }
  };
  console.log(this.events);
  if (ctx.method === "POST") {
      var type = ctx.body.type;
      if (!type)
        throw "No type specified";

      switch(type) {
         case "node":
          var node = this.db.createNode(ctx.body.data);
          node.save(function (err, node) {
            if (err) ctx.done(err, {statusCode: 400});
            ctx.done(err, {statusCode: 200, node: node.data});
          });
          break;
       }
  } else if (ctx.method === "GET") {
    var type = ctx.body.type;
     if (!type)
        throw "No type specified";

    switch (type) {
    case "node":
      this.db.readNode(parts[0], function (err, node) {
        console.log("T");
         if (err) ctx.done({statusCode: 400}, {statusCode: 200, node:node});
        ctx.done(err, {statusCode: 200, node:node.data});
      });
      break;
    }
  } else {
    next();
  }

};
<|endoftext|>


<commit_before>var stream = require('stream')
var events = require('events')
var exit = require('./exit')

var Destructible = require('destructible')

var coalesce = require('extant')

var Program = require('./arguable')

var slice = [].slice

var rescue = require('rescue')

var Signal = require('signal')

var Child = require('./child')

module.exports = function () {
    // Variadic arguments.
    var vargs = slice.call(arguments)

    // First argument is always the module.
    var module = vargs.shift()

    // Usage source can be specified explicitly, or else it is sought in the
    // comments of the main module.
    var usage = typeof vargs[0] == 'string'
              ? vargs.shift()
              : module.filename

    // Optional options that both configure Arguable and provide our dear user
    // with a means to specify production objects for production and mock
    // objects for testing.
    var definition = typeof vargs[0] == 'object' ? vargs.shift() : {}

    // The main method.
    var main = vargs.shift()

    // TODO How about an optinal method here for command line completion logic?
    module.exports = function (argv, invocation, callback) {
        var vargs = []
        vargs.push.apply(vargs, arguments)

        var argv = vargs.shift()

        var options = {}
        for (var option in definition) {
            options[option] = definition[option]
        }
        for (var option in invocation) {
            options[option] = invocation[option]
        }

        var parameters = []
        if (!Array.isArray(argv)) {
            argv = [ argv ]
        }

        argv = argv.slice()
        while (argv.length != 0) {
            var argument = argv.shift()
            switch (typeof argument) {
            case 'object':
                // TODO Probably want `Program.flatten({ name: 'a', value: 1 // }, ...)`.
                // TODO Flattening would require knowing from the parameters
                // whether or not they accepted arguments in the case of
                // switch arguments.
                if (Array.isArray(argument)) {
                    argv.unshift.apply(argv, argument)
                } else {
                    var unshift = []
                    for (var name in argument) {
                        unshift.push('--' + name, argument[name].toString())
                    }
                    argv.unshift(unshift)
                }
                break
            default:
                parameters.push(argument)
                break
            }
        }

        var lang = coalesce(options.$lang, process.env.LANG && process.env.LANG.split('.')[0])
        // What we're shooting for here is this:
        //
        //   Create a signature that would be a reasonable signature for a
        //   generic function that is not an Arguable argument parser.
        //
        //   Or put another way, tell the user to create an argument parser that
        //   accepts an arguments array and a pseudo-process, the program, and a
        //   callback, so that you can tell them to either use Arguable, or else
        //   implement an argument parser that accepts reasonable arguments as
        //   opposed to accepting convoluted named parameters.
        //
        // If options is really an `EventEmitter`, then our argument parser is
        // being called as a universal submodule. This is an interface that
        // allows a library module author to document that a submodule accepts
        // an arguments array and a signal handler. The library module author
        // can document as many `Program` features as they would like, or they
        // could simply say that it is only for events, or they can say that it
        // is mean to be ignored by the submodule author.
        //
        // Now the submodule author can use Arguable for their argument parser
        // and program will be correctly configured, or they can create a
        // function that takes the argument array and use the argument parser
        // module of their choice. Additional properties are arguments to the
        // argument parser, not properties on this mystery event emitter.
        var program = new Program(usage, parameters, {
            module: module,
            stdin: coalesce(options.$stdin, process.stdin),
            stdout: coalesce(options.$stdout, process.stdout),
            stderr: coalesce(options.$stderr, process.stderr),
            isMainModule: isMainModule,
            options: options,
            lang: lang
        })

        var cb = vargs.pop()

        var isMainModule = ('$isMainModule' in options)
                         ? options.$isMainModule
                         : process.mainModule === module
        program.isMainModule = isMainModule
        program.stdout = coalesce(options.$stdout, process.stdout)
        program.stderr = coalesce(options.$stderr, process.stderr)
        program.stdin = coalesce(options.$stdin, process.stdin)
        var identifier = typeof options.$destructible == 'boolean'
                       ? module.filename : options.$destructible
        program.identifier = identifier
        var destructible = new Destructible(identifier)
        var trap = { SIGINT: 'destroy', SIGTERM: 'destroy', SIGHUP: 'swallow' }
        var $trap = ('$trap' in options) ? options.$trap : {}
        var $untrap = ('$untrap' in options)
                    ? options.$untrap
                    : isMainModule ? false
                                   : true
        var signals = coalesce(options.$signals, process)
        if (typeof $trap == 'boolean') {
            if (!$trap) {
                trap = {}
            }
        } else {
            for (var signal in $trap) {
                trap[signal] = $trap[signal]
            }
        }
        var traps = [], listener
        for (var signal in trap) {
            switch (trap[signal]) {
            case 'destroy':
                traps.push({
                    signal: signal,
                    listener: listener = destructible.destroy.bind(destructible)
                })
                signals.on(signal, listener)
                break
            case 'swallow':
                traps.push({
                    signal: signal,
                    listener: listener = function () {}
                })
                signals.on(signal, listener)
                break
            case 'default':
                break
            }
        }
        var exit = new Signal
        var child = new Child(destructible, exit, options)
        destructible.completed.wait(function () {
            var vargs = []
            vargs.push.apply(vargs, arguments)
            if ($untrap) {
                traps.forEach(function (trap) {
                    signals.removeListener(trap.signal, trap.listener)
                })
            }
            if (vargs[0]) {
                try {
                    rescue([{
                        name: 'message',
                        when: [ '..', /^bigeasy\.arguable#abend$/m, 'only' ]
                    }])(function (rescued) {
                        exit.unlatch({
                            exitCode: rescued.errors[0].exitCode
                        })
                    })(vargs[0])
                } catch (error) {
                    exit.unlatch(vargs[0])
                }
            } else {
                exit.unlatch.apply(exit, [ null ].concat(0, vargs.slice(1)))
            }
        })
        var cadence = require('cadence')
        var initialize = destructible.ephemeral('initialize')
        destructible.durable('main', cadence(function (async, destructible) {
            async([function () {
                main(destructible, program, async())
            }, function (error) {
                initialize(error)
                throw error
            }], [], function (vargs) {
                initialize()
                return vargs.concat(child)
            })
        }), function () {
            if (arguments[0] == null) {
                cb.apply(null, arguments)
            } else {
                destructible.destroy()
                exit.wait(cb)
            }
        })
    }

    if (module === process.mainModule) {
        module.exports(process.argv.slice(2), {}, exit(process))
    }
}
<commit_msg>Rename `Program` to `Arguable` in `index.js`.<commit_after>var stream = require('stream')
var events = require('events')
var exit = require('./exit')

var Destructible = require('destructible')

var coalesce = require('extant')

var Arguable = require('./arguable')

var slice = [].slice

var rescue = require('rescue')

var Signal = require('signal')

var Child = require('./child')

module.exports = function () {
    // Variadic arguments.
    var vargs = slice.call(arguments)

    // First argument is always the module.
    var module = vargs.shift()

    // Usage source can be specified explicitly, or else it is sought in the
    // comments of the main module.
    var usage = typeof vargs[0] == 'string'
              ? vargs.shift()
              : module.filename

    // Optional options that both configure Arguable and provide our dear user
    // with a means to specify production objects for production and mock
    // objects for testing.
    var definition = typeof vargs[0] == 'object' ? vargs.shift() : {}

    // The main method.
    var main = vargs.shift()

    // TODO How about an optinal method here for command line completion logic?
    module.exports = function (argv, invocation, callback) {
        var vargs = []
        vargs.push.apply(vargs, arguments)

        var argv = vargs.shift()

        var options = {}
        for (var option in definition) {
            options[option] = definition[option]
        }
        for (var option in invocation) {
            options[option] = invocation[option]
        }

        var parameters = []
        if (!Array.isArray(argv)) {
            argv = [ argv ]
        }

        argv = argv.slice()
        while (argv.length != 0) {
            var argument = argv.shift()
            switch (typeof argument) {
            case 'object':
                // TODO Probably want `Arguable.flatten({ name: 'a', value: 1 // }, ...)`.
                // TODO Flattening would require knowing from the parameters
                // whether or not they accepted arguments in the case of
                // switch arguments.
                if (Array.isArray(argument)) {
                    argv.unshift.apply(argv, argument)
                } else {
                    var unshift = []
                    for (var name in argument) {
                        unshift.push('--' + name, argument[name].toString())
                    }
                    argv.unshift(unshift)
                }
                break
            default:
                parameters.push(argument)
                break
            }
        }

        var isMainModule = ('$isMainModule' in options)
                         ? options.$isMainModule
                         : process.mainModule === module
        var lang = coalesce(options.$lang, process.env.LANG && process.env.LANG.split('.')[0])
        var arguable = new Arguable(usage, parameters, {
            isMainModule: isMainModule,
            stdin: coalesce(options.$stdin, process.stdin),
            stdout: coalesce(options.$stdout, process.stdout),
            stderr: coalesce(options.$stderr, process.stderr),
            options: options,
            lang: lang
        })

        var cb = vargs.pop()

        var identifier = typeof options.$destructible == 'boolean'
                       ? module.filename : options.$destructible
        arguable.identifier = identifier
        var destructible = new Destructible(identifier)
        var trap = { SIGINT: 'destroy', SIGTERM: 'destroy', SIGHUP: 'swallow' }
        var $trap = ('$trap' in options) ? options.$trap : {}
        var $untrap = ('$untrap' in options)
                    ? options.$untrap
                    : isMainModule ? false
                                   : true
        var signals = coalesce(options.$signals, process)
        if (typeof $trap == 'boolean') {
            if (!$trap) {
                trap = {}
            }
        } else {
            for (var signal in $trap) {
                trap[signal] = $trap[signal]
            }
        }
        var traps = [], listener
        for (var signal in trap) {
            switch (trap[signal]) {
            case 'destroy':
                traps.push({
                    signal: signal,
                    listener: listener = destructible.destroy.bind(destructible)
                })
                signals.on(signal, listener)
                break
            case 'swallow':
                traps.push({
                    signal: signal,
                    listener: listener = function () {}
                })
                signals.on(signal, listener)
                break
            case 'default':
                break
            }
        }
        var exit = new Signal
        var child = new Child(destructible, exit, options)
        destructible.completed.wait(function () {
            var vargs = []
            vargs.push.apply(vargs, arguments)
            if ($untrap) {
                traps.forEach(function (trap) {
                    signals.removeListener(trap.signal, trap.listener)
                })
            }
            if (vargs[0]) {
                try {
                    rescue([{
                        name: 'message',
                        when: [ '..', /^bigeasy\.arguable#abend$/m, 'only' ]
                    }])(function (rescued) {
                        exit.unlatch({
                            exitCode: rescued.errors[0].exitCode
                        })
                    })(vargs[0])
                } catch (error) {
                    exit.unlatch(vargs[0])
                }
            } else {
                exit.unlatch.apply(exit, [ null ].concat(0, vargs.slice(1)))
            }
        })
        var cadence = require('cadence')
        var initialize = destructible.ephemeral('initialize')
        destructible.durable('main', cadence(function (async, destructible) {
            async([function () {
                main(destructible, arguable, async())
            }, function (error) {
                initialize(error)
                throw error
            }], [], function (vargs) {
                initialize()
                return vargs.concat(child)
            })
        }), function () {
            if (arguments[0] == null) {
                cb.apply(null, arguments)
            } else {
                destructible.destroy()
                exit.wait(cb)
            }
        })
    }

    if (module === process.mainModule) {
        module.exports(process.argv.slice(2), {}, exit(process))
    }
}
<|endoftext|>


<commit_before>// # Module proto*
//
// Proxy-based Self-and-Slate-inspired slow-as-fuck multiple-delegation
// for ECMAScript6-aka-JavaScript
//
//
// Copyright (c) 2013 Quildreen "Sorella" Motta <quildreen@gmail.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

require('harmony-reflect')
var clone   = Object.create
var proto   = Object.getPrototypeOf
var keys    = Object.keys
var define  = Object.defineProperty
var slice   = Function.call.bind([].slice)
var Nothing = {}

function unique(xs) {
  return xs.reduce(function(as, b) {
                     return as.indexOf(b) != -1?  as
                     :                            as.concat(b) }, [])}

function flatten(xs) {
  return xs.reduce(function(as, bs){ return as.concat(bs) }, []) }

function extend(target) {
  slice(arguments, 1).forEach(function(x){
                                keys(x).forEach(function(k){
                                                  target[k] = x[k] })})
  return target }

function all(o) {
  return [o].concat(o.proto$) }

function firstMatch(o, f) {
  return all(o).reduce(function(r, a) {
                         return r !== Nothing?  r
                         :                      f(a) }, Nothing)}

function lookup(o, s) {
  return firstMatch(o, function(a) {
                         return s in a?  a[s]
                         :               Nothing })}

function propertyNames(o) {
  return unique(all(o).map(keys).reduce(flatten).sort()) }

function makeObject(anObject) {
  return Proxy(anObject, {
    getOwnPropertyDescriptor: function(o, n) {
      return Object.getOwnPropertyDescriptor(o, n) }

  , getOwnPropertyNames: function(o) {
      return Object.getOwnPropertyNames(o) }

  , getPrototypeOf: function(o) {
      return o.proto$ }

  , defineProperty: function(o, n, d) {
      return define(o, n, d) }

  , deleteProperty: function(o, n, d) {
      return delete o[n] }

  , has: function(o, name) {
      return lookup(o, name) !== Nothing }

  , hasOwn: function(o, name) {
      return o.hasOwnProperty(name) }

  , get: function(o, name) {
      var result = lookup(o, name)
      return result === Nothing? undefined : result }

  , set: function(o, name, val) {
      return o[name] = val }

  , keys: function(o) {
      return propertyNames(o) }

  , enumerate: function(o) {
      return propertyNames(o) }
  }) }

Base = {
  proto$: []

, addDelegation: function(to) {
    unique(this.proto$ = [to].concat(this.proto$)) }

, removeDelegation: function(to) {
    this.proto$ = this.proto$.filter(function(a){ return a !== to })}

, clone: function(f) {
    var result = makeObject({ proto$: [this] })
    if (f)  f.call(result)
    return result }

, cloneWith: function(o) {
    return extend(this.clone(), o) }
}

module.exports = makeObject(Base)<commit_msg>Makes `unique` consistent by enforcing `b` to be a singleton array.<commit_after>// # Module proto*
//
// Proxy-based Self-and-Slate-inspired slow-as-fuck multiple-delegation
// for ECMAScript6-aka-JavaScript
//
//
// Copyright (c) 2013 Quildreen "Sorella" Motta <quildreen@gmail.com>
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation files
// (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

require('harmony-reflect')
var clone   = Object.create
var proto   = Object.getPrototypeOf
var keys    = Object.keys
var define  = Object.defineProperty
var slice   = Function.call.bind([].slice)
var Nothing = {}

function unique(xs) {
  return xs.reduce(function(as, b) {
                     return as.indexOf(b) != -1?  as
                     :                            as.concat([b]) }, [])}

function flatten(xs) {
  return xs.reduce(function(as, bs){ return as.concat(bs) }, []) }

function extend(target) {
  slice(arguments, 1).forEach(function(x){
                                keys(x).forEach(function(k){
                                                  target[k] = x[k] })})
  return target }

function all(o) {
  return [o].concat(o.proto$) }

function firstMatch(o, f) {
  return all(o).reduce(function(r, a) {
                         return r !== Nothing?  r
                         :                      f(a) }, Nothing)}

function lookup(o, s) {
  return firstMatch(o, function(a) {
                         return s in a?  a[s]
                         :               Nothing })}

function propertyNames(o) {
  return unique(all(o).map(keys).reduce(flatten).sort()) }

function makeObject(anObject) {
  return Proxy(anObject, {
    getOwnPropertyDescriptor: function(o, n) {
      return Object.getOwnPropertyDescriptor(o, n) }

  , getOwnPropertyNames: function(o) {
      return Object.getOwnPropertyNames(o) }

  , getPrototypeOf: function(o) {
      return o.proto$ }

  , defineProperty: function(o, n, d) {
      return define(o, n, d) }

  , deleteProperty: function(o, n, d) {
      return delete o[n] }

  , has: function(o, name) {
      return lookup(o, name) !== Nothing }

  , hasOwn: function(o, name) {
      return o.hasOwnProperty(name) }

  , get: function(o, name) {
      var result = lookup(o, name)
      return result === Nothing? undefined : result }

  , set: function(o, name, val) {
      return o[name] = val }

  , keys: function(o) {
      return propertyNames(o) }

  , enumerate: function(o) {
      return propertyNames(o) }
  }) }

Base = {
  proto$: []

, addDelegation: function(to) {
    unique(this.proto$ = [to].concat(this.proto$)) }

, removeDelegation: function(to) {
    this.proto$ = this.proto$.filter(function(a){ return a !== to })}

, clone: function(f) {
    var result = makeObject({ proto$: [this] })
    if (f)  f.call(result)
    return result }

, cloneWith: function(o) {
    return extend(this.clone(), o) }
}

module.exports = makeObject(Base)
<|endoftext|>


<commit_before>/**
 * Module exports
 */
module.exports = BlockEvent;

var EventEmitter = require('events').EventEmitter;

function BlockEvent(thresh) {
    var self = this;
    var start = process.hrtime();
    var loopInterval = 100;
    var threshold = thresh || 10;

    EventEmitter.call(this);

    this.stop = function stop() {
        clearInterval(this.timer);
        this.emit('watchStopped');
    };
    this.resume = function resume() {
        this.timer = setInterval(watchEvent, loopInterval);
        this.timer.unref();
        this.emit('watchStarted');
    };

    function watchEvent() {
        var diff = process.hrtime(start);
        var nanosec = diff[0] * 1e9 + diff[1];
        var ms = nanosec / 1e6;
        var n = ms - loopInterval;
        start = process.hrtime();
        if (n > threshold) {
            self.emit('blocked', n);
        }
    }

    this.resume();
}
BlockEvent.prototype = EventEmitter.prototype;
<commit_msg>fix in parameters<commit_after>/**
 * Module exports
 */
module.exports = BlockEvent;

var EventEmitter = require('events').EventEmitter;

/**
 * BlockEvent constructor
 * @param {Number}
 */
function BlockEvent(_threshold) {
    var self = this;
    var start = process.hrtime();
    var loopInterval = 100;  //ms
    var threshold = _threshold || 10; //ms

    EventEmitter.call(this);

    this.stop = function stop() {
        clearInterval(this.timer);
        this.emit('watchStopped');
    };

    this.resume = function resume() {
        this.timer = setInterval(watchEvent, loopInterval);
        this.timer.unref();
        this.emit('watchStarted');
    };

    function watchEvent() {
        var diff = process.hrtime(start);
        var nanosec = diff[0] * 1e9 + diff[1];
        var ms = nanosec / 1e6;
        var n = ms - loopInterval;
        start = process.hrtime();
        if (n > threshold) {
            self.emit('blocked', n);
        }
    }

    this.resume();
}
BlockEvent.prototype = EventEmitter.prototype;
<|endoftext|>


<commit_before>module.exports = exports = sseMiddlewareFactory;

const HANDSHAKE_QUERY = 'handshake-interval';
const RETRY_QUERY = 'retry';
const LAST_EVENT_ID_QUERY = 'lastEventId';
const LAST_EVENT_ID_HEADER = 'last-event-id';
const defaultConfig = {
  handShakeInterval: 3000,
  // https://www.w3.org/TR/eventsource/#concept-event-stream-reconnection-time
  retry: 3000
};

/**
 * Middleware that adds support of Server Sent Events
 * @param {{handShakeInterval: number, retry: number}} options
 * @void
 */
function sseMiddlewareFactory(options = defaultConfig) {
  return (req, res, next) => {
    const config = {
      handShakeInterval: req.query[HANDSHAKE_QUERY] || options.handShakeInterval || defaultConfig.handShakeInterval,
      retry: req.query[RETRY_QUERY] || options.retry || defaultConfig.retry
    };

    establishConnection(res, config);

    res.sse = sse(res, config);

    Object.defineProperty(res.sse, 'lastEventId', {
      writable: false,
      value: req.get(LAST_EVENT_ID_HEADER) || req.query[LAST_EVENT_ID_QUERY] || res.sse.lastEventId
    });

    next();
  }
}

/**
 * Sends proper headers to keep connection alive. Also starts a time which periodically sends handshake event
 * @param res
 * @param config
 */
function establishConnection(res, config) {
  keepAlive(res);
  setHandshakeInterval(res, config.handShakeInterval);
}

/**
 * Returns function which sends "server sent event" to client
 * @param res
 * @param {{handShakeInterval: number, retry: number}} config
 * @returns {function({data: string, [event]: string, [id]: string}|Array<{data: string, [event]: string, [id]: string}>)}
 */
function sse(res, config) {
  return (message) => {
    if (Array.isArray(message)) {
      message = message.map(msg => configureStreamObject(msg, config));
    } else {
      message = configureStreamObject(message, config);
    }

    const eventStream = buildEventStream(message);
    // Retrieve message
    const singleMessage = Array.isArray(message) ? message[message.length - 1] : message;

    if (singleMessage.id) {
      res.sse.lastEventId = singleMessage.id;
    }

    res.write(eventStream);
  };
}

/**
 * Add/modify message from config
 * @param message
 * @param retry
 * @returns {*}
 */
function configureStreamObject(message, {retry}) {
  message.retry = retry;

  return message;
}

/**
 * Builds event stream. Accept either field set or array of field sets
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format
 * @param {{data: *, event?: string, id?: string|number, retry?: number}|Array} fields
 * @returns {string}
 */
function buildEventStream(fields) {
  if (Array.isArray(fields)) {
    return fields.map(fieldSet => buildEventStream(fieldSet)).join('');
  }

  const {event, id, retry} = fields;
  let data = fields.data;
  let message = `retry: ${retry}\n`;

  if (id) {
    message += `id: ${id}\n`;
  }

  if (event) {
    message += `event: ${event}\n`;
  }

  if (typeof data === 'object') {
    data = JSON.stringify(data);
  }

  message += `data: ${data}\n\n`;

  return message;
}

/**
 * Sends headers to keep connection alive
 * @param res
 */
function keepAlive(res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });
}

/**
 * Periodically sends messages to client to keep connection alive
 * @param res
 * @param updateInterval
 */
function setHandshakeInterval(res, updateInterval) {
  const handshakeInterval = setInterval(() => res.write(': sse-handshake'), updateInterval);

  res.on('finish', () => clearInterval(handshakeInterval));
  res.on('close', () => clearInterval(handshakeInterval));
}<commit_msg>Terminate handshakes<commit_after>module.exports = exports = sseMiddlewareFactory;

const HANDSHAKE_QUERY = 'handshake-interval';
const RETRY_QUERY = 'retry';
const LAST_EVENT_ID_QUERY = 'lastEventId';
const LAST_EVENT_ID_HEADER = 'last-event-id';
const defaultConfig = {
  handShakeInterval: 3000,
  // https://www.w3.org/TR/eventsource/#concept-event-stream-reconnection-time
  retry: 3000
};

/**
 * Middleware that adds support of Server Sent Events
 * @param {{handShakeInterval: number, retry: number}} options
 * @void
 */
function sseMiddlewareFactory(options = defaultConfig) {
  return (req, res, next) => {
    const config = {
      handShakeInterval: req.query[HANDSHAKE_QUERY] || options.handShakeInterval || defaultConfig.handShakeInterval,
      retry: req.query[RETRY_QUERY] || options.retry || defaultConfig.retry
    };

    establishConnection(res, config);

    res.sse = sse(res, config);

    Object.defineProperty(res.sse, 'lastEventId', {
      writable: false,
      value: req.get(LAST_EVENT_ID_HEADER) || req.query[LAST_EVENT_ID_QUERY] || res.sse.lastEventId
    });

    next();
  }
}

/**
 * Sends proper headers to keep connection alive. Also starts a time which periodically sends handshake event
 * @param res
 * @param config
 */
function establishConnection(res, config) {
  keepAlive(res);
  setHandshakeInterval(res, config.handShakeInterval);
}

/**
 * Returns function which sends "server sent event" to client
 * @param res
 * @param {{handShakeInterval: number, retry: number}} config
 * @returns {function({data: string, [event]: string, [id]: string}|Array<{data: string, [event]: string, [id]: string}>)}
 */
function sse(res, config) {
  return (message) => {
    if (Array.isArray(message)) {
      message = message.map(msg => configureStreamObject(msg, config));
    } else {
      message = configureStreamObject(message, config);
    }

    const eventStream = buildEventStream(message);
    // Retrieve message
    const singleMessage = Array.isArray(message) ? message[message.length - 1] : message;

    if (singleMessage.id) {
      res.sse.lastEventId = singleMessage.id;
    }

    res.write(eventStream);
  };
}

/**
 * Add/modify message from config
 * @param message
 * @param retry
 * @returns {*}
 */
function configureStreamObject(message, {retry}) {
  message.retry = retry;

  return message;
}

/**
 * Builds event stream. Accept either field set or array of field sets
 * @see https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format
 * @param {{data: *, event?: string, id?: string|number, retry?: number}|Array} fields
 * @returns {string}
 */
function buildEventStream(fields) {
  if (Array.isArray(fields)) {
    return fields.map(fieldSet => buildEventStream(fieldSet)).join('');
  }

  const {event, id, retry} = fields;
  let data = fields.data;
  let message = `retry: ${retry}\n`;

  if (id) {
    message += `id: ${id}\n`;
  }

  if (event) {
    message += `event: ${event}\n`;
  }

  if (typeof data === 'object') {
    data = JSON.stringify(data);
  }

  message += `data: ${data}\n\n`;

  return message;
}

/**
 * Sends headers to keep connection alive
 * @param res
 */
function keepAlive(res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Connection': 'keep-alive'
  });
}

/**
 * Periodically sends messages to client to keep connection alive
 * @param res
 * @param updateInterval
 */
function setHandshakeInterval(res, updateInterval) {
  const handshakeInterval = setInterval(() => res.write(': sse-handshake\n'), updateInterval);

  res.on('finish', () => clearInterval(handshakeInterval));
  res.on('close', () => clearInterval(handshakeInterval));
}
<|endoftext|>


<commit_before>var http = require('http');

http.createServer(function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  res.end('hello world');
})
.listen(3000, '127.0.0.1');

console.log("server running ...");
<commit_msg>host server with express<commit_after>var express = require('express');

var app = express();

app.get('/', function(req, res) {
  res.send('hello world');
});

var server = app.listen(3000, function() {
  console.log("server running ...");
});
<|endoftext|>


<commit_before>var ok = require('assert').ok,
    __slice = [].slice

function detach (cartridge) {
    var magazine = cartridge._magazine, cache = magazine._cache
    magazine.heft -= cartridge.heft
    cache.heft -= cartridge.heft
    delete cache._cache[cartridge._compoundKey]
    magazine.count--
    cache.count--
    unlink(cartridge)
}

function unlink (cartridge, prefix) {
    if (!prefix) {
        unlink(cartridge, 'cache')
        unlink(cartridge, 'magazine')
    } else {
        var prev = '_' + prefix + 'Previous'
        var next = '_' + prefix + 'Next'
        cartridge[prev][next] = cartridge[next]
        cartridge[next][prev] = cartridge[prev]
    }
}

function link (cartridge, previous, prefix) {
    var prev = '_' + prefix + 'Previous'
    var next = '_' + prefix + 'Next'
    cartridge[next] = previous[next]
    cartridge[prev] = previous
    cartridge[next][prev] = cartridge
    previous[next] = cartridge
}

function Cache (constructor) {
    var head = {}
    head._cachePrevious = head._cacheNext = head

    this._constructor = constructor // todo bad
    this._cache = {}
    this._head = head
    this._nextKey = 0

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Cache.prototype.createMagazine = function () {
    var key = ':' + (++this._nextKey) + ':'
    return new Magazine(this, key)
}

Cache.prototype.purge = function () {
    purge.call(this, '_cachePrevious', __slice.call(arguments))
}

function Magazine (cache, key) {
    var head = {}
    head._magazinePrevious = head._magazineNext = head

    this._cache = cache
    this._key = key
    this._head = head

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Magazine.prototype.hold = function (key, defaultValue) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge) {
        if (typeof defaultValue == 'function') {
            defaultValue = defaultValue()
        }
        cartridge = this._cache._cache[compoundKey] = new Cartridge(this, defaultValue, compoundKey)
        this.count++
        this._cache.count++
    } else {
        unlink(cartridge)
    }
    link(cartridge, this._cache._head, 'cache')
    link(cartridge, this._head, 'magazine')
    cartridge.holds++
    this.holds++
    this._cache.holds++
    cartridge.when = Date.now()
    return cartridge
}

Magazine.prototype.get = function (key) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge || !cartridge.holds) {
        throw new Error('attempt to get a cartridge not held')
    }
    return cartridge
}

function purge (next, vargs) {
    var downTo, condition, gather, stop, head, iterator, cache, magazine
    downTo = vargs.shift()
    if (typeof vargs[0] == 'function') {
        condition = vargs.shift()
    }
    if (Array.isArray(vargs[0])) {
        gather = vargs.shift()
    }
    condition || (condition = function () { return true })
    stop = downTo
    head = this._head
    iterator = head
    if (typeof downTo == 'number') {
        downTo = Math.max(downTo, -1)
        stop = function () { return this.heft <= downTo }.bind(this)
    }
    while (iterator[next] !== head && !stop(iterator[next])) {
        var cartridge = iterator[next]
        if (!cartridge.holds && condition(cartridge)) {
            magazine = cartridge._magazine, cache = magazine._cache
            if (gather) {
                gather.push(cartridge.value)
            }
            detach(cartridge)
        } else {
            iterator = cartridge
        }
    }
}

Magazine.prototype.purge = function () {
    purge.call(this, '_magazinePrevious', __slice.call(arguments))
}

function Cartridge (magazine, defaultValue, compoundKey) {
    this.value = defaultValue
    this._magazine = magazine
    this._compoundKey = compoundKey
    this.heft = 0
    this.holds = 0
}

Cartridge.prototype.adjustHeft = function (heft) {
    this.heft += heft
    this._magazine.heft += heft
    this._magazine._cache.heft += heft
}

Cartridge.prototype.release = function () {
    if (!this.holds) {
        throw new Error('attempt to release a cartridge not held')
    }
    if (--this.holds == 0) {
        this._magazine.holds--
        this._magazine._cache.holds--
    }
}

Cartridge.prototype.remove = function () {
    if (this.holds != 1) {
        throw new Error('attempt to remove cartridge held by others')
    }
    detach(this)
}

module.exports = Cache
<commit_msg>Make `adjustHeft` chain.<commit_after>var ok = require('assert').ok,
    __slice = [].slice

function detach (cartridge) {
    var magazine = cartridge._magazine, cache = magazine._cache
    magazine.heft -= cartridge.heft
    cache.heft -= cartridge.heft
    delete cache._cache[cartridge._compoundKey]
    magazine.count--
    cache.count--
    unlink(cartridge)
}

function unlink (cartridge, prefix) {
    if (!prefix) {
        unlink(cartridge, 'cache')
        unlink(cartridge, 'magazine')
    } else {
        var prev = '_' + prefix + 'Previous'
        var next = '_' + prefix + 'Next'
        cartridge[prev][next] = cartridge[next]
        cartridge[next][prev] = cartridge[prev]
    }
}

function link (cartridge, previous, prefix) {
    var prev = '_' + prefix + 'Previous'
    var next = '_' + prefix + 'Next'
    cartridge[next] = previous[next]
    cartridge[prev] = previous
    cartridge[next][prev] = cartridge
    previous[next] = cartridge
}

function Cache (constructor) {
    var head = {}
    head._cachePrevious = head._cacheNext = head

    this._constructor = constructor // todo bad
    this._cache = {}
    this._head = head
    this._nextKey = 0

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Cache.prototype.createMagazine = function () {
    var key = ':' + (++this._nextKey) + ':'
    return new Magazine(this, key)
}

Cache.prototype.purge = function () {
    purge.call(this, '_cachePrevious', __slice.call(arguments))
}

function Magazine (cache, key) {
    var head = {}
    head._magazinePrevious = head._magazineNext = head

    this._cache = cache
    this._key = key
    this._head = head

    this.count = 0
    this.holds = 0
    this.heft = 0
}

Magazine.prototype.hold = function (key, defaultValue) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge) {
        if (typeof defaultValue == 'function') {
            defaultValue = defaultValue()
        }
        cartridge = this._cache._cache[compoundKey] = new Cartridge(this, defaultValue, compoundKey)
        this.count++
        this._cache.count++
    } else {
        unlink(cartridge)
    }
    link(cartridge, this._cache._head, 'cache')
    link(cartridge, this._head, 'magazine')
    cartridge.holds++
    this.holds++
    this._cache.holds++
    cartridge.when = Date.now()
    return cartridge
}

Magazine.prototype.get = function (key) {
    var compoundKey = this._key + key
    var cartridge = this._cache._cache[compoundKey]
    if (!cartridge || !cartridge.holds) {
        throw new Error('attempt to get a cartridge not held')
    }
    return cartridge
}

function purge (next, vargs) {
    var downTo, condition, gather, stop, head, iterator, cache, magazine
    downTo = vargs.shift()
    if (typeof vargs[0] == 'function') {
        condition = vargs.shift()
    }
    if (Array.isArray(vargs[0])) {
        gather = vargs.shift()
    }
    condition || (condition = function () { return true })
    stop = downTo
    head = this._head
    iterator = head
    if (typeof downTo == 'number') {
        downTo = Math.max(downTo, -1)
        stop = function () { return this.heft <= downTo }.bind(this)
    }
    while (iterator[next] !== head && !stop(iterator[next])) {
        var cartridge = iterator[next]
        if (!cartridge.holds && condition(cartridge)) {
            magazine = cartridge._magazine, cache = magazine._cache
            if (gather) {
                gather.push(cartridge.value)
            }
            detach(cartridge)
        } else {
            iterator = cartridge
        }
    }
}

Magazine.prototype.purge = function () {
    purge.call(this, '_magazinePrevious', __slice.call(arguments))
}

function Cartridge (magazine, defaultValue, compoundKey) {
    this.value = defaultValue
    this._magazine = magazine
    this._compoundKey = compoundKey
    this.heft = 0
    this.holds = 0
}

Cartridge.prototype.adjustHeft = function (heft) {
    this.heft += heft
    this._magazine.heft += heft
    this._magazine._cache.heft += heft
    return this
}

Cartridge.prototype.release = function () {
    if (!this.holds) {
        throw new Error('attempt to release a cartridge not held')
    }
    if (--this.holds == 0) {
        this._magazine.holds--
        this._magazine._cache.holds--
    }
}

Cartridge.prototype.remove = function () {
    if (this.holds != 1) {
        throw new Error('attempt to remove cartridge held by others')
    }
    detach(this)
}

module.exports = Cache
<|endoftext|>


<commit_before>var parentRequire = require('parent-require'),
    gulp = parentRequire('gulp'),
    extend = require('extend'),
    fs = require('fs'),
    path = require('path'),
    watch = require('gulp-debounced-watch'),
    inject = require('gulp-inject'),
    replace = require('gulp-replace'),
    livereload = require('gulp-livereload'),
    webserver = require('gulp-webserver'),
    open = require('open'),
    opened,
    vendorPath = path.join('node_modules', 'gulp-jasmine-livereload-task', 'vendor'),
    template = {
        '1.3': path.join(vendorPath, 'jasmine-1.3.1', 'SpecRunner.html'),
        '2.0': path.join(vendorPath, 'jasmine-2.0.2', 'SpecRunner.html'),
        '2.1': path.join(vendorPath, 'jasmine-2.1.3', 'SpecRunner.html'),
        '2.2': path.join(vendorPath, 'jasmine-2.2.0', 'SpecRunner.html'),
        'peer': path.join('node_modules', 'jasmine', 'SpecRunner.html')
    },
    jshint = {
        '2.6': path.join(vendorPath, 'jshint-2.6.0', 'jshint.js'),
        'peer': path.join('node_modules', 'jshint', 'dist', 'jshint.js')
    },
    defaults = {
        files: undefined,
        jasmine: '2.2',
        livereload: '35729',
        jshint: {
            version: '2.6',
            files: [],
            options: {}
        },
        watch: {
            options: {}
        }
    },
    options;

module.exports = function(opts) {

    if (fs.existsSync(template.peer)) {
        defaults.jasmine = 'peer';
        console.log('Installed Jasmine found');
    } else {
        console.log('No installed Jasmine found. Using embedded one');
    }

    if (opts && opts.jshint && opts.jshint.files && opts.jshint.files.length) {
        if (fs.existsSync(jshint.peer)) {
            defaults.jshint.version = 'peer';
            console.log('Installed Jshint found');
        } else {
            console.log('No installed jshint found. Using embedded one');
        }
    }

    options = extend(true, {}, defaults, opts);

    return function() {
        createSpecrunner();
        livereload.listen({
            port: options.livereload
        });
        watch(options.files, options.watch.options, createSpecrunner);
    };
};

function createSpecrunner () {
    var target = gulp.dest('.'),
        specrunner;

    target.on('end', function () {
        if (!opened) {
            if (!options.host) {
                open('file:///' + path.join(path.resolve('.'), 'SpecRunner.html'));
            } else {
                gulp.src('.')
                    .pipe(webserver({
                      open: 'SpecRunner.html',
                      host: options.host,
                      port: options.port
                    }));
            }
            opened = true;
        }
    });

    if (!fs.existsSync(template[options.jasmine])) {
        throw new Error('Jasmine version ' + options.jasmine + ' is currently not supported!');
    }

    specrunner = gulp.src(template[options.jasmine])
        .pipe(inject(gulp.src(options.files, {read: false}), {
            addRootSlash: false
        }))
        .pipe(replace(/<!-- options:js -->/g, '<script>var gulpJasmineLivereloadTask = {}; gulpJasmineLivereloadTask.options = JSON.parse(\'' + JSON.stringify(options) + '\');</script>'))
        .pipe(replace(/<!-- livereload:js -->/g, '<script src="http://localhost:' + options.livereload + '/livereload.js"></script>'));

    if (options.jshint.files.length > 0) {
        specrunner = specrunner
            .pipe(replace(/<!-- sources:js -->/g, '<script>gulpJasmineLivereloadTask.sources = [];/*sources:js*//*endinject*/</script>'))
            .pipe(inject(gulp.src(options.jshint.files), {
            name: 'sources',
            addRootSlash: false,
            starttag: '/*sources:js*/',
            endtag: '/*endinject*/',
            transform: function (filePath, file) {
                var source = encodeURI(file.contents.toString('utf8'));
                return 'gulpJasmineLivereloadTask.sources.push({path: "' + filePath + '", timeStamp: "' + file.stat.mtime.getTime() + '", source: "' + source + '"});\n';
            }
        }))
            .pipe(replace(/<!-- jshint:js -->/g, '<script src="' + jshint[options.jshint.version] + '"></script>\n<script src="node_modules/gulp-jasmine-livereload-task/jshint-spec.js"></script>'));
    }

    specrunner
        .pipe(target)
        .pipe(livereload());
}
<commit_msg>static assets path option, specrunner path option, JS style fix<commit_after>var parentRequire = require('parent-require'),
    gulp = parentRequire('gulp'),
    extend = require('extend'),
    fs = require('fs'),
    path = require('path'),
    watch = require('gulp-debounced-watch'),
    inject = require('gulp-inject'),
    replace = require('gulp-replace'),
    livereload = require('gulp-livereload'),
    webserver = require('gulp-webserver'),
    open = require('open'),
    opened,
    vendorPath = path.join('node_modules', 'gulp-jasmine-livereload-task', 'vendor'),
    template = {
        '1.3': path.join(vendorPath, 'jasmine-1.3.1', 'SpecRunner.html'),
        '2.0': path.join(vendorPath, 'jasmine-2.0.2', 'SpecRunner.html'),
        '2.1': path.join(vendorPath, 'jasmine-2.1.3', 'SpecRunner.html'),
        '2.2': path.join(vendorPath, 'jasmine-2.2.0', 'SpecRunner.html'),
        'peer': path.join('node_modules', 'jasmine', 'SpecRunner.html')
    },
    jshint = {
        '2.6': path.join(vendorPath, 'jshint-2.6.0', 'jshint.js'),
        'peer': path.join('node_modules', 'jshint', 'dist', 'jshint.js')
    },
    defaults = {
        files: undefined,
        jasmine: '2.2',
        livereload: '35729',
        jshint: {
            version: '2.6',
            files: [],
            options: {}
        },
        watch: {
            options: {}
        }
    },
    options;

module.exports = function (opts) {
    if (fs.existsSync(template.peer)) {
        defaults.jasmine = 'peer';
        console.log('Installed Jasmine found');
    } else {
        console.log('No installed Jasmine found. Using embedded one');
    }

    if (opts && opts.jshint && opts.jshint.files && opts.jshint.files.length) {
        if (fs.existsSync(jshint.peer)) {
            defaults.jshint.version = 'peer';
            console.log('Installed Jshint found');
        } else {
            console.log('No installed jshint found. Using embedded one');
        }
    }

    options = extend(true, {}, defaults, opts);

    return function () {
        createSpecrunner();
        livereload.listen({
            port: options.livereload
        });
        watch(options.files, options.watch.options, createSpecrunner);
    };
};

function createSpecrunner() {
    var target = gulp.dest('.'),
        specrunner;

    target.on('end', function () {
        if (!opened) {
            if (!options.host) {
                open('file:///' + path.join(path.resolve('.'), 'SpecRunner.html'));
            } else {
                gulp.src(options.staticAssetsPath || '.')
                    .pipe(
                        webserver({
                            open: options.specRunnerPath || 'SpecRunner.html',
                            host: options.host,
                            port: options.port
                        })
                    );
            }
            opened = true;
        }
    });

    if (!fs.existsSync(template[options.jasmine])) {
        throw new Error('Jasmine version ' + options.jasmine + ' is currently not supported!');
    }

    specrunner = gulp.src(template[options.jasmine])
        .pipe(inject(gulp.src(options.files, {read: false}), {
            addRootSlash: false
        }))
        .pipe(replace(/<!-- options:js -->/g, '<script>var gulpJasmineLivereloadTask = {}; gulpJasmineLivereloadTask.options = JSON.parse(\'' + JSON.stringify(options) + '\');</script>'))
        .pipe(replace(/<!-- livereload:js -->/g, '<script src="http://localhost:' + options.livereload + '/livereload.js"></script>'));

    if (options.jshint.files.length > 0) {
        specrunner = specrunner
            .pipe(replace(/<!-- sources:js -->/g, '<script>gulpJasmineLivereloadTask.sources = [];/*sources:js*//*endinject*/</script>'))
            .pipe(inject(gulp.src(options.jshint.files), {
            name: 'sources',
            addRootSlash: false,
            starttag: '/*sources:js*/',
            endtag: '/*endinject*/',
            transform: function (filePath, file) {
                var source = encodeURI(file.contents.toString('utf8'));
                return 'gulpJasmineLivereloadTask.sources.push({path: "' + filePath + '", timeStamp: "' + file.stat.mtime.getTime() + '", source: "' + source + '"});\n';
            }
        }))
            .pipe(replace(/<!-- jshint:js -->/g, '<script src="' + jshint[options.jshint.version] + '"></script>\n<script src="node_modules/gulp-jasmine-livereload-task/jshint-spec.js"></script>'));
    }

    specrunner
        .pipe(target)
        .pipe(livereload());
}
<|endoftext|>


<commit_before>/**
 * Static Server
 */
var static = require('node-static');
var fileServer = new static.Server('./views');
require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    }).resume();
}).listen(5000);<commit_msg>server<commit_after>/**
 * Static server setup
 * @type {[type]}
 */
var static = require('node-static');
var fileServer = new static.Server('./views');
require('http').createServer(function (request, response) {
    request.addListener('end', function () {
        fileServer.serve(request, response);
    }).resume();
}).listen(5000);<|endoftext|>


<commit_before>'use strict';
var async = require('async');

var assert = function (condition, description) {
    if (!condition) {
        throw new Error(description);
    }
};

/**
 * Dependency container and injection class
 * @constructor
 */
var Plugme = function () {
    this._registry = {};
    this._errorHandlers = [];
    this.timeout = 10000;
};

/**
 * Set an error handler
 * @param  {Function} cb
 */
Plugme.prototype.onError = function (cb) {
    this._errorHandlers.push(cb);
};

/**
 * Set an error handler only once
 * @param  {Function} cb
 */
Plugme.prototype.onceError = function (cb) {
    cb.once = true;
    this._errorHandlers.push(cb);
};

/**
 * Unset an error handler
 * @param  {Function} cb
 */
Plugme.prototype.offError = function (cb) {
    var index = this._errorHandlers.indexOf(cb);
    if (index !== -1) {
        this._errorHandlers.splice(index, 1);
    }
};

/**
 * Set a new component
 * @param {String} name Name of the component
 * @param {String | String[] | Function} pDepsOrFactory Dependencies or factory function for the component
 * @param {Function} [pFactory] Factory function
 */
Plugme.prototype.set = function (pNameOrDict, pDepsOrFactory, pFactory) {
    assert(['string', 'object'].indexOf(typeof pNameOrDict) >= 0, 'Plugme#set first argument must be a string or a plain object');
    if (typeof pNameOrDict === 'string') {
        if (typeof pFactory === 'function') {
            this._setFactory(pNameOrDict, pDepsOrFactory, pFactory);
        } else if (typeof pDepsOrFactory === 'function') {
            this._setFactory(pNameOrDict, [], pDepsOrFactory);
        } else {
            this._setScalar(pNameOrDict, pDepsOrFactory);
        }
    } else {
        this._setDictionary(pNameOrDict);
    }
};

/**
 * Get components from the registry and execute the callback
 * @param  {String | String[]}   pNameOrDeps
 * @param  {Function} cb
 */
Plugme.prototype.get = function (pNameOrDeps, cb) {
    if (typeof pNameOrDeps !== 'string') {
        pNameOrDeps.forEach(function (dep) {
            assert(typeof dep === 'string', 'Plugme#set dependencies must be a string or an array of strings');
        });
    }
    if (typeof pNameOrDeps === 'string') {
        this._getOne(pNameOrDeps, function (err, ret) {
            if (!err) {
                cb(ret);
            }
        });
    } else {
        async.map(pNameOrDeps, this._getOne.bind(this), function (err, results) {
            if (!err) {
                cb.apply(null, results);
            }
        });
    }
};

/**
 * Start the application
 * @param  {Function} [cb] Function to call after the application is ready
 */
Plugme.prototype.start = function (cb) {
    assert(this._registry.hasOwnProperty('start'), 'A start component must be declared before start is called');
    this._getOne('start', typeof cb === 'function' ? cb : function () {
        return null;
    });
};

/**
 * Return true if a component is already available
 * @param  {String}  name
 * @return {Boolean} true if component is available
 */
Plugme.prototype.isLoaded = function (name) {
    return this._registry.hasOwnProperty(name) && this._registry[name].cache !== undefined;
};

// PRIVATE

/**
 * Get one dependency and inject it in the callback
 * @private
 * @param  {String}   name
 * @param  {Function} cb
 */
Plugme.prototype._getOne = function (name, cb) {
    var _this = this;
    if (this._registry.hasOwnProperty(name)) {
        if (this._registry[name].cache !== undefined) {
            cb(null, this._registry[name].cache);
        } else {
            this._create(name, function () {
                cb(null, _this._registry[name].cache);
            });
        }
    } else {
        this._emitError(new Error('Component ' + name + 'does not exist'));
    }
};

/**
 * Set a new factory in the component registry
 * @private
 * @param {String} name
 * @param {String[]} deps
 * @param {Function} factory
 */
Plugme.prototype._setFactory = function (name, deps, factory) {
    deps.forEach(function (value) {
        assert(typeof value === 'string', 'Dependencies must be an array of string');
    });
    this._registry[name] = {
        factory: factory,
        deps: deps,
        hasBeginLoading: false,
        callbacks: []
    };
};

/**
 * Set a new scalar value in the registry
 * @private
 * @param {String} name
 * @param {Any} value
 */
Plugme.prototype._setScalar = function (name, value) {
    this._registry[name] = {};
    this._registry[name].cache = value;
};

/**
 * Set multiple scalar values from a dictionary
 * @param dictionary
 * @private
 */
Plugme.prototype._setDictionary = function (dictionary) {
    var _this = this;
    Object.keys(dictionary).forEach(function (key) {
        _this._setScalar(key, dictionary[key]);
    });
};

/**
 * Emit an error
 * @param ex
 * @private
 */
Plugme.prototype._emitError = function (ex) {
    var _this = this;
    this._errorHandlers.forEach(function (handler) {
        if (handler.once) {
            _this.offError(handler);
        }
        handler(ex);
    });
};

/**
 * Create a new lazy loaded component from factory
 * @private
 * @param  {String}   name
 * @param  {Function} cb
 */
Plugme.prototype._create = function (name, cb) {
    var _this = this;
    this._registry[name].callbacks.push(cb);
    if (this._registry[name].hasBeginLoading) {
        return;
    }
    this._registry[name].hasBeginLoading = true;
    async.map(this._registry[name].deps, this._getOne.bind(this), function (err, dependencies) {
        var alreadyReturned, returnFunction, value, timeout, hasTimeout;
        if (err) {
            _this._emitError(err);
        }
        alreadyReturned = false;
        timeout = setTimeout(function () {
            hasTimeout = true;
            _this._emitError(new Error('Timeout for component: ' + name));
        }, _this.timeout);
        returnFunction = function (result) {
            if (hasTimeout) {
                return;
            }
            clearTimeout(timeout);
            assert(!alreadyReturned, 'Factory must not call the return callback and return a value other than undefined: ' + name);
            alreadyReturned = true;
            _this._registry[name].cache = result;
            _this._registry[name].callbacks.forEach(function (cb) {
                cb();
            });
            _this._registry[name].callbacks.length = 0;
        };
        dependencies.push(returnFunction);
        try {
            value = _this._registry[name].factory.apply(this, dependencies);
            if (value !== undefined) {
                returnFunction(value);
            }
        } catch (ex) {
            _this._registry[name].hasBeginLoading = false;
            _this._emitError(ex);
        }
    });
};

module.exports = Plugme;
<commit_msg>Modified index.js file to be a proxy to the generated js file in /js<commit_after>module.exports = require('./js');
<|endoftext|>