<commit_before>import * as calculate from '../utils/calculate'
import * as getFromCSV from './scriptUtils/getFromCSV'
import * as fs from 'fs'
import assert from 'assert'
import R from 'ramda'
import readCSV from '../service/readCSV'
import jsonfile from 'jsonfile'
import * as collection from '../utils/constants'

const getProperties = ev => ({
  year: getFromCSV.getYear(ev),
  term: getFromCSV.getTerm(ev),
  course: getFromCSV.getCourse(ev),
  section: getFromCSV.getSection(ev),
  courseName: getFromCSV.getCourseName(ev),
  courseLevel: getFromCSV.getCourseLevel(ev),
  dept: getFromCSV.getDept(ev),
  instructorName: getFromCSV.getInstructorName(ev),
  PUID: getFromCSV.getPUID(ev),
  gender: getFromCSV.getGender(ev)
})

// filter out any rows in the csv with all 0 UMI ratings
const filterAll0s = csv => csv.filter(ev => {
  if (getFromCSV.getUMI1(ev) === 0 &&
    getFromCSV.getUMI2(ev) === 0 &&
    getFromCSV.getUMI3(ev) === 0 &&
    getFromCSV.getUMI4(ev) === 0 &&
    getFromCSV.getUMI5(ev) === 0 &&
    getFromCSV.getUMI6(ev) === 0) return false
  else return true
})

const createCourseObj = csv => {
  const filteredCSV = filterAll0s(csv)
  return filteredCSV.reduce((acc, ev) => {
    const { year, term, course, section, courseName, courseLevel, dept, instructorName, PUID, gender } = getProperties(ev)

    const uniqSectionInTerm = x => (x.year === year &&
      x.course === course &&
      x.term === term &&
      x.section === section &&
      x.instructorName === instructorName)

    if (acc.some(x => uniqSectionInTerm(x))) {
      const index = acc.findIndex(x => uniqSectionInTerm(x))

      for (let i = 1; i <= 6; i++) {
        let getUMI
        let UMI = 'UMI' + i
        if (i === 1) getUMI = getFromCSV.getUMI1(ev)
        if (i === 2) getUMI = getFromCSV.getUMI2(ev)
        if (i === 3) getUMI = getFromCSV.getUMI3(ev)
        if (i === 4) getUMI = getFromCSV.getUMI4(ev)
        if (i === 5) getUMI = getFromCSV.getUMI5(ev)
        if (i === 6) getUMI = getFromCSV.getUMI6(ev)
        if (typeof (acc[index][UMI].count[getUMI]) === 'undefined') {
          acc[index][UMI].count = { ...acc[index][UMI].count, [getUMI]: 1 }
        } else acc[index][UMI].count[getUMI] = acc[index][UMI].count[getUMI] + 1
      }
      acc[index].gender[gender] = acc[index].gender[gender] + 1
      return acc
    } else {
      acc.push({
        year,
        term,
        course,
        section,
        courseName,
        courseLevel,
        dept,
        instructorName,
        PUID,
        gender: {
          Female: (gender === 'Female') ? 1 : 0,
          Male: (gender === 'Male') ? 1 : 0
        },
        UMI1: { count: { [String(getFromCSV.getUMI1(ev))]: 1 } },
        UMI2: { count: { [String(getFromCSV.getUMI2(ev))]: 1 } },
        UMI3: { count: { [String(getFromCSV.getUMI3(ev))]: 1 } },
        UMI4: { count: { [String(getFromCSV.getUMI4(ev))]: 1 } },
        UMI5: { count: { [String(getFromCSV.getUMI5(ev))]: 1 } },
        UMI6: { count: { [String(getFromCSV.getUMI6(ev))]: 1 } }
      })
      return acc
    }
  }, [])
}

const removeIncorrectCounts = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    const countObj = courseObj[UMI].count
    const newObj = R.pick(['1', '2', '3', '4', '5'], countObj)
    courseObj[UMI].count = newObj
  }
  return courseObj
}

const insertDispersionIndex = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    courseObj[UMI].dispersionIndex = calculate.dispersionIndex(courseObj[UMI].count)
  }
  return courseObj
}

const insertAvg = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    courseObj[UMI].average = calculate.umiAvg(courseObj[UMI].count)
  }
  return courseObj
}

const insertPercentFav = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    courseObj[UMI].percentFavourable = calculate.percentFavourable(courseObj[UMI].count)
  }
  return courseObj
}

const insertPercentileRanking = courseObjs => {
  let sortedByUMI
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    sortedByUMI = courseObjs.sort((a, b) => a[UMI].average - b[UMI].average)
    sortedByUMI.map((course) => {
      const filteredByTermAndYear = sortedByUMI.filter(x => x.year === course.year && x.term === course.term)
      const filteredByTermYearAndDept = filteredByTermAndYear.filter(x => x.dept === course.dept)
      course[UMI].percentileRankingByFaculty = calculate.percentileRankingOfCourse(course, UMI, filteredByTermAndYear)
      course[UMI].percentileRankingByDept = calculate.percentileRankingOfCourse(course, UMI, filteredByTermYearAndDept)
    })
  }
  return sortedByUMI
}

const outputAggregatedData = cb => {
  readCSV('../scripts/source/rawDataAll.csv', (csv) => {
    let courseObjs = createCourseObj(csv)

    courseObjs.map(courseObj => R.pipe(
      x => removeIncorrectCounts(x),
      x => insertDispersionIndex(x),
      x => insertAvg(x),
      x => insertPercentFav(x)
    )(courseObj))

    courseObjs = insertPercentileRanking(courseObjs)

    // filters courses with null umi6 averages (rarely happens)
    courseObjs = courseObjs.filter(courseObj => courseObj.UMI6.average)

    // check directory for enrollment data file
    if (fs.existsSync('../scripts/source/course_eval_enrollments-2009-2017WA.csv')) {
      // this adds in the enrolment data from another CSV
      readCSV('../scripts/source/course_eval_enrollments-2009-2017WA.csv', csv => {
        csv.map(enrolmentCourse => {
          const { enrolmentCourseName, enrolmentCourseID, enrolmentSection, enrolmentYear, enrolmentTerm, enrolment } =
            {
              enrolmentCourseName: enrolmentCourse.crsname,
              enrolmentCourseID: getFromCSV.getEnrolmentCourseNumber(enrolmentCourse.crsnum),
              enrolmentSection: getFromCSV.getEnrolmentSection(enrolmentCourse.section),
              enrolmentYear: getFromCSV.getEnrolmentYear(enrolmentCourse.period),
              enrolmentTerm: getFromCSV.getEnrolmentTerm(enrolmentCourse.period),
              enrolment: enrolmentCourse.no_enrolled
            }

          courseObjs.map(course => {
            const { courseName, courseID, section, year, term } =
              {
                courseName: course.courseName,
                courseID: course.course,
                section: course.section,
                year: course.year,
                term: course.term
              }
            if (courseName === enrolmentCourseName &&
              courseID === enrolmentCourseID &&
              section === enrolmentSection &&
              year === enrolmentYear &&
              term === enrolmentTerm) {
              course.enrolment = enrolment
              const responses = course.gender.Female + course.gender.Male
              const responseRate = calculate.toTwoDecimal(responses / enrolment)
              course.responseRate = responseRate
              course.meetsMin = calculate.meetsMinimum(enrolment, responseRate)
            }
          })
        })
      })
    } else {
      courseObjs.map(course => {
        const enrolment = 200
        course.enrolment = enrolment
        const responses = course.gender.Female + course.gender.Male
        const responseRate = calculate.toTwoDecimal(responses / enrolment)
        course.responseRate = responseRate
        course.meetsMin = calculate.meetsMinimum(enrolment, responseRate)
      })
    }

    const file = './output/' + collection.aggregatedData + '.json'
    jsonfile.writeFile(file, courseObjs, (err) => {
      assert.equal(err, null)
      cb()
    })
  })
}

export {
  createCourseObj,
  insertDispersionIndex,
  insertAvg,
  insertPercentFav,
  insertPercentileRanking,
  removeIncorrectCounts,
  outputAggregatedData
}
<commit_msg>add comment<commit_after>import * as calculate from '../utils/calculate'
import * as getFromCSV from './scriptUtils/getFromCSV'
import * as fs from 'fs'
import assert from 'assert'
import R from 'ramda'
import readCSV from '../service/readCSV'
import jsonfile from 'jsonfile'
import * as collection from '../utils/constants'

const getProperties = ev => ({
  year: getFromCSV.getYear(ev),
  term: getFromCSV.getTerm(ev),
  course: getFromCSV.getCourse(ev),
  section: getFromCSV.getSection(ev),
  courseName: getFromCSV.getCourseName(ev),
  courseLevel: getFromCSV.getCourseLevel(ev),
  dept: getFromCSV.getDept(ev),
  instructorName: getFromCSV.getInstructorName(ev),
  PUID: getFromCSV.getPUID(ev),
  gender: getFromCSV.getGender(ev)
})

// filter out any rows in the csv with all 0 UMI ratings
const filterAll0s = csv => csv.filter(ev => {
  if (getFromCSV.getUMI1(ev) === 0 &&
    getFromCSV.getUMI2(ev) === 0 &&
    getFromCSV.getUMI3(ev) === 0 &&
    getFromCSV.getUMI4(ev) === 0 &&
    getFromCSV.getUMI5(ev) === 0 &&
    getFromCSV.getUMI6(ev) === 0) return false
  else return true
})

const createCourseObj = csv => {
  const filteredCSV = filterAll0s(csv)
  return filteredCSV.reduce((acc, ev) => {
    const { year, term, course, section, courseName, courseLevel, dept, instructorName, PUID, gender } = getProperties(ev)

    const uniqSectionInTerm = x => (x.year === year &&
      x.course === course &&
      x.term === term &&
      x.section === section &&
      x.instructorName === instructorName)

    if (acc.some(x => uniqSectionInTerm(x))) {
      const index = acc.findIndex(x => uniqSectionInTerm(x))

      for (let i = 1; i <= 6; i++) {
        let getUMI
        let UMI = 'UMI' + i
        if (i === 1) getUMI = getFromCSV.getUMI1(ev)
        if (i === 2) getUMI = getFromCSV.getUMI2(ev)
        if (i === 3) getUMI = getFromCSV.getUMI3(ev)
        if (i === 4) getUMI = getFromCSV.getUMI4(ev)
        if (i === 5) getUMI = getFromCSV.getUMI5(ev)
        if (i === 6) getUMI = getFromCSV.getUMI6(ev)
        if (typeof (acc[index][UMI].count[getUMI]) === 'undefined') {
          acc[index][UMI].count = { ...acc[index][UMI].count, [getUMI]: 1 }
        } else acc[index][UMI].count[getUMI] = acc[index][UMI].count[getUMI] + 1
      }
      acc[index].gender[gender] = acc[index].gender[gender] + 1
      return acc
    } else {
      acc.push({
        year,
        term,
        course,
        section,
        courseName,
        courseLevel,
        dept,
        instructorName,
        PUID,
        gender: {
          Female: (gender === 'Female') ? 1 : 0,
          Male: (gender === 'Male') ? 1 : 0
        },
        UMI1: { count: { [String(getFromCSV.getUMI1(ev))]: 1 } },
        UMI2: { count: { [String(getFromCSV.getUMI2(ev))]: 1 } },
        UMI3: { count: { [String(getFromCSV.getUMI3(ev))]: 1 } },
        UMI4: { count: { [String(getFromCSV.getUMI4(ev))]: 1 } },
        UMI5: { count: { [String(getFromCSV.getUMI5(ev))]: 1 } },
        UMI6: { count: { [String(getFromCSV.getUMI6(ev))]: 1 } }
      })
      return acc
    }
  }, [])
}

const removeIncorrectCounts = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    const countObj = courseObj[UMI].count
    const newObj = R.pick(['1', '2', '3', '4', '5'], countObj)
    courseObj[UMI].count = newObj
  }
  return courseObj
}

const insertDispersionIndex = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    courseObj[UMI].dispersionIndex = calculate.dispersionIndex(courseObj[UMI].count)
  }
  return courseObj
}

const insertAvg = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    courseObj[UMI].average = calculate.umiAvg(courseObj[UMI].count)
  }
  return courseObj
}

const insertPercentFav = courseObj => {
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    courseObj[UMI].percentFavourable = calculate.percentFavourable(courseObj[UMI].count)
  }
  return courseObj
}

const insertPercentileRanking = courseObjs => {
  let sortedByUMI
  for (let i = 1; i <= 6; i++) {
    let UMI = 'UMI' + i
    sortedByUMI = courseObjs.sort((a, b) => a[UMI].average - b[UMI].average)
    sortedByUMI.map((course) => {
      const filteredByTermAndYear = sortedByUMI.filter(x => x.year === course.year && x.term === course.term)
      const filteredByTermYearAndDept = filteredByTermAndYear.filter(x => x.dept === course.dept)
      course[UMI].percentileRankingByFaculty = calculate.percentileRankingOfCourse(course, UMI, filteredByTermAndYear)
      course[UMI].percentileRankingByDept = calculate.percentileRankingOfCourse(course, UMI, filteredByTermYearAndDept)
    })
  }
  return sortedByUMI
}

const outputAggregatedData = cb => {
  readCSV('../scripts/source/rawDataAll.csv', (csv) => {
    let courseObjs = createCourseObj(csv)

    courseObjs.map(courseObj => R.pipe(
      x => removeIncorrectCounts(x),
      x => insertDispersionIndex(x),
      x => insertAvg(x),
      x => insertPercentFav(x)
    )(courseObj))

    courseObjs = insertPercentileRanking(courseObjs)

    // filters courses with null umi6 averages (rarely happens)
    courseObjs = courseObjs.filter(courseObj => courseObj.UMI6.average)

    // check directory for enrollment data file
    if (fs.existsSync('../scripts/source/course_eval_enrollments-2009-2017WA.csv')) {
      // this adds in the enrolment data from another CSV
      readCSV('../scripts/source/course_eval_enrollments-2009-2017WA.csv', csv => {
        csv.map(enrolmentCourse => {
          const { enrolmentCourseName, enrolmentCourseID, enrolmentSection, enrolmentYear, enrolmentTerm, enrolment } =
            {
              enrolmentCourseName: enrolmentCourse.crsname,
              enrolmentCourseID: getFromCSV.getEnrolmentCourseNumber(enrolmentCourse.crsnum),
              enrolmentSection: getFromCSV.getEnrolmentSection(enrolmentCourse.section),
              enrolmentYear: getFromCSV.getEnrolmentYear(enrolmentCourse.period),
              enrolmentTerm: getFromCSV.getEnrolmentTerm(enrolmentCourse.period),
              enrolment: enrolmentCourse.no_enrolled
            }

          courseObjs.map(course => {
            const { courseName, courseID, section, year, term } =
              {
                courseName: course.courseName,
                courseID: course.course,
                section: course.section,
                year: course.year,
                term: course.term
              }
            if (courseName === enrolmentCourseName &&
              courseID === enrolmentCourseID &&
              section === enrolmentSection &&
              year === enrolmentYear &&
              term === enrolmentTerm) {
              course.enrolment = enrolment
              const responses = course.gender.Female + course.gender.Male
              const responseRate = calculate.toTwoDecimal(responses / enrolment)
              course.responseRate = responseRate
              course.meetsMin = calculate.meetsMinimum(enrolment, responseRate)
            }
          })
        })
      })
    } else { // use an arbitrary value for class size
      courseObjs.map(course => {
        const enrolment = 200
        course.enrolment = enrolment
        const responses = course.gender.Female + course.gender.Male
        const responseRate = calculate.toTwoDecimal(responses / enrolment)
        course.responseRate = responseRate
        course.meetsMin = calculate.meetsMinimum(enrolment, responseRate)
      })
    }

    const file = './output/' + collection.aggregatedData + '.json'
    jsonfile.writeFile(file, courseObjs, (err) => {
      assert.equal(err, null)
      cb()
    })
  })
}

export {
  createCourseObj,
  insertDispersionIndex,
  insertAvg,
  insertPercentFav,
  insertPercentileRanking,
  removeIncorrectCounts,
  outputAggregatedData
}
<|endoftext|>


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

  angular.module('sentry.flash', [])
    .factory('flash', [
      '$rootScope', '$timeout',
      function($rootScope, $timeout){
        var messages = [],
            reset;

        var cleanup = function() {
          $timeout.cancel(reset);
          reset = $timeout(function() {
            messages = [];
          });
        };

        var emit = function() {
          $rootScope.$emit('flash:message', messages, cleanup);
        };

        $rootScope.$on('$routeChangeSuccess', emit);

        var getLevelTypeName = function(level) {
          if (level == 'error') {
            return 'danger';
          } else {
            return level;
          }
        };

        var asMessage = function(level, text) {
          if (text === undefined) {
            text = level;
            level = 'success';
          }
          return {
            type: getLevelTypeName(level),
            text: text
          };
        };

        var asArrayOfMessages = function(level, text) {
          if (level instanceof Array) return level.map(function(message) {
            return message.text ? message : asMessage(message);
          });
          return [asMessage(level, text)];
        };

        return function(level, text) {
          emit(messages = asArrayOfMessages(level, text));
        };
      }
    ])
    .directive('flashMessages', function() {
      return {
        restrict: 'E',
        replace: true,
        template:
          '
' +
            '
' +
              '
' +
                '
' +
                  '<button type="button" class="close" ng-click=close($index)>×</button>' +
                  '{{m.text}}' +
                '
' +
              '
' +
            '
' +
          '
',
        controller: function($scope, $rootScope) {
          $scope.close = function(index){
            $scope.messages.splice(index, 1);
            if (!!messages) {
              $(".messages-container").remove();
            }
          };

          $rootScope.$on('flash:message', function(_, messages, done) {
            $scope.messages = messages;
            done();
          });

          $rootScope.$on('$stateChangeSuccess', function(_u1, _u2, $stateParams){
            $scope.messages = [];
          });
        }
      };
    });
}());
<commit_msg>Add icons to js flash messages<commit_after>(function(){
  'use strict';

  angular.module('sentry.flash', [])
    .factory('flash', [
      '$rootScope', '$timeout',
      function($rootScope, $timeout){
        var messages = [],
            reset;

        var cleanup = function() {
          $timeout.cancel(reset);
          reset = $timeout(function() {
            messages = [];
          });
        };

        var emit = function() {
          $rootScope.$emit('flash:message', messages, cleanup);
        };

        $rootScope.$on('$routeChangeSuccess', emit);

        var getLevelTypeName = function(level) {
          if (level == 'error') {
            return 'danger';
          } else {
            return level;
          }
        };

        var asMessage = function(level, text) {
          if (text === undefined) {
            text = level;
            level = 'success';
          }
          return {
            type: getLevelTypeName(level),
            text: text
          };
        };

        var asArrayOfMessages = function(level, text) {
          if (level instanceof Array) return level.map(function(message) {
            return message.text ? message : asMessage(message);
          });
          return [asMessage(level, text)];
        };

        return function(level, text) {
          emit(messages = asArrayOfMessages(level, text));
        };
      }
    ])
    .directive('flashMessages', function() {
      return {
        restrict: 'E',
        replace: true,
        template:
          '
' +
            '
' +
              '
' +
                '
' +
                  '<button type="button" class="close" ng-click=close($index)>×</button>' +
                  '' +
                  '' +
                  '' +
                  '{{m.text}}' +
                '
' +
              '
' +
            '
' +
          '
',
        controller: function($scope, $rootScope) {
          $scope.close = function(index){
            $scope.messages.splice(index, 1);
            if (!!messages) {
              $(".messages-container").remove();
            }
          };

          $rootScope.$on('flash:message', function(_, messages, done) {
            $scope.messages = messages;
            done();
          });

          $rootScope.$on('$stateChangeSuccess', function(_u1, _u2, $stateParams){
            $scope.messages = [];
          });
        }
      };
    });
}());
<|endoftext|>


<commit_before>/**
 * ManiaPlanet Generic Callbacks
 *
 * Maps generic mp callbacks into events.
 */
'use strict';

/**
 * Run the registers.
 *
 * @param {CallbackManager} manager
 * @param {function} manager.register
 */
export default function (manager) {

  /**
   * PLAYER EVENTS
   */
  // Connect
  manager.register({
    callback: 'ManiaPlanet.PlayerConnect',
    event: 'player.connect',
    parameters: {
      login: 0,
      spectator: 1
    },
    flow: (app, params) => {
      return app.gameFacade.players.connect(params.login);
    }
  });

  // Disconnect
  manager.register({
    callback: 'ManiaPlanet.PlayerDisconnect',
    event: 'player.disconnect',
    parameters: {
      login: 0,
      reason: 1
    }
  });

  // Chat
  manager.register({
    callback: 'ManiaPlanet.PlayerChat',
    event: 'player.chat',
    parameters: {
      playerid: 0,
      login: 1,
      text: 2,
      command: 3
    },
    pass: function(params) {
      return (params[0] !== 0); // Prevent the server itself being seen as a chat message event.
    }
  });

  // info change
  manager.register({
    callback: 'ManiaPlanet.PlayerInfoChanged',
    event: 'player.change',
    parse: (raw) => {
      let info = raw[0];

      let isSpectator =       info.SpectatorStatus           % 10;
      let isTempSpectator =  (info.SpectatorStatus / 10)     % 10;
      let isPureSpectator =  (info.SpectatorStatus / 100)    % 10;
      let autoTarget =       (info.SpectatorStatus / 1000)   % 10;
      let targetId =         (info.SpectatorStatus / 10000)      ;

      return {
        login: info.Login,
        nickName: info.NickName,
        playerId: info.PlayerId,
        teamId: info.TeamId,
        spectatorStatus: info.SpectatorStatus,
        flags: info.Flags,

        isSpectator: isSpectator,
        isTempSpectator: isTempSpectator,
        isPureSpectator: isPureSpectator,
        autoTarget: autoTarget,
        targetId: targetId
      };
    },
    flow: (app, params) => {
      return app.gameFacade.players.update(params.login, params.nickName, params);
    }
  });

  // alies changed
  manager.register({
    callback: 'ManiaPlanet.PlayerAlliesChanged',
    event: 'player.alieschange',
    parameters: {
      login: 0
    }
  });

  // manialink answer
  manager.register({
    callback: 'ManiaPlanet.PlayerManialinkPageAnswer',
    event: 'player.manialinkanswer',
    parameters: {
      playerid: 0,
      login: 1,
      answer: 2,
      entries: 3
    },
    flow: (app, params) => {
      // First call the ui manager.
      return app.uiFacade.manager.answer(params);
    }
  });

  // TODO: ManiaPlanet.PlayerManialinkPageAnswer

  /**
   * SERVER EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.Echo',
    event: 'server.echo',
    parameters: {
      internal: 0,
      public: 1
    }
  });

  manager.register({
    callback: 'ManiaPlanet.ServerStart',
    event: 'server.start'
  });

  manager.register({
    callback: 'ManiaPlanet.ServerStop',
    event: 'server.stop'
  });

  /**
   * MATCH EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.BeginMatch',
    event: 'match.begin'
  });

  manager.register({
    callback: 'ManiaPlanet.EndMatch',
    event: 'match.end',
    parameters: {
      rankings: 0,
      winnerTeam: 1
    }
  });

  /**
   * MAP EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.BeginMap',
    event: 'map.begin',
    parse: (raw) => {
      return raw[0];
    },
    flow: (app, params) => {
      return app.gameFacade.maps.begin(params.UId);
    }
  });

  manager.register({
    callback: 'ManiaPlanet.EndMap',
    event: 'map.end',
    parameters: {
      map: 0
    }
  });

  // TODO: ManiaPlanet.StatusChanged

  /**
   * OTHER EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.BillUpdated',
    event: 'bill.update',
    parameters: {
      billId: 0,
      state: 1,
      stateName: 2,
      transactionId: 3
    }
  });

  manager.register({
    callback: 'ManiaPlanet.TunnelDataReceived',
    event: 'server.tunneldatareceived',
    parameters: {
      playerId: 0,
      login: 1,
      data: 2 // base64, needs decoding maybe?
    }
  });

  manager.register({
    callback: 'ManiaPlanet.MapListModified',
    event: 'map.listchange',
    parameters: {
      currentMapIndex: 0,
      nextMapIndex: 1,
      isListModified: 2
    }
  });

  manager.register({
    callback: 'ManiaPlanet.VoteUpdated',
    event: 'vote.update',
    parameters: {
      stateName: 0, // StateName values: NewVote, VoteCancelled, VotePassed or VoteFailed
      login: 1,
      cmdName: 2,
      cmdParam: 3
    }
  });

  // custom script callbacks.
  // TODO: ModeScriptCallback + ModeScriptCallbackArray

}
<commit_msg>Call the player.connect AFTER we fetched the player data. (fix).<commit_after>/**
 * ManiaPlanet Generic Callbacks
 *
 * Maps generic mp callbacks into events.
 */
'use strict';

/**
 * Run the registers.
 *
 * @param {CallbackManager} manager
 * @param {function} manager.register
 */
export default function (manager) {

  /**
   * PLAYER EVENTS
   */
  // Connect
  manager.register({
    callback: 'ManiaPlanet.PlayerConnect',
    event: 'player.connect',
    parameters: {
      login: 0,
      spectator: 1
    },
    pass: (params) => {
      return false; // We don't have the player info yet, wait until info change event is fetching player info from db.
    }
  });

  // Disconnect
  manager.register({
    callback: 'ManiaPlanet.PlayerDisconnect',
    event: 'player.disconnect',
    parameters: {
      login: 0,
      reason: 1
    },
    flow: (app, params) => {
      return app.gameFacade.players.disconnect(params.login);
    }
  });

  // Chat
  manager.register({
    callback: 'ManiaPlanet.PlayerChat',
    event: 'player.chat',
    parameters: {
      playerid: 0,
      login: 1,
      text: 2,
      command: 3
    },
    pass: function(params) {
      return (params[0] !== 0); // Prevent the server itself being seen as a chat message event.
    }
  });

  // info change
  manager.register({
    callback: 'ManiaPlanet.PlayerInfoChanged',
    event: 'player.change',
    parse: (raw) => {
      let info = raw[0];

      let isSpectator =       info.SpectatorStatus           % 10;
      let isTempSpectator =  (info.SpectatorStatus / 10)     % 10;
      let isPureSpectator =  (info.SpectatorStatus / 100)    % 10;
      let autoTarget =       (info.SpectatorStatus / 1000)   % 10;
      let targetId =         (info.SpectatorStatus / 10000)      ;

      return {
        login: info.Login,
        nickName: info.NickName,
        playerId: info.PlayerId,
        teamId: info.TeamId,
        spectatorStatus: info.SpectatorStatus,
        flags: info.Flags,

        isSpectator: isSpectator,
        isTempSpectator: isTempSpectator,
        isPureSpectator: isPureSpectator,
        autoTarget: autoTarget,
        targetId: targetId
      };
    },
    flow: (app, params) => {
      if (! app.gameFacade.players.list.hasOwnProperty(params.login) || app.gameFacade.players.list[params.login].disconnected) {
        return app.gameFacade.players.connect(params.login, params.nickName, params, true);
      }
      return Promise.resolve();
    }
  });

  // alies changed
  manager.register({
    callback: 'ManiaPlanet.PlayerAlliesChanged',
    event: 'player.alieschange',
    parameters: {
      login: 0
    }
  });

  // manialink answer
  manager.register({
    callback: 'ManiaPlanet.PlayerManialinkPageAnswer',
    event: 'player.manialinkanswer',
    parameters: {
      playerid: 0,
      login: 1,
      answer: 2,
      entries: 3
    },
    flow: (app, params) => {
      // First call the ui manager.
      return app.uiFacade.manager.answer(params);
    }
  });

  /**
   * SERVER EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.Echo',
    event: 'server.echo',
    parameters: {
      internal: 0,
      public: 1
    }
  });

  manager.register({
    callback: 'ManiaPlanet.ServerStart',
    event: 'server.start'
  });

  manager.register({
    callback: 'ManiaPlanet.ServerStop',
    event: 'server.stop'
  });

  /**
   * MATCH EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.BeginMatch',
    event: 'match.begin'
  });

  manager.register({
    callback: 'ManiaPlanet.EndMatch',
    event: 'match.end',
    parameters: {
      rankings: 0,
      winnerTeam: 1
    }
  });

  /**
   * MAP EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.BeginMap',
    event: 'map.begin',
    parse: (raw) => {
      return raw[0];
    },
    flow: (app, params) => {
      return app.gameFacade.maps.begin(params.UId);
    }
  });

  manager.register({
    callback: 'ManiaPlanet.EndMap',
    event: 'map.end',
    parameters: {
      map: 0
    }
  });

  // TODO: ManiaPlanet.StatusChanged

  /**
   * OTHER EVENTS
   */
  manager.register({
    callback: 'ManiaPlanet.BillUpdated',
    event: 'bill.update',
    parameters: {
      billId: 0,
      state: 1,
      stateName: 2,
      transactionId: 3
    }
  });

  manager.register({
    callback: 'ManiaPlanet.TunnelDataReceived',
    event: 'server.tunneldatareceived',
    parameters: {
      playerId: 0,
      login: 1,
      data: 2 // base64, needs decoding maybe?
    }
  });

  manager.register({
    callback: 'ManiaPlanet.MapListModified',
    event: 'map.listchange',
    parameters: {
      currentMapIndex: 0,
      nextMapIndex: 1,
      isListModified: 2
    }
  });

  manager.register({
    callback: 'ManiaPlanet.VoteUpdated',
    event: 'vote.update',
    parameters: {
      stateName: 0, // StateName values: NewVote, VoteCancelled, VotePassed or VoteFailed
      login: 1,
      cmdName: 2,
      cmdParam: 3
    }
  });

  // custom script callbacks.
  // TODO: ModeScriptCallback + ModeScriptCallbackArray

}
<|endoftext|>


<commit_before>const moment = require('moment')
const { mapValues, get } = require('lodash')
const { buildCompanyUrl } = require('./company.service')

function transformToApi (body) {
  const schema = {
    'client_relationship_manager': Object,
    'referral_source_adviser': Object,
    'referral_source_activity': Object,
    'referral_source_activity_marketing': Object,
    'referral_source_activity_website': Object,
    'investor_company': Object,
    'investment_type': Object,
    'fdi_type': Object,
    'non_fdi_type': Object,
    'sector': Object,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const relationshipMgr = body['is-relationship-manager']
  if (relationshipMgr !== 'No') {
    body.client_relationship_manager = relationshipMgr
  }

  const referralSource = body['is-referral-source']
  if (referralSource !== 'No') {
    body.referral_source_adviser = referralSource
  }

  const formatted = mapValues(schema, (type, key) => {
    const value = body[key]

    if (!value) {
      return
    }

    if (type === Array) {
      return [{ id: value }]
    }

    return { id: value }
  })

  formatted['estimated_land_date'] = `${body['land-date_year']}-${body['land-date_month']}-01`

  return Object.assign({}, body, formatted)
}

function transformFromApi (body) {
  const schema = {
    'client_relationship_manager': String,
    'referral_source_adviser': String,
    'referral_source_activity': String,
    'referral_source_activity_marketing': String,
    'referral_source_activity_website': String,
    'investor_company': String,
    'investment_type': String,
    'fdi_type': String,
    'non_fdi_type': String,
    'sector': String,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const formatted = mapValues(schema, (type, key) => {
    if (type === Array) {
      return get(body, `${key}[0].id`, '')
    }
    return get(body, `${key}.id`)
  })

  const date = new Date(body['estimated_land_date'])
  formatted['land-date_year'] = date.getFullYear()
  formatted['land-date_month'] = date.getMonth() + 1 // month is zero based index

  return Object.assign({}, body, formatted)
}

function formatProjectData (data) {
  return {
    'Client': {
      name: data.investor_company.name,
      url: buildCompanyUrl(data.investor_company),
    },
    'Type of investment': data.investment_type.name,
    'Primary sector': get(data, 'sector.name', null),
    'Sub-sector': null,
    'Business activity': data.business_activity,
    'Project description': data.description,
    'Non-disclosure agreement': data.nda_signed ? 'Signed' : 'Not signed',
    'Shareable with UK partners': null,
    'Anonymous description': null,
    'Estimated land date': data.estimated_land_date ? moment(data.estimated_land_date).format('MMMM YYYY') : null,
  }
}

function formatValueData (data) {
  return {
    'Total investment': data.total_investment,
    'Foreign equity investment': data.foreign_equity_investment,
    'Government assistance': data.government_assistance,
    'New jobs': data.number_new_jobs,
    'Average salary': data.average_salary,
    'Safeguarded jobs': data.number_safeguarded_jobs,
    'R&D budget': data.r_and_d_budget,
    'Non-FDI R&D project': data.non_fdi_r_and_d_budget,
    'New-to-world tech': data.new_tech_to_uk,
    'Export revenue': data.export_revenue,
  }
}

function formatRequirementsData (data) {
  return {
    'Main strategic drivers': data.strategic_drivers,
    'Client requirements': data.client_requirements,
    'Competitor countries': data.competitor_countries,
    'Possible UK locations': data.uk_region_locations,
    'Investment location': null,
    'UK recipient company': data.uk_company,
  }
}

function formatProjectStatusData (data) {
  return {
    id: data.id,
    name: data.name,
    projectCode: data.project_code,
    phaseName: data.phase.name,
  }
}

module.exports = {
  formatProjectData,
  formatValueData,
  formatRequirementsData,
  formatProjectStatusData,
  transformToApi,
  transformFromApi,
}
<commit_msg>Return from transformFromApi if there's nothing to transform<commit_after>const moment = require('moment')
const { mapValues, get } = require('lodash')
const { buildCompanyUrl } = require('./company.service')

function transformToApi (body) {
  const schema = {
    'client_relationship_manager': Object,
    'referral_source_adviser': Object,
    'referral_source_activity': Object,
    'referral_source_activity_marketing': Object,
    'referral_source_activity_website': Object,
    'investor_company': Object,
    'investment_type': Object,
    'fdi_type': Object,
    'non_fdi_type': Object,
    'sector': Object,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const relationshipMgr = body['is-relationship-manager']
  if (relationshipMgr !== 'No') {
    body.client_relationship_manager = relationshipMgr
  }

  const referralSource = body['is-referral-source']
  if (referralSource !== 'No') {
    body.referral_source_adviser = referralSource
  }

  const formatted = mapValues(schema, (type, key) => {
    const value = body[key]

    if (!value) {
      return
    }

    if (type === Array) {
      return [{ id: value }]
    }

    return { id: value }
  })

  formatted['estimated_land_date'] = `${body['land-date_year']}-${body['land-date_month']}-01`

  return Object.assign({}, body, formatted)
}

function transformFromApi (body) {
  if (!body) {
    return
  }

  const schema = {
    'client_relationship_manager': String,
    'referral_source_adviser': String,
    'referral_source_activity': String,
    'referral_source_activity_marketing': String,
    'referral_source_activity_website': String,
    'investor_company': String,
    'investment_type': String,
    'fdi_type': String,
    'non_fdi_type': String,
    'sector': String,
    'client_contacts': Array,
    'business_activities': Array,
  }

  const formatted = mapValues(schema, (type, key) => {
    if (type === Array) {
      return get(body, `${key}[0].id`, '')
    }
    return get(body, `${key}.id`)
  })

  const date = new Date(body['estimated_land_date'])
  formatted['land-date_year'] = date.getFullYear()
  formatted['land-date_month'] = date.getMonth() + 1 // month is zero based index

  return Object.assign({}, body, formatted)
}

function formatProjectData (data) {
  return {
    'Client': {
      name: data.investor_company.name,
      url: buildCompanyUrl(data.investor_company),
    },
    'Type of investment': data.investment_type.name,
    'Primary sector': get(data, 'sector.name', null),
    'Sub-sector': null,
    'Business activity': data.business_activity,
    'Project description': data.description,
    'Non-disclosure agreement': data.nda_signed ? 'Signed' : 'Not signed',
    'Shareable with UK partners': null,
    'Anonymous description': null,
    'Estimated land date': data.estimated_land_date ? moment(data.estimated_land_date).format('MMMM YYYY') : null,
  }
}

function formatValueData (data) {
  return {
    'Total investment': data.total_investment,
    'Foreign equity investment': data.foreign_equity_investment,
    'Government assistance': data.government_assistance,
    'New jobs': data.number_new_jobs,
    'Average salary': data.average_salary,
    'Safeguarded jobs': data.number_safeguarded_jobs,
    'R&D budget': data.r_and_d_budget,
    'Non-FDI R&D project': data.non_fdi_r_and_d_budget,
    'New-to-world tech': data.new_tech_to_uk,
    'Export revenue': data.export_revenue,
  }
}

function formatRequirementsData (data) {
  return {
    'Main strategic drivers': data.strategic_drivers,
    'Client requirements': data.client_requirements,
    'Competitor countries': data.competitor_countries,
    'Possible UK locations': data.uk_region_locations,
    'Investment location': null,
    'UK recipient company': data.uk_company,
  }
}

function formatProjectStatusData (data) {
  return {
    id: data.id,
    name: data.name,
    projectCode: data.project_code,
    phaseName: data.phase.name,
  }
}

module.exports = {
  formatProjectData,
  formatValueData,
  formatRequirementsData,
  formatProjectStatusData,
  transformToApi,
  transformFromApi,
}
<|endoftext|>


<commit_before>import React, { Children, Component, PropTypes } from 'react'
import withSideEffect from 'react-side-effect'

class DocumentTitle extends Component {
  render () {
    if (this.props.children) {
      return Children.only(this.props.children)
    } else {
      return null
    }
  }
}

DocumentTitle.propTypes = {
  title: PropTypes.string.isRequired,
  children: PropTypes.any
}

function reducePropsToState (propsList) {
  const innermostProps = propsList[propsList.length - 1]
  if (innermostProps) {
    const { defaultTitle, title } = innermostProps
    return defaultTitle
      ? `${title} | ${defaultTitle}`
      : `${title} | Untitled Document`
  }
}

function handleStateChangeOnClient (title) {
  document.title = title || ''
}

export default withSideEffect(
  reducePropsToState,
  handleStateChangeOnClient
)(DocumentTitle)
<commit_msg>fix title<commit_after>import React, { Children, Component, PropTypes } from 'react'
import withSideEffect from 'react-side-effect'

class DocumentTitle extends Component {
  render () {
    if (this.props.children) {
      return Children.only(this.props.children)
    } else {
      return null
    }
  }
}

DocumentTitle.propTypes = {
  title: PropTypes.string.isRequired,
  children: PropTypes.any
}

function reducePropsToState (propsList) {
  const innermostProps = propsList[propsList.length - 1]
  if (innermostProps) {
    const { defaultTitle, title } = innermostProps
    if (typeof title !== 'undefined') {
      return defaultTitle
        ? `${title} | ${defaultTitle}`
        : `${title} | Untitled Document`
    }
  }
}

function handleStateChangeOnClient (title) {
  document.title = title || ''
}

export default withSideEffect(
  reducePropsToState,
  handleStateChangeOnClient
)(DocumentTitle)
<|endoftext|>


<commit_before>var chaisePage = require('../../../../utils/chaise.page.js');
var recordEditHelpers = require('../../helpers.js'), chance = require('chance').Chance();

describe('Record Add', function() {

    var params, testConfiguration = browser.params.configuration.tests, testParams = testConfiguration.params;

    for (var i=0; i< testParams.tables.length; i++) {

    	(function(tableParams, index) {

    		describe("======================================================================= \n    "
    			+ tableParams.records + " record(s) for table " + tableParams.table_name + ",", function() {

				beforeAll(function (done) {
					browser.ignoreSynchronization=true;
					browser.get(browser.params.url + ":" + tableParams.table_name);
                    chaisePage.waitForElement(element(by.id("submit-record-button"))).then(function() {
                        done();
                    });
			    });

				describe("Presentation and validation,", function() {
                    var params = recordEditHelpers.testPresentationAndBasicValidation(tableParams);
				});

				describe("delete record, ", function() {

					if (tableParams.records > 1) {

						it(tableParams.records + " buttons should be visible and enabled", function() {
							chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
								expect(buttons.length).toBe(tableParams.records + 1);
								buttons.forEach(function(btn) {
									expect(btn.isDisplayed()).toBe(true);
									expect(btn.isEnabled()).toBe(true);
								});
							});
						});

						var randomNo = chaisePage.recordEditPage.getRandomInt(0, tableParams.records - 1);

						it("click any delete button", function() {
							chaisePage.recordEditPage.getDeleteRowButton(randomNo).then(function(button)	 {
								chaisePage.clickButton(button);
								browser.sleep(50);
								chaisePage.recordEditPage.getDeleteModalButton().then(function(modalBtn) {
									chaisePage.clickButton(modalBtn);
									browser.sleep(50);
									chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
										expect(buttons.length).toBe(tableParams.records);
									});
								});
							});
						});
					} else {
						it("zero delete buttons should be visible", function() {
							chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
								expect(buttons.length).toBe(1);
								buttons.forEach(function(btn) {
									expect(btn.isDisplayed()).toBe(false);
								});
							});
						});
					}
				});

				describe("Submit " + tableParams.records + " records", function() {
					beforeAll(function() {
						// Submit the form
						chaisePage.recordEditPage.submitForm();
					});

					var hasErrors = false;

					it("should have no errors, and should be redirected", function(done) {
						chaisePage.recordEditPage.getAlertError().then(function(err) {
							if (err) {
								expect("Page has errors").toBe("No errors");
								hasErrors = true;
							} else {
								expect(true).toBe(true);
							}
						});
                        done();
					});

					it("should be redirected to record page", function() {
						if (!hasErrors) {
                            // doesn't redirect to record
                            if (tableParams.records > 1) {
                                // wait for url change
                                browser.wait(function () {
                                    return browser.driver.getCurrentUrl().then(function(url) {
                                        return url.startsWith(process.env.CHAISE_BASE_URL + "/recordedit/");
                                    });
                                }, browser.params.defaultTimeout);
                                // verify url and ct
                                browser.driver.getCurrentUrl().then(function(url) {
    						        expect(url.startsWith(process.env.CHAISE_BASE_URL + "/recordedit/")).toBe(true);

                                    chaisePage.recordsetPage.getRows().count().then(function (ct) {
                                        expect(ct).toBe(tableParams.records);
                                    });
                                });
                            // redirects to record
						    } else {
                                // wait for url change
                                browser.wait(function () {
                                    return browser.driver.getCurrentUrl().then(function(url) {
                                        return url.startsWith(process.env.CHAISE_BASE_URL + "/record/");
                                    });
                                }, browser.params.defaultTimeout);
                                // cerify url
                                browser.driver.getCurrentUrl().then(function(url) {
                                    expect(url.startsWith(process.env.CHAISE_BASE_URL + "/record/")).toBe(true);
                                });
						    }
						}
					});
				});
    		});
    	})(testParams.tables[i], i);
    }

    it('should load custom CSS and document title defined in chaise-config.js', function() {
        var chaiseConfig;
        browser.get(browser.params.url + ":" + testParams.tables[0].table_name);
        chaisePage.waitForElement(element(by.id("submit-record-button"))).then(function() {
            return browser.executeScript('return chaiseConfig');
        }).then(function(config) {
            chaiseConfig = config;
            return browser.executeScript('return $("link[href=\'' + chaiseConfig.customCSS + '\']")');
        }).then(function(elemArray) {
            expect(elemArray.length).toBeTruthy();
            return browser.getTitle();
        }).then(function(title) {
            expect(title).toEqual(chaiseConfig.headTitle);
        });
    });

    describe('When url has a prefill query string param set, ', function() {
        var testCookie = {};
        beforeAll(function() {
            // Refresh the page
            browser.get(browser.params.url + ":" + testParams.tables[0].table_name);
            browser.sleep(100);

            // Write a dummy cookie for creating a record in Accommodation table
            testCookie = {
                constraintName: 'product:fk_category', // A FK that Accommodation table has with Category table
                rowname: chance.sentence(),
                keys: {id: 1}
            };
            browser.manage().addCookie({name: 'test', value: JSON.stringify(testCookie)});

            // Reload the page with prefill query param in url
            browser.get(browser.params.url + ":" + testParams.tables[0].table_name + '?prefill=test');
        });

        it('should pre-fill fields from the prefill cookie', function() {
            chaisePage.waitForElement(element(by.id("submit-record-button"))).then(function() {
                return browser.manage().getCookies();
            }).then(function(cookies) {
                var cookie = {name: "no cookie"};
                for (var i = 0; i < cookies.length; i++) {
                    if (cookies[i].name === "test") {
                        cookie = cookies[i];
                    }
                }
                expect(cookie.name).toBe("test");
                var field = element.all(by.css('.popup-select-value')).first();
                expect(field.getText()).toBe(testCookie.rowname);
            });
        });

        afterAll(function() {
            browser.manage().deleteCookie('test');
        });
    });

});
<commit_msg>cookie creation changed<commit_after>var chaisePage = require('../../../../utils/chaise.page.js');
var recordEditHelpers = require('../../helpers.js'), chance = require('chance').Chance();

describe('Record Add', function() {

    var params, testConfiguration = browser.params.configuration.tests, testParams = testConfiguration.params;

    for (var i=0; i< testParams.tables.length; i++) {

    	(function(tableParams, index) {

    		describe("======================================================================= \n    "
    			+ tableParams.records + " record(s) for table " + tableParams.table_name + ",", function() {

				beforeAll(function (done) {
					browser.ignoreSynchronization=true;
					browser.get(browser.params.url + ":" + tableParams.table_name);
                    chaisePage.waitForElement(element(by.id("submit-record-button"))).then(function() {
                        done();
                    });
			    });

				describe("Presentation and validation,", function() {
                    var params = recordEditHelpers.testPresentationAndBasicValidation(tableParams);
				});

				describe("delete record, ", function() {

					if (tableParams.records > 1) {

						it(tableParams.records + " buttons should be visible and enabled", function() {
							chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
								expect(buttons.length).toBe(tableParams.records + 1);
								buttons.forEach(function(btn) {
									expect(btn.isDisplayed()).toBe(true);
									expect(btn.isEnabled()).toBe(true);
								});
							});
						});

						var randomNo = chaisePage.recordEditPage.getRandomInt(0, tableParams.records - 1);

						it("click any delete button", function() {
							chaisePage.recordEditPage.getDeleteRowButton(randomNo).then(function(button)	 {
								chaisePage.clickButton(button);
								browser.sleep(50);
								chaisePage.recordEditPage.getDeleteModalButton().then(function(modalBtn) {
									chaisePage.clickButton(modalBtn);
									browser.sleep(50);
									chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
										expect(buttons.length).toBe(tableParams.records);
									});
								});
							});
						});
					} else {
						it("zero delete buttons should be visible", function() {
							chaisePage.recordEditPage.getAllDeleteRowButtons().then(function(buttons) {
								expect(buttons.length).toBe(1);
								buttons.forEach(function(btn) {
									expect(btn.isDisplayed()).toBe(false);
								});
							});
						});
					}
				});

				describe("Submit " + tableParams.records + " records", function() {
					beforeAll(function() {
						// Submit the form
						chaisePage.recordEditPage.submitForm();
					});

					var hasErrors = false;

					it("should have no errors, and should be redirected", function(done) {
						chaisePage.recordEditPage.getAlertError().then(function(err) {
							if (err) {
								expect("Page has errors").toBe("No errors");
								hasErrors = true;
							} else {
								expect(true).toBe(true);
							}
						});
                        done();
					});

					it("should be redirected to record page", function() {
						if (!hasErrors) {
                            // doesn't redirect to record
                            if (tableParams.records > 1) {
                                // wait for url change
                                browser.wait(function () {
                                    return browser.driver.getCurrentUrl().then(function(url) {
                                        return url.startsWith(process.env.CHAISE_BASE_URL + "/recordedit/");
                                    });
                                }, browser.params.defaultTimeout);
                                // verify url and ct
                                browser.driver.getCurrentUrl().then(function(url) {
    						        expect(url.startsWith(process.env.CHAISE_BASE_URL + "/recordedit/")).toBe(true);

                                    chaisePage.recordsetPage.getRows().count().then(function (ct) {
                                        expect(ct).toBe(tableParams.records);
                                    });
                                });
                            // redirects to record
						    } else {
                                // wait for url change
                                browser.wait(function () {
                                    return browser.driver.getCurrentUrl().then(function(url) {
                                        return url.startsWith(process.env.CHAISE_BASE_URL + "/record/");
                                    });
                                }, browser.params.defaultTimeout);
                                // cerify url
                                browser.driver.getCurrentUrl().then(function(url) {
                                    expect(url.startsWith(process.env.CHAISE_BASE_URL + "/record/")).toBe(true);
                                });
						    }
						}
					});
				});
    		});
    	})(testParams.tables[i], i);
    }

    it('should load custom CSS and document title defined in chaise-config.js', function() {
        var chaiseConfig;
        browser.get(browser.params.url + ":" + testParams.tables[0].table_name);
        chaisePage.waitForElement(element(by.id("submit-record-button"))).then(function() {
            return browser.executeScript('return chaiseConfig');
        }).then(function(config) {
            chaiseConfig = config;
            return browser.executeScript('return $("link[href=\'' + chaiseConfig.customCSS + '\']")');
        }).then(function(elemArray) {
            expect(elemArray.length).toBeTruthy();
            return browser.getTitle();
        }).then(function(title) {
            expect(title).toEqual(chaiseConfig.headTitle);
        });
    });

    describe('When url has a prefill query string param set, ', function() {
        var testCookie = {};
        beforeAll(function() {
            // Refresh the page
            browser.get(browser.params.url + ":" + testParams.tables[0].table_name);
            browser.sleep(100);

            // Write a dummy cookie for creating a record in Accommodation table
            testCookie = {
                constraintName: 'product:fk_category', // A FK that Accommodation table has with Category table
                rowname: chance.sentence(),
                keys: {id: 1}
            };
            browser.manage().addCookie(name: 'test', value: JSON.stringify(testCookie));

            // Reload the page with prefill query param in url
            browser.get(browser.params.url + ":" + testParams.tables[0].table_name + '?prefill=test');
        });

        it('should pre-fill fields from the prefill cookie', function() {
            chaisePage.waitForElement(element(by.id("submit-record-button"))).then(function() {
                return browser.manage().getCookies();
            }).then(function(cookies) {
                var cookie = {name: "no cookie"};
                for (var i = 0; i < cookies.length; i++) {
                    if (cookies[i].name === "test") {
                        cookie = cookies[i];
                    }
                }
                expect(cookie.name).toBe("test");
                var field = element.all(by.css('.popup-select-value')).first();
                expect(field.getText()).toBe(testCookie.rowname);
            });
        });

        afterAll(function() {
            browser.manage().deleteCookie('test');
        });
    });

});
<|endoftext|>


<commit_before>/* global module:false define:false */

(function (global, factory) {
    if (typeof exports === 'object' && typeof module !== 'undefined') {
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        define(factory);
    } else {
        global.resterFormatJson = factory();
    }
})(this, function () {
    const S = (function () {
        let s = 0;
        return {
            VALUE: s++,
            STRING: s++,
            STRING_SLASHED: s++,
            STRING_SLASHED_U_1: s++,
            STRING_SLASHED_U_2: s++,
            STRING_SLASHED_U_3: s++,
            STRING_SLASHED_U_4: s++,
            NUMBER: s++,
            OBJECT: s++,
            OBJECT_KEY: s++,
            OBJECT_VALUE: s++,
            OBJECT_VALUE_END: s++,
            ARRAY: s++,
            ARRAY_VALUE_END: s++,
            TRUE_1: s++,
            TRUE_2: s++,
            TRUE_3: s++,
            FALSE_1: s++,
            FALSE_2: s++,
            FALSE_3: s++,
            FALSE_4: s++,
            NULL_1: s++,
            NULL_2: s++,
            NULL_3: s++,
            END: s++,
        };
    })();
    const INDENT_SIZE = 4;
    const NUMBER_START_CHARS = new Set('-0123456789');
    const NUMBER_CHARS = new Set('-+0123456789.eE');
    const STRING_ESCAPED_CHARS = new Set('"\\/bfnrt');
    const WHITESPACE_CHARS = new Set('\r\n \t');
    const HEX_CHARS = new Set('0123456789abcdefABCDEF');

    function formatJson(str) {
        let result = '';

        let indent = 0;
        let formatBefore = '';
        let formatAfter = '';

        const len = str.length;
        let state = S.VALUE;
        const nextState = [S.END];
        for (let i = 0; i < len; i++) {
            const c = str[i];

            switch (state) {
                case S.VALUE:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === '"') {
                        state = S.STRING;
                    } else if (NUMBER_START_CHARS.has(c)) {
                        state = S.NUMBER;
                    } else if (c === '{') {
                        state = S.OBJECT;
                    } else if (c === '[') {
                        state = S.ARRAY;
                    } else if (c === 't') {
                        state = S.TRUE_1;
                    } else if (c === 'f') {
                        state = S.FALSE_1;
                    } else if (c === 'n') {
                        state = S.NULL_1;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.STRING:
                    if (c === '\\') {
                        state = S.STRING_SLASHED;
                        nextState.push(S.STRING);
                    } else if (c === '"') {
                        state = nextState.pop();
                    } else {
                        // TODO: is this a valid character in the string?
                    }
                    break;
                case S.STRING_SLASHED:
                    if (STRING_ESCAPED_CHARS.has(c)) {
                        state = nextState.pop();
                    } else if (c === 'u') {
                        state = S.STRING_SLASHED_U_1;
                    } else {
                        throw new ParseError(
                            'invalid escaped char in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_1:
                    if (HEX_CHARS.has(c)) {
                        state = S.STRING_SLASHED_U_2;
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_2:
                    if (HEX_CHARS.has(c)) {
                        state = S.STRING_SLASHED_U_3;
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_3:
                    if (HEX_CHARS.has(c)) {
                        state = S.STRING_SLASHED_U_4;
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_4:
                    if (HEX_CHARS.has(c)) {
                        state = nextState.pop();
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.NUMBER:
                    // TODO: validate number format?
                    if (!NUMBER_CHARS.has(c)) {
                        state = nextState.pop();
                        i--;
                        continue;
                    }
                    break;
                case S.OBJECT:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === '"') {
                        indent += INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state = S.STRING;
                        nextState.push(S.OBJECT_VALUE);
                    } else if (c === '}') {
                        state = nextState.pop();
                    } else {
                        throw new ParseError('invalid object', i);
                    }
                    break;
                case S.OBJECT_KEY:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === '"') {
                        state = S.STRING;
                        nextState.push(S.OBJECT_VALUE);
                    } else {
                        throw new ParseError('invalid object key', i);
                    }
                    break;
                case S.OBJECT_VALUE:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ':') {
                        formatAfter = ' ';
                        state = S.VALUE;
                        nextState.push(S.OBJECT_VALUE_END);
                    } else {
                        throw new ParseError('invalid object value', i);
                    }
                    break;
                case S.OBJECT_VALUE_END:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ',') {
                        formatAfter = generateIndent(indent);
                        state = S.OBJECT_KEY;
                    } else if (c === '}') {
                        indent -= INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state = nextState.pop();
                    } else {
                        throw new ParseError('invalid object', i);
                    }
                    break;
                case S.ARRAY:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ']') {
                        state = nextState.pop();
                    } else {
                        indent += INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state = S.VALUE;
                        nextState.push(S.ARRAY_VALUE_END);
                        i--;
                        continue;
                    }
                    break;
                case S.ARRAY_VALUE_END:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ',') {
                        formatAfter = generateIndent(indent);
                        state = S.VALUE;
                        nextState.push(S.ARRAY_VALUE_END);
                    } else if (c === ']') {
                        indent -= INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state = nextState.pop();
                    } else {
                        throw new ParseError('invalid array', i);
                    }
                    break;
                case S.TRUE_1:
                    if (c === 'r') {
                        state = S.TRUE_2;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.TRUE_2:
                    if (c === 'u') {
                        state = S.TRUE_3;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.TRUE_3:
                    if (c === 'e') {
                        state = nextState.pop();
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_1:
                    if (c === 'a') {
                        state = S.FALSE_2;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_2:
                    if (c === 'l') {
                        state = S.FALSE_3;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_3:
                    if (c === 's') {
                        state = S.FALSE_4;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_4:
                    if (c === 'e') {
                        state = nextState.pop();
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.NULL_1:
                    if (c === 'u') {
                        state = S.NULL_2;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.NULL_2:
                    if (c === 'l') {
                        state = S.NULL_3;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.NULL_3:
                    if (c === 'l') {
                        state = nextState.pop();
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.END:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    throw new ParseError('invalid end', i);
                default:
                    throw new ParseError('invalid state', i);
            }

            result += formatBefore + c + formatAfter;
            formatBefore = '';
            formatAfter = '';
        }
        if (state === S.NUMBER) {
            state = nextState.pop();
        }

        if (state !== S.END) {
            throw new ParseError('incomplete json', len);
        }

        return result;
    }

    function generateIndent(indent) {
        return '\n' + ' '.repeat(indent);
    }

    class ParseError extends Error {
        constructor(msg, i) {
            super(`ParseError at ${i}: ${msg}`);
        }
    }

    return {
        formatJson,
        ParseError,
    };
});
<commit_msg>Limit nesting depth<commit_after>/* global module:false define:false */

(function (global, factory) {
    if (typeof exports === 'object' && typeof module !== 'undefined') {
        module.exports = factory();
    } else if (typeof define === 'function' && define.amd) {
        define(factory);
    } else {
        global.resterFormatJson = factory();
    }
})(this, function () {
    const S = (function () {
        let s = 0;
        return {
            VALUE: s++,
            STRING: s++,
            STRING_SLASHED: s++,
            STRING_SLASHED_U_1: s++,
            STRING_SLASHED_U_2: s++,
            STRING_SLASHED_U_3: s++,
            STRING_SLASHED_U_4: s++,
            NUMBER: s++,
            OBJECT: s++,
            OBJECT_KEY: s++,
            OBJECT_VALUE: s++,
            OBJECT_VALUE_END: s++,
            ARRAY: s++,
            ARRAY_VALUE_END: s++,
            TRUE_1: s++,
            TRUE_2: s++,
            TRUE_3: s++,
            FALSE_1: s++,
            FALSE_2: s++,
            FALSE_3: s++,
            FALSE_4: s++,
            NULL_1: s++,
            NULL_2: s++,
            NULL_3: s++,
            END: s++,
        };
    })();
    const INDENT_SIZE = 4;
    const MAX_DEPTH = 500;
    const NUMBER_START_CHARS = new Set('-0123456789');
    const NUMBER_CHARS = new Set('-+0123456789.eE');
    const STRING_ESCAPED_CHARS = new Set('"\\/bfnrt');
    const WHITESPACE_CHARS = new Set('\r\n \t');
    const HEX_CHARS = new Set('0123456789abcdefABCDEF');

    class State {
        constructor(initial, final) {
            this.current = initial;
            this.next = [final];
        }

        push(next) {
            if (this.next.length > MAX_DEPTH) {
                throw new ParseError('max depth reached', Number.NaN);
            }

            this.next.push(next);
        }

        pop() {
            this.current = this.next.pop();
        }
    }

    function formatJson(str) {
        let result = '';

        let indent = 0;
        let formatBefore = '';
        let formatAfter = '';

        const len = str.length;
        const state = new State(S.VALUE, S.END);
        for (let i = 0; i < len; i++) {
            const c = str[i];

            switch (state.current) {
                case S.VALUE:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === '"') {
                        state.current = S.STRING;
                    } else if (NUMBER_START_CHARS.has(c)) {
                        state.current = S.NUMBER;
                    } else if (c === '{') {
                        state.current = S.OBJECT;
                    } else if (c === '[') {
                        state.current = S.ARRAY;
                    } else if (c === 't') {
                        state.current = S.TRUE_1;
                    } else if (c === 'f') {
                        state.current = S.FALSE_1;
                    } else if (c === 'n') {
                        state.current = S.NULL_1;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.STRING:
                    if (c === '\\') {
                        state.current = S.STRING_SLASHED;
                        state.push(S.STRING);
                    } else if (c === '"') {
                        state.pop();
                    } else {
                        // TODO: is this a valid character in the string?
                    }
                    break;
                case S.STRING_SLASHED:
                    if (STRING_ESCAPED_CHARS.has(c)) {
                        state.pop();
                    } else if (c === 'u') {
                        state.current = S.STRING_SLASHED_U_1;
                    } else {
                        throw new ParseError(
                            'invalid escaped char in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_1:
                    if (HEX_CHARS.has(c)) {
                        state.current = S.STRING_SLASHED_U_2;
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_2:
                    if (HEX_CHARS.has(c)) {
                        state.current = S.STRING_SLASHED_U_3;
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_3:
                    if (HEX_CHARS.has(c)) {
                        state.current = S.STRING_SLASHED_U_4;
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.STRING_SLASHED_U_4:
                    if (HEX_CHARS.has(c)) {
                        state.pop();
                    } else {
                        throw new ParseError(
                            'invalid escaped unicode in string',
                            i
                        );
                    }
                    break;
                case S.NUMBER:
                    // TODO: validate number format?
                    if (!NUMBER_CHARS.has(c)) {
                        state.pop();
                        i--;
                        continue;
                    }
                    break;
                case S.OBJECT:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === '"') {
                        indent += INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state.current = S.STRING;
                        state.push(S.OBJECT_VALUE);
                    } else if (c === '}') {
                        state.pop();
                    } else {
                        throw new ParseError('invalid object', i);
                    }
                    break;
                case S.OBJECT_KEY:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === '"') {
                        state.current = S.STRING;
                        state.push(S.OBJECT_VALUE);
                    } else {
                        throw new ParseError('invalid object key', i);
                    }
                    break;
                case S.OBJECT_VALUE:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ':') {
                        formatAfter = ' ';
                        state.current = S.VALUE;
                        state.push(S.OBJECT_VALUE_END);
                    } else {
                        throw new ParseError('invalid object value', i);
                    }
                    break;
                case S.OBJECT_VALUE_END:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ',') {
                        formatAfter = generateIndent(indent);
                        state.current = S.OBJECT_KEY;
                    } else if (c === '}') {
                        indent -= INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state.pop();
                    } else {
                        throw new ParseError('invalid object', i);
                    }
                    break;
                case S.ARRAY:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ']') {
                        state.pop();
                    } else {
                        indent += INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state.current = S.VALUE;
                        state.push(S.ARRAY_VALUE_END);
                        i--;
                        continue;
                    }
                    break;
                case S.ARRAY_VALUE_END:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    if (c === ',') {
                        formatAfter = generateIndent(indent);
                        state.current = S.VALUE;
                        state.push(S.ARRAY_VALUE_END);
                    } else if (c === ']') {
                        indent -= INDENT_SIZE;
                        formatBefore = generateIndent(indent);
                        state.pop();
                    } else {
                        throw new ParseError('invalid array', i);
                    }
                    break;
                case S.TRUE_1:
                    if (c === 'r') {
                        state.current = S.TRUE_2;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.TRUE_2:
                    if (c === 'u') {
                        state.current = S.TRUE_3;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.TRUE_3:
                    if (c === 'e') {
                        state.pop();
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_1:
                    if (c === 'a') {
                        state.current = S.FALSE_2;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_2:
                    if (c === 'l') {
                        state.current = S.FALSE_3;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_3:
                    if (c === 's') {
                        state.current = S.FALSE_4;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.FALSE_4:
                    if (c === 'e') {
                        state.pop();
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.NULL_1:
                    if (c === 'u') {
                        state.current = S.NULL_2;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.NULL_2:
                    if (c === 'l') {
                        state.current = S.NULL_3;
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.NULL_3:
                    if (c === 'l') {
                        state.pop();
                    } else {
                        throw new ParseError('invalid value', i);
                    }
                    break;
                case S.END:
                    if (WHITESPACE_CHARS.has(c)) continue;
                    throw new ParseError('invalid end', i);
                default:
                    throw new ParseError('invalid state', i);
            }

            result += formatBefore + c + formatAfter;
            formatBefore = '';
            formatAfter = '';
        }
        if (state.current === S.NUMBER) {
            state.pop();
        }

        if (state.current !== S.END) {
            throw new ParseError('incomplete json', len);
        }

        return result;
    }

    function generateIndent(indent) {
        return '\n' + ' '.repeat(indent);
    }

    class ParseError extends Error {
        constructor(msg, i) {
            super(`ParseError at ${i}: ${msg}`);
        }
    }

    return {
        formatJson,
        ParseError,
    };
});
<|endoftext|>


<commit_before>import buble from 'rollup-plugin-buble';
import { terser } from "rollup-plugin-terser";

function glconstants() {

	var constants = {
		POINTS: 0, ZERO: 0,
		LINES: 1, ONE: 1,
		LINE_LOOP: 2,
		LINE_STRIP: 3,
		TRIANGLES: 4,
		TRIANGLE_STRIP: 5,
		TRIANGLE_FAN: 6,
		DEPTH_BUFFER_BIT: 256,
		LESS: 513,
		NEVER: 512,
		EQUAL: 514,
		LEQUAL: 515,
		GREATER: 516,
		NOTEQUAL: 517,
		GEQUAL: 518,
		ALWAYS: 519,
		SRC_COLOR: 768,
		ONE_MINUS_SRC_COLOR: 769,
		SRC_ALPHA: 770,
		ONE_MINUS_SRC_ALPHA: 771,
		DST_ALPHA: 772,
		ONE_MINUS_DST_ALPHA: 773,
		DST_COLOR: 774,
		ONE_MINUS_DST_COLOR: 775,
		SRC_ALPHA_SATURATE: 776,
		STENCIL_BUFFER_BIT: 1024,
		FRONT: 1028,
		BACK: 1029,
		FRONT_AND_BACK: 1032,
		CW: 2304,
		CCW: 2305,
		CULL_FACE: 2884,
		DEPTH_TEST: 2929,
		STENCIL_TEST: 2960,
		BLEND: 3042,
		SCISSOR_TEST: 3089,
		UNPACK_ALIGNMENT: 3317,
		MAX_TEXTURE_SIZE: 3379,
		DEPTH24_STENCIL8: 35056,
		TEXTURE_2D: 3553,
		BYTE: 5120,
		UNSIGNED_BYTE: 5121,
		SHORT: 5122,
		UNSIGNED_INT: 5125,
		UNSIGNED_SHORT: 5123,
		INT: 5124,
		FLOAT: 5126,
		HALF_FLOAT: 5131,
		DEPTH_COMPONENT: 6402,
		RED: 6403,
		ALPHA: 6406,
		RGB: 6407,
		RGBA: 6408,
		LUMINANCE: 6409,
		LUMINANCE_ALPHA: 6410,
		RED_INTEGER: 36244,
		RG: 33319,
		RG_INTEGER: 33320,
		RGB_INTEGER: 36248,
		RGBA_INTEGER: 36249,
		VERSION: 7938,
		NEAREST: 9728,
		LINEAR: 9729,
		NEAREST_MIPMAP_NEAREST: 9984,
		LINEAR_MIPMAP_NEAREST: 9985,
		NEAREST_MIPMAP_LINEAR: 9986,
		LINEAR_MIPMAP_LINEAR: 9987,
		TEXTURE_MAG_FILTER: 10240,
		TEXTURE_MIN_FILTER: 10241,
		TEXTURE_WRAP_S: 10242,
		TEXTURE_WRAP_T: 10243,
		TEXTURE_WRAP_R: 32882,
		REPEAT: 10497,
		COLOR_BUFFER_BIT: 16384,
		FUNC_ADD: 32774,
		MIN: 32775,
		MAX: 32776,
		FUNC_SUBTRACT: 32778,
		FUNC_REVERSE_SUBTRACT: 32779,
		UNSIGNED_SHORT_4_4_4_4: 32819,
		UNSIGNED_SHORT_5_5_5_1: 32820,
		POLYGON_OFFSET_FILL: 32823,
		RGB8: 32849,
		RGBA4: 32854,
		RGBA8: 32856,
		TEXTURE_3D: 32879,
		CLAMP_TO_EDGE: 33071,
		DEPTH_COMPONENT16: 33189,
		DEPTH_COMPONENT24: 33190,
		DEPTH_COMPONENT32F: 36012,
		DEPTH_STENCIL_ATTACHMENT: 33306,
		R8: 33321,
		R16F: 33325,
		R32F: 33326,
		UNSIGNED_SHORT_5_6_5: 33635,
		MIRRORED_REPEAT: 33648,
		TEXTURE0: 33984,
		DEPTH_STENCIL: 34041,
		UNSIGNED_INT_24_8: 34042,
		TEXTURE_CUBE_MAP: 34067,
		TEXTURE_CUBE_MAP_POSITIVE_X: 34069,
		MAX_CUBE_MAP_TEXTURE_SIZE: 34076,
		COMPRESSED_TEXTURE_FORMATS: 34467,
		RGBA32F: 34836,
		RGB32F: 34837,
		RGBA16F: 34842,
		RGB16F: 34843,
		MAX_VERTEX_ATTRIBS: 34921,
		MAX_TEXTURE_IMAGE_UNITS: 34930,
		ARRAY_BUFFER: 34962,
		ELEMENT_ARRAY_BUFFER: 34963,
		STATIC_DRAW: 35044,
		DYNAMIC_DRAW: 35048,
		VERTEX_SHADER: 35633,
		FRAGMENT_SHADER: 35632,
		MAX_VERTEX_TEXTURE_IMAGE_UNITS: 35660,
		MAX_COMBINED_TEXTURE_IMAGE_UNITS: 35661,
		COMPILE_STATUS: 35713,
		LINK_STATUS: 35714,
		VALIDATE_STATUS: 35715,
		ACTIVE_UNIFORMS: 35718,
		ACTIVE_ATTRIBUTES: 35721,
		IMPLEMENTATION_COLOR_READ_TYPE: 35738,
		IMPLEMENTATION_COLOR_READ_FORMAT: 35739,
		TEXTURE_2D_ARRAY: 35866,
		COLOR_ATTACHMENT0: 36064,
		FRAMEBUFFER_COMPLETE: 36053,
		DEPTH_ATTACHMENT: 36096,
		FRAMEBUFFER: 36160,
		RENDERBUFFER: 36161,
		LOW_FLOAT: 36336,
		MEDIUM_FLOAT: 36337,
		HIGH_FLOAT: 36338,
		MAX_VERTEX_UNIFORM_VECTORS: 36347,
		MAX_VARYING_VECTORS: 36348,
		MAX_FRAGMENT_UNIFORM_VECTORS: 36349,
		UNPACK_FLIP_Y_WEBGL: 37440,
		UNPACK_PREMULTIPLY_ALPHA_WEBGL: 37441,
		MAX_SAMPLES: 36183,
		READ_FRAMEBUFFER: 36008,
		DRAW_FRAMEBUFFER: 36009
	};

	return {

		transform( code ) {

			code = code.replace( /_?gl\.([A-Z0-9_]+)/g, function ( match, p1 ) {

				if ( p1 in constants ) return constants[ p1 ];
				console.log( '* Unhandled GL Constant:', p1 );
				return match;

			} );

			return {
				code: code,
				map: null
			};

		}

	};

}

function glsl() {

	return {

		transform( code, id ) {

			if ( /\.glsl.js$/.test( id ) === false ) return;

			code = code.replace( /\/\* glsl \*\/\`((.|\n)*)\`/, function ( match, p1 ) {

				return JSON.stringify(
					p1
						.trim()
						.replace( /\r/g, '' )
						.replace( /[ \t]*\/\/.*\n/g, '' ) // remove //
						.replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ) // remove /* */
						.replace( /\n{2,}/g, '\n' ) // # \n+ to \n
				);

			} );

			return {
				code: code,
				map: null
			};

		}

	};

}

function bubleCleanup() {

	const danglingTabs = /(^\t+$\n)|(\n^\t+$)/gm;
	const wrappedClass = /(var (\w+) = \/\*@__PURE__*\*\/\(function \((\w+)\) {\n).*(return \2;\s+}\(\3\)\);\n)/s;
	const unwrap = function ( match, wrapperStart, klass, parentClass, wrapperEnd ) {

		return match
			.replace( wrapperStart, '' )
			.replace( `if ( ${parentClass} ) ${klass}.__proto__ = ${parentClass};`, '' )
			.replace(
				`${klass}.prototype = Object.create( ${parentClass} && ${parentClass}.prototype );`,
				`${klass}.prototype = Object.create( ${parentClass}.prototype );`
			)
			.replace( wrapperEnd, '' )
			.replace( danglingTabs, '' );

	};

	return {

		transform( code ) {

			while ( wrappedClass.test( code ) ) {

				code = code.replace( wrappedClass, unwrap );

			}

			return {
				code: code,
				map: null
			};

		}

	};

}

function header() {

	const template = "// threejs.org/license\n${code}";

	return {

		renderChunk( code ) {

			return template.replace( '${code}', code );

		}

	};

}

export default [
	{
		input: 'src/Three.js',
		plugins: [
			glconstants(),
			glsl(),
			buble( {
				transforms: {
					arrow: false,
					classes: true
				}
			} ),
			bubleCleanup(),
			header()
		],
		output: [
			{
				format: 'umd',
				name: 'THREE',
				file: 'build/three.js',
				indent: '\t'
			}
		]
	},
	{
		input: 'src/Three.js',
		plugins: [
			glconstants(),
			glsl(),
			buble( {
				transforms: {
					arrow: false,
					classes: true
				}
			} ),
			bubleCleanup(),
			terser(),
			header()
		],
		output: [
			{
				format: 'umd',
				name: 'THREE',
				file: 'build/three.min.js',
				indent: '\t'
			}
		]
	},
	{
		input: 'src/Three.js',
		plugins: [
			glconstants(),
			glsl(),
			header()
		],
		output: [
			{
				format: 'esm',
				file: 'build/three.module.js',
				indent: '\t'
			}
		]
	}

];
<commit_msg>Clean up.<commit_after>import buble from 'rollup-plugin-buble';
import { terser } from "rollup-plugin-terser";

function glconstants() {

	var constants = {
		POINTS: 0, ZERO: 0,
		LINES: 1, ONE: 1,
		LINE_LOOP: 2,
		LINE_STRIP: 3,
		TRIANGLES: 4,
		TRIANGLE_STRIP: 5,
		TRIANGLE_FAN: 6,
		DEPTH_BUFFER_BIT: 256,
		LESS: 513,
		NEVER: 512,
		EQUAL: 514,
		LEQUAL: 515,
		GREATER: 516,
		NOTEQUAL: 517,
		GEQUAL: 518,
		ALWAYS: 519,
		SRC_COLOR: 768,
		ONE_MINUS_SRC_COLOR: 769,
		SRC_ALPHA: 770,
		ONE_MINUS_SRC_ALPHA: 771,
		DST_ALPHA: 772,
		ONE_MINUS_DST_ALPHA: 773,
		DST_COLOR: 774,
		ONE_MINUS_DST_COLOR: 775,
		SRC_ALPHA_SATURATE: 776,
		STENCIL_BUFFER_BIT: 1024,
		FRONT: 1028,
		BACK: 1029,
		FRONT_AND_BACK: 1032,
		CW: 2304,
		CCW: 2305,
		CULL_FACE: 2884,
		DEPTH_TEST: 2929,
		STENCIL_TEST: 2960,
		BLEND: 3042,
		SCISSOR_TEST: 3089,
		UNPACK_ALIGNMENT: 3317,
		MAX_TEXTURE_SIZE: 3379,
		DEPTH24_STENCIL8: 35056,
		TEXTURE_2D: 3553,
		BYTE: 5120,
		UNSIGNED_BYTE: 5121,
		SHORT: 5122,
		UNSIGNED_INT: 5125,
		UNSIGNED_SHORT: 5123,
		INT: 5124,
		FLOAT: 5126,
		HALF_FLOAT: 5131,
		DEPTH_COMPONENT: 6402,
		RED: 6403,
		ALPHA: 6406,
		RGB: 6407,
		RGBA: 6408,
		LUMINANCE: 6409,
		LUMINANCE_ALPHA: 6410,
		RED_INTEGER: 36244,
		RG: 33319,
		RG_INTEGER: 33320,
		RGB_INTEGER: 36248,
		RGBA_INTEGER: 36249,
		VERSION: 7938,
		NEAREST: 9728,
		LINEAR: 9729,
		NEAREST_MIPMAP_NEAREST: 9984,
		LINEAR_MIPMAP_NEAREST: 9985,
		NEAREST_MIPMAP_LINEAR: 9986,
		LINEAR_MIPMAP_LINEAR: 9987,
		TEXTURE_MAG_FILTER: 10240,
		TEXTURE_MIN_FILTER: 10241,
		TEXTURE_WRAP_S: 10242,
		TEXTURE_WRAP_T: 10243,
		TEXTURE_WRAP_R: 32882,
		REPEAT: 10497,
		COLOR_BUFFER_BIT: 16384,
		FUNC_ADD: 32774,
		MIN: 32775,
		MAX: 32776,
		FUNC_SUBTRACT: 32778,
		FUNC_REVERSE_SUBTRACT: 32779,
		UNSIGNED_SHORT_4_4_4_4: 32819,
		UNSIGNED_SHORT_5_5_5_1: 32820,
		POLYGON_OFFSET_FILL: 32823,
		RGB8: 32849,
		RGBA4: 32854,
		RGBA8: 32856,
		TEXTURE_3D: 32879,
		CLAMP_TO_EDGE: 33071,
		DEPTH_COMPONENT16: 33189,
		DEPTH_COMPONENT24: 33190,
		DEPTH_COMPONENT32F: 36012,
		DEPTH_STENCIL_ATTACHMENT: 33306,
		R8: 33321,
		R16F: 33325,
		R32F: 33326,
		UNSIGNED_SHORT_5_6_5: 33635,
		MIRRORED_REPEAT: 33648,
		TEXTURE0: 33984,
		DEPTH_STENCIL: 34041,
		UNSIGNED_INT_24_8: 34042,
		TEXTURE_CUBE_MAP: 34067,
		TEXTURE_CUBE_MAP_POSITIVE_X: 34069,
		MAX_CUBE_MAP_TEXTURE_SIZE: 34076,
		COMPRESSED_TEXTURE_FORMATS: 34467,
		RGBA32F: 34836,
		RGB32F: 34837,
		RGBA16F: 34842,
		RGB16F: 34843,
		MAX_VERTEX_ATTRIBS: 34921,
		MAX_TEXTURE_IMAGE_UNITS: 34930,
		ARRAY_BUFFER: 34962,
		ELEMENT_ARRAY_BUFFER: 34963,
		STATIC_DRAW: 35044,
		DYNAMIC_DRAW: 35048,
		VERTEX_SHADER: 35633,
		FRAGMENT_SHADER: 35632,
		MAX_VERTEX_TEXTURE_IMAGE_UNITS: 35660,
		MAX_COMBINED_TEXTURE_IMAGE_UNITS: 35661,
		COMPILE_STATUS: 35713,
		LINK_STATUS: 35714,
		VALIDATE_STATUS: 35715,
		ACTIVE_UNIFORMS: 35718,
		ACTIVE_ATTRIBUTES: 35721,
		IMPLEMENTATION_COLOR_READ_TYPE: 35738,
		IMPLEMENTATION_COLOR_READ_FORMAT: 35739,
		TEXTURE_2D_ARRAY: 35866,
		COLOR_ATTACHMENT0: 36064,
		FRAMEBUFFER_COMPLETE: 36053,
		DEPTH_ATTACHMENT: 36096,
		FRAMEBUFFER: 36160,
		RENDERBUFFER: 36161,
		LOW_FLOAT: 36336,
		MEDIUM_FLOAT: 36337,
		HIGH_FLOAT: 36338,
		MAX_VERTEX_UNIFORM_VECTORS: 36347,
		MAX_VARYING_VECTORS: 36348,
		MAX_FRAGMENT_UNIFORM_VECTORS: 36349,
		UNPACK_FLIP_Y_WEBGL: 37440,
		UNPACK_PREMULTIPLY_ALPHA_WEBGL: 37441,
		MAX_SAMPLES: 36183,
		READ_FRAMEBUFFER: 36008,
		DRAW_FRAMEBUFFER: 36009
	};

	return {

		transform( code ) {

			code = code.replace( /_?gl\.([A-Z0-9_]+)/g, function ( match, p1 ) {

				if ( p1 in constants ) return constants[ p1 ];
				console.log( '* Unhandled GL Constant:', p1 );
				return match;

			} );

			return {
				code: code,
				map: null
			};

		}

	};

}

function glsl() {

	return {

		transform( code, id ) {

			if ( /\.glsl.js$/.test( id ) === false ) return;

			code = code.replace( /\/\* glsl \*\/\`((.|\n)*)\`/, function ( match, p1 ) {

				return JSON.stringify(
					p1
						.trim()
						.replace( /\r/g, '' )
						.replace( /[ \t]*\/\/.*\n/g, '' ) // remove //
						.replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ) // remove /* */
						.replace( /\n{2,}/g, '\n' ) // # \n+ to \n
				);

			} );

			return {
				code: code,
				map: null
			};

		}

	};

}

function bubleCleanup() {

	const danglingTabs = /(^\t+$\n)|(\n^\t+$)/gm;
	const wrappedClass = /(var (\w+) = \/\*@__PURE__*\*\/\(function \((\w+)\) {\n).*(return \2;\s+}\(\3\)\);\n)/s;
	const unwrap = function ( match, wrapperStart, klass, parentClass, wrapperEnd ) {

		return match
			.replace( wrapperStart, '' )
			.replace( `if ( ${parentClass} ) ${klass}.__proto__ = ${parentClass};`, '' )
			.replace(
				`${klass}.prototype = Object.create( ${parentClass} && ${parentClass}.prototype );`,
				`${klass}.prototype = Object.create( ${parentClass}.prototype );`
			)
			.replace( wrapperEnd, '' )
			.replace( danglingTabs, '' );

	};

	return {

		transform( code ) {

			while ( wrappedClass.test( code ) ) {

				code = code.replace( wrappedClass, unwrap );

			}

			return {
				code: code,
				map: null
			};

		}

	};

}

function header() {

	const template = "// threejs.org/license\n${code}";

	return {

		renderChunk( code ) {

			return template.replace( '${code}', code );

		}

	};

}

export default [
	{
		input: 'src/Three.js',
		plugins: [
			glconstants(),
			glsl(),
			buble( {
				transforms: {
					arrow: false,
					classes: true
				}
			} ),
			bubleCleanup(),
			header()
		],
		output: [
			{
				format: 'umd',
				name: 'THREE',
				file: 'build/three.js',
				indent: '\t'
			}
		]
	},
	{
		input: 'src/Three.js',
		plugins: [
			glconstants(),
			glsl(),
			buble( {
				transforms: {
					arrow: false,
					classes: true
				}
			} ),
			bubleCleanup(),
			terser(),
			header()
		],
		output: [
			{
				format: 'umd',
				name: 'THREE',
				file: 'build/three.min.js',
				indent: '\t'
			}
		]
	},
	{
		input: 'src/Three.js',
		plugins: [
			glconstants(),
			glsl(),
			header()
		],
		output: [
			{
				format: 'esm',
				file: 'build/three.module.js',
				indent: '\t'
			}
		]
	}
];
<|endoftext|>