<commit_before>const version = require('child_process').execSync('git describe --always', { cwd: __dirname }).toString().trim();

function tests_buildsystem(path) {
  return [
    `${path}/node/node_modules/@openmicrostep/msbuildsystem.aspects.tests/index.js`,
  ]
}
function tests_aspects(path) {
  return [
    `${path}/js/node_modules/@openmicrostep/aspects.tests/typescript/core/tst/core.spec.js`,
    `${path}/js/node_modules/@openmicrostep/aspects.sql.tests/typescript/datasource.sql/tst/datasource.sql.spec.js`,
    `${path}/js/node_modules/@openmicrostep/aspects.obi.tests/typescript/datasource.obi/tst/datasource.obi.spec.js`,
  ]
}

module.exports =  {
  is: "project",
  name: "Aspects",
  "ts base=": { is: 'component', type: "javascript", compiler: "aspects",
      npmPackage: { is: "component",
        "version": version,
      },
      tsConfig: { is: "component",
        "stripInternal": true,
        "module": "commonjs",
        "target": "es6",
        "declaration": true,
        "sourceMap": true,
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "strictNullChecks": true,
        "skipLibCheck": true,
        "noImplicitThis": true,
        "noImplicitReturns": true,
        "lib": ["es6"]
    }
  },
  "test=": {
    is: 'component',
    components: ["=ts base"],
    tsConfig: { is: "component",
      "types": ["chai"]
    },
    npmPackage: { is: "component",
      dependencies: { is: "component",
        "chai": "^4.1.2"
      },
      devDependencies: { is: "component",
        "@types/chai": "^4.0.4",
        "@openmicrostep/tests": "^0.1.0"
      }
    }
  },
  "node=": {
    is: 'component',
    tsConfig: { is: "component",
      "module": "commonjs",
      "types": ["node"]
    },
    npmPackage: { is: "component",
      devDependencies: { is: "component",
        "@types/node": "^6.0.78"
      }
    },
  },
  "browser=": {
    is: 'component',
    tsConfig: { is: "component",
      "module": "commonjs",
      "lib": ["dom"]
    },
  },
  "envs=": { is: 'group',
    "js=": {
      is: 'environment',
      packager: "npm",
      components: ["=ts base"]
    },
  },
  "Files=": { is: 'group', elements: [
      { is: 'group', name: 'core', path: 'typescript/core/', elements: [
        { is: 'group', name: 'src', path: 'src/', elements: [
          { is: 'file', name: 'core.ts', tags: ['tsc'] },
          { is: 'file', name: 'datasource.interface.md', tags: ['interface'] },
        ]},
        { is: 'group', name: 'tst', path: 'tst/', elements: [
          { is: 'file', name: 'core.spec.ts', tags: ['tsc'] },
          { is: 'file', name: 'resource.interface.md', tags: ['interface'] },
        ]},
      ]},
      { is: 'group', name: 'datasource.sql', path: 'typescript/datasource.sql/', elements: [
        { is: 'group', name: 'src', path: 'src/', elements: [
          { is: 'file', name: 'index.ts', tags: ['tsc'] },
        ]},
        { is: 'group', name: 'tst', path: 'tst/', elements: [
          { is: 'file', name: 'datasource.sql.spec.ts', tags: ['tsc'] },
        ]},
      ]},
      { is: 'group', name: 'datasource.obi', path: 'typescript/datasource.obi/', elements: [
        { is: 'group', name: 'src', path: 'src/', elements: [
          { is: 'file', name: 'index.ts', tags: ['tsc'] },
        ]},
        { is: 'group', name: 'tst', path: 'tst/', elements: [
          { is: 'file', name: 'datasource.obi.spec.ts', tags: ['tsc'] },
        ]},
      ]},
      { is: 'group', name: 'transport.express', path: 'typescript/transport.express/src', elements: [
        { is: 'file', name: 'transport.express.ts', tags: ['tsc'] }
      ]},
      { is: 'group', name: 'transport.xhr', path: 'typescript/transport.xhr/src', elements: [
        { is: 'file', name: 'transport.xhr.ts', tags: ['tsc'] }
      ]},
  ]},
  "typescript targets=": { is: 'group',
    "aspects core=":  {
      is: 'target',
      outputName: "@openmicrostep/aspects",
      environments: ["=envs:js"],
      files: ["=Files:core:src ? tsc"],
      interfaces: [{
        is: "group",
        elements: ["=Files:core:src ? interface"],
        customHeader: `
          import {
            Aspect, ControlCenter, ControlCenterContext,
            VersionedObject, VersionedObjectConstructor,
            Result,
            DataSourceInternal, DataSourceQueries, DataSourceTransaction, DataSourceOptionalTransaction,
            ImmutableList, ImmutableSet, ImmutableObject,
            SafeValidators, EncodedVersionedObjects
          } from '../typescript/core/src/core';
          import ObjectSet = DataSourceInternal.ObjectSet;
          import ResolvedScope = DataSourceInternal.ResolvedScope;
        `
      }],
      npmPackage: { is: "component",
        "main": "typescript/core/src/core.js",
        "typings": "typescript/core/src/core.d.ts",
        "dependencies": { is: "component",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
          "@openmicrostep/async": "^0.1.0",
          "@openmicrostep/mstools": "^1.0.2",
        },
      },
    },
    "aspects core.tests=":  {
      is: 'target',
      outputName: "@openmicrostep/aspects.tests",
      environments: ["=envs:js"],
      files: ["=Files:core:tst ? tsc"],
      targets: ["aspects core"],
      components: ["=test", "=::aspects core::", "=node"],
      interfaces: ["=Files:core:tst ? interface"],
      npmPackage: { is: "component",
        "dependencies": { is: "component",
          "source-map-support": "^0.4.0",
        },
      },
    },
    "aspects express=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.express",
      targets: ["aspects core"],
      components: ["=::aspects core::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:transport.express ? tsc"],
      npmPackage: { is: "component",
        "main": "transport.express.js",
        "typings": "transport.express.d.ts",
        "devDependencies": { is: "component",
          "express": "^4.14.0",
          "@types/express": "^4.0.34",
          "@types/body-parser": "^0.0.33",
          "body-parser": "^1.15.2",
          "@openmicrostep/mstools": "^1.0.2"
        },
      },
    },
    "aspects sql=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.sql",
      targets: ["aspects core"],
      components: ["=::aspects core::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.sql:src ? tsc"],
      npmPackage: { is: "component",
        "main": "index.js",
        "typings": "index.d.ts",
        "dependencies": { is: "component",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects sql.tests=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.sql.tests",
      targets: ["aspects core", "aspects sql"],
      components: ["=test", "=::aspects core::", "=::aspects sql::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.sql:tst ? tsc"],
      interfaces: ["=Files:core:tst ? interface"],
      npmPackage: { is: "component",
        "dependencies": { is: "component",
          "sqlite3": "^3.1.8",
          "mysql2": "^1.2.0",
          "pg": "^6.1.5",
          "tedious": "^2.0.0",
          //"oracledb-pb": "^1.12.3",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects obi=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.obi",
      targets: ["aspects core", "aspects sql"],
      components: ["=::aspects core::", "=::aspects sql::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.obi:src ? tsc"],
      npmPackage: { is: "component",
        "main": "index.js",
        "typings": "index.d.ts",
        "dependencies": { is: "component",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects obi.tests=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.obi.tests",
      targets: ["aspects core", "aspects obi"],
      components: ["=test", "=::aspects core::", "=::aspects sql::", "=::aspects obi::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.obi:tst ? tsc"],
      interfaces: ["=Files:core:tst ? interface"],
      npmPackage: { is: "component",
        "dependencies": { is: "component",
          "sqlite3": "^3.1.8",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects client=": {
      is: 'target',
      packager: "npm",
      outputName: "@openmicrostep/aspects.xhr",
      npmPackage: { is: "component",
        "main": "transport.xhr.js",
        "typings": "transport.xhr.d.ts",
        "devDependencies": { is: "component",
          "@openmicrostep/mstools": "^1.0.2"
        },
      },
      targets: ["aspects core"],
      components: ["=::aspects core::", "=browser"],
      environments: ["=envs:js"],
      files: ["=Files:transport.xhr ? tsc"],
    }
  },
  'commands=': { is: "group",
    "envs=": { is: "group", elements: [
      { is: "environment", name: "gitlab"  , tags: ["ci"   ] },
      { is: "environment", name: "travis"  , tags: ["ci"   , "coveralls"] },
      { is: "environment", name: "appveyor", tags: ["ci"   , "coveralls"] },
      { is: "environment", name: "local"   , tags: ["local"] },
    ]},
    "shell=": {
      is: "component",
      type: "basic",
      manual: true,
      environments: ["=envs"],
    },
    "cmd=": {
      is: "component",
      type: "cmd",
      cwd: "={cwd}.absolutePath",
      tty: true,
      shell: true,
    },
    'cwd=': { is: 'group', elements: [{ is: 'file', name: "./" }] },
    "install-deps=": { is: "task", components: ["=cmd"], cmd: "npm install -g -q coveralls nyc@11.1.0 @openmicrostep/tests" },
    "build-bs=": { is: "task", components: ["=cmd"], cmd: Value([
      "msbuildsystem", "build", "-p", "MSBuildSystem/@msbuildsystem", "-p", "buildsystem", "-w", "dist/bs-aspects/"
    ]) },
    "tests-bs=": { is: "task", components: ["=cmd"], cmd: Value([
      "mstests", "-c", "-t", "20000", ...tests_buildsystem("dist/bs-aspects")
    ]) },
    "build-aspects=": { is: "task", components: ["=cmd"], cmd: Value([
      "node", "dist/bs-aspects/node/node_modules/@openmicrostep/msbuildsystem.cli/index.js", "build", "-w", "dist/aspects/",
      "-p", ".",
      "-p", "typescript/examples/angular2/",
      "--env", "js",
    ]) },
    "tests-aspects=": { is: "task", components: ["=cmd"],
      env: { is: "component", "OCI_LIB_DIR": "/opt/oracle/instantclient", "OCI_INC_DIR": "/opt/oracle/instantclient/sdk/include" },
      cmd: Value(["mstests", "-c", "-t", "20000", ...tests_aspects("dist/aspects")]),
    },

    "coverage-local=": { is: "task", components: ["=cmd"], env: { is: "component", NYC_CWD: "dist/aspects/js/node_modules/@openmicrostep" }, cmd:
      `nyc --reporter=html --report-dir dist/coverage -x "*.tests/**" -x "**/generated/**" mstests -c -t 20000 ${tests_aspects("dist/aspects").join(' ')}`
    },
    "coveralls=": { is: "task", components: ["=cmd"], env: { is: "component", NYC_CWD: "dist/aspects/js/node_modules/@openmicrostep" }, cmd:
      `nyc --reporter=text-lcov --report-dir dist/coverage -x "*.tests/**" -x "**/generated/**" mstests -c -t 20000 ${tests_aspects("dist/aspects").join(' ')} | coveralls`
    },

    "deploy-msbuildsystem.aspects=": { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/bs-aspects/node/node_modules/@openmicrostep/msbuildsystem.aspects"]) },
    "deploy-aspects="              : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects"]) },
    "deploy-aspects.express="      : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects.express"]) },
    "deploy-aspects.sql="          : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects.sql"]) },
    "deploy-aspects.xhr="          : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects.xhr"]) },
    "deploy=": { is: "target", components: ["=shell"], targets: ["build"],
      preTasks: Value(["=deploy-msbuildsystem.aspects", "=deploy-aspects", "=deploy-aspects.express", "=deploy-aspects.sql", "=deploy-aspects.xhr"]) },

    "build=":     { is: "target", components: ["=shell"], preTasksByEnvironment: {
      "=envs ? ci + !coveralls": Value(["=install-deps", "=build-bs", "=tests-bs", "=build-aspects", "=tests-aspects"                   ]),
      "=envs ? ci +  coveralls": Value(["=install-deps", "=build-bs", "=tests-bs", "=build-aspects", "=tests-aspects", "=coveralls"     ]),
      "=envs ? local"          : Value([                 "=build-bs", "=tests-bs", "=build-aspects", "=tests-aspects", "=coverage-local"]),
    } },
  }
};
<commit_msg>project: add obi to deployment<commit_after>const version = require('child_process').execSync('git describe --always', { cwd: __dirname }).toString().trim();

function tests_buildsystem(path) {
  return [
    `${path}/node/node_modules/@openmicrostep/msbuildsystem.aspects.tests/index.js`,
  ]
}
function tests_aspects(path) {
  return [
    `${path}/js/node_modules/@openmicrostep/aspects.tests/typescript/core/tst/core.spec.js`,
    `${path}/js/node_modules/@openmicrostep/aspects.sql.tests/typescript/datasource.sql/tst/datasource.sql.spec.js`,
    `${path}/js/node_modules/@openmicrostep/aspects.obi.tests/typescript/datasource.obi/tst/datasource.obi.spec.js`,
  ]
}

module.exports =  {
  is: "project",
  name: "Aspects",
  "ts base=": { is: 'component', type: "javascript", compiler: "aspects",
      npmPackage: { is: "component",
        "version": version,
      },
      tsConfig: { is: "component",
        "stripInternal": true,
        "module": "commonjs",
        "target": "es6",
        "declaration": true,
        "sourceMap": true,
        "moduleResolution": "node",
        "experimentalDecorators": true,
        "strictNullChecks": true,
        "skipLibCheck": true,
        "noImplicitThis": true,
        "noImplicitReturns": true,
        "lib": ["es6"]
    }
  },
  "test=": {
    is: 'component',
    components: ["=ts base"],
    tsConfig: { is: "component",
      "types": ["chai"]
    },
    npmPackage: { is: "component",
      dependencies: { is: "component",
        "chai": "^4.1.2"
      },
      devDependencies: { is: "component",
        "@types/chai": "^4.0.4",
        "@openmicrostep/tests": "^0.1.0"
      }
    }
  },
  "node=": {
    is: 'component',
    tsConfig: { is: "component",
      "module": "commonjs",
      "types": ["node"]
    },
    npmPackage: { is: "component",
      devDependencies: { is: "component",
        "@types/node": "^6.0.78"
      }
    },
  },
  "browser=": {
    is: 'component',
    tsConfig: { is: "component",
      "module": "commonjs",
      "lib": ["dom"]
    },
  },
  "envs=": { is: 'group',
    "js=": {
      is: 'environment',
      packager: "npm",
      components: ["=ts base"]
    },
  },
  "Files=": { is: 'group', elements: [
      { is: 'group', name: 'core', path: 'typescript/core/', elements: [
        { is: 'group', name: 'src', path: 'src/', elements: [
          { is: 'file', name: 'core.ts', tags: ['tsc'] },
          { is: 'file', name: 'datasource.interface.md', tags: ['interface'] },
        ]},
        { is: 'group', name: 'tst', path: 'tst/', elements: [
          { is: 'file', name: 'core.spec.ts', tags: ['tsc'] },
          { is: 'file', name: 'resource.interface.md', tags: ['interface'] },
        ]},
      ]},
      { is: 'group', name: 'datasource.sql', path: 'typescript/datasource.sql/', elements: [
        { is: 'group', name: 'src', path: 'src/', elements: [
          { is: 'file', name: 'index.ts', tags: ['tsc'] },
        ]},
        { is: 'group', name: 'tst', path: 'tst/', elements: [
          { is: 'file', name: 'datasource.sql.spec.ts', tags: ['tsc'] },
        ]},
      ]},
      { is: 'group', name: 'datasource.obi', path: 'typescript/datasource.obi/', elements: [
        { is: 'group', name: 'src', path: 'src/', elements: [
          { is: 'file', name: 'index.ts', tags: ['tsc'] },
        ]},
        { is: 'group', name: 'tst', path: 'tst/', elements: [
          { is: 'file', name: 'datasource.obi.spec.ts', tags: ['tsc'] },
        ]},
      ]},
      { is: 'group', name: 'transport.express', path: 'typescript/transport.express/src', elements: [
        { is: 'file', name: 'transport.express.ts', tags: ['tsc'] }
      ]},
      { is: 'group', name: 'transport.xhr', path: 'typescript/transport.xhr/src', elements: [
        { is: 'file', name: 'transport.xhr.ts', tags: ['tsc'] }
      ]},
  ]},
  "typescript targets=": { is: 'group',
    "aspects core=":  {
      is: 'target',
      outputName: "@openmicrostep/aspects",
      environments: ["=envs:js"],
      files: ["=Files:core:src ? tsc"],
      interfaces: [{
        is: "group",
        elements: ["=Files:core:src ? interface"],
        customHeader: `
          import {
            Aspect, ControlCenter, ControlCenterContext,
            VersionedObject, VersionedObjectConstructor,
            Result,
            DataSourceInternal, DataSourceQueries, DataSourceTransaction, DataSourceOptionalTransaction,
            ImmutableList, ImmutableSet, ImmutableObject,
            SafeValidators, EncodedVersionedObjects
          } from '../typescript/core/src/core';
          import ObjectSet = DataSourceInternal.ObjectSet;
          import ResolvedScope = DataSourceInternal.ResolvedScope;
        `
      }],
      npmPackage: { is: "component",
        "main": "typescript/core/src/core.js",
        "typings": "typescript/core/src/core.d.ts",
        "dependencies": { is: "component",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
          "@openmicrostep/async": "^0.1.0",
          "@openmicrostep/mstools": "^1.0.2",
        },
      },
    },
    "aspects core.tests=":  {
      is: 'target',
      outputName: "@openmicrostep/aspects.tests",
      environments: ["=envs:js"],
      files: ["=Files:core:tst ? tsc"],
      targets: ["aspects core"],
      components: ["=test", "=::aspects core::", "=node"],
      interfaces: ["=Files:core:tst ? interface"],
      npmPackage: { is: "component",
        "dependencies": { is: "component",
          "source-map-support": "^0.4.0",
        },
      },
    },
    "aspects express=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.express",
      targets: ["aspects core"],
      components: ["=::aspects core::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:transport.express ? tsc"],
      npmPackage: { is: "component",
        "main": "transport.express.js",
        "typings": "transport.express.d.ts",
        "devDependencies": { is: "component",
          "express": "^4.14.0",
          "@types/express": "^4.0.34",
          "@types/body-parser": "^0.0.33",
          "body-parser": "^1.15.2",
          "@openmicrostep/mstools": "^1.0.2"
        },
      },
    },
    "aspects sql=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.sql",
      targets: ["aspects core"],
      components: ["=::aspects core::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.sql:src ? tsc"],
      npmPackage: { is: "component",
        "main": "index.js",
        "typings": "index.d.ts",
        "dependencies": { is: "component",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects sql.tests=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.sql.tests",
      targets: ["aspects core", "aspects sql"],
      components: ["=test", "=::aspects core::", "=::aspects sql::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.sql:tst ? tsc"],
      interfaces: ["=Files:core:tst ? interface"],
      npmPackage: { is: "component",
        "dependencies": { is: "component",
          "sqlite3": "^3.1.8",
          "mysql2": "^1.2.0",
          "pg": "^6.1.5",
          "tedious": "^2.0.0",
          //"oracledb-pb": "^1.12.3",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects obi=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.obi",
      targets: ["aspects core", "aspects sql"],
      components: ["=::aspects core::", "=::aspects sql::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.obi:src ? tsc"],
      npmPackage: { is: "component",
        "main": "index.js",
        "typings": "index.d.ts",
        "dependencies": { is: "component",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects obi.tests=": {
      is: 'target',
      outputName: "@openmicrostep/aspects.obi.tests",
      targets: ["aspects core", "aspects obi"],
      components: ["=test", "=::aspects core::", "=::aspects sql::", "=::aspects obi::", "=node"],
      environments: ["=envs:js"],
      files: ["=Files:datasource.obi:tst ? tsc"],
      interfaces: ["=Files:core:tst ? interface"],
      npmPackage: { is: "component",
        "dependencies": { is: "component",
          "sqlite3": "^3.1.8",
          "@openmicrostep/msbuildsystem.shared": "^0.6.3",
        },
      },
    },
    "aspects client=": {
      is: 'target',
      packager: "npm",
      outputName: "@openmicrostep/aspects.xhr",
      npmPackage: { is: "component",
        "main": "transport.xhr.js",
        "typings": "transport.xhr.d.ts",
        "devDependencies": { is: "component",
          "@openmicrostep/mstools": "^1.0.2"
        },
      },
      targets: ["aspects core"],
      components: ["=::aspects core::", "=browser"],
      environments: ["=envs:js"],
      files: ["=Files:transport.xhr ? tsc"],
    }
  },
  'commands=': { is: "group",
    "envs=": { is: "group", elements: [
      { is: "environment", name: "gitlab"  , tags: ["ci"   ] },
      { is: "environment", name: "travis"  , tags: ["ci"   , "coveralls"] },
      { is: "environment", name: "appveyor", tags: ["ci"   , "coveralls"] },
      { is: "environment", name: "local"   , tags: ["local"] },
    ]},
    "shell=": {
      is: "component",
      type: "basic",
      manual: true,
      environments: ["=envs"],
    },
    "cmd=": {
      is: "component",
      type: "cmd",
      cwd: "={cwd}.absolutePath",
      tty: true,
      shell: true,
    },
    'cwd=': { is: 'group', elements: [{ is: 'file', name: "./" }] },
    "install-deps=": { is: "task", components: ["=cmd"], cmd: "npm install -g -q coveralls nyc@11.1.0 @openmicrostep/tests" },
    "build-bs=": { is: "task", components: ["=cmd"], cmd: Value([
      "msbuildsystem", "build", "-p", "MSBuildSystem/@msbuildsystem", "-p", "buildsystem", "-w", "dist/bs-aspects/"
    ]) },
    "tests-bs=": { is: "task", components: ["=cmd"], cmd: Value([
      "mstests", "-c", "-t", "20000", ...tests_buildsystem("dist/bs-aspects")
    ]) },
    "build-aspects=": { is: "task", components: ["=cmd"], cmd: Value([
      "node", "dist/bs-aspects/node/node_modules/@openmicrostep/msbuildsystem.cli/index.js", "build", "-w", "dist/aspects/",
      "-p", ".",
      "-p", "typescript/examples/angular2/",
      "--env", "js",
    ]) },
    "tests-aspects=": { is: "task", components: ["=cmd"],
      env: { is: "component", "OCI_LIB_DIR": "/opt/oracle/instantclient", "OCI_INC_DIR": "/opt/oracle/instantclient/sdk/include" },
      cmd: Value(["mstests", "-c", "-t", "20000", ...tests_aspects("dist/aspects")]),
    },

    "coverage-local=": { is: "task", components: ["=cmd"], env: { is: "component", NYC_CWD: "dist/aspects/js/node_modules/@openmicrostep" }, cmd:
      `nyc --reporter=html --report-dir dist/coverage -x "*.tests/**" -x "**/generated/**" mstests -c -t 20000 ${tests_aspects("dist/aspects").join(' ')}`
    },
    "coveralls=": { is: "task", components: ["=cmd"], env: { is: "component", NYC_CWD: "dist/aspects/js/node_modules/@openmicrostep" }, cmd:
      `nyc --reporter=text-lcov --report-dir dist/coverage -x "*.tests/**" -x "**/generated/**" mstests -c -t 20000 ${tests_aspects("dist/aspects").join(' ')} | coveralls`
    },

    "deploy-msbuildsystem.aspects=": { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/bs-aspects/node/node_modules/@openmicrostep/msbuildsystem.aspects"]) },
    "deploy-aspects="              : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects"]) },
    "deploy-aspects.express="      : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects.express"]) },
    "deploy-aspects.sql="          : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects.sql"]) },
    "deploy-aspects.obi="          : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects.obi"]) },
    "deploy-aspects.xhr="          : { is: "task", components: ["=cmd"], cmd: Value(["npm", "publish", "dist/aspects/js/node_modules/@openmicrostep/aspects.xhr"]) },
    "deploy=": { is: "target", components: ["=shell"], targets: ["build"],
      preTasks: Value(["=deploy-msbuildsystem.aspects", "=deploy-aspects", "=deploy-aspects.express", "=deploy-aspects.sql", "=deploy-aspects.obi", "=deploy-aspects.xhr"]) },

    "build=":     { is: "target", components: ["=shell"], preTasksByEnvironment: {
      "=envs ? ci + !coveralls": Value(["=install-deps", "=build-bs", "=tests-bs", "=build-aspects", "=tests-aspects"                   ]),
      "=envs ? ci +  coveralls": Value(["=install-deps", "=build-bs", "=tests-bs", "=build-aspects", "=tests-aspects", "=coveralls"     ]),
      "=envs ? local"          : Value([                 "=build-bs", "=tests-bs", "=build-aspects", "=tests-aspects", "=coverage-local"]),
    } },
  }
};
<|endoftext|>


<commit_before>module.exports =  {
  is: "project",
  name: "Repository",
  workspace: "logitud.repository",
  "files=": { is: 'group', elements: [
      { is: 'group', name: 'app', path: 'app/src/', elements: [
        { is: 'file', name: 'main.ts', tags: ['tsc'] },
        { is: 'file', name: 'index.html', tags: ['copy'] },
        { is: 'file', name: 'styles.css', tags: ['copy'] },
        { is: 'file', name: 'systemjs.config.js', tags: ['copy'] },
        { is: 'file', name: 'images/*.png', tags: ['copy'] },
      ]},
      { is: 'group', name: 'server', path: 'server/src/', elements: [
        { is: 'file', name: 'server.ts', tags: ['tsc']},
      ]},
      { is: 'group', name: 'shared', path: 'shared/src/', elements: [
        { is: 'file', name: 'interfaces.md', tags: ['interface']},
      ]},
      { is: 'group', name: 'xnet', path: 'xnet/src/', elements: [
        { is: 'file', name: 'plist.js', tags: ['copy'] },
        { is: 'file', name: 'villes.plist', tags: ['copy'] },
      ]},
  ]},
  "targets=": { is: 'group',
    "repository app=":  {
      is: 'target',
      environments: ["=::openms.aspects.angular::"],
      files: ["=files:app ? tsc", "=files:shared ? tsc"],
      copyFiles: [{ is: "group", elements: ["=files:app ? copy"], dest: "", expand: true }],
      interfaces: [{ is: "group", elements: ['=files:shared ? interface'] }],
      npmPackage: { is: "component",
        dependencies: { is: "component",
          "@openmicrostep/async": "^0.1.1",
        },
      },
    },
    "repository server=":  {
      is: 'target',
      environments: ["=::openms.aspects.node::"],
      files: ["=files:server ? tsc", "=files:shared ? tsc"],
      copyFiles: [{ is: "group", elements: ["=files:xnet ? copy"], dest: "xnet/src", expand: true }],
      interfaces: [{ is: "group", elements: ['=files:shared ? interface'] }],
      npmPackage: { is: "component",
        dependencies: { is: "component",
          "sqlite3": "^3.1.8",
          "pg": "^7.3.0",
          "mongodb": "^2.2.31",
          "request": "^2.83.0",
          "request-promise-native": "^1.0.5",
          "express-session": "^1.15.6",
          "connect-mongo": "^1.3.2",
          "ldapjs": "^1.0.1",
        },
        devDependencies: { is: "component",
          "@types/ldapjs": "^1.0.0",
          "@types/express-session": "^1.15.3",
        },
      },
    }
  }
};
<commit_msg>fix make.js<commit_after>module.exports =  {
  is: "project",
  name: "Repository",
  workspace: "logitud.repository",
  "files=": { is: 'group', elements: [
      { is: 'group', name: 'app', path: 'app/src/', elements: [
        { is: 'file', name: 'main.ts', tags: ['tsc'] },
        { is: 'file', name: 'index.html', tags: ['copy'] },
        { is: 'file', name: 'styles.css', tags: ['copy'] },
        { is: 'file', name: 'systemjs.config.js', tags: ['copy'] },
        { is: 'file', name: 'images/*.png', tags: ['copy'] },
      ]},
      { is: 'group', name: 'server', path: 'server/src/', elements: [
        { is: 'file', name: 'server.ts', tags: ['tsc']},
      ]},
      { is: 'group', name: 'shared', path: 'shared/src/', elements: [
        { is: 'file', name: 'interfaces.md', tags: ['interface']},
      ]},
  ]},
  "targets=": { is: 'group',
    "repository app=":  {
      is: 'target',
      environments: ["=::openms.aspects.angular::"],
      files: ["=files:app ? tsc", "=files:shared ? tsc"],
      copyFiles: [{ is: "group", elements: ["=files:app ? copy"], dest: "", expand: true }],
      interfaces: [{ is: "group", elements: ['=files:shared ? interface'] }],
      npmPackage: { is: "component",
        dependencies: { is: "component",
          "@openmicrostep/async": "^0.1.1",
        },
      },
    },
    "repository server=":  {
      is: 'target',
      environments: ["=::openms.aspects.node::"],
      files: ["=files:server ? tsc", "=files:shared ? tsc"],
      interfaces: [{ is: "group", elements: ['=files:shared ? interface'] }],
      npmPackage: { is: "component",
        dependencies: { is: "component",
          "sqlite3": "^3.1.8",
          "pg": "^7.3.0",
          "mongodb": "^2.2.31",
          "request": "^2.83.0",
          "request-promise-native": "^1.0.5",
          "express-session": "^1.15.6",
          "connect-mongo": "^1.3.2",
          "ldapjs": "^1.0.1",
        },
        devDependencies: { is: "component",
          "@types/ldapjs": "^1.0.0",
          "@types/express-session": "^1.15.3",
          "@types/request-promise-native": "^1.0.8",
        },
      },
    }
  }
};
<|endoftext|>


<commit_before>var config = require('./config');

var Maki = require('./lib/Maki');
var maki = new Maki( config );

var Sessions = require('maki-sessions');
var sessions = new Sessions({
  resource: 'Person'
});
maki.use( sessions );

maki.define('Person', {
  attributes: {
    username: { type: String , max: 80 , required: true , slug: true },
    hash:     { type: String , restricted: true },
    salt:     { type: String , restricted: true },
    email:    { type: String , max: 80 , restricted: true },
    created:  { type: Date , default: Date.now }
  },
  icon: 'user'
});

maki.define('Example', {
  attributes: {
    name:    { type: String , max: 80 },
    slug:    { type: String , max: 80 , id: true },
    content: { type: String },
    screenshot: { type: 'File' }
  },
  source: 'data/examples.json',
  icon: 'idea'
});

maki.define('Release', {
  attributes: {
    name: { type: String , max: 80 },
    tag: { type: String , max: 80 },
    created: { type: Date },
    published: { type: Date },
    notes: { type: String , render: 'markdown' }
  },
  source: 'https://api.github.com/repos/martindale/maki/releases',
  icon: 'tags',
  map: function( release ) {
    return {
      name: release.name,
      tag: release.tag_name,
      notes: release.body,
      published: new Date( release.published_at )
    };
  }
});

var Analytics = require('maki-analytics');
var analytics = new Analytics({ id: 'UA-57746323-2' });

maki.use( analytics ).serve(['http']).start();
<commit_msg>disable analytics<commit_after>var config = require('./config');

var Maki = require('./lib/Maki');
var maki = new Maki( config );

var Sessions = require('maki-sessions');
var sessions = new Sessions({
  resource: 'Person'
});
maki.use( sessions );

maki.define('Person', {
  attributes: {
    username: { type: String , max: 80 , required: true , slug: true },
    hash:     { type: String , restricted: true },
    salt:     { type: String , restricted: true },
    email:    { type: String , max: 80 , restricted: true },
    created:  { type: Date , default: Date.now }
  },
  icon: 'user'
});

maki.define('Example', {
  attributes: {
    name:    { type: String , max: 80 },
    slug:    { type: String , max: 80 , id: true },
    content: { type: String },
    screenshot: { type: 'File' }
  },
  source: 'data/examples.json',
  icon: 'idea'
});

maki.define('Release', {
  attributes: {
    name: { type: String , max: 80 },
    tag: { type: String , max: 80 },
    created: { type: Date },
    published: { type: Date },
    notes: { type: String , render: 'markdown' }
  },
  source: 'https://api.github.com/repos/martindale/maki/releases',
  icon: 'tags',
  map: function( release ) {
    return {
      name: release.name,
      tag: release.tag_name,
      notes: release.body,
      published: new Date( release.published_at )
    };
  }
});

/*var Analytics = require('maki-analytics');
var analytics = new Analytics({ id: 'UA-57746323-2' });

maki.use( analytics ).serve(['http']).start();*/
maki.serve(['http']).start();
<|endoftext|>


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

var fs = require('fs');
var spawn = require('child_process').spawn;
var colors = require('colors');
var eol = require('os').EOL;
var optimist = require('optimist')
    .alias('e', 'edit')
    .describe('e', 'Edit command\'s mann page.')
    .usage('Usage:' + eol + '  mann <command>' + eol + '  mann -e <command>');

var mannDir = getUserHome() + '/.mann';
fs.mkdir(mannDir, function() {});

if (!optimist.argv.e) {
  if (optimist.argv._.length == 0) {
    console.log(optimist.help());
    return;
  }

  optimist.argv._.forEach(function(command) {
    var mannFile = mannDir + '/' + command + '.md';

    if (!fs.existsSync(mannFile)) {
      console.error('No mann page exists for ' + command);
      console.error('Type \'mann -e ' + command + '\' to add a mann page for it.');
      return;
    }

    var mann = fs.readFileSync(mannFile).toString();
    mann = mann.replace(/^(# *.*)$/gm, '$1'.green);
    mann = mann.replace(/^(\n|\r|\r\n)+/, '').replace(/(\n|\r|\r\n)+$/, '');

    console.log(mann);
  });
}
else {
  var command = argv.e;

  if (typeof command != 'string') {
    console.log(optimist.help());
    return;
  }

  var mannFile = mannDir + '/' + command + '.md';
  launchEditor(mannFile);
}

function launchEditor(file) {
  var editor = process.env.EDITOR;

  if (!editor) {
    console.error('No editor found. Please set the EDITOR environment variable.');
    return;
  }

  var editorArgs = editor.split(' ');
  var editorExecutable = editorArgs.shift();

  spawn(editorExecutable, editorArgs.concat([file]), {stdio: 'inherit'})
  .on('error', function() {
    console.error('Failed to launch the editor. Make sure the EDITOR environment variable is correctly set.');
  });
}

function getUserHome() {
  return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
<commit_msg>Added -a support.<commit_after>#!/usr/bin/env node

var fs = require('fs');
var spawn = require('child_process').spawn;
var colors = require('colors');
var eol = require('os').EOL;
var optimist = require('optimist')
    .alias('e', 'edit')
    .alias('a', 'add')
    .describe('e', 'Edit command\'s mann page.')
    .describe('a', 'Add line to command\'s mann page.')
    .usage('Usage:' + eol + '  mann <command>' + eol + '  mann -e <command>' + eol + '  mann -a <command> <line>');

var mannDir = getUserHome() + '/.mann';
fs.mkdir(mannDir, function() {});

if (optimist.argv.e) {
  var command = optimist.argv.e;

  if (typeof command != 'string') {
    console.log(optimist.help());
    return;
  }

  var mannFile = mannDir + '/' + command + '.md';
  launchEditor(mannFile);
}
else if (optimist.argv.a) {
  var command = optimist.argv.a;

  if (typeof command != 'string') {
    console.log(optimist.help());
    return;
  }

  var line = optimist.argv._.join(' ');

  if (!line) {
    console.log(optimist.help());
    return;
  }

  var mann = '';
  var mannFile = mannDir + '/' + command + '.md';

  if (fs.existsSync(mannFile))
    mann = fs.readFileSync(mannFile).toString();

  mann = mann + eol + line;
  fs.writeFileSync(mannFile, mann);
}
else {
  if (optimist.argv._.length == 0) {
    console.log(optimist.help());
    return;
  }

  optimist.argv._.forEach(function(command) {
    var mannFile = mannDir + '/' + command + '.md';

    if (!fs.existsSync(mannFile)) {
      console.error('No mann page exists for ' + command);
      console.error('Type \'mann -e ' + command + '\' to add a mann page for it.');
      return;
    }

    var mann = fs.readFileSync(mannFile).toString();
    mann = mann.replace(/^(# *.*)$/gm, '$1'.green);
    mann = mann.replace(/^(\n|\r|\r\n)+/, '').replace(/(\n|\r|\r\n)+$/, '');

    console.log(mann);
  });
}

function launchEditor(file) {
  var editor = process.env.EDITOR;

  if (!editor) {
    console.error('No editor found. Please set the EDITOR environment variable.');
    return;
  }

  var editorArgs = editor.split(' ');
  var editorExecutable = editorArgs.shift();

  spawn(editorExecutable, editorArgs.concat([file]), {stdio: 'inherit'})
  .on('error', function() {
    console.error('Failed to launch the editor. Make sure the EDITOR environment variable is correctly set.');
  });
}

function getUserHome() {
  return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
<|endoftext|>


<commit_before>// Add outerHtml to jQuery
jQuery.fn.outerHTML = function(s) {
	return s
	? this.before(s).remove()
	: jQuery("<p>").append(this.eq(0).clone()).html();
};

// Build mast objects and set defaults
Mast = _.extend(Backbone,
{

	// Route map that will be populated by user definitions
	routes: {},

	// Model/collection dictionary that will be populated by user definitions
	models: {},

	// Cache of models and collections, by cid
	modelCache: {},

	// Component dictionary that will be populated by user definitions
	components: {},

	// Detect mobile viewports (looks at the user agent string)
	isMobile: navigator.userAgent.match(/(iPhone|iPod|Android|BlackBerry)/),

	// Register models, collections, components, and trees and manage dependencies/inheritance
	registerEntities: function () {

		var infinityCounter = 0;
		while(Mast._registerQueue.length > 0) {
			_.each(Mast._registerQueue,function(v,i) {
				v.definition = v.definition || {};								// Support undefined definition
				var entitySet =													// Determine entity set (i.e. Mast.components, Mast.models)
					( v.type == 'tree' || v.type == 'component') ?
					Mast.components : Mast.models;
				var parent = (v.definition.extendsFrom) ?						// Determine parent
					entitySet[v.definition.extendsFrom] :
					Mast[_.str.capitalize(v.type)];
				if (parent) {
					var newEntity = parent.extend(v.definition);				// Extend parent
					newEntity.prototype.events =								// Extend events hash as well
					_.extend({},parent.prototype.events,
						newEntity.prototype.events);
					entitySet[v.name] = newEntity;								// Register new instance in entity set
					Mast._registerQueue.splice(i,1);
				}
				else {
					infinityCounter++;
					if (infinityCounter > 1000) {
						debug.warn('Parent does not seem to be registered',
							v.definition.extendsFrom,"in:",entitySet
						);
						throw new Error("Could find parent, "+v.definition.extendsFrom+"!");
					}
				}
			});
		}
	},

	// Mast.raise() instantiates the Mast library with the specified options
	raise: function (options,afterLoadFn,beforeRouteFn) {

		$(function(){
			options = _.defaults(options || {},{								// Extend defaults
				socket			: true,
				afterLoadFn		: afterLoadFn,
				beforeRouteFn	: beforeRouteFn
			});

			Mast.registerEntities();											// Register Mast.entities and enable inheritance

			// Convert options.routes into a format Backbone's router will accept
			// (can't have key:function(){} style routes, must use a string function name)
			var routerConfig = {
				routes:{}
			};
			var indexRoute = null;

			// If external router is specified in options, use it
			if (options.router) {
				Mast.routes = options.router;
			}

			// Decorate and interpret routes
			_.each(Mast.routes,function(action,query) {
				// "routes" is a reserved word
				if (query=="routes") throw new Error("Can't define a route using reserved word: '"+query+"'!");

				// Save index route for the end
				if (query=="index") {
					indexRoute = action;
				}
				routerConfig.routes[query] = query;
				routerConfig[query] = action;
			});

			// Define default (index) route
			routerConfig.routes[""] = "index";
			routerConfig.index = indexRoute;

			// Prepare template library
			// HTML templates can be manually assigned here
			// otherwise they can be loaded from DOM elements
			// or from a URL
			Mast.TemplateLibrary = {}

			// Initialize Socket
			// Override default base URL if one was specified
			if (Mast.Socket && options.socket) {
				Mast.Socket.baseurl = (options && options.baseurl) || Mast.Socket.baseurl;
				Mast.Socket.initialize();
			}

			// Before routing, trigger beforeRouteFn callback (if specified)
			options.beforeRouteFn && options.beforeRouteFn();

			// Extend and instantiate main router
			var AppRouter = Mast.Router.extend(routerConfig);

			var self = this;
			_.defer(function(){
				Mast.app = new AppRouter();

				// Mast makes the assumption that you want to trigger
				// the route handler.  This can be overridden
				Mast.navigate = function(query,options) {
					return Mast.app.navigate(query,_.extend({
						trigger:true
					},options));
				}

				// TODO: Go ahead and absorb all of the templates in the library
				// right from the get-go

				// Set up template settings
				_.templateSettings = {
					//				variable: 'data',
					interpolate : /\{\{(.+?)\}\}/g,
					escape : /\{\{-(.+?)\}\}/g,
					evaluate : /\{\%(.+?)\%\}/g
				};

				// when document is ready
				$(function(){

					// Launch history manager
					Mast.history.start();

					// When Mast and $.document are ready,
					// trigger afterLoad callback (if specified)
					options.afterLoadFn && _.defer(options.afterLoadFn);
				});
			});
		});
	}
},
Backbone.Events);

// Accepts:
// - Mast object
// - string referencing object name
Mast._provisionPrototype= function (identity, identitySet) {

	if (identity && _.isObject(identity) && _.isFunction(identity)) {			// A Mast entity definition
		return identity;
	}
	else if (_.isString(identity)) {
		if (! (identitySet[identity])) {										// A string component name
			throw new Error("No entity with that name ("+identity+") exists!");
		}
		identity = identitySet[identity];
	}
	else {																		// Any other definition is invalid
		throw new Error ("Invalid identity provided: " + identity);
	}
	return identity;
}

Mast.Model = Mast.Model.extend({
	initialize: function() {
		_.bindAll(this);

		Mast.modelCache[this.cid] = this;
		// TODO: Make model cache smarter (instead of cids, use id+class name)
		//
		// Trigger init event
		_.result(this,'init');
	}
})

Mast.Collection = Mast.Collection.extend({
	initialize: function() {
		_.bindAll(this);

		Mast.modelCache[this.cid] = this;

		// handle string model definitions to maintain parity with Mast.Component
		// and allow for dependencies to exist between files
		this.model = this.model && Mast._provisionPrototype(this.model,Mast.models);

		// Trigger init event
		_.result(this,'init');
	}
});<commit_msg>Cleaned up Mast.app from namespace (renamed to Mast.appRouter.<commit_after>// Add outerHtml to jQuery
jQuery.fn.outerHTML = function(s) {
	return s
	? this.before(s).remove()
	: jQuery("<p>").append(this.eq(0).clone()).html();
};

// Build mast objects and set defaults
Mast = _.extend(Backbone,
{

	// Route map that will be populated by user definitions
	routes: {},

	// Model/collection dictionary that will be populated by user definitions
	models: {},

	// Cache of models and collections, by cid
	modelCache: {},

	// Component dictionary that will be populated by user definitions
	components: {},

	// Detect mobile viewports (looks at the user agent string)
	isMobile: navigator.userAgent.match(/(iPhone|iPod|Android|BlackBerry)/),

	// Register models, collections, components, and trees and manage dependencies/inheritance
	registerEntities: function () {

		var infinityCounter = 0;
		while(Mast._registerQueue.length > 0) {
			_.each(Mast._registerQueue,function(v,i) {
				v.definition = v.definition || {};								// Support undefined definition
				var entitySet =													// Determine entity set (i.e. Mast.components, Mast.models)
					( v.type == 'tree' || v.type == 'component') ?
					Mast.components : Mast.models;
				var parent = (v.definition.extendsFrom) ?						// Determine parent
					entitySet[v.definition.extendsFrom] :
					Mast[_.str.capitalize(v.type)];
				if (parent) {
					var newEntity = parent.extend(v.definition);				// Extend parent
					newEntity.prototype.events =								// Extend events hash as well
					_.extend({},parent.prototype.events,
						newEntity.prototype.events);
					entitySet[v.name] = newEntity;								// Register new instance in entity set
					Mast._registerQueue.splice(i,1);
				}
				else {
					infinityCounter++;
					if (infinityCounter > 1000) {
						debug.warn('Parent does not seem to be registered',
							v.definition.extendsFrom,"in:",entitySet
						);
						throw new Error("Could find parent, "+v.definition.extendsFrom+"!");
					}
				}
			});
		}
	},

	// Mast.raise() instantiates the Mast library with the specified options
	raise: function (options,afterLoadFn,beforeRouteFn) {

		$(function(){
			options = _.defaults(options || {},{								// Extend defaults
				socket			: true,
				afterLoadFn		: afterLoadFn,
				beforeRouteFn	: beforeRouteFn
			});

			Mast.registerEntities();											// Register Mast.entities and enable inheritance

			// Convert options.routes into a format Backbone's router will accept
			// (can't have key:function(){} style routes, must use a string function name)
			var routerConfig = {
				routes:{}
			};
			var indexRoute = null;

			// If external router is specified in options, use it
			if (options.router) {
				Mast.routes = options.router;
			}

			// Decorate and interpret routes
			_.each(Mast.routes,function(action,query) {
				// "routes" is a reserved word
				if (query=="routes") throw new Error("Can't define a route using reserved word: '"+query+"'!");

				// Save index route for the end
				if (query=="index") {
					indexRoute = action;
				}
				routerConfig.routes[query] = query;
				routerConfig[query] = action;
			});

			// Define default (index) route
			routerConfig.routes[""] = "index";
			routerConfig.index = indexRoute;

			// Prepare template library
			// HTML templates can be manually assigned here
			// otherwise they can be loaded from DOM elements
			// or from a URL
			Mast.TemplateLibrary = {}

			// Initialize Socket
			// Override default base URL if one was specified
			if (Mast.Socket && options.socket) {
				Mast.Socket.baseurl = (options && options.baseurl) || Mast.Socket.baseurl;
				Mast.Socket.initialize();
			}

			// Before routing, trigger beforeRouteFn callback (if specified)
			options.beforeRouteFn && options.beforeRouteFn();

			// Extend and instantiate main router
			var AppRouter = Mast.Router.extend(routerConfig);

			var self = this;
			_.defer(function(){
				Mast.appRouter = new AppRouter();

				// Mast makes the assumption that you want to trigger
				// the route handler.  This can be overridden
				Mast.navigate = function(query,options) {
					return Mast.appRouter.navigate(query,_.extend({
						trigger:true
					},options));
				}

				// TODO: Go ahead and absorb all of the templates in the library
				// right from the get-go

				// Set up template settings
				_.templateSettings = {
					//				variable: 'data',
					interpolate : /\{\{(.+?)\}\}/g,
					escape : /\{\{-(.+?)\}\}/g,
					evaluate : /\{\%(.+?)\%\}/g
				};

				// when document is ready
				$(function(){

					// Launch history manager
					Mast.history.start();

					// When Mast and $.document are ready,
					// trigger afterLoad callback (if specified)
					options.afterLoadFn && _.defer(options.afterLoadFn);
				});
			});
		});
	}
},
Backbone.Events);

// Accepts:
// - Mast object
// - string referencing object name
Mast._provisionPrototype= function (identity, identitySet) {

	if (identity && _.isObject(identity) && _.isFunction(identity)) {			// A Mast entity definition
		return identity;
	}
	else if (_.isString(identity)) {
		if (! (identitySet[identity])) {										// A string component name
			throw new Error("No entity with that name ("+identity+") exists!");
		}
		identity = identitySet[identity];
	}
	else {																		// Any other definition is invalid
		throw new Error ("Invalid identity provided: " + identity);
	}
	return identity;
}

Mast.Model = Mast.Model.extend({
	initialize: function() {
		_.bindAll(this);

		Mast.modelCache[this.cid] = this;
		// TODO: Make model cache smarter (instead of cids, use id+class name)
		//
		// Trigger init event
		_.result(this,'init');
	}
})

Mast.Collection = Mast.Collection.extend({
	initialize: function() {
		_.bindAll(this);

		Mast.modelCache[this.cid] = this;

		// handle string model definitions to maintain parity with Mast.Component
		// and allow for dependencies to exist between files
		this.model = this.model && Mast._provisionPrototype(this.model,Mast.models);

		// Trigger init event
		_.result(this,'init');
	}
});<|endoftext|>


<commit_before>//be used to create a menu.html

var fs = require("fs");

var base = "./src/";
var files = fs.readdirSync(base);

var html = fs.readFileSync("./menu.html").toString();
var ul_html = '\n
';
files.forEach(function(f){
    var npath = base + f;
    var array;

    if(fs.lstatSync(npath).isDirectory()){
        array = findHtml(npath);

        if(array.length > 0){
            ul_html += '\n
' + f + '
\n
\n';

            array.forEach(function(p){
                var title = /<title>(.*)<\/title>/.test(fs.readFileSync(p[0]).toString()) ? RegExp.$1 : "Document";
                ul_html += '
' + title + '(' + p[1] + ')
\n';
            });

            ul_html += '
\n';
        }
    }
});
ul_html += "
\n";
html = html.replace(/()[\s\S]*?(<\/body>)/ , "$1"+ul_html+"$2");
fs.writeFileSync("./menu.html" , html);

function findHtml(folder_path , collector){
    collector = collector || [];

    folder_path += "/";
    var files = fs.readdirSync(folder_path);

    files.forEach(function(f){
        var npath = folder_path + f;

        if(fs.lstatSync(npath).isDirectory()){
            findHtml(npath , collector);
            return;
        }

        if(/\.html$/.test(f)){
            collector.push([npath , f]);
        }
    });

    return collector;
}<commit_msg>update<commit_after>//be used to create a menu.html

var fs = require("fs");

var base = "./src/";
var files = fs.readdirSync(base);

var html = fs.readFileSync("./menu.html").toString();
var ul_html = '\n
';
files.forEach(function(f){
    var npath = base + f;
    var array;

    if(fs.lstatSync(npath).isDirectory()){
        array = findHtml(npath);

        if(array.length > 0){
            ul_html += '\n
' + f + '
\n
\n';

            array.forEach(function(p){
                var title = /<title>(.*)<\/title>/.test(fs.readFileSync(p[0]).toString()) ? RegExp.$1 : "Document";
                ul_html += '
' + title + '(' + p[1] + ')
\n';
            });

            ul_html += '
\n';
        }
    }
});
ul_html += "
\n";
html = html.replace(/()[\s\S]*?(<\/body>)/ , "$1"+ul_html+"$2");
fs.writeFileSync("./menu.html" , html);

function findHtml(folder_path , collector){
    collector = collector || [];

    folder_path += "/";
    var files = fs.readdirSync(folder_path);

    files.forEach(function(f){
        var npath = folder_path + f;

        if(fs.lstatSync(npath).isDirectory()){
            findHtml(npath , collector);
            return;
        }

        if(/\.html$/.test(f)){
            collector.push([npath , f]);
        }
    });

    return collector;
}<|endoftext|>


<commit_before>const os = require('os')
const githubAccountDefault = os.userInfo().username

module.exports = {
  schema: {},
  prompts: {
    name: {
      type: 'string',
      required: true,
      message: 'Plugin name'
    },
    description: {
      type: 'string',
      required: false,
      message: 'Plugin description',
      default: 'A Vue.js Plugin'
    },
    version: {
      type: 'string',
      required: false,
      message: 'Initial version',
      default: '0.0.0'
    },
    author: {
      type: 'string',
      message: 'Author'
    },
    githubAccount: {
      type: 'string',
      required: false,
      message: 'GitHub Account',
      default: githubAccountDefault
    }
  },
  filters: {
    ".eslintrc.js": "lint",
    ".eslintignore": "lint",
    "config/test.env.js": "unit || e2e",
    "test/unit/**/*": "unit",
    "build/webpack.test.conf.js": "unit",
    "test/e2e/**/*": "e2e",
    "src/router/**/*": "router"
  },
  helpers: {
    nowYear: function () {
      return new Date().getFullYear()
    },
    authorFullNameFrom: function (author) {
      const startPosition = author.indexOf('<')
      return author.slice(0, startPosition - 1)
    },
    authorEmailFrom: function (author) {
      const startPosition = author.indexOf('<')
      const endPosition = author.indexOf('>')
      return author.slice(startPosition + 1, endPosition)
    }
  }
}<commit_msg>Add filters<commit_after>const os = require('os')
const githubAccountDefault = os.userInfo().username

module.exports = {
  schema: {},
  prompts: {
    name: {
      type: 'string',
      required: true,
      message: 'Plugin name'
    },
    description: {
      type: 'string',
      required: false,
      message: 'Plugin description',
      default: 'A Vue.js Plugin'
    },
    version: {
      type: 'string',
      required: false,
      message: 'Initial version',
      default: '0.0.0'
    },
    author: {
      type: 'string',
      message: 'Author'
    },
    githubAccount: {
      type: 'string',
      required: false,
      message: 'GitHub Account',
      default: githubAccountDefault
    }
  },
  filters: {
    "test/unit/**/*": "unit",
    "test/e2e/**/*": "e2e"
  },
  helpers: {
    nowYear: function () {
      return new Date().getFullYear()
    },
    authorFullNameFrom: function (author) {
      const startPosition = author.indexOf('<')
      return author.slice(0, startPosition - 1)
    },
    authorEmailFrom: function (author) {
      const startPosition = author.indexOf('<')
      const endPosition = author.indexOf('>')
      return author.slice(startPosition + 1, endPosition)
    }
  }
}<|endoftext|>


<commit_before>
/*
node-debug --web-host 0.0.0.0 --save-live-edit true renderyt.js
http://wmaiz-v-sofa02.dbc.zdf.de:8080/debug?port=5858
apt-get install flashplugin-installer imagemagick openjdk-jre daemon
https://github.com/werty1st/selenium-grid-startup
*/

function RenderWorker()
{
	var initcompleted = false;
	var pool = [];
	var running = false;

	this.add = function add(func)
	{
		pool.push(func);
		console.log("poolsize_add:",pool.length);
		run();
	}

	this.init = function init()
	{
		initcompleted = true;
		run();
	}

	var completed = function completed()
	{
		running = false;
		console.log("next rw");
		console.log("poolsize_com:",pool.length);
		run();
	}

	var run = function run()
	{
		if (running) return;
		if (!initcompleted) return;

		if (pool.length > 0)
		{
			running = true;
			var task = pool.shift();
				task(completed);
		}
	}

}

var gm = require('gm');
//setup environment
var webdriver = require('selenium-webdriver'),
	By = webdriver.By,
    until = webdriver.until,
    firefox = require('selenium-webdriver/firefox');

var runHeadless = require('./headless');

function saveImage(buffer, imagedimensions, posttarget, onCompleted) {

	posttarget(buffer, imagedimensions, onCompleted);
}

function captureScreen(driver, imagedimensions, posttarget, onCompleted) {

	function convertImage(image)
	{
		gm(image, "temp.png")
			.options({imageMagick: true})
			.crop(imagedimensions.width-10, imagedimensions.height, imagedimensions.x, imagedimensions.y)
			.toBuffer('PNG',function (err, buffer) {
				saveImage(buffer, {"width":imagedimensions.width, "height": imagedimensions.height}, posttarget, onCompleted);
			});
			// .write("test.png", function (err) {
			// 	if (!err) console.log('crazytown has arrived');
			// 	console.log("saved to:","test.png");
			//     //saveImage(imagefile, posttarget, onCompleted);
			// })
	}

	driver.takeScreenshot().then(
	    function(image, err) {
	    	var buf = new Buffer(image, 'base64');
	        convertImage(buf);
	        // require('fs').writeFile("temp.png", image, 'base64', function(err) {
	        // });
	    }
	);
}

function pageloaded(driver, posttarget, Timeout, onCompleted){
	clearTimeout(Timeout);
	console.log("session loaded");

	setTimeout(function (){
			var imagedimensions = {};

			var x = driver.wait(function() {

				return driver.findElement(By.id("maincontainer")).then(function(ele) {
					ele.getLocation().then(function(point){
						imagedimensions.x = point.x;
						imagedimensions.y = point.y;

						ele.getSize().then(function(size){
							imagedimensions.width = size.width;
							imagedimensions.height = size.height;
							//take screenshot
							captureScreen(driver, imagedimensions, posttarget, onCompleted);
						})
					});
					return true;

			 	}, function (Err) {
			 		//benachrichtige applogic über den fehler
			 			posttarget(function(){
			 				return Err.message;
			 			},"",onCompleted);
			 			x.cancel();
			 		return true;
			 	});

			}, 7000);

			// var ele = driver.findElement(By.id("maincontainer"));
			// 	ele.getLocation().then(function(point){
			// 		imagedimensions.x = point.x;
			// 		imagedimensions.y = point.y;

			// 		ele.getSize().then(function(size){
			// 			imagedimensions.width = size.width;
			// 			imagedimensions.height = size.height;
			// 			//take screenshot
			// 			captureScreen(imagedimensions, posttarget, onCompleted);
			// 		})
			// 	});
		},3000);
}

function renderRequestTask(driver, url, posttarget, onCompleted){

	console.log("running session",url);

	//todo
	//laufenden process/timeout abfragen wenn vorhandn dann push nach waitingCalls
	//alternativ einen pool aus new firefox.Driver(); //bringt keinen performane vorteil lieber eins nach dem anderen

	//todo fehler einbauen kein default
	//var url = url || 'http://merlin.intern.zdf.de:5984/twr/c0cb0d515756ec82976722085fa7d904257eb5de/rendersource.html';

	var timeout1 = 0;
	driver.get(url);

	var pagestate = driver.executeScript('return document.readyState;')

	timeout1 = setTimeout(function ()
	{
		console.log("session took to much time to load");
	},15000)

	pagestate.then(function(readyState){
		console.log("pagestate",readyState);
		if (readyState === "complete"){
			pageloaded(driver, posttarget, timeout1, onCompleted);
		}
	});
}

var options = {};
var headless = {};
var driver = {};
var rw = {};

	headless.klein = new runHeadless({ display: {width: 350, height: 350, depth: 24}},
	function(err, childProcess, servernum) {
		//xvfb ready
		if(!err){
			console.log("display at:",servernum);
			process.env.DISPLAY = ":" + servernum;
			driver.klein = new firefox.Driver();
			rw.klein = new RenderWorker();
			rw.klein.init();
		} else {
			//error
			throw new Error("X or Selenium not running.");
		}
	});

	headless.gross = runHeadless({ display: {width: 1600, height: 1200, depth: 24}},
	function(err, childProcess, servernum){
		//xvfb ready
		if(!err){
			console.log("display at:",servernum);
			process.env.DISPLAY = ":" + servernum;
			driver.gross = new firefox.Driver();
			rw.gross = new RenderWorker();
			rw.gross.init();
		} else {
			//error
			throw new Error("X or Selenium not running.");
		}
	});

module.exports.renderUrl = function renderUrl(url, posttarget, screensize){

	//console.log("screensize",screensize);

	if(screensize==1){
		//klein
		rw.klein.add(function(onCompleted){
			var _url = url;
			var _posttarget = posttarget;
			renderRequestTask(driver.klein, _url, _posttarget, onCompleted);
		});
	} else if (screensize==2){
		//groß

		rw.gross.add(function(onCompleted){
			var _url = url;
			var _posttarget = posttarget;
			renderRequestTask(driver.gross, _url, _posttarget, onCompleted);
		});
	}

}

<commit_msg>crop18<commit_after>
/*
node-debug --web-host 0.0.0.0 --save-live-edit true renderyt.js
http://wmaiz-v-sofa02.dbc.zdf.de:8080/debug?port=5858
apt-get install flashplugin-installer imagemagick openjdk-jre daemon
https://github.com/werty1st/selenium-grid-startup
*/

function RenderWorker()
{
	var initcompleted = false;
	var pool = [];
	var running = false;

	this.add = function add(func)
	{
		pool.push(func);
		console.log("poolsize_add:",pool.length);
		run();
	}

	this.init = function init()
	{
		initcompleted = true;
		run();
	}

	var completed = function completed()
	{
		running = false;
		console.log("next rw");
		console.log("poolsize_com:",pool.length);
		run();
	}

	var run = function run()
	{
		if (running) return;
		if (!initcompleted) return;

		if (pool.length > 0)
		{
			running = true;
			var task = pool.shift();
				task(completed);
		}
	}

}

var gm = require('gm');
//setup environment
var webdriver = require('selenium-webdriver'),
	By = webdriver.By,
    until = webdriver.until,
    firefox = require('selenium-webdriver/firefox');

var runHeadless = require('./headless');

function saveImage(buffer, imagedimensions, posttarget, onCompleted) {

	posttarget(buffer, imagedimensions, onCompleted);
}

function captureScreen(driver, imagedimensions, posttarget, onCompleted) {

	function convertImage(image)
	{
		gm(image, "temp.png")
			.options({imageMagick: true})
			.crop(imagedimensions.width-18, imagedimensions.height, imagedimensions.x, imagedimensions.y)
			.toBuffer('PNG',function (err, buffer) {
				saveImage(buffer, {"width":imagedimensions.width, "height": imagedimensions.height}, posttarget, onCompleted);
			});
			// .write("test.png", function (err) {
			// 	if (!err) console.log('crazytown has arrived');
			// 	console.log("saved to:","test.png");
			//     //saveImage(imagefile, posttarget, onCompleted);
			// })
	}

	driver.takeScreenshot().then(
	    function(image, err) {
	    	var buf = new Buffer(image, 'base64');
	        convertImage(buf);
	        // require('fs').writeFile("temp.png", image, 'base64', function(err) {
	        // });
	    }
	);
}

function pageloaded(driver, posttarget, Timeout, onCompleted){
	clearTimeout(Timeout);
	console.log("session loaded");

	setTimeout(function (){
			var imagedimensions = {};

			var x = driver.wait(function() {

				return driver.findElement(By.id("maincontainer")).then(function(ele) {
					ele.getLocation().then(function(point){
						imagedimensions.x = point.x;
						imagedimensions.y = point.y;

						ele.getSize().then(function(size){
							imagedimensions.width = size.width;
							imagedimensions.height = size.height;
							//take screenshot
							captureScreen(driver, imagedimensions, posttarget, onCompleted);
						})
					});
					return true;

			 	}, function (Err) {
			 		//benachrichtige applogic über den fehler
			 			posttarget(function(){
			 				return Err.message;
			 			},"",onCompleted);
			 			x.cancel();
			 		return true;
			 	});

			}, 7000);

			// var ele = driver.findElement(By.id("maincontainer"));
			// 	ele.getLocation().then(function(point){
			// 		imagedimensions.x = point.x;
			// 		imagedimensions.y = point.y;

			// 		ele.getSize().then(function(size){
			// 			imagedimensions.width = size.width;
			// 			imagedimensions.height = size.height;
			// 			//take screenshot
			// 			captureScreen(imagedimensions, posttarget, onCompleted);
			// 		})
			// 	});
		},3000);
}

function renderRequestTask(driver, url, posttarget, onCompleted){

	console.log("running session",url);

	//todo
	//laufenden process/timeout abfragen wenn vorhandn dann push nach waitingCalls
	//alternativ einen pool aus new firefox.Driver(); //bringt keinen performane vorteil lieber eins nach dem anderen

	//todo fehler einbauen kein default
	//var url = url || 'http://merlin.intern.zdf.de:5984/twr/c0cb0d515756ec82976722085fa7d904257eb5de/rendersource.html';

	var timeout1 = 0;
	driver.get(url);

	var pagestate = driver.executeScript('return document.readyState;')

	timeout1 = setTimeout(function ()
	{
		console.log("session took to much time to load");
	},15000)

	pagestate.then(function(readyState){
		console.log("pagestate",readyState);
		if (readyState === "complete"){
			pageloaded(driver, posttarget, timeout1, onCompleted);
		}
	});
}

var options = {};
var headless = {};
var driver = {};
var rw = {};

	headless.klein = new runHeadless({ display: {width: 350, height: 350, depth: 24}},
	function(err, childProcess, servernum) {
		//xvfb ready
		if(!err){
			console.log("display at:",servernum);
			process.env.DISPLAY = ":" + servernum;
			driver.klein = new firefox.Driver();
			rw.klein = new RenderWorker();
			rw.klein.init();
		} else {
			//error
			throw new Error("X or Selenium not running.");
		}
	});

	headless.gross = runHeadless({ display: {width: 1600, height: 1200, depth: 24}},
	function(err, childProcess, servernum){
		//xvfb ready
		if(!err){
			console.log("display at:",servernum);
			process.env.DISPLAY = ":" + servernum;
			driver.gross = new firefox.Driver();
			rw.gross = new RenderWorker();
			rw.gross.init();
		} else {
			//error
			throw new Error("X or Selenium not running.");
		}
	});

module.exports.renderUrl = function renderUrl(url, posttarget, screensize){

	//console.log("screensize",screensize);

	if(screensize==1){
		//klein
		rw.klein.add(function(onCompleted){
			var _url = url;
			var _posttarget = posttarget;
			renderRequestTask(driver.klein, _url, _posttarget, onCompleted);
		});
	} else if (screensize==2){
		//groß

		rw.gross.add(function(onCompleted){
			var _url = url;
			var _posttarget = posttarget;
			renderRequestTask(driver.gross, _url, _posttarget, onCompleted);
		});
	}

}

<|endoftext|>


<commit_before>(function () {
    "use strict";

    var argv, express, corser, mongo, url, binaryBodyParser, app;

    argv = require("optimist")
             .options("port", {
                 default: 1337,
                 describe: "Port"
             })
             .options("connection-string", {
                 default: "mongodb://localhost/ming",
                 describe: "MongoDB Connection String for the default deployment."
             })
             .options("enable-proxying", {
                 default: false,
                 describe: "Allow connections to other MongoDB deployments."
             })
             .argv;
    express = require("express");
    corser = require("corser");
    mongo = require("mongodb");
    url = require("url");

    binaryBodyParser = function (req, res, next) {
        var body;
        body = new Buffer(0);
        req.on("data", function (chunk) {
            var buffer;
            buffer = new Buffer(body.length + chunk.length);
            body.copy(buffer);
            chunk.copy(buffer, body.length);
            body = buffer;
        });
        req.on("end", function () {
            req.body = body;
            next();
        });
    };

    app = express();

    app.configure(function () {

     // Handle CORS.
        app.use(corser.create({
            methods: corser.simpleMethods.concat(["DELETE", "PATCH"]),
            requestHeaders: corser.simpleRequestHeaders.concat(["Authorization", "X-Connection-String"]),
            responseHeaders: corser.simpleResponseHeaders.concat(["Location"])
        }));

     // Terminate CORS preflights.
        app.use(function (req, res, next) {
            if (req.method === "OPTIONS") {
                res.send(204);
            } else {
                next();
            }
        });

     // Prepare MongoDB client.
        app.use(function (req, res, next) {
            var connectionString;
            if (argv["enable-proxying"] === true && req.headers.hasOwnProperty("x-connection-string") === true) {
                connectionString = req.headers["x-connection-string"];
            } else {
                connectionString = argv["connection-string"];
            }
            req.connectionString = url.parse(connectionString);
            mongo.MongoClient.connect(connectionString, function (err, db) {
                if (err !== null) {
                    next(err);
                } else {
                    req.db = db;
                    next();
                }
            });
        });

     // Basic auth.
        app.use(function (req, res, next) {
            var basicAuth;
            basicAuth = express.basicAuth(function (username, password, callback) {
                req.db.authenticate(username, password, function (err) {
                    if (err !== null) {
                     // Close database if authentication fails.
                        req.db.close();
                        callback(err, null);
                    } else {
                        callback(null, username);
                    }
                });
            }, "MongoDB");
            basicAuth(req, res, next);
        });

     // Deploy routes.
        app.use(app.router);

     // 404 handler.
        app.use(function (req, res) {
            req.db.close();
            res.send(404, "Not Found");
        });

     // 500 handler.
        app.use(function (err, req, res, next) {
            if (req.hasOwnProperty("db") === true) {
                req.db.close();
            }
            res.send(500, "Internal Server Error");
        });

    });

    app.get("/", function (req, res) {
        req.db.collectionNames({
            namesOnly: true
        }, function (err, collections) {
            var names;
            if (err !== null) {
                next(err);
            } else {
                names = collections.map(function (collection) {
                 // Strip database name.
                    return collection.substring(req.connectionString.pathname.length);
                });
                res.send({
                    collections: names
                });
                req.db.close();
            }
        });
    });

    app.get("/:collection", function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            if (err !== null) {
                next(err);
            } else {
                collection.find().count(function (err, count) {
                    if (err !== null) {
                        next(err);
                    } else {
                        res.send({count: count});
                        req.db.close();
                    }
                });
            }
        });
    });

    app.get("/:prefix.files/:file", function (req, res, next) {
        var prefixParam, fileParam;
        prefixParam = req.params.prefix;
        fileParam = req.params.file;
        req.db.collection(prefixParam + ".files", function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(fileParam);
                 // Get metadata first.
                    collection.findOne({
                        _id: id
                    }, function (err, document) {
                        var grid;
                        if (err !== null) {
                            next(err);
                        } else {
                            if (document === null) {
                             // Route to 404 handler.
                                next();
                            } else {
                                if (req.query.hasOwnProperty("binary") === true && req.query.binary === "true") {
                                    grid = new mongo.Grid(req.db, prefixParam);
                                    grid.get(id, function (err, file) {
                                        var contentType;
                                        if (err !== null) {
                                            next(err);
                                        } else {
                                            if (document.contentType) {
                                                contentType = document.contentType;
                                            } else if (document.filename) {
                                             // Guess file type from file extension.
                                                contentType = document.filename.match(/(\.\w+)$/)[1];
                                            } else {
                                                contentType = "application/octet-stream";
                                            }
                                            res.type(contentType);
                                            res.send(file);
                                            req.db.close();
                                        }
                                    });
                                } else {
                                    res.send(document);
                                    req.db.close();
                                }
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.get("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    collection.findOne({
                        _id: id
                    }, function (err, document) {
                        if (err !== null) {
                            next(err);
                        } else {
                            if (document === null) {
                             // Route to 404 handler.
                                next();
                            } else {
                                res.send(document);
                                req.db.close();
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.get("/:collection/:document/:field", function (req, res, next) {
        var collectionParam, documentParam, fieldParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        fieldParam = req.params.field;
        req.db.collection(collectionParam, function (err, collection) {
            var id, fields;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    fields = {};
                    fields[fieldParam] = 1;
                    collection.findOne({
                        _id: id
                    }, {
                        fields: fields
                    }, function (err, document) {
                        if (err !== null) {
                            next(err);
                        } else {
                            if (document === null || document.hasOwnProperty(fieldParam) === false) {
                             // Route to 404 handler.
                                next();
                            } else {
                                res.send(document[fieldParam]);
                                req.db.close();
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.post("/:collection/query", express.json(), function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            var options;
            if (err !== null) {
                next(err);
            } else {
                options = {};
                if (req.query.limit) {
                    options.limit = req.query.limit;
                }
                if (req.query.skip) {
                    options.skip = req.query.skip;
                }
                if (req.query.sort) {
                    options.sort = req.query.sort;
                }
                collection.find(req.body, options).toArray(function (err, documents) {
                    if (err !== null) {
                        next(err);
                    } else {
                        res.send(documents);
                        req.db.close();
                    }
                });
            }
        });
    });

    app.post("/:prefix.files", binaryBodyParser, function (req, res, next) {
        var prefixParam, contentType, grid;
        prefixParam = req.params.prefix;
        contentType = req.headers["content-type"];
        grid = new mongo.Grid(req.db, prefixParam);
        grid.put(req.body, {
            content_type: contentType
        }, function (err, document) {
            if (err !== null) {
                next(err);
            } else {
                res.location(prefixParam + ".files/" + document._id.toHexString());
                res.send(201, "Created");
                req.db.close();
            }
        });
    });

    app.post("/:collection", express.json(), function (req, res) {
        var collectionParam, payload;
        collectionParam = req.params.collection;
        payload = req.body;
        req.db.collection(collectionParam, function (err, collection) {
            if (err !== null) {
                next(err);
            } else {
                collection.insert(payload, function (err, document) {
                    if (err !== null) {
                        next(err);
                    } else {
                        res.location(collectionParam + "/" + document[0]._id.toHexString());
                        res.send(201, "Created");
                        req.db.close();
                    }
                });
            }
        });
    });

    app.patch("/:collection/:document", express.json(), function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    collection.update({
                        _id: id
                    }, req.body, function (err) {
                        if (err !== null) {
                            next(err);
                        } else {
                            res.send(204, "No Content");
                            req.db.close();
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.delete("/:prefix.files/:file", function (req, res, next) {
        var prefixParam, fileParam, grid, id;
        prefixParam = req.params.prefix;
        fileParam = req.params.file;
        grid = new mongo.Grid(req.db, prefixParam);
        try {
            id = new mongo.ObjectID(fileParam);
            grid.delete(id, function (err, flag) {
                if (err !== null) {
                    next(err);
                } else {
                 // TODO: Detect if file was actually deleted.
                    res.send(200, "OK");
                    req.db.close();
                }
            });
        } catch (e) {
         // Route to 404 handler.
            next();
        }
    });

    app.delete("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    collection.remove({
                        _id: id
                    }, function (err, num) {
                        if (err !== null) {
                            next(err);
                        } else {
                            if (num === 0) {
                             // Route to 404 handler.
                                next();
                            } else {
                                res.send(200, "Deleted");
                                req.db.close();
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.listen(argv.port);

    console.log("Ming is running on port " + argv.port + ", connected to " + argv["connection-string"]);

}());
<commit_msg>Keep connection pool small.<commit_after>(function () {
    "use strict";

    var argv, express, corser, mongo, url, binaryBodyParser, app;

    argv = require("optimist")
             .options("port", {
                 default: 1337,
                 describe: "Port"
             })
             .options("connection-string", {
                 default: "mongodb://localhost/ming",
                 describe: "MongoDB Connection String for the default deployment."
             })
             .options("enable-proxying", {
                 default: false,
                 describe: "Allow connections to other MongoDB deployments."
             })
             .argv;
    express = require("express");
    corser = require("corser");
    mongo = require("mongodb");
    url = require("url");

    binaryBodyParser = function (req, res, next) {
        var body;
        body = new Buffer(0);
        req.on("data", function (chunk) {
            var buffer;
            buffer = new Buffer(body.length + chunk.length);
            body.copy(buffer);
            chunk.copy(buffer, body.length);
            body = buffer;
        });
        req.on("end", function () {
            req.body = body;
            next();
        });
    };

    app = express();

    app.configure(function () {

     // Handle CORS.
        app.use(corser.create({
            methods: corser.simpleMethods.concat(["DELETE", "PATCH"]),
            requestHeaders: corser.simpleRequestHeaders.concat(["Authorization", "X-Connection-String"]),
            responseHeaders: corser.simpleResponseHeaders.concat(["Location"])
        }));

     // Terminate CORS preflights.
        app.use(function (req, res, next) {
            if (req.method === "OPTIONS") {
                res.send(204);
            } else {
                next();
            }
        });

     // Prepare MongoDB client.
        app.use(function (req, res, next) {
            var connectionString;
            if (argv["enable-proxying"] === true && req.headers.hasOwnProperty("x-connection-string") === true) {
                connectionString = req.headers["x-connection-string"];
            } else {
                connectionString = argv["connection-string"];
            }
            connectionString = url.parse(connectionString, true);
         // Keep connection pool small.
            connectionString.query.maxPoolSize = 1;
         // Keep a reference to the connection string for later use.
            req.connectionString = connectionString;
            mongo.MongoClient.connect(url.format(connectionString), function (err, db) {
                if (err !== null) {
                    next(err);
                } else {
                    req.db = db;
                    next();
                }
            });
        });

     // Basic auth.
        app.use(function (req, res, next) {
            var basicAuth;
            basicAuth = express.basicAuth(function (username, password, callback) {
                req.db.authenticate(username, password, function (err) {
                    if (err !== null) {
                     // Close database if authentication fails.
                        req.db.close();
                        callback(err, null);
                    } else {
                        callback(null, username);
                    }
                });
            }, "MongoDB");
            basicAuth(req, res, next);
        });

     // Deploy routes.
        app.use(app.router);

     // 404 handler.
        app.use(function (req, res) {
            req.db.close();
            res.send(404, "Not Found");
        });

     // 500 handler.
        app.use(function (err, req, res, next) {
            if (req.hasOwnProperty("db") === true) {
                req.db.close();
            }
            res.send(500, "Internal Server Error");
        });

    });

    app.get("/", function (req, res) {
        req.db.collectionNames({
            namesOnly: true
        }, function (err, collections) {
            var names;
            if (err !== null) {
                next(err);
            } else {
                names = collections.map(function (collection) {
                 // Strip database name.
                    return collection.substring(req.connectionString.pathname.length);
                });
                res.send({
                    collections: names
                });
                req.db.close();
            }
        });
    });

    app.get("/:collection", function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            if (err !== null) {
                next(err);
            } else {
                collection.find().count(function (err, count) {
                    if (err !== null) {
                        next(err);
                    } else {
                        res.send({count: count});
                        req.db.close();
                    }
                });
            }
        });
    });

    app.get("/:prefix.files/:file", function (req, res, next) {
        var prefixParam, fileParam;
        prefixParam = req.params.prefix;
        fileParam = req.params.file;
        req.db.collection(prefixParam + ".files", function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(fileParam);
                 // Get metadata first.
                    collection.findOne({
                        _id: id
                    }, function (err, document) {
                        var grid;
                        if (err !== null) {
                            next(err);
                        } else {
                            if (document === null) {
                             // Route to 404 handler.
                                next();
                            } else {
                                if (req.query.hasOwnProperty("binary") === true && req.query.binary === "true") {
                                    grid = new mongo.Grid(req.db, prefixParam);
                                    grid.get(id, function (err, file) {
                                        var contentType;
                                        if (err !== null) {
                                            next(err);
                                        } else {
                                            if (document.contentType) {
                                                contentType = document.contentType;
                                            } else if (document.filename) {
                                             // Guess file type from file extension.
                                                contentType = document.filename.match(/(\.\w+)$/)[1];
                                            } else {
                                                contentType = "application/octet-stream";
                                            }
                                            res.type(contentType);
                                            res.send(file);
                                            req.db.close();
                                        }
                                    });
                                } else {
                                    res.send(document);
                                    req.db.close();
                                }
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.get("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    collection.findOne({
                        _id: id
                    }, function (err, document) {
                        if (err !== null) {
                            next(err);
                        } else {
                            if (document === null) {
                             // Route to 404 handler.
                                next();
                            } else {
                                res.send(document);
                                req.db.close();
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.get("/:collection/:document/:field", function (req, res, next) {
        var collectionParam, documentParam, fieldParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        fieldParam = req.params.field;
        req.db.collection(collectionParam, function (err, collection) {
            var id, fields;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    fields = {};
                    fields[fieldParam] = 1;
                    collection.findOne({
                        _id: id
                    }, {
                        fields: fields
                    }, function (err, document) {
                        if (err !== null) {
                            next(err);
                        } else {
                            if (document === null || document.hasOwnProperty(fieldParam) === false) {
                             // Route to 404 handler.
                                next();
                            } else {
                                res.send(document[fieldParam]);
                                req.db.close();
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.post("/:collection/query", express.json(), function (req, res) {
        var collectionParam;
        collectionParam = req.params.collection;
        req.db.collection(collectionParam, function (err, collection) {
            var options;
            if (err !== null) {
                next(err);
            } else {
                options = {};
                if (req.query.limit) {
                    options.limit = req.query.limit;
                }
                if (req.query.skip) {
                    options.skip = req.query.skip;
                }
                if (req.query.sort) {
                    options.sort = req.query.sort;
                }
                collection.find(req.body, options).toArray(function (err, documents) {
                    if (err !== null) {
                        next(err);
                    } else {
                        res.send(documents);
                        req.db.close();
                    }
                });
            }
        });
    });

    app.post("/:prefix.files", binaryBodyParser, function (req, res, next) {
        var prefixParam, contentType, grid;
        prefixParam = req.params.prefix;
        contentType = req.headers["content-type"];
        grid = new mongo.Grid(req.db, prefixParam);
        grid.put(req.body, {
            content_type: contentType
        }, function (err, document) {
            if (err !== null) {
                next(err);
            } else {
                res.location(prefixParam + ".files/" + document._id.toHexString());
                res.send(201, "Created");
                req.db.close();
            }
        });
    });

    app.post("/:collection", express.json(), function (req, res) {
        var collectionParam, payload;
        collectionParam = req.params.collection;
        payload = req.body;
        req.db.collection(collectionParam, function (err, collection) {
            if (err !== null) {
                next(err);
            } else {
                collection.insert(payload, function (err, document) {
                    if (err !== null) {
                        next(err);
                    } else {
                        res.location(collectionParam + "/" + document[0]._id.toHexString());
                        res.send(201, "Created");
                        req.db.close();
                    }
                });
            }
        });
    });

    app.patch("/:collection/:document", express.json(), function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    collection.update({
                        _id: id
                    }, req.body, function (err) {
                        if (err !== null) {
                            next(err);
                        } else {
                            res.send(204, "No Content");
                            req.db.close();
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.delete("/:prefix.files/:file", function (req, res, next) {
        var prefixParam, fileParam, grid, id;
        prefixParam = req.params.prefix;
        fileParam = req.params.file;
        grid = new mongo.Grid(req.db, prefixParam);
        try {
            id = new mongo.ObjectID(fileParam);
            grid.delete(id, function (err, flag) {
                if (err !== null) {
                    next(err);
                } else {
                 // TODO: Detect if file was actually deleted.
                    res.send(200, "OK");
                    req.db.close();
                }
            });
        } catch (e) {
         // Route to 404 handler.
            next();
        }
    });

    app.delete("/:collection/:document", function (req, res, next) {
        var collectionParam, documentParam;
        collectionParam = req.params.collection;
        documentParam = req.params.document;
        req.db.collection(collectionParam, function (err, collection) {
            var id;
            if (err !== null) {
                next(err);
            } else {
                try {
                    id = new mongo.ObjectID(documentParam);
                    collection.remove({
                        _id: id
                    }, function (err, num) {
                        if (err !== null) {
                            next(err);
                        } else {
                            if (num === 0) {
                             // Route to 404 handler.
                                next();
                            } else {
                                res.send(200, "Deleted");
                                req.db.close();
                            }
                        }
                    });
                } catch (e) {
                 // Route to 404 handler.
                    next();
                }
            }
        });
    });

    app.listen(argv.port);

    console.log("Ming is running on port " + argv.port + ", connected to " + argv["connection-string"]);

}());
<|endoftext|>