<commit_before>/* global describe, it, xit */
/* jslint node: true, esnext: true */

"use strict";

const chai = require('chai'),
  assert = chai.assert,
  expect = chai.expect,
  should = chai.should(),
  mochaInterceptorTest = require('kronos-test-interceptor').mochaInterceptorTest,
  llm = require('loglevel-mixin'),
  Interceptor = require('../index').Interceptor,
  TimeLoggerInterceptor = require('../index').TimeLoggerInterceptor,
  TimeoutInterceptor = require('../index').TimeoutInterceptor,
  LimitingInterceptor = require('../index').LimitingInterceptor;

const logger = {};
llm.defineLogLevelProperties(logger, llm.defaultLogLevels, llm.defaultLogLevels);

/* simple owner with name */
function dummyEndpoint(name) {
  return {get name() {
      return name;
    },
    toString() {
      return this.name;
    },
    "step": logger
  };
}

describe('interceptors', () => {
  const ep = dummyEndpoint('ep');

  mochaInterceptorTest(Interceptor, ep, {}, "none");

  mochaInterceptorTest(TimeLoggerInterceptor, ep, {}, "logger-request-time", itc => {});

  const REQUEST_LIMIT = 1;

  mochaInterceptorTest(LimitingInterceptor, ep, {
    limit: REQUEST_LIMIT
  }, "request-limit", (itc, withConfig) => {
    it('has limit', () => assert.equal(itc.limit, REQUEST_LIMIT));

    itc.connected = dummyEndpoint('ep');

    // request value is the timeout
    itc.connected.receive = request =>
      new Promise((fullfilled, rejected) =>
        setTimeout(() => fullfilled(request), 200));

    xit('sending lots of request', done => {
      let i;
      for (i = 0; i < REQUEST_LIMIT + 1; i++) {
        const response = itc.receive(i).then(
          f => {
            console.log(`fullfilled: ${f}`);
          },
          r => {
            console.log(`rejected: ${r}`);

            if (i === REQUEST_LIMIT) {
              done();
            }
          }
        );
        console.log(`send: ${i} ${itc.ongoingResponses.size}`);
      }
    });
  });

  mochaInterceptorTest(TimeoutInterceptor, ep, {
    timeout: 15
  }, "timeout", (itc, withConfig) => {
    it('has timeout', () => assert.equal(itc.timeout, 15));

    itc.connected = dummyEndpoint('ep');

    // request value is the timeout
    itc.connected.receive = request =>
      new Promise((fullfilled, rejected) =>
        setTimeout(() => fullfilled(request), request));

    it('passing request within time', done => {
      const response = itc.receive(5); // wait 5 msecs then fullfill
      response.then(resolved => {
        done();
      }).catch(rejected => {
        //console.log(`got timeout ? ${rejected}`);
        done(rejected);
      });
    });

    it('rejecting long running request', done => {
      const response = itc.receive(100); // wait 100 msecs then fullfill -> timeout
      response.then(resolved => {
        console.log(`resolved ${resolved}`);
      }).catch(rejected => {
        //console.log(`got timeout ? ${rejected}`);
        done();
      });
    });

  });
});
<commit_msg>test(interceptor): Add a test to get the interceptor type<commit_after>/* global describe, it, xit */
/* jslint node: true, esnext: true */

"use strict";

const chai = require('chai'),
  assert = chai.assert,
  expect = chai.expect,
  should = chai.should(),
  mochaInterceptorTest = require('kronos-test-interceptor').mochaInterceptorTest,
  llm = require('loglevel-mixin'),
  Interceptor = require('../index').Interceptor,
  TimeLoggerInterceptor = require('../index').TimeLoggerInterceptor,
  TimeoutInterceptor = require('../index').TimeoutInterceptor,
  LimitingInterceptor = require('../index').LimitingInterceptor;

const logger = {};
llm.defineLogLevelProperties(logger, llm.defaultLogLevels, llm.defaultLogLevels);

/* simple owner with name */
function dummyEndpoint(name) {
  return {get name() {
      return name;
    },
    toString() {
      return this.name;
    },
    "step": logger
  };
}

describe('interceptors', () => {

  it('get type', done => {
    assert.equal("none", Interceptor.type);
    done();
  });

  const ep = dummyEndpoint('ep');

  mochaInterceptorTest(Interceptor, ep, {}, "none");

  mochaInterceptorTest(TimeLoggerInterceptor, ep, {}, "logger-request-time", itc => {});

  const REQUEST_LIMIT = 1;

  mochaInterceptorTest(LimitingInterceptor, ep, {
    limit: REQUEST_LIMIT
  }, "request-limit", (itc, withConfig) => {
    it('has limit', () => assert.equal(itc.limit, REQUEST_LIMIT));

    itc.connected = dummyEndpoint('ep');

    // request value is the timeout
    itc.connected.receive = request =>
      new Promise((fullfilled, rejected) =>
        setTimeout(() => fullfilled(request), 200));

    xit('sending lots of request', done => {
      let i;
      for (i = 0; i < REQUEST_LIMIT + 1; i++) {
        const response = itc.receive(i).then(
          f => {
            console.log(`fullfilled: ${f}`);
          },
          r => {
            console.log(`rejected: ${r}`);

            if (i === REQUEST_LIMIT) {
              done();
            }
          }
        );
        console.log(`send: ${i} ${itc.ongoingResponses.size}`);
      }
    });
  });

  mochaInterceptorTest(TimeoutInterceptor, ep, {
    timeout: 15
  }, "timeout", (itc, withConfig) => {
    it('has timeout', () => assert.equal(itc.timeout, 15));

    itc.connected = dummyEndpoint('ep');

    // request value is the timeout
    itc.connected.receive = request =>
      new Promise((fullfilled, rejected) =>
        setTimeout(() => fullfilled(request), request));

    it('passing request within time', done => {
      const response = itc.receive(5); // wait 5 msecs then fullfill
      response.then(resolved => {
        done();
      }).catch(rejected => {
        //console.log(`got timeout ? ${rejected}`);
        done(rejected);
      });
    });

    it('rejecting long running request', done => {
      const response = itc.receive(100); // wait 100 msecs then fullfill -> timeout
      response.then(resolved => {
        console.log(`resolved ${resolved}`);
      }).catch(rejected => {
        //console.log(`got timeout ? ${rejected}`);
        done();
      });
    });

  });
});
<|endoftext|>


<commit_before>describe('traffic', function() {
  beforeEach(function() {
    window.matrix.settings = {
      profileId: ''
    };
    subject =  window.matrix.landing;
    sandbox = sinon.sandbox.create();
    server = sinon.fakeServer.create();
  });
  afterEach(function() {
    sandbox.restore();
    server.restore();
  });
  describe('#init', function() {
    beforeEach(function() {
      $('body').append('

');
      sandbox.stub(Handlebars, 'compile');
    });
    it("calls reload", function() {
      mock = sandbox.mock(subject).expects("reload").once();
      subject.init();
      mock.verify();
    });
    it("calls reload with interval of 1 minute", function() {
      clock = sinon.useFakeTimers(Date.now());
      mock = sandbox.mock(subject).expects("reload").twice();
      subject.init();
      clock.tick(60000);
      mock.verify();
      clock.restore();
    });
  });
  describe('#reload', function() {
    it("calls endpoint", function() {
      sandbox.stub(xhr, "json");
      mock = sandbox.mock(subject).expects("endpoint").once();
      subject.reload();
      mock.verify();
    });
    context('json returned', function(){
      beforeEach(function() {
        stub = sandbox.stub(xhr, 'json');
      });
      it("calls parseResponse", function() {
        mock = sandbox.mock(subject).expects("parseResponse").once();
        subject.reload();
        stub.callArgWith(1, {}, {});
        mock.verify();
      });
    });
  });
  describe('#parseResponse', function() {
    context("error parsing json", function() {
      it("returns withpout parsing", function() {
        mock = sandbox.mock(subject).expects("parseData").never();
        subject.parseResponse({}, null);
        mock.verify();
      });
      it("does not refresh the results", function() {
        mock = sandbox.mock(subject).expects("refreshResults").never();
        subject.parseResponse({}, null);
        mock.verify();
      });
    });
    context("no error parsing json", function() {
      context("has data from GA", function() {
        it("calls parseData", function() {
          sandbox.stub(subject, 'refreshResults');
          mock = sandbox.mock(subject).expects("parseData").once();
          subject.parseResponse(null, {rows: []});
          mock.verify();
        });
        it("refreshes the results", function() {
          mock = sandbox.mock(subject).expects("refreshResults").once();
          subject.parseResponse(null, {rows: []});
          mock.verify();
        });
      });
      context("no rows (no data from GA)", function() {
        it("does not call parseData", function() {
          mock = sandbox.mock(subject).expects("parseData").never();
          subject.parseResponse(null, {});
          mock.verify();
        });
      });
    });
  });
  describe('#parseData', function() {
    beforeEach(function() {
      data = { rows: [["Titel 1","url 1","(not set)","00","1"],["Titel 2","url 2","(not set)","00","1"],["Titel 3","url 3","(not set)","01","3"],["Titel 4","url 4","(not set)","02","3"]] };
    });
    it("calls addTerm for every row less than two minutes ago", function() {
      mock = sandbox.mock(subject).expects("addTerm").thrice();
      subject.parseData(data);
      mock.verify();
    });
    it("calls addTerm for every row", function() {
      data = { rows: [["Titel 1","url 1","(not set)","00","DESKTOP","1"]] };
      mock = sandbox.mock(subject).expects("addTerm").withArgs("Titel 1", 1, "url 1", "(not set)");
      subject.parseData(data);
      mock.verify();
    });
    context('Search Term', function() {
      beforeEach(function(){
        data = { rows: [["Search", "url", "source", "10"]]};
      });
      it("does not call addTerm for the row", function() {
        mock = sandbox.mock(subject).expects("addTerm").never();
        subject.parseData(data);
        mock.verify();
      });
    });
  });
  describe('#addTerm', function() {
    beforeEach(function() {
      subject.terms = [];
    });
    it("adds new items to terms", function() {
      result = { term: 'Test', total: 1, url: 'url', source: 'source', has_url: true, has_source: true }
      subject.addTerm("Test", 1, "url", "source");
      expect(subject.terms[0]).to.eql(result);
    });
  });
  describe('#refreshResults', function() {
    beforeEach(function() {
      subject.terms = [{ term: 'Test', total: 1, url: 'url', source: 'source' }];
    });
    it("shows all terms", function() {
    });
    it("calls handlebars template", function() {
    });
  });
  describe('#endpoint', function() {
    it('returns the path to the servers realtime endpoint', function() {
      expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:pageViews&dimensions=ga:pageTitle,ga:pagePath,rt:source,rt:minutesAgo,rt:deviceCategory&sort=rt:minutesAgo&max-results=10000');
    });
    context('with profileId', function() {
      beforeEach(function() {
        window.matrix.settings = {
          profileId: 'Test'
        };
      });
      it('returns correct profile Id in the endpoint path', function() {
      expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:pageViews&dimensions=ga:pageTitle,ga:pagePath,rt:source,rt:minutesAgo,rt:deviceCategory&sort=rt:minutesAgo&max-results=10000');
      });
    });
  });
});
<commit_msg>Add more tests<commit_after>describe('traffic', function() {
  beforeEach(function() {
    window.matrix.settings = {
      profileId: ''
    };
    subject =  window.matrix.landing;
    sandbox = sinon.sandbox.create();
    server = sinon.fakeServer.create();
  });
  afterEach(function() {
    sandbox.restore();
    server.restore();
  });
  describe('#init', function() {
    beforeEach(function() {
      $('body').append('

');
      sandbox.stub(Handlebars, 'compile');
    });
    it("calls reload", function() {
      mock = sandbox.mock(subject).expects("reload").once();
      subject.init();
      mock.verify();
    });
    it("calls reload with interval of 1 minute", function() {
      clock = sinon.useFakeTimers(Date.now());
      mock = sandbox.mock(subject).expects("reload").twice();
      subject.init();
      clock.tick(60000);
      mock.verify();
      clock.restore();
    });
  });
  describe('#reload', function() {
    it("calls endpoint", function() {
      sandbox.stub(xhr, "json");
      mock = sandbox.mock(subject).expects("endpoint").once();
      subject.reload();
      mock.verify();
    });
    context('json returned', function(){
      beforeEach(function() {
        stub = sandbox.stub(xhr, 'json');
      });
      it("calls parseResponse", function() {
        mock = sandbox.mock(subject).expects("parseResponse").once();
        subject.reload();
        stub.callArgWith(1, {}, {});
        mock.verify();
      });
    });
  });
  describe('#parseResponse', function() {
    context("error parsing json", function() {
      it("returns withpout parsing", function() {
        mock = sandbox.mock(subject).expects("parseData").never();
        subject.parseResponse({}, null);
        mock.verify();
      });
      it("does not refresh the results", function() {
        mock = sandbox.mock(subject).expects("refreshResults").never();
        subject.parseResponse({}, null);
        mock.verify();
      });
    });
    context("no error parsing json", function() {
      context("has data from GA", function() {
        it("calls parseData", function() {
          sandbox.stub(subject, 'refreshResults');
          mock = sandbox.mock(subject).expects("parseData").once();
          subject.parseResponse(null, {rows: []});
          mock.verify();
        });
        it("refreshes the results", function() {
          mock = sandbox.mock(subject).expects("refreshResults").once();
          subject.parseResponse(null, {rows: []});
          mock.verify();
        });
      });
      context("no rows (no data from GA)", function() {
        it("does not call parseData", function() {
          mock = sandbox.mock(subject).expects("parseData").never();
          subject.parseResponse(null, {});
          mock.verify();
        });
      });
    });
  });
  describe('#parseData', function() {
    beforeEach(function() {
      data = { rows: [["Titel 1","url 1","(not set)","00","1"],["Titel 2","url 2","(not set)","00","1"],["Titel 3","url 3","(not set)","01","3"],["Titel 4","url 4","(not set)","02","3"]] };
    });
    it("calls addTerm for every row less than two minutes ago", function() {
      mock = sandbox.mock(subject).expects("addTerm").thrice();
      subject.parseData(data);
      mock.verify();
    });
    it("calls addTerm for every row", function() {
      data = { rows: [["Titel 1","url 1","(not set)","00","DESKTOP","1"]] };
      mock = sandbox.mock(subject).expects("addTerm").withArgs("Titel 1", 1, "url 1", "(not set)");
      subject.parseData(data);
      mock.verify();
    });
    context('Search Term', function() {
      beforeEach(function(){
        data = { rows: [["Search", "url", "source", "10"]]};
      });
      it("does not call addTerm for the row", function() {
        mock = sandbox.mock(subject).expects("addTerm").never();
        subject.parseData(data);
        mock.verify();
      });
    });
  });
  describe('#addTerm', function() {
    beforeEach(function() {
      subject.terms = [];
    });
    it("adds new items to terms", function() {
      result = { term: 'Test', total: 1, url: 'url', source: 'source', has_url: true, has_source: true }
      subject.addTerm("Test", 1, "url", "source");
      expect(subject.terms[0]).to.eql(result);
    });
  });
  describe('#refreshResults', function() {
    beforeEach(function() {
      subject.terms = [{ term: 'Test', total: 1, url: 'url', source: 'source' }];
    });
    it("shows all terms", function() {
    });
    it("calls handlebars template", function() {
      mock = sandbox.mock(templateHelper).expects('prependTemplate').once();
      subject.refreshResults();
      mock.verify();
    });
  });
  describe('#endpoint', function() {
    it('returns the path to the servers realtime endpoint', function() {
      expect(subject.endpoint()).to.eql('/realtime?ids=ga:&metrics=rt:pageViews&dimensions=ga:pageTitle,ga:pagePath,rt:source,rt:minutesAgo,rt:deviceCategory&sort=rt:minutesAgo&max-results=10000');
    });
    context('with profileId', function() {
      beforeEach(function() {
        window.matrix.settings = {
          profileId: 'Test'
        };
      });
      it('returns correct profile Id in the endpoint path', function() {
      expect(subject.endpoint()).to.eql('/realtime?ids=ga:Test&metrics=rt:pageViews&dimensions=ga:pageTitle,ga:pagePath,rt:source,rt:minutesAgo,rt:deviceCategory&sort=rt:minutesAgo&max-results=10000');
      });
    });
  });
  describe("safeTerm", function() {
    context("email address", function() {
      it("is not safe", function() {
        expect(subject.safeTerm("iw@jwi.de")).to.eq(false);
      });
    });
    context("just numbers", function() {
      it("is not safe", function() {
        expect(subject.safeTerm("432913")).to.eq(false);
      });
    });
    context("503 request", function() {
      it("is not safe", function() {
        expect(subject.safeTerm("Sorry, we are experiencing technical difficulties (503 error)")).to.eq(false);
      });
    });
  });
});
<|endoftext|>


<commit_before>/**@module app-kernel*/
modules.define('app-kernel', [
    'request-listener', 'app-router-base', 'BEMTREE', 'BEMHTML', 'pages', 'app-logger'
], function (provide, RequestListener, appRouterBase, BEMTREE, BEMHTML, pages, logger) {
    "use strict";

    /**
     * @typedef {Object} RequestData
     * @property {{url: String, method: String, headers: {host: String}} request
     * @property {Route} route
     * @property {ApiRequester} apiRequester
     * @property {{error: String, handled: ?Boolean, response: [{statusCode: Number, statusText: String}]}} error
     */

    /**
     * @class AppKernel
     * @exports
     */
    provide(/**@lends AppKernel.prototype*/{

        getDefaultParams: function () {
            return {
                page404: 'page-404',
                page403: 'page-403',
                page500: 'page-500'
            };
        },

        onSetMod: {
            js: {
                /**
                 * @constructs
                 */
                inited: function () {
                    this._initPages(function () {
                        this._initRequestListener();
                    });
                }
            }
        },

        /**
         * @returns {Array.<String>}
         * @private
         */
        _getPagesNames: function () {
            return pages;
        },

        /**
         * @param {Function} callback
         * @private
         */
        _initPages: function (callback) {
            var pages = this._getPagesNames();
            modules.require(pages, function () {
                this._pages = Array.prototype.slice.call(arguments).reduce(function (pages, Page) {
                    pages[Page.getRoute()] = Page;
                    return pages;
                }, {});
                callback.call(this);
            }.bind(this));
        },

        /**
         * @returns {{}}
         * @protected
         */
        _getRequestListenerParams: function () {
            return {};
        },

        /**
         * @private
         */
        _initRequestListener: function () {
            this._requestListener = new RequestListener(null, this._getRequestListenerParams());
            this._requestListener.on('request', this._onRequest, this);
        },

        /**
         * @param request
         * @returns {?Route}
         * @private
         */
        _getRoute: function (request) {
            return appRouterBase.match({
                path: request.url,
                method: request.method
            });
        },

        /**
         * @param {Event} e
         * @param {Object} data
         * @listens RequestListener#request
         * @private
         */
        _onRequest: function (e, data) {
            this._processRequest(this._fillRequestData(data));
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _processRequest: function (data) {
            this._processPage(data.route.id, data);
        },

        /**
         * @param {RequestData} data
         * @returns {RequestData}
         * @protected
         */
        _fillRequestData: function (data) {
            var route = data.route || this._getRoute(data.request);

            if (!route) {
                logger.info('Route for request ', data.request.url, ' not found');
                route = {id: this.params.page404};
            }

            data.route = route;
            return data;
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _onPageProcessSuccess: function (data) {
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _onPageProcessError: function (data) {
            var e = data.error;
            if (e.handled) {
                logger.error(data);
                throw new Error(data);
            }
            e.handled = true;
            var statusCode = e.response ? e.response.statusCode : undefined;
            if (statusCode === 404) {
                this._handlePage404Error(data);
            } else if (statusCode === 403) {
                this._handlePage403Error(data);
            } else if (e.redirect) {
                this._redirect(e.path, data);
            } else {
                this._handlePageError(data);
            }
        },

        /**
         * @param {String} pageName
         * @param {RequestData} data
         * @param {String} level 'error' or 'info'
         * @private
         */
        _redirectWithError: function (pageName, data, level) {
            var e = data.error,
                request = data.request;
            this._processPage(pageName, data);
            logger[level]('Error process page', request.url, request.method, level === 'error' && e.stack ? e.stack : e);
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _handlePage404Error: function (data) {
            this._redirectWithError(this.params.page404, data, 'info');
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _handlePage403Error: function (data) {
            this._redirectWithError(this.params.page403, data, 'info');
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _handlePageError: function (data) {
            this._redirectWithError(this.params.page500, data, 'error');
        },

        /**
         * @param {String} page
         * @param {RequestData} data
         * @returns {vow:Promise}
         * @protected
         */
        _processPage: function (page, data) {
            var Page = this._pages[page];

            if (!Page) {
                var errorMessage = 'Page "' + page + '" not found';
                logger.error(errorMessage, data.request.url);
                throw new Error(errorMessage);
            }

            logger.info('Start process page', page);
            var promise = BEMTREE.apply(this._getBEMJSON(Page, data), data.apiRequester)
                .then(function (bemjson) {
                    this._writeResponse(BEMHTML.apply(bemjson), data, Page);
                    return data;
                }, this);
            return this._postProcessPage(promise, data);
        },

        /**
         * @param {vow:Promise} promise
         * @param {RequestData} data
         * @returns {vow:Promise}
         * @protected
         */
        _postProcessPage: function (promise, data) {
            return promise.then(function () {
                return this._onPageProcessSuccess(data);
            }, function (e) {
                data.error = e;
                return this._onPageProcessError(data);
            }, this);
        },

        /**
         * @param {String} html
         * @param {RequestData} data
         * @param {Function} Page
         * @protected
         */
        _writeResponse: function (html, data, Page) {

        },

        /**
         * @param {String} url
         * @param {RequestData} data
         * @protected
         */
        _redirect: function (url, data) {
        },

        /**
         * @param {Function} Page
         * @param {RequestData} data
         * @returns {Object}
         * @protected
         */
        _getBEMJSON: function (Page, data) {
            return this._getPageContentBEMJSON(Page, data);
        },

        /**
         * @param {Function} Page
         * @param {RequestData} data
         * @returns {Object}
         * @protected
         */
        _getPageContentBEMJSON: function (Page, data) {
            return {
                block: Page.getName(),
                js: true,
                request: data.request,
                route: data.route
            };
        }
    });
});
<commit_msg>Improve error handling. Closes #11.<commit_after>/**@module app-kernel*/
modules.define('app-kernel', [
    'request-listener', 'app-router-base', 'BEMTREE', 'BEMHTML', 'pages', 'app-logger', 'vow'
], function (provide, RequestListener, appRouterBase, BEMTREE, BEMHTML, pages, logger, Vow) {
    "use strict";

    /**
     * @typedef {Object} RequestData
     * @property {{url: String, method: String, headers: {host: String}} request
     * @property {Route} route
     * @property {ApiRequester} apiRequester
     * @property {{error: String, handled: ?Boolean, response: [{statusCode: Number, statusText: String}]}} error
     */

    /**
     * @class AppKernel
     * @exports
     */
    provide(/**@lends AppKernel.prototype*/{

        getDefaultParams: function () {
            return {
                page404: 'page-404',
                page403: 'page-403',
                page500: 'page-500'
            };
        },

        onSetMod: {
            js: {
                /**
                 * @constructs
                 */
                inited: function () {
                    this._initPages(function () {
                        this._initRequestListener();
                    });
                }
            }
        },

        /**
         * @returns {Array.<String>}
         * @private
         */
        _getPagesNames: function () {
            return pages;
        },

        /**
         * @param {Function} callback
         * @private
         */
        _initPages: function (callback) {
            var pages = this._getPagesNames();
            modules.require(pages, function () {
                this._pages = Array.prototype.slice.call(arguments).reduce(function (pages, Page) {
                    pages[Page.getRoute()] = Page;
                    return pages;
                }, {});
                callback.call(this);
            }.bind(this));
        },

        /**
         * @returns {{}}
         * @protected
         */
        _getRequestListenerParams: function () {
            return {};
        },

        /**
         * @private
         */
        _initRequestListener: function () {
            this._requestListener = new RequestListener(null, this._getRequestListenerParams());
            this._requestListener.on('request', this._onRequest, this);
        },

        /**
         * @param request
         * @returns {?Route}
         * @private
         */
        _getRoute: function (request) {
            return appRouterBase.match({
                path: request.url,
                method: request.method
            });
        },

        /**
         * @param {Event} e
         * @param {Object} data
         * @listens RequestListener#request
         * @private
         */
        _onRequest: function (e, data) {
            this._processRequest(this._fillRequestData(data));
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _processRequest: function (data) {
            this._processPage(data.route.id, data);
        },

        /**
         * @param {RequestData} data
         * @returns {RequestData}
         * @protected
         */
        _fillRequestData: function (data) {
            var route = data.route || this._getRoute(data.request);

            if (!route) {
                logger.info('Route for request ', data.request.url, ' not found');
                route = {id: this.params.page404};
            }

            data.route = route;
            return data;
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _onPageProcessSuccess: function (data) {
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _onPageProcessError: function (data) {
            var e = data.error;
            if (e.handled) {
                logger.error(data);
                throw new Error(data);
            }
            e.handled = true;
            var statusCode = e.response ? e.response.statusCode : undefined;
            if (statusCode === 404) {
                this._handlePage404Error(data);
            } else if (statusCode === 403) {
                this._handlePage403Error(data);
            } else if (e.redirect) {
                this._redirect(e.path, data);
            } else {
                this._handlePageError(data);
            }
        },

        /**
         * @param {String} pageName
         * @param {RequestData} data
         * @param {String} level 'error' or 'info'
         * @private
         */
        _redirectWithError: function (pageName, data, level) {
            var e = data.error,
                request = data.request;
            this._processPage(pageName, data);
            logger[level]('Error process page', request.url, request.method, level === 'error' && e.stack ? e.stack : e);
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _handlePage404Error: function (data) {
            this._redirectWithError(this.params.page404, data, 'info');
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _handlePage403Error: function (data) {
            this._redirectWithError(this.params.page403, data, 'info');
        },

        /**
         * @param {RequestData} data
         * @protected
         */
        _handlePageError: function (data) {
            this._redirectWithError(this.params.page500, data, 'error');
        },

        /**
         * @param {String} page
         * @param {RequestData} data
         * @returns {vow:Promise}
         * @protected
         */
        _processPage: function (page, data) {
            var Page = this._pages[page];

            if (!Page) {
                var errorMessage = 'Page "' + page + '" not found';
                logger.error(errorMessage, data.request.url);
                logger.error('Is "' + page + '" in the bemdecl.js file?');
                data.error = new Error(errorMessage);
                if (this._pages[this.params.page404]) {
                    this._handlePage404Error(data);
                } else if (this._pages[this.params.page500]) {
                    this._handlePageError(data);
                } else {
                    throw data.error;
                }
                return;
            }

            logger.info('Start process page', page);
            var promise;
            try {
                promise = BEMTREE.apply(this._getBEMJSON(Page, data), data.apiRequester)
                    .then(function (bemjson) {
                        this._writeResponse(BEMHTML.apply(bemjson), data, Page);
                        return data;
                    }, this);
            } catch (e) {
                promise = Vow.reject(e);
            }
            return this._postProcessPage(promise, data);
        },

        /**
         * @param {vow:Promise} promise
         * @param {RequestData} data
         * @returns {vow:Promise}
         * @protected
         */
        _postProcessPage: function (promise, data) {
            return promise.then(function () {
                return this._onPageProcessSuccess(data);
            }, function (e) {
                data.error = e;
                return this._onPageProcessError(data);
            }, this);
        },

        /**
         * @param {String} html
         * @param {RequestData} data
         * @param {Function} Page
         * @protected
         */
        _writeResponse: function (html, data, Page) {

        },

        /**
         * @param {String} url
         * @param {RequestData} data
         * @protected
         */
        _redirect: function (url, data) {
        },

        /**
         * @param {Function} Page
         * @param {RequestData} data
         * @returns {Object}
         * @protected
         */
        _getBEMJSON: function (Page, data) {
            return this._getPageContentBEMJSON(Page, data);
        },

        /**
         * @param {Function} Page
         * @param {RequestData} data
         * @returns {Object}
         * @protected
         */
        _getPageContentBEMJSON: function (Page, data) {
            return {
                block: Page.getName(),
                js: true,
                request: data.request,
                route: data.route
            };
        }
    });
});
<|endoftext|>


<commit_before>addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;

function sortables_init() {
		var lastAssignedId = 0;
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
				if (!thisTbl.id) {
      		thisTbl.id = 'sortableTable'+this.lastAssignedId++;
    		}
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
            //initTable(thisTbl.id);
            ts_makeSortable(thisTbl);
        }
    }
}

function ts_makeSortable(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;

    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = ts_getInnerText(cell);
        cell.innerHTML = '' +
        txt+'   ';
    }
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";

	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk,clid) {
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = ts_getInnerText(span);
    var td = lnk.parentNode;
    while(td.nodeName.toLowerCase() != 'td')
        td = td.parentNode;
    var column = clid || td.cellIndex;
    var table = getParent(td,'TABLE');

    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^[$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+\s*(bytes|b|kb|tb|gb|mb)$/i)) sortfn = ts_sort_filesize;
    // Special cases for our mailbox lists
    if (itm.match(/^(Empty|Unlimited)$/)) sortfn = ts_sort_filesize;
    if (itm.match(/^[\d\.]+$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
    for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }

    newRows.sort(sortfn);

    if (span.getAttribute("sortdir") == 'down') {
        ARROW = '  ↑';
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
        ARROW = '  ↓';
        span.setAttribute('sortdir','down');
    }

    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}

    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '   ';
            }
        }
    }

    span.innerHTML = ARROW;
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa.length == 10) {
        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
    } else {
        yr = aa.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
    }
    if (bb.length == 10) {
        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
    } else {
        yr = bb.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
    }
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}

function ts_sort_currency(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

// handles file sizes, simple numerics, and Unlimited/Empty/None special cases
function ts_sort_filesize(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();

    if (aa.length == 0) return -1;
    else if (bb.length == 0) return 1;

    var regex = /^([\d\.]*|none|empty|unlimited)\s*(bytes|b|kb|tb|gb|mb)?$/i;
    matchA = aa.match(regex);
    matchB = bb.match(regex);

    // Give file size class an integer value, if we don't already have one
    if (matchA[1] == 'none') valA = -999;
    else if (matchA[1] == 'empty') valA = 0;
    else if (matchA[1] == '0') valA = 0;
    else if (matchA[1] == 'unlimited') valA = 999;
    else if (matchA[2] == 'b' || matchA[2] == 'bytes') valA = 1;
    else if (matchA[2] == undefined || matchA[2] == '') valA = 1;
    else if (matchA[2] == 'kb') valA = 2;
    else if (matchA[2] == 'mb') valA = 3;
    else if (matchA[2] == 'gb') valA = 4;
    else if (matchA[2] == 'tb') valA = 5;

    if (matchB[1] == 'none') valB = -999;
    else if (matchB[1] == 'empty') valB = 0;
    else if (matchB[1] == '0') valB = 0;
    else if (matchB[1] == 'unlimited') valB = 999;
    else if (matchB[2] == 'b' || matchB[2] == 'bytes') valB = 1;
    else if (matchB[2] == undefined || matchB[2] == '') valB = 1;
    else if (matchB[2] == 'kb') valB = 2;
    else if (matchB[2] == 'mb') valB = 3;
    else if (matchB[2] == 'gb') valB = 4;
    else if (matchB[2] == 'tb') valB = 5;

    if (valA == valB) {
			if ( isNaN(matchA[1])) return -1;
      if ( isNaN(matchB[1])) return 1;
      // Files are in the same size class kb/gb/mb/etc
      // just do a numeric sort on the file size
			return matchA[1]-matchB[1];
    } else if (valA < valB) {
      return -1;
    } else if (valA > valB) {
      return 1;
    }
}

function ts_sort_numeric(a,b) {
    aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX]));
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function ts_sort_default(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}
<commit_msg>Allow percentage sorting<commit_after>addEvent(window, "load", sortables_init);

var SORT_COLUMN_INDEX;

function sortables_init() {
		var lastAssignedId = 0;
    // Find all tables with class sortable and make them sortable
    if (!document.getElementsByTagName) return;
    tbls = document.getElementsByTagName("table");
    for (ti=0;ti<tbls.length;ti++) {
        thisTbl = tbls[ti];
				if (!thisTbl.id) {
      		thisTbl.id = 'sortableTable'+this.lastAssignedId++;
    		}
        if (((' '+thisTbl.className+' ').indexOf("sortable") != -1) && (thisTbl.id)) {
            //initTable(thisTbl.id);
            ts_makeSortable(thisTbl);
        }
    }
}

function ts_makeSortable(table) {
    if (table.rows && table.rows.length > 0) {
        var firstRow = table.rows[0];
    }
    if (!firstRow) return;

    // We have a first row: assume it's the header, and make its contents clickable links
    for (var i=0;i<firstRow.cells.length;i++) {
        var cell = firstRow.cells[i];
        var txt = ts_getInnerText(cell);
        cell.innerHTML = '' +
        txt+'   ';
    }
}

function ts_getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";

	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += ts_getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

function ts_resortTable(lnk,clid) {
    // get the span
    var span;
    for (var ci=0;ci<lnk.childNodes.length;ci++) {
        if (lnk.childNodes[ci].tagName && lnk.childNodes[ci].tagName.toLowerCase() == 'span') span = lnk.childNodes[ci];
    }
    var spantext = ts_getInnerText(span);
    var td = lnk.parentNode;
    while(td.nodeName.toLowerCase() != 'td')
        td = td.parentNode;
    var column = clid || td.cellIndex;
    var table = getParent(td,'TABLE');

    // Work out a type for the column
    if (table.rows.length <= 1) return;
    var itm = ts_getInnerText(table.rows[1].cells[column]);
    sortfn = ts_sort_caseinsensitive;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^\d\d[\/-]\d\d[\/-]\d\d$/)) sortfn = ts_sort_date;
    if (itm.match(/^[$]/)) sortfn = ts_sort_currency;
    if (itm.match(/^[\d\.]+\s*(bytes|b|kb|tb|gb|mb)$/i)) sortfn = ts_sort_filesize;
    // Special cases for our mailbox lists
    if (itm.match(/^(Empty|Unlimited)$/)) sortfn = ts_sort_filesize;
    if (itm.match(/^[\d\.]+%?$/)) sortfn = ts_sort_numeric;
    SORT_COLUMN_INDEX = column;
    var firstRow = new Array();
    var newRows = new Array();
    for (i=0;i<table.rows[0].length;i++) { firstRow[i] = table.rows[0][i]; }
    for (j=1;j<table.rows.length;j++) { newRows[j-1] = table.rows[j]; }

    newRows.sort(sortfn);

    if (span.getAttribute("sortdir") == 'down') {
        ARROW = '  ↑';
        newRows.reverse();
        span.setAttribute('sortdir','up');
    } else {
        ARROW = '  ↓';
        span.setAttribute('sortdir','down');
    }

    // We appendChild rows that already exist to the tbody, so it moves them rather than creating new ones
    // don't do sortbottom rows
    for (i=0;i<newRows.length;i++) { if (!newRows[i].className || (newRows[i].className && (newRows[i].className.indexOf('sortbottom') == -1))) table.tBodies[0].appendChild(newRows[i]);}
    // do sortbottom rows only
    for (i=0;i<newRows.length;i++) { if (newRows[i].className && (newRows[i].className.indexOf('sortbottom') != -1)) table.tBodies[0].appendChild(newRows[i]);}

    // Delete any other arrows there may be showing
    var allspans = document.getElementsByTagName("span");
    for (var ci=0;ci<allspans.length;ci++) {
        if (allspans[ci].className == 'sortarrow') {
            if (getParent(allspans[ci],"table") == getParent(lnk,"table")) { // in the same table as us?
                allspans[ci].innerHTML = '   ';
            }
        }
    }

    span.innerHTML = ARROW;
}

function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}
function ts_sort_date(a,b) {
    // y2k notes: two digit years less than 50 are treated as 20XX, greater than 50 are treated as 19XX
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa.length == 10) {
        dt1 = aa.substr(6,4)+aa.substr(3,2)+aa.substr(0,2);
    } else {
        yr = aa.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt1 = yr+aa.substr(3,2)+aa.substr(0,2);
    }
    if (bb.length == 10) {
        dt2 = bb.substr(6,4)+bb.substr(3,2)+bb.substr(0,2);
    } else {
        yr = bb.substr(6,2);
        if (parseInt(yr) < 50) { yr = '20'+yr; } else { yr = '19'+yr; }
        dt2 = yr+bb.substr(3,2)+bb.substr(0,2);
    }
    if (dt1==dt2) return 0;
    if (dt1<dt2) return -1;
    return 1;
}

function ts_sort_currency(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).replace(/[^0-9.]/g,'');
    return parseFloat(aa) - parseFloat(bb);
}

// handles file sizes, simple numerics, and Unlimited/Empty/None special cases
function ts_sort_filesize(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();

    if (aa.length == 0) return -1;
    else if (bb.length == 0) return 1;

    var regex = /^([\d\.]*|none|empty|unlimited)\s*(bytes|b|kb|tb|gb|mb)?$/i;
    matchA = aa.match(regex);
    matchB = bb.match(regex);

    // Give file size class an integer value, if we don't already have one
    if (matchA[1] == 'none') valA = -999;
    else if (matchA[1] == 'empty') valA = 0;
    else if (matchA[1] == '0') valA = 0;
    else if (matchA[1] == 'unlimited') valA = 999;
    else if (matchA[2] == 'b' || matchA[2] == 'bytes') valA = 1;
    else if (matchA[2] == undefined || matchA[2] == '') valA = 1;
    else if (matchA[2] == 'kb') valA = 2;
    else if (matchA[2] == 'mb') valA = 3;
    else if (matchA[2] == 'gb') valA = 4;
    else if (matchA[2] == 'tb') valA = 5;

    if (matchB[1] == 'none') valB = -999;
    else if (matchB[1] == 'empty') valB = 0;
    else if (matchB[1] == '0') valB = 0;
    else if (matchB[1] == 'unlimited') valB = 999;
    else if (matchB[2] == 'b' || matchB[2] == 'bytes') valB = 1;
    else if (matchB[2] == undefined || matchB[2] == '') valB = 1;
    else if (matchB[2] == 'kb') valB = 2;
    else if (matchB[2] == 'mb') valB = 3;
    else if (matchB[2] == 'gb') valB = 4;
    else if (matchB[2] == 'tb') valB = 5;

    if (valA == valB) {
			if ( isNaN(matchA[1])) return -1;
      if ( isNaN(matchB[1])) return 1;
      // Files are in the same size class kb/gb/mb/etc
      // just do a numeric sort on the file size
			return matchA[1]-matchB[1];
    } else if (valA < valB) {
      return -1;
    } else if (valA > valB) {
      return 1;
    }
}

function ts_sort_numeric(a,b) {
    aa = parseFloat(ts_getInnerText(a.cells[SORT_COLUMN_INDEX]));
    if (isNaN(aa)) aa = 0;
    bb = parseFloat(ts_getInnerText(b.cells[SORT_COLUMN_INDEX]));
    if (isNaN(bb)) bb = 0;
    return aa-bb;
}

function ts_sort_caseinsensitive(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]).toLowerCase();
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]).toLowerCase();
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function ts_sort_default(a,b) {
    aa = ts_getInnerText(a.cells[SORT_COLUMN_INDEX]);
    bb = ts_getInnerText(b.cells[SORT_COLUMN_INDEX]);
    if (aa==bb) return 0;
    if (aa<bb) return -1;
    return 1;
}

function addEvent(elm, evType, fn, useCapture)
// addEvent and removeEvent
// cross-browser event handling for IE5+,  NS6 and Mozilla
// By Scott Andrew
{
  if (elm.addEventListener){
    elm.addEventListener(evType, fn, useCapture);
    return true;
  } else if (elm.attachEvent){
    var r = elm.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
}
<|endoftext|>


<commit_before>/* eslint-env node */
module.exports = {
  // description: ''

  afterInstall(options) {
    // Perform extra work here.
    return this.addPackagesToProject([{
      name: 'sweetalert2',
      target: '6.10.1'
    }, {
      name: 'select2',
      target: '4.0.3'
    }]);
  }
};
<commit_msg>fix: correção de bug de instalação<commit_after>/* eslint-env node */
module.exports = {
  // description: ''
  normalizeEntityName: function() {}, // Isso precisa ficar aqui, assim mesmo.

  afterInstall(options) {
    // Perform extra work here.
    return this.addPackagesToProject([{
      name: 'sweetalert2',
      target: '6.10.1'
    }, {
      name: 'select2',
      target: '4.0.3'
    }]);
  }
};
<|endoftext|>


<commit_before>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @providesModule createExamplePage
 * @flow
 */
'use strict';

var React = require('react-native');
var UIExplorerBlock = require('./UIExplorerBlock');
var UIExplorerPage = require('./UIExplorerPage');

var invariant = require('invariant');

class Example extends React.Component {
  title: string;
  description: string;
}

type ExampleModule = {
  title: string;
  description: string;
  examples: Array<Example>;
};

var createExamplePage = function(title: ?string, exampleModule: ExampleModule)
  : ReactClass<any, any, any> {
  invariant(!!exampleModule.examples, 'The module must have examples');

  var ExamplePage = React.createClass({
    statics: {
      title: exampleModule.title,
      description: exampleModule.description,
    },

    getBlock: function(example, i) {
      // Hack warning: This is a hack because the www UI explorer requires
      // renderComponent to be called.
      var originalRenderComponent = React.renderComponent;
      var originalRender = React.render;
      var renderedComponent;
      // TODO remove typecasts when Flow bug #6560135 is fixed
      // and workaround is removed from react-native.js
      (React: Object).render = (React: Object).renderComponent = function(element, container) {
        renderedComponent = element;
      };
      var result = example.render(null);
      if (result) {
        renderedComponent = result;
      }
      (React: Object).renderComponent = originalRenderComponent;
      (React: Object).render = originalRender;
      return (
        <UIExplorerBlock
          key={i}
          title={example.title}
          description={example.description}>
          {renderedComponent}
        </UIExplorerBlock>
      );
    },

    render: function() {
      return (
        <UIExplorerPage title={title}>
          {exampleModule.examples.map(this.getBlock)}
        </UIExplorerPage>
      );
    }
  });

  return ExamplePage;
};

module.exports = createExamplePage;
<commit_msg>[react-native] Fix example pages requiring React directly<commit_after>/**
 * The examples provided by Facebook are for non-commercial testing and
 * evaluation purposes only.
 *
 * Facebook reserves all rights not expressly granted.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
 * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
 * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *
 * @providesModule createExamplePage
 * @flow
 */
'use strict';

var React = require('react-native');
var ReactIOS = require('ReactIOS');
var UIExplorerBlock = require('./UIExplorerBlock');
var UIExplorerPage = require('./UIExplorerPage');

var invariant = require('invariant');

class Example extends React.Component {
  title: string;
  description: string;
}

type ExampleModule = {
  title: string;
  description: string;
  examples: Array<Example>;
};

var createExamplePage = function(title: ?string, exampleModule: ExampleModule)
  : ReactClass<any, any, any> {
  invariant(!!exampleModule.examples, 'The module must have examples');

  var ExamplePage = React.createClass({
    statics: {
      title: exampleModule.title,
      description: exampleModule.description,
    },

    getBlock: function(example, i) {
      // Hack warning: This is a hack because the www UI explorer requires
      // renderComponent to be called.
      var originalRender = React.render;
      var originalRenderComponent = React.renderComponent;
      var originalIOSRender = ReactIOS.render;
      var originalIOSRenderComponent = ReactIOS.renderComponent;
      var renderedComponent;
      // TODO remove typecasts when Flow bug #6560135 is fixed
      // and workaround is removed from react-native.js
      (React: Object).render =
      (React: Object).renderComponent =
      (ReactIOS: Object).render =
      (ReactIOS: Object).renderComponent =
        function(element, container) {
          renderedComponent = element;
        };
      var result = example.render(null);
      if (result) {
        renderedComponent = result;
      }
      (React: Object).render = originalRender;
      (React: Object).renderComponent = originalRenderComponent;
      (ReactIOS: Object).render = originalIOSRender;
      (ReactIOS: Object).renderComponent = originalIOSRenderComponent;
      return (
        <UIExplorerBlock
          key={i}
          title={example.title}
          description={example.description}>
          {renderedComponent}
        </UIExplorerBlock>
      );
    },

    render: function() {
      return (
        <UIExplorerPage title={title}>
          {exampleModule.examples.map(this.getBlock)}
        </UIExplorerPage>
      );
    }
  });

  return ExamplePage;
};

module.exports = createExamplePage;
<|endoftext|>


<commit_before>// Queue design document
//

var lib = require('./lib')
  , util = require('util')
  , assert = require('assert')
  ;

//
// Constants
//

var TEMPLATE =
  // _id
  // _rev
{ ApproximateNumberOfMessages          : 0
, ApproximateNumberOfMessagesNotVisible: 0
, VisibilityTimeout                    : 30
, CreatedTimestamp                     : null
, LastModifiedTimestamp                : null
, Policy                               : null
, MaximumMessageSize                   : 8192
, MessageRetentionPeriod               : 345600
, QueueArn                             : null

, "views": {
           }

, "validate_doc_update": validate_doc_update
}

function validate_doc_update(newDoc, oldDoc, userCtx, secObj) {
  var NAME = "XXX_name_XXX";

  var for_me = XXX_for_me_XXX;

  if(! /^CQS\//.test(newDoc._id)) // A simple test, hopefully future-proof
    throw({forbidden: "This database is for CQS only"});

  if(! for_me(newDoc))
    return; // Another ddoc will handle this validation.

  var good_keys = [ "_id", "_rev",
                  // TODO
                  ];

  var key;
  for (key in newDoc)
    if(good_keys.indexOf(key) === -1)
      throw({forbidden: "Invalid field: " + key});
}

//
// API
//

function DDoc (queue) {
  var self = this;
  var now = new Date;

  assert.ok(queue.name);
  assert.ok(queue.DefaultVisibilityTimeout);
  self.queue = queue;

  self.copy_template();

  self._id = "_design/CQS/" + queue.name;
  self.CreatedTimestamp = now;
  self.LastModifiedTimestamp = now;
  self.DefaultVisibilityTimeout = queue.DefaultVisibilityTimeout;
}

DDoc.prototype.copy_template = function() {
  var self = this;

  if(self.queue.name.length < 1 || self.queue.name.length > 80)
    throw new Error("Queue name exceeds length max of 80: " + self.queue.name.length)

  var ddoc = templated_ddoc(self.queue.name);
  lib.copy(ddoc, self);
}

module.exports = { "DDoc" : DDoc
                 };

//
// Utilities
//

function templated_ddoc(name) {
  var for_this_ddoc = func_from_template(for_me, {name:name});

  function stringify_functions(obj) {
    var copy = {};

    if(Array.isArray(obj))
      return obj.map(stringify_functions)

    else if(typeof obj === 'object' && obj !== null) {
      Object.keys(obj).forEach(function(key) {
        copy[key] = stringify_functions(obj[key]);
      })
      return copy;
    }

    else if(typeof obj === 'function')
      return func_from_template(obj, {name:name, for_me:for_this_ddoc});

    else
      return lib.JDUP(obj);
  }

  return stringify_functions(TEMPLATE);
}

function func_from_template(func, vals) {
  var name = vals.name;
  if(!name || typeof name !== 'string')
    throw new Error('Invalid queue name: ' + util.inspect(name));

  var src = func.toString();
  src = src.replace(/^function.*?\(/, 'function (');

  src = src.replace(/XXX_(.*?)_XXX/g, function(match, key) {
    return vals[key];
  })
  return src;
}

function for_me(doc) {
  var tester = /^CQS\/XXX_name_XXX\/([a-fA-F0-9]+)$/;
  return tester.test(doc._id);
}
<commit_msg>Don't store the queue object, just the name<commit_after>// Queue design document
//

var lib = require('./lib')
  , util = require('util')
  , assert = require('assert')
  ;

//
// Constants
//

var TEMPLATE =
  // _id
  // _rev
{ ApproximateNumberOfMessages          : 0
, ApproximateNumberOfMessagesNotVisible: 0
, VisibilityTimeout                    : 30
, CreatedTimestamp                     : null
, LastModifiedTimestamp                : null
, Policy                               : null
, MaximumMessageSize                   : 8192
, MessageRetentionPeriod               : 345600
, QueueArn                             : null

, "views": {
           }

, "validate_doc_update": validate_doc_update
}

function validate_doc_update(newDoc, oldDoc, userCtx, secObj) {
  var NAME = "XXX_name_XXX";

  var for_me = XXX_for_me_XXX;

  if(! /^CQS\//.test(newDoc._id)) // A simple test, hopefully future-proof
    throw({forbidden: "This database is for CQS only"});

  if(! for_me(newDoc))
    return; // Another ddoc will handle this validation.

  var good_keys = [ "_id", "_rev",
                  // TODO
                  ];

  var key;
  for (key in newDoc)
    if(good_keys.indexOf(key) === -1)
      throw({forbidden: "Invalid field: " + key});
}

//
// API
//

function DDoc (queue) {
  var self = this;
  var now = new Date;

  assert.ok(queue.name);
  assert.ok(queue.DefaultVisibilityTimeout);

  self.name = queue.name;
  self.copy_template();

  self._id = "_design/CQS/" + queue.name;
  self.CreatedTimestamp = now;
  self.LastModifiedTimestamp = now;
  self.DefaultVisibilityTimeout = queue.DefaultVisibilityTimeout;
}

DDoc.prototype.copy_template = function() {
  var self = this;

  if(self.name.length < 1 || self.name.length > 80)
    throw new Error("Queue name exceeds length max of 80: " + self.name.length)

  var ddoc = templated_ddoc(self.name);
  lib.copy(ddoc, self);
}

module.exports = { "DDoc" : DDoc
                 };

//
// Utilities
//

function templated_ddoc(name) {
  var for_this_ddoc = func_from_template(for_me, {name:name});

  function stringify_functions(obj) {
    var copy = {};

    if(Array.isArray(obj))
      return obj.map(stringify_functions)

    else if(typeof obj === 'object' && obj !== null) {
      Object.keys(obj).forEach(function(key) {
        copy[key] = stringify_functions(obj[key]);
      })
      return copy;
    }

    else if(typeof obj === 'function')
      return func_from_template(obj, {name:name, for_me:for_this_ddoc});

    else
      return lib.JDUP(obj);
  }

  return stringify_functions(TEMPLATE);
}

function func_from_template(func, vals) {
  var name = vals.name;
  if(!name || typeof name !== 'string')
    throw new Error('Invalid queue name: ' + util.inspect(name));

  var src = func.toString();
  src = src.replace(/^function.*?\(/, 'function (');

  src = src.replace(/XXX_(.*?)_XXX/g, function(match, key) {
    return vals[key];
  })
  return src;
}

function for_me(doc) {
  var tester = /^CQS\/XXX_name_XXX\/([a-fA-F0-9]+)$/;
  return tester.test(doc._id);
}
<|endoftext|>


<commit_before>"use strict"

var matrixToCSS = require("matrix-to-css")
var shell = require("gl-now")({clearColor: [0.2, 0.4, 0.8, 1.0]})
var camera = require("game-shell-orbit-camera")(shell)
var renderText = require("gl-render-text")
var mat4 = require("gl-mat4")
var mat3 = require("gl-mat3")
var vec3 = require("gl-vec3")
var quat = require("gl-matrix-quat")
var createMesh = require("gl-mesh")
var glslify = require("glslify")

var texture
var positions = new Array(100)
var mesh
var shader

var cssWorld = document.createElement('div')
cssWorld.style.transformStyle = 'preserve-3d'
cssWorld.style.overflow = 'hidden'
cssWorld.style.pointerEvents = 'none'
cssWorld.style.position = 'absolute'
cssWorld.style.zIndex = '1' // above WebGL canvas

var element = document.createElement('iframe')
//element.src = 'http://browserify.org'
element.src = 'data:text/html,<body bgcolor=purple>'
element.style.width = 256 + 'px'
element.style.height = 256 + 'px'
element.style.position = 'absolute'
element.style.transformStyle = 'preserve-3d'
//element.style.display = 'none'
//element.style.pointerEvents = 'auto' // allow mouse interaction

cssWorld.appendChild(element)
document.body.appendChild(cssWorld)

shell.on("gl-init", function() {
  var gl = shell.gl
  texture = renderText(gl, "Billboard")

  mesh = createMesh(gl,
      [
      [0, 1, 2],
      [3, 1, 2]
       ],
      { "position": [
        [-1, -1, 0],
        [-1, 1, 0],
        [1, -1, 0],
        [1, 1, 0]] })

  shader = glslify({
    inline: true,
    vertex: "/* voxel-decals vertex shader */\
attribute vec3 position;\
\
uniform mat4 projViewModel;\
varying vec4 vColor;\
\
void main() {\
  gl_Position = projViewModel * vec4(position, 1.0);\
  vColor = vec4(gl_Position.x, gl_Position.y, gl_Position.z, 1.0);\
}",

  fragment: "/* voxel-decals fragment shader */\
precision highp float;\
varying vec4 vColor;\
\
void main() {\
  gl_FragColor = vColor;\
}"})(gl)

})

var model = mat4.create()
var s=1/3
mat4.scale(model, model, [s,s,s])

var projViewModel = mat4.create()

var cameraFOVdegrees = 45

var scratch0 = new Float32Array(16)
var scratch1 = new Float32Array(16)

// based on orbit-camera
function simpleCameraView(out) {
  if (!out) out = mat4.create()

  var quaternion = [0,1,0,0]
  var translation = [0,0,-1]
  mat4.fromRotationTranslation(out, quaternion, translation)

  return out
}

shell.on("gl-render", function() {
  var proj = mat4.perspective(mat4.create(), cameraFOVdegrees * Math.PI / 180, shell.width/shell.height, 0.1, 1000.0)
  //var view = camera.view()
  var view = simpleCameraView()

  shader.bind()
  shader.attributes.position.location = 0

  mat4.multiply(projViewModel, proj, view)
  mat4.multiply(projViewModel, projViewModel, model)

  shader.uniforms.projViewModel = projViewModel

  mesh.bind(shader)
  mesh.draw()
  mesh.unbind()

  // CSS world perspective TODO: only on gl-resize -- this doesn't change often
  var cameraFOV = 45
  var screenHeight = shell.height
  var fovPx = 0.5 / Math.tan(cameraFOVdegrees * Math.PI / 360) * screenHeight
  cssWorld.style.perspective = fovPx + 'px'
  cssWorld.style.width = shell.width + 'px'
  cssWorld.style.height = shell.height + 'px'

  // CSS element
  //element.style.transform = 'translateZ(' + fovPx + 'px) ' + matrixToCSS(view) + ' translate3d(' + (shell.width/2) + 'px, ' + (shell.height/2) + 'px, 0)'
  //var matrixWorldInverse = mat4.create()
  //mat4.invert(matrixWorldInverse, view)
  //mat4.transpose(matrixWorldInverse, matrixWorldInverse)
  element.style.transform = matrixToCSS(view)
})
<commit_msg>CSS element dimensions from shell dimensions<commit_after>"use strict"

var matrixToCSS = require("matrix-to-css")
var shell = require("gl-now")({clearColor: [0.2, 0.4, 0.8, 1.0]})
var camera = require("game-shell-orbit-camera")(shell)
var renderText = require("gl-render-text")
var mat4 = require("gl-mat4")
var mat3 = require("gl-mat3")
var vec3 = require("gl-vec3")
var quat = require("gl-matrix-quat")
var createMesh = require("gl-mesh")
var glslify = require("glslify")

var texture
var positions = new Array(100)
var mesh
var shader

var cssWorld = document.createElement('div')
cssWorld.style.transformStyle = 'preserve-3d'
cssWorld.style.overflow = 'hidden'
cssWorld.style.pointerEvents = 'none'
cssWorld.style.position = 'absolute'
cssWorld.style.zIndex = '1' // above WebGL canvas

var element = document.createElement('iframe')
//element.src = 'http://browserify.org'
element.src = 'data:text/html,<body bgcolor=purple>'
element.style.position = 'absolute'
element.style.transformStyle = 'preserve-3d'
//element.style.display = 'none'
//element.style.pointerEvents = 'auto' // allow mouse interaction

cssWorld.appendChild(element)
document.body.appendChild(cssWorld)

shell.on("gl-init", function() {
  var gl = shell.gl
  texture = renderText(gl, "Billboard")

  mesh = createMesh(gl,
      [
      [0, 1, 2],
      [3, 1, 2]
       ],
      { "position": [
        [-1, -1, 0],
        [-1, 1, 0],
        [1, -1, 0],
        [1, 1, 0]] })

  shader = glslify({
    inline: true,
    vertex: "/* voxel-decals vertex shader */\
attribute vec3 position;\
\
uniform mat4 projViewModel;\
varying vec4 vColor;\
\
void main() {\
  gl_Position = projViewModel * vec4(position, 1.0);\
  vColor = vec4(gl_Position.x, gl_Position.y, gl_Position.z, 1.0);\
}",

  fragment: "/* voxel-decals fragment shader */\
precision highp float;\
varying vec4 vColor;\
\
void main() {\
  gl_FragColor = vColor;\
}"})(gl)

})

var model = mat4.create()
var s=1/3
mat4.scale(model, model, [s,s,s])

var projViewModel = mat4.create()

var cameraFOVdegrees = 45

var scratch0 = new Float32Array(16)
var scratch1 = new Float32Array(16)

// based on orbit-camera
function simpleCameraView(out) {
  if (!out) out = mat4.create()

  var quaternion = [0,1,0,0]
  var translation = [0,0,-1]
  mat4.fromRotationTranslation(out, quaternion, translation)

  return out
}

shell.on("gl-render", function() {
  var proj = mat4.perspective(mat4.create(), cameraFOVdegrees * Math.PI / 180, shell.width/shell.height, 0.1, 1000.0)
  //var view = camera.view()
  var view = simpleCameraView()

  shader.bind()
  shader.attributes.position.location = 0

  mat4.multiply(projViewModel, proj, view)
  mat4.multiply(projViewModel, projViewModel, model)

  shader.uniforms.projViewModel = projViewModel

  mesh.bind(shader)
  mesh.draw()
  mesh.unbind()

  // CSS world perspective TODO: only on gl-resize -- this doesn't change often
  var cameraFOV = 45
  var screenHeight = shell.height
  var fovPx = 0.5 / Math.tan(cameraFOVdegrees * Math.PI / 360) * screenHeight
  cssWorld.style.perspective = fovPx + 'px'
  cssWorld.style.width = shell.width + 'px'
  cssWorld.style.height = shell.height + 'px'

  // CSS element
  //element.style.transform = 'translateZ(' + fovPx + 'px) ' + matrixToCSS(view) + ' translate3d(' + (shell.width/2) + 'px, ' + (shell.height/2) + 'px, 0)'
  //var matrixWorldInverse = mat4.create()
  //mat4.invert(matrixWorldInverse, view)
  //mat4.transpose(matrixWorldInverse, matrixWorldInverse)
  element.style.width = (shell.width / 3) + 'px'
  element.style.height = (shell.height / 3) + 'px'
  element.style.transform = matrixToCSS(view)
})
<|endoftext|>


<commit_before>var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
var fs = require('fs');

var browserify_builtins = require('browserify/lib/builtins');
browserify_builtins.child_process = 'child_process.js';
browserify_builtins.fs = require.resolve('browserify-fs'); // TODO: what is the api equivalent of cli -r fs:browserify-fs?
browserify_builtins['graceful-fs'] = browserify_builtins.fs;

var b = browserify();

//b.require('browserify-fs', {expose:'fs'});

//b.transform('brfs');

var textReplacements = [
  [/require\.resolve/g, 'require'], // TODO: what is require.resolve for browserify?

  // semi-dynamic fs.readFileSync()
  [/fs\.readFileSync/g, 'window.staticReadFileSync'],
  [/require\('fs'\)\.readFileSync/g, 'window.staticReadFileSync'],

  // semi-dynamic require()

  // node_modules/npm/lib/npm.js
  [/require\(__dirname\+"\/"\+a\+"\.js"\)/g, 'window.npmCommandRequire(__dirname+"/"+a+".js")'],

  // npm/node_modules/npm-registry-client/index.js
  [/client\[name\] = require\(entry\)/g, 'client[name] = window.npmRegistryClientRequire(entry)'],

  // node_modules/npm/node_modules/request somewhere
  // Disable credentials in XHR for CORS proxies with Access-Control-Allow-Origin: *
  // TODO: surely a better way to make this change
  [/params.withCredentials = true/g, 'params.withCredentials = false'],

  // download tarball URLs also through CORS proxy TODO: more general fix, please
  [/url\.parse\(dist\.tarball\)/g, 'url.parse(("http://cors.maxogden.com/"+dist.tarball))'],
];

// Included file data for staticReadFileSync; this is similar to
// brfs's fs.readFileSync transclusion but ours is looked up dynamically,
// because brfs can only replace files from static source code analysis.
var preloadedFilenames = [
  'node_modules/browserify/node_modules/umd/template.js',
  'node_modules/browserify/node_modules/browser-pack/_prelude.js',
  'node_modules/npm/package.json',
];

// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
  var data = '';
  return through(write, end);

  function write(buf) { data += buf; }
  function end() {
    for (var i = 0; i < textReplacements.length; i += 1) {
      var regex = textReplacements[i][0];
      var replacement = textReplacements[i][1];

      data  = data.replace(regex, replacement);
    }

    this.queue(data);
    this.queue(null);
  };
}, { global: true });

b.add('./webnpm.js');

var preloadedReadFileSyncs = {};
for (var i = 0; i < preloadedFilenames.length; i += 1) {
  var path = preloadedFilenames[i];
  preloadedReadFileSyncs['/' + path] = JSON.stringify(fs.readFileSync(path, 'utf8'));
}

process.stdout.write('window.preloadedReadFileSyncs = ' + JSON.stringify(preloadedReadFileSyncs) + '\n;');

b.bundle().pipe(process.stdout);

<commit_msg>Apply the same http-browserify resume workaround in npm-registry-client as for request GH-10<commit_after>var browserify = require('browserify');
var brfs = require('brfs');
var through = require('through');
var fs = require('fs');

var browserify_builtins = require('browserify/lib/builtins');
browserify_builtins.child_process = 'child_process.js';
browserify_builtins.fs = require.resolve('browserify-fs'); // TODO: what is the api equivalent of cli -r fs:browserify-fs?
browserify_builtins['graceful-fs'] = browserify_builtins.fs;

var b = browserify();

//b.require('browserify-fs', {expose:'fs'});

//b.transform('brfs');

var textReplacements = [
  [/require\.resolve/g, 'require'], // TODO: what is require.resolve for browserify?

  // semi-dynamic fs.readFileSync()
  [/fs\.readFileSync/g, 'window.staticReadFileSync'],
  [/require\('fs'\)\.readFileSync/g, 'window.staticReadFileSync'],

  // semi-dynamic require()

  // node_modules/npm/lib/npm.js
  [/require\(__dirname\+"\/"\+a\+"\.js"\)/g, 'window.npmCommandRequire(__dirname+"/"+a+".js")'],

  // npm/node_modules/npm-registry-client/index.js
  [/client\[name\] = require\(entry\)/g, 'client[name] = window.npmRegistryClientRequire(entry)'],

  // node_modules/npm/node_modules/request somewhere
  // Disable credentials in XHR for CORS proxies with Access-Control-Allow-Origin: *
  // TODO: surely a better way to make this change
  [/params.withCredentials = true/g, 'params.withCredentials = false'],

  // download tarball URLs also through CORS proxy TODO: more general fix, please
  [/url\.parse\(dist\.tarball\)/g, 'url.parse(("http://cors.maxogden.com/"+dist.tarball))'],

  // node_modules/npm/node_modules/npm-registry-client/lib/fetch.js
  // workaround https://github.com/substack/http-browserify/issues/81 Response inherits from Stream instead of Stream.Readable
  // note: the 'request' module has the same workaround
  [/          \/\/ Work around bug in node v0\.10\.0 where the CryptoStream\s+\/\/ gets stuck and never starts reading again\.\s+res\.resume\(\)/g, 'if (res.resume) res.resume()'],

];

// Included file data for staticReadFileSync; this is similar to
// brfs's fs.readFileSync transclusion but ours is looked up dynamically,
// because brfs can only replace files from static source code analysis.
var preloadedFilenames = [
  'node_modules/browserify/node_modules/umd/template.js',
  'node_modules/browserify/node_modules/browser-pack/_prelude.js',
  'node_modules/npm/package.json',
];

// directly include rfile TODO: use brfs, but it replaces fs.readFileSync
b.transform(function(s) {
  var data = '';
  return through(write, end);

  function write(buf) { data += buf; }
  function end() {
    for (var i = 0; i < textReplacements.length; i += 1) {
      var regex = textReplacements[i][0];
      var replacement = textReplacements[i][1];

      data  = data.replace(regex, replacement);
    }

    this.queue(data);
    this.queue(null);
  };
}, { global: true });

b.add('./webnpm.js');

var preloadedReadFileSyncs = {};
for (var i = 0; i < preloadedFilenames.length; i += 1) {
  var path = preloadedFilenames[i];
  preloadedReadFileSyncs['/' + path] = JSON.stringify(fs.readFileSync(path, 'utf8'));
}

process.stdout.write('window.preloadedReadFileSyncs = ' + JSON.stringify(preloadedReadFileSyncs) + '\n;');

b.bundle().pipe(process.stdout);

<|endoftext|>


<commit_before>/**
 * ======README PLEASE====
 * ===== FOR DEMO PURPOSES ONLY ==========
 * I use the GinxParserTest to create N extact copies of log files in
 *	 ./test/tmplogs from either ./test/logs/nginx_prod-[large|small|tiny].log, so I won't have to commit all sample logs,
 *  you will usually have your own log files
 *  and since I need to wait for these the files to be copied before I actually start parsing, I pass the parsing code in a callback anon function
 *
 *  One more note, the setupTest does delete the storage before running, if you don't want to do so, pass it a 'false' in the  3rd argument.
 *  currently the program does not delete the storage (tmp/*) for you,
 */
var GinxParserTest = require('./test/setup/ginxparsertest')
var parserTest = new GinxParserTest();
// give it a try
// setupTest(NumberOfFilesToCreateThenParse, file's size => 'large'(~20k lines) or 'small' (~50 lines) or 'tiny'(~10 lines), DeleteTheStorageBefore?, cb)
parserTest.setupTest(150, 'large', true, function () {
    console.log("[GINXPARSER-TEST] finished SetupTest - Parsing begins now");
    var startTime = Date.now();
    // This is how you would use it usually, in a NodeJS program

    // Require the module
    var GinxParser = require('./lib/ginxparser'); // OR require('ginxparser'), depends how and where you isntalled it
    //construct a parser object,
    // optionally you can pass in two arguments, a boolean (persistent or not) and a string the Nginx access_log format.
    // default is Persistent, and the default Nginx access_log, check ./lib/ginxparser.js source to see the default format
    var parser = new GinxParser();

    parser.parseDir("/Users/akhoury/code/ginxparser/test/tmplogs",

    function (err, row) {
        if (err) throw err;
        /*
         * uncomment on your own risk :P - this will print out every row after it gets parsed, and it has a performance hit.
         * usually these would be persisted to a database, or handled in an analysis, or search
         * I would change the setupTest to parse 2 or 3 tiny files if you don't want to fill up your terminal before uncommenting.
         */
        //console.log(row);

        /* Here's a sample one row output, the attributes may change depending on the format, except __file, __lastCharAt and __originalText */
        //			  { __file: '/Users/akhoury/code/ginxparser/test/tmplogs/_large_nginx1.log',
        //          __lastCharAt: 1786,
        //          __originalText: '10.100.9.92 - - [12/Nov/2012:12:15:69 -0500] "GET /assets/application-b3c5eeba998a57a7440394ae2ef6f6df.css HTTP/1.1" 200 111128 "http://demonet.trll.co/users/sign_in" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11"',
        //         remote_addr: '172.28.0.104',
        //         remote_user: null,
        //         time_local: Thu Feb 21 2013 09:10:57 GMT-0500 (EST),
        //         request: 'GET /favicon.ico HTTP/1.1',
        //         status: '502',
        //         body_bytes_sent: '172',
        //         http_referer: null,
        //         http_user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0'
        //        }

    },

    function (file) {
      // something here
    },
    function(){
        console.log("[GINXPARSER-DEBUG] all Files parsing completed in " + (Date.now()-startTime) + " ms");
    });

    /**
     * parses a single log file
     * first callback prints out each row as it gets parsed
     * second callback prints out the file when it's completely parsed
     */
    //		parser.parseFile("./test/logs/nginx_prod-tiny.log",
    //			function (err, row) {
    //				if (err) {throw err;}
    //				/*
    //					uncomment on your own risk - this will print out every row,
    //					usually these would be persisted to the database, or handled in an analysis, or search
    //				*/
    //				 //console.log(row);
    //				},
    //			function(file){
    //			 console.log("[DEBUG] " + file + " parsing completed in ParseFile()");
    //			}
    //		);

});<commit_msg>indentation fixes! ugh i need a new editor<commit_after>/**
 * ======README PLEASE====
 * ===== FOR DEMO PURPOSES ONLY ==========
 * I use the GinxParserTest to create N extact copies of log files in
 *	 ./test/tmplogs from either ./test/logs/nginx_prod-[large|small|tiny].log, so I won't have to commit all sample logs,
 *  you will usually have your own log files
 *  and since I need to wait for these the files to be copied before I actually start parsing, I pass the parsing code in a callback anon function
 *
 *  One more note, the setupTest does delete the storage before running, if you don't want to do so, pass it a 'false' in the  3rd argument.
 *  currently the program does not delete the storage (tmp/*) for you,
 */
var GinxParserTest = require('./test/setup/ginxparsertest')
var parserTest = new GinxParserTest();
// give it a try
// setupTest(NumberOfFilesToCreateThenParse, file's size => 'large'(~20k lines) or 'small' (~50 lines) or 'tiny'(~10 lines), DeleteTheStorageBefore?, cb)
parserTest.setupTest(150, 'large', true, function () {
    console.log("[GINXPARSER-TEST] finished SetupTest - Parsing begins now");
    var startTime = Date.now();
    // This is how you would use it usually, in a NodeJS program

    // Require the module
    var GinxParser = require('./lib/ginxparser'); // OR require('ginxparser'), depends how and where you isntalled it
    //construct a parser object,
    // optionally you can pass in two arguments, a boolean (persistent or not) and a string the Nginx access_log format.
    // default is Persistent, and the default Nginx access_log, check ./lib/ginxparser.js source to see the default format
    var parser = new GinxParser();

    parser.parseDir("/Users/akhoury/code/ginxparser/test/tmplogs",

        function (err, row) {
            if (err) throw err;
            /*
             * uncomment on your own risk :P - this will print out every row after it gets parsed, and it has a performance hit.
             * usually these would be persisted to a database, or handled in an analysis, or search
             * I would change the setupTest to parse 2 or 3 tiny files if you don't want to fill up your terminal before uncommenting.
             */
              //console.log(row);

            /* Here's a sample one row output, the attributes may change depending on the format, except __file, __lastCharAt and __originalText */
            //			  { __file: '/Users/akhoury/code/ginxparser/test/tmplogs/_large_nginx1.log',
            //          __lastCharAt: 1786,
            //          __originalText: '10.100.9.92 - - [12/Nov/2012:12:15:69 -0500] "GET /assets/application-b3c5eeba998a57a7440394ae2ef6f6df.css HTTP/1.1" 200 111128 "http://demonet.trll.co/users/sign_in" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11"',
            //         remote_addr: '172.28.0.104',
            //         remote_user: null,
            //         time_local: Thu Feb 21 2013 09:10:57 GMT-0500 (EST),
            //         request: 'GET /favicon.ico HTTP/1.1',
            //         status: '502',
            //         body_bytes_sent: '172',
            //         http_referer: null,
            //         http_user_agent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:19.0) Gecko/20100101 Firefox/19.0'
            //        }

            },

        function (file) {
          // something here
        },
        function(){
            console.log("[GINXPARSER-DEBUG] all Files parsing completed in " + (Date.now()-startTime) + " ms");
        });

        /**
         * parses a single log file
         * first callback prints out each row as it gets parsed
         * second callback prints out the file when it's completely parsed
         */
        //		parser.parseFile("./test/logs/nginx_prod-tiny.log",
        //			function (err, row) {
        //				if (err) {throw err;}
        //				/*
        //					uncomment on your own risk - this will print out every row,
        //					usually these would be persisted to the database, or handled in an analysis, or search
        //				*/
        //				 //console.log(row);
        //				},
        //			function(file){
        //			 console.log("[DEBUG] " + file + " parsing completed in ParseFile()");
        //			}
        //		);

});<|endoftext|>