<commit_before>(function () {
  // Eagerly require cached-run-in-this-context to prevent a circular require
  // when using `NativeCompileCache` for the first time.
  require('cached-run-in-this-context')

  const electron = require('electron')
  const path = require('path')
  const Module = require('module')
  const getWindowLoadSettings = require('../src/get-window-load-settings')
  const entryPointDirPath = __dirname
  let blobStore = null
  let useSnapshot = false

  window.onload = function () {
    try {
      const startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      setupAtomHome()
      const devMode = getWindowLoadSettings().devMode || !getWindowLoadSettings().resourcePath.startsWith(process.resourcesPath + path.sep)
      useSnapshot = !devMode && typeof snapshotResult !== 'undefined'

      if (devMode) {
        const metadata = require('../package.json')
        if (!metadata._deprecatedPackages) {
          try {
            metadata._deprecatedPackages = require('../script/deprecated-packages.json')
          } catch (requireError) {
            console.error('Failed to setup deprecated packages list', requireError.stack)
          }
        }
      } else if (useSnapshot) {
        Module.prototype.require = function (module) {
          const absoluteFilePath = Module._resolveFilename(module, this, false)
          const relativeFilePath = path.relative(entryPointDirPath, absoluteFilePath)
          let cachedModule = snapshotResult.customRequire.cache[relativeFilePath]
          if (!cachedModule) {
            cachedModule = Module._load(module, this, false)
            snapshotResult.customRequire.cache[relativeFilePath] = cachedModule
          }
          return cachedModule
        }

        snapshotResult.setGlobals(global, process, window, document, require)
        snapshotResult.entryPointDirPath = __dirname
      }

      const FileSystemBlobStore = useSnapshot ? snapshotResult.customRequire('../src/file-system-blob-store.js') : require('../src/file-system-blob-store')
      blobStore = FileSystemBlobStore.load(path.join(process.env.ATOM_HOME, 'blob-store'))

      const NativeCompileCache = useSnapshot ? snapshotResult.customRequire('../src/native-compile-cache.js') : require('../src/native-compile-cache')
      NativeCompileCache.setCacheStore(blobStore)
      NativeCompileCache.setV8Version(process.versions.v8)
      NativeCompileCache.install()

      if (getWindowLoadSettings().profileStartup) {
        profileStartup(Date.now() - startTime)
      } else {
        setupWindow()
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
    }
  }

  function handleSetupError (error) {
    const currentWindow = electron.remote.getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow () {
    const CompileCache = useSnapshot ? snapshotResult.customRequire('../src/compile-cache.js') : require('../src/compile-cache')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)
    CompileCache.install(require)

    const ModuleCache = useSnapshot ? snapshotResult.customRequire('../src/module-cache.js') : require('../src/module-cache')
    ModuleCache.register(getWindowLoadSettings())

    const startCrashReporter = useSnapshot ? snapshotResult.customRequire('../src/crash-reporter-start.js') : require('../src/crash-reporter-start')
    startCrashReporter({_version: getWindowLoadSettings().appVersion})

    const CSON = useSnapshot ? snapshotResult.customRequire('../node_modules/season/lib/cson.js') : require('season')
    CSON.setCacheDir(path.join(CompileCache.getCacheDirectory(), 'cson'))

    const initScriptPath = path.relative(entryPointDirPath, getWindowLoadSettings().windowInitializationScript)
    const initialize = useSnapshot ? snapshotResult.customRequire(initScriptPath) : require(initScriptPath)
    return initialize({blobStore: blobStore}).then(function () {
      electron.ipcRenderer.send('window-command', 'window:loaded')
    })
  }

  function profileStartup (initialTime) {
    function profile () {
      console.profile('startup')
      const startTime = Date.now()
      setupWindow().then(function () {
        setLoadTime(Date.now() - startTime + initialTime)
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      })
    }

    const webContents = electron.remote.getCurrentWindow().webContents
    if (webContents.devToolsWebContents) {
      profile()
    } else {
      webContents.once('devtools-opened', () => { setTimeout(profile, 1000) })
      webContents.openDevTools()
    }
  }

  function setupAtomHome () {
    if (process.env.ATOM_HOME) {
      return
    }

    // Ensure ATOM_HOME is always set before anything else is required
    // This is because of a difference in Linux not inherited between browser and render processes
    // https://github.com/atom/atom/issues/5412
    if (getWindowLoadSettings() && getWindowLoadSettings().atomHome) {
      process.env.ATOM_HOME = getWindowLoadSettings().atomHome
    }
  }
})()
<commit_msg>Don't assign snapshotResult.entryPointDirPath<commit_after>(function () {
  // Eagerly require cached-run-in-this-context to prevent a circular require
  // when using `NativeCompileCache` for the first time.
  require('cached-run-in-this-context')

  const electron = require('electron')
  const path = require('path')
  const Module = require('module')
  const getWindowLoadSettings = require('../src/get-window-load-settings')
  const entryPointDirPath = __dirname
  let blobStore = null
  let useSnapshot = false

  window.onload = function () {
    try {
      const startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      setupAtomHome()
      const devMode = getWindowLoadSettings().devMode || !getWindowLoadSettings().resourcePath.startsWith(process.resourcesPath + path.sep)
      useSnapshot = !devMode && typeof snapshotResult !== 'undefined'

      if (devMode) {
        const metadata = require('../package.json')
        if (!metadata._deprecatedPackages) {
          try {
            metadata._deprecatedPackages = require('../script/deprecated-packages.json')
          } catch (requireError) {
            console.error('Failed to setup deprecated packages list', requireError.stack)
          }
        }
      } else if (useSnapshot) {
        Module.prototype.require = function (module) {
          const absoluteFilePath = Module._resolveFilename(module, this, false)
          const relativeFilePath = path.relative(entryPointDirPath, absoluteFilePath)
          let cachedModule = snapshotResult.customRequire.cache[relativeFilePath]
          if (!cachedModule) {
            cachedModule = Module._load(module, this, false)
            snapshotResult.customRequire.cache[relativeFilePath] = cachedModule
          }
          return cachedModule
        }

        snapshotResult.setGlobals(global, process, window, document, require)
      }

      const FileSystemBlobStore = useSnapshot ? snapshotResult.customRequire('../src/file-system-blob-store.js') : require('../src/file-system-blob-store')
      blobStore = FileSystemBlobStore.load(path.join(process.env.ATOM_HOME, 'blob-store'))

      const NativeCompileCache = useSnapshot ? snapshotResult.customRequire('../src/native-compile-cache.js') : require('../src/native-compile-cache')
      NativeCompileCache.setCacheStore(blobStore)
      NativeCompileCache.setV8Version(process.versions.v8)
      NativeCompileCache.install()

      if (getWindowLoadSettings().profileStartup) {
        profileStartup(Date.now() - startTime)
      } else {
        setupWindow()
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
    }
  }

  function handleSetupError (error) {
    const currentWindow = electron.remote.getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow () {
    const CompileCache = useSnapshot ? snapshotResult.customRequire('../src/compile-cache.js') : require('../src/compile-cache')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)
    CompileCache.install(require)

    const ModuleCache = useSnapshot ? snapshotResult.customRequire('../src/module-cache.js') : require('../src/module-cache')
    ModuleCache.register(getWindowLoadSettings())

    const startCrashReporter = useSnapshot ? snapshotResult.customRequire('../src/crash-reporter-start.js') : require('../src/crash-reporter-start')
    startCrashReporter({_version: getWindowLoadSettings().appVersion})

    const CSON = useSnapshot ? snapshotResult.customRequire('../node_modules/season/lib/cson.js') : require('season')
    CSON.setCacheDir(path.join(CompileCache.getCacheDirectory(), 'cson'))

    const initScriptPath = path.relative(entryPointDirPath, getWindowLoadSettings().windowInitializationScript)
    const initialize = useSnapshot ? snapshotResult.customRequire(initScriptPath) : require(initScriptPath)
    return initialize({blobStore: blobStore}).then(function () {
      electron.ipcRenderer.send('window-command', 'window:loaded')
    })
  }

  function profileStartup (initialTime) {
    function profile () {
      console.profile('startup')
      const startTime = Date.now()
      setupWindow().then(function () {
        setLoadTime(Date.now() - startTime + initialTime)
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      })
    }

    const webContents = electron.remote.getCurrentWindow().webContents
    if (webContents.devToolsWebContents) {
      profile()
    } else {
      webContents.once('devtools-opened', () => { setTimeout(profile, 1000) })
      webContents.openDevTools()
    }
  }

  function setupAtomHome () {
    if (process.env.ATOM_HOME) {
      return
    }

    // Ensure ATOM_HOME is always set before anything else is required
    // This is because of a difference in Linux not inherited between browser and render processes
    // https://github.com/atom/atom/issues/5412
    if (getWindowLoadSettings() && getWindowLoadSettings().atomHome) {
      process.env.ATOM_HOME = getWindowLoadSettings().atomHome
    }
  }
})()
<|endoftext|>


<commit_before>SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBox = function(Facade, el) {
	var that = this;
	var userDefinedSettings = Facade.publish("UserDefinedSettings");
	this.optionItems = [];
	this.observer;
	this.element = el;
	this.usePolling = userDefinedSettings.usePolling || false;
	this.pollingInterval = userDefinedSettings.pollingInterval || 100;
	this.isElemHidden;
	this.isElemDisabled;
	this.optionsCount;

	this.attach = function() {
		this.optionItems = [];
		var optionsLength = this.element.options.length;
		this.optionsCount = optionsLength;
		for (var i = 0; i < optionsLength; i++) {
			var option = this.element.options[i];
			var optionItem = new SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBoxItem(Facade, option);
			this.optionItems.push(optionItem);
		}
		//if (MUTATION_OBSERVER !== undefined && this.observer === undefined)
		//	attachDomObserver();
		if (this.usePolling)
			this.poller = setInterval(this.poll.bind(this), this.pollingInterval);
		if (this.usePolling) {
			this.isElemHidden = this.isHidden();
			this.isElemDisabled = this.isDisabled();
		}
		return this.element;
	}

	this.detach = function() {
		this.observer = undefined;
		if (this.poller !== undefined)
			clearInterval(this.poller);
	}

	this.triggerFocus = function() {
		SELECT.UTILS.triggerEvent("focus", this.element);
	}

	this.setValue = function(value) {
		this.element.value = value;
	}

	this.poll = function() {
		var isHidden = this.element.isHidden();
		if (isHidden !== this.isElemHidden) {
			this.isElemHidden = isHidden;
			if (isHidden)
				Facade.publish("Wrapper:hide");
			else
				Facade.publish("Wrapper:show");
		}
		var isDisabled = this.element.isDisabled();
		if (isDisabled !== this.isElemDisabled) {
			this.isElemDisabled = isDisabled;
			if (isDisabled)
				Facade.publish("Wrapper:disable");
			else
				Facade.publish("Wrapper:enable");
		}
		//if (this.observer === undefined) { //mutation observer does not detech attribute changes on <select>
			var optionsCount = this.element.options.length;
			if (optionsCount !== this.optionsCount) {
				this.optionsCount = optionsCount;
				this.attach();
				Facade.publish("OptionsMenuList").refresh();
			}
		//}
	}

	this.getOptions = function() {
		return this.optionItems;
	}

	function attachDomObserver() {
    	that.observer = new MUTATION_OBSERVER(function(mutations, observer) {
    		mutations.forEach(function (mutation) {
    			var addedNodesLength = (mutation.addedNodes === undefined) ? 0 : mutation.addedNodes.length;
    			var removedNodesLength = (mutation.removedNodes === undefined) ? 0 : mutation.removedNodes.length;
    			if (addedNodesLength > 0 || removedNodesLength.length > 0) {
    				that.attach();
    				Facade.publish("OptionsMenuList").refresh();
    			}
      		});
    	});
    	var config = {
    		attributes: true,
    		childList: true,
    		characterData : false,
    		subtree : false,
    		attributeOldValue: false,
    		attributeFilter: [],
    		characterDataOldValue: false,
    	};
    	that.observer.observe(that.element, config);
	}

	this.setSelectedOption = function(value) {
		var selectedIndex = this.element.selectedIndex;
		return this.element.options[selectedIndex];
	}

	this.getSelectedOptionText = function() {
		var selectedOption = this.getSelectedOption();
		if (selectedOption !== undefined)
			return selectedOption.text;
		return "";
	}

	this.clearSelected = function() {
		var l = this.optionItems.length;
		for (var i = 0; i < l; i++)
			this.optionItems[i].removeSelected();
	}

	this.triggerChange = function() {
		this.clearSelected();
	    SELECT.UTILS.triggerEvent("change", this.element);
	}

	this.getSelectedOptionValue = function() {
		var selectedOption = this.getSelectedOption();
		if (selectedOption !== undefined)
			return selectedOption.value;
		return "";
	}

	this.getSelectedOptionImageUrl = function() {
		var selectedOption = this.getSelectedOption();
		if (selectedOption !== undefined)
			return selectedOption.getDataAttribute("image-url");
	}

	this.getSelectedOption = function() {
		var l = this.element.options.length;
		for (var i = 0; i < l; i++) {
			var option = this.element.options[i];
			var selected = (option.getAttribute("selected") === null) ? false : true;
			if (selected)
				return option;
		}
	}

};

SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBox.prototype = Object.create(SELECT.ELEMENTS.Element.prototype);<commit_msg>fix to getSelectedOption<commit_after>SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBox = function(Facade, el) {
	var that = this;
	var userDefinedSettings = Facade.publish("UserDefinedSettings");
	this.optionItems = [];
	this.observer;
	this.element = el;
	this.usePolling = userDefinedSettings.usePolling || false;
	this.pollingInterval = userDefinedSettings.pollingInterval || 100;
	this.isElemHidden;
	this.isElemDisabled;
	this.optionsCount;

	this.attach = function() {
		this.optionItems = [];
		var optionsLength = this.element.options.length;
		this.optionsCount = optionsLength;
		for (var i = 0; i < optionsLength; i++) {
			var option = this.element.options[i];
			var optionItem = new SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBoxItem(Facade, option);
			this.optionItems.push(optionItem);
		}
		//if (MUTATION_OBSERVER !== undefined && this.observer === undefined)
		//	attachDomObserver();
		if (this.usePolling)
			this.poller = setInterval(this.poll.bind(this), this.pollingInterval);
		if (this.usePolling) {
			this.isElemHidden = this.isHidden();
			this.isElemDisabled = this.isDisabled();
		}
		return this.element;
	}

	this.detach = function() {
		this.observer = undefined;
		if (this.poller !== undefined)
			clearInterval(this.poller);
	}

	this.triggerFocus = function() {
		SELECT.UTILS.triggerEvent("focus", this.element);
	}

	this.setValue = function(value) {
		this.element.value = value;
	}

	this.poll = function() {
		var isHidden = this.element.isHidden();
		if (isHidden !== this.isElemHidden) {
			this.isElemHidden = isHidden;
			if (isHidden)
				Facade.publish("Wrapper:hide");
			else
				Facade.publish("Wrapper:show");
		}
		var isDisabled = this.element.isDisabled();
		if (isDisabled !== this.isElemDisabled) {
			this.isElemDisabled = isDisabled;
			if (isDisabled)
				Facade.publish("Wrapper:disable");
			else
				Facade.publish("Wrapper:enable");
		}
		//if (this.observer === undefined) { //mutation observer does not detech attribute changes on <select>
			var optionsCount = this.element.options.length;
			if (optionsCount !== this.optionsCount) {
				this.optionsCount = optionsCount;
				this.attach();
				Facade.publish("OptionsMenuList").refresh();
			}
		//}
	}

	this.getOptions = function() {
		return this.optionItems;
	}

	function attachDomObserver() {
    	that.observer = new MUTATION_OBSERVER(function(mutations, observer) {
    		mutations.forEach(function (mutation) {
    			var addedNodesLength = (mutation.addedNodes === undefined) ? 0 : mutation.addedNodes.length;
    			var removedNodesLength = (mutation.removedNodes === undefined) ? 0 : mutation.removedNodes.length;
    			if (addedNodesLength > 0 || removedNodesLength.length > 0) {
    				that.attach();
    				Facade.publish("OptionsMenuList").refresh();
    			}
      		});
    	});
    	var config = {
    		attributes: true,
    		childList: true,
    		characterData : false,
    		subtree : false,
    		attributeOldValue: false,
    		attributeFilter: [],
    		characterDataOldValue: false,
    	};
    	that.observer.observe(that.element, config);
	}

	this.setSelectedOption = function(value) {
		var selectedIndex = this.element.selectedIndex;
		return this.element.options[selectedIndex];
	}

	this.getSelectedOptionText = function() {
		var selectedOption = this.getSelectedOption();
		if (selectedOption !== undefined)
			return selectedOption.text;
		return "";
	}

	this.clearSelected = function() {
		var l = this.optionItems.length;
		for (var i = 0; i < l; i++)
			this.optionItems[i].removeSelected();
	}

	this.triggerChange = function() {
		this.clearSelected();
	    SELECT.UTILS.triggerEvent("change", this.element);
	}

	this.getSelectedOptionValue = function() {
		var selectedOption = this.getSelectedOption();
		if (selectedOption !== undefined)
			return selectedOption.value;
		return "";
	}

	this.getSelectedOptionImageUrl = function() {
		var selectedOption = this.getSelectedOption();
		if (selectedOption !== undefined)
			return selectedOption.getDataAttribute("image-url");
	}

	this.getSelectedOption = function() {
		return this.element.options[this.element.selectedIndex];
	}

};

SELECT.ELEMENTS.NATIVE_SELECT.NativeSelectBox.prototype = Object.create(SELECT.ELEMENTS.Element.prototype);<|endoftext|>


<commit_before>const Solution = require('../models/Solution')
const Ids = require('../models/ID')
const { extractPagination, isUndefined } = require('../utils')

/**
  返回一个 solution 的列表，以时间降序（从晚到早的排）
*/
async function queryList (ctx, next) {
  const filter = {}
  ;['uid', 'pid', 'judge', 'language'].forEach((item) => {
    if (!isUndefined(ctx.query[item])) {
      filter[item] = ctx.query[item]
    }
  })

  const res = await Solution
    .paginate(filter, {
      limit: +ctx.query.limit || 30, // 加号表示使其变为数字
      page: +ctx.query.page || 1,
      sort: {sid: -1},
      // '-_id' 结果不包含 _id
      // http://stackoverflow.com/questions/9598505/mongoose-retrieving-data-without-id-field
      select: '-_id sid uid pid judge time memory language length create sim sim_s_id'
    })

  ctx.body = {
    solutions: res.docs,
    pagination: extractPagination(res)
  }
}

/**
  返回一个具体的solution
*/
async function queryOneSolution (ctx, next) {
  const sid = +ctx.params.sid // router 那的中间件已经保证这是数字了
  const solution = await Solution
    .findOne({sid})
    // 比上面函数里的 select 多了一个 code
    .select('-_id sid uid pid judge time memory language length create sim sim_s_id code error')
    .exec()

  if (!solution) {
    ctx.throw(400, 'No such a solution')
  }

  ctx.body = {
    solution
  }
}

/**
  创建新的提交
*/
async function create (ctx, next) {
  // 必备的字段
  ;['pid', 'code', 'language'].forEach((item) => {
    if (isUndefined(ctx.request.body[item])) {
      ctx.throw(400, `Field "${item}" is required`)
    }
  })

  const verified = Solution.validate(ctx.request.body)
  if (!verified.valid) {
    ctx.throw(400, verified.error)
  }

  const { pid, code, language } = ctx.request.body
  const mid = ctx.request.body['mid'] || 0
  const sid = await Ids.generateId('solution')
  const uid = ctx.session.user.uid

  const solution = new Solution({
    uid, sid, pid, mid, code, language: +language, length: code.length
  })

  await solution.save()
  await solution.pending()

  ctx.body = {
    solution: {
      sid, pid, mid, code, language, length: code.length
    }
  }
}

/**
  更新提交，其实就是 rejudge
*/
async function rejudge (ctx, next) {
  const sid = +ctx.params.sid
  const solution = await Solution
    .findOne({sid})
    .exec()

  if (!solution) {
    ctx.throw(400, 'No such a solution')
  }

  await solution.save()

  // 似乎可以不用等待?
  await solution.pending()
  ctx.body = {}
}

module.exports = {
  queryList,
  queryOneSolution,
  create,
  rejudge
}
<commit_msg>fix bugs: querying contest solutions are allowed<commit_after>const Solution = require('../models/Solution')
const Ids = require('../models/ID')
const { extractPagination, isUndefined } = require('../utils')

/**
  返回一个 solution 的列表，以时间降序（从晚到早的排）
*/
async function queryList (ctx, next) {
  const filter = {}
  ;['uid', 'pid', 'judge', 'language', 'mid'].forEach((item) => {
    if (!isUndefined(ctx.query[item])) {
      filter[item] = ctx.query[item]
    }
  })

  const res = await Solution
    .paginate(filter, {
      limit: +ctx.query.limit || 30, // 加号表示使其变为数字
      page: +ctx.query.page || 1,
      sort: {sid: -1},
      // '-_id' 结果不包含 _id
      // http://stackoverflow.com/questions/9598505/mongoose-retrieving-data-without-id-field
      select: '-_id sid uid pid judge time memory language length create sim sim_s_id'
    })

  ctx.body = {
    solutions: res.docs,
    pagination: extractPagination(res)
  }
}

/**
  返回一个具体的solution
*/
async function queryOneSolution (ctx, next) {
  const sid = +ctx.params.sid // router 那的中间件已经保证这是数字了
  const solution = await Solution
    .findOne({sid})
    // 比上面函数里的 select 多了一个 code
    .select('-_id sid uid pid judge time memory language length create sim sim_s_id code error')
    .exec()

  if (!solution) {
    ctx.throw(400, 'No such a solution')
  }

  ctx.body = {
    solution
  }
}

/**
  创建新的提交
*/
async function create (ctx, next) {
  // 必备的字段
  ;['pid', 'code', 'language'].forEach((item) => {
    if (isUndefined(ctx.request.body[item])) {
      ctx.throw(400, `Field "${item}" is required`)
    }
  })

  const verified = Solution.validate(ctx.request.body)
  if (!verified.valid) {
    ctx.throw(400, verified.error)
  }

  const { pid, code, language } = ctx.request.body
  const mid = ctx.request.body['mid'] || 0
  const sid = await Ids.generateId('solution')
  const uid = ctx.session.user.uid

  const solution = new Solution({
    uid, sid, pid, mid, code, language: +language, length: code.length
  })

  await solution.save()
  await solution.pending()

  ctx.body = {
    solution: {
      sid, pid, mid, code, language, length: code.length
    }
  }
}

/**
  更新提交，其实就是 rejudge
*/
async function rejudge (ctx, next) {
  const sid = +ctx.params.sid
  const solution = await Solution
    .findOne({sid})
    .exec()

  if (!solution) {
    ctx.throw(400, 'No such a solution')
  }

  await solution.save()

  // 似乎可以不用等待?
  await solution.pending()
  ctx.body = {}
}

module.exports = {
  queryList,
  queryOneSolution,
  create,
  rejudge
}
<|endoftext|>


<commit_before>seajs.use(['$', 'placeholder', 'sticky', 'word-color', 'autocomplete'], function($, Placeholder, Sticky, wordColor, Autocomplete) {

  Sticky.stick('#document-wrapper', 0);

  var modules = [];

  var urls = [
    'http://spmjs.org/repository/arale/?define',
    'http://spmjs.org/repository/gallery/?define',
    'http://spmjs.org/repository/jquery/?define'
  ];

  seajs.use(urls, function(arale, gallery, jquery) {
    $('.modules-utility').empty();
    modules = modules.concat(arale);
    modules = modules.concat(gallery);
    modules = modules.concat(jquery);

    insertModules(arale);
    insertModules(gallery);
    insertModules(jquery);
    color('.module');
  });

  seajs.use('http://yuan.alipay.im/repository/alipay/?define', function(alipay) {
    if (alipay) {
      modules = modules.concat(alipay);
      insertModules(alipay);
      color('.module');
    }
  });

  function insertModules(data) {

    if ($('#module-wrapper').length === 0) {
      return;
    }

    data = data.sort(function(a, b) {
      return a.name[0] > b.name[0];
    });

    for (var i = 0; i < data.length; i++) {
      var item = $('
\
        \
        \

\

');

      var pkg = data[i];
      var family = pkg.family || pkg.root;

      item.find(".module-name").html(pkg.name)
                                .attr('href', '/' + pkg.name + '/')
                                .attr('title', pkg.name);
      item.find(".module-version").html(pkg.version);
      item.find(".module-description").html(pkg.description)
                                      .attr('title', pkg.description);

      if (family === 'gallery' || family === 'jquery') {
        item.find(".module-name").attr('href', pkg.homepage);
        $('.modules-' + family).append(item).prev().show();
      } else if (family === 'arale') {
        if (pkg.keywords) {
          $('.modules-' + pkg.keywords[0]).append(item).prev().show();
        } else {
          $('.modules-widget').append(item).prev().show();
        }
      } else if (family === 'alipay') {
        var url = [
          'http://arale.alipay.im',
          (pkg.family || pkg.root),
          pkg.name
        ].join('/') + '/';
        item.find(".module-name").attr('href', url);
        $('.modules-alipay').append(item).prev().show();
      }
    }
  }

  function color(items) {
    items = $(items);
    items.each(function(index, item) {
      item = $(item);
      item.css('border-left-color', toRgba(wordColor(item.find('.module-name').html()), 0.65));
    });
  }

  function toRgba(rgb, opacity) {
    if (!$.support.opacity) {
      return rgb;
    }
    return rgb.replace('rgb', 'rgba').replace(')', ',' + opacity + ')');
  }

  var ac = new Autocomplete({
    trigger: '#search',
    selectFirst: true,
    template:
        '
\

\
                {{#each items}}\

\

{{highlightItem ../classPrefix matchKey}}
\

{{desc}}
\

\
                {{/each}}\

\

',
    dataSource: function() {
      this.trigger('data', modules);
    },
    filter: function(data, query) {
      var result = [];
      query = query.toLowerCase();

      $.each(data, function(index, value) {
        value.description = value.description.toLowerCase() || '';
        value.family = value.family.toLowerCase();
        value.name = value.name.toLowerCase();
        var FamilyAndName = value.family + '.' + value.name;

        var item = {
          matchKey: FamilyAndName,
          desc: value.description,
          url: value.homepage,
          score: 0  //匹配度
        };

        if (FamilyAndName.indexOf(query) > -1) {
          item.score += 1;
        }
        if (value.description.indexOf(query) > -1) {
          item.score += 1;
        }
        if (value.family.indexOf(query) > -1) {
          item.score += 5;
        }
        if (value.family.indexOf(query) === 0 && query.length > 1) {
          item.score += 10;
        }
        if (value.name.indexOf(query) > -1) {
          item.score += 5;
        }
        if (value.name.indexOf(query) === 0 && query.length > 1) {
          item.score += 100;
        }
        result.push(item);
      });

      return result.sort(function(a, b) {
        return a.score < b.score;
      });

    }
  }).render();

  ac.on('itemSelect', function(item) {
    ac.get('trigger').val('正转到 ' + item.matchKey).attr('disabled', 'disabled');
    var value = item.matchKey.split('.');
    if (value[0] === 'arale') {
      location.href = '/' + value[1];
    } else if (value[0] === 'alipay') {
      location.href = 'http://arale.alipay.im/alipay/' + value[1];
    } else {
      location.href = item.url;
    }
  });
});
<commit_msg>优化搜索框的排序逻辑<commit_after>seajs.use(['$', 'placeholder', 'sticky', 'word-color', 'autocomplete'], function($, Placeholder, Sticky, wordColor, Autocomplete) {

  Sticky.stick('#document-wrapper', 0);

  var modules = [];

  var urls = [
    'http://spmjs.org/repository/arale/?define',
    'http://spmjs.org/repository/gallery/?define',
    'http://spmjs.org/repository/jquery/?define'
  ];

  seajs.use(urls, function(arale, gallery, jquery) {
    $('.modules-utility').empty();
    modules = modules.concat(arale);
    modules = modules.concat(gallery);
    modules = modules.concat(jquery);

    insertModules(arale);
    insertModules(gallery);
    insertModules(jquery);
    color('.module');
  });

  seajs.use('http://yuan.alipay.im/repository/alipay/?define', function(alipay) {
    if (alipay) {
      modules = modules.concat(alipay);
      insertModules(alipay);
      color('.module');
    }
  });

  function insertModules(data) {

    if ($('#module-wrapper').length === 0) {
      return;
    }

    data = data.sort(function(a, b) {
      return a.name[0] > b.name[0];
    });

    for (var i = 0; i < data.length; i++) {
      var item = $('
\
        \
        \

\

');

      var pkg = data[i];
      var family = pkg.family || pkg.root;

      item.find(".module-name").html(pkg.name)
                                .attr('href', '/' + pkg.name + '/')
                                .attr('title', pkg.name);
      item.find(".module-version").html(pkg.version);
      item.find(".module-description").html(pkg.description)
                                      .attr('title', pkg.description);

      if (family === 'gallery' || family === 'jquery') {
        item.find(".module-name").attr('href', pkg.homepage);
        $('.modules-' + family).append(item).prev().show();
      } else if (family === 'arale') {
        if (pkg.keywords) {
          $('.modules-' + pkg.keywords[0]).append(item).prev().show();
        } else {
          $('.modules-widget').append(item).prev().show();
        }
      } else if (family === 'alipay') {
        var url = [
          'http://arale.alipay.im',
          (pkg.family || pkg.root),
          pkg.name
        ].join('/') + '/';
        item.find(".module-name").attr('href', url);
        $('.modules-alipay').append(item).prev().show();
      }
    }
  }

  function color(items) {
    items = $(items);
    items.each(function(index, item) {
      item = $(item);
      item.css('border-left-color', toRgba(wordColor(item.find('.module-name').html()), 0.65));
    });
  }

  function toRgba(rgb, opacity) {
    if (!$.support.opacity) {
      return rgb;
    }
    return rgb.replace('rgb', 'rgba').replace(')', ',' + opacity + ')');
  }

  var ac = new Autocomplete({
    trigger: '#search',
    selectFirst: true,
    template:
        '
\

\
                {{#each items}}\

\

{{highlightItem ../classPrefix matchKey}}
\

{{desc}}
\

\
                {{/each}}\

\

',
    dataSource: function() {
      this.trigger('data', modules);
    },
    filter: function(data, query) {
      var result = [];
      query = query.toLowerCase();

      $.each(data, function(index, value) {
        value.description = value.description.toLowerCase() || '';
        value.family = value.family.toLowerCase();
        value.name = value.name.toLowerCase();
        var FamilyAndName = value.family + '.' + value.name;

        var item = {
          matchKey: FamilyAndName,
          desc: value.description,
          url: value.homepage,
          score: 0  //匹配度
        };

        if (FamilyAndName.indexOf(query) > -1) {
          item.score += 1;
        }
        if (value.description.indexOf(query) > -1) {
          item.score += 1;
        }
        if (value.family.indexOf(query) > -1) {
          item.score += 5;
        }
        if (value.family.indexOf(query) === 0 && query.length > 1) {
          item.score += 10;
        }
        if (value.name.indexOf(query) > -1) {
          item.score += 5;
        }
        if (value.name.indexOf(query) === 0 && query.length > 1) {
          item.score += 100;
        }
        if (item.score > 0) {
          result.push(item);
        }
      });

      return result.sort(function(a, b) {
        return a.score < b.score;
      });

    }
  }).render();

  ac.on('itemSelect', function(item) {
    ac.get('trigger').val('正转到 ' + item.matchKey).attr('disabled', 'disabled');
    var value = item.matchKey.split('.');
    if (value[0] === 'arale') {
      location.href = '/' + value[1];
    } else if (value[0] === 'alipay') {
      location.href = 'http://arale.alipay.im/alipay/' + value[1];
    } else {
      location.href = item.url;
    }
  });
});
<|endoftext|>


<commit_before>import fs from 'fs';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import flow from 'rollup-plugin-flow';
import resolve from 'rollup-plugin-node-resolve';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';

const extractPackagePeerDependencies = () => {
  const packageNpm = JSON.parse(
    fs.readFileSync('./package.json', { encoding: 'utf8' })
  );

  return Object.keys(packageNpm.peerDependencies || {});
};

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/cjs/index.js',
    format: 'cjs',
    sourcemap: true,
  },
  external: extractPackagePeerDependencies(),
  plugins: [
    babel({
      babelrc: false,
      exclude: 'node_modules/**', // only transpile our source code
      presets: [
        [
          'es2015',
          {
            modules: false,
          },
        ],
        'stage-2',
        'react',
        'flow',
      ],
      plugins: ['external-helpers'],
      externalHelpers: true,
    }),
    resolve({
      module: true,
      jsnext: true,
      main: true,
      browser: true,
    }),
    commonjs({
      sourceMap: true,
      namedExports: {
        react: ['isValidElement'],
      },
    }),
    globals(),
    builtins(),
    flow(),
  ],
};
<commit_msg>fix(browser): Add IE 11 support (#288)<commit_after>import fs from 'fs';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import flow from 'rollup-plugin-flow';
import resolve from 'rollup-plugin-node-resolve';
import builtins from 'rollup-plugin-node-builtins';
import globals from 'rollup-plugin-node-globals';

const extractPackagePeerDependencies = () => {
  const packageNpm = JSON.parse(
    fs.readFileSync('./package.json', { encoding: 'utf8' })
  );

  return Object.keys(packageNpm.peerDependencies || {});
};

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/cjs/index.js',
    format: 'cjs',
    sourcemap: true,
  },
  external: extractPackagePeerDependencies(),
  plugins: [
    babel({
      babelrc: false,
      // Don't transpile `node_modules` except for `stringify-object`. This enables IE 11 support
      // and minification in older versions of Uglify.
      exclude: 'node_modules/!(stringify-object)/**',
      presets: [
        [
          'es2015',
          {
            modules: false,
          },
        ],
        'stage-2',
        'react',
        'flow',
      ],
      plugins: ['external-helpers'],
      externalHelpers: true,
    }),
    resolve({
      module: true,
      jsnext: true,
      main: true,
      browser: true,
    }),
    commonjs({
      sourceMap: true,
      namedExports: {
        react: ['isValidElement'],
      },
    }),
    globals(),
    builtins(),
    flow(),
  ],
};
<|endoftext|>


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

window.onload = function() {
  try {
    var startTime = Date.now();

    process.on('unhandledRejection', function(error, promise) {
      console.error('Unhandled promise rejection %o with error: %o', promise, error);
    });

    // Ensure ATOM_HOME is always set before anything else is required
    setupAtomHome();

    var cacheDir = path.join(process.env.ATOM_HOME, 'compile-cache');
    // Use separate compile cache when sudo'ing as root to avoid permission issues
    if (process.env.USER === 'root' && process.env.SUDO_USER && process.env.SUDO_USER !== process.env.USER) {
      cacheDir = path.join(cacheDir, 'root');
    }

    var rawLoadSettings = decodeURIComponent(location.hash.substr(1));
    var loadSettings;
    try {
      loadSettings = JSON.parse(rawLoadSettings);
    } catch (error) {
      console.error("Failed to parse load settings: " + rawLoadSettings);
      throw error;
    }

    // Normalize to make sure drive letter case is consistent on Windows
    process.resourcesPath = path.normalize(process.resourcesPath);

    var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep);

    if (loadSettings.profileStartup) {
      profileStartup(cacheDir, loadSettings, Date.now() - startTime);
    } else {
      setupWindow(cacheDir, loadSettings);
      setLoadTime(Date.now() - startTime);
    }
  } catch (error) {
    handleSetupError(error);
  }
}

var setLoadTime = function(loadTime) {
  if (global.atom) {
    global.atom.loadTime = loadTime;
    console.log('Window load time: ' + global.atom.getWindowLoadTime() + 'ms');
  }
}

var handleSetupError = function(error) {
  var currentWindow = require('remote').getCurrentWindow();
  currentWindow.setSize(800, 600);
  currentWindow.center();
  currentWindow.show();
  currentWindow.openDevTools();
  console.error(error.stack || error);
}

var setupWindow = function(cacheDir, loadSettings) {
  setupCoffeeCache(cacheDir);

  ModuleCache = require('../src/module-cache');
  ModuleCache.register(loadSettings);
  ModuleCache.add(loadSettings.resourcePath);

  require('grim').includeDeprecatedAPIs = !loadSettings.apiPreviewMode;

  // Start the crash reporter before anything else.
  require('crash-reporter').start({
    productName: 'Atom',
    companyName: 'GitHub',
    // By explicitly passing the app version here, we could save the call
    // of "require('remote').require('app').getVersion()".
    extra: {_version: loadSettings.appVersion}
  });

  setupVmCompatibility();
  setupCsonCache(cacheDir);
  setupSourceMapCache(cacheDir);
  setupBabel(cacheDir);
  setupTypeScript(cacheDir);

  require(loadSettings.bootstrapScript);
  require('ipc').sendChannel('window-command', 'window:loaded');
}

var setupCoffeeCache = function(cacheDir) {
  var CoffeeCache = require('coffee-cash');
  CoffeeCache.setCacheDirectory(path.join(cacheDir, 'coffee'));
  CoffeeCache.register();
}

var setupAtomHome = function() {
  if (!process.env.ATOM_HOME) {
    var home;
    if (process.platform === 'win32') {
      home = process.env.USERPROFILE;
    } else {
      home = process.env.HOME;
    }
    var atomHome = path.join(home, '.atom');
    try {
      atomHome = fs.realpathSync(atomHome);
    } catch (error) {
      // Ignore since the path might just not exist yet.
    }
    process.env.ATOM_HOME = atomHome;
  }
}

var setupBabel = function(cacheDir) {
  var babel = require('../src/babel');
  babel.setCacheDirectory(path.join(cacheDir, 'js', 'babel'));
  babel.register();
}

var setupTypeScript = function(cacheDir) {
  var typescript = require('../src/typescript');
  typescript.setCacheDirectory(path.join(cacheDir, 'typescript'));
  typescript.register();
}

var setupCsonCache = function(cacheDir) {
  require('season').setCacheDir(path.join(cacheDir, 'cson'));
}

var setupSourceMapCache = function(cacheDir) {
  require('coffeestack').setCacheDirectory(path.join(cacheDir, 'coffee', 'source-maps'));
}

var setupVmCompatibility = function() {
  var vm = require('vm');
  if (!vm.Script.createContext)
    vm.Script.createContext = vm.createContext;
}

var profileStartup = function(cacheDir, loadSettings, initialTime) {
  var profile = function() {
    console.profile('startup');
    try {
      var startTime = Date.now()
      setupWindow(cacheDir, loadSettings);
      setLoadTime(Date.now() - startTime + initialTime);
    } catch (error) {
      handleSetupError(error);
    } finally {
      console.profileEnd('startup');
      console.log("Switch to the Profiles tab to view the created startup profile")
    }
  };

  var currentWindow = require('remote').getCurrentWindow();
  if (currentWindow.devToolsWebContents) {
    profile();
  } else {
    currentWindow.openDevTools();
    currentWindow.once('devtools-opened', function() {
      setTimeout(profile, 100);
    });
  }
}

var setupWindowBackground = function() {
  var backgroundColor = window.localStorage.getItem('atom:window-background-color');
  if (!backgroundColor) {
    return;
  }

  var backgroundStylesheet = document.createElement('style');
  backgroundStylesheet.type = 'text/css';
  backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + '; }';
  document.head.appendChild(backgroundStylesheet);

  // Remove once the page loads
  window.addEventListener("load", function loadWindow() {
    window.removeEventListener("load", loadWindow, false);
    setTimeout(function() {
      backgroundStylesheet.remove();
      backgroundStylesheet = null;
    }, 1000);
  }, false);
}

setupWindowBackground();
<commit_msg>Don't set background of spec windows<commit_after>var fs = require('fs');
var path = require('path');

var loadSettings = null;
var loadSettingsError = null;

window.onload = function() {
  try {
    var startTime = Date.now();

    process.on('unhandledRejection', function(error, promise) {
      console.error('Unhandled promise rejection %o with error: %o', promise, error);
    });

    // Ensure ATOM_HOME is always set before anything else is required
    setupAtomHome();

    var cacheDir = path.join(process.env.ATOM_HOME, 'compile-cache');
    // Use separate compile cache when sudo'ing as root to avoid permission issues
    if (process.env.USER === 'root' && process.env.SUDO_USER && process.env.SUDO_USER !== process.env.USER) {
      cacheDir = path.join(cacheDir, 'root');
    }

    // Normalize to make sure drive letter case is consistent on Windows
    process.resourcesPath = path.normalize(process.resourcesPath);

    if (loadSettingsError) {
      throw loadSettingsError;
    }

    var devMode = loadSettings.devMode || !loadSettings.resourcePath.startsWith(process.resourcesPath + path.sep);

    if (loadSettings.profileStartup) {
      profileStartup(cacheDir, loadSettings, Date.now() - startTime);
    } else {
      setupWindow(cacheDir, loadSettings);
      setLoadTime(Date.now() - startTime);
    }
  } catch (error) {
    handleSetupError(error);
  }
}

var setLoadTime = function(loadTime) {
  if (global.atom) {
    global.atom.loadTime = loadTime;
    console.log('Window load time: ' + global.atom.getWindowLoadTime() + 'ms');
  }
}

var handleSetupError = function(error) {
  var currentWindow = require('remote').getCurrentWindow();
  currentWindow.setSize(800, 600);
  currentWindow.center();
  currentWindow.show();
  currentWindow.openDevTools();
  console.error(error.stack || error);
}

var setupWindow = function(cacheDir, loadSettings) {
  setupCoffeeCache(cacheDir);

  ModuleCache = require('../src/module-cache');
  ModuleCache.register(loadSettings);
  ModuleCache.add(loadSettings.resourcePath);

  require('grim').includeDeprecatedAPIs = !loadSettings.apiPreviewMode;

  // Start the crash reporter before anything else.
  require('crash-reporter').start({
    productName: 'Atom',
    companyName: 'GitHub',
    // By explicitly passing the app version here, we could save the call
    // of "require('remote').require('app').getVersion()".
    extra: {_version: loadSettings.appVersion}
  });

  setupVmCompatibility();
  setupCsonCache(cacheDir);
  setupSourceMapCache(cacheDir);
  setupBabel(cacheDir);
  setupTypeScript(cacheDir);

  require(loadSettings.bootstrapScript);
  require('ipc').sendChannel('window-command', 'window:loaded');
}

var setupCoffeeCache = function(cacheDir) {
  var CoffeeCache = require('coffee-cash');
  CoffeeCache.setCacheDirectory(path.join(cacheDir, 'coffee'));
  CoffeeCache.register();
}

var setupAtomHome = function() {
  if (!process.env.ATOM_HOME) {
    var home;
    if (process.platform === 'win32') {
      home = process.env.USERPROFILE;
    } else {
      home = process.env.HOME;
    }
    var atomHome = path.join(home, '.atom');
    try {
      atomHome = fs.realpathSync(atomHome);
    } catch (error) {
      // Ignore since the path might just not exist yet.
    }
    process.env.ATOM_HOME = atomHome;
  }
}

var setupBabel = function(cacheDir) {
  var babel = require('../src/babel');
  babel.setCacheDirectory(path.join(cacheDir, 'js', 'babel'));
  babel.register();
}

var setupTypeScript = function(cacheDir) {
  var typescript = require('../src/typescript');
  typescript.setCacheDirectory(path.join(cacheDir, 'typescript'));
  typescript.register();
}

var setupCsonCache = function(cacheDir) {
  require('season').setCacheDir(path.join(cacheDir, 'cson'));
}

var setupSourceMapCache = function(cacheDir) {
  require('coffeestack').setCacheDirectory(path.join(cacheDir, 'coffee', 'source-maps'));
}

var setupVmCompatibility = function() {
  var vm = require('vm');
  if (!vm.Script.createContext)
    vm.Script.createContext = vm.createContext;
}

var profileStartup = function(cacheDir, loadSettings, initialTime) {
  var profile = function() {
    console.profile('startup');
    try {
      var startTime = Date.now()
      setupWindow(cacheDir, loadSettings);
      setLoadTime(Date.now() - startTime + initialTime);
    } catch (error) {
      handleSetupError(error);
    } finally {
      console.profileEnd('startup');
      console.log("Switch to the Profiles tab to view the created startup profile")
    }
  };

  var currentWindow = require('remote').getCurrentWindow();
  if (currentWindow.devToolsWebContents) {
    profile();
  } else {
    currentWindow.openDevTools();
    currentWindow.once('devtools-opened', function() {
      setTimeout(profile, 100);
    });
  }
}

var parseLoadSettings = function() {
  var rawLoadSettings = decodeURIComponent(location.hash.substr(1));
  try {
    loadSettings = JSON.parse(rawLoadSettings);
  } catch (error) {
    loadSettingsError = error;
  }

  if (!loadSettings || typeof loadSettings !== 'object') {
    loadSettings = {};
  }
}

var setupWindowBackground = function() {
  if (loadSettings.isSpec) {
    return;
  }

  var backgroundColor = window.localStorage.getItem('atom:window-background-color');
  if (!backgroundColor) {
    return;
  }

  var backgroundStylesheet = document.createElement('style');
  backgroundStylesheet.type = 'text/css';
  backgroundStylesheet.innerText = 'html, body { background: ' + backgroundColor + '; }';
  document.head.appendChild(backgroundStylesheet);

  // Remove once the page loads
  window.addEventListener("load", function loadWindow() {
    window.removeEventListener("load", loadWindow, false);
    setTimeout(function() {
      backgroundStylesheet.remove();
      backgroundStylesheet = null;
    }, 1000);
  }, false);
}

parseLoadSettings();
setupWindowBackground();
<|endoftext|>


<commit_before>(function () {
  const electron = require('electron')
  const path = require('path')
  const fs = require('fs-plus')
  const Module = require('module')
  const getWindowLoadSettings = require('../src/get-window-load-settings')
  const entryPointDirPath = __dirname
  let blobStore = null
  let devMode = false
  let useSnapshot = false
  let requireFunction = null

  window.onload = function () {
    try {
      const startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      setupAtomHome()
      devMode = getWindowLoadSettings().devMode || !getWindowLoadSettings().resourcePath.startsWith(process.resourcesPath + path.sep)
      useSnapshot = !devMode && typeof snapshotResult !== 'undefined'
      requireFunction = useSnapshot ? snapshotResult.customRequire : require

      if (devMode) {
        const metadata = require('../package.json')
        if (!metadata._deprecatedPackages) {
          try {
            metadata._deprecatedPackages = require('../script/deprecated-packages.json')
          } catch (requireError) {
            console.error('Failed to setup deprecated packages list', requireError.stack)
          }
        }
      } else if (useSnapshot) {
        Module.prototype.require = function (module) {
          const absoluteFilePath = Module._resolveFilename(module, this, false)
          const relativeFilePath = path.relative(entryPointDirPath, absoluteFilePath)
          let cachedModule = snapshotResult.customRequire.cache[relativeFilePath]
          if (!cachedModule) {
            cachedModule = Module._load(module, this, false)
            snapshotResult.customRequire.cache[relativeFilePath] = cachedModule
          }
          return cachedModule
        }

        snapshotResult.setGlobals(global, process, window, document, require)
        snapshotResult.entryPointDirPath = __dirname
      }

      // const FileSystemBlobStore = requireFunction('../src/file-system-blob-store.js')
      // blobStore = FileSystemBlobStore.load(
      //   path.join(process.env.ATOM_HOME, 'blob-store/')
      // )

      // const NativeCompileCache = requireFunction('../src/native-compile-cache.js')
      // NativeCompileCache.setCacheStore(blobStore)
      // NativeCompileCache.setV8Version(process.versions.v8)
      // NativeCompileCache.install()

      if (getWindowLoadSettings().profileStartup) {
        profileStartup(Date.now() - startTime)
      } else {
        setupWindow()
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
    }
  }

  function handleSetupError (error) {
    const currentWindow = electron.remote.getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow () {
    const CompileCache = requireFunction('../src/compile-cache.js')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)
    CompileCache.install(require)

    const ModuleCache = requireFunction('../src/module-cache.js')
    ModuleCache.register(getWindowLoadSettings())

    const startCrashReporter = requireFunction('../src/crash-reporter-start.js')
    startCrashReporter({_version: getWindowLoadSettings().appVersion})

    const CSON = requireFunction(useSnapshot ? '../node_modules/season/lib/cson.js' : 'season')
    CSON.setCacheDir(path.join(CompileCache.getCacheDirectory(), 'cson'))

    const initScriptPath = path.relative(entryPointDirPath, getWindowLoadSettings().windowInitializationScript)
    const initialize = requireFunction(initScriptPath)
    return initialize({blobStore: blobStore}).then(function () {
      electron.ipcRenderer.send('window-command', 'window:loaded')
    })
  }

  function profileStartup (initialTime) {
    function profile () {
      console.profile('startup')
      const startTime = Date.now()
      setupWindow().then(function () {
        setLoadTime(Date.now() - startTime + initialTime)
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      })
    }

    const webContents = electron.remote.getCurrentWindow().webContents
    if (webContents.devToolsWebContents) {
      profile()
    } else {
      webContents.once('devtools-opened', () => { setTimeout(profile, 1000) })
      webContents.openDevTools()
    }
  }

  function setupAtomHome () {
    if (process.env.ATOM_HOME) {
      return
    }

    // Ensure ATOM_HOME is always set before anything else is required
    // This is because of a difference in Linux not inherited between browser and render processes
    // https://github.com/atom/atom/issues/5412
    if (getWindowLoadSettings() && getWindowLoadSettings().atomHome) {
      process.env.ATOM_HOME = getWindowLoadSettings().atomHome
    }
  }
})()
<commit_msg>Fix dev mode<commit_after>(function () {
  const electron = require('electron')
  const path = require('path')
  const fs = require('fs-plus')
  const Module = require('module')
  const getWindowLoadSettings = require('../src/get-window-load-settings')
  const entryPointDirPath = __dirname
  let blobStore = null
  let devMode = false
  let useSnapshot = false

  window.onload = function () {
    try {
      const startTime = Date.now()

      process.on('unhandledRejection', function (error, promise) {
        console.error('Unhandled promise rejection %o with error: %o', promise, error)
      })

      // Normalize to make sure drive letter case is consistent on Windows
      process.resourcesPath = path.normalize(process.resourcesPath)

      setupAtomHome()
      devMode = getWindowLoadSettings().devMode || !getWindowLoadSettings().resourcePath.startsWith(process.resourcesPath + path.sep)
      useSnapshot = !devMode && typeof snapshotResult !== 'undefined'

      if (devMode) {
        const metadata = require('../package.json')
        if (!metadata._deprecatedPackages) {
          try {
            metadata._deprecatedPackages = require('../script/deprecated-packages.json')
          } catch (requireError) {
            console.error('Failed to setup deprecated packages list', requireError.stack)
          }
        }
      } else if (useSnapshot) {
        Module.prototype.require = function (module) {
          const absoluteFilePath = Module._resolveFilename(module, this, false)
          const relativeFilePath = path.relative(entryPointDirPath, absoluteFilePath)
          let cachedModule = snapshotResult.customRequire.cache[relativeFilePath]
          if (!cachedModule) {
            cachedModule = Module._load(module, this, false)
            snapshotResult.customRequire.cache[relativeFilePath] = cachedModule
          }
          return cachedModule
        }

        snapshotResult.setGlobals(global, process, window, document, require)
        snapshotResult.entryPointDirPath = __dirname
      }

      if (getWindowLoadSettings().profileStartup) {
        profileStartup(Date.now() - startTime)
      } else {
        setupWindow()
        setLoadTime(Date.now() - startTime)
      }
    } catch (error) {
      handleSetupError(error)
    }
  }

  function setLoadTime (loadTime) {
    if (global.atom) {
      global.atom.loadTime = loadTime
    }
  }

  function handleSetupError (error) {
    const currentWindow = electron.remote.getCurrentWindow()
    currentWindow.setSize(800, 600)
    currentWindow.center()
    currentWindow.show()
    currentWindow.openDevTools()
    console.error(error.stack || error)
  }

  function setupWindow () {
    const CompileCache = useSnapshot ? snapshotResult.customRequire('../src/compile-cache.js') : require('../src/compile-cache')
    CompileCache.setAtomHomeDirectory(process.env.ATOM_HOME)
    CompileCache.install(require)

    const ModuleCache = useSnapshot ? snapshotResult.customRequire('../src/module-cache.js') : require('../src/module-cache')
    ModuleCache.register(getWindowLoadSettings())

    const startCrashReporter = useSnapshot ? snapshotResult.customRequire('../src/crash-reporter-start.js') : require('../src/crash-reporter-start')
    startCrashReporter({_version: getWindowLoadSettings().appVersion})

    const CSON = useSnapshot ? snapshotResult.customRequire('../node_modules/season/lib/cson.js') : require('season')
    CSON.setCacheDir(path.join(CompileCache.getCacheDirectory(), 'cson'))

    const initScriptPath = path.relative(entryPointDirPath, getWindowLoadSettings().windowInitializationScript)
    const initialize = useSnapshot ? snapshotResult.customRequire(initScriptPath) : require(initScriptPath)
    return initialize({blobStore: blobStore}).then(function () {
      electron.ipcRenderer.send('window-command', 'window:loaded')
    })
  }

  function profileStartup (initialTime) {
    function profile () {
      console.profile('startup')
      const startTime = Date.now()
      setupWindow().then(function () {
        setLoadTime(Date.now() - startTime + initialTime)
        console.profileEnd('startup')
        console.log('Switch to the Profiles tab to view the created startup profile')
      })
    }

    const webContents = electron.remote.getCurrentWindow().webContents
    if (webContents.devToolsWebContents) {
      profile()
    } else {
      webContents.once('devtools-opened', () => { setTimeout(profile, 1000) })
      webContents.openDevTools()
    }
  }

  function setupAtomHome () {
    if (process.env.ATOM_HOME) {
      return
    }

    // Ensure ATOM_HOME is always set before anything else is required
    // This is because of a difference in Linux not inherited between browser and render processes
    // https://github.com/atom/atom/issues/5412
    if (getWindowLoadSettings() && getWindowLoadSettings().atomHome) {
      process.env.ATOM_HOME = getWindowLoadSettings().atomHome
    }
  }
})()
<|endoftext|>


<commit_before>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import babel from 'rollup-plugin-babel';

export default {
  entry: 'src/route.js',
  plugins: [
    babel({
      babelrc: false,
      exclude: ['./node_modules/**'],
      presets: [['travi', {targets: {node: 8, browser: true}, react: true, modules: false}]]
    })
  ],
  targets: [
    {dest: 'lib/plugin.cjs.js', format: 'cjs'},
    {dest: 'lib/plugin.es.js', format: 'es'}
  ]
};
<commit_msg>build(rollup): updated to the latest rollup config expectations<commit_after>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import babel from 'rollup-plugin-babel';

export default {
  input: 'src/route.js',
  external: [
    'react',
    'react-dom/server',
    'react-router',
    'boom',
    'http-status-codes',
    'redial'
  ],
  plugins: [
    babel({
      babelrc: false,
      exclude: ['./node_modules/**'],
      presets: [['travi', {targets: {node: 8, browser: true}, react: true, modules: false}]]
    })
  ],
  output: [
    {file: 'lib/plugin.cjs.js', format: 'cjs'},
    {file: 'lib/plugin.es.js', format: 'es'}
  ]
};
<|endoftext|>


<commit_before>import * as path from 'path';
import * as glob from 'glob';

import autoprefixer from 'autoprefixer';

import alias from '@rollup/plugin-alias';
import { babel } from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import eslint from '@rollup/plugin-eslint';
import ignore from 'rollup-plugin-ignore';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import postcss from 'rollup-plugin-postcss';
import replace from 'rollup-plugin-re';
import { string } from 'rollup-plugin-string';
import svgo from 'rollup-plugin-svgo';
import webworkerLoader from 'rollup-plugin-web-worker-loader';

import { rewriteFilenames } from './Utilities/rollup/plugin-rewrite-filenames';

const IGNORE_LIST = [
  /[/\\]example_?[/\\]/,
  /[/\\]test/,
  /^Sources[/\\](Testing|ThirdParty)/,
];

function ignoreFile(name, ignoreList = IGNORE_LIST) {
  return ignoreList.some((toMatch) => {
    if (toMatch instanceof RegExp) {
      return toMatch.test(name);
    }
    if (toMatch instanceof String) {
      return toMatch === name;
    }
    return false;
  });
}

const entryPoints = [
  path.join('Sources', 'macro.js'),
  path.join('Sources', 'vtk.js'),
  path.join('Sources', 'favicon.js'),
  ...glob.sync('Sources/**/index.js').filter((file) => !ignoreFile(file)),
];

const entries = {};
entryPoints.forEach((entry) => {
  entries[entry.replace(/^Sources[/\\]/, '')] = entry;
});

export default {
  input: entries,
  output: {
    dir: 'dist/esm/',
    format: 'es',
    entryFileNames(chunkInfo) {
      const name = chunkInfo.name;

      // rewrite vtk.js files from Sources/.../<NAME>/index.js to .../<NAME>.js
      const sourcesMatch = /^(.*?)[/\\]([A-Z]\w+)[/\\]index\.js$/.exec(name);
      if (sourcesMatch) {
        return path.join(sourcesMatch[1], `${sourcesMatch[2]}.js`);
      }

      return name;
    },
    manualChunks(id) {
      if (id.includes('node_modules')) {
        return 'vendor';
      }
      // strip out full path to project root
      return id.replace(`${path.resolve(__dirname)}${path.sep}`, '');
    },
    chunkFileNames(chunkInfo) {
      let name = chunkInfo.name;

      if (name === 'vendor') {
        return path.join('_vendor', 'vendor.js');
      }

      // throw all subscript prefixed chunks into a virtual folder
      if (name.startsWith('_')) {
        return name.replace(/^_/, `_virtual${path.sep}`);
      }

      if (!name.endsWith('.js')) {
        name += '.js';
      }

      // rewrite Sources/ chunks
      return name.replace(/^Sources[/\\]/, '');
    },
  },
  external: [/@babel\/runtime/],
  plugins: [
    // should be before commonjs
    replace({
      patterns: [
        {
          // match against jszip/lib/load.js
          // Workaround until https://github.com/Stuk/jszip/pull/731 is merged
          include: path.resolve(
            __dirname,
            'node_modules',
            'jszip',
            'lib',
            'load.js'
          ),
          test: /'use strict';\nvar utils = require\('.\/utils'\);/m,
          replace: "'use strict'",
        },
        {
          // match against jszip/lib/compressedObject.js
          // Workaround until https://github.com/Stuk/jszip/pull/731 is merged
          include: path.resolve(
            __dirname,
            'node_modules',
            'jszip',
            'lib',
            'compressedObject.js'
          ),
          test: /Crc32Probe'\);\nvar DataLengthProbe = require\('.\/stream\/DataLengthProbe'\);/m,
          replace: "Crc32Probe');\n",
        },
      ],
    }),
    alias({
      entries: [
        { find: 'vtk.js', replacement: path.resolve(__dirname) },
        { find: 'stream', replacement: require.resolve('stream-browserify') },
      ],
    }),
    // ignore crypto module
    ignore(['crypto']),
    // needs to be before nodeResolve
    webworkerLoader({
      targetPlatform: 'browser',
      // needs to match the full import statement path
      pattern: /^.+\.worker(?:\.js)?$/,
      inline: false,
      preserveFileNames: true,
      outputFolder: 'WebWorkers',
    }),
    nodeResolve({
      // don't rely on node builtins for web
      preferBuiltins: false,
      browser: true,
    }),
    !process.env.NOLINT &&
      eslint({
        include: '**/*.js',
        exclude: 'node_modules/**',
      }),
    // commonjs should be before babel
    commonjs({
      dynamicRequireTargets: [
        // handle a dynamic require circular dependencies
        'node_modules/readable-stream/lib/_stream_duplex.js',
        'node_modules/jszip/lib/base64.js',
        'node_modules/xmlbuilder/lib/*.js',
      ],
      // dynamicRequireTargets implies transformMixedEsModules because
      // dynamicRequireTargets generates mixed modules
      transformMixedEsModules: true,
    }),
    babel({
      include: 'Sources/**',
      exclude: 'node_modules/**',
      extensions: ['.js'],
      babelHelpers: 'runtime',
    }),
    string({
      include: '**/*.glsl',
    }),
    json(),
    svgo(),
    postcss({
      modules: true,
      plugins: [autoprefixer],
    }),
    // windows ntfs hates colons in filenames,
    // and node-resolve and web-worker-loader are notorious for
    // inserting them into virtual modules that are written out
    // to the filesystem via preserveModules: true.
    rewriteFilenames({
      find: /:/g,
      replace: '_',
    }),
  ],
};
<commit_msg>fix(rollup): Do not hoist transitive imports<commit_after>import * as path from 'path';
import * as glob from 'glob';

import autoprefixer from 'autoprefixer';

import alias from '@rollup/plugin-alias';
import { babel } from '@rollup/plugin-babel';
import commonjs from '@rollup/plugin-commonjs';
import eslint from '@rollup/plugin-eslint';
import ignore from 'rollup-plugin-ignore';
import json from '@rollup/plugin-json';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import postcss from 'rollup-plugin-postcss';
import replace from 'rollup-plugin-re';
import { string } from 'rollup-plugin-string';
import svgo from 'rollup-plugin-svgo';
import webworkerLoader from 'rollup-plugin-web-worker-loader';

import { rewriteFilenames } from './Utilities/rollup/plugin-rewrite-filenames';

const IGNORE_LIST = [
  /[/\\]example_?[/\\]/,
  /[/\\]test/,
  /^Sources[/\\](Testing|ThirdParty)/,
];

function ignoreFile(name, ignoreList = IGNORE_LIST) {
  return ignoreList.some((toMatch) => {
    if (toMatch instanceof RegExp) {
      return toMatch.test(name);
    }
    if (toMatch instanceof String) {
      return toMatch === name;
    }
    return false;
  });
}

const entryPoints = [
  path.join('Sources', 'macro.js'),
  path.join('Sources', 'vtk.js'),
  path.join('Sources', 'favicon.js'),
  ...glob.sync('Sources/**/index.js').filter((file) => !ignoreFile(file)),
];

const entries = {};
entryPoints.forEach((entry) => {
  entries[entry.replace(/^Sources[/\\]/, '')] = entry;
});

export default {
  input: entries,
  output: {
    dir: 'dist/esm/',
    format: 'es',
    hoistTransitiveImports: false,
    entryFileNames(chunkInfo) {
      const name = chunkInfo.name;

      // rewrite vtk.js files from Sources/.../<NAME>/index.js to .../<NAME>.js
      const sourcesMatch = /^(.*?)[/\\]([A-Z]\w+)[/\\]index\.js$/.exec(name);
      if (sourcesMatch) {
        return path.join(sourcesMatch[1], `${sourcesMatch[2]}.js`);
      }

      return name;
    },
    manualChunks(id) {
      if (id.includes('node_modules')) {
        return 'vendor';
      }
      // strip out full path to project root
      return id.replace(`${path.resolve(__dirname)}${path.sep}`, '');
    },
    chunkFileNames(chunkInfo) {
      let name = chunkInfo.name;

      if (name === 'vendor') {
        return path.join('_vendor', 'vendor.js');
      }

      // throw all subscript prefixed chunks into a virtual folder
      if (name.startsWith('_')) {
        return name.replace(/^_/, `_virtual${path.sep}`);
      }

      if (!name.endsWith('.js')) {
        name += '.js';
      }

      // rewrite Sources/ chunks
      return name.replace(/^Sources[/\\]/, '');
    },
  },
  external: [/@babel\/runtime/],
  plugins: [
    // should be before commonjs
    replace({
      patterns: [
        {
          // match against jszip/lib/load.js
          // Workaround until https://github.com/Stuk/jszip/pull/731 is merged
          include: path.resolve(
            __dirname,
            'node_modules',
            'jszip',
            'lib',
            'load.js'
          ),
          test: /'use strict';\nvar utils = require\('.\/utils'\);/m,
          replace: "'use strict'",
        },
        {
          // match against jszip/lib/compressedObject.js
          // Workaround until https://github.com/Stuk/jszip/pull/731 is merged
          include: path.resolve(
            __dirname,
            'node_modules',
            'jszip',
            'lib',
            'compressedObject.js'
          ),
          test: /Crc32Probe'\);\nvar DataLengthProbe = require\('.\/stream\/DataLengthProbe'\);/m,
          replace: "Crc32Probe');\n",
        },
      ],
    }),
    alias({
      entries: [
        { find: 'vtk.js', replacement: path.resolve(__dirname) },
        { find: 'stream', replacement: require.resolve('stream-browserify') },
      ],
    }),
    // ignore crypto module
    ignore(['crypto']),
    // needs to be before nodeResolve
    webworkerLoader({
      targetPlatform: 'browser',
      // needs to match the full import statement path
      pattern: /^.+\.worker(?:\.js)?$/,
      inline: false,
      preserveFileNames: true,
      outputFolder: 'WebWorkers',
    }),
    nodeResolve({
      // don't rely on node builtins for web
      preferBuiltins: false,
      browser: true,
    }),
    !process.env.NOLINT &&
      eslint({
        include: '**/*.js',
        exclude: 'node_modules/**',
      }),
    // commonjs should be before babel
    commonjs({
      dynamicRequireTargets: [
        // handle a dynamic require circular dependencies
        'node_modules/readable-stream/lib/_stream_duplex.js',
        'node_modules/jszip/lib/base64.js',
        'node_modules/xmlbuilder/lib/*.js',
      ],
      // dynamicRequireTargets implies transformMixedEsModules because
      // dynamicRequireTargets generates mixed modules
      transformMixedEsModules: true,
    }),
    babel({
      include: 'Sources/**',
      exclude: 'node_modules/**',
      extensions: ['.js'],
      babelHelpers: 'runtime',
    }),
    string({
      include: '**/*.glsl',
    }),
    json(),
    svgo(),
    postcss({
      modules: true,
      plugins: [autoprefixer],
    }),
    // windows ntfs hates colons in filenames,
    // and node-resolve and web-worker-loader are notorious for
    // inserting them into virtual modules that are written out
    // to the filesystem via preserveModules: true.
    rewriteFilenames({
      find: /:/g,
      replace: '_',
    }),
  ],
};
<|endoftext|>


<commit_before>import commonjs from '@rollup/plugin-commonjs';
// import eslint from '@rollup/plugin-eslint';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';
import { terser } from 'rollup-plugin-terser';

import pkg from './package.json';

const local = process.env.NODE_ENV === 'local';

export default {
    input: 'src/index.ts',
    output: [
        {
            dir: './',
            entryFileNames: pkg.main,
            format: 'cjs',
            sourcemap: local,
            exports: 'named',
        },
        {
            dir: './',
            entryFileNames: pkg.module,
            format: 'es',
            sourcemap: local,
        },
    ],
    external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})],
    watch: {
        include: 'src/**',
    },
    plugins: [
        // eslint(),
        typescript({
            typescript: require('typescript'),
            sourceMap: local,
            declaration: true,
            declarationDir: 'dist/',
            rootDir: 'src/',
        }),
        commonjs(),
        nodeResolve(),
        terser(),
    ],
};
<commit_msg>#000: Remove paths from rollup config<commit_after>import commonjs from '@rollup/plugin-commonjs';
// import eslint from '@rollup/plugin-eslint';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import typescript from '@rollup/plugin-typescript';
import { terser } from 'rollup-plugin-terser';

import pkg from './package.json';

const local = process.env.NODE_ENV === 'local';

export default {
    input: 'src/index.ts',
    output: [
        {
            dir: './',
            entryFileNames: pkg.main,
            format: 'cjs',
            sourcemap: local,
            exports: 'named',
        },
        {
            dir: './',
            entryFileNames: pkg.module,
            format: 'es',
            sourcemap: local,
        },
    ],
    external: [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.peerDependencies || {})],
    watch: {
        include: 'src/**',
    },
    plugins: [
        // eslint(),
        typescript({
            typescript: require('typescript'),
            sourceMap: local,
        }),
        commonjs(),
        nodeResolve(),
        terser(),
    ],
};
<|endoftext|>


<commit_before>// Some functions to interact with Facebook

var FB_PERMISSIONS = 'public_profile, user_friends, publish_actions';

var FB_UID = undefined;
var FB_ACCESS_TOKEN = undefined;

function _fbSaveLogin(response)
{
    FB_UID = response.authResponse.userID;
    FB_ACCESS_TOKEN = response.authResponse.accessToken;
}

function fbIsLoggedIn() {
    return Boolean(FB_UID && FB_ACCESS_TOKEN);
}

function fbPublishScore(score, callback, errorCallback) {
    fbUseApi('/' + FB_UID + '/scores', 'post', {},
        function (response) {
            if (response.success) {
                if (callback) {
                    callback(score);
                }
            } else {
                console.error('Could not publish score to Facebook');
                if (errorCallback) {
                    errorCallback();
                }
            }
        });
}

function fbGetUserScore(callback) {
    fbUseApi('/' + FB_UID + '/scores', 'get', {},
        function (response) {
            data = response.data;
            if (data.length < 1) {
                console.error('Could not retrieve the user score');
                return;
            }
            // Check if there are several scores in the response
            var iScore = 0;
            if (data.length > 1) {
                // Find the app score
                for (var i = 0; i < data.length; i++) {
                    if (data[i].application.id == FB_APP_ID) {
                        iScore = i;
                        break;
                    }
                }
            }
            // Get the score
            var score = data[iScore].score;
            if (callback) {
                callback(score);
            }
        });
}

function fbGetFriendsScores(callback) {
    fbUseApi('/' + FB_APP_ID + '/scores', 'get', {},
        function (response) {
            data = response.data;
            // Find user position
            var userIdx = undefined;
            for (var i = 0; i < data.length; i++) {
                if (data[i].user.id == FB_UID) {
                    userIdx = i;
                    break;
                }
            }

            if (callback) {
                callback(data, userIdx);
            }
        });
}

function fbGetProfilePicture(uid, callback) {
    fbUseApi('/' + uid + '/picture', 'get', {},
        function (response) {
            if (callback) {
                callback(response.data.url, response.data.is_silhouette);
            }
        });
}

function fbGetUserProfilePicture(callback) {
    fbUseApi('/me/picture', 'get', {},
        function (response) {
            if (callback) {
                callback(response.data.url, response.data.is_silhouette);
            }
        };);
}

function fbUseApi(url, method, params, callback) {
    params = params || ({});
    if (fbIsLoggedIn()) {
        // Already logged in
        params.access_token = FB_ACCESS_TOKEN;
        FB.api(url, method, params, callback);
    } else {
        FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                // Already granted permissions
                _fbSaveLogin(response);
                params.access_token = FB_ACCESS_TOKEN;
                FB.api(url, method, params, callback);
            } else {
                // Show login dialog first
                FB.login(function (response) {
                    _fbSaveLogin(response);
                    params.access_token = FB_ACCESS_TOKEN;
                    FB.api(url, method, params, callback);
                }, {scope: FB_PERMISSIONS});
            }
        });
    }
}
<commit_msg>Freaking extra semicolon<commit_after>// Some functions to interact with Facebook

var FB_PERMISSIONS = 'public_profile, user_friends, publish_actions';

var FB_UID = undefined;
var FB_ACCESS_TOKEN = undefined;

function _fbSaveLogin(response)
{
    FB_UID = response.authResponse.userID;
    FB_ACCESS_TOKEN = response.authResponse.accessToken;
}

function fbIsLoggedIn() {
    return Boolean(FB_UID && FB_ACCESS_TOKEN);
}

function fbPublishScore(score, callback, errorCallback) {
    fbUseApi('/' + FB_UID + '/scores', 'post', {},
        function (response) {
            if (response.success) {
                if (callback) {
                    callback(score);
                }
            } else {
                console.error('Could not publish score to Facebook');
                if (errorCallback) {
                    errorCallback();
                }
            }
        });
}

function fbGetUserScore(callback) {
    fbUseApi('/' + FB_UID + '/scores', 'get', {},
        function (response) {
            data = response.data;
            if (data.length < 1) {
                console.error('Could not retrieve the user score');
                return;
            }
            // Check if there are several scores in the response
            var iScore = 0;
            if (data.length > 1) {
                // Find the app score
                for (var i = 0; i < data.length; i++) {
                    if (data[i].application.id == FB_APP_ID) {
                        iScore = i;
                        break;
                    }
                }
            }
            // Get the score
            var score = data[iScore].score;
            if (callback) {
                callback(score);
            }
        });
}

function fbGetFriendsScores(callback) {
    fbUseApi('/' + FB_APP_ID + '/scores', 'get', {},
        function (response) {
            data = response.data;
            // Find user position
            var userIdx = undefined;
            for (var i = 0; i < data.length; i++) {
                if (data[i].user.id == FB_UID) {
                    userIdx = i;
                    break;
                }
            }

            if (callback) {
                callback(data, userIdx);
            }
        });
}

function fbGetProfilePicture(uid, callback) {
    fbUseApi('/' + uid + '/picture', 'get', {},
        function (response) {
            if (callback) {
                callback(response.data.url, response.data.is_silhouette);
            }
        });
}

function fbGetUserProfilePicture(callback) {
    fbUseApi('/me/picture', 'get', {},
        function (response) {
            if (callback) {
                callback(response.data.url, response.data.is_silhouette);
            }
        });
}

function fbUseApi(url, method, params, callback) {
    params = params || ({});
    if (fbIsLoggedIn()) {
        // Already logged in
        params.access_token = FB_ACCESS_TOKEN;
        FB.api(url, method, params, callback);
    } else {
        FB.getLoginStatus(function (response) {
            if (response.status === 'connected') {
                // Already granted permissions
                _fbSaveLogin(response);
                params.access_token = FB_ACCESS_TOKEN;
                FB.api(url, method, params, callback);
            } else {
                // Show login dialog first
                FB.login(function (response) {
                    _fbSaveLogin(response);
                    params.access_token = FB_ACCESS_TOKEN;
                    FB.api(url, method, params, callback);
                }, {scope: FB_PERMISSIONS});
            }
        });
    }
}
<|endoftext|>


<commit_before>/* eslint-disable no-console */
import json from '@rollup/plugin-json'
import resolve from '@rollup/plugin-node-resolve'
import fs from 'fs'
import gitrev from 'git-rev-promises'
import autoExternal from 'rollup-plugin-auto-external'
import babel from 'rollup-plugin-babel'
import pkg from './package.json'

Promise.all([
  gitrev.long(),
  gitrev.branch(),
  gitrev.tags(),
  gitrev.date(),
]).then(([hash, branch, tags, date]) => {
  const buildJson = JSON.stringify({
    version: pkg.version,
    hash,
    branch,
    tags,
    date,
  })
  fs.writeFile('build.json', buildJson, 'utf8', () => {
    console.info('Build information saved')
  })
})

const config = {
  input: 'src/index.mjs',
  output: {
    dir: 'dist',
    format: 'esm',
    entryFileNames: '[name].mjs',
    sourcemap: true,
  },
  external: ['nanoid/async'],
  preserveModules: true,
  plugins: [autoExternal(), json(), resolve(), babel({ externalHelpers: true })],
}

export default config

<commit_msg>Ensure workers are built and output to dist<commit_after>/* eslint-disable no-console */
import json from '@rollup/plugin-json'
import resolve from '@rollup/plugin-node-resolve'
import fs from 'fs'
import gitrev from 'git-rev-promises'
import autoExternal from 'rollup-plugin-auto-external'
import babel from 'rollup-plugin-babel'
import pkg from './package.json'

Promise.all([
  gitrev.long(),
  gitrev.branch(),
  gitrev.tags(),
  gitrev.date(),
]).then(([hash, branch, tags, date]) => {
  const buildJson = JSON.stringify({
    version: pkg.version,
    hash,
    branch,
    tags,
    date,
  })
  fs.writeFile('build.json', buildJson, 'utf8', () => {
    console.info('Build information saved')
  })
})

const defineEntry = (input, outputDir) => {
  return {
    input,
    output: {
      dir: outputDir,
      format: 'esm',
      entryFileNames: '[name].mjs',
      sourcemap: true,
    },
    external: ['nanoid/async'],
    preserveModules: true,
    plugins: [autoExternal(), json(), resolve(), babel({ externalHelpers: true })],
  }
}

const config = [
  defineEntry('src/index.mjs', 'dist'),
  defineEntry('src/workers/certificate.mjs', 'dist/workers'),
  defineEntry('src/workers/image.mjs', 'dist/workers'),
]

export default config

<|endoftext|>


<commit_before>function glsl() {

	return {

		transform( code, id ) {

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

			var transformedCode = 'export default ' + JSON.stringify(
				code
					.replace( /[ \t]*\/\/.*\n/g, '' ) // remove //
					.replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ) // remove /* */
					.replace( /\n{2,}/g, '\n' ) // # \n+ to \n
			) + ';';
			return {
				code: transformedCode,
				map: { mappings: '' }
			};

		}

	};

}

export default {
	input: 'src/Three.js',
	plugins: [
		glsl()
	],
	// sourceMap: true,
	output: [
		{
			format: 'umd',
			name: 'THREE',
			file: 'build/three.js',
			indent: '\t'
		},
		{
			format: 'es',
			file: 'build/three.module.js',
			indent: '\t'
		}
	]
};
<commit_msg>Rollup: Added plugin for converting gl constants to their values.<commit_after>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,
		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,
		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,
		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_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,
		DEPTH_COMPONENT32F: 36012,
		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
	};

	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: { mappings: '' }
			}
		}

	}

}

function glsl() {

	return {

		transform( code, id ) {

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

			var transformedCode = 'export default ' + JSON.stringify(
				code
					.replace( /[ \t]*\/\/.*\n/g, '' ) // remove //
					.replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ) // remove /* */
					.replace( /\n{2,}/g, '\n' ) // # \n+ to \n
			) + ';';
			return {
				code: transformedCode,
				map: { mappings: '' }
			};

		}

	};

}

export default {
	input: 'src/Three.js',
	plugins: [
		glconstants(),
		glsl()
	],
	// sourceMap: true,
	output: [
		{
			format: 'umd',
			name: 'THREE',
			file: 'build/three.js',
			indent: '\t'
		},
		{
			format: 'es',
			file: 'build/three.module.js',
			indent: '\t'
		}
	]
};
<|endoftext|>


<commit_before>/*!
 * algorithms/helpers.js - Internal functions and fields used in Cryptographic
 * Algorithms
 *
 * Copyright (c) 2015 Cisco Systems, Inc.  See LICENSE file.
 */
"use strict";

require("es6-promise").polyfill();

// ###
exports.int32ToBuffer = function(v, b) {
  b = b || new Buffer(4);
  b[0] = (v >>> 24) & 0xff;
  b[1] = (v >>> 16) & 0xff;
  b[2] = (v >>> 8) & 0xff;
  b[3] = v & 0xff;
  return b;
};

var MAX_INT32 = Math.pow(2, 32);
exports.int64ToBuffer = function(v, b) {
  b = b || new Buffer(8);
  var hi = Math.floor(v / MAX_INT32),
      lo = v % MAX_INT32;
  hi = exports.int32ToBuffer(hi);
  lo = exports.int32ToBuffer(lo);
  b = Buffer.concat([hi, lo]);
  return b;
};

// ### crypto and DOMException in browsers ###
/* global crypto:false, DOMException:false */

function getCryptoSubtle() {
  if ("undefined" !== typeof crypto) {
    if ("undefined" !== typeof crypto.subtle) {
      return crypto.subtle;
    }
    if ("undefined" !== typeof crypto.webkitSubtle) {
      return crypto.webkitSubtle;
    }
  }

  return undefined;
}
function getCryptoNodeJS() {
  var crypto;
  try {
    var pkgname = "crypto";
    crypto = require(pkgname);
  } catch (err) {
    return undefined;
  }

  return crypto;
}

var supported = {};
Object.defineProperty(exports, "subtleCrypto", {
  get: function() {
    var result;

    if ("subtleCrypto" in supported) {
      result = supported.subtleCrypto;
    } else {
      result = supported.subtleCrypto = getCryptoSubtle();
    }

    return result;
  },
  enumerable: true
});
Object.defineProperty(exports, "nodeCrypto", {
  get: function() {
    var result;

    if ("nodeCrypto" in supported) {
      result = supported.nodeCrypto;
    } else {
      result = supported.nodeCrypto = getCryptoNodeJS();
    }

    return result;
  },
  enumerable: true
});

exports.setupFallback = function(nodejs, webcrypto, fallback) {
  var impl;

  if (nodejs && exports.nodeCrypto) {
    impl = function main() {
      var args = arguments,
          promise;

      function check(err) {
        if (0 === err.message.indexOf("unsupported algorithm:")) {
          impl = fallback;
          return impl.apply(null, args);
        }

        return Promise.reject(err);
      }

      try {
        promise = Promise.resolve(nodejs.apply(null, args));
      } catch(err) {
        promise = check(err);
      }

      return promise;
    };
  } else if (webcrypto && exports.subtleCrypto) {
    impl = function main() {
      var args = arguments,
         promise;

      function check(err) {
        if (err.code === DOMException.NOT_SUPPORTED_ERR ||
            err.message === "Only ArrayBuffer and ArrayBufferView objects can be passed as CryptoOperationData") {
          // not actually supported -- always use fallback
          impl = fallback;
          return impl.apply(null, args);
        }

       return Promise.reject(err);
      }

      try {
        promise = webcrypto.apply(null, args);
        promise = promise.catch(check);
      } catch(err) {
        promise = check(err);
      }

      return promise;
    };
  } else {
    impl = fallback;
  }

  return impl;
};
<commit_msg>polyfill not required all the time<commit_after>/*!
 * algorithms/helpers.js - Internal functions and fields used in Cryptographic
 * Algorithms
 *
 * Copyright (c) 2015 Cisco Systems, Inc.  See LICENSE file.
 */
"use strict";

if (typeof Promise === "undefined") {
  require("es6-promise").polyfill();
}

// ###
exports.int32ToBuffer = function(v, b) {
  b = b || new Buffer(4);
  b[0] = (v >>> 24) & 0xff;
  b[1] = (v >>> 16) & 0xff;
  b[2] = (v >>> 8) & 0xff;
  b[3] = v & 0xff;
  return b;
};

var MAX_INT32 = Math.pow(2, 32);
exports.int64ToBuffer = function(v, b) {
  b = b || new Buffer(8);
  var hi = Math.floor(v / MAX_INT32),
      lo = v % MAX_INT32;
  hi = exports.int32ToBuffer(hi);
  lo = exports.int32ToBuffer(lo);
  b = Buffer.concat([hi, lo]);
  return b;
};

// ### crypto and DOMException in browsers ###
/* global crypto:false, DOMException:false */

function getCryptoSubtle() {
  if ("undefined" !== typeof crypto) {
    if ("undefined" !== typeof crypto.subtle) {
      return crypto.subtle;
    }
    if ("undefined" !== typeof crypto.webkitSubtle) {
      return crypto.webkitSubtle;
    }
  }

  return undefined;
}
function getCryptoNodeJS() {
  var crypto;
  try {
    var pkgname = "crypto";
    crypto = require(pkgname);
  } catch (err) {
    return undefined;
  }

  return crypto;
}

var supported = {};
Object.defineProperty(exports, "subtleCrypto", {
  get: function() {
    var result;

    if ("subtleCrypto" in supported) {
      result = supported.subtleCrypto;
    } else {
      result = supported.subtleCrypto = getCryptoSubtle();
    }

    return result;
  },
  enumerable: true
});
Object.defineProperty(exports, "nodeCrypto", {
  get: function() {
    var result;

    if ("nodeCrypto" in supported) {
      result = supported.nodeCrypto;
    } else {
      result = supported.nodeCrypto = getCryptoNodeJS();
    }

    return result;
  },
  enumerable: true
});

exports.setupFallback = function(nodejs, webcrypto, fallback) {
  var impl;

  if (nodejs && exports.nodeCrypto) {
    impl = function main() {
      var args = arguments,
          promise;

      function check(err) {
        if (0 === err.message.indexOf("unsupported algorithm:")) {
          impl = fallback;
          return impl.apply(null, args);
        }

        return Promise.reject(err);
      }

      try {
        promise = Promise.resolve(nodejs.apply(null, args));
      } catch(err) {
        promise = check(err);
      }

      return promise;
    };
  } else if (webcrypto && exports.subtleCrypto) {
    impl = function main() {
      var args = arguments,
         promise;

      function check(err) {
        if (err.code === DOMException.NOT_SUPPORTED_ERR ||
            err.message === "Only ArrayBuffer and ArrayBufferView objects can be passed as CryptoOperationData") {
          // not actually supported -- always use fallback
          impl = fallback;
          return impl.apply(null, args);
        }

       return Promise.reject(err);
      }

      try {
        promise = webcrypto.apply(null, args);
        promise = promise.catch(check);
      } catch(err) {
        promise = check(err);
      }

      return promise;
    };
  } else {
    impl = fallback;
  }

  return impl;
};
<|endoftext|>


<commit_before>import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import sourceMaps from 'rollup-plugin-sourcemaps'
import json from 'rollup-plugin-json'
import builtins from 'rollup-plugin-node-builtins'

const pkg = require('./package.json')
const camelCase = require('lodash.camelcase')

const libraryName = 'dynamo-easy'

export default {
  input: `compiled/${libraryName}.js`,
  output: [
    {file: pkg.main, format: 'umd', name: camelCase(libraryName)},
    {file: pkg.module, format: 'es'}
  ],
  sourcemap: true,
  // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash')
  external: function (id) {
    // console.log('external stuff', id)
    return /^(lodash|moment|aws-sdk|rxjs|reflect-metadata)/.test(id)
  },
  globals: function (id) {
    console.log('global ' + id);
    return false
  },
  plugins: [
    json({
      include: ['node_modules/aws-sdk/**/*', 'node_modules/winston/**/*'],
    }),
    builtins(),
    // Allow node_modules resolution, so you can use 'external' to control
    // which external modules to include in the bundle
    // https://github.com/rollup/rollup-plugin-node-resolve#usage
    resolve({
      // libraries ready to support es2015 modules may have this field
      jsnext: true,
      main: true
    }),

    // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
    commonjs(),

    // Resolve source maps to the original source
    sourceMaps()
  ]
}
<commit_msg>feat(reflectMetadata): trigger new build with a feature mark<commit_after>import resolve from 'rollup-plugin-node-resolve'
import commonjs from 'rollup-plugin-commonjs'
import sourceMaps from 'rollup-plugin-sourcemaps'
import json from 'rollup-plugin-json'
import builtins from 'rollup-plugin-node-builtins'

const pkg = require('./package.json')
const camelCase = require('lodash.camelcase')

const libraryName = 'dynamo-easy'

export default {
  input: `compiled/${libraryName}.js`,
  output: [
    {file: pkg.main, format: 'umd', name: camelCase(libraryName)},
    {file: pkg.module, format: 'es'}
  ],
  sourcemap: true,
  // Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash')
  external: function (id) {
    return /^(lodash|moment|aws-sdk|rxjs|reflect-metadata)/.test(id)
  },
  globals: function (id) {
    console.log('global ' + id);
    return false
  },
  plugins: [
    json({
      include: ['node_modules/aws-sdk/**/*'],
    }),
    builtins(),
    // Allow node_modules resolution, so you can use 'external' to control
    // which external modules to include in the bundle
    // https://github.com/rollup/rollup-plugin-node-resolve#usage
    resolve({
      // libraries ready to support es2015 modules may have this field
      jsnext: true,
      main: true
    }),

    // Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
    commonjs(),

    // Resolve source maps to the original source
    sourceMaps()
  ]
}
<|endoftext|>