<commit_before>#!/usr/bin/env node
"use strict";

const path = require("path");
const open = require("opn");
const fs = require("fs");
const net = require("net");
const portfinder = require("portfinder");
const addDevServerEntrypoints = require("../lib/util/addDevServerEntrypoints");
const createDomain = require("../lib/util/createDomain");

// Local version replaces global one
try {
	const localWebpackDevServer = require.resolve(path.join(process.cwd(), "node_modules", "webpack-dev-server", "bin", "webpack-dev-server.js"));
	if(__filename !== localWebpackDevServer) {
		return require(localWebpackDevServer);
	}
} catch(e) {}

const Server = require("../lib/Server");
const webpack = require("webpack");

function versionInfo() {
	return `webpack-dev-server ${require("../package.json").version}\n` +
		`webpack ${require("webpack/package.json").version}`;
}

function colorInfo(useColor, msg) {
	if(useColor)
		// Make text blue and bold, so it *pops*
		return `\u001b[1m\u001b[34m${msg}\u001b[39m\u001b[22m`;
	return msg;
}

function colorError(useColor, msg) {
	if(useColor)
		// Make text red and bold, so it *pops*
		return `\u001b[1m\u001b[31m${msg}\u001b[39m\u001b[22m`;
	return msg;
}

const yargs = require("yargs")
	.usage(`${versionInfo()
		}\nUsage: https://webpack.js.org/configuration/dev-server/`);

require("webpack/bin/config-yargs")(yargs);

// It is important that this is done after the webpack yargs config,
// so it overrides webpack's version info.
yargs.version(versionInfo);

const ADVANCED_GROUP = "Advanced options:";
const DISPLAY_GROUP = "Stats options:";
const SSL_GROUP = "SSL options:";
const CONNECTION_GROUP = "Connection options:";
const RESPONSE_GROUP = "Response options:";
const BASIC_GROUP = "Basic options:";

// Taken out of yargs because we must know if
// it wasn't given by the user, in which case
// we should use portfinder.
const DEFAULT_PORT = 8080;

yargs.options({
	"lazy": {
		type: "boolean",
		describe: "Lazy"
	},
	"inline": {
		type: "boolean",
		default: true,
		describe: "Inline mode (set to false to disable including client scripts like livereload)"
	},
	"progress": {
		type: "boolean",
		describe: "Print compilation progress in percentage",
		group: BASIC_GROUP
	},
	"hot-only": {
		type: "boolean",
		describe: "Do not refresh page if HMR fails",
		group: ADVANCED_GROUP
	},
	"stdin": {
		type: "boolean",
		describe: "close when stdin ends"
	},
	"open": {
		type: "boolean",
		describe: "Open default browser"
	},
	"color": {
		type: "boolean",
		alias: "colors",
		default: function supportsColor() {
			return require("supports-color");
		},
		group: DISPLAY_GROUP,
		describe: "Enables/Disables colors on the console"
	},
	"info": {
		type: "boolean",
		group: DISPLAY_GROUP,
		default: true,
		describe: "Info"
	},
	"quiet": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Quiet"
	},
	"client-log-level": {
		type: "string",
		group: DISPLAY_GROUP,
		default: "info",
		describe: "Log level in the browser (info, warning, error or none)"
	},
	"https": {
		type: "boolean",
		group: SSL_GROUP,
		describe: "HTTPS"
	},
	"key": {
		type: "string",
		describe: "Path to a SSL key.",
		group: SSL_GROUP
	},
	"cert": {
		type: "string",
		describe: "Path to a SSL certificate.",
		group: SSL_GROUP
	},
	"cacert": {
		type: "string",
		describe: "Path to a SSL CA certificate.",
		group: SSL_GROUP
	},
	"pfx": {
		type: "string",
		describe: "Path to a SSL pfx file.",
		group: SSL_GROUP
	},
	"pfx-passphrase": {
		type: "string",
		describe: "Passphrase for pfx file.",
		group: SSL_GROUP
	},
	"content-base": {
		type: "string",
		describe: "A directory or URL to serve HTML content from.",
		group: RESPONSE_GROUP
	},
	"watch-content-base": {
		type: "boolean",
		describe: "Enable live-reloading of the content-base.",
		group: RESPONSE_GROUP
	},
	"history-api-fallback": {
		type: "boolean",
		describe: "Fallback to /index.html for Single Page Applications.",
		group: RESPONSE_GROUP
	},
	"compress": {
		type: "boolean",
		describe: "Enable gzip compression",
		group: RESPONSE_GROUP
	},
	"port": {
		describe: "The port",
		group: CONNECTION_GROUP
	},
	"socket": {
		type: "String",
		describe: "Socket to listen",
		group: CONNECTION_GROUP
	},
	"public": {
		type: "string",
		describe: "The public hostname/ip address of the server",
		group: CONNECTION_GROUP
	},
	"host": {
		type: "string",
		default: "localhost",
		describe: "The hostname/ip address the server will bind to",
		group: CONNECTION_GROUP
	}
});

const argv = yargs.argv;

const wpOpt = require("webpack/bin/convert-argv")(yargs, argv, {
	outputFilename: "/bundle.js"
});

function processOptions(wpOpt) {
	// process Promise
	if(typeof wpOpt.then === "function") {
		wpOpt.then(processOptions).catch(function(err) {
			console.error(err.stack || err);
			process.exit(); // eslint-disable-line
		});
		return;
	}

	const firstWpOpt = Array.isArray(wpOpt) ? wpOpt[0] : wpOpt;

	const options = wpOpt.devServer || firstWpOpt.devServer || {};

	if(argv.host !== "localhost" || !options.host)
		options.host = argv.host;

	if(argv.public)
		options.public = argv.public;

	if(argv.socket)
		options.socket = argv.socket;

	if(!options.publicPath) {
		options.publicPath = firstWpOpt.output && firstWpOpt.output.publicPath || "";
		if(!/^(https?:)?\/\//.test(options.publicPath) && options.publicPath[0] !== "/")
			options.publicPath = `/${options.publicPath}`;
	}

	if(!options.filename)
		options.filename = firstWpOpt.output && firstWpOpt.output.filename;

	if(!options.watchOptions)
		options.watchOptions = firstWpOpt.watchOptions;

	if(argv["stdin"]) {
		process.stdin.on("end", function() {
			process.exit(0); // eslint-disable-line no-process-exit
		});
		process.stdin.resume();
	}

	if(!options.hot)
		options.hot = argv["hot"];

	if(!options.hotOnly)
		options.hotOnly = argv["hot-only"];

	if(!options.clientLogLevel)
		options.clientLogLevel = argv["client-log-level"];

	if(options.contentBase === undefined) {
		if(argv["content-base"]) {
			options.contentBase = argv["content-base"];
			if(/^[0-9]$/.test(options.contentBase))
				options.contentBase = +options.contentBase;
			else if(!/^(https?:)?\/\//.test(options.contentBase))
				options.contentBase = path.resolve(options.contentBase);
		// It is possible to disable the contentBase by using `--no-content-base`, which results in arg["content-base"] = false
		} else if(argv["content-base"] === false) {
			options.contentBase = false;
		}
	}

	if(argv["watch-content-base"])
		options.watchContentBase = true;

	if(!options.stats) {
		options.stats = {
			cached: false,
			cachedAssets: false
		};
	}

	if(typeof options.stats === "object" && typeof options.stats.colors === "undefined")
		options.stats.colors = argv.color;

	if(argv["lazy"])
		options.lazy = true;

	if(!argv["info"])
		options.noInfo = true;

	if(argv["quiet"])
		options.quiet = true;

	if(argv["https"])
		options.https = true;

	if(argv["cert"])
		options.cert = fs.readFileSync(path.resolve(argv["cert"]));

	if(argv["key"])
		options.key = fs.readFileSync(path.resolve(argv["key"]));

	if(argv["cacert"])
		options.ca = fs.readFileSync(path.resolve(argv["cacert"]));

	if(argv["pfx"])
		options.pfx = fs.readFileSync(path.resolve(argv["pfx"]));

	if(argv["pfx-passphrase"])
		options.pfxPassphrase = argv["pfx-passphrase"];

	if(argv["inline"] === false)
		options.inline = false;

	if(argv["history-api-fallback"])
		options.historyApiFallback = true;

	if(argv["compress"])
		options.compress = true;

	if(argv["open"])
		options.open = true;

	// Kind of weird, but ensures prior behavior isn't broken in cases
	// that wouldn't throw errors. E.g. both argv.port and options.port
	// were specified, but since argv.port is 8080, options.port will be
	// tried first instead.
	options.port = argv.port === DEFAULT_PORT ? (options.port || argv.port) : (argv.port || options.port);
	if(options.port) {
		startDevServer(wpOpt, options);
		return;
	}

	portfinder.basePort = DEFAULT_PORT;
	portfinder.getPort(function(err, port) {
		if(err) throw err;
		options.port = port;
		startDevServer(wpOpt, options);
	});
}

function startDevServer(wpOpt, options) {
	addDevServerEntrypoints(wpOpt, options);

	let compiler;
	try {
		compiler = webpack(wpOpt);
	} catch(e) {
		if(e instanceof webpack.WebpackOptionsValidationError) {
			console.error(colorError(options.stats.colors, e.message));
			process.exit(1); // eslint-disable-line
		}
		throw e;
	}

	if(argv["progress"]) {
		compiler.apply(new webpack.ProgressPlugin({
			profile: argv["profile"]
		}));
	}

	const uri = createDomain(options) + (options.inline !== false || options.lazy === true ? "/" : "/webpack-dev-server/");

	let server;
	try {
		server = new Server(compiler, options);
	} catch(e) {
		const OptionsValidationError = require("../lib/OptionsValidationError");
		if(e instanceof OptionsValidationError) {
			console.error(colorError(options.stats.colors, e.message));
			process.exit(1); // eslint-disable-line
		}
		throw e;
	}

	["SIGINT", "SIGTERM"].forEach(function(sig) {
		process.on(sig, function() {
			console.log(`Gracefully shutting down server after ${sig}...`);
			server.close();
			process.exit();  // eslint-disable-line no-process-exit
		});
	});

	if(options.socket) {
		server.listeningApp.on("error", function(e) {
			if(e.code === "EADDRINUSE") {
				const clientSocket = new net.Socket();
				clientSocket.on("error", function(e) {
					if(e.code === "ECONNREFUSED") {
						// No other server listening on this socket so it can be safely removed
						fs.unlinkSync(options.socket);
						server.listen(options.socket, options.host, function(err) {
							if(err) throw err;
						});
					}
				});
				clientSocket.connect({ path: options.socket }, function() {
					throw new Error("This socket is already used");
				});
			}
		});
		server.listen(options.socket, options.host, function(err) {
			if(err) throw err;
			const READ_WRITE = 438; // chmod 666 (rw rw rw)
			fs.chmod(options.socket, READ_WRITE, function(err) {
				if(err) throw err;
				reportReadiness(uri, options);
			});
		});
	} else {
		server.listen(options.port, options.host, function(err) {
			if(err) throw err;
			reportReadiness(uri, options);
		});
	}
}

function reportReadiness(uri, options) {
	const useColor = argv.color;
	let startSentence = `Project is running at ${colorInfo(useColor, uri)}`
	if(options.socket) {
		startSentence = `Listening to socket at ${colorInfo(useColor, options.socket)}`;
	}
	console.log((argv["progress"] ? "\n" : "") + startSentence);

	console.log(`webpack output is served from ${colorInfo(useColor, options.publicPath)}`);
	const contentBase = Array.isArray(options.contentBase) ? options.contentBase.join(", ") : options.contentBase;
	if(contentBase)
		console.log(`Content not from webpack is served from ${colorInfo(useColor, contentBase)}`);
	if(options.historyApiFallback)
		console.log(`404s will fallback to ${colorInfo(useColor, options.historyApiFallback.index || "/index.html")}`);
	if(options.open) {
		open(uri).catch(function() {
			console.log("Unable to open browser. If you are running in a headless environment, please do not use the open flag.");
		});
	}
}

processOptions(wpOpt);
<commit_msg>Remove unnecessary logging of closing the dev-server<commit_after>#!/usr/bin/env node
"use strict";

const path = require("path");
const open = require("opn");
const fs = require("fs");
const net = require("net");
const portfinder = require("portfinder");
const addDevServerEntrypoints = require("../lib/util/addDevServerEntrypoints");
const createDomain = require("../lib/util/createDomain");

// Local version replaces global one
try {
	const localWebpackDevServer = require.resolve(path.join(process.cwd(), "node_modules", "webpack-dev-server", "bin", "webpack-dev-server.js"));
	if(__filename !== localWebpackDevServer) {
		return require(localWebpackDevServer);
	}
} catch(e) {}

const Server = require("../lib/Server");
const webpack = require("webpack");

function versionInfo() {
	return `webpack-dev-server ${require("../package.json").version}\n` +
		`webpack ${require("webpack/package.json").version}`;
}

function colorInfo(useColor, msg) {
	if(useColor)
		// Make text blue and bold, so it *pops*
		return `\u001b[1m\u001b[34m${msg}\u001b[39m\u001b[22m`;
	return msg;
}

function colorError(useColor, msg) {
	if(useColor)
		// Make text red and bold, so it *pops*
		return `\u001b[1m\u001b[31m${msg}\u001b[39m\u001b[22m`;
	return msg;
}

const yargs = require("yargs")
	.usage(`${versionInfo()
		}\nUsage: https://webpack.js.org/configuration/dev-server/`);

require("webpack/bin/config-yargs")(yargs);

// It is important that this is done after the webpack yargs config,
// so it overrides webpack's version info.
yargs.version(versionInfo);

const ADVANCED_GROUP = "Advanced options:";
const DISPLAY_GROUP = "Stats options:";
const SSL_GROUP = "SSL options:";
const CONNECTION_GROUP = "Connection options:";
const RESPONSE_GROUP = "Response options:";
const BASIC_GROUP = "Basic options:";

// Taken out of yargs because we must know if
// it wasn't given by the user, in which case
// we should use portfinder.
const DEFAULT_PORT = 8080;

yargs.options({
	"lazy": {
		type: "boolean",
		describe: "Lazy"
	},
	"inline": {
		type: "boolean",
		default: true,
		describe: "Inline mode (set to false to disable including client scripts like livereload)"
	},
	"progress": {
		type: "boolean",
		describe: "Print compilation progress in percentage",
		group: BASIC_GROUP
	},
	"hot-only": {
		type: "boolean",
		describe: "Do not refresh page if HMR fails",
		group: ADVANCED_GROUP
	},
	"stdin": {
		type: "boolean",
		describe: "close when stdin ends"
	},
	"open": {
		type: "boolean",
		describe: "Open default browser"
	},
	"color": {
		type: "boolean",
		alias: "colors",
		default: function supportsColor() {
			return require("supports-color");
		},
		group: DISPLAY_GROUP,
		describe: "Enables/Disables colors on the console"
	},
	"info": {
		type: "boolean",
		group: DISPLAY_GROUP,
		default: true,
		describe: "Info"
	},
	"quiet": {
		type: "boolean",
		group: DISPLAY_GROUP,
		describe: "Quiet"
	},
	"client-log-level": {
		type: "string",
		group: DISPLAY_GROUP,
		default: "info",
		describe: "Log level in the browser (info, warning, error or none)"
	},
	"https": {
		type: "boolean",
		group: SSL_GROUP,
		describe: "HTTPS"
	},
	"key": {
		type: "string",
		describe: "Path to a SSL key.",
		group: SSL_GROUP
	},
	"cert": {
		type: "string",
		describe: "Path to a SSL certificate.",
		group: SSL_GROUP
	},
	"cacert": {
		type: "string",
		describe: "Path to a SSL CA certificate.",
		group: SSL_GROUP
	},
	"pfx": {
		type: "string",
		describe: "Path to a SSL pfx file.",
		group: SSL_GROUP
	},
	"pfx-passphrase": {
		type: "string",
		describe: "Passphrase for pfx file.",
		group: SSL_GROUP
	},
	"content-base": {
		type: "string",
		describe: "A directory or URL to serve HTML content from.",
		group: RESPONSE_GROUP
	},
	"watch-content-base": {
		type: "boolean",
		describe: "Enable live-reloading of the content-base.",
		group: RESPONSE_GROUP
	},
	"history-api-fallback": {
		type: "boolean",
		describe: "Fallback to /index.html for Single Page Applications.",
		group: RESPONSE_GROUP
	},
	"compress": {
		type: "boolean",
		describe: "Enable gzip compression",
		group: RESPONSE_GROUP
	},
	"port": {
		describe: "The port",
		group: CONNECTION_GROUP
	},
	"socket": {
		type: "String",
		describe: "Socket to listen",
		group: CONNECTION_GROUP
	},
	"public": {
		type: "string",
		describe: "The public hostname/ip address of the server",
		group: CONNECTION_GROUP
	},
	"host": {
		type: "string",
		default: "localhost",
		describe: "The hostname/ip address the server will bind to",
		group: CONNECTION_GROUP
	}
});

const argv = yargs.argv;

const wpOpt = require("webpack/bin/convert-argv")(yargs, argv, {
	outputFilename: "/bundle.js"
});

function processOptions(wpOpt) {
	// process Promise
	if(typeof wpOpt.then === "function") {
		wpOpt.then(processOptions).catch(function(err) {
			console.error(err.stack || err);
			process.exit(); // eslint-disable-line
		});
		return;
	}

	const firstWpOpt = Array.isArray(wpOpt) ? wpOpt[0] : wpOpt;

	const options = wpOpt.devServer || firstWpOpt.devServer || {};

	if(argv.host !== "localhost" || !options.host)
		options.host = argv.host;

	if(argv.public)
		options.public = argv.public;

	if(argv.socket)
		options.socket = argv.socket;

	if(!options.publicPath) {
		options.publicPath = firstWpOpt.output && firstWpOpt.output.publicPath || "";
		if(!/^(https?:)?\/\//.test(options.publicPath) && options.publicPath[0] !== "/")
			options.publicPath = `/${options.publicPath}`;
	}

	if(!options.filename)
		options.filename = firstWpOpt.output && firstWpOpt.output.filename;

	if(!options.watchOptions)
		options.watchOptions = firstWpOpt.watchOptions;

	if(argv["stdin"]) {
		process.stdin.on("end", function() {
			process.exit(0); // eslint-disable-line no-process-exit
		});
		process.stdin.resume();
	}

	if(!options.hot)
		options.hot = argv["hot"];

	if(!options.hotOnly)
		options.hotOnly = argv["hot-only"];

	if(!options.clientLogLevel)
		options.clientLogLevel = argv["client-log-level"];

	if(options.contentBase === undefined) {
		if(argv["content-base"]) {
			options.contentBase = argv["content-base"];
			if(/^[0-9]$/.test(options.contentBase))
				options.contentBase = +options.contentBase;
			else if(!/^(https?:)?\/\//.test(options.contentBase))
				options.contentBase = path.resolve(options.contentBase);
		// It is possible to disable the contentBase by using `--no-content-base`, which results in arg["content-base"] = false
		} else if(argv["content-base"] === false) {
			options.contentBase = false;
		}
	}

	if(argv["watch-content-base"])
		options.watchContentBase = true;

	if(!options.stats) {
		options.stats = {
			cached: false,
			cachedAssets: false
		};
	}

	if(typeof options.stats === "object" && typeof options.stats.colors === "undefined")
		options.stats.colors = argv.color;

	if(argv["lazy"])
		options.lazy = true;

	if(!argv["info"])
		options.noInfo = true;

	if(argv["quiet"])
		options.quiet = true;

	if(argv["https"])
		options.https = true;

	if(argv["cert"])
		options.cert = fs.readFileSync(path.resolve(argv["cert"]));

	if(argv["key"])
		options.key = fs.readFileSync(path.resolve(argv["key"]));

	if(argv["cacert"])
		options.ca = fs.readFileSync(path.resolve(argv["cacert"]));

	if(argv["pfx"])
		options.pfx = fs.readFileSync(path.resolve(argv["pfx"]));

	if(argv["pfx-passphrase"])
		options.pfxPassphrase = argv["pfx-passphrase"];

	if(argv["inline"] === false)
		options.inline = false;

	if(argv["history-api-fallback"])
		options.historyApiFallback = true;

	if(argv["compress"])
		options.compress = true;

	if(argv["open"])
		options.open = true;

	// Kind of weird, but ensures prior behavior isn't broken in cases
	// that wouldn't throw errors. E.g. both argv.port and options.port
	// were specified, but since argv.port is 8080, options.port will be
	// tried first instead.
	options.port = argv.port === DEFAULT_PORT ? (options.port || argv.port) : (argv.port || options.port);
	if(options.port) {
		startDevServer(wpOpt, options);
		return;
	}

	portfinder.basePort = DEFAULT_PORT;
	portfinder.getPort(function(err, port) {
		if(err) throw err;
		options.port = port;
		startDevServer(wpOpt, options);
	});
}

function startDevServer(wpOpt, options) {
	addDevServerEntrypoints(wpOpt, options);

	let compiler;
	try {
		compiler = webpack(wpOpt);
	} catch(e) {
		if(e instanceof webpack.WebpackOptionsValidationError) {
			console.error(colorError(options.stats.colors, e.message));
			process.exit(1); // eslint-disable-line
		}
		throw e;
	}

	if(argv["progress"]) {
		compiler.apply(new webpack.ProgressPlugin({
			profile: argv["profile"]
		}));
	}

	const uri = createDomain(options) + (options.inline !== false || options.lazy === true ? "/" : "/webpack-dev-server/");

	let server;
	try {
		server = new Server(compiler, options);
	} catch(e) {
		const OptionsValidationError = require("../lib/OptionsValidationError");
		if(e instanceof OptionsValidationError) {
			console.error(colorError(options.stats.colors, e.message));
			process.exit(1); // eslint-disable-line
		}
		throw e;
	}

	["SIGINT", "SIGTERM"].forEach(function(sig) {
		process.on(sig, function() {
			server.close();
			process.exit(); // eslint-disable-line no-process-exit
		});
	});

	if(options.socket) {
		server.listeningApp.on("error", function(e) {
			if(e.code === "EADDRINUSE") {
				const clientSocket = new net.Socket();
				clientSocket.on("error", function(e) {
					if(e.code === "ECONNREFUSED") {
						// No other server listening on this socket so it can be safely removed
						fs.unlinkSync(options.socket);
						server.listen(options.socket, options.host, function(err) {
							if(err) throw err;
						});
					}
				});
				clientSocket.connect({ path: options.socket }, function() {
					throw new Error("This socket is already used");
				});
			}
		});
		server.listen(options.socket, options.host, function(err) {
			if(err) throw err;
			const READ_WRITE = 438; // chmod 666 (rw rw rw)
			fs.chmod(options.socket, READ_WRITE, function(err) {
				if(err) throw err;
				reportReadiness(uri, options);
			});
		});
	} else {
		server.listen(options.port, options.host, function(err) {
			if(err) throw err;
			reportReadiness(uri, options);
		});
	}
}

function reportReadiness(uri, options) {
	const useColor = argv.color;
	let startSentence = `Project is running at ${colorInfo(useColor, uri)}`
	if(options.socket) {
		startSentence = `Listening to socket at ${colorInfo(useColor, options.socket)}`;
	}
	console.log((argv["progress"] ? "\n" : "") + startSentence);

	console.log(`webpack output is served from ${colorInfo(useColor, options.publicPath)}`);
	const contentBase = Array.isArray(options.contentBase) ? options.contentBase.join(", ") : options.contentBase;
	if(contentBase)
		console.log(`Content not from webpack is served from ${colorInfo(useColor, contentBase)}`);
	if(options.historyApiFallback)
		console.log(`404s will fallback to ${colorInfo(useColor, options.historyApiFallback.index || "/index.html")}`);
	if(options.open) {
		open(uri).catch(function() {
			console.log("Unable to open browser. If you are running in a headless environment, please do not use the open flag.");
		});
	}
}

processOptions(wpOpt);
<|endoftext|>


<commit_before>#!/usr/bin/env node
const octicons = require('octicons')
const fse = require('fs-extra')
const {join} = require('path')

const DIR = 'icons'

function CamelCase(str) {
  return str.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase())
}

const icons = [...Object.entries(octicons)].map(([key, octicon]) => {
  const name = CamelCase(key)
  const {width, height, path} = octicon
  // convert attributes like fill-rule into JSX equivalents, e.g. fillRule
  const svg = path.replace(/([a-z]+)-([a-z]+)=/g, (_, a, b) => `${a}${CamelCase(b)}=`)
  const code = `import React from 'react'
export default function ${name}() {
  return ${svg}
}
${name}.size = [${width}, ${height}]
`

  return {
    key,
    name,
    octicon,
    code
  }
})

const tasks = icons
  // sort them alphabetically
  .sort((a, b) => a.key.localeCompare(b.key))
  .map(({key, name, code}) => {
    const file = join(DIR, `${key}.js`)
    return fse.writeFile(file, code, 'utf8').then(() => ({key, name, file}))
  })

function writeIndex(icons) {
  const count = icons.length
  console.warn('wrote %d files to %s.', count, DIR)
  const file = join(DIR, 'index.js')
  const code = `/* THIS FILE IS GENERATED. DO NOT EDIT IT. */
${icons.map(({key, name}) => `import {default as ${name}} from './${key}'`).join('\n')}

const iconsByName = {
  ${icons.map(({key, name}) => `'${key}': ${name}`).join(',\n  ')}
}

function getIconByName(name) {
  return iconsByName[name]
}

export {
  getIconByName,
  iconsByName,
  ${icons.map(({name}) => name).join(',\n  ')}
}`
  return fse.writeFile(file, code, 'utf8').then(() => {
    console.warn('wrote %s with %d exports', file, count)
    return icons
  })
}

Promise.all(tasks)
  .then(writeIndex)
  .catch(error => {
    console.error(error)
    process.exit(1)
  })
<commit_msg>write icons to src/icons<commit_after>#!/usr/bin/env node
const octicons = require('octicons')
const fse = require('fs-extra')
const {join, resolve} = require('path')

const iconsDir = resolve(__dirname, '../src/icons')

function CamelCase(str) {
  return str.replace(/(^|-)([a-z])/g, (_, __, c) => c.toUpperCase())
}

const icons = [...Object.entries(octicons)].map(([key, octicon]) => {
  const name = CamelCase(key)
  const {width, height, path} = octicon
  // convert attributes like fill-rule into JSX equivalents, e.g. fillRule
  const svg = path.replace(/([a-z]+)-([a-z]+)=/g, (_, a, b) => `${a}${CamelCase(b)}=`)
  const code = `import React from 'react'
export default function ${name}() {
  return ${svg}
}
${name}.size = [${width}, ${height}]
`

  return {
    key,
    name,
    octicon,
    code
  }
})

const tasks = icons
  // sort them alphabetically
  .sort((a, b) => a.key.localeCompare(b.key))
  .map(({key, name, code}) => {
    const file = join(iconsDir, `${key}.js`)
    return fse.writeFile(file, code, 'utf8').then(() => ({key, name, file}))
  })

function writeIndex(icons) {
  const count = icons.length
  console.warn('wrote %d files to %s', count, iconsDir)
  const file = join(iconsDir, 'index.js')
  const code = `/* THIS FILE IS GENERATED. DO NOT EDIT IT. */
${icons.map(({key, name}) => `import {default as ${name}} from './${key}'`).join('\n')}

const iconsByName = {
  ${icons.map(({key, name}) => `'${key}': ${name}`).join(',\n  ')}
}

function getIconByName(name) {
  return iconsByName[name]
}

export {
  getIconByName,
  iconsByName,
  ${icons.map(({name}) => name).join(',\n  ')}
}`
  return fse.writeFile(file, code, 'utf8').then(() => {
    console.warn('wrote %s with %d exports', file, count)
    return icons
  })
}

Promise.all(tasks)
  .then(writeIndex)
  .catch(error => {
    console.error(error)
    process.exit(1)
  })
<|endoftext|>


<commit_before>//$(document).ajaxSend(function(event, request, settings) {
//  if (typeof(AUTH_TOKEN) == "undefined") return;
//  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
//  settings.data = settings.data || "";
//  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
//});

$(document).ready(function(){
  var show_asset_box = function() {
    $.fancybox.showActivity();
    var f_width = $(window).width()*0.8;
    var f_height = $(window).height()*0.8;
    $.ajaxSetup({cache: false});
    $.get('/assets/new', { content_only: true }, function(data) {
      $.fancybox({
        content: data,
        padding: 0,
        autoDimensions: false,
        width: f_width,
        height: f_height,
        onComplete: function(){
          $("#fancybox-content").data("box-type","add_asset");
          $.fancybox.resize();
        }
      });
    });
  };
  $(window).keydown(function(event){
    switch(event.keyCode) {
    case 65: // a
      activeObj = document.activeElement;
      if (activeObj.type == "textarea") break;
      if (activeObj.type == "text") break;
      if ($(activeObj).attr("class") != undefined && $(activeObj).attr("class").indexOf("slot") != -1) break;
      if ($("#fancybox-wrap").is(":visible")) {
        $.fancybox.close();
      } else {
        show_asset_box();
      }
      break;
    }
  });
  $(document).ajaxComplete(function() {
    adjust_links();
  });
  var adjust_links = function() {
    $("#add_asset_sidebar li.asset_type").click(function(event){
      event.preventDefault();
      $.fancybox.showActivity();
      asset_type = $(event.target).data("asset-type");
      $("div.fassets_core.new").load("/assets/new", {type: asset_type, content_only: true });
      $.fancybox.resize();
      $.fancybox.hideActivity();
    });
    $("#fancybox-content .asset_create_button").click(function(event){
      event.preventDefault();
      $.fancybox.showActivity();
      var action = $("#add_asset_content form").attr("action");
      $.post(action, $("#add_asset_content form").serialize(), function(data){
        $("#fancybox-content #add_asset_content").load(data[0].edit_box_url+"?type="+data[0].content_type);
      });
      reload_tray();
      $.fancybox.resize();;
      $.fancybox.hideActivity();
    });
    $("#fancybox-content .asset_submit_button").click(function(event){
      event.preventDefault();
      $.fancybox.showActivity();
      //var token = encodeURIComponent(AUTH_TOKEN)
      var asset_type = $(event.target).data("asset-type");
      reload_tray();
      $.fancybox.hideActivity();
    });
    $("form.edit_classification input[type=submit][value=Save]").hide();
  };

  adjust_links();
  $("#new_asset_link").click(function(event){
    event.preventDefault();
    show_asset_box();
  });
  var reload_tray = function() {
    var user_id = $("#tray").data("user-id");
    $("#tray").load("/users/"+user_id+"/tray_positions/", function() {
      $('#tray .drop_button').click(function(event){
        event.preventDefault();
        var user_id = $(event.target).data("user-id");
        var tp_id = $(event.target).data("tp-id");
        $.ajax({
          type: 'DELETE',
          cache	: false,
          url		: "/users/"+user_id+"/tray_positions/"+tp_id,
          success: function(data) {
            $("#tray").load("/users/"+user_id+"/tray_positions/");
          }
        });
      });
    });
  };
});
<commit_msg>remove JS overriding submit buttons in forms<commit_after>//$(document).ajaxSend(function(event, request, settings) {
//  if (typeof(AUTH_TOKEN) == "undefined") return;
//  // settings.data is a serialized string like "foo=bar&baz=boink" (or null)
//  settings.data = settings.data || "";
//  settings.data += (settings.data ? "&" : "") + "authenticity_token=" + encodeURIComponent(AUTH_TOKEN);
//});

$(document).ready(function(){
  var show_asset_box = function() {
    $.fancybox.showActivity();
    var f_width = $(window).width()*0.8;
    var f_height = $(window).height()*0.8;
    $.ajaxSetup({cache: false});
    $.get('/assets/new', { content_only: true }, function(data) {
      $.fancybox({
        content: data,
        padding: 0,
        autoDimensions: false,
        width: f_width,
        height: f_height,
        onComplete: function(){
          $("#fancybox-content").data("box-type","add_asset");
          $.fancybox.resize();
        }
      });
    });
  };
  $(window).keydown(function(event){
    switch(event.keyCode) {
    case 65: // a
      activeObj = document.activeElement;
      if (activeObj.type == "textarea") break;
      if (activeObj.type == "text") break;
      if ($(activeObj).attr("class") != undefined && $(activeObj).attr("class").indexOf("slot") != -1) break;
      if ($("#fancybox-wrap").is(":visible")) {
        $.fancybox.close();
      } else {
        show_asset_box();
      }
      break;
    }
  });
  $(document).ajaxComplete(function() {
    adjust_links();
  });
  var adjust_links = function() {
    $("#add_asset_sidebar li.asset_type").click(function(event){
      event.preventDefault();
      $.fancybox.showActivity();
      asset_type = $(event.target).data("asset-type");
      $("div.fassets_core.new").load("/assets/new", {type: asset_type, content_only: true });
      $.fancybox.resize();
      $.fancybox.hideActivity();
    });
    $("form.edit_classification input[type=submit][value=Save]").hide();
  };

  adjust_links();
  $("#new_asset_link").click(function(event){
    event.preventDefault();
    show_asset_box();
  });
  var reload_tray = function() {
    var user_id = $("#tray").data("user-id");
    $("#tray").load("/users/"+user_id+"/tray_positions/", function() {
      $('#tray .drop_button').click(function(event){
        event.preventDefault();
        var user_id = $(event.target).data("user-id");
        var tp_id = $(event.target).data("tp-id");
        $.ajax({
          type: 'DELETE',
          cache	: false,
          url		: "/users/"+user_id+"/tray_positions/"+tp_id,
          success: function(data) {
            $("#tray").load("/users/"+user_id+"/tray_positions/");
          }
        });
      });
    });
  };
});
<|endoftext|>


<commit_before>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

/**
 * @class The application running and listening on a specific port.
 *
 * @extends BaseApplication
 *
 * @param {Object} options Options to specify the behaviour
 * @param {Number} options.port The port, which should be used when launching the application server.
 *
 * @since 0.1
 * @author DracoBlue
 */
ServerApplication = function(options) {
    this.setOptions(options);

    /**
     * The Http-Server listening for new connections.
     *
     * @private
     */
    this.server = null;
};

process.mixin(true, ServerApplication.prototype, BaseApplication.prototype);

/**
 * Runs the application.
 */
ServerApplication.prototype.run = function() {
    var http = require("http");

    var finishRequest = function(req, res, body) {
        var context = {
            status: 200,
            headers: {
                'Content-Type': 'text/plain'
            }
        };

        context.params = {};

        if (body !== null) {
            /*
             * Ok, we need to parse that!
             */
             var body_entries = body.split("&");
             var body_entries_length = body_entries.length;
             var i = 0;

             for (i=0; i<body_entries_length; i++) {
                var row = body_entries[i].split("=");
                var key = decodeURIComponent(row[0]);
                var value = decodeURIComponent(row[1] || "");
                context.params[key] = value;
             }
        }

        ContextToolkit.applyRequestHeaders(context, req.headers);

        var response = null;

        try {
            response = BaseApplication.executePath(req.uri.full.substr(1), context);
        } catch (e) {
            context.status = 404;
            var sys = require("sys");
            response = "Page not found!" + sys.inspect(e);
        }

        res.sendHeader(context.status, context.headers);
        res.sendBody(response);

        res.finish();
    };

    this.server = http.createServer(function(req, res) {
        if (req.method === "GET") {
            finishRequest(req, res, null);
            return ;
        }

        var body = [];

        req.addListener('body', function(content) {
            if (content === null) {
                return ;
            }
            body.push(content);
        });

        req.addListener('complete', function(content) {
            finishRequest(req, res, body.join(""));
        });

    });

    this.server.listen(this.options["port"]);
};
<commit_msg>added session_key options. retrieving the session by id (if exists), setting the new session id if the one in context.session_id is different from the previous one.<commit_after>/*
 * This file is part of the Spludo Framework.
 * Copyright (c) 2009 DracoBlue, http://dracoblue.net/
 *
 * Licensed under the terms of MIT License. For the full copyright and license
 * information, please see the LICENSE file in the root folder.
 */

/**
 * @class The application running and listening on a specific port.
 *
 * @extends BaseApplication
 *
 * @param {Object} options Options to specify the behaviour
 * @param {Number} options.port The port, which should be used when launching the application server.
 *
 * @since 0.1
 * @author DracoBlue
 */
ServerApplication = function(options) {
    this.setOptions(options);

    this.options.session_key = this.options.session_key || "s";

    /**
     * The Http-Server listening for new connections.
     *
     * @private
     */
    this.server = null;
};

process.mixin(true, ServerApplication.prototype, BaseApplication.prototype);

/**
 * Runs the application.
 */
ServerApplication.prototype.run = function() {
    var http = require("http");

    var session_key = this.options.session_key;

    var finishRequest = function(req, res, body) {
        var context = {
            status: 200,
            headers: {
                'Content-Type': 'text/plain'
            }
        };

        context.params = {};

        if (body !== null) {
            /*
             * Ok, we need to parse that!
             */
             var body_entries = body.split("&");
             var body_entries_length = body_entries.length;
             var i = 0;

             for (i=0; i<body_entries_length; i++) {
                var row = body_entries[i].split("=");
                var key = decodeURIComponent(row[0]);
                var value = decodeURIComponent(row[1] || "");
                context.params[key] = value;
             }
        }

        ContextToolkit.applyRequestHeaders(context, req.headers);

        var session_id = (context.cookies && context.cookies[session_key]) || null;

        if (session_id) {
            try {
                context.session = session_manager.getSession(session_id);
                context.session_id = session_id;
            } catch (e) {
                /*
                 * Seems like that cookie is invalid by now. Let's remove the cookie.
                 */
                ContextToolkit.removeCookie(context, session_key);
                session_id = null;
            }
        }

        var response = null;

        try {
            response = BaseApplication.executePath(req.uri.full.substr(1), context);
        } catch (e) {
            context.status = 404;
            var sys = require("sys");
            response = "Page not found!" + sys.inspect(e);
        }

        if (session_id !== context.session_id) {
            session_id = context.session_id;

            if (session_id === null) {
                ContextToolkit.removeCookie(context, session_key);
            } else {
                ContextToolkit.setCookie(context, session_key, session_id);
            }
        }

        ContextToolkit.applyCookiesToHeaders(context);

        res.sendHeader(context.status, context.headers);
        res.sendBody(response);

        res.finish();
    };

    this.server = http.createServer(function(req, res) {
        if (req.method === "GET") {
            finishRequest(req, res, null);
            return ;
        }

        var body = [];

        req.addListener('body', function(content) {
            if (content === null) {
                return ;
            }
            body.push(content);
        });

        req.addListener('complete', function(content) {
            finishRequest(req, res, body.join(""));
        });

    });

    this.server.listen(this.options["port"]);
};
<|endoftext|>


<commit_before>const Store = require('electron-store');
const { URL_FOR_CHAIN } = require('./utils');

const DEFAULTS = {
  version: 1,
  geth: URL_FOR_CHAIN.mainnet,
  chain: {
    name: 'mainnet',
    id: 61,
  },
  terms: 'none',
};

class Settings {
  constructor() {
    this.settings = new Store({
      name: 'settings',
      defaults: DEFAULTS,
    });
    // not used anymore
    this.settings.delete('geth');
  }

  /**
     * Get settings as plain JavaScript object
     * @returns {*}
     */
  toJS() {
    return this.settings.store;
  }

  getChain() {
    return this.settings.get('chain');
  }

  setChain(chain) {
    this.settings.set('chain', chain);
    return this;
  }

  setTerms(v) {
    this.settings.set('terms', v);
    return this;
  }
}

module.exports = Settings;
<commit_msg>problem: doesn't give a chance to select chain on first launch<commit_after>const Store = require('electron-store');
const { URL_FOR_CHAIN } = require('./utils');

const DEFAULTS = {
  version: 1,
  terms: 'none',
};

class Settings {
  constructor() {
    this.settings = new Store({
      name: 'settings',
      defaults: DEFAULTS,
    });
    // not used anymore
    this.settings.delete('geth');
  }

  /**
     * Get settings as plain JavaScript object
     * @returns {*}
     */
  toJS() {
    return this.settings.store;
  }

  getChain() {
    return this.settings.get('chain');
  }

  setChain(chain) {
    this.settings.set('chain', chain);
    return this;
  }

  setTerms(v) {
    this.settings.set('terms', v);
    return this;
  }
}

module.exports = Settings;
<|endoftext|>


<commit_before>var tinycolor = require("tinycolor2"),
    helper;

function parseRgb(rgb, type) {
    switch(type) {
        case "object":
            var re,
                tmp = helper.trimRgb(rgb);
            if (rgb.indexOf(",") > -1) {
                tmp = tmp.split(",");
            } else {
                tmp = tmp.split(" ");
            }
            return {
                r: tmp[0],
                g: tmp[1],
                b: tmp[2]
            };
            break;
        case "string":
            return rgb.r + "," + rgb.g + "," + rgb.b;
            break;
    }
};

function parseDecimal(dec) {
    if (dec > 1) {
        return Math.round(dec.toFixed(2));
    } else {
        return Math.round((dec.toFixed(2)) * 100);
    }
};

function objectifyHsl(data) {
    return {
        h: data.hue,
        s: data.saturation,
        l: data.lightness
    };
};

function convertRgb(data) {
    var rgb = parseRgb(data.rgb, "object");
    return {
        "rgb": parseRgb(rgb, "string"),
        "hex": tinycolor(rgb).toHex(),
        "hue": parseDecimal(tinycolor(rgb).toHsl()["h"]),
        "saturation": parseDecimal(tinycolor(rgb).toHsl()["s"]),
        "lightness": parseDecimal(tinycolor(rgb).toHsl()["l"]),
        "theme": tinycolor(rgb).isDark() ? "light" : "dark",
        "bgColour": tinycolor(rgb).toHex()
    };
};

function convertHex(data) {
    return {
        "rgb": parseRgb(tinycolor(data.hex).toRgb(), "string"),
        "hex": data.hex,
        "hue": parseDecimal(tinycolor(data.hex).toHsl()["h"]),
        "saturation": parseDecimal(tinycolor(data.hex).toHsl()["s"]),
        "lightness": parseDecimal(tinycolor(data.hex).toHsl()["l"]),
        "theme": tinycolor(data.hex).isDark() ? "light" : "dark",
        "bgColour": data.hex
    };
}

function convertHsl(data) {
    var hsl = objectifyHsl(data);
    return {
        "rgb": parseRgb(tinycolor(hsl).toRgb(), "string"),
        "hex": tinycolor(hsl).toHex(),
        "hue": data.hue,
        "saturation": data.saturation,
        "lightness": data.lightness,
        "theme": tinycolor(hsl).isDark() ? "light" : "dark",
        "bgColour": tinycolor(hsl).toHex()
    };
};

var helper = {

    validateRgb: function(rgb) {
        return rgb.match(/^(\d+\,\s*\d+\,\s*\d+)$|^(\s*\d{1,3}\s\d{1,3}\s\d{1,3})$/gim) !== null;
    },

    validateHex: function(hex) {
        if (hex.length === 3 || hex.length === 6) {
            return true;
        }
        return false;
    },

    validateColours: function(colour) {
        switch (colour.type) {
            case "rgb":
                return helper.validateRgb(colour.rgb);
                break;
            case "hex":
                return helper.validateHex(colour.hex);
                break;
            default:
                // hsl values will default
                return true;
        }
    },

    trimRgb: function(colour) {
        var tmp = JSON.stringify(colour).replace(/[^\w\s\,\.]|[rgb]/g, "");
        if (tmp.substring(0, 1) === " ") {
            return tmp.substring(1);
        } else {
            return tmp;
        }
    },

    trimHex: function(colour) {
        return JSON.stringify(colour).replace(/[^a-f0-9\s]/g, "");
    },

    convertColours: function(data) {
        switch(data.type) {
            case 'rgb':
                return convertRgb(data);
                break;
            case 'hex':
                return convertHex(data);
                break;
            case 'hue':
            case 'saturation':
            case 'lightness':
                return convertHsl(data);
                break;
        }
    }

};
module.exports = helper;
<commit_msg>:bug: Fixed inability to type caps in hex input<commit_after>var tinycolor = require("tinycolor2"),
    helper;

function parseRgb(rgb, type) {
    switch(type) {
        case "object":
            var re,
                tmp = helper.trimRgb(rgb);
            if (rgb.indexOf(",") > -1) {
                tmp = tmp.split(",");
            } else {
                tmp = tmp.split(" ");
            }
            return {
                r: tmp[0],
                g: tmp[1],
                b: tmp[2]
            };
            break;
        case "string":
            return rgb.r + "," + rgb.g + "," + rgb.b;
            break;
    }
};

function parseDecimal(dec) {
    if (dec > 1) {
        return Math.round(dec.toFixed(2));
    } else {
        return Math.round((dec.toFixed(2)) * 100);
    }
};

function objectifyHsl(data) {
    return {
        h: data.hue,
        s: data.saturation,
        l: data.lightness
    };
};

function convertRgb(data) {
    var rgb = parseRgb(data.rgb, "object");
    return {
        "rgb": parseRgb(rgb, "string"),
        "hex": tinycolor(rgb).toHex(),
        "hue": parseDecimal(tinycolor(rgb).toHsl()["h"]),
        "saturation": parseDecimal(tinycolor(rgb).toHsl()["s"]),
        "lightness": parseDecimal(tinycolor(rgb).toHsl()["l"]),
        "theme": tinycolor(rgb).isDark() ? "light" : "dark",
        "bgColour": tinycolor(rgb).toHex()
    };
};

function convertHex(data) {
    return {
        "rgb": parseRgb(tinycolor(data.hex).toRgb(), "string"),
        "hex": data.hex,
        "hue": parseDecimal(tinycolor(data.hex).toHsl()["h"]),
        "saturation": parseDecimal(tinycolor(data.hex).toHsl()["s"]),
        "lightness": parseDecimal(tinycolor(data.hex).toHsl()["l"]),
        "theme": tinycolor(data.hex).isDark() ? "light" : "dark",
        "bgColour": data.hex
    };
}

function convertHsl(data) {
    var hsl = objectifyHsl(data);
    return {
        "rgb": parseRgb(tinycolor(hsl).toRgb(), "string"),
        "hex": tinycolor(hsl).toHex(),
        "hue": data.hue,
        "saturation": data.saturation,
        "lightness": data.lightness,
        "theme": tinycolor(hsl).isDark() ? "light" : "dark",
        "bgColour": tinycolor(hsl).toHex()
    };
};

var helper = {

    validateRgb: function(rgb) {
        return rgb.match(/^(\d+\,\s*\d+\,\s*\d+)$|^(\s*\d{1,3}\s\d{1,3}\s\d{1,3})$/gim) !== null;
    },

    validateHex: function(hex) {
        if (hex.length === 3 || hex.length === 6) {
            return true;
        }
        return false;
    },

    validateColours: function(colour) {
        switch (colour.type) {
            case "rgb":
                return helper.validateRgb(colour.rgb);
                break;
            case "hex":
                return helper.validateHex(colour.hex);
                break;
            default:
                // hsl values will default
                return true;
        }
    },

    trimRgb: function(colour) {
        var tmp = JSON.stringify(colour).replace(/[^\w\s\,\.]|[rgb]/g, "");
        if (tmp.substring(0, 1) === " ") {
            return tmp.substring(1);
        } else {
            return tmp;
        }
    },

    trimHex: function(colour) {
        return JSON.stringify(colour).replace(/[^a-fA-F0-9\s]/g, "");
    },

    convertColours: function(data) {
        switch(data.type) {
            case 'rgb':
                return convertRgb(data);
                break;
            case 'hex':
                return convertHex(data);
                break;
            case 'hue':
            case 'saturation':
            case 'lightness':
                return convertHsl(data);
                break;
        }
    }

};
module.exports = helper;
<|endoftext|>


<commit_before>/**
 * Import statements are static so its parameters cannot be dynamic.
 * TODO(issue/22): figure out how to use dynamic imports
 */
import {setCookie, setErrorMessage} from '../common-functions.js';

/**
 * Gets job Id of the current job post.
 */
// TODO(issue/53): implement this function
function getJobId() {
  return "xxxxx";
}

const submitButton = document.getElementById('update');
submitButton.addEventListener('click', (_) => {

  const jobId = getJobId();

  if (jobId === '') {
    setErrorMessage(/* errorMessageElementId= */'error-message', /* msg= */ 'Empty Job Id found.',
      /* includesDefault= */false);
    return;
  }

  setCookie("jobId", jobId);

  fetch('../update-job/index.html', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: document.cookie,
  })
      .catch((error) => {
        setErrorMessage(/* errorMessageElementId= */'error-message', /* msg= */ "There is error when transferring jobId",
          /* includesDefault= */false);
        console.log('error', error);
      });
});
<commit_msg>Minor change<commit_after>/**
 * Import statements are static so its parameters cannot be dynamic.
 * TODO(issue/22): figure out how to use dynamic imports
 */
import {setCookie, setErrorMessage} from '../common-functions.js';

/**
 * Gets job Id of the current job post.
 */
// TODO(issue/53): implement this function
function getJobId() {
  return "xxxxx";
}

const submitButton = document.getElementById('update');
submitButton.addEventListener('click', (_) => {

  const jobId = getJobId();

  if (jobId === '') {
    setErrorMessage(/* errorMessageElementId= */'error-message', /* msg= */ 'Empty Job Id found.',
      /* includesDefault= */false);
    return;
  }

  setCookie("jobId", jobId);

  fetch('../update-job/index.html', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    credentials: 'include',
  })
  .then((response) => response.text())
  .then((data) => {
      console.log('data', data);
      /** reset the error (there might have been an error msg from earlier) */
      setErrorMessage(/* errorMessageElementId= */'error-message', /* msg= */ '', /* includesDefault= */false);
      window.location.href= "../update-job/index.html";
  })
  .catch((error) => {
      setErrorMessage(/* errorMessageElementId= */'error-message', /* msg= */ "Error occur when sending jobId",
          /* includesDefault= */false);
      console.log('error', error);
  });
});
<|endoftext|>


<commit_before>import { createStore, createState } from 'test/support/Helpers'
import Model from 'app/model/Model'

describe('Features – Relations – Has Many Through', () => {
  it('can create data contains has many through relationship', () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    const data = {
      id: 1,
      posts: [
        { id: 1 },
        { id: 2 }
      ]
    }

    const expected = createState({
      countries: {
        '1': { $id: 1, id: 1, posts: [] }
      },
      posts: {
        '1': { $id: 1, id: 1, user_id: null },
        '2': { $id: 2, id: 2, user_id: null }
      },
      users: {}
    })

    store.dispatch('entities/countries/create', { data })

    expect(store.state.entities).toEqual(expected)
  })

  it('can resolve has many through relationship', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { id: 1, country_id: 1 },
        { id: 2, country_id: 1 },
        { id: 3, country_id: 2 }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { id: 1, user_id: 1 },
        { id: 2, user_id: 2 },
        { id: 3, user_id: 3 },
        { id: 4, user_id: 1 }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { id: 1 },
        { id: 2 }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(1)

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(3)
    expect(country.posts[0]).toBeInstanceOf(Post)

    // user_id: 1
    expect(country.posts[0].user_id).toBe(1)
    expect(country.posts[1].user_id).toBe(1)
    expect(country.posts[0].id).toBe(1)
    expect(country.posts[1].id).toBe(4)

    // user_id: 2
    expect(country.posts[2].user_id).toBe(2)
    expect(country.posts[2].id).toBe(2)
  })

  it('can resolve has many through relationship with string value id', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.string(''),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.string(''),
          country_id: this.string(''),
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.string(''),
          user_id: this.string(''),
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { id: 'string-id-1', country_id: 'string-id-1' },
        { id: 'string-id-2', country_id: 'string-id-1' },
        { id: 'string-id-3', country_id: 'string-id-2' }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { id: 'string-id-1', user_id: 'string-id-1' },
        { id: 'string-id-2', user_id: 'string-id-2' },
        { id: 'string-id-3', user_id: 'string-id-3' },
        { id: 'string-id-4', user_id: 'string-id-1' }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { id: 'string-id-1' },
        { id: 'string-id-2' }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find('string-id-1')

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(3)
    expect(country.posts[0]).toBeInstanceOf(Post)

    expect(country.posts[0].user_id).toBe('string-id-1')
    expect(country.posts[1].user_id).toBe('string-id-1')
    expect(country.posts[2].user_id).toBe('string-id-2')
    expect(country.posts[0].id).toBe('string-id-1')
    expect(country.posts[1].id).toBe('string-id-4')
    expect(country.posts[2].id).toBe('string-id-2')
  })

  it('can resolve empty has many through relationship', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/countries/create', {
      data: [{ id: 1 }]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(1)

    expect(country.posts.length).toBe(0)
  })

  it('can resolve has many through relationship with custom primary keys', async () => {
    class Country extends Model {
      static entity = 'countries'

      static primaryKey = 'c_id'

      static fields () {
        return {
          c_id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static primaryKey = 'u_id'

      static fields () {
        return {
          u_id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static primaryKey = 'p_id'

      static fields () {
        return {
          p_id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { u_id: 1, country_id: 1 },
        { u_id: 2, country_id: 1 },
        { u_id: 3, country_id: 2 }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { p_id: 1, user_id: 1 },
        { p_id: 2, user_id: 2 },
        { p_id: 3, user_id: 3 }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { c_id: 1 },
        { c_id: 2 }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(1)

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(2)
    expect(country.posts[0]).toBeInstanceOf(Post)
    expect(country.posts[0].p_id).toBe(1)
    expect(country.posts[1].p_id).toBe(2)
  })

  it('can resolve has many through relationship with custom local keys', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          c_id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id', 'c_id', 'u_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          u_id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          p_id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { id: 11, u_id: 1, country_id: 1 },
        { id: 12, u_id: 2, country_id: 1 },
        { id: 13, u_id: 3, country_id: 2 }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { id: 11, p_id: 1, user_id: 1 },
        { id: 12, p_id: 2, user_id: 2 },
        { id: 13, p_id: 3, user_id: 3 }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { id: 11, c_id: 1 },
        { id: 12, c_id: 2 }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(11)

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(2)
    expect(country.posts[0]).toBeInstanceOf(Post)
    expect(country.posts[0].id).toBe(11)
    expect(country.posts[1].id).toBe(12)
  })
})
<commit_msg>Fix linter error<commit_after>import { createStore, createState } from 'test/support/Helpers'
import Model from 'app/model/Model'

describe('Features – Relations – Has Many Through', () => {
  it('can create data contains has many through relationship', () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    const data = {
      id: 1,
      posts: [
        { id: 1 },
        { id: 2 }
      ]
    }

    const expected = createState({
      countries: {
        '1': { $id: 1, id: 1, posts: [] }
      },
      posts: {
        '1': { $id: 1, id: 1, user_id: null },
        '2': { $id: 2, id: 2, user_id: null }
      },
      users: {}
    })

    store.dispatch('entities/countries/create', { data })

    expect(store.state.entities).toEqual(expected)
  })

  it('can resolve has many through relationship', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { id: 1, country_id: 1 },
        { id: 2, country_id: 1 },
        { id: 3, country_id: 2 }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { id: 1, user_id: 1 },
        { id: 2, user_id: 2 },
        { id: 3, user_id: 3 },
        { id: 4, user_id: 1 }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { id: 1 },
        { id: 2 }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(1)

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(3)
    expect(country.posts[0]).toBeInstanceOf(Post)

    // user_id: 1
    expect(country.posts[0].user_id).toBe(1)
    expect(country.posts[1].user_id).toBe(1)
    expect(country.posts[0].id).toBe(1)
    expect(country.posts[1].id).toBe(4)

    // user_id: 2
    expect(country.posts[2].user_id).toBe(2)
    expect(country.posts[2].id).toBe(2)
  })

  it('can resolve has many through relationship with string value id', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.string(''),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.string(''),
          country_id: this.string('')
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.string(''),
          user_id: this.string('')
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { id: 'string-id-1', country_id: 'string-id-1' },
        { id: 'string-id-2', country_id: 'string-id-1' },
        { id: 'string-id-3', country_id: 'string-id-2' }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { id: 'string-id-1', user_id: 'string-id-1' },
        { id: 'string-id-2', user_id: 'string-id-2' },
        { id: 'string-id-3', user_id: 'string-id-3' },
        { id: 'string-id-4', user_id: 'string-id-1' }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { id: 'string-id-1' },
        { id: 'string-id-2' }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find('string-id-1')

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(3)
    expect(country.posts[0]).toBeInstanceOf(Post)

    expect(country.posts[0].user_id).toBe('string-id-1')
    expect(country.posts[1].user_id).toBe('string-id-1')
    expect(country.posts[2].user_id).toBe('string-id-2')
    expect(country.posts[0].id).toBe('string-id-1')
    expect(country.posts[1].id).toBe('string-id-4')
    expect(country.posts[2].id).toBe('string-id-2')
  })

  it('can resolve empty has many through relationship', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/countries/create', {
      data: [{ id: 1 }]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(1)

    expect(country.posts.length).toBe(0)
  })

  it('can resolve has many through relationship with custom primary keys', async () => {
    class Country extends Model {
      static entity = 'countries'

      static primaryKey = 'c_id'

      static fields () {
        return {
          c_id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static primaryKey = 'u_id'

      static fields () {
        return {
          u_id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static primaryKey = 'p_id'

      static fields () {
        return {
          p_id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { u_id: 1, country_id: 1 },
        { u_id: 2, country_id: 1 },
        { u_id: 3, country_id: 2 }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { p_id: 1, user_id: 1 },
        { p_id: 2, user_id: 2 },
        { p_id: 3, user_id: 3 }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { c_id: 1 },
        { c_id: 2 }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(1)

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(2)
    expect(country.posts[0]).toBeInstanceOf(Post)
    expect(country.posts[0].p_id).toBe(1)
    expect(country.posts[1].p_id).toBe(2)
  })

  it('can resolve has many through relationship with custom local keys', async () => {
    class Country extends Model {
      static entity = 'countries'

      static fields () {
        return {
          id: this.attr(null),
          c_id: this.attr(null),
          posts: this.hasManyThrough(Post, User, 'country_id', 'user_id', 'c_id', 'u_id')
        }
      }
    }

    class User extends Model {
      static entity = 'users'

      static fields () {
        return {
          id: this.attr(null),
          u_id: this.attr(null),
          country_id: this.attr(null)
        }
      }
    }

    class Post extends Model {
      static entity = 'posts'

      static fields () {
        return {
          id: this.attr(null),
          p_id: this.attr(null),
          user_id: this.attr(null)
        }
      }
    }

    const store = createStore([{ model: Country }, { model: User }, { model: Post }])

    await store.dispatch('entities/users/create', {
      data: [
        { id: 11, u_id: 1, country_id: 1 },
        { id: 12, u_id: 2, country_id: 1 },
        { id: 13, u_id: 3, country_id: 2 }
      ]
    })

    await store.dispatch('entities/posts/create', {
      data: [
        { id: 11, p_id: 1, user_id: 1 },
        { id: 12, p_id: 2, user_id: 2 },
        { id: 13, p_id: 3, user_id: 3 }
      ]
    })

    await store.dispatch('entities/countries/create', {
      data: [
        { id: 11, c_id: 1 },
        { id: 12, c_id: 2 }
      ]
    })

    const country = store.getters['entities/countries/query']().with('posts').find(11)

    expect(country).toBeInstanceOf(Country)
    expect(country.posts.length).toBe(2)
    expect(country.posts[0]).toBeInstanceOf(Post)
    expect(country.posts[0].id).toBe(11)
    expect(country.posts[1].id).toBe(12)
  })
})
<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _from = require('babel-runtime/core-js/array/from');

var _from2 = _interopRequireDefault(_from);

var _map = require('babel-runtime/core-js/map');

var _map2 = _interopRequireDefault(_map);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _markdownToReactComponents = require('markdown-to-react-components');

var _markdownToReactComponents2 = _interopRequireDefault(_markdownToReactComponents);

var _PropTable = require('./PropTable');

var _PropTable2 = _interopRequireDefault(_PropTable);

var _Node = require('./Node');

var _Node2 = _interopRequireDefault(_Node);

var _theme = require('./theme');

var _markdown = require('./markdown');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var stylesheet = {
  link: {
    base: {
      fontFamily: 'sans-serif',
      fontSize: 12,
      display: 'block',
      position: 'fixed',
      textDecoration: 'none',
      background: '#28c',
      color: '#fff',
      padding: '5px 15px',
      cursor: 'pointer'
    },
    topRight: {
      top: 0,
      right: 0,
      borderRadius: '0 0 0 5px'
    }
  },
  info: {
    position: 'absolute',
    background: 'white',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    padding: '0 40px',
    overflow: 'auto'
  },
  children: {
    position: 'relative',
    zIndex: 0
  },
  infoBody: (0, _extends3.default)({}, _theme.baseFonts, {
    fontWeight: 300,
    lineHeight: 1.45,
    fontSize: 15
  }),
  infoContent: {
    marginBottom: 0
  },
  header: {
    h1: {
      margin: '20px 0 0 0',
      padding: 0,
      fontSize: 35
    },
    h2: {
      margin: '0 0 10px 0',
      padding: 0,
      fontWeight: 400,
      fontSize: 22
    },
    body: {
      borderBottom: '1px solid #eee',
      marginBottom: 10
    }
  },
  source: {
    h1: {
      margin: '20px 0 0 0',
      padding: '0 0 5px 0',
      fontSize: 25,
      borderBottom: '1px solid #EEE'
    }
  },
  propTableHead: {
    margin: '20px 0 0 0'
  }
};

var Story = function (_React$Component) {
  (0, _inherits3.default)(Story, _React$Component);

  function Story() {
    var _Object$getPrototypeO;

    (0, _classCallCheck3.default)(this, Story);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var _this = (0, _possibleConstructorReturn3.default)(this, (_Object$getPrototypeO = (0, _getPrototypeOf2.default)(Story)).call.apply(_Object$getPrototypeO, [this].concat(args)));

    _this.state = { open: false };
    _markdownToReactComponents2.default.configure(_this.props.mtrcConf);
    return _this;
  }

  (0, _createClass3.default)(Story, [{
    key: '_renderStory',
    value: function _renderStory() {
      return _react2.default.createElement(
        'div',
        null,
        this.props.children
      );
    }
  }, {
    key: '_renderInline',
    value: function _renderInline() {
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { style: stylesheet.infoPage },
          _react2.default.createElement(
            'div',
            { style: stylesheet.infoBody },
            this._getInfoHeader()
          )
        ),
        _react2.default.createElement(
          'div',
          null,
          this._renderStory()
        ),
        _react2.default.createElement(
          'div',
          { style: stylesheet.infoPage },
          _react2.default.createElement(
            'div',
            { style: stylesheet.infoBody },
            this._getInfoContent(),
            this._getSourceCode(),
            this._getPropTables()
          )
        )
      );
    }
  }, {
    key: '_renderOverlay',
    value: function _renderOverlay() {
      var _this2 = this;

      var linkStyle = (0, _extends3.default)({}, stylesheet.link.base, stylesheet.link.topRight);

      var infoStyle = (0, _assign2.default)({}, stylesheet.info);
      if (!this.state.open) {
        infoStyle.display = 'none';
      }

      var openOverlay = function openOverlay() {
        _this2.setState({ open: true });
        return false;
      };

      var closeOverlay = function closeOverlay() {
        _this2.setState({ open: false });
        return false;
      };

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { style: stylesheet.children },
          this.props.children
        ),
        _react2.default.createElement(
          'a',
          { style: linkStyle, onClick: openOverlay },
          '?'
        ),
        _react2.default.createElement(
          'div',
          { style: infoStyle },
          _react2.default.createElement(
            'a',
            { style: linkStyle, onClick: closeOverlay },
            '×'
          ),
          _react2.default.createElement(
            'div',
            { style: stylesheet.infoPage },
            _react2.default.createElement(
              'div',
              { style: stylesheet.infoBody },
              this._getInfoHeader(),
              this._getInfoContent(),
              this._getSourceCode(),
              this._getPropTables()
            )
          )
        )
      );
    }
  }, {
    key: '_getInfoHeader',
    value: function _getInfoHeader() {
      if (!this.props.context || !this.props.showHeader) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        { style: stylesheet.header.body },
        _react2.default.createElement(
          'h1',
          { style: stylesheet.header.h1 },
          this.props.context.kind
        ),
        _react2.default.createElement(
          'h2',
          { style: stylesheet.header.h2 },
          this.props.context.story
        )
      );
    }
  }, {
    key: '_getInfoContent',
    value: function _getInfoContent() {
      if (!this.props.info) {
        return '';
      }
      var lines = this.props.info.split('\n');
      while (lines[0].trim() === '') {
        lines.shift();
      }
      var padding = 0;
      var matches = lines[0].match(/^ */);
      if (matches) {
        padding = matches[0].length;
      }
      var source = lines.map(function (s) {
        return s.slice(padding);
      }).join('\n');
      return _react2.default.createElement(
        'div',
        { style: stylesheet.infoContent },
        (0, _markdownToReactComponents2.default)(source).tree
      );
    }
  }, {
    key: '_getSourceCode',
    value: function _getSourceCode() {
      if (!this.props.showSource) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'h1',
          { style: stylesheet.source.h1 },
          'Story Source'
        ),
        _react2.default.createElement(
          _markdown.Pre,
          null,
          _react2.default.Children.map(this.props.children, function (root, idx) {
            return _react2.default.createElement(_Node2.default, { key: idx, depth: 0, node: root });
          })
        )
      );
    }
  }, {
    key: '_getPropTables',
    value: function _getPropTables() {
      var types = new _map2.default();

      if (this.props.propTables === null) {
        return null;
      }

      if (!this.props.children) {
        return null;
      }

      if (this.props.propTables) {
        this.props.propTables.forEach(function (type) {
          types.set(type, true);
        });
      }

      function extract(children) {
        var type = children.type;

        if (Array.isArray(children)) {
          children.forEach(extract);
          return;
        }
        if (typeof children === 'string' || typeof children.type === 'string') {
          return;
        }

        if (!types.has(type)) {
          types.set(type, true);
        }
        if (children.props.children) {
          extract(children.props.children);
        }
      }

      // extract components from children
      extract(this.props.children);

      var array = (0, _from2.default)(types.keys());
      array.sort(function (a, b) {
        return (a.displayName || a.name) > (b.displayName || b.name);
      });

      var propTables = array.map(function (type, idx) {
        return _react2.default.createElement(
          'div',
          { key: idx },
          _react2.default.createElement(
            'h2',
            { style: stylesheet.propTableHead },
            '"',
            type.displayName || type.name,
            '" Component'
          ),
          _react2.default.createElement(_PropTable2.default, { type: type })
        );
      });

      if (!propTables || propTables.length === 0) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'h1',
          { style: stylesheet.source.h1 },
          'Prop Types'
        ),
        propTables
      );

      return;
    }
  }, {
    key: 'render',
    value: function render() {
      if (this.props.showInline) {
        return this._renderInline();
      }

      return this._renderOverlay();
    }
  }]);
  return Story;
}(_react2.default.Component);

exports.default = Story;

Story.displayName = 'Story';
Story.propTypes = {
  context: _react2.default.PropTypes.object,
  info: _react2.default.PropTypes.string,
  propTables: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.func),
  showInline: _react2.default.PropTypes.bool,
  showHeader: _react2.default.PropTypes.bool,
  showSource: _react2.default.PropTypes.bool,
  children: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.object, _react2.default.PropTypes.array]),
  mtrcConf: _react2.default.PropTypes.object
};

Story.defaultProps = {
  showInline: false,
  showHeader: true,
  showSource: true,
  mtrcConf: {}
};<commit_msg>Update dist<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _from = require('babel-runtime/core-js/array/from');

var _from2 = _interopRequireDefault(_from);

var _map = require('babel-runtime/core-js/map');

var _map2 = _interopRequireDefault(_map);

var _assign = require('babel-runtime/core-js/object/assign');

var _assign2 = _interopRequireDefault(_assign);

var _getPrototypeOf = require('babel-runtime/core-js/object/get-prototype-of');

var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf);

var _classCallCheck2 = require('babel-runtime/helpers/classCallCheck');

var _classCallCheck3 = _interopRequireDefault(_classCallCheck2);

var _createClass2 = require('babel-runtime/helpers/createClass');

var _createClass3 = _interopRequireDefault(_createClass2);

var _possibleConstructorReturn2 = require('babel-runtime/helpers/possibleConstructorReturn');

var _possibleConstructorReturn3 = _interopRequireDefault(_possibleConstructorReturn2);

var _inherits2 = require('babel-runtime/helpers/inherits');

var _inherits3 = _interopRequireDefault(_inherits2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _markdownToReactComponents = require('markdown-to-react-components');

var _markdownToReactComponents2 = _interopRequireDefault(_markdownToReactComponents);

var _PropTable = require('./PropTable');

var _PropTable2 = _interopRequireDefault(_PropTable);

var _Node = require('./Node');

var _Node2 = _interopRequireDefault(_Node);

var _theme = require('./theme');

var _markdown = require('./markdown');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var stylesheet = {
  link: {
    base: {
      fontFamily: 'sans-serif',
      fontSize: 12,
      display: 'block',
      position: 'fixed',
      textDecoration: 'none',
      background: '#28c',
      color: '#fff',
      padding: '5px 15px',
      cursor: 'pointer'
    },
    topRight: {
      top: 0,
      right: 0,
      borderRadius: '0 0 0 5px'
    }
  },
  info: {
    position: 'absolute',
    background: 'white',
    top: 0,
    bottom: 0,
    left: 0,
    right: 0,
    padding: '0 40px',
    overflow: 'auto'
  },
  children: {
    position: 'relative',
    zIndex: 0
  },
  infoBody: (0, _extends3.default)({}, _theme.baseFonts, {
    fontWeight: 300,
    lineHeight: 1.45,
    fontSize: 15
  }),
  infoContent: {
    marginBottom: 0
  },
  header: {
    h1: {
      margin: '20px 0 0 0',
      padding: 0,
      fontSize: 35
    },
    h2: {
      margin: '0 0 10px 0',
      padding: 0,
      fontWeight: 400,
      fontSize: 22
    },
    body: {
      borderBottom: '1px solid #eee',
      marginBottom: 10
    }
  },
  source: {
    h1: {
      margin: '20px 0 0 0',
      padding: '0 0 5px 0',
      fontSize: 25,
      borderBottom: '1px solid #EEE'
    }
  },
  propTableHead: {
    margin: '20px 0 0 0'
  }
};

var Story = function (_React$Component) {
  (0, _inherits3.default)(Story, _React$Component);

  function Story() {
    var _Object$getPrototypeO;

    (0, _classCallCheck3.default)(this, Story);

    for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    var _this = (0, _possibleConstructorReturn3.default)(this, (_Object$getPrototypeO = (0, _getPrototypeOf2.default)(Story)).call.apply(_Object$getPrototypeO, [this].concat(args)));

    _this.state = { open: false };
    _markdownToReactComponents2.default.configure(_this.props.mtrcConf);
    return _this;
  }

  (0, _createClass3.default)(Story, [{
    key: '_renderStory',
    value: function _renderStory() {
      return _react2.default.createElement(
        'div',
        null,
        this.props.children
      );
    }
  }, {
    key: '_renderInline',
    value: function _renderInline() {
      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { style: stylesheet.infoPage },
          _react2.default.createElement(
            'div',
            { style: stylesheet.infoBody },
            this._getInfoHeader()
          )
        ),
        _react2.default.createElement(
          'div',
          null,
          this._renderStory()
        ),
        _react2.default.createElement(
          'div',
          { style: stylesheet.infoPage },
          _react2.default.createElement(
            'div',
            { style: stylesheet.infoBody },
            this._getInfoContent(),
            this._getSourceCode(),
            this._getPropTables()
          )
        )
      );
    }
  }, {
    key: '_renderOverlay',
    value: function _renderOverlay() {
      var _this2 = this;

      var linkStyle = (0, _extends3.default)({}, stylesheet.link.base, stylesheet.link.topRight);

      var infoStyle = (0, _assign2.default)({}, stylesheet.info);
      if (!this.state.open) {
        infoStyle.display = 'none';
      }

      var openOverlay = function openOverlay() {
        _this2.setState({ open: true });
        return false;
      };

      var closeOverlay = function closeOverlay() {
        _this2.setState({ open: false });
        return false;
      };

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'div',
          { style: stylesheet.children },
          this.props.children
        ),
        _react2.default.createElement(
          'a',
          { style: linkStyle, onClick: openOverlay },
          '?'
        ),
        _react2.default.createElement(
          'div',
          { style: infoStyle },
          _react2.default.createElement(
            'a',
            { style: linkStyle, onClick: closeOverlay },
            '×'
          ),
          _react2.default.createElement(
            'div',
            { style: stylesheet.infoPage },
            _react2.default.createElement(
              'div',
              { style: stylesheet.infoBody },
              this._getInfoHeader(),
              this._getInfoContent(),
              this._getSourceCode(),
              this._getPropTables()
            )
          )
        )
      );
    }
  }, {
    key: '_getInfoHeader',
    value: function _getInfoHeader() {
      if (!this.props.context || !this.props.showHeader) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        { style: stylesheet.header.body },
        _react2.default.createElement(
          'h1',
          { style: stylesheet.header.h1 },
          this.props.context.kind
        ),
        _react2.default.createElement(
          'h2',
          { style: stylesheet.header.h2 },
          this.props.context.story
        )
      );
    }
  }, {
    key: '_getInfoContent',
    value: function _getInfoContent() {
      if (!this.props.info) {
        return '';
      }
      var lines = this.props.info.split('\n');
      while (lines[0].trim() === '') {
        lines.shift();
      }
      var padding = 0;
      var matches = lines[0].match(/^ */);
      if (matches) {
        padding = matches[0].length;
      }
      var source = lines.map(function (s) {
        return s.slice(padding);
      }).join('\n');
      return _react2.default.createElement(
        'div',
        { style: stylesheet.infoContent },
        (0, _markdownToReactComponents2.default)(source).tree
      );
    }
  }, {
    key: '_getSourceCode',
    value: function _getSourceCode() {
      if (!this.props.showSource) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'h1',
          { style: stylesheet.source.h1 },
          'Story Source'
        ),
        _react2.default.createElement(
          _markdown.Pre,
          null,
          _react2.default.Children.map(this.props.children, function (root, idx) {
            return _react2.default.createElement(_Node2.default, { key: idx, depth: 0, node: root });
          })
        )
      );
    }
  }, {
    key: '_getPropTables',
    value: function _getPropTables() {
      var types = new _map2.default();

      if (this.props.propTables === null) {
        return null;
      }

      if (!this.props.children) {
        return null;
      }

      if (this.props.propTables) {
        this.props.propTables.forEach(function (type) {
          types.set(type, true);
        });
      }

      // depth-first traverse and collect types
      function extract(children) {
        if (!children) {
          return;
        }
        if (Array.isArray(children)) {
          children.forEach(extract);
          return;
        }
        if (children.props && children.props.children) {
          extract(children.props.children);
        }
        if (typeof children === 'string' || typeof children.type === 'string') {
          return;
        }
        if (children.type && !types.has(children.type)) {
          types.set(children.type, true);
        }
      }

      // extract components from children
      extract(this.props.children);

      var array = (0, _from2.default)(types.keys());
      array.sort(function (a, b) {
        return (a.displayName || a.name) > (b.displayName || b.name);
      });

      var propTables = array.map(function (type, idx) {
        return _react2.default.createElement(
          'div',
          { key: idx },
          _react2.default.createElement(
            'h2',
            { style: stylesheet.propTableHead },
            '"',
            type.displayName || type.name,
            '" Component'
          ),
          _react2.default.createElement(_PropTable2.default, { type: type })
        );
      });

      if (!propTables || propTables.length === 0) {
        return null;
      }

      return _react2.default.createElement(
        'div',
        null,
        _react2.default.createElement(
          'h1',
          { style: stylesheet.source.h1 },
          'Prop Types'
        ),
        propTables
      );

      return;
    }
  }, {
    key: 'render',
    value: function render() {
      if (this.props.showInline) {
        return this._renderInline();
      }

      return this._renderOverlay();
    }
  }]);
  return Story;
}(_react2.default.Component);

exports.default = Story;

Story.displayName = 'Story';
Story.propTypes = {
  context: _react2.default.PropTypes.object,
  info: _react2.default.PropTypes.string,
  propTables: _react2.default.PropTypes.arrayOf(_react2.default.PropTypes.func),
  showInline: _react2.default.PropTypes.bool,
  showHeader: _react2.default.PropTypes.bool,
  showSource: _react2.default.PropTypes.bool,
  children: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.object, _react2.default.PropTypes.array]),
  mtrcConf: _react2.default.PropTypes.object
};

Story.defaultProps = {
  showInline: false,
  showHeader: true,
  showSource: true,
  mtrcConf: {}
};<|endoftext|>


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

var path = require("path");
var Server = require("../lib/Server");
var webpack = require("webpack");

var optimist = require("optimist")

	.usage("webpack-dev-server " + require("../package.json").version + "\n" +
			"Usage: https://github.com/webpack/docs/wiki/webpack-detailed-usage")

	.boolean("colors").alias("colors", "c").describe("colors")

	.boolean("info").describe("info").default("info", true)

	.boolean("quiet").describe("quiet")

	.string("content-base").describe("content-base", "A directory or URL to serve HTML content from.")

	.describe("port", "The port").default("port", 8080);

require("webpack/bin/config-optimist")(optimist);

var argv = optimist.argv;

var options = {};

var wpOpt = require("webpack/bin/convert-argv")(optimist, argv, { outputFilename: "/bundle.js" });

options.publicPath = wpOpt.output.publicPath || "";
options.outputPath = wpOpt.output.path = "/";
options.filename = wpOpt.output.filename;
options.hot = wpOpt.hot;

if(options.publicPath[0] !== "/")
	options.publicPath = "/" + options.publicPath;

if(argv["content-base"]) {
	options.contentBase = argv["content-base"];
	if(!/^(https?:)?\/\//.test(options.contentBase))
		options.contentBase = path.resolve(options.contentBase);
} else {
	options.contentBase = process.cwd();
}

if(argv["colors"])
	options.stats = { colors: true };

if(!argv["info"])
	options.noInfo = true;

if(argv["quiet"])
	options.quiet = true;

new Server(webpack(wpOpt), options).listen(argv.port, function(err) {
	if(err) throw err;
	console.log("http://localhost:" + argv.port + "/webpack-dev-server/");
	console.log("webpack result is served from " + options.publicPath);
	console.log("content is served from " + options.contentBase);
});<commit_msg>Local version replaces global one<commit_after>#!/usr/bin/env node

// Local version replaces global one
try {
	var localWebpackDevServer = require.resolve(path.join(process.cwd(), "node_modules", "webpack-dev-server", "bin", "webpack-dev-server.js"));
	if(__filename !== localWebpackDevServer) {
		return require(localWebpackDevServer);
	}
} catch(e) {}

var path = require("path");
var Server = require("../lib/Server");
var webpack = require("webpack");

var optimist = require("optimist")

	.usage("webpack-dev-server " + require("../package.json").version + "\n" +
			"Usage: https://github.com/webpack/docs/wiki/webpack-detailed-usage")

	.boolean("colors").alias("colors", "c").describe("colors")

	.boolean("info").describe("info").default("info", true)

	.boolean("quiet").describe("quiet")

	.string("content-base").describe("content-base", "A directory or URL to serve HTML content from.")

	.describe("port", "The port").default("port", 8080);

require("webpack/bin/config-optimist")(optimist);

var argv = optimist.argv;

var options = {};

var wpOpt = require("webpack/bin/convert-argv")(optimist, argv, { outputFilename: "/bundle.js" });

options.publicPath = wpOpt.output.publicPath || "";
options.outputPath = wpOpt.output.path = "/";
options.filename = wpOpt.output.filename;
options.hot = wpOpt.hot;

if(options.publicPath[0] !== "/")
	options.publicPath = "/" + options.publicPath;

if(argv["content-base"]) {
	options.contentBase = argv["content-base"];
	if(!/^(https?:)?\/\//.test(options.contentBase))
		options.contentBase = path.resolve(options.contentBase);
} else {
	options.contentBase = process.cwd();
}

if(argv["colors"])
	options.stats = { colors: true };

if(!argv["info"])
	options.noInfo = true;

if(argv["quiet"])
	options.quiet = true;

new Server(webpack(wpOpt), options).listen(argv.port, function(err) {
	if(err) throw err;
	console.log("http://localhost:" + argv.port + "/webpack-dev-server/");
	console.log("webpack result is served from " + options.publicPath);
	console.log("content is served from " + options.contentBase);
});<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/bigquery-storage',
    theme: 'lumen',
    default: {
      "outputSourceFiles": false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<commit_msg>chore: update .jsdoc.js by add protos and remove double quotes (#15)<commit_after>// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

'use strict';

module.exports = {
  opts: {
    readme: './README.md',
    package: './package.json',
    template: './node_modules/jsdoc-fresh',
    recurse: true,
    verbose: true,
    destination: './docs/'
  },
  plugins: [
    'plugins/markdown',
    'jsdoc-region-tag'
  ],
  source: {
    excludePattern: '(^|\\/|\\\\)[._]',
    include: [
      'build/src',
      'protos'
    ],
    includePattern: '\\.js$'
  },
  templates: {
    copyright: 'Copyright 2019 Google, LLC.',
    includeDate: false,
    sourceFiles: false,
    systemName: '@google-cloud/bigquery-storage',
    theme: 'lumen',
    default: {
      outputSourceFiles: false
    }
  },
  markdown: {
    idInHeadings: true
  }
};
<|endoftext|>