<commit_before>module.exports = {
  plugins: ['@typescript-eslint', 'jest', 'import', 'eslint-comments'],
  env: {
    browser: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier/@typescript-eslint',
    // after 2.0 is released:
    // 'plugin:@typescript-eslint/recommended-requiring-type-checking',
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json',
    tsconfigRootDir: './',
    ecmaVersion: 2019,
    ecmaFeatures: {
      jsx: false,
    },
  },
  overrides: [
    {
      files: ['**/*.test.ts'],
      extends: ['plugin:jest/recommended'],
      env: {
        'jest/globals': true,
      },
      rules: {
        'jest/no-disabled-tests': 'warn',
        'jest/no-focused-tests': 'error',
        'jest/no-alias-methods': 'error',
        'jest/no-identical-title': 'error',
        'jest/no-jasmine-globals': 'error',
        'jest/no-jest-import': 'error',
        'jest/no-test-prefixes': 'error',
        'jest/no-test-callback': 'error',
        'jest/no-test-return-statement': 'error',
        'jest/prefer-to-have-length': 'warn',
        'jest/prefer-spy-on': 'error',
        'jest/valid-expect': 'error',
        'jest/expect-expect': 'off',
        '@typescript-eslint/ban-ts-ignore': 'off',
      },
    },
  ],
  rules: {
    eqeqeq: 'error',
    'no-var': 'error',
    'prefer-const': 'error',
    'no-trailing-spaces': 'error',
    radix: 'error',
    'no-multiple-empty-lines': 'error',

    '@typescript-eslint/no-unused-vars': [
      'error',
      {vars: 'all', args: 'none', varsIgnorePattern: '[iI]gnored'},
    ],
    '@typescript-eslint/consistent-type-definitions': ['error', 'interface'],
    '@typescript-eslint/no-explicit-any': 'error',
    // '@typescript-eslint/no-non-null-assertion': 'off',
    // '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-use-before-define': 'off',
    '@typescript-eslint/unbound-method': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-parameter-properties': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off',
    // eslint base
    //

    'comma-dangle': ['error', 'always-multiline'],
    curly: ['error', 'multi-line'],
    'no-mixed-operators': 'off',
    'no-console': 'error',
    'no-process-exit': 'error',

    //
    // eslint-plugin-eslint-comment
    //

    // require a eslint-enable comment for every eslint-disable comment
    'eslint-comments/disable-enable-pair': [
      'error',
      {
        allowWholeFile: true,
      },
    ],
    // disallow a eslint-enable comment for multiple eslint-disable comments
    'eslint-comments/no-aggregating-enable': 'error',
    // disallow duplicate eslint-disable comments
    'eslint-comments/no-duplicate-disable': 'error',
    // disallow eslint-disable comments without rule names
    'eslint-comments/no-unlimited-disable': 'error',
    // disallow unused eslint-disable comments
    'eslint-comments/no-unused-disable': 'error',
    // disallow unused eslint-enable comments
    'eslint-comments/no-unused-enable': 'error',
    // disallow ESLint directive-comments
    'eslint-comments/no-use': [
      'error',
      {
        allow: [
          'eslint-disable',
          'eslint-disable-line',
          'eslint-disable-next-line',
          'eslint-enable',
        ],
      },
    ],

    //
    // eslint-plugin-import
    //

    // disallow non-import statements appearing before import statements
    'import/first': 'error',
    // Require a newline after the last import/require in a group
    'import/newline-after-import': 'error',
    // Forbid import of modules using absolute paths
    'import/no-absolute-path': 'error',
    // disallow AMD require/define
    'import/no-amd': 'error',
    // forbid default exports
    'import/no-default-export': 'off',
    // Forbid the use of extraneous packages
    'import/no-extraneous-dependencies': [
      'error',
      {
        devDependencies: true,
        peerDependencies: true,
        optionalDependencies: false,
      },
    ],
    // Forbid mutable exports
    'import/no-mutable-exports': 'error',
    // Prevent importing the default as if it were named
    'import/no-named-default': 'error',
    // Prohibit named exports
    'import/no-named-export': 'off', // we want everything to be a named export
    // Forbid a module from importing itself
    'import/no-self-import': 'error',
    // Require modules with a single export to use a default export
    'import/prefer-default-export': 'off', // we want everything to be named
  },
}
<commit_msg>build: change eslint options<commit_after>module.exports = {
  plugins: ['@typescript-eslint', 'jest', 'import', 'eslint-comments'],
  env: {
    browser: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/eslint-recommended',
    'plugin:@typescript-eslint/recommended',
    'plugin:@typescript-eslint/recommended-requiring-type-checking',
    'prettier/@typescript-eslint',
    // after 2.0 is released:
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: './tsconfig.json',
    tsconfigRootDir: './',
    ecmaVersion: 2019,
    ecmaFeatures: {
      jsx: false,
    },
  },
  overrides: [
    {
      files: ['**/*.test.ts'],
      extends: ['plugin:jest/recommended'],
      env: {
        'jest/globals': true,
      },
      rules: {
        'jest/no-disabled-tests': 'warn',
        'jest/no-focused-tests': 'error',
        'jest/no-alias-methods': 'error',
        'jest/no-identical-title': 'error',
        'jest/no-jasmine-globals': 'error',
        'jest/no-jest-import': 'error',
        'jest/no-test-prefixes': 'error',
        'jest/no-test-callback': 'error',
        'jest/no-test-return-statement': 'error',
        'jest/prefer-to-have-length': 'warn',
        'jest/prefer-spy-on': 'error',
        'jest/valid-expect': 'error',
        'jest/expect-expect': 'off',
        '@typescript-eslint/ban-ts-ignore': 'off',
      },
    },
  ],
  rules: {
    eqeqeq: 'error',
    'no-var': 'error',
    'prefer-const': 'error',
    'no-trailing-spaces': 'error',
    radix: 'error',
    'no-multiple-empty-lines': 'error',

    '@typescript-eslint/no-unused-vars': [
      'error',
      {vars: 'all', args: 'none', varsIgnorePattern: '[iI]gnored'},
    ],
    '@typescript-eslint/consistent-type-definitions': ['error', 'interface'],

    '@typescript-eslint/prefer-optional-chain': 'error',
    '@typescript-eslint/no-explicit-any': 'error',
    // '@typescript-eslint/no-non-null-assertion': 'off',
    // '@typescript-eslint/no-var-requires': 'off',
    '@typescript-eslint/no-use-before-define': 'off',
    '@typescript-eslint/unbound-method': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/no-parameter-properties': 'off',
    '@typescript-eslint/no-non-null-assertion': 'off',
    // eslint base
    //

    'comma-dangle': ['error', 'always-multiline'],
    curly: ['error', 'multi-line'],
    'no-mixed-operators': 'off',
    'no-console': 'error',
    'no-process-exit': 'error',

    //
    // eslint-plugin-eslint-comment
    //

    // require a eslint-enable comment for every eslint-disable comment
    'eslint-comments/disable-enable-pair': [
      'error',
      {
        allowWholeFile: true,
      },
    ],
    // disallow a eslint-enable comment for multiple eslint-disable comments
    'eslint-comments/no-aggregating-enable': 'error',
    // disallow duplicate eslint-disable comments
    'eslint-comments/no-duplicate-disable': 'error',
    // disallow eslint-disable comments without rule names
    'eslint-comments/no-unlimited-disable': 'error',
    // disallow unused eslint-disable comments
    'eslint-comments/no-unused-disable': 'error',
    // disallow unused eslint-enable comments
    'eslint-comments/no-unused-enable': 'error',
    // disallow ESLint directive-comments
    'eslint-comments/no-use': [
      'error',
      {
        allow: [
          'eslint-disable',
          'eslint-disable-line',
          'eslint-disable-next-line',
          'eslint-enable',
        ],
      },
    ],

    //
    // eslint-plugin-import
    //

    // disallow non-import statements appearing before import statements
    'import/first': 'error',
    // Require a newline after the last import/require in a group
    'import/newline-after-import': 'error',
    // Forbid import of modules using absolute paths
    'import/no-absolute-path': 'error',
    // disallow AMD require/define
    'import/no-amd': 'error',
    // forbid default exports
    'import/no-default-export': 'off',
    // Forbid the use of extraneous packages
    'import/no-extraneous-dependencies': [
      'error',
      {
        devDependencies: true,
        peerDependencies: true,
        optionalDependencies: false,
      },
    ],
    // Forbid mutable exports
    'import/no-mutable-exports': 'error',
    // Prevent importing the default as if it were named
    'import/no-named-default': 'error',
    // Prohibit named exports
    'import/no-named-export': 'off', // we want everything to be a named export
    // Forbid a module from importing itself
    'import/no-self-import': 'error',
    // Require modules with a single export to use a default export
    'import/prefer-default-export': 'off', // we want everything to be named
  },
}
<|endoftext|>


<commit_before>module.exports = {
  root: true,  // ESLint 一旦发现配置文件中有 "root": true，它就会停止在父级目录中寻找配置文件。
  parser: 'babel-eslint',
  parserOptions: {
    // 设置为 "script" (默认) 或 "module"（如果你的代码是 ECMAScript 模块)
    sourceType: 'module'
  },
  extends: ['eslint:recommended'],  // 配置代码检查风格
  // extends: ['eslint:recommended', 'angular'],  // 配置代码检查风格
  // extends: ['airbnb-base', 'angular'],
  // extends: 'airbnb-base',
  'rules': {
    // add your custom rules here

    ///////////
    // allow //
    ///////////
    'no-console': 0, // 不允许console.log
    'comma-dangle': 0,
    'no-extra-semi': 0, // 不允许多余的分号
    'linebreak-style': 0, // 强制使用一致的换行符风格
    'semi': 0, // 要求或禁止使用分号而不是 ASI
    "no-control-regex": 0, // 禁止在正则表达式中使用控制字符 ：new RegExp("\x1f")
    'no-div-regex': 0,
    'no-param-reassign': 0, // 不允许对 function 的参数进行重新赋值
    'no-undefined':　0, // 禁止将 undefined 作为标识符
    'computed-property-spacing': 0, // 强制在计算的属性的方括号中使用一致的空格
    'eol-last': 0, // 强制文件末尾至少保留一行空行
    'consistent-this': 0,  // 当获取当前执行环境的上下文时，强制使用一致的命名
    'func-names': 0, // 强制使用命名的 function 表达式
    'no-multiple-empty-lines': 0, // 不允许多个空行
    'max-len': [0, {"ignoreComments": true}], // 强制一行的最大长度(80)
    'keyword-spacing': 0,
    'indent': [0, 4], // 强制使用一致的缩进 (默认为4个空格)
    /////////////
    // warning //
    /////////////

    'valid-jsdoc': 1, // 强制使用有效的 JSDoc 注释
    'guard-for-in': 1, // 要求 for-in 循环中有一个 if 语句
    'no-alert': 1, // 禁用 alert、confirm 和 prompt
    'no-extend-native': 1, // 禁止扩展原生类型
    'no-implicit-coercion': 1, // 禁止使用短符号进行类型转换
    'no-multi-spaces': 1, // 禁止使用多个空格
    'no-new-wrappers': 1, // 禁止对 String，Number 和 Boolean 使用 new 操作符
    'no-proto': 1, // 禁用 proto 操作符
    'no-void': 1, // 禁用 void 操作符
    'vars-on-top': 1, // 要求所有的 var 声明出现在它们所在的作用域顶部
    'no-shadow': 1, // 禁止 var 声明 与外层作用域的变量同名
    'no-undef-init': 1 , // 禁止将变量初始化为 undefined
    'no-use-before-define': 1, // 不允许在变量定义之前使用它们(更好的与let和const接轨)
    'brace-style': ["error", "1tbs",  { "allowSingleLine": true }], // one true brace style 大括号风格要求
    'comma-spacing': 1, // 强制在逗号前后使用一致的空格
    'comma-style': 1, // 强制使用一致的逗号风格
    'id-length': [1, {'min': 2, 'max': 20}],  // 强制标识符的最新和最大长度
    'new-parens': 1, // 要求调用无参构造函数时有圆括号
    'newline-per-chained-call': 1, // 要求方法链中每个调用都有一个换行符
    'no-array-constructor': 1, // 禁止使用 Array 构造函数
    'no-mixed-operators': 1, // 禁止混合使用不同的操作符
    'no-negated-condition': 1, // 不允许否定的表达式
    'no-nested-ternary': 1, // 不允许使用嵌套的三元表达式
    'no-new-object': 1,
    'no-spaced-func': 1, // 禁止 function 标识符和括号之间出现空格
    'require-jsdoc': 1, // 要求使用 JSDoc 注释
    'space-infix-ops': 1, // 要求操作符周围有空格
    'consistent-return': [1, {"treatUndefinedAsUnspecified": true}], // 要求 return 语句要么总是指定返回的值，要么不指定
    'no-irregular-whitespace': 1,

    //////////////
    // disabled //
    //////////////
    "no-unused-vars": 2, // 不允许定义了但未使用的变量
    'block-scoped-var': 2,
    'accessor-pairs': 2,  // 强制 getter 和 setter 在对象中成对出现
    'array-callback-return': 2, // 强制数组方法的回调函数中有 return 语句
    'block-scoped-var': 2, // 强制把变量的使用限制在其定义的作用域范围内(当移植到es6时，则可以直接用let全局替换var)
    "complexity": ["error", { "max": 10 }],  // 指定程序中允许的最大环路复杂度
    'default-case': 2, // 要求 switch 语句中有 default 分支
    'dot-notation': 2, // 强制在任何允许的时候使用点号
    'eqeqeq': 2, // 要求使用 === 和 !==
    'no-caller': 2, // 禁用 arguments.caller 或 arguments.callee
    'no-case-declarations': 2, // 不允许在 case 子句中使用词法声明
    'no-else-return': 2, // 禁止 if 语句中有 return 之后有 else
    'no-empty-function': 2, // 禁止出现空函数
    'no-eq-null': 2, // 禁止在没有类型检查操作符的情况下与 null 进行比较
    'no-eval': 2,
    'no-extra-bind': 2, // 禁止不必要的 .bind() 调用
    'no-fallthrough': 2, // 禁止 case 语句落空
    'no-floating-decimal': 2, // 禁止数字字面量中使用前导和末尾小数点
    'no-implicit-globals': 2, // 禁止在全局范围内使用 var 和命名的 function 声明
    'no-invalid-this': 2, //  禁止 this 关键字出现在类和类对象之外
    'no-lone-blocks': 2, // 禁用不必要的嵌套块
    'no-loop-func': 2, // 禁止在循环中出现 function 声明和表达式
    'no-magic-numbers': 2, // 禁用魔术数字(去除硬编码)
    'no-multi-str': 2, // 禁止使用多行字符串(like \)
    'no-native-reassign': 2, // 禁止对原生对象赋值
    'no-new': 2, // 禁止在非赋值或条件语句中使用 new 操作符
    'no-new-func': 2, // 禁止对 Function 对象使用 new 操作符
    'no-redeclare': 2, // 禁止使用 var 多次声明同一变量
    'no-return-assign': 2, // 禁止在 return 语句中使用赋值语句

    'no-self-compare': 2, // 禁止自身比较
    'no-throw-literal': 2, // 禁止抛出非异常字面量
    'no-unused-expressions': 2, // 禁止出现未使用过的表达式
    'no-useless-call': 2, // 禁止不必要的 .call() 和 .apply()
    'no-useless-concat': 2, // 禁止不必要的字符串字面量或模板字面量的连接
    'no-with': 2, // 禁用 with 语句
    'wrap-iife': 2, // 要求 IIFE 使用括号括起来
    'yoda': 2, // 要求或禁止 “Yoda” 条件
    'strict': 2, // 要求使用严格模式
    'no-shadow-restricted-names': 2, // 禁止覆盖受限制的标识符
    'no-undef': 2, // 禁用未声明的变量，除非它们在 /*global */ 注释中被提到
    'no-unused-vars': 2, // 禁止出现未使用过的变量

    // 代码风格指南
    'camelcase': 2, // 强制使用骆驼拼写法命名约定
    'max-depth': 2, // 强制可嵌套的块的最大深度(4)
    'max-nested-callbacks': ["error", { "max": 3 }], // 强制回调函数最大嵌套深度
    'valid-typeof': 2, // 强制 typeof 表达式与有效的字符串进行比较
    'no-floating-decimal': 2, // 禁止数字字面量中使用前导和末尾小数点
    'max-params': ["error", { "max": 4 }], // 强制 function 定义中最多允许的参数数量
    'max-statements': ["error", { "max": 30 }], // 强制 function 块最多允许的的语句数量
    'new-cap': 2, // 要求构造函数首字母大写
    'no-bitwise': 2, // 禁用按位运算符
    'no-unneeded-ternary': 2, // 禁止可以在有更简单的可替代的表达式时使用三元操作符
    'operator-assignment': 2, // 要求或禁止在可能的情况下要求使用简化的赋值操作符(默认为要求)

  },

  "env": {
    "browser": true,  //  browser 全局变量, 解决window变量报错的问题
    "node": true,
    "phantomjs": true,
    "protractor": true,
    "jasmine": true,  // 添加所有的 Jasmine 版本 1.3 和 2.0 的测试全局变量。
    "es6": true  // 支持除了modules所有 ECMAScript 6 特性。
  },
}
<commit_msg>remove the id-length rule from eslint<commit_after>module.exports = {
  root: true,  // ESLint 一旦发现配置文件中有 "root": true，它就会停止在父级目录中寻找配置文件。
  parser: 'babel-eslint',
  parserOptions: {
    // 设置为 "script" (默认) 或 "module"（如果你的代码是 ECMAScript 模块)
    sourceType: 'module'
  },
  extends: ['eslint:recommended'],  // 配置代码检查风格
  // extends: ['eslint:recommended', 'angular'],  // 配置代码检查风格
  // extends: ['airbnb-base', 'angular'],
  // extends: 'airbnb-base',
  'rules': {
    // add your custom rules here

    ///////////
    // allow //
    ///////////
    'no-console': 0, // 不允许console.log
    'comma-dangle': 0,
    'no-extra-semi': 0, // 不允许多余的分号
    'linebreak-style': 0, // 强制使用一致的换行符风格
    'semi': 0, // 要求或禁止使用分号而不是 ASI
    "no-control-regex": 0, // 禁止在正则表达式中使用控制字符 ：new RegExp("\x1f")
    'no-div-regex': 0,
    'no-param-reassign': 0, // 不允许对 function 的参数进行重新赋值
    'no-undefined':　0, // 禁止将 undefined 作为标识符
    'computed-property-spacing': 0, // 强制在计算的属性的方括号中使用一致的空格
    'eol-last': 0, // 强制文件末尾至少保留一行空行
    'consistent-this': 0,  // 当获取当前执行环境的上下文时，强制使用一致的命名
    'func-names': 0, // 强制使用命名的 function 表达式
    'no-multiple-empty-lines': 0, // 不允许多个空行
    'max-len': [0, {"ignoreComments": true}], // 强制一行的最大长度(80)
    'keyword-spacing': 0,
    'indent': [0, 4], // 强制使用一致的缩进 (默认为4个空格)
    /////////////
    // warning //
    /////////////

    'valid-jsdoc': 1, // 强制使用有效的 JSDoc 注释
    'guard-for-in': 1, // 要求 for-in 循环中有一个 if 语句
    'no-alert': 1, // 禁用 alert、confirm 和 prompt
    'no-extend-native': 1, // 禁止扩展原生类型
    'no-implicit-coercion': 1, // 禁止使用短符号进行类型转换
    'no-multi-spaces': 1, // 禁止使用多个空格
    'no-new-wrappers': 1, // 禁止对 String，Number 和 Boolean 使用 new 操作符
    'no-proto': 1, // 禁用 proto 操作符
    'no-void': 1, // 禁用 void 操作符
    'vars-on-top': 1, // 要求所有的 var 声明出现在它们所在的作用域顶部
    'no-shadow': 1, // 禁止 var 声明 与外层作用域的变量同名
    'no-undef-init': 1 , // 禁止将变量初始化为 undefined
    'no-use-before-define': 1, // 不允许在变量定义之前使用它们(更好的与let和const接轨)
    'brace-style': ["error", "1tbs",  { "allowSingleLine": true }], // one true brace style 大括号风格要求
    'comma-spacing': 1, // 强制在逗号前后使用一致的空格
    'comma-style': 1, // 强制使用一致的逗号风格
    'id-length': [1, {'min': 1, 'max': 20}],  // 强制标识符的最新和最大长度
    'new-parens': 1, // 要求调用无参构造函数时有圆括号
    'newline-per-chained-call': 1, // 要求方法链中每个调用都有一个换行符
    'no-array-constructor': 1, // 禁止使用 Array 构造函数
    'no-mixed-operators': 1, // 禁止混合使用不同的操作符
    'no-negated-condition': 1, // 不允许否定的表达式
    'no-nested-ternary': 1, // 不允许使用嵌套的三元表达式
    'no-new-object': 1,
    'no-spaced-func': 1, // 禁止 function 标识符和括号之间出现空格
    'require-jsdoc': 1, // 要求使用 JSDoc 注释
    'space-infix-ops': 1, // 要求操作符周围有空格
    'consistent-return': [1, {"treatUndefinedAsUnspecified": true}], // 要求 return 语句要么总是指定返回的值，要么不指定
    'no-irregular-whitespace': 1,

    //////////////
    // disabled //
    //////////////
    "no-unused-vars": 2, // 不允许定义了但未使用的变量
    'block-scoped-var': 2,
    'accessor-pairs': 2,  // 强制 getter 和 setter 在对象中成对出现
    'array-callback-return': 2, // 强制数组方法的回调函数中有 return 语句
    'block-scoped-var': 2, // 强制把变量的使用限制在其定义的作用域范围内(当移植到es6时，则可以直接用let全局替换var)
    "complexity": ["error", { "max": 10 }],  // 指定程序中允许的最大环路复杂度
    'default-case': 2, // 要求 switch 语句中有 default 分支
    'dot-notation': 2, // 强制在任何允许的时候使用点号
    'eqeqeq': 2, // 要求使用 === 和 !==
    'no-caller': 2, // 禁用 arguments.caller 或 arguments.callee
    'no-case-declarations': 2, // 不允许在 case 子句中使用词法声明
    'no-else-return': 2, // 禁止 if 语句中有 return 之后有 else
    'no-empty-function': 2, // 禁止出现空函数
    'no-eq-null': 2, // 禁止在没有类型检查操作符的情况下与 null 进行比较
    'no-eval': 2,
    'no-extra-bind': 2, // 禁止不必要的 .bind() 调用
    'no-fallthrough': 2, // 禁止 case 语句落空
    'no-floating-decimal': 2, // 禁止数字字面量中使用前导和末尾小数点
    'no-implicit-globals': 2, // 禁止在全局范围内使用 var 和命名的 function 声明
    'no-invalid-this': 2, //  禁止 this 关键字出现在类和类对象之外
    'no-lone-blocks': 2, // 禁用不必要的嵌套块
    'no-loop-func': 2, // 禁止在循环中出现 function 声明和表达式
    'no-magic-numbers': 2, // 禁用魔术数字(去除硬编码)
    'no-multi-str': 2, // 禁止使用多行字符串(like \)
    'no-native-reassign': 2, // 禁止对原生对象赋值
    'no-new': 2, // 禁止在非赋值或条件语句中使用 new 操作符
    'no-new-func': 2, // 禁止对 Function 对象使用 new 操作符
    'no-redeclare': 2, // 禁止使用 var 多次声明同一变量
    'no-return-assign': 2, // 禁止在 return 语句中使用赋值语句

    'no-self-compare': 2, // 禁止自身比较
    'no-throw-literal': 2, // 禁止抛出非异常字面量
    'no-unused-expressions': 2, // 禁止出现未使用过的表达式
    'no-useless-call': 2, // 禁止不必要的 .call() 和 .apply()
    'no-useless-concat': 2, // 禁止不必要的字符串字面量或模板字面量的连接
    'no-with': 2, // 禁用 with 语句
    'wrap-iife': 2, // 要求 IIFE 使用括号括起来
    'yoda': 2, // 要求或禁止 “Yoda” 条件
    'strict': 2, // 要求使用严格模式
    'no-shadow-restricted-names': 2, // 禁止覆盖受限制的标识符
    'no-undef': 2, // 禁用未声明的变量，除非它们在 /*global */ 注释中被提到
    'no-unused-vars': 2, // 禁止出现未使用过的变量

    // 代码风格指南
    'camelcase': 2, // 强制使用骆驼拼写法命名约定
    'max-depth': 2, // 强制可嵌套的块的最大深度(4)
    'max-nested-callbacks': ["error", { "max": 3 }], // 强制回调函数最大嵌套深度
    'valid-typeof': 2, // 强制 typeof 表达式与有效的字符串进行比较
    'no-floating-decimal': 2, // 禁止数字字面量中使用前导和末尾小数点
    'max-params': ["error", { "max": 4 }], // 强制 function 定义中最多允许的参数数量
    'max-statements': ["error", { "max": 30 }], // 强制 function 块最多允许的的语句数量
    'new-cap': 2, // 要求构造函数首字母大写
    'no-bitwise': 2, // 禁用按位运算符
    'no-unneeded-ternary': 2, // 禁止可以在有更简单的可替代的表达式时使用三元操作符
    'operator-assignment': 2, // 要求或禁止在可能的情况下要求使用简化的赋值操作符(默认为要求)

  },

  "env": {
    "browser": true,  //  browser 全局变量, 解决window变量报错的问题
    "node": true,
    "phantomjs": true,
    "protractor": true,
    "jasmine": true,  // 添加所有的 Jasmine 版本 1.3 和 2.0 的测试全局变量。
    "es6": true  // 支持除了modules所有 ECMAScript 6 特性。
  },
}
<|endoftext|>


<commit_before>var path = require('path')

const downgraded = [
  'array-callback-return',
  'class-methods-use-this',
  'consistent-return',
  'eqeqeq',
  'getter-return',
  'no-async-promise-executor',
  'no-await-in-loop',
  'no-prototype-builtins',
  'no-restricted-globals',
  'no-restricted-syntax',
  'no-return-assign',
  'no-self-compare',
  'no-shadow',
  'no-underscore-dangle',
  'no-use-before-define',
]

module.exports = {
  extends: '@ln-zap',
  rules: downgraded.reduce(
    (acc, next) => {
      acc[next] = 'warn'
      return acc
    },
    {
      'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
      'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
    }
  ),
  settings: {
    'import/resolver': {
      'babel-module': {},
    },
    node: {
      moduleDirectory: ['renderer', 'node_modules'],
    },
    webpack: {
      config: path.resolve(__dirname, 'webpack', 'webpack.config.eslint.js'),
    },
  },
}
<commit_msg>style(lint): upgrade getter-return lint rule from warn to error<commit_after>var path = require('path')

const downgraded = [
  'array-callback-return',
  'class-methods-use-this',
  'consistent-return',
  'eqeqeq',
  'no-async-promise-executor',
  'no-await-in-loop',
  'no-prototype-builtins',
  'no-restricted-globals',
  'no-restricted-syntax',
  'no-return-assign',
  'no-self-compare',
  'no-shadow',
  'no-underscore-dangle',
  'no-use-before-define',
]

module.exports = {
  extends: '@ln-zap',
  rules: downgraded.reduce(
    (acc, next) => {
      acc[next] = 'warn'
      return acc
    },
    {
      'no-unused-expressions': ['error', { allowShortCircuit: true, allowTernary: true }],
      'no-plusplus': ['error', { allowForLoopAfterthoughts: true }],
    }
  ),
  settings: {
    'import/resolver': {
      'babel-module': {},
    },
    node: {
      moduleDirectory: ['renderer', 'node_modules'],
    },
    webpack: {
      config: path.resolve(__dirname, 'webpack', 'webpack.config.eslint.js'),
    },
  },
}
<|endoftext|>


<commit_before>module.exports = {
    "extends": ["standard"],
    "plugins": [
        "standard",
        "promise",
        "node"
    ]
};<commit_msg>set eslint node no-unspported-features to v4 for aws lambda<commit_after>module.exports = {
    "extends": ["standard"],
    "plugins": [
        "standard",
        "promise",
        "node"
    ],
    "rules": {
      "node/no-unsupported-features": ["error", {
          "version": 4
      }]
    }
};<|endoftext|>


<commit_before>module.exports = {
    "extends": "eslint:recommended",
    // add your custom rules here
    rules: {
        "semi": ["error", "always"],
        "indent": ["error", 4],
        "space-before-function-paren": ["error", "never"],
        "no-extra-boolean-cast": 0, // 0=silence, 1=warning, 2=error
        // allow async-await
        'generator-star-spacing': 'off',
        // allow debugger during development
        'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
        "camelcase": [2, {"properties": "always"}]
    },
    "globals": {
        "define": false,
        "require": false,
        "window": false,
        "console": false,
        "history": false,
        "location": false,
        "Promise": false,
        "setTimeout": false
    }
};
<commit_msg>Permit ES6 syntax, re #7537<commit_after>module.exports = {
    "extends": "eslint:recommended",
    // add your custom rules here
    rules: {
        "semi": ["error", "always"],
        "indent": ["error", 4],
        "space-before-function-paren": ["error", "never"],
        "no-extra-boolean-cast": 0, // 0=silence, 1=warning, 2=error
        // allow async-await
        'generator-star-spacing': 'off',
        // allow debugger during development
        'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
        "camelcase": [2, {"properties": "always"}]
    },
    "globals": {
        "define": false,
        "require": false,
        "window": false,
        "console": false,
        "history": false,
        "location": false,
        "Promise": false,
        "setTimeout": false
    },
    "parserOptions": {
        "ecmaVersion": 2017
    },
    "env": {
        "es6": true
    }
};
<|endoftext|>


<commit_before>'use strict';

function ValueModel(name, $scope, webSocket) {
  this.topic = null;

  var callback = function (message) {
    $scope[name] = message;
    $scope.$apply();
  };

  this.update = function (newTopic) {
    if (this.topic) {
      webSocket.unsubscribe(this.topic, callback);
    }
    this.topic = newTopic;
    webSocket.subscribe(this.topic, callback, $scope);
  };
}

//TODO
function ChartModel(name, $scope, webSocket) {
  this.topic = null;

  var max = 30;
  var data = [];

  var callback = function (value) {
    var now = Date.now();

    data.push({
      timestamp: now,
      value: value
    });

    if (data.length > 100) { //TODO
      data.shift();
    }

    $scope[name] = {
      data: data,
      max: max
    };

    $scope.$apply();
  };

  this.update = function (newTopic) {
    if (this.topic) {
      webSocket.unsubscribe(this.topic, callback);
    }

    this.topic = newTopic;
    data = [];

    webSocket.subscribe(this.topic, callback, $scope);
  };
}

function DataSource(model, topic) {
  this.model = model;
  this.topic = topic;

  if (topic) {
    this.model.update(topic);
  }

  this.update = function (topic) {
    this.topic = topic;
    this.model.update(topic);
  };
}

angular.module('app')
  .factory('WebSocketDataSource', function (WidgetDataSource, webSocket) {
    function WebSocketDataSource() {
      console.log('WebSocketDataSource constructor');
    }
    WebSocketDataSource.prototype = Object.create(WidgetDataSource.prototype);

    WebSocketDataSource.prototype.init = function () {
      this.topic = null;
      this.callback = null;
      this.update('app.visualdata.piValue');
    };

    WebSocketDataSource.prototype.update = function (newTopic) {
      console.log('_update');
      var that = this;

      if (this.topic && this.callback) {
        webSocket.unsubscribe(this.topic, this.callback);
      }

      this.callback = function (message) {
        //console.log('_callback ' + that.topic);
        that.updateScope(message);
        that.widgetScope.$apply();
      };

      this.topic = newTopic;
      webSocket.subscribe(this.topic, this.callback, this.widgetScope);
    };

    WebSocketDataSource.prototype.destroy = function () {
      WidgetDataSource.prototype.destroy.call(this);

      console.log('_WebSocketDataSource destroy');

      if (this.topic && this.callback) {
        webSocket.unsubscribe(this.topic, this.callback);
      }
    };

    return WebSocketDataSource;
  })
  .factory('RandomValueDataSource', function (WidgetDataSource, $interval) {
    function RandomValueDataSource() {
      console.log('RandomValueDataSource constructor');
    }
    RandomValueDataSource.prototype = Object.create(WidgetDataSource.prototype);

    RandomValueDataSource.prototype.init = function () {
      var base = Math.floor(Math.random() * 10) * 10;

      this.updateScope(base);

      var that = this;

      this.intervalPromise = $interval(function () {
        var random = base + Math.random();
        //console.log(random);
        that.updateScope(random);
      }, 500);
    };

    RandomValueDataSource.prototype.destroy = function () {
      WidgetDataSource.prototype.destroy.call(this);
      console.log('_RandomValueDataSource destroy');
      $interval.cancel(this.intervalPromise);
    };

    return RandomValueDataSource;
  })
  .controller('ServerDataCtrl', function ($scope, webSocket, settings, RandomValueDataSource, WebSocketDataSource) {
    $scope.value1 = 'not defined';
    $scope.value2 = 'not defined';

    var widgetDefinitions = [
      {
        name: 'value1',
        directive: 'wt-scope-watch',
        dataAttrName: 'value',
        //ds: new WidgetDataSource(),
        //ds: new RandomValueDataSource(),
        dataSourceType: RandomValueDataSource,
        style: {
          width: '40%'
        }
      },
      {
        name: 'value2',
        directive: 'wt-scope-watch',
        dataAttrName: 'value',
        dataSourceType: WebSocketDataSource,
        style: {
          width: '40%'
        }
      },
      {
        name: 'chart1',
        directive: 'wt-line-chart',
        attrs: {
          chart: 'chart'
        },
        dataSource: new DataSource(
          new ChartModel('chart', $scope, webSocket),
          'app.visualdata.chartValue'
        ),
        style: {
          width: '50%'
        }
      },
      {
        name: 'chart2',
        directive: 'wt-line-chart',
        attrs: {
          chart: 'chart2'
        },
        style: {
          width: '50%'
        }
      },
      {
        name: 'topics',
        templateUrl: 'template/topics.html'
      },
      {
        name: 'wt-gauge',
        attrs: {
          value: 'gaugeValue'
        },
        dataSource: new DataSource(
          new ValueModel('gaugeValue', $scope, webSocket),
          'app.visualdata.chartValue'
        ),
        style: {
          width: '250px'
        }
      },
      {
        name: 'wt-top-n',
        attrs: {
          data: 'serverTopTen'
        }
      }
    ];

    var defaultWidgets = _.clone(widgetDefinitions);

    $scope.dashboardOptions = {
      widgetButtons: true,
      widgetDefinitions: widgetDefinitions,
      defaultWidgets: defaultWidgets,
      optionsTemplateUrl: 'template/widgetOptions.html'
    };

    //TODO
    $scope.serverValue = 0;
    webSocket.subscribe(settings.randomValueTopic, function (message) {
      $scope.serverValue = message.value;
      $scope.$apply();
    }, $scope);

    webSocket.subscribe(settings.topNTopic, function (message) {
      var list = [];
      _.each(message, function (value, key) {
        list.push({ name: key, value: parseInt(value, 10) });
      }, $scope);

      $scope.serverTopTen = list;
      $scope.$apply();
    }, $scope);

    $scope.chartValue = 0;
    var valueModel = new ValueModel('chartValue', $scope, webSocket);

    var chartModel = new ChartModel('chart', $scope, webSocket);

    var chartModel2 = new ChartModel('chart2', $scope, webSocket);
    chartModel2.update('app.visualdata.chartValue2');

    $scope.$on('topic', function (event, topic) {
      valueModel.update(topic);
      chartModel.update(topic);
    });
  })
  .controller('TopicCtrl', function ($scope, webSocket) {
    webSocket.subscribe('_latestTopics', function (message) {
      var list = _.reject(message, function (topic) {
        return topic.indexOf('applications.') >= 0;
      });
      $scope.topics = _.sortBy(list, function (topic) {
        return topic;
      });
      if (message.length) {
        $scope.topic = $scope.topics[0];
      }
      $scope.$apply();
    }, $scope);
    webSocket.send({ type: 'getLatestTopics' });

    var callback = function (message) {
      $scope.topicData = JSON.stringify(message, null, ' ');
      $scope.$apply();
    };

    $scope.$watch('topic', function (newTopic, oldTopic) {
      if (oldTopic && callback) {
        webSocket.unsubscribe(oldTopic, callback);
      }

      if (newTopic) {
        $scope.topicData = 'Loading...';
        webSocket.subscribe(newTopic, callback, $scope);
        //$scope.$emit('topic', newTopic); //TODO
        //$rootScope.$broadcast('topic', newTopic);
      }
    });
  })
  .controller('WidgetOptionsCtrl', function ($scope, webSocket) {
    var widget = $scope.widget;
    if (widget && widget.dataSource) {
      $scope.topic = widget.dataSource.topic;

      // load available topics
      webSocket.subscribe('_latestTopics', function (message) {
        var list = _.reject(message, function (topic) {
          return topic.indexOf('applications.') >= 0;
        });
        $scope.topics = _.sortBy(list, function (topic) {
          return topic;
        });

        //TODO unsubscribe webSocket.get(request).then(...);

        $scope.$apply();
      }, $scope);
      webSocket.send({ type: 'getLatestTopics' });

      $scope.$watch('topic', function (newTopic) {
        if (newTopic && (newTopic !== widget.dataSource.topic)) {
          widget.dataSource.update(newTopic);
        }
      });
    }
  });<commit_msg>time series data source<commit_after>'use strict';

function ValueModel(name, $scope, webSocket) {
  this.topic = null;

  var callback = function (message) {
    $scope[name] = message;
    $scope.$apply();
  };

  this.update = function (newTopic) {
    if (this.topic) {
      webSocket.unsubscribe(this.topic, callback);
    }
    this.topic = newTopic;
    webSocket.subscribe(this.topic, callback, $scope);
  };
}

//TODO
function ChartModel(name, $scope, webSocket) {
  this.topic = null;

  var max = 30;
  var data = [];

  var callback = function (value) {
    var now = Date.now();

    data.push({
      timestamp: now,
      value: value
    });

    if (data.length > 100) { //TODO
      data.shift();
    }

    $scope[name] = {
      data: data,
      max: max
    };

    $scope.$apply();
  };

  this.update = function (newTopic) {
    if (this.topic) {
      webSocket.unsubscribe(this.topic, callback);
    }

    this.topic = newTopic;
    data = [];

    webSocket.subscribe(this.topic, callback, $scope);
  };
}

function DataSource(model, topic) {
  this.model = model;
  this.topic = topic;

  if (topic) {
    this.model.update(topic);
  }

  this.update = function (topic) {
    this.topic = topic;
    this.model.update(topic);
  };
}

angular.module('app')
  .factory('TimeSeriesDataSource', function (WebSocketDataSource) {
    function TimeSeriesDataSource() {
    }
    TimeSeriesDataSource.prototype = Object.create(WebSocketDataSource.prototype);

    TimeSeriesDataSource.prototype.init = function () {
      WebSocketDataSource.prototype.init.call(this);
    };

    TimeSeriesDataSource.prototype.update = function (newTopic) {
      WebSocketDataSource.prototype.update.call(this, newTopic);
      this.items = [];
    };

    TimeSeriesDataSource.prototype.updateScope = function (value) {
      this.items.push({
        timestamp: parseInt(value[0].timestamp, 10), //TODO
        value: parseInt(value[0].value, 10) //TODO
      });

      if (this.items > 100) { //TODO
        this.items.shift();
      }

      var chart = {
        data: this.items,
        max: 30
      };

      WebSocketDataSource.prototype.updateScope.call(this, chart);
      this.data = [];
    };

    return TimeSeriesDataSource;
  })
  .factory('WebSocketDataSource', function (WidgetDataSource, webSocket) {
    function WebSocketDataSource() {
    }
    WebSocketDataSource.prototype = Object.create(WidgetDataSource.prototype);

    WebSocketDataSource.prototype.init = function () {
      this.topic = null;
      this.callback = null;
      if (this.dataSourceOptions && this.dataSourceOptions.defaultTopic) {
        this.update(this.dataSourceOptions.defaultTopic);
      }
    };

    WebSocketDataSource.prototype.update = function (newTopic) {
      var that = this;

      if (this.topic && this.callback) {
        webSocket.unsubscribe(this.topic, this.callback);
      }

      this.callback = function (message) {
        that.updateScope(message);
        that.widgetScope.$apply();
      };

      this.topic = newTopic;
      webSocket.subscribe(this.topic, this.callback, this.widgetScope);
    };

    WebSocketDataSource.prototype.destroy = function () {
      WidgetDataSource.prototype.destroy.call(this);

      if (this.topic && this.callback) {
        webSocket.unsubscribe(this.topic, this.callback);
      }
    };

    return WebSocketDataSource;
  })
  .factory('RandomValueDataSource', function (WidgetDataSource, $interval) {
    function RandomValueDataSource() {
    }
    RandomValueDataSource.prototype = Object.create(WidgetDataSource.prototype);

    RandomValueDataSource.prototype.init = function () {
      var base = Math.floor(Math.random() * 10) * 10;

      this.updateScope(base);

      var that = this;

      this.intervalPromise = $interval(function () {
        var random = base + Math.random();
        that.updateScope(random);
      }, 500);
    };

    RandomValueDataSource.prototype.destroy = function () {
      WidgetDataSource.prototype.destroy.call(this);
      $interval.cancel(this.intervalPromise);
    };

    return RandomValueDataSource;
  })
  .controller('ServerDataCtrl', function ($scope, webSocket, settings, RandomValueDataSource, WebSocketDataSource, TimeSeriesDataSource) {
    $scope.value1 = 'not defined';
    $scope.value2 = 'not defined';

    var widgetDefinitions = [
      {
        name: 'value1',
        directive: 'wt-scope-watch',
        dataAttrName: 'value',
        dataSourceType: RandomValueDataSource,
        style: {
          width: '30%'
        }
      },
      {
        name: 'value2',
        directive: 'wt-scope-watch',
        dataAttrName: 'value',
        dataSourceType: WebSocketDataSource,
        dataSourceOptions: {
          defaultTopic: 'app.visualdata.piValue'
        },
        style: {
          width: '30%'
        }
      },
      {
        name: 'value3',
        directive: 'wt-scope-watch',
        dataAttrName: 'value',
        dataSourceType: WebSocketDataSource,
        dataSourceOptions: {
          defaultTopic: 'app.visualdata.chartValue'
        },
        style: {
          width: '30%'
        }
      },
      {
        name: 'chart1',
        directive: 'wt-line-chart',
        dataAttrName: 'chart',
        dataSourceType: TimeSeriesDataSource,
        dataSourceOptions: {
          defaultTopic: 'app.visualdata.chartValue_{type:\'timeseries\',minValue:0,maxValue:100}' //TODO
        },
        style: {
          width: '50%'
        }
      },
      {
        name: 'chart2',
        directive: 'wt-line-chart',
        dataAttrName: 'chart',
        dataSourceType: TimeSeriesDataSource,
        dataSourceOptions: {
          defaultTopic: 'app.visualdata.chartValue2_{type:\'timeseries\',minValue:0,maxValue:100}' //TODO
        },
        style: {
          width: '50%'
        }
      },
      {
        name: 'topics',
        templateUrl: 'template/topics.html'
      },
      {
        name: 'wt-gauge',
        attrs: {
          value: 'gaugeValue'
        },
        dataSource: new DataSource(
          new ValueModel('gaugeValue', $scope, webSocket),
          'app.visualdata.chartValue'
        ),
        style: {
          width: '250px'
        }
      },
      {
        name: 'wt-top-n',
        attrs: {
          data: 'serverTopTen'
        }
      }
    ];

    var defaultWidgets = _.clone(widgetDefinitions);

    $scope.dashboardOptions = {
      widgetButtons: true,
      widgetDefinitions: widgetDefinitions,
      defaultWidgets: defaultWidgets,
      optionsTemplateUrl: 'template/widgetOptions.html'
    };

    //TODO
    $scope.serverValue = 0;
    webSocket.subscribe(settings.randomValueTopic, function (message) {
      $scope.serverValue = message.value;
      $scope.$apply();
    }, $scope);

    webSocket.subscribe(settings.topNTopic, function (message) {
      var list = [];
      _.each(message, function (value, key) {
        list.push({ name: key, value: parseInt(value, 10) });
      }, $scope);

      $scope.serverTopTen = list;
      $scope.$apply();
    }, $scope);

    $scope.chartValue = 0;
    var valueModel = new ValueModel('chartValue', $scope, webSocket);

    var chartModel = new ChartModel('chart', $scope, webSocket);

    var chartModel2 = new ChartModel('chart2', $scope, webSocket);
    chartModel2.update('app.visualdata.chartValue2');

    $scope.$on('topic', function (event, topic) {
      valueModel.update(topic);
      chartModel.update(topic);
    });
  })
  .controller('TopicCtrl', function ($scope, webSocket) {
    webSocket.subscribe('_latestTopics', function (message) {
      var list = _.reject(message, function (topic) {
        return topic.indexOf('applications.') >= 0;
      });
      $scope.topics = _.sortBy(list, function (topic) {
        return topic;
      });
      if (message.length) {
        $scope.topic = $scope.topics[0];
      }
      $scope.$apply();
    }, $scope);
    webSocket.send({ type: 'getLatestTopics' });

    var callback = function (message) {
      $scope.topicData = JSON.stringify(message, null, ' ');
      $scope.$apply();
    };

    $scope.$watch('topic', function (newTopic, oldTopic) {
      if (oldTopic && callback) {
        webSocket.unsubscribe(oldTopic, callback);
      }

      if (newTopic) {
        $scope.topicData = 'Loading...';
        webSocket.subscribe(newTopic, callback, $scope);
        //$scope.$emit('topic', newTopic); //TODO
        //$rootScope.$broadcast('topic', newTopic);
      }
    });
  })
  .controller('WidgetOptionsCtrl', function ($scope, webSocket) {
    var widget = $scope.widget;
    if (widget && widget.dataSource) {
      $scope.topic = widget.dataSource.topic;

      // load available topics
      webSocket.subscribe('_latestTopics', function (message) {
        var list = _.reject(message, function (topic) {
          return topic.indexOf('applications.') >= 0;
        });
        $scope.topics = _.sortBy(list, function (topic) {
          return topic;
        });

        //TODO unsubscribe webSocket.get(request).then(...);

        $scope.$apply();
      }, $scope);
      webSocket.send({ type: 'getLatestTopics' });

      $scope.$watch('topic', function (newTopic) {
        if (newTopic && (newTopic !== widget.dataSource.topic)) {
          widget.dataSource.update(newTopic);
        }
      });
    }
  });<|endoftext|>


<commit_before>'use strict';

/**
 * @ngdoc service
 * @name Configuration
 * @description
 *  Configuration object for the app.
 */
angular.module('searchApp')
  .constant('Configuration', {
      "production":               "https://solr.esrc.unimelb.edu.au",
      "testing":                  "https://data.esrc.info/solr",
      "deployment":               "production",
      "site":                     "ESRC",
      "searchType":               "keyword",
      "searchTypeKeywordUnion":   "AND",
      "datasetStart":             "1600-01-01T00:00:00Z",
      "datasetEnd":               "2014-12-31T23:59:59Z",

      "searchFields": {
          "name":        { "fieldName": "name",           "displayName": "Entity Name",           "weight": "100" },
          "altname":     { "fieldName": "altname",        "displayName": "Entity Alternate Name", "weight": "50" },
          "locality":    { "fieldName": "locality",       "displayName": "Locality",              "weight": "30" },
          "text":        { "fieldName": "text",           "displayName": "Entity Content",        "weight": "10" },
          "description": { "fieldName": "description",    "displayName": "Resource Content",      "weight": "1" }
      },

      "facetWidgets": [
          { "facetField": "site_name",  "label": "Site",            "join": "OR" },
          //{ "facetField": "type",       "label": "Entity Type",     "join": "OR" },
          { "facetField": "function",   "label": "Entity Function", "join": "AND" },
          //{ "facetField": "repository", "label": "Repository",      "join": "OR" },
          //{ "facetField": "tag",        "label": "Tag",             "join": "AND" }
      ],

      "dateFacetWidgets": [
          //{ "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "1",
          //  "label": "Age of Discovery: 1400 - 1699", "start": "1400", "end": "1699", "interval": "50" },

          //{ "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "2",
          //  "label": "Georgian Era: 1700 - 1879", "start": "1700", "end": "1879", "interval": "20" },

          //{ "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "3",
          //  "label": "Machine Age: 1880 - 1939", "start": "1880", "end": "1939", "interval": "10" },

          { "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "4",
            "label": "Atomic Age: 1940 - 1969", "start": "1940", "end": "1969", "interval": "5" },

          { "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "5",
            "label": "Information Age: 1970 - present", "start": "1970", "interval": "5" },
      ]

  });
<commit_msg>enable the other filters<commit_after>'use strict';

/**
 * @ngdoc service
 * @name Configuration
 * @description
 *  Configuration object for the app.
 */
angular.module('searchApp')
  .constant('Configuration', {
      "production":               "https://solr.esrc.unimelb.edu.au",
      "testing":                  "https://data.esrc.info/solr",
      "deployment":               "production",
      "site":                     "ESRC",
      "searchType":               "keyword",
      "searchTypeKeywordUnion":   "AND",
      "datasetStart":             "1600-01-01T00:00:00Z",
      "datasetEnd":               "2014-12-31T23:59:59Z",

      "searchFields": {
          "name":        { "fieldName": "name",           "displayName": "Entity Name",           "weight": "100" },
          "altname":     { "fieldName": "altname",        "displayName": "Entity Alternate Name", "weight": "50" },
          "locality":    { "fieldName": "locality",       "displayName": "Locality",              "weight": "30" },
          "text":        { "fieldName": "text",           "displayName": "Entity Content",        "weight": "10" },
          "description": { "fieldName": "description",    "displayName": "Resource Content",      "weight": "1" }
      },

      "facetWidgets": [
          { "facetField": "site_name",  "label": "Site",            "join": "OR" },
          { "facetField": "type",       "label": "Entity Type",     "join": "OR" },
          { "facetField": "function",   "label": "Entity Function", "join": "AND" },
          { "facetField": "repository", "label": "Repository",      "join": "OR" },
          { "facetField": "tag",        "label": "Tag",             "join": "AND" }
      ],

      "dateFacetWidgets": [
          { "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "1",
            "label": "Age of Discovery: 1400 - 1699", "start": "1400", "end": "1699", "interval": "50" },

          { "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "2",
            "label": "Georgian Era: 1700 - 1879", "start": "1700", "end": "1879", "interval": "20" },

          { "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "3",
            "label": "Machine Age: 1880 - 1939", "start": "1880", "end": "1939", "interval": "10" },

          { "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "4",
            "label": "Atomic Age: 1940 - 1969", "start": "1940", "end": "1969", "interval": "5" },

          { "facetField": "exist_from", "existenceFromField": "exist_from", "existenceToField": "exist_to", "id": "5",
            "label": "Information Age: 1970 - present", "start": "1970", "interval": "5" },
      ]

  });
<|endoftext|>


<commit_before>var TAPPED_OUT_HOSTNAME = "tappedout.net";
var EDHREC_API_URL = "http://edhrec.com/rec";
var API_REF = "kevin";
var LAND_TYPE = "Land";
var CREATURE_TYPE = "Creature";
var ARTIFACT_TYPE = "Artifact";
var ENCHANTMENT_TYPE = "Enchantment";
var INSTANT_TYPE = "Instant";
var SORCERY_TYPE = "Sorcery";
var PLANESWALKER_TYPE = "Planeswalker";
var MAX_TOP_RECOMMENDATIONS = 12;
var MAX_RECOMMENDATIONS_PER_TYPE = 15;

app.service("recommendationService", function($http, $q) {
  this.getRecommendations = function(deckUrl) {
    var deferred = $q.defer();
    if (!this.isValidDeckUrl_(deckUrl)) {
      deferred.reject("Invalid deck URL.");
      return deferred.promise;
    }

    var url = EDHREC_API_URL + "?to=" + deckUrl + "&ref=" + API_REF;
    $http.get(url).then($.proxy(function(result) {
      ga("send", "event", "search", "success", deckUrl);
      deferred.resolve(this.parseResponse_(result.data));
    }, this), function(error) {
      ga("send", "event", "search", "error", error.status, 1);
      var message = "Error generating recommendations. Status code: " + error.status;
      if (error.status == 500) {
        message += ". Please verify your deck link is correct and that your deck isn't marked as private.";
      }
      deferred.reject(message);
    });

    return deferred.promise;
  };

  this.isValidDeckUrl_ = function(deckUrl) {
    var parser = document.createElement("a");
    parser.href = deckUrl;
    return parser.hostname === TAPPED_OUT_HOSTNAME;
  };

  this.parseResponse_ = function(data) {
    var recommendations = {
      top: [],
      creatures: [],
      artifacts: [],
      enchantments: [],
      instants: [],
      sorceries: [],
      planeswalkers: [],
      lands: [],
      cuts: data.cuts
    }

    for (var i = 0; i < data.recs.length; i++) {
      var card = data.recs[i];
      var land = this.isType_(card, LAND_TYPE);

      if (recommendations.top.length < MAX_TOP_RECOMMENDATIONS && !land) {
        recommendations.top.push(card);
      } else {
        if (land) {
          recommendations.lands.push(card);
        } else if (this.isType_(card, CREATURE_TYPE)) {
          recommendations.creatures.push(card);
        } else if (this.isType_(card, ARTIFACT_TYPE)) {
          recommendations.artifacts.push(card);
        } else if (this.isType_(card, ENCHANTMENT_TYPE)) {
          recommendations.enchantments.push(card);
        } else if (this.isType_(card, INSTANT_TYPE)) {
          recommendations.instants.push(card);
        } else if (this.isType_(card, SORCERY_TYPE)) {
          recommendations.sorceries.push(card);
        } else if (this.isType_(card, PLANESWALKER_TYPE)) {
          recommendations.planeswalkers.push(card);
        }
      }
    }

    recommendations.creatures = recommendations.creatures.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.artifacts = recommendations.artifacts.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.enchantments = recommendations.enchantments.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.instants = recommendations.instants.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.sorceries = recommendations.sorceries.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.planeswalkers = recommendations.planeswalkers.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.lands = recommendations.lands.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.cuts = recommendations.cuts.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    return recommendations;
  }

  this.isType_ = function(card, type) {
    return $.inArray(type, card.card_info.types) > -1;
  }
});
<commit_msg>Make success a count<commit_after>var TAPPED_OUT_HOSTNAME = "tappedout.net";
var EDHREC_API_URL = "http://edhrec.com/rec";
var API_REF = "kevin";
var LAND_TYPE = "Land";
var CREATURE_TYPE = "Creature";
var ARTIFACT_TYPE = "Artifact";
var ENCHANTMENT_TYPE = "Enchantment";
var INSTANT_TYPE = "Instant";
var SORCERY_TYPE = "Sorcery";
var PLANESWALKER_TYPE = "Planeswalker";
var MAX_TOP_RECOMMENDATIONS = 12;
var MAX_RECOMMENDATIONS_PER_TYPE = 15;

app.service("recommendationService", function($http, $q) {
  this.getRecommendations = function(deckUrl) {
    var deferred = $q.defer();
    if (!this.isValidDeckUrl_(deckUrl)) {
      deferred.reject("Invalid deck URL.");
      return deferred.promise;
    }

    var url = EDHREC_API_URL + "?to=" + deckUrl + "&ref=" + API_REF;
    $http.get(url).then($.proxy(function(result) {
      ga("send", "event", "search", "success", null, 1);
      deferred.resolve(this.parseResponse_(result.data));
    }, this), function(error) {
      ga("send", "event", "search", "error", error.status, 1);
      var message = "Error generating recommendations. Status code: " + error.status;
      if (error.status == 500) {
        message += ". Please verify your deck link is correct and that your deck isn't marked as private.";
      }
      deferred.reject(message);
    });

    return deferred.promise;
  };

  this.isValidDeckUrl_ = function(deckUrl) {
    var parser = document.createElement("a");
    parser.href = deckUrl;
    return parser.hostname === TAPPED_OUT_HOSTNAME;
  };

  this.parseResponse_ = function(data) {
    var recommendations = {
      top: [],
      creatures: [],
      artifacts: [],
      enchantments: [],
      instants: [],
      sorceries: [],
      planeswalkers: [],
      lands: [],
      cuts: data.cuts
    }

    for (var i = 0; i < data.recs.length; i++) {
      var card = data.recs[i];
      var land = this.isType_(card, LAND_TYPE);

      if (recommendations.top.length < MAX_TOP_RECOMMENDATIONS && !land) {
        recommendations.top.push(card);
      } else {
        if (land) {
          recommendations.lands.push(card);
        } else if (this.isType_(card, CREATURE_TYPE)) {
          recommendations.creatures.push(card);
        } else if (this.isType_(card, ARTIFACT_TYPE)) {
          recommendations.artifacts.push(card);
        } else if (this.isType_(card, ENCHANTMENT_TYPE)) {
          recommendations.enchantments.push(card);
        } else if (this.isType_(card, INSTANT_TYPE)) {
          recommendations.instants.push(card);
        } else if (this.isType_(card, SORCERY_TYPE)) {
          recommendations.sorceries.push(card);
        } else if (this.isType_(card, PLANESWALKER_TYPE)) {
          recommendations.planeswalkers.push(card);
        }
      }
    }

    recommendations.creatures = recommendations.creatures.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.artifacts = recommendations.artifacts.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.enchantments = recommendations.enchantments.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.instants = recommendations.instants.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.sorceries = recommendations.sorceries.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.planeswalkers = recommendations.planeswalkers.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.lands = recommendations.lands.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    recommendations.cuts = recommendations.cuts.slice(0, MAX_RECOMMENDATIONS_PER_TYPE);
    return recommendations;
  }

  this.isType_ = function(card, type) {
    return $.inArray(type, card.card_info.types) > -1;
  }
});
<|endoftext|>


<commit_before>/*
"URL-safe" Base64 Codec, by Jacob Rus

This library happily strips off as many trailing '=' as are included in the
input to 'decode', and doesn't worry whether its length is an even multiple
of 4. It does not include trailing '=' in its own output. It uses the
'URL safe' base64 alphabet, where the last two characters are '-' and '_'.

--------------------

Copyright (c) 2009 Jacob Rus

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 alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
	trailingPad = '=',
	padChar = alphabet.charAt(alphabet.length - 1);

var decodeMap = {};
for (var i = 0, len = alphabet.length; i < len; i++) {
	decodeMap[alphabet.charAt(i)] = i;
}

// use this regexp in the decode function to sniff out invalid characters.
var alphabet_inverse = new RegExp('[^' + alphabet.replace('-', '\\-') + ']');

exports.Base64CodecError = Class(Error, function(supr) {
	this.name = 'Base64CodecError';

	this.init = function(message) {
		supr(this, 'init', arguments);
		this.message = message;
	}
});

var assertOrBadInput = function (exp, message) {
	if (!exp) { throw new exports.Base64CodecError(message) };
};

exports.encode = function (bytes) {
	assertOrBadInput(!(/[^\x00-\xFF]/.test(bytes)), // disallow two-byte chars
		'Input contains out-of-range characters.');
	var padding = '\x00\x00\x00'.slice((bytes.length % 3) || 3);
	bytes += padding; // pad with null bytes
	var out_array = [];
	for (var i=0, n=bytes.length; i < n; i+=3) {
		var newchars = (
			(bytes.charCodeAt(i)   << 020) +
			(bytes.charCodeAt(i+1) << 010) +
			(bytes.charCodeAt(i+2)));
		out_array.push(
			alphabet.charAt((newchars >> 18) & 077),
			alphabet.charAt((newchars >> 12) & 077),
			alphabet.charAt((newchars >> 6)  & 077),
			alphabet.charAt((newchars)	   & 077));
	};

	out_array.length -= padding.length;
	return out_array.join('');
};

exports.decode = function (b64text) {
	logger.debug('decode', b64text);
	b64text = b64text.replace(/\s/g, ''); // kill whitespace

	// strip trailing pad characters from input; // XXX maybe some better way?
	var i = b64text.length;
	while (b64text.charAt(--i) === trailingPad) {};
	b64text = b64text.slice(0, i + 1);

	assertOrBadInput(!alphabet_inverse.test(b64text), 'Input contains out-of-range characters.');

	var padLength = 4 - ((b64text.length % 4) || 4),
		padding = Array(padLength + 1).join(padChar);

	b64text += padding; // pad with last letter of alphabet

	var out_array = [],
		length = i + padLength + 1; // length of b64text

	for (var i = 0; i < length; i += 4) {
		newchars = (
			(decodeMap[b64text.charAt(i)]   << 18) +
			(decodeMap[b64text.charAt(i+1)] << 12) +
			(decodeMap[b64text.charAt(i+2)] << 6)  +
			(decodeMap[b64text.charAt(i+3)]));
		out_array.push(
			(newchars >> 020) & 0xFF,
			(newchars >> 010) & 0xFF,
			(newchars)		& 0xFF);
	};

	length = (out_array.length -= padLength);

	// Safari fromCharCode can't be passed more than 65536 arguments at once
	var result,
		MAX_CHUNK = 65536;

	if (length > MAX_CHUNK) {
		result = [];
		var i = 0, j = 0;
		while (i < length) {
			result[j++] = String.fromCharCode.apply(String, out_array.slice(i, i + MAX_CHUNK));
			i += MAX_CHUNK;
		}
		result = result.join('');
	} else {
		result = String.fromCharCode.apply(String, out_array);
	}
	logger.debug('decoded', result);
	return result;
};
<commit_msg>add padding optionally to base64 encoded strings --@mgh (reviewed by @mcav)<commit_after>/*
"URL-safe" Base64 Codec, by Jacob Rus

This library happily strips off as many trailing '=' as are included in the
input to 'decode', and doesn't worry whether its length is an even multiple
of 4. It does not include trailing '=' in its own output. It uses the
'URL safe' base64 alphabet, where the last two characters are '-' and '_'.

--------------------

Copyright (c) 2009 Jacob Rus

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 alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',
	trailingPad = '=',
	padChar = alphabet.charAt(alphabet.length - 1);

var decodeMap = {};
for (var i = 0, len = alphabet.length; i < len; i++) {
	decodeMap[alphabet.charAt(i)] = i;
}

// use this regexp in the decode function to sniff out invalid characters.
var alphabet_inverse = new RegExp('[^' + alphabet.replace('-', '\\-') + ']');

exports.Base64CodecError = Class(Error, function(supr) {
	this.name = 'Base64CodecError';

	this.init = function(message) {
		supr(this, 'init', arguments);
		this.message = message;
	}
});

var assertOrBadInput = function (exp, message) {
	if (!exp) { throw new exports.Base64CodecError(message) };
};

exports.encode = function (bytes, addPadding) {
	assertOrBadInput(!(/[^\x00-\xFF]/.test(bytes)), // disallow two-byte chars
		'Input contains out-of-range characters.');
	var paddingSize = bytes.length % 3;
	var padding = '\x00\x00\x00'.slice(paddingSize || 3);
	bytes += padding; // pad with null bytes
	var out_array = [];
	for (var i=0, n=bytes.length; i < n; i+=3) {
		var newchars = (
			(bytes.charCodeAt(i)   << 020) +
			(bytes.charCodeAt(i+1) << 010) +
			(bytes.charCodeAt(i+2)));
		out_array.push(
			alphabet.charAt((newchars >> 18) & 077),
			alphabet.charAt((newchars >> 12) & 077),
			alphabet.charAt((newchars >> 6)  & 077),
			alphabet.charAt((newchars)	   & 077));
	};

	out_array.length -= padding.length;
	var ret = out_array.join('');
	if (addPadding) {
		ret += "===".slice(0, paddingSize);
	}

	return ret;
};

exports.decode = function (b64text) {
	logger.debug('decode', b64text);
	b64text = b64text.replace(/\s/g, ''); // kill whitespace

	// strip trailing pad characters from input; // XXX maybe some better way?
	var i = b64text.length;
	while (b64text.charAt(--i) === trailingPad) {};
	b64text = b64text.slice(0, i + 1);

	assertOrBadInput(!alphabet_inverse.test(b64text), 'Input contains out-of-range characters.');

	var padLength = 4 - ((b64text.length % 4) || 4),
		padding = Array(padLength + 1).join(padChar);

	b64text += padding; // pad with last letter of alphabet

	var out_array = [],
		length = i + padLength + 1; // length of b64text

	for (var i = 0; i < length; i += 4) {
		newchars = (
			(decodeMap[b64text.charAt(i)]   << 18) +
			(decodeMap[b64text.charAt(i+1)] << 12) +
			(decodeMap[b64text.charAt(i+2)] << 6)  +
			(decodeMap[b64text.charAt(i+3)]));
		out_array.push(
			(newchars >> 020) & 0xFF,
			(newchars >> 010) & 0xFF,
			(newchars)		& 0xFF);
	};

	length = (out_array.length -= padLength);

	// Safari fromCharCode can't be passed more than 65536 arguments at once
	var result,
		MAX_CHUNK = 65536;

	if (length > MAX_CHUNK) {
		result = [];
		var i = 0, j = 0;
		while (i < length) {
			result[j++] = String.fromCharCode.apply(String, out_array.slice(i, i + MAX_CHUNK));
			i += MAX_CHUNK;
		}
		result = result.join('');
	} else {
		result = String.fromCharCode.apply(String, out_array);
	}
	logger.debug('decoded', result);
	return result;
};
<|endoftext|>


<commit_before>// @flow
import React, { Component } from 'react'
import Router from 'next/router'
import { setAuthInfo, getAuthParams } from '../../utils/auth'
import type { AuthInfo, AuthQueryParams } from '../../utils/auth'

type Props = {
  authInfo: AuthInfo,
}

export default class AuthCallback extends Component<Props> {
  static async getInitialProps(ctx: { query: AuthQueryParams }) {
    return ctx.query ? {
      authInfo: getAuthParams(ctx.query),
    } : {}
  }

  componentDidMount() {
    setAuthInfo(this.props.authInfo)
    Router.replace('/')
  }

  render() {
    return
Loading...

  }
}
<commit_msg>Get auth info from window object on componentDidMount<commit_after>// @flow
import React, { Component } from 'react'
import Router from 'next/router'
import { setAuthInfo, getAuthParams } from '../../utils/auth'
import type { AuthInfo, AuthQueryParams } from '../../utils/auth'

type Props = {}

const getAuthInfoFrom = (queryStrings: String): AuthInfo => {
  // Removing '?' in the head of string.
  const query = queryStrings.slice(1).split('&').reduce((info, queryString) => {
    const keyValue = queryString.split('=')
    return Object.assign(info, { [keyValue[0]]: keyValue[1] })
  }, {})

  return {
    accessToken: query.auth_token,
    clientId: query.client_id,
    uid: query.uid,
  }
}

export default class AuthCallback extends Component<Props> {
  // getInitialProps doesn't work when exported as static html.
  static async getInitialProps(ctx: { query: AuthQueryParams }) {
    return ctx.query ? {
      authInfo: getAuthParams(ctx.query),
    } : {}
  }

  componentDidMount() {
    const authInfo = getAuthInfoFrom(window.location.search)
    setAuthInfo(authInfo)
    Router.replace('/')
  }

  render() {
    return
Loading...

  }
}
<|endoftext|>


<commit_before>"use strict";
const { OpenShiftClientX } = require("@bcgov/pipeline-cli");
const path = require("path");

const util = require("./util");

module.exports = (settings) => {
  const phases = settings.phases;
  const options = settings.options;
  const phase = options.env;
  const changeId = phases[phase].changeId;
  const oc = new OpenShiftClientX(
    Object.assign({ namespace: phases[phase].namespace }, options)
  );

  const templatesLocalBaseUrl = oc.toFileUrl(
    path.resolve(__dirname, "../../openshift")
  );
  var objects = [];

  const dbSecret = util.getSecret(
    oc,
    phases[phase].namespace,
    `${phases[phase].name}-db${phases[phase].suffix}`
  );

  if (!dbSecret) {
    console.log("Adding Db postgresql secret");

    objects.push(
      ...oc.processDeploymentTemplate(
        `${templatesLocalBaseUrl}/secrets/db-postgresql-secrets.yaml`,
        {
          param: {
            NAME: `${phases[phase].name}-db`,
            SUFFIX: phases[phase].suffix,
          },
        }
      )
    );
  }

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/postgresql-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-db`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/api-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-api`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
          ASPNETCORE_ENVIRONMENT: phases[phase].dotnet_env,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/pdf-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-pdf`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/frontend-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-frontend`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          HOST: phases[phase].host,
          ENV: phases[phase].phase,
          ASPNETCORE_ENVIRONMENT: phases[phase].dotnet_env,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/ccw-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-ccw`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
          ASPNETCORE_ENVIRONMENT: phases[phase].dotnet_env,
        },
      }
    )
  );

  oc.applyRecommendedLabels(
    objects,
    phases[phase].name,
    phase,
    `${changeId}`,
    phases[phase].instance
  );
  oc.importImageStreams(
    objects,
    phases[phase].tag,
    phases.build.namespace,
    phases.build.tag
  );
  oc.applyAndDeploy(objects, phases[phase].instance);
};
<commit_msg>DB DC<commit_after>"use strict";
const { OpenShiftClientX } = require("@bcgov/pipeline-cli");
const path = require("path");

const util = require("./utils");

module.exports = (settings) => {
  const phases = settings.phases;
  const options = settings.options;
  const phase = options.env;
  const changeId = phases[phase].changeId;
  const oc = new OpenShiftClientX(
    Object.assign({ namespace: phases[phase].namespace }, options)
  );

  const templatesLocalBaseUrl = oc.toFileUrl(
    path.resolve(__dirname, "../../openshift")
  );
  var objects = [];

  const dbSecret = util.getSecret(
    oc,
    phases[phase].namespace,
    `${phases[phase].name}-db${phases[phase].suffix}`
  );

  if (!dbSecret) {
    console.log("Adding Db postgresql secret");

    objects.push(
      ...oc.processDeploymentTemplate(
        `${templatesLocalBaseUrl}/secrets/db-postgresql-secrets.yaml`,
        {
          param: {
            NAME: `${phases[phase].name}-db`,
            SUFFIX: phases[phase].suffix,
          },
        }
      )
    );
  }

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/postgresql-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-db`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/api-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-api`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
          ASPNETCORE_ENVIRONMENT: phases[phase].dotnet_env,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/pdf-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-pdf`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/frontend-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-frontend`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          HOST: phases[phase].host,
          ENV: phases[phase].phase,
          ASPNETCORE_ENVIRONMENT: phases[phase].dotnet_env,
        },
      }
    )
  );

  objects.push(
    ...oc.processDeploymentTemplate(
      `${templatesLocalBaseUrl}/ccw-deploy-config.yaml`,
      {
        param: {
          NAME: `${phases[phase].name}-ccw`,
          SUFFIX: phases[phase].suffix,
          VERSION: phases[phase].tag,
          ENV: phases[phase].phase,
          ASPNETCORE_ENVIRONMENT: phases[phase].dotnet_env,
        },
      }
    )
  );

  oc.applyRecommendedLabels(
    objects,
    phases[phase].name,
    phase,
    `${changeId}`,
    phases[phase].instance
  );
  oc.importImageStreams(
    objects,
    phases[phase].tag,
    phases.build.namespace,
    phases.build.tag
  );
  oc.applyAndDeploy(objects, phases[phase].instance);
};
<|endoftext|>


<commit_before>/* ************************************************************************
 *
 *    qooxdoo-compiler - node.js based replacement for the Qooxdoo python
 *    toolchain
 *
 *    https://github.com/qooxdoo/qooxdoo-compiler
 *
 *    Copyright:
 *      2011-2017 Zenesis Limited, http://www.zenesis.com
 *
 *    License:
 *      MIT: https://opensource.org/licenses/MIT
 *
 *      This software is provided under the same licensing terms as Qooxdoo,
 *      please see the LICENSE file in the Qooxdoo project's top-level directory
 *      for details.
 *
 *    Authors:
 *      * John Spackman (john.spackman@zenesis.com, @johnspackman)
 *
 * ************************************************************************/

var path = require("path");
require("qooxdoo");
var fs = require("fs");
var async = require("async");
var util = require("../util");

const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);

var log = util.createLog("translation");

/**
 * Reads and writes .po files for translation
 */
module.exports = qx.Class.define("qx.tool.compiler.app.Translation", {
  extend: qx.core.Object,

  /**
   * Constructor
   * @param library {Library}
   * @param locale {String}
   */
  construct: function(library, locale) {
    this.base(arguments);
    this.setLibrary(library);
    if (locale)
      this.setLocale(locale);
    this.__translations = {};
    this.__headers = {};
  },

  properties: {
    /** The library that this translation is for */
    library: {
      nullable: false,
      check: "qx.tool.compiler.app.Library"
    },

    /** The locale */
    locale: {
      init: "en",
      nullable: false,
      check :"String"
    }
  },

  members: {
    __translations: null,
    __headers: null,
    __mtime: 0,

    /**
     * Filename for the .po file
     * @returns {string}
     */
    getPoFilename: function() {
      var library = this.getLibrary();
      return library.getRootDir() + "/" + library.getTranslationPath() + "/" + this.getLocale() + ".po";
    },

    /**
     * Reads the .po file, but only if it has not been loaded or has changed
     *
     * @returns {Promise}|
     */
    checkRead: async function() {
      var t = this;
      if (!this.__mtime)
        return this.read();
      var poFile = this.getPoFilename();
      return new Promise((resolve) => {
          fs.stat(poFile, function (err, stat) {
            if (err)
              return err.code == "ENOENT" ? resolve() : reject(err);
            if (t.__mtime == stat.mtime)
              return resolve();
            return t.read(cb);
          });
        });
    },

    /**
     * Reads the .po file
     */
    read: async function() {
      var t = this;
      if (t.__onRead)
        return t.__onRead;

      return t.__onRead = new Promise((resolve, reject) => {
        t.__translations = {};
        t.__headers = {};
        var poFile = this.getPoFilename();

        fs.stat(poFile, function(err, stat) {
          if (err) {
            if (err.code == "ENOENT")
              return resolve();
            return reject(err);
          }
          t.__mtime = stat.mtime;
          readFile(poFile, { encoding: "utf8" })
            .then((data) => {

              function saveEntry() {
                if (entry) {
                  var key;
                  if (entry.msgctxt)
                    key = entry.msgctxt + ":" + entry.msgid;
                  else
                    key = entry.msgid;
                  t.__translations[key] = entry;
                }
                entry = null;
                lastKey = null;
              }

              function set(key, value, append) {
                var index = null;
                var m = key.match(/^([^[]+)\[([0-9]+)\]$/);
                if (m) {
                  key = m[1];
                  index = parseInt(m[2]);
                  if (entry[key] === undefined)
                    entry[key] = [];
                  if (!append || typeof entry[key][index] !== "string")
                    entry[key][index] = value;
                  else
                    entry[key][index] += value;
                } else if (!append || typeof entry[key] !== "string")
                  entry[key] = value;
                else
                  entry[key] += value;
              }

              var entry = null;
              var lastKey = null;
              data.split('\n').forEach(function (line, lineNo) {
                line = line.trim();
                if (!line)
                  return saveEntry();

                if (!entry)
                  entry = {};

                // Comment?
                var m = line.match(/^#([^ ]?) (.*)$/);
                if (m) {
                  var type = m[1];
                  var comment = m[2];
                  var key;
                  if (!entry.comments)
                    entry.comments = {};
                  switch (type) {
                    case "":
                      entry.comments.translator = comment;
                      break;

                    case ".":
                      entry.comments.extracted = comment;
                      break;

                    case ":":
                      if (!entry.comments.reference) {
                        entry.comments.reference = {};
                      }
                      const ref = entry.comments.reference;
                      comment.match(/[\w/\.]+:\d+/g).forEach(entry => {
                        const split = entry.split(":");
                        const classname = split[0];
                        const lineNo = parseInt(split[1], 10);
                        if (!ref[classname]) {
                          ref[classname] = [lineNo];
                        } else if (!ref[classname].includes(lineNo)) {
                          ref[classname].push(lineNo);
                        }
                      });
                      break;

                    case ",":
                      entry.comments.flags = comment.split(',');
                      break;

                    case "|":
                      m = comment.match(/^([^\s]+)\s+(.*)$/);
                      if (m) {
                        if (!entry.previous)
                          entry.previous = {};
                        var tmp = m[1];
                        if (tmp == "msgctxt" || tmp == "msgid")
                          entry[tmp] = m[2];
                        else
                          log.warn("Cannot interpret line " + (lineNo + 1));
                      } else
                        log.warn("Cannot interpret line " + (lineNo + 1));
                      break;
                  }
                  return;
                }

                if (line[0] == '"' && line[line.length - 1] == '"') {
                  line = line.substring(1, line.length - 1);
                  if (!lastKey.match(/^.*\[\d+\]$/) && (lastKey === null || entry[lastKey] === undefined))
                    log.error("Cannot interpret line because there is no key to append to, line " + (lineNo+1));
                  else
                    set(lastKey, line, true);
                  return;
                }

                // Part of the translation
                if (line == "#")
                  return;
                m = line.match(/^([^\s]+)\s+(.*)$/);
                if (!m) {
                  log.warn("Cannot interpret line " + (lineNo + 1));
                  return;
                }

                var key = lastKey = m[1];
                var value = m[2];
                if (value.length >= 2 && value[0] == '"' && value[value.length - 1] == '"') {
                  value = value.substring(1, value.length - 1);
                  set(key, value);
                }
              });

              resolve();
            });
        });
      });
    },

    /**
     * Writes the .po file
     * @param cb
     */
    write: function(cb) {
      this.writeTo(this.getPoFilename(), cb);
    },

    /**
     * Writes the .po file to a specific filename
     * @param filename {String}
     * @param cb
     */
    writeTo: function(filename, cb) {
      function write(key, value) {
        if (value === undefined || value === null)
          return;
        value = value.replace(/\\n(.)/g, function(a, c) { return "\\n\"\n\"" + c; });
        lines.push(key + " \"" + value + "\"");
      }
      var t = this;
      var lines = [];
      for (var msgid in t.__translations) {
        var entry = t.__translations[msgid];
        if (entry.comments) {
          if (entry.comments.translator)
            lines.push("# " + entry.comments.translator);
          if (entry.comments.extracted)
            lines.push("#. " + entry.comments.extracted);
          if (entry.comments.reference) {
            let refStr = "#:";
            const ref = entry.comments.reference;
            for (let classname in ref) {
              if (ref.hasOwnProperty(classname)) {
                for (let lineNo of ref[classname]) {
                  const addStr = " " + classname + ":" + lineNo;
                  if (refStr.length + addStr.length > 78) {  // 78 is default length in python po library
                    // line break
                    lines.push(refStr);
                    refStr = "#:" + addStr;
                  } else {
                    refStr += addStr;
                  }
                }
              }
            }
            if (refStr.length > 3) {  // write remaining refStr
              lines.push(refStr);
            }
          }
          if (entry.comments.flags)
            lines.push("#, " + entry.comments.flags.join(','));
        } else
          lines.push("#");
        if (entry.msgctxt)
          lines.push("msgctxt \"" + entry.msgctxt + "\"");
        write("msgid", entry.msgid);
        write("msgid_plural", entry.msgid_plural);
        if (qx.lang.Type.isArray(entry.msgstr)) {
          entry.msgstr.forEach(function (value, index) {
            write("msgstr[" + index + "]", value);
          });
        } else if (entry.msgid_plural) {
          write("msgstr[0]", "");
          write("msgstr[1]", "");
        } else {
          write("msgstr", entry.msgstr || "");
        }
        lines.push("");
      }
      var data = lines.join("\n");
      fs.writeFile(filename, data, { encoding: "utf8" }, cb);
    },

    /**
     * Returns the entry with the given msgid, null if it does not exist
     * @param id
     * @returns {*|null}
     */
    getEntry: function(id) {
      var t = this;
      return t.__translations[id]||null;
    },

    /**
     * Returns the entry with the given msgid, creating it if it does not exist
     * @param id
     * @returns {*|null}
     */
    getOrCreateEntry: function(id) {
      var t = this;
      var entry = t.__translations[id];
      if (!entry) {
        entry = t.__translations[id] = {
          msgid: id
        };
      }
      return entry;
    },

    /**
     * Returns all entries
     * @returns {null}
     */
    getEntries: function() {
      return this.__translations;
    },

    /**
     * Returns the translation headers
     * @returns {null}
     */
    getHeaders: function() {
      return this.__headers;
    }

  }
});
<commit_msg>fix for #123: escaping po files<commit_after>/* ************************************************************************
 *
 *    qooxdoo-compiler - node.js based replacement for the Qooxdoo python
 *    toolchain
 *
 *    https://github.com/qooxdoo/qooxdoo-compiler
 *
 *    Copyright:
 *      2011-2017 Zenesis Limited, http://www.zenesis.com
 *
 *    License:
 *      MIT: https://opensource.org/licenses/MIT
 *
 *      This software is provided under the same licensing terms as Qooxdoo,
 *      please see the LICENSE file in the Qooxdoo project's top-level directory
 *      for details.
 *
 *    Authors:
 *      * John Spackman (john.spackman@zenesis.com, @johnspackman)
 *
 * ************************************************************************/

var path = require("path");
require("qooxdoo");
var fs = require("fs");
var async = require("async");
var util = require("../util");

const readFile = util.promisify(fs.readFile);
const writeFile = util.promisify(fs.writeFile);

var log = util.createLog("translation");

/**
 * Reads and writes .po files for translation
 */
module.exports = qx.Class.define("qx.tool.compiler.app.Translation", {
  extend: qx.core.Object,

  /**
   * Constructor
   * @param library {Library}
   * @param locale {String}
   */
  construct: function(library, locale) {
    this.base(arguments);
    this.setLibrary(library);
    if (locale)
      this.setLocale(locale);
    this.__translations = {};
    this.__headers = {};
  },

  properties: {
    /** The library that this translation is for */
    library: {
      nullable: false,
      check: "qx.tool.compiler.app.Library"
    },

    /** The locale */
    locale: {
      init: "en",
      nullable: false,
      check :"String"
    }
  },

  members: {
    __translations: null,
    __headers: null,
    __mtime: 0,

    /**
     * Filename for the .po file
     * @returns {string}
     */
    getPoFilename: function() {
      var library = this.getLibrary();
      return library.getRootDir() + "/" + library.getTranslationPath() + "/" + this.getLocale() + ".po";
    },

    /**
     * Reads the .po file, but only if it has not been loaded or has changed
     *
     * @returns {Promise}|
     */
    checkRead: async function() {
      var t = this;
      if (!this.__mtime)
        return this.read();
      var poFile = this.getPoFilename();
      return new Promise((resolve) => {
          fs.stat(poFile, function (err, stat) {
            if (err)
              return err.code == "ENOENT" ? resolve() : reject(err);
            if (t.__mtime == stat.mtime)
              return resolve();
            return t.read(cb);
          });
        });
    },

    /**
     * Reads the .po file
     */
    read: async function() {
      var t = this;
      if (t.__onRead)
        return t.__onRead;

      return t.__onRead = new Promise((resolve, reject) => {
        t.__translations = {};
        t.__headers = {};
        var poFile = this.getPoFilename();

        fs.stat(poFile, function(err, stat) {
          if (err) {
            if (err.code == "ENOENT")
              return resolve();
            return reject(err);
          }
          t.__mtime = stat.mtime;
          readFile(poFile, { encoding: "utf8" })
            .then((data) => {

              function saveEntry() {
                if (entry) {
                  var key;
                  if (entry.msgctxt)
                    key = entry.msgctxt + ":" + entry.msgid;
                  else
                    key = entry.msgid;
                  t.__translations[key] = entry;
                }
                entry = null;
                lastKey = null;
              }

              function set(key, value, append) {
                var index = null;
                var m = key.match(/^([^[]+)\[([0-9]+)\]$/);
                if (m) {
                  key = m[1];
                  index = parseInt(m[2]);
                  if (entry[key] === undefined)
                    entry[key] = [];
                  if (!append || typeof entry[key][index] !== "string")
                    entry[key][index] = value;
                  else
                    entry[key][index] += value;
                } else if (!append || typeof entry[key] !== "string")
                  entry[key] = value;
                else
                  entry[key] += value;
              }

              var entry = null;
              var lastKey = null;
              data.split('\n').forEach(function (line, lineNo) {
                line = line.trim();
                if (!line)
                  return saveEntry();

                if (!entry)
                  entry = {};

                // Comment?
                var m = line.match(/^#([^ ]?) (.*)$/);
                if (m) {
                  var type = m[1];
                  var comment = m[2];
                  var key;
                  if (!entry.comments)
                    entry.comments = {};
                  switch (type) {
                    case "":
                      entry.comments.translator = comment;
                      break;

                    case ".":
                      entry.comments.extracted = comment;
                      break;

                    case ":":
                      if (!entry.comments.reference) {
                        entry.comments.reference = {};
                      }
                      const ref = entry.comments.reference;
                      comment.match(/[\w/\.]+:\d+/g).forEach(entry => {
                        const split = entry.split(":");
                        const classname = split[0];
                        const lineNo = parseInt(split[1], 10);
                        if (!ref[classname]) {
                          ref[classname] = [lineNo];
                        } else if (!ref[classname].includes(lineNo)) {
                          ref[classname].push(lineNo);
                        }
                      });
                      break;

                    case ",":
                      entry.comments.flags = comment.split(',');
                      break;

                    case "|":
                      m = comment.match(/^([^\s]+)\s+(.*)$/);
                      if (m) {
                        if (!entry.previous)
                          entry.previous = {};
                        var tmp = m[1];
                        if (tmp == "msgctxt" || tmp == "msgid")
                          entry[tmp] = m[2];
                        else
                          log.warn("Cannot interpret line " + (lineNo + 1));
                      } else
                        log.warn("Cannot interpret line " + (lineNo + 1));
                      break;
                  }
                  return;
                }

                if (line[0] == '"' && line[line.length - 1] == '"') {
                  line = line.substring(1, line.length - 1);
                  if (!lastKey.match(/^.*\[\d+\]$/) && (lastKey === null || entry[lastKey] === undefined))
                    log.error("Cannot interpret line because there is no key to append to, line " + (lineNo+1));
                  else
                    set(lastKey, line, true);
                  return;
                }

                // Part of the translation
                if (line == "#")
                  return;
                m = line.match(/^([^\s]+)\s+(.*)$/);
                if (!m) {
                  log.warn("Cannot interpret line " + (lineNo + 1));
                  return;
                }

                var key = lastKey = m[1];
                var value = m[2];
                if (value.length >= 2 && value[0] == '"' && value[value.length - 1] == '"') {
                  value = value.substring(1, value.length - 1);
                  value = value.replace(/\\t/g, "\t").replace(/\\r/g, "\r").replace(/\\n/g, "\n").replace(/\\"/g, '"');
                  set(key, value);
                }
              });

              resolve();
            });
        });
      });
    },

    /**
     * Writes the .po file
     * @param cb
     */
    write: function(cb) {
      this.writeTo(this.getPoFilename(), cb);
    },

    /**
     * Writes the .po file to a specific filename
     * @param filename {String}
     * @param cb
     */
    writeTo: function(filename, cb) {
      function write(key, value) {
        if (value === undefined || value === null)
          return;
        value = value.replace(/\t/g, "\\t").replace(/\r/g, "\\r").replace(/\n/g, "\\n").replace(/"/g, '\\"');
        lines.push(key + " \"" + value + "\"");
      }
      var t = this;
      var lines = [];
      for (var msgid in t.__translations) {
        var entry = t.__translations[msgid];
        if (entry.comments) {
          if (entry.comments.translator)
            lines.push("# " + entry.comments.translator);
          if (entry.comments.extracted)
            lines.push("#. " + entry.comments.extracted);
          if (entry.comments.reference) {
            let refStr = "#:";
            const ref = entry.comments.reference;
            for (let classname in ref) {
              if (ref.hasOwnProperty(classname)) {
                for (let lineNo of ref[classname]) {
                  const addStr = " " + classname + ":" + lineNo;
                  if (refStr.length + addStr.length > 78) {  // 78 is default length in python po library
                    // line break
                    lines.push(refStr);
                    refStr = "#:" + addStr;
                  } else {
                    refStr += addStr;
                  }
                }
              }
            }
            if (refStr.length > 3) {  // write remaining refStr
              lines.push(refStr);
            }
          }
          if (entry.comments.flags)
            lines.push("#, " + entry.comments.flags.join(','));
        } else
          lines.push("#");
        if (entry.msgctxt)
          lines.push("msgctxt \"" + entry.msgctxt + "\"");
        write("msgid", entry.msgid);
        write("msgid_plural", entry.msgid_plural);
        if (qx.lang.Type.isArray(entry.msgstr)) {
          entry.msgstr.forEach(function (value, index) {
            write("msgstr[" + index + "]", value);
          });
        } else if (entry.msgid_plural) {
          write("msgstr[0]", "");
          write("msgstr[1]", "");
        } else {
          write("msgstr", entry.msgstr || "");
        }
        lines.push("");
      }
      var data = lines.join("\n");
      fs.writeFile(filename, data, { encoding: "utf8" }, cb);
    },

    /**
     * Returns the entry with the given msgid, null if it does not exist
     * @param id
     * @returns {*|null}
     */
    getEntry: function(id) {
      var t = this;
      return t.__translations[id]||null;
    },

    /**
     * Returns the entry with the given msgid, creating it if it does not exist
     * @param id
     * @returns {*|null}
     */
    getOrCreateEntry: function(id) {
      var t = this;
      var entry = t.__translations[id];
      if (!entry) {
        entry = t.__translations[id] = {
          msgid: id
        };
      }
      return entry;
    },

    /**
     * Returns all entries
     * @returns {null}
     */
    getEntries: function() {
      return this.__translations;
    },

    /**
     * Returns the translation headers
     * @returns {null}
     */
    getHeaders: function() {
      return this.__headers;
    }

  }
});
<|endoftext|>


<commit_before>var INHERIT = require('inherit');

module.exports = function(json, plugins, pluginsEngine) {

    var engine = new (pluginsEngine || PluginsEngine)();

    json = engine.pass(json, plugins.directPass);
    json = engine.pass(json, plugins.reversePass, true);

    return json;

};

var PluginsEngine = exports.PluginsEngine = INHERIT({

    _makePluginsList: function(arr) {

        return arr.map(function(plugin) {
            plugin.fn = require('../plugins/' + plugin.name)[plugin.name];

            return plugin;
        });

    },

    pass: function(json, plugins, reverse) {

        plugins = this._makePluginsList(plugins);

        function monkeys(data) {

            data.content = data.content.filter(function(item) {

                if (reverse && item.content) {
                    monkeys.call(this, item);
                }

                var filter = true;

                plugins.forEach(function(plugin) {
                    if (plugin.active && plugin.fn(item, plugin.params) === false) {
                        filter = false;
                    }
                });

                if (!reverse && item.content) {
                    monkeys.call(this, item);
                }

                return filter;

            }, this);

            return data;

        };

        return monkeys.call(this, json);

    },

    full: function() {

        this.fullList.forEach(function(plugin) {
            if (plugin.active) {
                json = plugin.fn(json, plugin.params);
            }
        });

        return json;

    }

});

/*
var MyPluginsEngine = INHERIT(PluginsEngine, {

    __constructor: function(options) {
        this.__base();
    }

});
*/
<commit_msg>lib/plugins: main filter function optimization<commit_after>var INHERIT = require('inherit');

module.exports = function(json, plugins, pluginsEngine) {

    var engine = new (pluginsEngine || PluginsEngine)();

    json = engine.pass(json, plugins.directPass);
    json = engine.pass(json, plugins.reversePass, true);

    return json;

};

var PluginsEngine = exports.PluginsEngine = INHERIT({

    _makePluginsList: function(arr) {

        return arr.map(function(plugin) {
            plugin.fn = require('../plugins/' + plugin.name)[plugin.name];

            return plugin;
        });

    },

    pass: function(json, plugins, reverse) {

        plugins = this._makePluginsList(plugins);

        function monkeys(data) {

            data.content = data.content.filter(function(item) {

                if (reverse && item.content) {
                    monkeys.call(this, item);
                }

                var filter = plugins.some(function(plugin) {
                    return plugin.active && plugin.fn(item, plugin.params) === false;
                });

                if (!reverse && item.content) {
                    monkeys.call(this, item);
                }

                return !filter;

            }, this);

            return data;

        };

        return monkeys.call(this, json);

    },

    full: function() {

        this.fullList.forEach(function(plugin) {
            if (plugin.active) {
                json = plugin.fn(json, plugin.params);
            }
        });

        return json;

    }

});

/*
var MyPluginsEngine = INHERIT(PluginsEngine, {

    __constructor: function(options) {
        this.__base();
    }

});
*/
<|endoftext|>