<commit_before>const nodeExternals = require('webpack-node-externals');
// const resolve = (dir) => require('path').join(__dirname, dir);

module.exports = {
  srcDir: 'app/',
  css: [
    'vuetify/src/stylus/app.styl',
    'assets/main.scss'
  ],
  modules: [
    '@nuxtjs/pwa'
  ],
  render: {
    http2: {
      push: true
    }
  },
  manifest: {
    theme_color: '#691b99',
    start_url: '/about/',
    short_name: 'MillerGeek'
  },
  plugins: [
    '@/plugins/vuetify'
  ],
  /*
  ** Headers of the page
  */
  head: {
    title: 'millergeek.xyz',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Personal Website' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'preload', as: 'font', href: 'https://fonts.googleapis.com/css?family=Merienda+One%7CRubik%7CIstok+Web' }
    ],
  },
  /*
  ** Customize the progress bar color
  */
  loading: false,
  /*
  ** Build configuration
  */
  build: {
    /*
    ** Run ESLint on save
    */
    babel: {
      plugins: [
        ['transform-imports', {
          'vuetify': {
            'transform': 'vuetify/es5/components/${member}',
            'preventFullImport': true
          }
        }]
      ]
    },
    vendor: [
      '@/plugins/vuetify.js'
    ],
    extend (config, { isDev, isClient, isServer }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        });
      }
      if (isServer) {
        config.externals = [
          nodeExternals({
            whitelist: [/^vuetify/]
          })
        ];
      }
      config.module.rules.push({
        test: /\.md$/,
        loader: 'vue-markdown-loader',
        options: {
          wrapper: 'div'
        }
      });
    }
  }
};
<commit_msg>try google font preconnect<commit_after>const nodeExternals = require('webpack-node-externals');
// const resolve = (dir) => require('path').join(__dirname, dir);

module.exports = {
  srcDir: 'app/',
  css: [
    'vuetify/src/stylus/app.styl',
    'assets/main.scss'
  ],
  modules: [
    '@nuxtjs/pwa'
  ],
  render: {
    http2: {
      push: true
    }
  },
  manifest: {
    theme_color: '#691b99',
    start_url: '/about/',
    short_name: 'MillerGeek'
  },
  plugins: [
    '@/plugins/vuetify'
  ],
  /*
  ** Headers of the page
  */
  head: {
    title: 'millergeek.xyz',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: 'Personal Website' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'preconnect', href: 'https://fonts.gstatic.com/', crossorigin: 'crossorigin'},
      { rel: 'preload', as: 'style', href: 'https://fonts.googleapis.com/css?family=Merienda+One%7CRubik%7CIstok+Web' }
    ],
  },
  /*
  ** Customize the progress bar color
  */
  loading: false,
  /*
  ** Build configuration
  */
  build: {
    /*
    ** Run ESLint on save
    */
    babel: {
      plugins: [
        ['transform-imports', {
          'vuetify': {
            'transform': 'vuetify/es5/components/${member}',
            'preventFullImport': true
          }
        }]
      ]
    },
    vendor: [
      '@/plugins/vuetify.js'
    ],
    extend (config, { isDev, isClient, isServer }) {
      if (isDev && isClient) {
        config.module.rules.push({
          enforce: 'pre',
          test: /\.(js|vue)$/,
          loader: 'eslint-loader',
          exclude: /(node_modules)/
        });
      }
      if (isServer) {
        config.externals = [
          nodeExternals({
            whitelist: [/^vuetify/]
          })
        ];
      }
      config.module.rules.push({
        test: /\.md$/,
        loader: 'vue-markdown-loader',
        options: {
          wrapper: 'div'
        }
      });
    }
  }
};
<|endoftext|>


<commit_before>import markdownIt from 'markdown-it';
import mila from 'markdown-it-link-attributes';
import path from 'path';
import dynamicRoutes from './lib/dynamic-routes';

/* eslint-disable-next-line import/no-extraneous-dependencies */
require('dotenv').config();

export default {
  mode: 'universal',

  env: {
    perPage: process.env.PER_PAGE || 8,
  },

  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' },
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato:700&display=swap' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Mate+SC&display=swap' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons&display=swap' },
    ],
  },

  loading: { color: '#2bb0ed' },

  css: [
  ],

  plugins: [
    '~/plugins/axios.js',
    '~/plugins/cloudinary.client.js',
    '~/plugins/vuejs-paginate.client.js',
    '~/plugins/vuelidate.js',
  ],

  buildModules: [
    '@nuxtjs/dotenv',
    '@nuxtjs/tailwindcss',
  ],

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/toast',
  ],

  toast: {
    position: 'bottom-right',
    singleton: true,
    iconPack: 'material',
  },

  purgeCSS: {
    whitelist: [
      'blockquote',
      'ul',
      'ol',
      'li',
      'markdown',
      'mt-6',
      'mb-6',
      'my-6',
      'md:mt-8',
      'md:mb-8',
      'md:my-8',
    ],
  },

  build: {
    analyze: true,
    /* eslint-disable-next-line no-unused-vars */
    extend(config, ctx) {
      config.module.rules.push(
        {
          test: /\.md$/,
          include: path.resolve(__dirname, 'content'),
          loader: 'frontmatter-markdown-loader',
          options: {
            mode: ['vue-render-functions'],
            markdownIt: markdownIt({
              html: true,
              linkify: true,
              typographer: true,
            }).use(mila, {
              pattern: /^https?:\/\//,
              attrs: {
                target: '_blank',
                rel: 'noopener noreferrer',
              },
            }),
            vue: {
              root: 'markdown',
            },
          },
        },
      );
    },
  },

  generate: {
    routes: dynamicRoutes(),
  },
};
<commit_msg>Comment out analyze build property.<commit_after>import markdownIt from 'markdown-it';
import mila from 'markdown-it-link-attributes';
import path from 'path';
import dynamicRoutes from './lib/dynamic-routes';

/* eslint-disable-next-line import/no-extraneous-dependencies */
require('dotenv').config();

export default {
  mode: 'universal',

  env: {
    perPage: process.env.PER_PAGE || 8,
  },

  head: {
    title: process.env.npm_package_name || '',
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: process.env.npm_package_description || '' },
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Lato:700&display=swap' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Mate+SC&display=swap' },
      { rel: 'stylesheet', href: 'https://fonts.googleapis.com/icon?family=Material+Icons&display=swap' },
    ],
  },

  loading: { color: '#2bb0ed' },

  css: [
  ],

  plugins: [
    '~/plugins/axios.js',
    '~/plugins/cloudinary.client.js',
    '~/plugins/vuejs-paginate.client.js',
    '~/plugins/vuelidate.js',
  ],

  buildModules: [
    '@nuxtjs/dotenv',
    '@nuxtjs/tailwindcss',
  ],

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/toast',
  ],

  toast: {
    position: 'bottom-right',
    singleton: true,
    iconPack: 'material',
  },

  purgeCSS: {
    whitelist: [
      'blockquote',
      'ul',
      'ol',
      'li',
      'markdown',
      'mt-6',
      'mb-6',
      'my-6',
      'md:mt-8',
      'md:mb-8',
      'md:my-8',
    ],
  },

  build: {
    // analyze: true,
    /* eslint-disable-next-line no-unused-vars */
    extend(config, ctx) {
      config.module.rules.push(
        {
          test: /\.md$/,
          include: path.resolve(__dirname, 'content'),
          loader: 'frontmatter-markdown-loader',
          options: {
            mode: ['vue-render-functions'],
            markdownIt: markdownIt({
              html: true,
              linkify: true,
              typographer: true,
            }).use(mila, {
              pattern: /^https?:\/\//,
              attrs: {
                target: '_blank',
                rel: 'noopener noreferrer',
              },
            }),
            vue: {
              root: 'markdown',
            },
          },
        },
      );
    },
  },

  generate: {
    routes: dynamicRoutes(),
  },
};
<|endoftext|>


<commit_before>require('acorn-jsx');

var tern = require('tern');
var infer = require('tern/lib/infer');
var walk = require('acorn/dist/walk');

tern.registerPlugin("reactjs", function (server) {
    server.on("preParse", function (text, options) {
        var plugins = options.plugins || {};
        plugins.jsx = true;
        options.plugins = plugins;
    });
    walk.base.JSXElement = function (node, state, cb) {
        cb(node.openingElement, state);
        node.children.forEach(function (child) {
            cb(child, state);
        });
    };
    walk.base.JSXOpeningElement = function (node, state, cb) {
        cb(node.name, state);
        node.attributes.forEach(function(attr) {
            cb(attr, state);
        });
    };
    walk.base.JSXAttribute = function (node, state, cb) {
        cb(node.argument || node.value, state);
    };
    walk.base.JSXEmptyExpression = function (node, state, cb) {
    };
    walk.base.JSXIdentifier = walk.base.Identifier;
    walk.base.JSXExpressionContainer = function (node, state, cb) {
        cb(node.expression, state);
    };
    infer.typeFinder.JSXElement = function (node, scope) {
        return scope.hasProp(node.openingElement.name.name) || infer.ANull;
    };
    infer.scopeGatherer.JSXElement = function (node, scope, c) {
        var inner = node.scope = new infer.Scope(scope, node);
        c(node.openingElement.name, scope, "Identifier");
        node.openingElement.attributes.forEach(function(attr) {
            c(attr.argument || attr.value, inner);
        });
        node.children.forEach(function (child) {
            c(child, inner);
        });
    };
    infer.inferWrapper.JSXElement = function (node, scope, callback) {
        callback(node.openingElement.name, scope, "Identifier");
        node.openingElement.attributes.forEach(function(attr) {
            callback(attr.argument || attr.value, scope);
        });
        node.children.forEach(function (child) {
            callback(child, scope);
        });
    };
    var original = infer.inferWrapper.Expression;
    infer.inferWrapper.Expression = function(node, scope, callback) {
        if (node.type == "JSXElement") {
            return callback(node, scope, "JSXElement");
        }
        original(node, scope, callback);
    };
    infer.inferWrapper.JSXExpressionContainer = function(node, scope, callback) {
        if (node.expression.type != "JSXEmptyExpression") {
            var handler = infer.inferExprVisitor[node.expression.type];
            if (handler) {
                handler(node.expression, scope, infer.ANull);
            }
            callback(node.expression, scope);
        }
    };
    infer.searchVisitor.JSXElement = function (node, scope, callback) {
        callback(node.openingElement.name, scope, "Identifier");
        node.openingElement.attributes.forEach(function(attr) {
            callback(attr.argument || attr.value, scope);
        });
        node.children.forEach(function (child) {
            callback(child, scope);
        });
    };
    server.addDefs(defs);
});

var defs = {
    "!name": "react",
    "!define": {
        "ComponentSpecs": {
            "!doc": "When creating a component class by invoking React.createClass(), you should provide a specification object that contains a render method and can optionally contain other lifecycle methods described here.",
            "!url": "https://facebook.github.io/react/docs/component-specs.html#component-specifications",
            "render": {
                "!type": "fn()"
            }
        },
        "ReactClass": {},
        "ReactElement": {}
    },
    "React": {
        "!doc": "React is the entry point to the React library. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can require() it.",
        "!url": "https://facebook.github.io/react/docs/top-level-api.html#react",
        "Component": {
            "!doc": "This is the base class for React Components when they're defined using ES6 classes. See Reusable Components for how to use ES6 classes with React. For what methods are actually provided by the base class, see the Component API.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.component"
        },
        "createClass": {
            "!type": "fn(specification: +ComponentSpecs) -> +ReactClass",
            "!doc": "Create a component class, given a specification. A component implements a render method which returns one single child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.createclass"
        },
        "createElement": {
            "!type": "fn(type: string|+ReactClass, props?: ?, children?: []) -> +ReactElement",
            "!doc": "Create and return a new ReactElement of the given type. The type argument can be either an html tag name string (eg. 'div', 'span', etc), or a ReactClass (created via React.createClass).",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.createelement"
        },
        "cloneElement": {
            "!type": "fn(element: +ReactElement, props?: ?, children?: []) -> +ReactElement",
            "!doc": "Clone and return a new ReactElement using element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. Unlike React.addons.cloneWithProps, key and ref from the original element will be preserved. There is no special behavior for merging any props (unlike cloneWithProps). See the v0.13 RC2 blog post for additional details.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement"
        },
        "createFactory": {
            "!type": "fn(type: string|+ReactClass) -> fn() -> +ReactElement",
            "!doc": "Return a function that produces ReactElements of a given type. Like React.createElement, the type argument can be either an html tag name string (eg. 'div', 'span', etc), or a ReactClass.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.createfactory"
        },
        "isValidElement": {
            "!type": "fn(object: ?) -> fn() -> bool",
            "!doc": "Verifies the object is a ReactElement.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement"
        },
        "DOM": {
            "!doc": "React.DOM provides convenience wrappers around React.createElement for DOM components. These should only be used when not using JSX. For example, React.DOM.div(null, 'Hello World!')",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.dom"
        }
    }
};
<commit_msg>JSX support (WIP)<commit_after>require('acorn-jsx');

var tern = require('tern');
var infer = require('tern/lib/infer');
var walk = require('acorn/dist/walk');

tern.registerPlugin("reactjs", function (server) {
    server.on("preParse", function (text, options) {
        var plugins = options.plugins || {};
        plugins.jsx = true;
        options.plugins = plugins;
    });
    walk.base.JSXElement = function (node, state, cb) {
        cb(node.openingElement, state);
        node.children.forEach(function (child) {
            cb(child, state);
        });
    };
    walk.base.JSXOpeningElement = function (node, state, cb) {
        cb(node.name, state);
        node.attributes.forEach(function(attr) {
            cb(attr, state);
        });
    };
    walk.base.JSXAttribute = walk.base.JSXSpreadAttribute = function (node, state, cb) {
        cb(node.argument || node.value, state);
    };
    walk.base.JSXEmptyExpression = function (node, state, cb) {
    };
    walk.base.JSXIdentifier = walk.base.Identifier;
    walk.base.JSXExpressionContainer = function (node, state, cb) {
        cb(node.expression, state);
    };

    infer.typeFinder.JSXElement = function (node, scope) {
        return scope.hasProp(node.openingElement.name.name) || infer.ANull;

    };

    infer.scopeGatherer.JSXElement = function (node, scope, c) {
        var inner = node.scope = new infer.Scope(scope, node);
        c(node.openingElement.name, scope, "Identifier");
        node.openingElement.attributes.forEach(function(attr) {
            c(attr.argument || attr.value, inner);
        });
        node.children.forEach(function (child) {
            c(child, inner);
        });
    };
    infer.inferWrapper.JSXElement = function (node, scope, callback) {
        callback(node.openingElement.name, scope, "Identifier");
        node.openingElement.attributes.forEach(function(attr) {
            callback(attr.argument || attr.value, scope);
        });
        node.children.forEach(function (child) {
            callback(child, scope);
        });
    };
    var original = infer.inferWrapper.Expression;
    infer.inferWrapper.Expression = function(node, scope, callback) {
        if (node.type == "JSXElement") {
            return callback(node, scope, "JSXElement");
        }
        original(node, scope, callback);
    };
    infer.inferWrapper.JSXExpressionContainer = function(node, scope, callback) {
        if (node.expression.type != "JSXEmptyExpression") {
            var handler = infer.inferExprVisitor[node.expression.type];
            if (handler) {
                handler(node.expression, scope, infer.ANull);
            }
            callback(node.expression, scope);
        }
    };

    infer.searchVisitor.JSXElement = function (node, scope, callback) {
        callback(node.openingElement.name, scope, "Identifier");
        node.openingElement.attributes.forEach(function(attr) {
            callback(attr.argument || attr.value, scope);
        });
        node.children.forEach(function (child) {
            callback(child, scope);
        });
    };

    infer.inferExprVisitor.JSXElement = function (node, scope) {

        node.openingElement.attributes.forEach(function(attr) {
            attr = attr.argument || attr.value;
            var handler = infer.inferExprVisitor[attr.type];
            if (handler) {
                handler(attr, scope, infer.ANull);
            }
        });
        node.children.forEach(function (child) {
            var handler = infer.inferExprVisitor[child.type];
            if (handler) {
                handler(child, scope, infer.ANull);
            }
        });
    };

    infer.inferExprVisitor.JSXExpressionContainer = function (node, scope) {
        if (node.expression.type != "JSXEmptyExpression") {
            var handler = infer.inferExprVisitor[node.expression.type];
            if (handler) {
                handler(node.expression, scope, infer.ANull);
            }
        }
    };

    server.addDefs(defs);
});

var defs = {
    "!name": "react",
    "!define": {
        "ComponentSpecs": {
            "!doc": "When creating a component class by invoking React.createClass(), you should provide a specification object that contains a render method and can optionally contain other lifecycle methods described here.",
            "!url": "https://facebook.github.io/react/docs/component-specs.html#component-specifications",
            "render": {
                "!type": "fn()"
            }
        },
        "ReactClass": {},
        "ReactElement": {}
    },
    "React": {
        "!doc": "React is the entry point to the React library. If you're using one of the prebuilt packages it's available as a global; if you're using CommonJS modules you can require() it.",
        "!url": "https://facebook.github.io/react/docs/top-level-api.html#react",
        "Component": {
            "!doc": "This is the base class for React Components when they're defined using ES6 classes. See Reusable Components for how to use ES6 classes with React. For what methods are actually provided by the base class, see the Component API.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.component"
        },
        "createClass": {
            "!type": "fn(specification: +ComponentSpecs) -> +ReactClass",
            "!doc": "Create a component class, given a specification. A component implements a render method which returns one single child. That child may have an arbitrarily deep child structure. One thing that makes components different than standard prototypal classes is that you don't need to call new on them. They are convenience wrappers that construct backing instances (via new) for you.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.createclass"
        },
        "createElement": {
            "!type": "fn(type: string|+ReactClass, props?: ?, children?: []) -> +ReactElement",
            "!doc": "Create and return a new ReactElement of the given type. The type argument can be either an html tag name string (eg. 'div', 'span', etc), or a ReactClass (created via React.createClass).",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.createelement"
        },
        "cloneElement": {
            "!type": "fn(element: +ReactElement, props?: ?, children?: []) -> +ReactElement",
            "!doc": "Clone and return a new ReactElement using element as the starting point. The resulting element will have the original element's props with the new props merged in shallowly. New children will replace existing children. Unlike React.addons.cloneWithProps, key and ref from the original element will be preserved. There is no special behavior for merging any props (unlike cloneWithProps). See the v0.13 RC2 blog post for additional details.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.cloneelement"
        },
        "createFactory": {
            "!type": "fn(type: string|+ReactClass) -> fn() -> +ReactElement",
            "!doc": "Return a function that produces ReactElements of a given type. Like React.createElement, the type argument can be either an html tag name string (eg. 'div', 'span', etc), or a ReactClass.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.createfactory"
        },
        "isValidElement": {
            "!type": "fn(object: ?) -> fn() -> bool",
            "!doc": "Verifies the object is a ReactElement.",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.isvalidelement"
        },
        "DOM": {
            "!doc": "React.DOM provides convenience wrappers around React.createElement for DOM components. These should only be used when not using JSX. For example, React.DOM.div(null, 'Hello World!')",
            "!url": "https://facebook.github.io/react/docs/top-level-api.html#react.dom"
        }
    }
};
<|endoftext|>


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

var program = require('commander')
	,request = require('request')
	,moment = require('moment');

program
  .version('0.0.1')
  .usage('[options]')
  .option('-d, --døgn [antal]', 'seneste døgn (default: 1)')
  .parse(process.argv);

// if (!program.args[0]) {
//    program.outputHelp();
//
//  }

var host= "http://dawa.aws.dk";

var antaldøgn= 1;
if (program.døgn) {
	antaldøgn= parseInt(program.døgn);
	if (isNaN(antaldøgn) || antaldøgn < 1) {
		program.outputHelp();
		process.exit(1);
	}
}

console.log('antal døgn: %d', antaldøgn);

var fra= moment(new Date()).subtract({weeks: 1});
var til= moment(new Date());
var url= host+"/replikering/vejstykker/haendelser?tidspunktfra="+fra.utc().toISOString()+"&tidspunkttil="+til.utc().toISOString();
console.log('url: %s', url);
process.exit(1);

var pvejnavne = new Promise(function(resolve, reject) {
	var options= {};
	options.uri= 'http://dawa.aws.dk/vejnavne';
	options.qs= {q: program.args[0], fuzzy: program.fuzzy, per_side: 20};

	request(options, function (error, response, body) {
		if (error) {
			reject(error);
			return;
		}
		if (response.statusCode !== 200) {
			reject(response.statusCode);
			return;
		}
		try {
	  	var vejnavne= JSON.parse(body);
	  	resolve(vejnavne);
		}
		catch(e) {
			reject(e.message);
		}
	});
});

pvejnavne
	.then(
		function(vejnavne) {
			for (var i = 0; i < vejnavne.length; i++) {
	  		console.log(vejnavne[i].navn);
	  	};
		})
	.catch(
		function(error) {
			console.log('Fejl: '+error)
		});<commit_msg>o, æ og s options<commit_after>#! /usr/bin/env node

var program = require('commander')
	,request = require('request')
	,moment = require('moment');

program
  .version('0.0.1')
  .usage('[options]')
  .option('-d, --døgn [antal]', 'seneste døgn (default: 1)')
  .option('-o, --opret', 'oprettede (default)')
  .option('-æ, --ændret', 'ændrede')
  .option('-s, --slet', 'slettede')
  .parse(process.argv);

// if (!program.args[0]) {
//    program.outputHelp();
//
//  }

var host= "http://dawa.aws.dk";

var antaldøgn= 1;
if (program.døgn) {
	antaldøgn= parseInt(program.døgn);
	if (isNaN(antaldøgn) || antaldøgn < 1) {
		program.outputHelp();
		process.exit(1);
	}
}

console.log('antal døgn: %d', antaldøgn);

var fra= moment(new Date()).subtract({days: antaldøgn});
var til= moment(new Date());
var url= host+"/replikering/vejstykker/haendelser";

var pvejnavne = new Promise(function(resolve, reject) {
	var options= {};
	options.uri= url;
	options.qs= {tidspunktfra: fra.utc().toISOString(), tidspunkttil: til.utc().toISOString()};

	request(options, function (error, response, body) {
		if (error) {
			reject(error);
			return;
		}
		if (response.statusCode !== 200) {
			reject(response.statusCode);
			return;
		}
		try {
	  	var vejnavne= JSON.parse(body);
	  	resolve(vejnavne);
		}
		catch(e) {
			reject(e.message);
		}
	});
});

pvejnavne
	.then(
		function(vejnavne) {
			for (var i = 0; i < vejnavne.length; i++) {
				if (!(program.opret || program.ændret || program.slet)
					|| program.opret && vejnavne[i].operation === 'insert'
					|| program.ændret && vejnavne[i].operation === 'update'
					|| program.slet && vejnavne[i].operation === 'delete') {
	  			console.log("%s %s: %s", vejnavne[i].operation ,moment(vejnavne[i].tidspunkt).local().format(),vejnavne[i].data.navn);
	  		}
	  	};
		})
	.catch(
		function(error) {
			console.log('Fejl: '+error)
		});<|endoftext|>


<commit_before>function dbg(msg) {
    $('#debug').append(msg + '\n');
}

function render_cert(src, fp) {
    var json = src + fp;
    var pem = json + "/pem";
    var der = json + "/der";
    dbg('json=' + json);
    $.getJSON(json, function(data) {
            $('.data').each(function(i, m) {
                var key = $(this).attr('datasrc');
                dbg("#data each i=" + i + " key=" + key);
                if (key in data)
                    $(this).html(data[key]);
            })
            function clickmore(elem, id) {
                $(id).toggle('fast');
                if (elem.html() == "[hide]") {
                    elem.html("[show]");
                } else {
                    elem.html("[hide]");
                }
            }
            $('.time_t').each(function(i, m) {
                var t = $(this).html();
                if (t.match(/^[0-9]+$/)) {
                    $(this).html(new Date(t * 1000) + " (" + t + ")");
                }
            })
            $('#x509more').click(function() {
                clickmore($(this), '#x509opt');
            })
            $('#sigmore').click(function() {
                clickmore($(this), '#sigopt');
            })
            $('#keymore').click(function() {
                clickmore($(this), '#keyopt');
            })
            $('#jsonlink').attr('href', json);

            var fingerprint = /SHA1 Fingerprint=(.*)/.exec(data.fingerprint);
            fingerprint = fingerprint[1].replace(/:/g, '').toLowerCase();
            dns.queryGoogleCertificateCatalog(fingerprint, display_google_certificate_catalog_status);
            dns.queryReverse(data.ip, display_ip_reverse_dns);
        })
}

function submit_searchbox() {
    dbg("submit_searchbox called");
    var x = $('#shasearch').serializeArray();
    dbg('x = ' + x);
    $(x).each(function(i, m) {
        var e = m.value.toLowerCase().replace(/:/g,"");
        dbg('i = ' + i + ' e = ' + e);
        if (!e.match(/^[0-9a-f]{40}$/)) {
            alert('invalid SHA1 "' + e + '".');
            return;
        }
        window.location.search = "?sha1=" + e;
    })
}

function display_ip_reverse_dns(infos) {
    var content = "No reverse DNS information found";

    if (infos !== undefined) {
        content = 'Reverse DNS : ' + infos + '';
    }

    var element = $('span.ip').filter('.data');
    element.addClass('withReverseDnsInfos');
    element.tipTip({ defaultPosition: 'top', maxWidth: 'auto', content: content });
}

function display_google_certificate_catalog_status(status) {
    var span = $('#googleCatalog');
    span.toggleClass('known', status !== undefined);
    span.toggleClass('unknown', status === undefined);

    if (status === undefined) {
        span.text('Certificate unknown to Google');
        span.tipTip({ defaultPosition: 'right', maxWidth: 'auto', content: 'Google never saw this certificate.' });
    } else {
        span.text('Google know this certificate');

        var content = 'Google saw this certificate ' + status.timesSeen + ' times.';
        content += '

The first time was on ' + status.firstSeen + '
';
        content += '
The last time was on ' + status.lastSeen + '

';
        span.tipTip({ defaultPosition: 'top', maxWidth: 'auto', content: content });
    }
}
<commit_msg>Sanitize input a bit.<commit_after>function dbg(msg) {
    $('#debug').append(msg + '\n');
}

function render_cert(src, fp) {
    var json = src + fp;
    var pem = json + "/pem";
    var der = json + "/der";
    dbg('json=' + json);
    $.getJSON(json, function(data) {
            $('.data').each(function(i, m) {
                var key = $(this).attr('datasrc');
                dbg("#data each i=" + i + " key=" + key);
                if (key in data)
                    $(this).html(data[key]);
            })
            function clickmore(elem, id) {
                $(id).toggle('fast');
                if (elem.html() == "[hide]") {
                    elem.html("[show]");
                } else {
                    elem.html("[hide]");
                }
            }
            $('.time_t').each(function(i, m) {
                var t = $(this).html();
                if (t.match(/^[0-9]+$/)) {
                    $(this).html(new Date(t * 1000) + " (" + t + ")");
                }
            })
            $('#x509more').click(function() {
                clickmore($(this), '#x509opt');
            })
            $('#sigmore').click(function() {
                clickmore($(this), '#sigopt');
            })
            $('#keymore').click(function() {
                clickmore($(this), '#keyopt');
            })
            $('#jsonlink').attr('href', json);

            var fingerprint = /SHA1 Fingerprint=(.*)/.exec(data.fingerprint);
            fingerprint = fingerprint[1].replace(/:/g, '').toLowerCase();
            dns.queryGoogleCertificateCatalog(fingerprint, display_google_certificate_catalog_status);
            dns.queryReverse(data.ip, display_ip_reverse_dns);
        })
}

function submit_searchbox() {
    dbg("submit_searchbox called");
    var x = $('#shasearch').serializeArray();
    dbg('x = ' + x);
    $(x).each(function(i, m) {
        var e = m.value.toLowerCase().replace(/:/g,"");
        e = e.replace(/ *$/, "");
        e = e.replace(/^ */, "");
        dbg('i = ' + i + ' e = ' + e);
        if (!e.match(/^[0-9a-f]{40}$/)) {
            alert('invalid SHA1 "' + e + '".');
            return;
        }
        window.location.search = "?sha1=" + e;
    })
}

function display_ip_reverse_dns(infos) {
    var content = "No reverse DNS information found";

    if (infos !== undefined) {
        content = 'Reverse DNS : ' + infos + '';
    }

    var element = $('span.ip').filter('.data');
    element.addClass('withReverseDnsInfos');
    element.tipTip({ defaultPosition: 'top', maxWidth: 'auto', content: content });
}

function display_google_certificate_catalog_status(status) {
    var span = $('#googleCatalog');
    span.toggleClass('known', status !== undefined);
    span.toggleClass('unknown', status === undefined);

    if (status === undefined) {
        span.text('Certificate unknown to Google');
        span.tipTip({ defaultPosition: 'right', maxWidth: 'auto', content: 'Google never saw this certificate.' });
    } else {
        span.text('Google know this certificate');

        var content = 'Google saw this certificate ' + status.timesSeen + ' times.';
        content += '

The first time was on ' + status.firstSeen + '
';
        content += '
The last time was on ' + status.lastSeen + '

';
        span.tipTip({ defaultPosition: 'top', maxWidth: 'auto', content: content });
    }
}
<|endoftext|>


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

var broccoli = require('./index')
var helpers = require('./helpers')

exports.Reader = Reader
Reader.prototype = Object.create(broccoli.Component.prototype)
Reader.prototype.constructor = Reader
function Reader () {}

Reader.prototype.read = function (destDir, callback) { throw new Error('not implemented') }

// This method is good for polling, but the interface will have to change once
// we implement inotify-based watching
Reader.prototype.statsHash = function () { throw new Error('not implemented') }

exports.PackageReader = PackageReader
PackageReader.prototype = Object.create(Reader.prototype)
PackageReader.prototype.constructor = PackageReader
function PackageReader (packages) {
  this.packages = packages
}

PackageReader.prototype.read = function (destDir, callback) {
  var self = this

  async.eachSeries(this.packages, function (pkg, pkgCallback) {
    if (pkg.transformer == null) {
      pkg.linkSourceTo(destDir)
      setImmediate(pkgCallback)
    } else {
      var intermediateDir = self.makeTmpDir()
      pkg.linkSourceTo(intermediateDir)
      pkg.transformer.setup(self._setupOptions)
      pkg.transformer.transform(intermediateDir, destDir, function (err) {
        setImmediate(function () {
          pkgCallback(err)
        })
      })
      // We should perhaps have a target dir and then link from there, so the
      // package's transformer doesn't have to support overwriting
    }
  }, function (err) {
    callback(err)
  })
}

PackageReader.prototype.statsHash = function () {
  return helpers.hashStrings(this.packages.map(function (pkg) {
    return pkg.statsHash()
  }))
}

exports.Package = Package
function Package (baseDirectory, transformer, options) {
  this.baseDirectory = baseDirectory
  this.transformer = transformer
  this.options = options || {}
}

Package.prototype.map = function (map) {
  var values = Object.keys(map).map(function (key) { return map[key] })
  helpers.assertAbsolutePaths(values)
  if (this._map != null) throw new Error('Multiple calls to .map not yet supported')
  this._map = map
  return this
}

Package.prototype.addTransformer = function (transformer) {
  if (this.transformer != null) throw new Error('Multiple transformers not yet supported')
  this.transformer = transformer
  return this
}

Package.prototype.linkSourceTo = function (destDir) {
  var self = this
  if (this._map == null) throw new Error('No package map for ' + this.baseDirectory)
  Object.keys(this._map).forEach(function (key) {
    helpers.linkRecursivelySync(
      path.join(self.baseDirectory, key),
      path.join(destDir, self._map[key]))
  })
}

Package.prototype.statsHash = function () {
  var self = this
  return helpers.hashStrings(Object.keys(this._map).map(function (relativePath) {
    return helpers.hashTree(path.join(self.baseDirectory, relativePath))
  }))
}

Package.fromDirectory = function (packageDir) {
  var broccolifile = path.resolve(packageDir, 'Broccolifile.js')
  var packages = []
  if (fs.existsSync(broccolifile)) {
    var factory = {
      makePackage: function () {
        return new Package(packageDir)
      }
    }
    packages = require(broccolifile)(factory, broccoli)
    if (!Array.isArray(packages)) throw new Error(broccolifile + ' must return an array of packages')
  } else {
    // Guess some reasonable defaults for our package
    var options = bowerOptionsForPackage(packageDir)
    var packageOptions = {}
    if (options.main != null) {
      var main = options.main
      if (typeof main === 'string') main = [main]
      if (!Array.isArray(main)) throw new Error(packageDir + ': Expected "main" bower option to be array or string')
      packageOptions.main = main
    }

    var map = {}
    // It's not clear that this is a sensible heuristic to hard-code here
    if (fs.existsSync(path.join(packageDir, 'lib'))) {
      map['lib'] = '/'
    }
    if (packageOptions.main) {
      for (var i = 0; i < packageOptions.main.length; i++) {
        map[packageOptions.main[i]] = '/' + path.basename(packageOptions.main[i])
      }
    } else {
      // Map package root into namespace root. We should perhaps avoid this, as
      // it causes clutter.
      map[''] = '/'
    }

    var pkg = new Package(packageDir, null, packageOptions).map(map)
    packages = [pkg]
  }

  return packages

  function bowerOptionsForPackage(packageDir) {
    var options = {}
    ;['.bower.json', 'bower.json'].forEach(function (fileName) {
      var json
      try {
        json = fs.readFileSync(path.join(packageDir, fileName))
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
        return
      }
      var hash = JSON.parse(json) // should report file name on invalid JSON
      for (var key in hash) {
        if (hash.hasOwnProperty(key)) {
          options[key] = hash[key]
        }
      }
    })
    return options
  }
}

exports.bowerPackages = bowerPackages
function bowerPackages (bowerDir, packageOptions) {
  if (typeof bowerDir !== 'string' && packageOptions == null) {
    // bowerDir is optional
    packageOptions = bowerDir
    bowerDir = null
  }
  if (bowerDir == null) {
    bowerDir = 'bower_components'
  }
  var entries = fs.readdirSync(bowerDir)
  var directories = entries.filter(function (f) {
    return fs.statSync(path.join(bowerDir, f)).isDirectory()
  })
  var files = entries.filter(function (f) {
    var stat = fs.statSync(path.join(bowerDir, f))
    return stat.isFile() || stat.isSymbolicLink()
  })
  var packages = []
  for (var i = 0; i < directories.length; i++) {
    packages = packages.concat(Package.fromDirectory(path.join(bowerDir, directories[i])))
  }
  // Pick up files as well; this is for compatibility with EAK's vendor/loader.js
  for (i = 0; i < files.length; i++) {
    var map = {}
    map['/' + files[i]] = '/' + files[i]
    packages.push(new Package(bowerDir).map(map))
  }
  return packages
}
<commit_msg>Rename "package" to "tree" to avoid ambiguity<commit_after>var fs = require('fs')
var path = require('path')
var async = require('async')

var broccoli = require('./index')
var helpers = require('./helpers')

exports.Reader = Reader
Reader.prototype = Object.create(broccoli.Component.prototype)
Reader.prototype.constructor = Reader
function Reader () {}

Reader.prototype.read = function (destDir, callback) { throw new Error('not implemented') }

// This method is good for polling, but the interface will have to change once
// we implement inotify-based watching
Reader.prototype.statsHash = function () { throw new Error('not implemented') }

exports.TreeReader = TreeReader
TreeReader.prototype = Object.create(Reader.prototype)
TreeReader.prototype.constructor = TreeReader
function TreeReader (trees) {
  this.trees = trees
}

TreeReader.prototype.read = function (destDir, callback) {
  var self = this

  async.eachSeries(this.trees, function (pkg, pkgCallback) {
    if (pkg.transformer == null) {
      pkg.linkSourceTo(destDir)
      setImmediate(pkgCallback)
    } else {
      var intermediateDir = self.makeTmpDir()
      pkg.linkSourceTo(intermediateDir)
      pkg.transformer.setup(self._setupOptions)
      pkg.transformer.transform(intermediateDir, destDir, function (err) {
        setImmediate(function () {
          pkgCallback(err)
        })
      })
      // We should perhaps have a target dir and then link from there, so the
      // transformer doesn't have to support overwriting
    }
  }, function (err) {
    callback(err)
  })
}

TreeReader.prototype.statsHash = function () {
  return helpers.hashStrings(this.trees.map(function (pkg) {
    return pkg.statsHash()
  }))
}

exports.Tree = Tree
function Tree (baseDirectory, transformer, options) {
  this.baseDirectory = baseDirectory
  this.transformer = transformer
  this.options = options || {}
}

Tree.prototype.map = function (map) {
  var values = Object.keys(map).map(function (key) { return map[key] })
  helpers.assertAbsolutePaths(values)
  if (this._map != null) throw new Error('Multiple calls to .map not yet supported')
  this._map = map
  return this
}

Tree.prototype.addTransformer = function (transformer) {
  if (this.transformer != null) throw new Error('Multiple transformers not yet supported')
  this.transformer = transformer
  return this
}

Tree.prototype.linkSourceTo = function (destDir) {
  var self = this
  if (this._map == null) throw new Error('No tree map for ' + this.baseDirectory)
  Object.keys(this._map).forEach(function (key) {
    helpers.linkRecursivelySync(
      path.join(self.baseDirectory, key),
      path.join(destDir, self._map[key]))
  })
}

Tree.prototype.statsHash = function () {
  var self = this
  return helpers.hashStrings(Object.keys(this._map).map(function (relativePath) {
    return helpers.hashTree(path.join(self.baseDirectory, relativePath))
  }))
}

Tree.fromDirectory = function (dir) {
  var broccolifile = path.resolve(dir, 'Broccolifile.js')
  var trees = []
  if (fs.existsSync(broccolifile)) {
    var factory = {
      makeTree: function () {
        return new Tree(dir)
      }
    }
    trees = require(broccolifile)(factory, broccoli)
    if (!Array.isArray(trees)) throw new Error(broccolifile + ' must return an array of trees')
  } else {
    // Guess some reasonable defaults
    var options = bowerOptionsForDirectory(dir)
    var treeOptions = {}
    if (options.main != null) {
      var main = options.main
      if (typeof main === 'string') main = [main]
      if (!Array.isArray(main)) throw new Error(dir + ': Expected "main" bower option to be array or string')
      treeOptions.main = main
    }

    var map = {}
    // It's not clear that this is a sensible heuristic to hard-code here
    if (fs.existsSync(path.join(dir, 'lib'))) {
      map['lib'] = '/'
    }
    if (treeOptions.main) {
      for (var i = 0; i < treeOptions.main.length; i++) {
        map[treeOptions.main[i]] = '/' + path.basename(treeOptions.main[i])
      }
    } else {
      // Map repo root into namespace root. We should perhaps avoid this, as
      // it causes clutter.
      map[''] = '/'
    }

    var pkg = new Tree(dir, null, treeOptions).map(map)
    trees = [pkg]
  }

  return trees

  function bowerOptionsForDirectory (dir) {
    var options = {}
    ;['.bower.json', 'bower.json'].forEach(function (fileName) {
      var json
      try {
        json = fs.readFileSync(path.join(dir, fileName))
      } catch (err) {
        if (err.code !== 'ENOENT') throw err
        return
      }
      var hash = JSON.parse(json) // should report file name on invalid JSON
      for (var key in hash) {
        if (hash.hasOwnProperty(key)) {
          options[key] = hash[key]
        }
      }
    })
    return options
  }
}

exports.bowerTrees = bowerTrees
function bowerTrees (bowerDir, treeOptions) {
  if (typeof bowerDir !== 'string' && treeOptions == null) {
    // bowerDir is optional
    treeOptions = bowerDir
    bowerDir = null
  }
  if (bowerDir == null) {
    bowerDir = 'bower_components'
  }
  var entries = fs.readdirSync(bowerDir)
  var directories = entries.filter(function (f) {
    return fs.statSync(path.join(bowerDir, f)).isDirectory()
  })
  var files = entries.filter(function (f) {
    var stat = fs.statSync(path.join(bowerDir, f))
    return stat.isFile() || stat.isSymbolicLink()
  })
  var trees = []
  for (var i = 0; i < directories.length; i++) {
    trees = trees.concat(Tree.fromDirectory(path.join(bowerDir, directories[i])))
  }
  // Pick up files as well; this is for compatibility with EAK's vendor/loader.js
  for (i = 0; i < files.length; i++) {
    var map = {}
    map['/' + files[i]] = '/' + files[i]
    trees.push(new Tree(bowerDir).map(map))
  }
  return trees
}
<|endoftext|>


<commit_before>/*jshint indent:2*/
'use strict';

var request = require('request')
  , _ = require('lodash')
  , moment = require('moment')
  , today = moment()
  , querystring = require('querystring');

function Redmine(host, apiKey) {
  if (!host || !apiKey) {
    throw new Error("Error: apiKey and host are required");
  }
  this.apiKey = apiKey;
  this.host = host;
  this.MAX_PAGE_SIZE = 100;
}

Redmine.prototype.pathPatterns = {
  'issue' : /^issues\/[0-9]+\.?(json|xml)?$/,
  'issues' : /^issues\.?(json|xml)?$/,
  'relations' : /^attachments\/[0-9]+\/relations\.?(json|xml)?$/,
  'users' : /^users\.?(json|xml)?$/,
  'user' : /^users\/[0-9]+\.?(json|xml)?$/,
  'time_entries' : /^time_entries\.?(json|xml)?$/,
  'issue_statuses' : /^issues_statuses\.?(json|xml)?$/,
  'projects' : /^projects\.?(json|xml)?$/,
  'versions' : /^projects\/[a-zA-Z0-9\+\-\_]+\/versions\.?(xml|json)?$/,
  'memberships' : /^projects\/[a-zA-Z0-9\+\-\_]+\/memberships\.?(xml|json)?$/,
  'issue_categories' : /^projects\/[a-zA-Z0-9\+\-\_]+\/issue_categories\.?(xml|json)?$/,
  'issue_priorities' : /^enumerations\/issue_priorities\.?(xml|json)?$/,
  'time_entry_activities' : /^enumerations\/time_entry_activities\.?(xml|json)?$/,
  'groups' : /^groups\.?(json|xml)?$/,
  'trackers' : /^trackers\.?(json|xml)?$/,
  'attachments' : /^attachments\/[0-9]+\.?(json|xml)?$/,
  'roles' : /^roles\.?(json|xml)?$/,
};

Redmine.prototype.createPath = function (path, params, method) {
  path = (path.slice(0, 1) !== '/') ? path = '/' + path : path;
  if(method==='GET'){
    delete params.format;
    delete params.method
    return this.host + path + '.' + params.format  + '?' + querystring.stringify(params);
  }else{
    return this.host + path + '.' + params.format;
  }
};

Redmine.prototype.api = function (path, opts, cb) {
  var self = this;
  opts = opts || {};

  var results = [];
  var reqCount = 0;
  var numRows = opts.numRows || self.MAX_PAGE_SIZE;
  var hasLimit = false;
  var called_method = self.getCalledMethod(path);

  delete opts.numRows;

  if (_.isFunction(opts)) {
    cb = opts;
    opts = {};
  }

  _.defaults(opts, {
    format : 'json',
    method : 'GET',
    offset : 0,
  });

  if (numRows === -1) {
    hasLimit = false;
    opts.limit = self.MAX_PAGE_SIZE;

    self.getItemsWithoutLimit({
      hasLimit: false,
      opts: opts,
      results: results,
      reqCount: reqCount,
      called_method: called_method,
      numRows: numRows,
      path: path,
      cb: cb
    });
  } else {
    hasLimit = true;
    opts.limit = (numRows > self.MAX_PAGE_SIZE) ? self.MAX_PAGE_SIZE : numRows;
    reqCount = Math.ceil(numRows / opts.limit);

    self.getItemsWithLimit({
      hasLimit: true,
      opts: opts,
      results: results,
      reqCount: reqCount,
      called_method: called_method,
      numRows: numRows,
      path: path,
      cb: cb
    });
  }
  return;
};

Redmine.prototype.getCalledMethod = function (path) {
  var self = this;
  for (var key in self.pathPatterns) {
    if (self.pathPatterns[key].test(path)) return key;
  }
  throw new Error('Called method not exists: ' + path);
};

Redmine.prototype.getItemsWithLimit = function (state) {
  var self = this;
  for (var i = 0; i < state.reqCount; i++) {
    self.processResults(state);
  }
};

Redmine.prototype.getItemsWithoutLimit = function (state) {
  var self = this;
  self.processResults(state);
};

Redmine.prototype.processResults = function (state) {
  var self = this;
  var reqOpts = {
    url : self.createPath(state.path, state.opts, state.opts.method),
    method : state.opts.method,
    headers : {
      'X-Redmine-API-Key': self.apiKey,
      'Content-Type': 'application/json'

    },
    body: state.opts.method === 'POST' ? JSON.stringify(state.opts.body) : ''
  };
  state.opts.offset += self.MAX_PAGE_SIZE;
  console.log(reqOpts.url);
  request(reqOpts, function (err, res, body) {
    if (!err && res.statusCode === 200) {
      var items = JSON.parse(body)[state.called_method];
      var moreOld = false;
      var moreOldIndex = -1;
      console.log('REQUEST: ', this.href);

      //it have limit and thus can be performed a for loop
      if (state.hasLimit) {
        state.reqCount--;
        state.results = state.results.concat(items);

        //if no more pending requests
        if (!state.reqCount && _.isFunction(state.cb)) {

          //if we have more results than expected then truncate the results
          if (state.results.length > state.numRows) {
            state.results.length = state.numRows;
          }
          state.cb(null, state.results);
        }
      } else {

        //polyfill redmine api. Search until we find an older item
        if (!_.isUndefined(state.opts.date_until)) {
          moreOld = _.some(items, function (item, index) {
            var dateCondition = (state.called_method === 'time_entries') ? 'spent_on' : 'updated_on';
            var older = self.isOlder(item, dateCondition, state.opts.date_until);
            if (older) moreOldIndex = index;
            return older;
          });

          //if we have more results than expected then truncate the results
          if (moreOld) items.length = moreOldIndex;
        }
        state.results = state.results.concat(items);
        if (!moreOld && items && items.length) {
          self.processResults(state);
        } else {
          if (_.isFunction(state.cb)) {
            state.cb(null, state.results);
          }
        }
      }
    } else if(res.statusCode !== 200){
      err = new Error('Error bad status code');
      if (_.isFunction(state.cb)) {
        state.cb(err, null);
      }
    } else {
      if (_.isFunction(state.cb)) {
        state.cb(err, null);
      }
    }
  });
};

Redmine.prototype.isOlder = function (item, dateKey, dateCondition) {
  var older = (moment(item[dateKey]).unix() - moment(dateCondition).unix()) <= 0;
  if (older) return true;
  return false;
};

module.exports = Redmine;<commit_msg>Remove format param delete<commit_after>/*jshint indent:2*/
'use strict';

var request = require('request')
  , _ = require('lodash')
  , moment = require('moment')
  , today = moment()
  , querystring = require('querystring');

function Redmine(host, apiKey) {
  if (!host || !apiKey) {
    throw new Error("Error: apiKey and host are required");
  }
  this.apiKey = apiKey;
  this.host = host;
  this.MAX_PAGE_SIZE = 100;
}

Redmine.prototype.pathPatterns = {
  'issue' : /^issues\/[0-9]+\.?(json|xml)?$/,
  'issues' : /^issues\.?(json|xml)?$/,
  'relations' : /^attachments\/[0-9]+\/relations\.?(json|xml)?$/,
  'users' : /^users\.?(json|xml)?$/,
  'user' : /^users\/[0-9]+\.?(json|xml)?$/,
  'time_entries' : /^time_entries\.?(json|xml)?$/,
  'issue_statuses' : /^issues_statuses\.?(json|xml)?$/,
  'projects' : /^projects\.?(json|xml)?$/,
  'versions' : /^projects\/[a-zA-Z0-9\+\-\_]+\/versions\.?(xml|json)?$/,
  'memberships' : /^projects\/[a-zA-Z0-9\+\-\_]+\/memberships\.?(xml|json)?$/,
  'issue_categories' : /^projects\/[a-zA-Z0-9\+\-\_]+\/issue_categories\.?(xml|json)?$/,
  'issue_priorities' : /^enumerations\/issue_priorities\.?(xml|json)?$/,
  'time_entry_activities' : /^enumerations\/time_entry_activities\.?(xml|json)?$/,
  'groups' : /^groups\.?(json|xml)?$/,
  'trackers' : /^trackers\.?(json|xml)?$/,
  'attachments' : /^attachments\/[0-9]+\.?(json|xml)?$/,
  'roles' : /^roles\.?(json|xml)?$/,
};

Redmine.prototype.createPath = function (path, params, method) {
  path = (path.slice(0, 1) !== '/') ? path = '/' + path : path;
  if(method==='GET'){
    delete params.method
    return this.host + path + '.' + params.format  + '?' + querystring.stringify(params);
  }else{
    return this.host + path + '.' + params.format;
  }
};

Redmine.prototype.api = function (path, opts, cb) {
  var self = this;
  opts = opts || {};

  var results = [];
  var reqCount = 0;
  var numRows = opts.numRows || self.MAX_PAGE_SIZE;
  var hasLimit = false;
  var called_method = self.getCalledMethod(path);

  delete opts.numRows;

  if (_.isFunction(opts)) {
    cb = opts;
    opts = {};
  }

  _.defaults(opts, {
    format : 'json',
    method : 'GET',
    offset : 0,
  });

  if (numRows === -1) {
    hasLimit = false;
    opts.limit = self.MAX_PAGE_SIZE;

    self.getItemsWithoutLimit({
      hasLimit: false,
      opts: opts,
      results: results,
      reqCount: reqCount,
      called_method: called_method,
      numRows: numRows,
      path: path,
      cb: cb
    });
  } else {
    hasLimit = true;
    opts.limit = (numRows > self.MAX_PAGE_SIZE) ? self.MAX_PAGE_SIZE : numRows;
    reqCount = Math.ceil(numRows / opts.limit);

    self.getItemsWithLimit({
      hasLimit: true,
      opts: opts,
      results: results,
      reqCount: reqCount,
      called_method: called_method,
      numRows: numRows,
      path: path,
      cb: cb
    });
  }
  return;
};

Redmine.prototype.getCalledMethod = function (path) {
  var self = this;
  for (var key in self.pathPatterns) {
    if (self.pathPatterns[key].test(path)) return key;
  }
  throw new Error('Called method not exists: ' + path);
};

Redmine.prototype.getItemsWithLimit = function (state) {
  var self = this;
  for (var i = 0; i < state.reqCount; i++) {
    self.processResults(state);
  }
};

Redmine.prototype.getItemsWithoutLimit = function (state) {
  var self = this;
  self.processResults(state);
};

Redmine.prototype.processResults = function (state) {
  var self = this;
  var reqOpts = {
    url : self.createPath(state.path, state.opts, state.opts.method),
    method : state.opts.method,
    headers : {
      'X-Redmine-API-Key': self.apiKey,
      'Content-Type': 'application/json'

    },
    body: state.opts.method === 'POST' ? JSON.stringify(state.opts.body) : ''
  };
  state.opts.offset += self.MAX_PAGE_SIZE;
  console.log(reqOpts.url);
  request(reqOpts, function (err, res, body) {
    if (!err && res.statusCode === 200) {
      var items = JSON.parse(body)[state.called_method];
      var moreOld = false;
      var moreOldIndex = -1;
      console.log('REQUEST: ', this.href);

      //it have limit and thus can be performed a for loop
      if (state.hasLimit) {
        state.reqCount--;
        state.results = state.results.concat(items);

        //if no more pending requests
        if (!state.reqCount && _.isFunction(state.cb)) {

          //if we have more results than expected then truncate the results
          if (state.results.length > state.numRows) {
            state.results.length = state.numRows;
          }
          state.cb(null, state.results);
        }
      } else {

        //polyfill redmine api. Search until we find an older item
        if (!_.isUndefined(state.opts.date_until)) {
          moreOld = _.some(items, function (item, index) {
            var dateCondition = (state.called_method === 'time_entries') ? 'spent_on' : 'updated_on';
            var older = self.isOlder(item, dateCondition, state.opts.date_until);
            if (older) moreOldIndex = index;
            return older;
          });

          //if we have more results than expected then truncate the results
          if (moreOld) items.length = moreOldIndex;
        }
        state.results = state.results.concat(items);
        if (!moreOld && items && items.length) {
          self.processResults(state);
        } else {
          if (_.isFunction(state.cb)) {
            state.cb(null, state.results);
          }
        }
      }
    } else if(res.statusCode !== 200){
      err = new Error('Error bad status code');
      if (_.isFunction(state.cb)) {
        state.cb(err, null);
      }
    } else {
      if (_.isFunction(state.cb)) {
        state.cb(err, null);
      }
    }
  });
};

Redmine.prototype.isOlder = function (item, dateKey, dateCondition) {
  var older = (moment(item[dateKey]).unix() - moment(dateCondition).unix()) <= 0;
  if (older) return true;
  return false;
};

module.exports = Redmine;<|endoftext|>


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

/**
 * Initializes a Panini instance by setting up layouts and built-in helpers. If partials, helpers, or data were configured, those are set up as well. If layout, partial, helper, or data files ever change, this method can be called again to update the Handlebars instance.
 */
module.exports = function() {
  this.loadLayouts(this.options.layouts);

  if (this.options.partials) {
    this.loadPartials(path.join(process.cwd(), this.options.partials));
  }

  if (this.options.helpers) {
    this.loadHelpers(path.join(process.cwd(), this.options.helpers));
  }

  if (this.options.data) {
    this.loadData(path.join(process.cwd(), this.options.data));
  }

  console.log('Panini refreshed.');
}
<commit_msg>Simplify code used for Panini.refresh()<commit_after>var path = require('path');

/**
 * Initializes a Panini instance by setting up layouts and built-in helpers. If partials, helpers, or data were configured, those are set up as well. If layout, partial, helper, or data files ever change, this method can be called again to update the Handlebars instance.
 */
module.exports = function() {
  this.loadLayouts(this.options.layouts);
  this.loadPartials(path.join(process.cwd(), this.options.partials || ''));
  this.loadHelpers(path.join(process.cwd(), this.options.helpers || ''));
  this.loadData(path.join(process.cwd(), this.options.data || ''));
}
<|endoftext|>


<commit_before>// Memoize working in object mode (supports any type of arguments)

'use strict';

var indexOf      = require('es5-ext/lib/Array/prototype/e-index-of')
  , hasListeners = require('event-emitter/lib/has-listeners')
  , apply = Function.prototype.apply

  , getId0 = function () { return ''; };

// Results are saved internally within array matrix:
// [0] -> Result of calling function with no arguments
// [1] -> Matrix that keeps results when function is called with one argument
//       [1][0] -> Array of arguments with which
//                 function have been called
//       [1][1] -> Array of results that matches [1][0] array
// [2] -> Matrix that keeps results when function is called with two arguments
//        [2][0] -> Array of first (of two) arguments with which
//                function have been called
//        [2][1] -> Matrixes that keeps results for two arguments function calls
//                  Each matrix matches first argument found in [2][0]
//                  [2][1][x][0] -> Array of second arguments with which
//                                  function have been called.
//                  [2][1][x][1] -> Array of results that matches [2][1][x][0]
//                                   arguments array
// ...and so on
module.exports = require('./_base')(function (conf, length) {
	var map, map1, map2, get, set, clear, count, fn
	  , hitListeners, initListeners, purgeListeners
	  , cache = conf.cache = {}, argsCache;

	if (length === 0) {
		get = set = clear = conf.get = getId0;
		conf.clearAll = function () { cache = conf.cache = {}; };
	} else {
		count = 0;
		if (length === 1) {
			map1 = [];
			map2 = [];
			get = conf.get = function (args) {
				return map2[indexOf.call(map1, args[0])];
			};
			set = function (args) {
				map1.push(args[0]);
				map2.push(++count);
				return count;
			};
			clear = function (id) {
				var index = indexOf.call(map2, id);
				if (index !== -1) {
					map1.splice(index, 1);
					map2.splice(index, 1);
				}
			};
			conf.clearAll = function () {
				map1 = [];
				map2 = [];
				cache = conf.cache = {};
			};
		} else if (length === false) {
			map = [];
			argsCache = {};
			get = conf.get = function (args) {
				var index = 0, set = map, i, length = args.length;
				if (length === 0) {
					return set[length];
				} else if ((set = set[length])) {
					while (index < (length - 1)) {
						i = indexOf.call(set[0], args[index]);
						if (i === -1) {
							return;
						}
						set = set[1][i];
						++index;
					}
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return;
					}
					return set[1][i];
				}
				return;
			};
			set = function (args) {
				var index = 0, set = map, i, length = args.length;
				if (length === 0) {
					set[length] = ++count;
				} else {
					if (!set[length]) {
						set[length] = [[], []];
					}
					set = set[length];
					while (index < (length - 1)) {
						i = indexOf.call(set[0], args[index]);
						if (i === -1) {
							i = set[0].push(args[index]) - 1;
							set[1].push([[], []]);
						}
						set = set[1][i];
						++index;
					}
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						i = set[0].push(args[index]) - 1;
					}
					set[1][i] = ++count;
				}
				argsCache[count] = args;
				return count;
			};
			clear = function (id) {
				var index = 0, set = map, i, args = argsCache[id], length = args.length
				  , path = [];
				if (length === 0) {
					delete set[length];
				} else if ((set = set[length])) {
					while (index < (length - 1)) {
						i = indexOf.call(set[0], args[index]);
						if (i === -1) {
							return;
						}
						path.push(set, i);
						set = set[1][i];
						++index;
					}
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return;
					}
					id = set[1][i];
					set[0].splice(i, 1);
					set[1].splice(i, 1);
					while (!set[0].length && path.length) {
						i = path.pop();
						set = path.pop();
						set[0].splice(i, 1);
						set[1].splice(i, 1);
					}
				}
				delete argsCache[id];
			};
			conf.clearAll = function () {
				map = [];
				cache = conf.cache = {};
				argsCache = {};
			};
		} else {
			map = [[], []];
			argsCache = {};
			get = conf.get = function (args) {
				var index = 0, set = map, i;
				while (index < (length - 1)) {
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return null;
					}
					set = set[1][i];
					++index;
				}
				i = indexOf.call(set[0], args[index]);
				if (i === -1) {
					return null;
				}
				return set[1][i];
			};
			set = function (args) {
				var index = 0, set = map, i;
				while (index < (length - 1)) {
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						i = set[0].push(args[index]) - 1;
						set[1].push([[], []]);
					}
					set = set[1][i];
					++index;
				}
				i = indexOf.call(set[0], args[index]);
				if (i === -1) {
					i = set[0].push(args[index]) - 1;
				}
				set[1][i] = ++count;
				argsCache[count] = args;
				return count;
			};
			clear = function (id) {
				var index = 0, set = map, i, path = [], args = argsCache[id];
				while (index < (length - 1)) {
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return;
					}
					path.push(set, i);
					set = set[1][i];
					++index;
				}
				i = indexOf.call(set[0], args[index]);
				if (i === -1) {
					return;
				}
				id = set[1][i];
				set[0].splice(i, 1);
				set[1].splice(i, 1);
				while (!set[0].length && path.length) {
					i = path.pop();
					set = path.pop();
					set[0].splice(i, 1);
					set[1].splice(i, 1);
				}
				delete argsCache[id];
			};
			conf.clearAll = function () {
				map = [[], []];
				cache = conf.cache = {};
				argsCache = {};
			};
		}
	}
	conf.memoized = function () {
		var id = get(arguments), value;
		if (cache.hasOwnProperty(id)) {
			hitListeners && conf.emit('hit', id, arguments, this);
			return cache[id];
		} else {
			value = apply.call(fn, this, arguments);
			id = set(arguments);
			cache[id] = value;
			initListeners && conf.emit('init', id);
			return value;
		}
	};
	conf.clear = function (id) {
		if (cache.hasOwnProperty(id)) {
			purgeListeners && conf.emit('purge', id);
			clear(id);
			delete cache[id];
		}
	};

	conf.once('ready', function () {
		fn = conf.fn;
		hitListeners = hasListeners(conf, 'hit');
		initListeners = hasListeners(conf, 'init');
		purgeListeners = hasListeners(conf, 'purge');
	});
});
<commit_msg>-- whitespace<commit_after>// Memoize working in object mode (supports any type of arguments)

'use strict';

var indexOf      = require('es5-ext/lib/Array/prototype/e-index-of')
  , hasListeners = require('event-emitter/lib/has-listeners')
  , apply = Function.prototype.apply

  , getId0 = function () { return ''; };

// Results are saved internally within array matrix:
// [0] -> Result of calling function with no arguments
// [1] -> Matrix that keeps results when function is called with one argument
//        [1][0] -> Array of arguments with which
//                 function have been called
//        [1][1] -> Array of results that matches [1][0] array
// [2] -> Matrix that keeps results when function is called with two arguments
//        [2][0] -> Array of first (of two) arguments with which
//                function have been called
//        [2][1] -> Matrixes that keeps results for two arguments function calls
//                  Each matrix matches first argument found in [2][0]
//                  [2][1][x][0] -> Array of second arguments with which
//                                  function have been called.
//                  [2][1][x][1] -> Array of results that matches [2][1][x][0]
//                                   arguments array
// ...and so on
module.exports = require('./_base')(function (conf, length) {
	var map, map1, map2, get, set, clear, count, fn
	  , hitListeners, initListeners, purgeListeners
	  , cache = conf.cache = {}, argsCache;

	if (length === 0) {
		get = set = clear = conf.get = getId0;
		conf.clearAll = function () { cache = conf.cache = {}; };
	} else {
		count = 0;
		if (length === 1) {
			map1 = [];
			map2 = [];
			get = conf.get = function (args) {
				return map2[indexOf.call(map1, args[0])];
			};
			set = function (args) {
				map1.push(args[0]);
				map2.push(++count);
				return count;
			};
			clear = function (id) {
				var index = indexOf.call(map2, id);
				if (index !== -1) {
					map1.splice(index, 1);
					map2.splice(index, 1);
				}
			};
			conf.clearAll = function () {
				map1 = [];
				map2 = [];
				cache = conf.cache = {};
			};
		} else if (length === false) {
			map = [];
			argsCache = {};
			get = conf.get = function (args) {
				var index = 0, set = map, i, length = args.length;
				if (length === 0) {
					return set[length];
				} else if ((set = set[length])) {
					while (index < (length - 1)) {
						i = indexOf.call(set[0], args[index]);
						if (i === -1) {
							return;
						}
						set = set[1][i];
						++index;
					}
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return;
					}
					return set[1][i];
				}
				return;
			};
			set = function (args) {
				var index = 0, set = map, i, length = args.length;
				if (length === 0) {
					set[length] = ++count;
				} else {
					if (!set[length]) {
						set[length] = [[], []];
					}
					set = set[length];
					while (index < (length - 1)) {
						i = indexOf.call(set[0], args[index]);
						if (i === -1) {
							i = set[0].push(args[index]) - 1;
							set[1].push([[], []]);
						}
						set = set[1][i];
						++index;
					}
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						i = set[0].push(args[index]) - 1;
					}
					set[1][i] = ++count;
				}
				argsCache[count] = args;
				return count;
			};
			clear = function (id) {
				var index = 0, set = map, i, args = argsCache[id], length = args.length
				  , path = [];
				if (length === 0) {
					delete set[length];
				} else if ((set = set[length])) {
					while (index < (length - 1)) {
						i = indexOf.call(set[0], args[index]);
						if (i === -1) {
							return;
						}
						path.push(set, i);
						set = set[1][i];
						++index;
					}
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return;
					}
					id = set[1][i];
					set[0].splice(i, 1);
					set[1].splice(i, 1);
					while (!set[0].length && path.length) {
						i = path.pop();
						set = path.pop();
						set[0].splice(i, 1);
						set[1].splice(i, 1);
					}
				}
				delete argsCache[id];
			};
			conf.clearAll = function () {
				map = [];
				cache = conf.cache = {};
				argsCache = {};
			};
		} else {
			map = [[], []];
			argsCache = {};
			get = conf.get = function (args) {
				var index = 0, set = map, i;
				while (index < (length - 1)) {
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return null;
					}
					set = set[1][i];
					++index;
				}
				i = indexOf.call(set[0], args[index]);
				if (i === -1) {
					return null;
				}
				return set[1][i];
			};
			set = function (args) {
				var index = 0, set = map, i;
				while (index < (length - 1)) {
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						i = set[0].push(args[index]) - 1;
						set[1].push([[], []]);
					}
					set = set[1][i];
					++index;
				}
				i = indexOf.call(set[0], args[index]);
				if (i === -1) {
					i = set[0].push(args[index]) - 1;
				}
				set[1][i] = ++count;
				argsCache[count] = args;
				return count;
			};
			clear = function (id) {
				var index = 0, set = map, i, path = [], args = argsCache[id];
				while (index < (length - 1)) {
					i = indexOf.call(set[0], args[index]);
					if (i === -1) {
						return;
					}
					path.push(set, i);
					set = set[1][i];
					++index;
				}
				i = indexOf.call(set[0], args[index]);
				if (i === -1) {
					return;
				}
				id = set[1][i];
				set[0].splice(i, 1);
				set[1].splice(i, 1);
				while (!set[0].length && path.length) {
					i = path.pop();
					set = path.pop();
					set[0].splice(i, 1);
					set[1].splice(i, 1);
				}
				delete argsCache[id];
			};
			conf.clearAll = function () {
				map = [[], []];
				cache = conf.cache = {};
				argsCache = {};
			};
		}
	}
	conf.memoized = function () {
		var id = get(arguments), value;
		if (cache.hasOwnProperty(id)) {
			hitListeners && conf.emit('hit', id, arguments, this);
			return cache[id];
		} else {
			value = apply.call(fn, this, arguments);
			id = set(arguments);
			cache[id] = value;
			initListeners && conf.emit('init', id);
			return value;
		}
	};
	conf.clear = function (id) {
		if (cache.hasOwnProperty(id)) {
			purgeListeners && conf.emit('purge', id);
			clear(id);
			delete cache[id];
		}
	};

	conf.once('ready', function () {
		fn = conf.fn;
		hitListeners = hasListeners(conf, 'hit');
		initListeners = hasListeners(conf, 'init');
		purgeListeners = hasListeners(conf, 'purge');
	});
});
<|endoftext|>


<commit_before>var parse = require('url').parse;
var defaultHeader = {'content-type': 'text/plain'};

/**
 * Handle http requests.
 *
 * @public
 * @param {object} The session object.
 * @param {object} The http request object.
 * @param {object} The http response object.
 */
module.exports = function handler (session, req, res) {

    var url = parse(req.url, true);

    // create path array
    var path = url.pathname.replace(/\/$|^\//g, "").split("/", 42);

    if (path[0] === engine.operation_id) {

        if (path.length < 3 || !path[1] || !path[2]) {
            return link.end(400, 'Invalid operation url.');
        }

        var instance;
        var role = session[engine.session_role];
        var link = {
            req: req,
            res: res,
            end: end
        };

        // set engine as instance (core module)
        if (path[1] === engine.operation_id) {
            instance = engine;
            link.path = path.slice(2);
            link.name = 'file';

        // get cached instance and check access
        } else {

            if (!(instance = engine.module.eventAccess(role, path[1], path[2]))) {

                // send a "not found" if instance is not found or access denied
                return link.end(404, 'Instance or operation not found.');
            };

            link.path = path.slice(3);
            link.name = path[2];
        }

        // extend link object
        link._ = instance;

        // create the link object
        link.session = session;
        link.pathname = url.pathname;
        link.query = url.query;

            // set a empty response header object
        link.haeders = {};

        // save session in link
        link[engine.session_role] = role;
        link[engine.session_user] = session[engine.session_user];
        link[engine.session_locale] = session[engine.session_locale];

        // emit operation
        instance.emit(link.name, link);

        // resume request
        return req.resume();
    }

    // pass request to the static module
    engine.static(url.pathname, req, res);
    req.resume();
};

/**
 * Send a http response (end the connection).
 *
 * @public
 * @param {number} The http status code.
 * @param {object} The response data.
 */
function end (code, data) {
    var self = this;

    var headers = self.headers || defaultHeader;
    headers.Server = 'JCES';

    data = convertToBuffer(data, headers);

    if (data === false) {
        code = 500;
        data = 'JSON stringify error';
    }

    headers['Content-Length'] = data.length;

    self.res.writeHead(code, headers);
    self.res.end(data);
}

/**
 * Convert data to a data buffer.
 *
 * @private
 * @param {object} The data to convert.
 * @param {object} The http headers.
 */
function convertToBuffer (data, headers) {

    if (data === undefined) {
        return new Buffer(0);
    }

    if (typeof data === 'string') {
        return new Buffer(data);
    }

    if (data instanceof Buffer) {
        return data;
    }

    try {
        data = JSON.stringify(data);

        if (headers) {
            headers['content-type'] = 'application/json; charset=utf-8';
        }
    } catch (err) {
        if (headers) {
            headers['content-type'] = 'text/plain';
        }
        return false;
    }

    if (data === undefined) {
        return false;
    }

    return new Buffer(data);
}
<commit_msg>added nice comments<commit_after>var parse = require('url').parse;
var defaultHeader = {'content-type': 'text/plain'};

/**
 * Handle http requests.
 *
 * @public
 * @param {object} The session object.
 * @param {object} The http request object.
 * @param {object} The http response object.
 */
module.exports = function handler (session, req, res) {

    var url = parse(req.url, true);

    // create path array
    var path = url.pathname.replace(/\/$|^\//g, "").split("/", 42);

    if (path[0] === engine.operation_id) {

        if (path.length < 3 || !path[1] || !path[2]) {
            return link.end(400, 'Invalid operation url.');
        }

        var instance;
        var role = session[engine.session_role];
        var link = {
            req: req,
            res: res,
            end: end
        };

        // set engine as instance (core module)
        if (path[1] === engine.operation_id) {

            // set engine core module as instance
            instance = engine;

            // remove operation key and instance name from path
            link.path = path.slice(2);

            // set event name to the core opertation to fetch files
            link.name = 'file';

        // get cached instance and check access
        } else {

            if (!(instance = engine.module.eventAccess(role, path[1], path[2]))) {

                // send a "not found" if instance is not found or access denied
                return link.end(404, 'Instance or operation not found.');
            };

            // remove operation key, module instance name and event from path
            link.path = path.slice(3);

            // get the event name
            link.name = path[2];
        }

        // extend link object
        link._ = instance;

        // save session object on link
        link.session = session;

        // add the pathname to the link
        link.pathname = url.pathname;

        // append the parsed query object to the link
        link.query = url.query;

        // set a empty response header object
        link.haeders = {};

        // save core session data shortcuts (role, userId, locale)
        link[engine.session_role] = role;
        link[engine.session_user] = session[engine.session_user];
        link[engine.session_locale] = session[engine.session_locale];

        // emit operation
        instance.emit(link.name, link);

        // resume request
        return req.resume();
    }

    // pass request to the static module
    engine.static(url.pathname, req, res);
    req.resume();
};

/**
 * Send a http response (end the connection).
 *
 * @public
 * @param {number} The http status code.
 * @param {object} The response data.
 */
function end (code, data) {
    var self = this;

    var headers = self.headers || defaultHeader;
    headers.Server = 'JCES';

    data = convertToBuffer(data, headers);

    if (data === false) {
        code = 500;
        data = 'JSON stringify error';
    }

    headers['Content-Length'] = data.length;

    self.res.writeHead(code, headers);
    self.res.end(data);
}

/**
 * Convert data to a data buffer.
 *
 * @private
 * @param {object} The data to convert.
 * @param {object} The http headers.
 */
function convertToBuffer (data, headers) {

    if (data === undefined) {
        return new Buffer(0);
    }

    if (typeof data === 'string') {
        return new Buffer(data);
    }

    if (data instanceof Buffer) {
        return data;
    }

    try {
        data = JSON.stringify(data);

        if (headers) {
            headers['content-type'] = 'application/json; charset=utf-8';
        }
    } catch (err) {
        if (headers) {
            headers['content-type'] = 'text/plain';
        }
        return false;
    }

    if (data === undefined) {
        return false;
    }

    return new Buffer(data);
}
<|endoftext|>


<commit_before>/**
 * @module request
 *
 * @description Jsonp requests on client normal http requests on server.
 */
/*!
 * @TODO: what about normal ajax requests on client ?
 */

var _ = require('lodash');
var UAParser = require('ua-parser-js');

module.exports = typeof window == 'undefined' ? serverRequest : clientRequest;

/**
 * Враппер для jQuery.ajax и request с более менее общим апи.
 *
 * Из параметров ниже, `xhr` и `errorDesc` зависит от среды исполнения.
 *
 * @param {string} conf.url - Урл запроса.
 * @param {string} conf.type - Тип запроса (на сервере поддерживается только json).
 * @param {Object} conf.data - Параметры запроса.
 * @param {Function} [conf.success] - callback(body, xhr)
 * @param {Function} [conf.error] - callback(xhr, reason)
 * @param {Function} [conf.complete] - callback(error, result, xhr)
 * @param {int} conf.timeout - In milliseconds.
 * @returns {*}
 */
function serverRequest(conf) {
    var request = require('request');

    if (!conf.body) {
        if (conf.method && conf.method.toLowerCase() == 'post') {
            conf.form = conf.data;
        } else {
            conf.qs = conf.data;
        }
    }

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        pool: false
    });

    // @doclink: https://github.com/mikeal/request#requestoptions-callback
    return request(conf, function(error, xhr, body) {
        if (error) {
            conf.error.call(conf.context, xhr, error);
        } else {
            try {
                body = conf.type.match(/^json/) ? JSON.parse(body) : body;
                conf.success.call(conf.context, body, xhr);
            } catch (ex) {
                if (ex instanceof SyntaxError) {
                    var err = new SyntaxError(
                        "[request] couldn't parse response as JSON (from " + conf.url + "): " + body
                    );

                    conf.error.call(conf.context, xhr, err);
                } else {
                    throw ex;
                }
            }
        }

        conf.complete.call(conf.context, error, body, xhr);
    });
}

var isLegacyIECached = null;

function isLegacyIE() {
    if (isLegacyIECached == null) {
        var res = UAParser(navigator.userAgent);
        isLegacyIECached = res.browser.name == 'IE' && Number(res.browser.major) < 10;
    }
    return isLegacyIECached;
}

var originRe = /(?:https?:)?\/\/([^/:]+)/;

function isCrossOrigin(url) {
    var matched = url.match(originRe);
    if (matched) {
        return document.location.hostname != matched[1];
    }
}

function clientRequest(conf) {
    var reqwest = require('reqwest');
    // @doclink: https://github.com/ded/reqwest

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        overrideType: _.noop
    });

    if (isCrossOrigin(conf.url)) {
        conf.crossOrigin = true;
    }

    // IE ниже 10 версии не поддерживают передачу кук в кросс-доменных сценариях
    if (conf.crossOrigin && conf.withCredentials && conf.type != 'jsonp' && isLegacyIE()) {
        conf.type = 'jsonp';
        conf.overrideType('jsonp');
    }

    var xhr = reqwest(conf);

    // во время аборта запроса не логируем его как ошибку
    var abort = xhr.abort;
    xhr.abort = function() {
        conf.error = _.noop;
        abort.call(xhr);
    };

    return xhr;
}
<commit_msg>put data in body instead form<commit_after>/**
 * @module request
 *
 * @description Jsonp requests on client normal http requests on server.
 */
/*!
 * @TODO: what about normal ajax requests on client ?
 */

var _ = require('lodash');
var UAParser = require('ua-parser-js');

module.exports = typeof window == 'undefined' ? serverRequest : clientRequest;

/**
 * Враппер для jQuery.ajax и request с более менее общим апи.
 *
 * Из параметров ниже, `xhr` и `errorDesc` зависит от среды исполнения.
 *
 * @param {string} conf.url - Урл запроса.
 * @param {string} conf.type - Тип запроса (на сервере поддерживается только json).
 * @param {Object} conf.data - Параметры запроса.
 * @param {Function} [conf.success] - callback(body, xhr)
 * @param {Function} [conf.error] - callback(xhr, reason)
 * @param {Function} [conf.complete] - callback(error, result, xhr)
 * @param {int} conf.timeout - In milliseconds.
 * @returns {*}
 */
function serverRequest(conf) {
    var request = require('request');

    if (conf.method && conf.method.toLowerCase() == 'post') {
        conf.body = conf.data;
    } else {
        conf.qs = conf.data;
    }

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        pool: false
    });

    // @doclink: https://github.com/mikeal/request#requestoptions-callback
    return request(conf, function(error, xhr, body) {
        if (error) {
            conf.error.call(conf.context, xhr, error);
        } else {
            try {
                body = conf.type.match(/^json/) ? JSON.parse(body) : body;
                conf.success.call(conf.context, body, xhr);
            } catch (ex) {
                if (ex instanceof SyntaxError) {
                    var err = new SyntaxError(
                        "[request] couldn't parse response as JSON (from " + conf.url + "): " + body
                    );

                    conf.error.call(conf.context, xhr, err);
                } else {
                    throw ex;
                }
            }
        }

        conf.complete.call(conf.context, error, body, xhr);
    });
}

var isLegacyIECached = null;

function isLegacyIE() {
    if (isLegacyIECached == null) {
        var res = UAParser(navigator.userAgent);
        isLegacyIECached = res.browser.name == 'IE' && Number(res.browser.major) < 10;
    }
    return isLegacyIECached;
}

var originRe = /(?:https?:)?\/\/([^/:]+)/;

function isCrossOrigin(url) {
    var matched = url.match(originRe);
    if (matched) {
        return document.location.hostname != matched[1];
    }
}

function clientRequest(conf) {
    var reqwest = require('reqwest');
    // @doclink: https://github.com/ded/reqwest

    _.defaults(conf, {
        success: _.noop,
        error: _.noop,
        complete: _.noop,
        overrideType: _.noop
    });

    if (isCrossOrigin(conf.url)) {
        conf.crossOrigin = true;
    }

    // IE ниже 10 версии не поддерживают передачу кук в кросс-доменных сценариях
    if (conf.crossOrigin && conf.withCredentials && conf.type != 'jsonp' && isLegacyIE()) {
        conf.type = 'jsonp';
        conf.overrideType('jsonp');
    }

    var xhr = reqwest(conf);

    // во время аборта запроса не логируем его как ошибку
    var abort = xhr.abort;
    xhr.abort = function() {
        conf.error = _.noop;
        abort.call(xhr);
    };

    return xhr;
}
<|endoftext|>


<commit_before>/**
 * To make the requests asynchronously
 */

var logger = require('./logger');

var Request = function(hostname, headers, logLevel) {
  this.hostname = hostname;
  this.headers = headers
  logger.level = logLevel || 0;
};

Request.prototype.post = function(path, data, cb) {
  this.completeRequest('post', path, cb, data);
};

Request.prototype.get = function(path, cb) {
  this.completeRequest('get', path, cb);
};

Request.prototype.delete = function(path, cb) {
  this.completeRequest('delete', path, cb);
};

Request.prototype.put = function(path, data, cb) {
  this.completeRequest('put', path, cb, data);
};

Request.prototype.completeRequest = function(method, path, cb, data) {

  var https = require('https'),
    dataString = JSON.stringify(data),
    options = {
      hostname: this.hostname,
      path: path,
      method: method.toLowerCase() || 'get',
      post: 443,
      headers: {
        'Content-Type': 'application/json'
      }
    };

  // Set Custom Headers
  if(this.headers) {
    for(var key in this.headers) {
      option.headers[key] = this.headers[key];
    }
  }

  if (options.method === 'post' || options.method === 'put' || options.method === 'delete') {
    options.headers['Content-Length'] = new Buffer(dataString).length;
  }

  var request = https.request(options, function(res) {
    logger.info('Status Returned: ' + res.statusCode);
    logger.info('Headers Returned: ' + JSON.stringify(res.headers));

    response.setEncoding('utf8');

    var body = '';

    response.on('data', function(chunk) {
      body += chunk;
    });

    response.on('end', function() {

      // If the API limit has been reached
      if(res.statusCode === 429) {
        var timeToWait = res.headers['X-Retry-After'],
          info = 'You have reached the rate limit for the '
          + 'BigCommerce API, we will retry again in ' +
          timeToWait + 'seconds.';

        return setTimeout(function() {
          this.completeRequest(method, path, cb, data);
        }, timeToWait*1000);
      }

      try{
        var json = {};
        if(body.trim !== ''){
          json = JSON.parse(body);
          if (json.hasOwnProperty('error') || json.hasOwnProperty('errors')) {
            return cb(new Error(json.error || JSON.stringify(json.errors)), null, response);
          }
        }
        return cb(null, json, response);
      }catch(e){
        cb(e);
      }

    });

  });

}

module.exports = Request;
<commit_msg>Added debugging to show the location of the request<commit_after>/**
 * To make the requests asynchronously
 */

var logger = require('./logger');

var Request = function(hostname, headers, logLevel) {
  this.hostname = hostname;
  this.headers = headers
  logger.level = logLevel || 0;
};

Request.prototype.post = function(path, data, cb) {
  this.completeRequest('post', path, cb, data);
};

Request.prototype.get = function(path, cb) {
  this.completeRequest('get', path, cb);
};

Request.prototype.delete = function(path, cb) {
  this.completeRequest('delete', path, cb);
};

Request.prototype.put = function(path, data, cb) {
  this.completeRequest('put', path, cb, data);
};

Request.prototype.completeRequest = function(method, path, cb, data) {

  logger.info('Requesting Data from: https://' + this.hostname + path);

  var https = require('https'),
    dataString = JSON.stringify(data),
    options = {
      hostname: this.hostname,
      path: path,
      method: method.toLowerCase() || 'get',
      post: 443,
      headers: {
        'Content-Type': 'application/json'
      }
    };

  // Set Custom Headers
  if(this.headers) {
    for(var key in this.headers) {
      option.headers[key] = this.headers[key];
    }
  }

  if (options.method === 'post' || options.method === 'put' || options.method === 'delete') {
    options.headers['Content-Length'] = new Buffer(dataString).length;
  }

  var request = https.request(options, function(res) {
    logger.info('Status Returned: ' + res.statusCode);
    logger.info('Headers Returned: ' + JSON.stringify(res.headers));

    response.setEncoding('utf8');

    var body = '';

    response.on('data', function(chunk) {
      body += chunk;
    });

    response.on('end', function() {

      // If the API limit has been reached
      if(res.statusCode === 429) {
        var timeToWait = res.headers['X-Retry-After'],
          info = 'You have reached the rate limit for the '
          + 'BigCommerce API, we will retry again in ' +
          timeToWait + 'seconds.';

        return setTimeout(function() {
          this.completeRequest(method, path, cb, data);
        }, timeToWait*1000);
      }

      try{
        var json = {};
        if(body.trim !== ''){
          json = JSON.parse(body);
          if (json.hasOwnProperty('error') || json.hasOwnProperty('errors')) {
            return cb(new Error(json.error || JSON.stringify(json.errors)), null, response);
          }
        }
        return cb(null, json, response);
      }catch(e){
        cb(e);
      }

    });

  });

}

module.exports = Request;
<|endoftext|>