<commit_before>var _ = require('lodash');
var Q = require("q");
var fs  =  require('fs');
var path = require('path');
var express = require('express');
var Gittle = require('gittle');
var wrench = require('wrench');
var exec = require('child_process').exec;

var Addon = require("./addon");
var manager = require("./manager");
var registry = require("./registry");

// GZIP static middleware
var gzipStatic = require('connect-gzip-static');

function setup(options, imports, register, app) {
    var logger = imports.logger.namespace("addons", false);
    var server = imports.server;
    var events = imports.events;
    var hooks = imports.hooks;

    // Directory with all the defaults addons
    var configDefaultsPath = path.resolve(options.defaultsPath);

    // Directory with all the box addons
    var configAddonsPath = path.resolve(options.path);

    // Directory for temporary storage
    var configTempPath = options.tempPath ? path.resolve(options.tempPath) : null;

    // Options for addons
    var addonsOptions = {
        'blacklist': options.blacklist,
        'logger': logger
    };

    // Build the directory for stroign addons
    if (!fs.existsSync(configAddonsPath)) {
        wrench.mkdirSyncRecursive(configAddonsPath);
    }

    // Check if an addons is a default addons
    var isDefaultAddon = function(addon) {
        if (!_.isString(addon)) addon = addon.infos.name;
        return fs.existsSync(path.join(configDefaultsPath, addon));
    };

    // Loader
    var loadAddonsInfos = function(addonsRoot, _options) {
        return manager.loadAddonsInfos(addonsOptions, addonsRoot || configAddonsPath, _options)
        .then(function(addons) {
            return _.chain(addons)
            .map(function(addon, name) {
                addon.infos.default = isDefaultAddon(addon);
                return [
                    name, addon
                ];
            })
            .object()
            .value()
        });
    };

    // Copy defaults addons
    var copyDefaultsAddons = function() {
        var first = loadAddonsInfos(configDefaultsPath);

        return first.then(manager.runAddonsOperation(function(addon) {
            logger.log("Adding default addon", addon.infos.name);

            // Path to addon
            var addonPath = path.resolve(configAddonsPath, addon.infos.name);

            return Q.nfcall(fs.lstat, addonPath)
            .then(function(stats) {
                if (!stats.isSymbolicLink()) {
                    logger.error("Remove and replace ", addonPath);
                    return wrench.rmdirRecursive(addonPath);
                }

                // Unlink only if exists
                return Q.nfcall(fs.unlink, addonPath);
            }, function(err) {
                if (err.code != 'ENOENT') {
                    return Q.reject(err);
                }
            })
            .then(function() {
                // Blacklist
                if (addon.isBlacklisted()) {
                    logger.error("Default addon", addon.infos.name, "is blacklisted");
                    return Q();
                }

                // Relink it
                //logger.log("link ", addon.root, configAddonsPath)
                return addon.symlink(configAddonsPath);
            });
        }));
    };

    // Install an addon by its git url
    var installAddon = function(git, _options) {
        var addon, tempDir;

        _options = _.defaults({}, _options || {}, {

        });

        var gitRef = "master";
        var gitParts = git.split("#");
        if (gitParts.length == 2) {
            git = gitParts[0];
            gitRef = gitParts[1];
        }

        logger.log("Install add-on", git, "ref="+gitRef);

        tempDir = path.join(configTempPath, "t"+Date.now());

        // Create temporary dir
        return Q.nfcall(fs.mkdir, tempDir).then(function() {
            // Clone git repo
            return Gittle.clone(git, tempDir);
        })
        .then(function(repo) {
            // Checkout the addon ref
            return repo.checkout(gitRef);
        })
        .then(function() {
            // Load addon
            addon = new Addon(tempDir, addonsOptions);
            return addon.load();
        })
        .then(function() {
            // Blacklist
            if (addon.isBlacklisted()) {
                return Q.reject(new Error("Addon "+addon.infos.name+"is blacklisted"));
            }

            // Valid installation of addon with a hook
            return hooks.use("addons", addon.infos);
        })
        .then(function() {
            // Copy to addons dir
            return addon.transfer(configAddonsPath);
        })
        .fin(function(newAddon) {
            addon = newAddon;

            // Remove temporary dir
            return Q.nfcall(wrench.rmdirRecursive, tempDir, false);
        })
        .then(function() {
            // Install node dependencies
            return addon.installDependencies();
        })
        .then(function() {
            // If client side addon then optimize it
            return addon.optimizeClient();
        })
        .then(function() {
            return addon.start(app);
        })
        .then(function() {
            // Emit events
            events.emit('addons.install', addon.infos);

            // Return addon infos
            return Q(addon);
        });
    };

    // Uninstall an addon
    var uninstallAddon = function(name) {
        var addonDir = path.join(configAddonsPath, name);
        logger.log("Uninstall add-on", name);
        if (isDefaultAddon(name)) {
            return Q.reject(new Error("Cannot uninstall a default addon"));
        }
        return Q.nfcall(wrench.rmdirRecursive, addonDir, false).then(function() {
            // Emit events
            events.emit('addons.uninstall', {
                'name': name
            });

            return Q(true);
        });
    };

    // Init addons
    server.app.use('/static/addons', gzipStatic(configAddonsPath));

    // Prepare defaults addons
    return copyDefaultsAddons()
    .then(function() {
        // Load collection of addons
        return loadAddonsInfos(configAddonsPath, {
            unlinkInvalid: true
        });
    })
    .then(manager.runAddonsOperation(function(addon) {
        // Install node dependencies
        return addon.installDependencies();
    }, {
        failOnError: false
    }))
    .then(manager.runAddonsOperation(function(addon) {
        // Build non optimized addons
        return addon.optimizeClient();
    }, {
        failOnError: false
    }))
    .then(manager.runAddonsOperation(function(addon) {
        // Start addons
        return addon.start(app);
    }, {
        failOnError: false
    }))
    .then(function() {
        logger.log("Addons are ready");
        return {
            'addons': {
                'registry': registry.get,
                'list': _.partial(loadAddonsInfos, configAddonsPath),
                'install': installAddon,
                'uninstall': uninstallAddon
            }
        };
    });
};

// Exports
module.exports = setup;
<commit_msg>Remove install of dependencies at codebox startup<commit_after>var _ = require('lodash');
var Q = require("q");
var fs  =  require('fs');
var path = require('path');
var express = require('express');
var Gittle = require('gittle');
var wrench = require('wrench');
var exec = require('child_process').exec;

var Addon = require("./addon");
var manager = require("./manager");
var registry = require("./registry");

// GZIP static middleware
var gzipStatic = require('connect-gzip-static');

function setup(options, imports, register, app) {
    var logger = imports.logger.namespace("addons", false);
    var server = imports.server;
    var events = imports.events;
    var hooks = imports.hooks;

    // Directory with all the defaults addons
    var configDefaultsPath = path.resolve(options.defaultsPath);

    // Directory with all the box addons
    var configAddonsPath = path.resolve(options.path);

    // Directory for temporary storage
    var configTempPath = options.tempPath ? path.resolve(options.tempPath) : null;

    // Options for addons
    var addonsOptions = {
        'blacklist': options.blacklist,
        'logger': logger
    };

    // Build the directory for stroign addons
    if (!fs.existsSync(configAddonsPath)) {
        wrench.mkdirSyncRecursive(configAddonsPath);
    }

    // Check if an addons is a default addons
    var isDefaultAddon = function(addon) {
        if (!_.isString(addon)) addon = addon.infos.name;
        return fs.existsSync(path.join(configDefaultsPath, addon));
    };

    // Loader
    var loadAddonsInfos = function(addonsRoot, _options) {
        return manager.loadAddonsInfos(addonsOptions, addonsRoot || configAddonsPath, _options)
        .then(function(addons) {
            return _.chain(addons)
            .map(function(addon, name) {
                addon.infos.default = isDefaultAddon(addon);
                return [
                    name, addon
                ];
            })
            .object()
            .value()
        });
    };

    // Copy defaults addons
    var copyDefaultsAddons = function() {
        var first = loadAddonsInfos(configDefaultsPath);

        return first.then(manager.runAddonsOperation(function(addon) {
            logger.log("Adding default addon", addon.infos.name);

            // Path to addon
            var addonPath = path.resolve(configAddonsPath, addon.infos.name);

            return Q.nfcall(fs.lstat, addonPath)
            .then(function(stats) {
                if (!stats.isSymbolicLink()) {
                    logger.error("Remove and replace ", addonPath);
                    return wrench.rmdirRecursive(addonPath);
                }

                // Unlink only if exists
                return Q.nfcall(fs.unlink, addonPath);
            }, function(err) {
                if (err.code != 'ENOENT') {
                    return Q.reject(err);
                }
            })
            .then(function() {
                // Blacklist
                if (addon.isBlacklisted()) {
                    logger.error("Default addon", addon.infos.name, "is blacklisted");
                    return Q();
                }

                // Relink it
                //logger.log("link ", addon.root, configAddonsPath)
                return addon.symlink(configAddonsPath);
            });
        }));
    };

    // Install an addon by its git url
    var installAddon = function(git, _options) {
        var addon, tempDir;

        _options = _.defaults({}, _options || {}, {

        });

        var gitRef = "master";
        var gitParts = git.split("#");
        if (gitParts.length == 2) {
            git = gitParts[0];
            gitRef = gitParts[1];
        }

        logger.log("Install add-on", git, "ref="+gitRef);

        tempDir = path.join(configTempPath, "t"+Date.now());

        // Create temporary dir
        return Q.nfcall(fs.mkdir, tempDir).then(function() {
            // Clone git repo
            return Gittle.clone(git, tempDir);
        })
        .then(function(repo) {
            // Checkout the addon ref
            return repo.checkout(gitRef);
        })
        .then(function() {
            // Load addon
            addon = new Addon(tempDir, addonsOptions);
            return addon.load();
        })
        .then(function() {
            // Blacklist
            if (addon.isBlacklisted()) {
                return Q.reject(new Error("Addon "+addon.infos.name+"is blacklisted"));
            }

            // Valid installation of addon with a hook
            return hooks.use("addons", addon.infos);
        })
        .then(function() {
            // Copy to addons dir
            return addon.transfer(configAddonsPath);
        })
        .fin(function(newAddon) {
            addon = newAddon;

            // Remove temporary dir
            return Q.nfcall(wrench.rmdirRecursive, tempDir, false);
        })
        .then(function() {
            // Install node dependencies
            return addon.installDependencies();
        })
        .then(function() {
            // If client side addon then optimize it
            return addon.optimizeClient();
        })
        .then(function() {
            return addon.start(app);
        })
        .then(function() {
            // Emit events
            events.emit('addons.install', addon.infos);

            // Return addon infos
            return Q(addon);
        });
    };

    // Uninstall an addon
    var uninstallAddon = function(name) {
        var addonDir = path.join(configAddonsPath, name);
        logger.log("Uninstall add-on", name);
        if (isDefaultAddon(name)) {
            return Q.reject(new Error("Cannot uninstall a default addon"));
        }
        return Q.nfcall(wrench.rmdirRecursive, addonDir, false).then(function() {
            // Emit events
            events.emit('addons.uninstall', {
                'name': name
            });

            return Q(true);
        });
    };

    // Init addons
    server.app.use('/static/addons', gzipStatic(configAddonsPath));

    // Prepare defaults addons
    return copyDefaultsAddons()
    .then(function() {
        // Load collection of addons
        return loadAddonsInfos(configAddonsPath, {
            unlinkInvalid: true
        });
    })
    .then(manager.runAddonsOperation(function(addon) {
        // Build non optimized addons
        return addon.optimizeClient();
    }, {
        failOnError: false
    }))
    .then(manager.runAddonsOperation(function(addon) {
        // Start addons
        return addon.start(app);
    }, {
        failOnError: false
    }))
    .then(function() {
        logger.log("Addons are ready");
        return {
            'addons': {
                'registry': registry.get,
                'list': _.partial(loadAddonsInfos, configAddonsPath),
                'install': installAddon,
                'uninstall': uninstallAddon
            }
        };
    });
};

// Exports
module.exports = setup;
<|endoftext|>


<commit_before>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const HotModuleReplacementPlugin = require("../HotModuleReplacementPlugin");
const InnerGraph = require("../optimize/InnerGraph");
const ConstDependency = require("./ConstDependency");
const HarmonyAcceptDependency = require("./HarmonyAcceptDependency");
const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency");
const HarmonyExports = require("./HarmonyExports");
const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency");
const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency");

/** @typedef {import("../Dependency")} Dependency */
/** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */
/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */
/** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */

const harmonySpecifierTag = Symbol("harmony import");

/**
 * @typedef {Object} HarmonySettings
 * @property {string[]} ids
 * @property {string} source
 * @property {number} sourceOrder
 * @property {string} name
 * @property {boolean} await
 */

module.exports = class HarmonyImportDependencyParserPlugin {
	constructor(options) {
		const { module: moduleOptions } = options;
		this.strictExportPresence = moduleOptions.strictExportPresence;
		this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports;
		this.importAwait = options.importAwait;
	}

	apply(parser) {
		parser.hooks.import.tap(
			"HarmonyImportDependencyParserPlugin",
			(statement, source) => {
				parser.state.lastHarmonyImportOrder =
					(parser.state.lastHarmonyImportOrder || 0) + 1;
				const clearDep = new ConstDependency("", statement.range);
				clearDep.loc = statement.loc;
				parser.state.module.addPresentationalDependency(clearDep);
				const sideEffectDep = new HarmonyImportSideEffectDependency(
					source,
					parser.state.lastHarmonyImportOrder
				);
				sideEffectDep.loc = statement.loc;
				sideEffectDep.await = statement.await;
				parser.state.module.addDependency(sideEffectDep);
				if (statement.await && !this.importAwait) {
					throw new Error(
						"Used 'import await' but import-await experiment is not enabled (set experiments.importAwait: true to enable it)"
					);
				}
				return true;
			}
		);
		parser.hooks.importSpecifier.tap(
			"HarmonyImportDependencyParserPlugin",
			(statement, source, id, name) => {
				const ids = id === null ? [] : [id];
				parser.tagVariable(name, harmonySpecifierTag, {
					name,
					source,
					ids,
					sourceOrder: parser.state.lastHarmonyImportOrder,
					await: statement.await
				});
				return true;
			}
		);
		parser.hooks.expression
			.for(harmonySpecifierTag)
			.tap("HarmonyImportDependencyParserPlugin", expr => {
				const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
				const dep = new HarmonyImportSpecifierDependency(
					settings.source,
					settings.sourceOrder,
					settings.ids,
					settings.name,
					expr.range,
					this.strictExportPresence
				);
				dep.shorthand = parser.scope.inShorthand;
				dep.directImport = true;
				dep.asiSafe = !parser.isAsiPosition(expr.range[0]);
				dep.await = settings.await;
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
				return true;
			});
		parser.hooks.expressionMemberChain
			.for(harmonySpecifierTag)
			.tap("HarmonyImportDependencyParserPlugin", (expr, members) => {
				const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
				const ids = settings.ids.concat(members);
				const dep = new HarmonyImportSpecifierDependency(
					settings.source,
					settings.sourceOrder,
					ids,
					settings.name,
					expr.range,
					this.strictExportPresence
				);
				dep.await = settings.await;
				dep.asiSafe = !parser.isAsiPosition(expr.range[0]);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
				return true;
			});
		parser.hooks.callMemberChain
			.for(harmonySpecifierTag)
			.tap("HarmonyImportDependencyParserPlugin", (expr, members) => {
				const args = expr.arguments;
				expr = expr.callee;
				const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
				const ids = settings.ids.concat(members);
				const dep = new HarmonyImportSpecifierDependency(
					settings.source,
					settings.sourceOrder,
					ids,
					settings.name,
					expr.range,
					this.strictExportPresence
				);
				dep.directImport = members.length === 0;
				dep.await = settings.await;
				dep.call = true;
				dep.asiSafe = !parser.isAsiPosition(expr.range[0]);
				// only in case when we strictly follow the spec we need a special case here
				dep.namespaceObjectAsContext =
					members.length > 0 && this.strictThisContextOnImports;
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				if (args) parser.walkExpressions(args);
				InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
				return true;
			});
		const {
			hotAcceptCallback,
			hotAcceptWithoutCallback
		} = HotModuleReplacementPlugin.getParserHooks(parser);
		hotAcceptCallback.tap(
			"HarmonyImportDependencyParserPlugin",
			(expr, requests) => {
				if (!HarmonyExports.isEnabled(parser.state)) {
					// This is not a harmony module, skip it
					return;
				}
				const dependencies = requests.map(request => {
					const dep = new HarmonyAcceptImportDependency(request);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
					return dep;
				});
				if (dependencies.length > 0) {
					const dep = new HarmonyAcceptDependency(
						expr.range,
						dependencies,
						true
					);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
				}
			}
		);
		hotAcceptWithoutCallback.tap(
			"HarmonyImportDependencyParserPlugin",
			(expr, requests) => {
				if (!HarmonyExports.isEnabled(parser.state)) {
					// This is not a harmony module, skip it
					return;
				}
				const dependencies = requests.map(request => {
					const dep = new HarmonyAcceptImportDependency(request);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
					return dep;
				});
				if (dependencies.length > 0) {
					const dep = new HarmonyAcceptDependency(
						expr.range,
						dependencies,
						false
					);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
				}
			}
		);
	}
};

module.exports.harmonySpecifierTag = harmonySpecifierTag;
<commit_msg>remove unused type import<commit_after>/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/

"use strict";

const HotModuleReplacementPlugin = require("../HotModuleReplacementPlugin");
const InnerGraph = require("../optimize/InnerGraph");
const ConstDependency = require("./ConstDependency");
const HarmonyAcceptDependency = require("./HarmonyAcceptDependency");
const HarmonyAcceptImportDependency = require("./HarmonyAcceptImportDependency");
const HarmonyExports = require("./HarmonyExports");
const HarmonyImportSideEffectDependency = require("./HarmonyImportSideEffectDependency");
const HarmonyImportSpecifierDependency = require("./HarmonyImportSpecifierDependency");

/** @typedef {import("../optimize/InnerGraph").InnerGraph} InnerGraph */
/** @typedef {import("../optimize/InnerGraph").TopLevelSymbol} TopLevelSymbol */
/** @typedef {import("./HarmonyImportDependency")} HarmonyImportDependency */

const harmonySpecifierTag = Symbol("harmony import");

/**
 * @typedef {Object} HarmonySettings
 * @property {string[]} ids
 * @property {string} source
 * @property {number} sourceOrder
 * @property {string} name
 * @property {boolean} await
 */

module.exports = class HarmonyImportDependencyParserPlugin {
	constructor(options) {
		const { module: moduleOptions } = options;
		this.strictExportPresence = moduleOptions.strictExportPresence;
		this.strictThisContextOnImports = moduleOptions.strictThisContextOnImports;
		this.importAwait = options.importAwait;
	}

	apply(parser) {
		parser.hooks.import.tap(
			"HarmonyImportDependencyParserPlugin",
			(statement, source) => {
				parser.state.lastHarmonyImportOrder =
					(parser.state.lastHarmonyImportOrder || 0) + 1;
				const clearDep = new ConstDependency("", statement.range);
				clearDep.loc = statement.loc;
				parser.state.module.addPresentationalDependency(clearDep);
				const sideEffectDep = new HarmonyImportSideEffectDependency(
					source,
					parser.state.lastHarmonyImportOrder
				);
				sideEffectDep.loc = statement.loc;
				sideEffectDep.await = statement.await;
				parser.state.module.addDependency(sideEffectDep);
				if (statement.await && !this.importAwait) {
					throw new Error(
						"Used 'import await' but import-await experiment is not enabled (set experiments.importAwait: true to enable it)"
					);
				}
				return true;
			}
		);
		parser.hooks.importSpecifier.tap(
			"HarmonyImportDependencyParserPlugin",
			(statement, source, id, name) => {
				const ids = id === null ? [] : [id];
				parser.tagVariable(name, harmonySpecifierTag, {
					name,
					source,
					ids,
					sourceOrder: parser.state.lastHarmonyImportOrder,
					await: statement.await
				});
				return true;
			}
		);
		parser.hooks.expression
			.for(harmonySpecifierTag)
			.tap("HarmonyImportDependencyParserPlugin", expr => {
				const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
				const dep = new HarmonyImportSpecifierDependency(
					settings.source,
					settings.sourceOrder,
					settings.ids,
					settings.name,
					expr.range,
					this.strictExportPresence
				);
				dep.shorthand = parser.scope.inShorthand;
				dep.directImport = true;
				dep.asiSafe = !parser.isAsiPosition(expr.range[0]);
				dep.await = settings.await;
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
				return true;
			});
		parser.hooks.expressionMemberChain
			.for(harmonySpecifierTag)
			.tap("HarmonyImportDependencyParserPlugin", (expr, members) => {
				const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
				const ids = settings.ids.concat(members);
				const dep = new HarmonyImportSpecifierDependency(
					settings.source,
					settings.sourceOrder,
					ids,
					settings.name,
					expr.range,
					this.strictExportPresence
				);
				dep.await = settings.await;
				dep.asiSafe = !parser.isAsiPosition(expr.range[0]);
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
				return true;
			});
		parser.hooks.callMemberChain
			.for(harmonySpecifierTag)
			.tap("HarmonyImportDependencyParserPlugin", (expr, members) => {
				const args = expr.arguments;
				expr = expr.callee;
				const settings = /** @type {HarmonySettings} */ (parser.currentTagData);
				const ids = settings.ids.concat(members);
				const dep = new HarmonyImportSpecifierDependency(
					settings.source,
					settings.sourceOrder,
					ids,
					settings.name,
					expr.range,
					this.strictExportPresence
				);
				dep.directImport = members.length === 0;
				dep.await = settings.await;
				dep.call = true;
				dep.asiSafe = !parser.isAsiPosition(expr.range[0]);
				// only in case when we strictly follow the spec we need a special case here
				dep.namespaceObjectAsContext =
					members.length > 0 && this.strictThisContextOnImports;
				dep.loc = expr.loc;
				parser.state.module.addDependency(dep);
				if (args) parser.walkExpressions(args);
				InnerGraph.onUsage(parser.state, e => (dep.usedByExports = e));
				return true;
			});
		const {
			hotAcceptCallback,
			hotAcceptWithoutCallback
		} = HotModuleReplacementPlugin.getParserHooks(parser);
		hotAcceptCallback.tap(
			"HarmonyImportDependencyParserPlugin",
			(expr, requests) => {
				if (!HarmonyExports.isEnabled(parser.state)) {
					// This is not a harmony module, skip it
					return;
				}
				const dependencies = requests.map(request => {
					const dep = new HarmonyAcceptImportDependency(request);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
					return dep;
				});
				if (dependencies.length > 0) {
					const dep = new HarmonyAcceptDependency(
						expr.range,
						dependencies,
						true
					);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
				}
			}
		);
		hotAcceptWithoutCallback.tap(
			"HarmonyImportDependencyParserPlugin",
			(expr, requests) => {
				if (!HarmonyExports.isEnabled(parser.state)) {
					// This is not a harmony module, skip it
					return;
				}
				const dependencies = requests.map(request => {
					const dep = new HarmonyAcceptImportDependency(request);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
					return dep;
				});
				if (dependencies.length > 0) {
					const dep = new HarmonyAcceptDependency(
						expr.range,
						dependencies,
						false
					);
					dep.loc = expr.loc;
					parser.state.module.addDependency(dep);
				}
			}
		);
	}
};

module.exports.harmonySpecifierTag = harmonySpecifierTag;
<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const config = {
    context: path.resolve(__dirname, '..'),
    devtool: 'source-map',
    devServer: {
        proxy: {
            'api': 'http://localhost:8080/'
        }
    },
    entry: './src/app/app.module.ts',
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../build/webapp')
    },
    resolve: {
        extensions: ['.ts', '.js', '.json']
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            inject: 'body',
            hash: true
        })
    ],
    module: {
        rules: [
            {
                enforce: 'pre',
                test: /\.ts$/,
                exclude: /node_modules/,
                loader: 'tslint-loader',
                options: {
                    emitErrors: true,
                    failOnHint: true
                }
            },
            {
                test: /\.html$/,
                exclude: /node_modules/,
                loader: 'html-loader'
            },
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                use: 'ts-loader'
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file?name=fonts/[name].[ext]'
            }
        ]
    }
};

module.exports = config;<commit_msg>Fixed AngularJS integration and routing, other minor fixes<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

const rootPath = path.resolve(__dirname, '..');
const sourcePath = path.join(rootPath, 'src');
const destPath = path.join(rootPath, 'build/webapp');

const config = {
    context: sourcePath,
    devtool: 'source-map',
    devServer: {
        contentBase: [destPath],
        proxy: {
            'api': 'http://localhost:8080/'
        }
    },
    entry: './app/app.module.ts',
    output: {
        filename: 'bundle.js',
        path: destPath
    },
    resolve: {
        extensions: ['.ts', '.js', '.json']
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            inject: 'body',
            hash: true
        })
    ],
    module: {
        rules: [
            {
                enforce: 'pre',
                test: /\.ts$/,
                exclude: /node_modules/,
                loader: 'tslint-loader',
                options: {
                    emitErrors: true,
                    failOnHint: true
                }
            },
            {
                test: /\.html$/,
                exclude: /node_modules/,
                loader: 'html-loader'
            },
            {
                test: /\.ts$/,
                exclude: /node_modules/,
                use: 'ts-loader'
            },
            {
                test: /\.(eot|svg|ttf|woff|woff2)$/,
                loader: 'file?name=fonts/[name].[ext]'
            }
        ]
    }
};

module.exports = config;<|endoftext|>


<commit_before>apos.define('apostrophe-array-editor-modal', {
  extend: 'apostrophe-modal',
  source: 'arrayEditor',
  transition: 'slide',
  chooser: true,
  construct: function(self, options) {
    self.load = function(){
      self.$arrayItems  = self.$el.find('[data-apos-array-items]');
      self.$arrayItem   = self.$el.find('[data-apos-array-item]');
      self.field        = options.field;
      self.arrayItems   = options.arrayItems || [];
      self.active       = 0;

      if (!self.arrayItems.length){
        return self.createItem();
      } else {
        self.setItemTitles();
        return self.editItem();
      }
    };

    self.generateTitle = function(item, index) {
      return item[self.field.titleField] || ('#' + (index + 1));
    }

    self.afterShow = function(){
      self.load();
    };

    self.addToItems = function() {
      self.arrayItems.push({ _title: "New Item", id: apos.utils.generateId() });
      self.active = self.arrayItems.length - 1;
      self.refreshItems();
    };

    self.setItemTitles = function() {
      self.arrayItems = _.map(self.arrayItems, function(item, i){
        item._title = self.generateTitle(item, i);
        return item;
      });
    };

    // Array Items-Related methods
    self.refreshItems = function(){
      return self.html('arrayItems', { arrayItems: self.arrayItems, field: self.field, active: self.active }, function(html) {
        self.$arrayItems.html($(html));
        self.bindClickHandlers();
      });
    };

    // Ask the server to create an empty form
    // populated by schema fields. Form is 'arrayItem.html'
    // Should also re-render the chooser.
    self.createItem = function(){
      return self.html('arrayItem', { field: self.field }, function(html) {
        self.$arrayItem.html($(html));
        self.addToItems();
        self.populateItem();
      });
    }

    // Like create, we're asking the server for a
    // empty form, populated by an existing item passed
    // into schema fields.
    self.editItem = function(){
      return self.html('arrayItem', { field: self.field }, function(html) {
        self.$arrayItem.html($(html));
        self.populateItem();
      });
    }

    self.populateItem = function(){
      apos.schemas.populate(self.$arrayItem.find('[data-apos-form]'), self.field.schema, self.arrayItems[self.active], function(err){
        if (err) {
          console.error(err)
        }
        self.refreshItems();
      });
    }

    self.saveItemState = function(callback){
      apos.schemas.convert(self.$arrayItem.find('[data-apos-form]'), self.field.schema, self.arrayItems[self.active], function(err){
        if (err) {
          console.error(err);
        }
        self.arrayItems[self.active]._title = self.generateTitle(self.arrayItems[self.active], self.active);
        return callback();
      })
    }

    self.saveArray = function(){
      options.save(self.arrayItems);
      self.hide();
    }

    // Click handlers
    self.bindClickHandlers = function(){

      self.$el.off('click', '[data-apos-add-array-item]').one('click', '[data-apos-add-array-item]', function(e){
        e.stopPropagation();
        e.preventDefault();
        self.saveItemState(function(){
          self.createItem();
        });
      });

      self.$el.one('click', '[data-apos-array-items-trigger]', function(e){
        e.stopPropagation();
        e.preventDefault();
        var $self = $(this);

        self.saveItemState(function(){
          self.active = $self.data('apos-array-items-trigger');
          self.editItem();
        });
      });

      self.$el.off('click', '[data-apos-move-array-item]').one('click', '[data-apos-move-array-item]', function(e) {
        e.stopPropagation();
        e.preventDefault();

        var $el = $(this);
        var id = $el.parent().data('id');
        var direction = $el.data('apos-move-array-item');
        var item = _.find(self.arrayItems, {id: id});
        var index = _.findIndex(self.arrayItems, {id: id});
        var newIndex;

        if (direction === 'up') {
          console.log('Move array item up');
          if (index <= 0) {
            return;
          }
          newIndex = index - 1;
        } else if (direction === 'down') {
          console.log('Move array item down');
          if (index >= self.arrayItems.length - 1) {
            return;
          }
          newIndex = index + 1;
        }
        var temp = self.arrayItems[index];
        self.arrayItems[index] = self.arrayItems[newIndex];
        self.arrayItems[newIndex] = temp;
        self.active = newIndex;
        self.editItem();
        self.refresh();
      });

      self.$el.one('click', '[data-apos-delete-array-item]', function(e) {
        e.stopPropagation();
        e.preventDefault();

        var $self = $(this);
        var id = $self.parent().data('id');

        if (id) {
          self.remove(id);
        }
        // If we just removed the active array item, switch to the one
        // before this one.
        if (self.active === parseInt($self.parent().data('apos-array-items-trigger'))) {
          self.active = Math.max(parseInt(self.active) - 1, 0);
          self.editItem();
        }
      });

      self.$el.parents('[data-modal]').find('[data-apos-save-array-items]').on('click', function(e){
        var $self = $(this);
        self.saveItemState(function(){
          self.saveArray();
        });
      });
    }

    self.remove = function(_id) {
      self.arrayItems = _.filter(self.arrayItems, function(choice) {
        return choice.id !== _id;
      });
      return self.refresh();
    };

    self.refreshing = 0;
    self.last = [];

    self.refresh = function(callback) {
      console.log('refresh');
      if (self.refreshing) {
        self.refreshing++;
        return;
      }
      self.refreshing++;
      self.$arrayItems.html('');
      console.log('arrayItems', self.arrayItems);
      return self.html('arrayItems', { arrayItems: self.arrayItems, field: self.field }, function(html) {
        self.$arrayItems.html(html);
        self.decrementRefreshing();
        var compare = JSON.stringify(self.arrayItems);
        if (self.last !== compare) {
          self.last = compare;
          //self.onChange();
        }
        if (callback){
          return callback();
        }
      }, function(err) {
        self.decrementRefreshing();
        if (callback){
          return callback();
        }
      });

    };

    self.decrementRefreshing = function() {
      self.refreshing--;
      // If one or more additional refreshes have been requested, carrying out
      // one more is sufficient
      if (self.refreshing > 0) {
        self.refreshing = 0;
        self.refresh();
      }
    };
  }
});
<commit_msg>Remove some extraneous logging.<commit_after>apos.define('apostrophe-array-editor-modal', {
  extend: 'apostrophe-modal',
  source: 'arrayEditor',
  transition: 'slide',
  chooser: true,
  construct: function(self, options) {
    self.load = function(){
      self.$arrayItems  = self.$el.find('[data-apos-array-items]');
      self.$arrayItem   = self.$el.find('[data-apos-array-item]');
      self.field        = options.field;
      self.arrayItems   = options.arrayItems || [];
      self.active       = 0;

      if (!self.arrayItems.length){
        return self.createItem();
      } else {
        self.setItemTitles();
        return self.editItem();
      }
    };

    self.generateTitle = function(item, index) {
      return item[self.field.titleField] || ('#' + (index + 1));
    }

    self.afterShow = function(){
      self.load();
    };

    self.addToItems = function() {
      self.arrayItems.push({ _title: "New Item", id: apos.utils.generateId() });
      self.active = self.arrayItems.length - 1;
      self.refreshItems();
    };

    self.setItemTitles = function() {
      self.arrayItems = _.map(self.arrayItems, function(item, i){
        item._title = self.generateTitle(item, i);
        return item;
      });
    };

    // Array Items-Related methods
    self.refreshItems = function(){
      return self.html('arrayItems', { arrayItems: self.arrayItems, field: self.field, active: self.active }, function(html) {
        self.$arrayItems.html($(html));
        self.bindClickHandlers();
      });
    };

    // Ask the server to create an empty form
    // populated by schema fields. Form is 'arrayItem.html'
    // Should also re-render the chooser.
    self.createItem = function(){
      return self.html('arrayItem', { field: self.field }, function(html) {
        self.$arrayItem.html($(html));
        self.addToItems();
        self.populateItem();
      });
    }

    // Like create, we're asking the server for a
    // empty form, populated by an existing item passed
    // into schema fields.
    self.editItem = function(){
      return self.html('arrayItem', { field: self.field }, function(html) {
        self.$arrayItem.html($(html));
        self.populateItem();
      });
    }

    self.populateItem = function(){
      apos.schemas.populate(self.$arrayItem.find('[data-apos-form]'), self.field.schema, self.arrayItems[self.active], function(err){
        if (err) {
          console.error(err)
        }
        self.refreshItems();
      });
    }

    self.saveItemState = function(callback){
      apos.schemas.convert(self.$arrayItem.find('[data-apos-form]'), self.field.schema, self.arrayItems[self.active], function(err){
        if (err) {
          console.error(err);
        }
        self.arrayItems[self.active]._title = self.generateTitle(self.arrayItems[self.active], self.active);
        return callback();
      })
    }

    self.saveArray = function(){
      options.save(self.arrayItems);
      self.hide();
    }

    // Click handlers
    self.bindClickHandlers = function(){

      self.$el.off('click', '[data-apos-add-array-item]').one('click', '[data-apos-add-array-item]', function(e){
        e.stopPropagation();
        e.preventDefault();
        self.saveItemState(function(){
          self.createItem();
        });
      });

      self.$el.one('click', '[data-apos-array-items-trigger]', function(e){
        e.stopPropagation();
        e.preventDefault();
        var $self = $(this);

        self.saveItemState(function(){
          self.active = $self.data('apos-array-items-trigger');
          self.editItem();
        });
      });

      self.$el.off('click', '[data-apos-move-array-item]').one('click', '[data-apos-move-array-item]', function(e) {
        e.stopPropagation();
        e.preventDefault();

        var $el = $(this);
        var id = $el.parent().data('id');
        var direction = $el.data('apos-move-array-item');
        var item = _.find(self.arrayItems, {id: id});
        var index = _.findIndex(self.arrayItems, {id: id});
        var newIndex;

        if (direction === 'up') {
          if (index <= 0) {
            return;
          }
          newIndex = index - 1;
        } else if (direction === 'down') {
          if (index >= self.arrayItems.length - 1) {
            return;
          }
          newIndex = index + 1;
        }
        var temp = self.arrayItems[index];
        self.arrayItems[index] = self.arrayItems[newIndex];
        self.arrayItems[newIndex] = temp;
        self.active = newIndex;
        self.editItem();
        self.refresh();
      });

      self.$el.one('click', '[data-apos-delete-array-item]', function(e) {
        e.stopPropagation();
        e.preventDefault();

        var $self = $(this);
        var id = $self.parent().data('id');

        if (id) {
          self.remove(id);
        }
        // If we just removed the active array item, switch to the one
        // before this one.
        if (self.active === parseInt($self.parent().data('apos-array-items-trigger'))) {
          self.active = Math.max(parseInt(self.active) - 1, 0);
          self.editItem();
        }
      });

      self.$el.parents('[data-modal]').find('[data-apos-save-array-items]').on('click', function(e){
        var $self = $(this);
        self.saveItemState(function(){
          self.saveArray();
        });
      });
    }

    self.remove = function(_id) {
      self.arrayItems = _.filter(self.arrayItems, function(choice) {
        return choice.id !== _id;
      });
      return self.refresh();
    };

    self.refreshing = 0;
    self.last = [];

    self.refresh = function(callback) {
      if (self.refreshing) {
        self.refreshing++;
        return;
      }
      self.refreshing++;
      self.$arrayItems.html('');
      return self.html('arrayItems', { arrayItems: self.arrayItems, field: self.field }, function(html) {
        self.$arrayItems.html(html);
        self.decrementRefreshing();
        var compare = JSON.stringify(self.arrayItems);
        if (self.last !== compare) {
          self.last = compare;
          //self.onChange();
        }
        if (callback){
          return callback();
        }
      }, function(err) {
        self.decrementRefreshing();
        if (callback){
          return callback();
        }
      });

    };

    self.decrementRefreshing = function() {
      self.refreshing--;
      // If one or more additional refreshes have been requested, carrying out
      // one more is sufficient
      if (self.refreshing > 0) {
        self.refreshing = 0;
        self.refresh();
      }
    };
  }
});
<|endoftext|>


<commit_before>'use strict';

/**
* Allocate a buffer using an octet array.
*
* @module @stdlib/buffer/from-array
*
* @example
* var array2buffer = require( '@stdlib/type/buffer/from-array' );
*
* var buf = array2buffer( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*/

// MODULES //

var hasFrom = require( './has_from.js' );

// MAIN //

var array2buffer;
if ( hasFrom ) {
	array2buffer = require( './main.js' );
} else {
	array2buffer = require( './polyfill.js' );
}

// EXPORTS //

module.exports = array2buffer;
<commit_msg>Refactor to avoid dynamic module resolution<commit_after>'use strict';

/**
* Allocate a buffer using an octet array.
*
* @module @stdlib/buffer/from-array
*
* @example
* var array2buffer = require( '@stdlib/type/buffer/from-array' );
*
* var buf = array2buffer( [ 1, 2, 3, 4 ] );
* // returns <Buffer>
*/

// MODULES //

var hasFrom = require( './has_from.js' );
var main = require( './main.js' );
var polyfill = require( './polyfill.js' );

// MAIN //

var array2buffer;
if ( hasFrom ) {
	array2buffer = main;
} else {
	array2buffer = polyfill;
}

// EXPORTS //

module.exports = array2buffer;
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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
*
*    http://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';

// MODULES //

var tape = require( 'tape' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var gamma = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof gamma, 'function', 'main export is a function' );
	t.end();
});

tape( 'attached to the main export is a method to generate pseudorandom number generators', function test( t ) {
	t.equal( typeof gamma.factory, 'function', 'has `factory` method' );
	t.end();
});

tape( 'attached to the main export is the generator name', function test( t ) {
	t.equal( gamma.NAME, 'gamma', 'has `NAME` property' );
	t.end();
});

tape( 'attached to the main export is the underlying PRNG', function test( t ) {
	t.equal( typeof gamma.PRNG, 'function', 'has `PRNG` property' );
	t.end();
});

tape( 'attached to the main export is the generator seed', function test( t ) {
	t.equal( isUint32Array( gamma.seed ), true, 'has `seed` property' );
	t.end();
});

tape( 'attached to the main export is the generator state', function test( t ) {
	t.equal( isUint32Array( gamma.state ), true, 'has `state` property' );
	t.end();
});

tape( 'attached to the main export is the generator state length', function test( t ) {
	t.equal( typeof gamma.stateLength, 'number', 'has `stateLength` property' );
	t.end();
});

tape( 'attached to the main export is the generator state size', function test( t ) {
	t.equal( typeof gamma.byteLength, 'number', 'has `byteLength` property' );
	t.end();
});

tape( 'the function returns pseudorandom numbers (when `alpha >= 1`)', function test( t ) {
	var r;
	var i;
	for ( i = 0; i < 1e2; i++ ) {
		r = gamma( 2.0, 1.0 );
		t.strictEqual( typeof r, 'number', 'returns a number' );
		t.strictEqual( r > 0.0, true, 'returns a positive number' );
	}
	t.end();
});

tape( 'the function returns pseudorandom numbers (when `alpha < 1`)', function test( t ) {
	var r;
	var i;
	for ( i = 0; i < 1e2; i++ ) {
		r = gamma( 0.05, 1.0 );
		t.strictEqual( typeof r, 'number', 'returns a number' );
		t.strictEqual( r > 0.0, true, 'returns a positive number' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha >= 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		gamma( 2.0, 2.0 );
	}
	// Capture the current state:
	state = gamma.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( gamma( 2.0, 2.0 ) );
	}
	// Set the state:
	gamma.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( gamma( 2.0, 2.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha < 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		gamma( 0.05, 2.0 );
	}
	// Capture the current state:
	state = gamma.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( gamma( 0.05, 2.0 ) );
	}
	// Set the state:
	gamma.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( gamma( 0.05, 2.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});
<commit_msg>Update tests<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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
*
*    http://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';

// MODULES //

var tape = require( 'tape' );
var isUint32Array = require( '@stdlib/assert/is-uint32array' );
var gamma = require( './../lib' );

// TESTS //

tape( 'main export is a function', function test( t ) {
	t.ok( true, __filename );
	t.equal( typeof gamma, 'function', 'main export is a function' );
	t.end();
});

tape( 'attached to the main export is a method to generate pseudorandom number generators', function test( t ) {
	t.equal( typeof gamma.factory, 'function', 'has method' );
	t.end();
});

tape( 'attached to the main export is the generator name', function test( t ) {
	t.equal( gamma.NAME, 'gamma', 'has property' );
	t.end();
});

tape( 'attached to the main export is the underlying PRNG', function test( t ) {
	t.equal( typeof gamma.PRNG, 'function', 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator seed', function test( t ) {
	t.equal( isUint32Array( gamma.seed ), true, 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator seed length', function test( t ) {
	t.equal( typeof gamma.seedLength, 'number', 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator state', function test( t ) {
	t.equal( isUint32Array( gamma.state ), true, 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator state length', function test( t ) {
	t.equal( typeof gamma.stateLength, 'number', 'has property' );
	t.end();
});

tape( 'attached to the main export is the generator state size', function test( t ) {
	t.equal( typeof gamma.byteLength, 'number', 'has property' );
	t.end();
});

tape( 'the function returns pseudorandom numbers (when `alpha >= 1`)', function test( t ) {
	var r;
	var i;
	for ( i = 0; i < 1e2; i++ ) {
		r = gamma( 2.0, 1.0 );
		t.strictEqual( typeof r, 'number', 'returns a number' );
		t.strictEqual( r > 0.0, true, 'returns a positive number' );
	}
	t.end();
});

tape( 'the function returns pseudorandom numbers (when `alpha < 1`)', function test( t ) {
	var r;
	var i;
	for ( i = 0; i < 1e2; i++ ) {
		r = gamma( 0.05, 1.0 );
		t.strictEqual( typeof r, 'number', 'returns a number' );
		t.strictEqual( r > 0.0, true, 'returns a positive number' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha >= 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		gamma( 2.0, 2.0 );
	}
	// Capture the current state:
	state = gamma.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( gamma( 2.0, 2.0 ) );
	}
	// Set the state:
	gamma.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( gamma( 2.0, 2.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});

tape( 'the function supports setting the generator state (alpha < 1.0)', function test( t ) {
	var state;
	var arr;
	var i;

	// Move to a future state...
	for ( i = 0; i < 100; i++ ) {
		gamma( 0.05, 2.0 );
	}
	// Capture the current state:
	state = gamma.state;

	// Move to a future state...
	arr = [];
	for ( i = 0; i < 100; i++ ) {
		arr.push( gamma( 0.05, 2.0 ) );
	}
	// Set the state:
	gamma.state = state;

	// Replay previously generated values...
	for ( i = 0; i < 100; i++ ) {
		t.equal( gamma( 0.05, 2.0 ), arr[ i ], 'returns expected value. i: '+i+'.' );
	}
	t.end();
});
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' );
var isTypedArrayLike = require( '@stdlib/assert/is-typed-array-like' );
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isIntegerArray = require( '@stdlib/assert/is-integer-array' ).primitives;
var isOrder = require( '@stdlib/types/ndarray/base/assert/is-order' );
var bytesPerElement = require( '@stdlib/types/ndarray/base/bytes-per-element' );
var baseCtor = require( '@stdlib/types/ndarray/base/ctor' );
var inherit = require( '@stdlib/utils/inherit' );
var defaults = require( './defaults.json' );
var igetValue = require( './iget.js' );
var isetValue = require( './iset.js' );
var getValue = require( './get.js' );
var setValue = require( './set.js' );
var validate = require( './validate.js' );

// MAIN //

/**
* Returns an ndarray constructor.
*
* @param {string} dtype - data type
* @param {PositiveInteger} ndims - number of dimensions
* @param {Options} [options] - function options
* @param {boolean} [options.codegen=true] - boolean indicating whether to use code generation
* @param {string} [options.mode="throw"] - specifies how to handle indices which exceed array dimensions
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} ndarray constructor
*
* @example
* var ndarray = ctor( 'float64', 3 );
* // returns <Function>
*
* var buffer = [ 1, 2, 3, 4, 5, 6 ];
* var shape = [ 3, 2 ];
* var strides = [ 2, 1 ];
* var offset = 0;
*
* var out = ndarray( buffer, shape, strides, offset, 'row-major' );
*/
function ctor( dtype, ndims, options ) {
	/* eslint-disable no-restricted-syntax */
	var parent;
	var opts;
	var err;

	opts = {};
	opts.codegen = defaults.codegen;
	opts.mode = defaults.mode;
	if ( arguments.length > 2 ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// Create a lower-level base constructor:
	parent = baseCtor( dtype, ndims, opts );

	/**
	* ndarray constructor.
	*
	* @private
	* @constructor
	* @param {(ArrayLikeObject|TypedArray|Buffer)} buffer - data buffer
	* @param {NonNegativeIntegerArray} shape - array shape
	* @param {IntegerArray} strides - array strides
	* @param {NonNegativeInteger} offset - index offset
	* @param {string} order - specifies whether an array is row-major (C-style) or column-major (Fortran-style)
	* @returns {ndarray} ndarray instance
	*/
	function ndarray( buffer, shape, strides, offset, order ) {
		/* eslint-disable no-invalid-this */
		if ( !(this instanceof ndarray) ) {
			return new ndarray( buffer, shape, strides, offset, order ); // eslint-disable-line no-new-cap
		}
		if (
			!isArrayLikeObject( buffer ) &&
			!isTypedArrayLike( buffer ) &&
			!isBuffer( buffer )
		) {
			throw new TypeError( 'invalid input argument. `buffer` argument must be an array-like object, typed-array-like, or a Buffer. Value: `' + buffer + '`.' );
		}
		if ( !isNonNegativeIntegerArray( shape ) ) {
			throw new TypeError( 'invalid input argument. `shape` argument must be an array-like object containing nonnegative integers. Value: `' + shape + '`.' );
		}
		if ( !isIntegerArray( strides ) ) {
			throw new TypeError( 'invalid input argument. `strides` argument must be an array-like object containing integers. Value: `' + strides + '`.' );
		}
		if ( !isNonNegativeInteger( offset ) ) {
			throw new TypeError( 'invalid input argument. `offset` argument must be a nonnegative integer. Value: `' + offset + '`.' );
		}
		if ( !isOrder( order ) ) {
			throw new TypeError( 'invalid input argument. `order` argument must be a supported order. Value: `' + order + '`.' );
		}
		// Call the parent constructor:
		parent.call( this, buffer, shape, strides, offset, order );

		// Cache references to the parent constructor and parent constructor methods:
		setReadOnly( this, '_parent', parent );

		// Set private properties...
		this._mode = opts.mode;

		return this;
	} // end FUNCTION ndarray()

	/**
	* Size (in bytes) of each array element (if known).
	*
	* @private
	* @memberof ndarray
	* @name BYTES_PER_ELEMENT
	* @type {(PositiveInteger|null)}
	*
	* @example
	* var nbytes = ndarray.BYTES_PER_ELEMENT;
	* // returns <number>
	*/
	Object.defineProperty( ndarray, 'BYTES_PER_ELEMENT', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': bytesPerElement( dtype )
	});

	/**
	* Underlying data type.
	*
	* @private
	* @memberof ndarray
	* @name dtype
	* @type {string}
	*
	* @example
	* var dtype = ndarray.dtype;
	* // returns <string>
	*/
	Object.defineProperty( ndarray, 'dtype', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': dtype
	});

	/**
	* Number of dimensions.
	*
	* @private
	* @memberof ndarray
	* @name ndims
	* @type {PositiveInteger}
	*
	* @example
	* var ndims = ndarray.ndims;
	* // returns <number>
	*/
	Object.defineProperty( ndarray, 'ndims', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': ndims
	});

	// Inherit from the parent constructor:
	inherit( ndarray, parent );

	/**
	* Returns an array element.
	*
	* @private
	* @memberof ndarray.prototype
	* @name get
	* @type {Function}
	* @param {...integer} idx - indices
	* @returns {*} array element
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.get( 1, 1 );
	* // returns 4
	*/
	Object.defineProperty( ndarray.prototype, 'get', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': getValue( ndims, opts.codegen )
	});

	/**
	* Returns an array element located at a specified linear index.
	*
	* @private
	* @memberof ndarray.prototype
	* @name iget
	* @type {Function}
	* @param {integer} idx - linear index
	* @returns {*} array element
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.iget( 3 );
	* // returns 4
	*/
	Object.defineProperty( ndarray.prototype, 'iget', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': igetValue( parent.prototype.iget )
	});

	/**
	* Sets an array element.
	*
	* @private
	* @memberof ndarray.prototype
	* @name set
	* @type {Function}
	* @param {...integer} idx - indices
	* @param {*} v - value to set
	* @returns {ndarray} ndarray instance
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.get( 1, 1 );
	* // returns 4
	*
	* x.set( 1, 1, 10 );
	*
	* var b = x.data;
	* // returns [ 1, 2, 3, 10, 5, 6 ]
	*
	* v = x.get( 1, 1 );
	* // returns 10
	*/
	Object.defineProperty( ndarray.prototype, 'set', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': setValue( ndims, opts.codegen )
	});

	/**
	* Sets an array element located at a specified linear index.
	*
	* @private
	* @memberof ndarray.prototype
	* @name iset
	* @type {Function}
	* @param {integer} idx - linear index
	* @param {*} v - value to set
	* @returns {ndarray} ndarray instance
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.iget( 3 );
	* // returns 4
	*
	* x.iset( 3, 10 );
	*
	* var b = x.data;
	* // returns [ 1, 2, 3, 10, 5, 6 ]
	*
	* v = x.iget( 3 );
	* // returns 10
	*/
	Object.defineProperty( ndarray.prototype, 'iset', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': isetValue( parent.prototype.iset )
	});

	return ndarray;
} // end FUNCTION ctor()

// EXPORTS //

module.exports = ctor;
<commit_msg>Validate input arguments<commit_after>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isArrayLikeObject = require( '@stdlib/assert/is-array-like-object' );
var isTypedArrayLike = require( '@stdlib/assert/is-typed-array-like' );
var isBuffer = require( '@stdlib/assert/is-buffer' );
var isNonNegativeIntegerArray = require( '@stdlib/assert/is-nonnegative-integer-array' ).primitives;
var isNonNegativeInteger = require( '@stdlib/assert/is-nonnegative-integer' ).isPrimitive;
var isPositiveInteger = require( '@stdlib/assert/is-positive-integer' ).isPrimitive;
var isIntegerArray = require( '@stdlib/assert/is-integer-array' ).primitives;
var isOrder = require( '@stdlib/types/ndarray/base/assert/is-order' );
var isDataType = require( '@stdlib/types/ndarray/base/assert/is-data-type' );
var bytesPerElement = require( '@stdlib/types/ndarray/base/bytes-per-element' );
var baseCtor = require( '@stdlib/types/ndarray/base/ctor' );
var inherit = require( '@stdlib/utils/inherit' );
var defaults = require( './defaults.json' );
var igetValue = require( './iget.js' );
var isetValue = require( './iset.js' );
var getValue = require( './get.js' );
var setValue = require( './set.js' );
var validate = require( './validate.js' );

// MAIN //

/**
* Returns an ndarray constructor.
*
* @param {string} dtype - data type
* @param {PositiveInteger} ndims - number of dimensions
* @param {Options} [options] - function options
* @param {boolean} [options.codegen=true] - boolean indicating whether to use code generation
* @param {string} [options.mode="throw"] - specifies how to handle indices which exceed array dimensions
* @throws {TypeError} first argument must be a supported ndarray data type
* @throws {TypeError} second argument must be a number having a positive integer value
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @returns {Function} ndarray constructor
*
* @example
* var ndarray = ctor( 'float64', 3 );
* // returns <Function>
*
* var buffer = [ 1, 2, 3, 4, 5, 6 ];
* var shape = [ 3, 2 ];
* var strides = [ 2, 1 ];
* var offset = 0;
*
* var out = ndarray( buffer, shape, strides, offset, 'row-major' );
*/
function ctor( dtype, ndims, options ) {
	/* eslint-disable no-restricted-syntax */
	var parent;
	var opts;
	var err;

	if ( !isDataType( dtype ) ) {
		throw new TypeError( 'invalid input argument. First argument must be a supported ndarray data type. Value: `' + dtype + '`.' );
	}
	if ( !isPositiveInteger( ndims ) ) {
		throw new TypeError( 'invalid input argument. Second argument must be a positive integer. Value: `' + ndims + '`.' );
	}
	opts = {};
	opts.codegen = defaults.codegen;
	opts.mode = defaults.mode;
	if ( arguments.length > 2 ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// Create a lower-level base constructor:
	parent = baseCtor( dtype, ndims, opts );

	/**
	* ndarray constructor.
	*
	* @private
	* @constructor
	* @param {(ArrayLikeObject|TypedArray|Buffer)} buffer - data buffer
	* @param {NonNegativeIntegerArray} shape - array shape
	* @param {IntegerArray} strides - array strides
	* @param {NonNegativeInteger} offset - index offset
	* @param {string} order - specifies whether an array is row-major (C-style) or column-major (Fortran-style)
	* @returns {ndarray} ndarray instance
	*/
	function ndarray( buffer, shape, strides, offset, order ) {
		/* eslint-disable no-invalid-this */
		if ( !(this instanceof ndarray) ) {
			return new ndarray( buffer, shape, strides, offset, order ); // eslint-disable-line no-new-cap
		}
		if (
			!isArrayLikeObject( buffer ) &&
			!isTypedArrayLike( buffer ) &&
			!isBuffer( buffer )
		) {
			throw new TypeError( 'invalid input argument. `buffer` argument must be an array-like object, typed-array-like, or a Buffer. Value: `' + buffer + '`.' );
		}
		if ( !isNonNegativeIntegerArray( shape ) ) {
			throw new TypeError( 'invalid input argument. `shape` argument must be an array-like object containing nonnegative integers. Value: `' + shape + '`.' );
		}
		if ( !isIntegerArray( strides ) ) {
			throw new TypeError( 'invalid input argument. `strides` argument must be an array-like object containing integers. Value: `' + strides + '`.' );
		}
		if ( !isNonNegativeInteger( offset ) ) {
			throw new TypeError( 'invalid input argument. `offset` argument must be a nonnegative integer. Value: `' + offset + '`.' );
		}
		if ( !isOrder( order ) ) {
			throw new TypeError( 'invalid input argument. `order` argument must be a supported order. Value: `' + order + '`.' );
		}
		// Call the parent constructor:
		parent.call( this, buffer, shape, strides, offset, order );

		// Cache references to the parent constructor and parent constructor methods:
		setReadOnly( this, '_parent', parent );

		// Set private properties...
		this._mode = opts.mode;

		return this;
	} // end FUNCTION ndarray()

	/**
	* Size (in bytes) of each array element (if known).
	*
	* @private
	* @memberof ndarray
	* @name BYTES_PER_ELEMENT
	* @type {(PositiveInteger|null)}
	*
	* @example
	* var nbytes = ndarray.BYTES_PER_ELEMENT;
	* // returns <number>
	*/
	Object.defineProperty( ndarray, 'BYTES_PER_ELEMENT', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': bytesPerElement( dtype )
	});

	/**
	* Underlying data type.
	*
	* @private
	* @memberof ndarray
	* @name dtype
	* @type {string}
	*
	* @example
	* var dtype = ndarray.dtype;
	* // returns <string>
	*/
	Object.defineProperty( ndarray, 'dtype', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': dtype
	});

	/**
	* Number of dimensions.
	*
	* @private
	* @memberof ndarray
	* @name ndims
	* @type {PositiveInteger}
	*
	* @example
	* var ndims = ndarray.ndims;
	* // returns <number>
	*/
	Object.defineProperty( ndarray, 'ndims', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': ndims
	});

	// Inherit from the parent constructor:
	inherit( ndarray, parent );

	/**
	* Returns an array element.
	*
	* @private
	* @memberof ndarray.prototype
	* @name get
	* @type {Function}
	* @param {...integer} idx - indices
	* @returns {*} array element
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.get( 1, 1 );
	* // returns 4
	*/
	Object.defineProperty( ndarray.prototype, 'get', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': getValue( ndims, opts.codegen )
	});

	/**
	* Returns an array element located at a specified linear index.
	*
	* @private
	* @memberof ndarray.prototype
	* @name iget
	* @type {Function}
	* @param {integer} idx - linear index
	* @returns {*} array element
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.iget( 3 );
	* // returns 4
	*/
	Object.defineProperty( ndarray.prototype, 'iget', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': igetValue( parent.prototype.iget )
	});

	/**
	* Sets an array element.
	*
	* @private
	* @memberof ndarray.prototype
	* @name set
	* @type {Function}
	* @param {...integer} idx - indices
	* @param {*} v - value to set
	* @returns {ndarray} ndarray instance
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.get( 1, 1 );
	* // returns 4
	*
	* x.set( 1, 1, 10 );
	*
	* var b = x.data;
	* // returns [ 1, 2, 3, 10, 5, 6 ]
	*
	* v = x.get( 1, 1 );
	* // returns 10
	*/
	Object.defineProperty( ndarray.prototype, 'set', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': setValue( ndims, opts.codegen )
	});

	/**
	* Sets an array element located at a specified linear index.
	*
	* @private
	* @memberof ndarray.prototype
	* @name iset
	* @type {Function}
	* @param {integer} idx - linear index
	* @param {*} v - value to set
	* @returns {ndarray} ndarray instance
	*
	* @example
	* var buffer = [ 1, 2, 3, 4, 5, 6 ];
	* var shape = [ 3, 2 ];
	* var strides = [ 2, 1 ];
	* var offset = 0;
	*
	* var x = ndarray( buffer, shape, strides, offset, 'row-major' );
	*
	* var v = x.iget( 3 );
	* // returns 4
	*
	* x.iset( 3, 10 );
	*
	* var b = x.data;
	* // returns [ 1, 2, 3, 10, 5, 6 ]
	*
	* v = x.iget( 3 );
	* // returns 10
	*/
	Object.defineProperty( ndarray.prototype, 'iset', {
		'configurable': false,
		'enumerable': false,
		'writable': false,
		'value': isetValue( parent.prototype.iset )
	});

	return ndarray;
} // end FUNCTION ctor()

// EXPORTS //

module.exports = ctor;
<|endoftext|>


<commit_before>{
  "id":23,
  "name":"Apply for Industrial Injuries Disablement Benefit",
  "description": "Discovery is looking at how we can make the Industrial Injuries Disablement Benefit service simpler and more efficient.",
  "theme": "Health & Disability",
  "location": "Stockport",
  "phase":"discovery",
  "sro":"Derek Hobbs",
  "service_man":"Zoe Gould",
  "phase-history":{
    "discovery": [
      {"label":"Started", "date": "Dec 2015"}
    ],
  "alpha": [
      {"label":"Predicted", "date": "February 2016"}
    ],
    "beta": [
      {"label":"Predicted Start Date", "date": "TBC"}
    ]
  },

  "priority":"Low"
}
<commit_msg>Update industrial-injuries-disablement-benefit.js<commit_after>{
  "id":23,
  "name":"Apply for Industrial Injuries Disablement Benefit",
  "description": "Discovery is looking at how we can make the Industrial Injuries Disablement Benefit service simpler and more efficient.",
  "theme": "Health & Disability",
  "location": "Stockport",
  "phase":"discovery",
  "sro":"Derek Hobbs",
  "service_man":"Zoe Gould",
  "phase-history":{
    "discovery": [
      {"label":"Started", "date": "December 2015"}
    ],
  "alpha": [
      {"label":"Predicted", "date": "February 2016"}
    ],
    "beta": [
      {"label":"Predicted Start Date", "date": "TBC"}
    ]
  },

  "priority":"Low"
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Fields can be created based on a JSON definition. This file
 *    contains methods for registering those JSON definitions, and building the
 *    fields based on JSON.
 * @author bekawestberg@gmail.com (Beka Westberg)
 */
'use strict';

goog.module('Blockly.fieldRegistry');
goog.module.declareLegacyNamespace();

/* eslint-disable-next-line no-unused-vars */
const Field = goog.requireType('Blockly.Field');
/* eslint-disable-next-line no-unused-vars */
const IRegistrableField = goog.requireType('Blockly.IRegistrableField');
const registry = goog.require('Blockly.registry');

/**
 * Registers a field type.
 * fieldRegistry.fromJson uses this registry to
 * find the appropriate field type.
 * @param {string} type The field type name as used in the JSON definition.
 * @param {!IRegistrableField} fieldClass The field class containing a
 *     fromJson function that can construct an instance of the field.
 * @throws {Error} if the type name is empty, the field is already
 *     registered, or the fieldClass is not an object containing a fromJson
 *     function.
 */
const register = function(type, fieldClass) {
  registry.register(registry.Type.FIELD, type, fieldClass);
};
exports.register = register;

/**
 * Unregisters the field registered with the given type.
 * @param {string} type The field type name as used in the JSON definition.
 */
const unregister = function(type) {
  registry.unregister(registry.Type.FIELD, type);
};
exports.unregister = unregister;

/**
 * Construct a Field from a JSON arg object.
 * Finds the appropriate registered field by the type name as registered using
 * fieldRegistry.register.
 * @param {!Object} options A JSON object with a type and options specific
 *     to the field type.
 * @return {?Field} The new field instance or null if a field wasn't
 *     found with the given type name
 */
const fromJson = function(options) {
  const fieldObject = /** @type {?IRegistrableField} */ (
    registry.getObject(registry.Type.FIELD, options['type']));
  if (!fieldObject) {
    console.warn('Blockly could not create a field of type ' + options['type'] +
      '. The field is probably not being registered. This could be because' +
      ' the file is not loaded, the field does not register itself (Issue' +
      ' #1584), or the registration is not being reached.');
    return null;
  }
  return fieldObject.fromJson(options);
};
/** @package */
exports.fromJson = fromJson;
<commit_msg>clang-format core/field_registry.js<commit_after>/**
 * @license
 * Copyright 2019 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

/**
 * @fileoverview Fields can be created based on a JSON definition. This file
 *    contains methods for registering those JSON definitions, and building the
 *    fields based on JSON.
 * @author bekawestberg@gmail.com (Beka Westberg)
 */
'use strict';

goog.module('Blockly.fieldRegistry');
goog.module.declareLegacyNamespace();

/* eslint-disable-next-line no-unused-vars */
const Field = goog.requireType('Blockly.Field');
/* eslint-disable-next-line no-unused-vars */
const IRegistrableField = goog.requireType('Blockly.IRegistrableField');
const registry = goog.require('Blockly.registry');

/**
 * Registers a field type.
 * fieldRegistry.fromJson uses this registry to
 * find the appropriate field type.
 * @param {string} type The field type name as used in the JSON definition.
 * @param {!IRegistrableField} fieldClass The field class containing a
 *     fromJson function that can construct an instance of the field.
 * @throws {Error} if the type name is empty, the field is already
 *     registered, or the fieldClass is not an object containing a fromJson
 *     function.
 */
const register = function(type, fieldClass) {
  registry.register(registry.Type.FIELD, type, fieldClass);
};
exports.register = register;

/**
 * Unregisters the field registered with the given type.
 * @param {string} type The field type name as used in the JSON definition.
 */
const unregister = function(type) {
  registry.unregister(registry.Type.FIELD, type);
};
exports.unregister = unregister;

/**
 * Construct a Field from a JSON arg object.
 * Finds the appropriate registered field by the type name as registered using
 * fieldRegistry.register.
 * @param {!Object} options A JSON object with a type and options specific
 *     to the field type.
 * @return {?Field} The new field instance or null if a field wasn't
 *     found with the given type name
 */
const fromJson = function(options) {
  const fieldObject = /** @type {?IRegistrableField} */ (
      registry.getObject(registry.Type.FIELD, options['type']));
  if (!fieldObject) {
    console.warn(
        'Blockly could not create a field of type ' + options['type'] +
        '. The field is probably not being registered. This could be because' +
        ' the file is not loaded, the field does not register itself (Issue' +
        ' #1584), or the registration is not being reached.');
    return null;
  }
  return fieldObject.fromJson(options);
};
/** @package */
exports.fromJson = fromJson;
<|endoftext|>


<commit_before>/*
This module provides convenience functions for messing
around with DOM elements via CSS transitions. Have at it.

### Try out these functions:
	CT.trans.rotate(node, opts)
	CT.trans.translate(node, opts)
	CT.trans.pan(node, opts)
	CT.trans.trans(opts)
	CT.trans.setVendorPrefixed(node, property, value)
	 - sets CSS properties for all vendor prefixes
	   - [ "-webkit-", "-moz-", "-ms-", "-o-", "" ]

### And here are the default options:
	trans: {
		duration: 500,
		property: "*",
		ease: "ease-in-out"
	},
	rotate: {
		degrees: 180,
		duration: 1000,
		property: "transform",
		ease: "linear",
		prefix: true
	},
	translate: {
		duration: 300,
		property: "transform",
		ease: "ease-out",
		prefix: true,
		x: 0,
		y: 0,
		z: 0
	},
	pan: {
		duration: 5000,
		property: "background-position",
		ease: "linear",
		value: "right"
	},
	fadeIn: {
		duration: 1000,
		property: "opacity",
		value: 1
	},
	fadeOut: {
		duration: 1000,
		property: "opacity",
		value: 0
	}

TODO: let's add some more, like scale.
*/

CT.trans = {
	_: {
		vender_prefixes: [ "-webkit-", "-moz-", "-ms-", "-o-", "" ],
		tswap: { transform: "-webkit-transform" }, // mobile safari transitions
		enames: [ "webkitTransitionEnd", "mozTransitionEnd", "oTransitionEnd", "transitionend"],
		defaults: {
			trans: {
				duration: 500,
				property: "*",
				ease: "ease-in-out"
			},
			rotate: {
				degrees: 180,
				duration: 1000,
				property: "transform",
				ease: "linear",
				prefix: true
			},
			translate: {
				duration: 300,
				property: "transform",
				ease: "ease-out",
				prefix: true,
				x: 0,
				y: 0,
				z: 0
			},
			pan: {
				duration: 5000,
				property: "background-position",
				ease: "linear",
				value: "right"
			},
			fadeIn: {
				duration: 1000,
				property: "opacity",
				value: 1
			},
			fadeOut: {
				duration: 1000,
				property: "opacity",
				value: 0
			}
		}
	},
	setVenderPrefixed: function(node, property, value) {
	    for (var i = 0; i < CT.trans._.vender_prefixes.length; i++)
	        node.style[CT.trans._.vender_prefixes[i] + property] = value;
	},
	trans: function(opts) {
		// opts: node, property, value, cb, duration, ease, prefix
		opts = CT.merge(opts, CT.trans._.defaults.trans);
		if (opts.node) {
			var prevTrans = opts.node.style.transition || "",
				transComponent = (CT.trans._.tswap[opts.property] || opts.property)
		        	+ " " + opts.duration + "ms " + opts.ease,
		        fullTrans = prevTrans ? (prevTrans + ", " + transComponent) : transComponent;
		    CT.trans.setVenderPrefixed(opts.node, "transition", fullTrans);
		}
	    if (opts.cb) {
	        var transTimeout, wrapper = function () {
	            opts.node && CT.trans.setVenderPrefixed(opts.node, "transition", prevTrans);
	            clearTimeout(transTimeout);
	            transTimeout = null;
	            if (opts.node) CT.trans._.enames.forEach(function(ename) {
		            opts.node.removeEventListener(ename, wrapper, false);
            	});
	            opts.cb();
	        }
            if (opts.node) CT.trans._.enames.forEach(function(ename) {
	            opts.node.addEventListener(ename, wrapper, false);
        	});
	        transTimeout = setTimeout(wrapper, opts.duration);
	    }
	    if (opts.property && opts.property != "*") {
	        if (opts.prefix)
	            CT.trans.setVenderPrefixed(opts.node, opts.property, opts.value);
	        else
	            opts.node.style[opts.property] = opts.value;
	    }
	},
	rotate: function(node, opts) {
		// opts may include: duration, degrees, cb, ease, forever
		opts = CT.merge(opts, CT.trans._.defaults.rotate);
		opts.node = node;
		opts.value = "rotate(" + opts.degrees + "deg)";
		if (opts.forever) opts.cb = function() {
			opts.degrees += CT.trans._.defaults.rotate.degrees;
			CT.trans.rotate(node, opts);
		};
		CT.trans.trans(opts);
	},
	translate: function(node, opts) {
		opts = CT.merge(opts, CT.trans._.defaults.translate);
		opts.node = node;
		opts.value = "translate3d(" + opts.x + "px," + opts.y + "px," + opts.z + "px)",
		CT.trans.trans(opts);
	},
	pan: function(node, opts) { // for background-position
		opts = CT.merge(opts, CT.trans._.defaults.pan);
		opts.node = node;
		opts.cb = function() {
			opts.value = opts.value == "left" ? "right" : "left";
			CT.trans.pan(node, opts);
		}
		CT.trans.trans(opts);
	},
	fadeIn: function(node, opts) {
		opts = CT.merge(opts, CT.trans._.defaults.fadeIn);
		opts.node = node;
		CT.trans.trans(opts);
	},
	fadeOut: function(node, opts) {
		opts = CT.merge(opts, CT.trans._.defaults.fadeOut);
		opts.node = node;
		CT.trans.trans(opts);
	}
};<commit_msg>CT.trans.pan(): pans left-right and up-down<commit_after>/*
This module provides convenience functions for messing
around with DOM elements via CSS transitions. Have at it.

### Try out these functions:
	CT.trans.rotate(node, opts)
	CT.trans.translate(node, opts)
	CT.trans.pan(node, opts)
	CT.trans.trans(opts)
	CT.trans.setVendorPrefixed(node, property, value)
	 - sets CSS properties for all vendor prefixes
	   - [ "-webkit-", "-moz-", "-ms-", "-o-", "" ]

### And here are the default options:
	trans: {
		duration: 500,
		property: "*",
		ease: "ease-in-out"
	},
	rotate: {
		degrees: 180,
		duration: 1000,
		property: "transform",
		ease: "linear",
		prefix: true
	},
	translate: {
		duration: 300,
		property: "transform",
		ease: "ease-out",
		prefix: true,
		x: 0,
		y: 0,
		z: 0
	},
	pan: {
		duration: 5000,
		property: "background-position",
		ease: "linear",
		value: "right"
	},
	fadeIn: {
		duration: 1000,
		property: "opacity",
		value: 1
	},
	fadeOut: {
		duration: 1000,
		property: "opacity",
		value: 0
	}

TODO: let's add some more, like scale.
*/

CT.trans = {
	_: {
		vender_prefixes: [ "-webkit-", "-moz-", "-ms-", "-o-", "" ],
		tswap: { transform: "-webkit-transform" }, // mobile safari transitions
		enames: [ "webkitTransitionEnd", "mozTransitionEnd", "oTransitionEnd", "transitionend"],
		defaults: {
			trans: {
				duration: 500,
				property: "*",
				ease: "ease-in-out"
			},
			rotate: {
				degrees: 180,
				duration: 1000,
				property: "transform",
				ease: "linear",
				prefix: true
			},
			translate: {
				duration: 300,
				property: "transform",
				ease: "ease-out",
				prefix: true,
				x: 0,
				y: 0,
				z: 0
			},
			pan: {
				duration: 5000,
				property: "background-position",
				ease: "linear",
				value: "right bottom"
			},
			fadeIn: {
				duration: 1000,
				property: "opacity",
				value: 1
			},
			fadeOut: {
				duration: 1000,
				property: "opacity",
				value: 0
			}
		}
	},
	setVenderPrefixed: function(node, property, value) {
	    for (var i = 0; i < CT.trans._.vender_prefixes.length; i++)
	        node.style[CT.trans._.vender_prefixes[i] + property] = value;
	},
	trans: function(opts) {
		// opts: node, property, value, cb, duration, ease, prefix
		opts = CT.merge(opts, CT.trans._.defaults.trans);
		if (opts.node) {
			var prevTrans = opts.node.style.transition || "",
				transComponent = (CT.trans._.tswap[opts.property] || opts.property)
		        	+ " " + opts.duration + "ms " + opts.ease,
		        fullTrans = prevTrans ? (prevTrans + ", " + transComponent) : transComponent;
		    CT.trans.setVenderPrefixed(opts.node, "transition", fullTrans);
		}
	    if (opts.cb) {
	        var transTimeout, wrapper = function () {
	            opts.node && CT.trans.setVenderPrefixed(opts.node, "transition", prevTrans);
	            clearTimeout(transTimeout);
	            transTimeout = null;
	            if (opts.node) CT.trans._.enames.forEach(function(ename) {
		            opts.node.removeEventListener(ename, wrapper, false);
            	});
	            opts.cb();
	        }
            if (opts.node) CT.trans._.enames.forEach(function(ename) {
	            opts.node.addEventListener(ename, wrapper, false);
        	});
	        transTimeout = setTimeout(wrapper, opts.duration);
	    }
	    if (opts.property && opts.property != "*") {
	        if (opts.prefix)
	            CT.trans.setVenderPrefixed(opts.node, opts.property, opts.value);
	        else
	            opts.node.style[opts.property] = opts.value;
	    }
	},
	rotate: function(node, opts) {
		// opts may include: duration, degrees, cb, ease, forever
		opts = CT.merge(opts, CT.trans._.defaults.rotate);
		opts.node = node;
		opts.value = "rotate(" + opts.degrees + "deg)";
		if (opts.forever) opts.cb = function() {
			opts.degrees += CT.trans._.defaults.rotate.degrees;
			CT.trans.rotate(node, opts);
		};
		CT.trans.trans(opts);
	},
	translate: function(node, opts) {
		opts = CT.merge(opts, CT.trans._.defaults.translate);
		opts.node = node;
		opts.value = "translate3d(" + opts.x + "px," + opts.y + "px," + opts.z + "px)",
		CT.trans.trans(opts);
	},
	pan: function(node, opts) { // for background-position
		opts = CT.merge(opts, CT.trans._.defaults.pan);
		opts.node = node;
		opts.cb = function() {
			opts.value = opts.value == "left top" ? "right bottom" : "left top";
			CT.trans.pan(node, opts);
		}
		CT.trans.trans(opts);
	},
	fadeIn: function(node, opts) {
		opts = CT.merge(opts, CT.trans._.defaults.fadeIn);
		opts.node = node;
		CT.trans.trans(opts);
	},
	fadeOut: function(node, opts) {
		opts = CT.merge(opts, CT.trans._.defaults.fadeOut);
		opts.node = node;
		CT.trans.trans(opts);
	}
};<|endoftext|>


<commit_before>'use strict';

const execa = require('execa');
const log = require('intel').getLogger('browsertime.video');
const get = require('lodash.get');
const path = require('path');
const { readFile, removeFile, copyFile } = require('../../../support/fileUtil');

const SCRIPT_PATH = path.join(
  __dirname,
  '..',
  '..',
  '..',
  '..',
  'browsertime',
  'visualmetrics.py'
);

const PORTABLE_SCRIPT_PATH = path.join(
  __dirname,
  '..',
  '..',
  '..',
  '..',
  'browsertime',
  'visualmetrics-portable.py'
);

function getScript(options) {
  if (options.visualMetricsPortable) {
    return PORTABLE_SCRIPT_PATH;
  }
  return SCRIPT_PATH;
}

module.exports = {
  async checkDependencies(options) {
    return execa(process.env.PYTHON || 'python', [
      getScript(options),
      '--check'
    ]);
  },
  async run(
    videoPath,
    imageDirPath,
    elementsFile,
    videoDir,
    index,
    pageNumber,
    visitedPageNumber,
    options
  ) {
    const filmstripQuality = get(options, 'videoParams.filmstripQuality', 75);
    const createFilmstrip = get(options, 'videoParams.createFilmstrip', true);
    const fullSizeFilmstrip = get(
      options,
      'videoParams.filmstripFullSize',
      false
    );

    const thumbsize = get(options, 'videoParams.thumbsize', 400);

    const scriptArgs = [
      '--video',
      videoPath,
      '--orange',
      '--force',
      '--renderignore',
      5,
      '--json',
      '--viewport',
      '--viewportretries',
      60,
      '--viewportminheight',
      100,
      '--viewportminwidth',
      100
    ];

    if (options.visualMetricsPerceptual) {
      scriptArgs.push('--perceptual');
    }

    if (options.visualMetricsContentful) {
      scriptArgs.push('--contentful');
    }

    // There seems to be a bug with --startwhite that makes VM bail out
    // 11:20:14.950 - Calculating image histograms
    // 11:20:14.951 - No video frames found in /private/var/folders/27/xpnvcsbs0nlfbb4qq397z3rh0000gn/T/vis-cn_JMf
    // 11:20:14.951 - Done calculating histograms
    // Since we tuned the borders of the video, I hope it will just work fine
    // without. If not, let us create a upstream issue
    // If it is the first page and no preURL we can use
    // start white, that gives us less variance in metrics in Chrome
    /*
    if (!options.preURL && visitedPageNumber === 0) {
      scriptArgs.push('--startwhite');
    }
    */

    if (options.visualElements) {
      scriptArgs.push('--herodata');
      scriptArgs.push(elementsFile);
    }

    if (createFilmstrip) {
      scriptArgs.push('-q');
      scriptArgs.push(filmstripQuality);
      scriptArgs.unshift('--dir', imageDirPath);
      if (fullSizeFilmstrip) {
        scriptArgs.push('--full');
      } else if (thumbsize !== 400) {
        scriptArgs.push('--thumbsize');
        scriptArgs.push(thumbsize);
      }
    }

    const visualMetricsLogFile = path.join(
      videoDir,
      index + '.visualmetrics.log'
    );

    scriptArgs.push('--logfile');
    scriptArgs.push(visualMetricsLogFile);
    if (options.verbose >= 1) {
      scriptArgs.push('-vvvv');
    } else {
      // Full -vvvv is really chatty so keep this level for now.
      scriptArgs.push('-vvv');
    }

    scriptArgs.unshift(getScript(options));

    log.debug('Running visualmetrics.py ' + scriptArgs.join(' '));
    log.info('Get visual metrics from the video');
    try {
      const result = await execa(process.env.PYTHON || 'python', scriptArgs);
      log.debug('visualmetrics.py output:' + result.stdout);
      if (options.verbose < 1) {
        try {
          await removeFile(visualMetricsLogFile);
        } catch (e) {
          log.error(
            'Could not remove the log file from VisualMetrics, does it exist?: %s',
            visualMetricsLogFile
          );
        }
      }
      return JSON.parse(result.stdout);
    } catch (e) {
      log.error('VisualMetrics failed to run', e);
      await copyFile(videoPath, videoPath + '.failed.mp4');

      if (options.visualElements) {
        await copyFile(elementsFile, elementsFile + '.failed.json');
      }

      // If something goes wrong, dump the visual metrics log to our log
      const visualMetricLog = await readFile(visualMetricsLogFile);
      log.error('Log from VisualMetrics: %s', visualMetricLog);
      throw e;
    }
  }
};
<commit_msg>log that visual metrics portable script is used<commit_after>'use strict';

const execa = require('execa');
const log = require('intel').getLogger('browsertime.video');
const get = require('lodash.get');
const path = require('path');
const { readFile, removeFile, copyFile } = require('../../../support/fileUtil');

const SCRIPT_PATH = path.join(
  __dirname,
  '..',
  '..',
  '..',
  '..',
  'browsertime',
  'visualmetrics.py'
);

const PORTABLE_SCRIPT_PATH = path.join(
  __dirname,
  '..',
  '..',
  '..',
  '..',
  'browsertime',
  'visualmetrics-portable.py'
);

function getScript(options) {
  if (options.visualMetricsPortable) {
    log.info('Use the visual metrics portable script');
    return PORTABLE_SCRIPT_PATH;
  }
  return SCRIPT_PATH;
}

module.exports = {
  async checkDependencies(options) {
    return execa(process.env.PYTHON || 'python', [
      getScript(options),
      '--check'
    ]);
  },
  async run(
    videoPath,
    imageDirPath,
    elementsFile,
    videoDir,
    index,
    pageNumber,
    visitedPageNumber,
    options
  ) {
    const filmstripQuality = get(options, 'videoParams.filmstripQuality', 75);
    const createFilmstrip = get(options, 'videoParams.createFilmstrip', true);
    const fullSizeFilmstrip = get(
      options,
      'videoParams.filmstripFullSize',
      false
    );

    const thumbsize = get(options, 'videoParams.thumbsize', 400);

    const scriptArgs = [
      '--video',
      videoPath,
      '--orange',
      '--force',
      '--renderignore',
      5,
      '--json',
      '--viewport',
      '--viewportretries',
      60,
      '--viewportminheight',
      100,
      '--viewportminwidth',
      100
    ];

    if (options.visualMetricsPerceptual) {
      scriptArgs.push('--perceptual');
    }

    if (options.visualMetricsContentful) {
      scriptArgs.push('--contentful');
    }

    // There seems to be a bug with --startwhite that makes VM bail out
    // 11:20:14.950 - Calculating image histograms
    // 11:20:14.951 - No video frames found in /private/var/folders/27/xpnvcsbs0nlfbb4qq397z3rh0000gn/T/vis-cn_JMf
    // 11:20:14.951 - Done calculating histograms
    // Since we tuned the borders of the video, I hope it will just work fine
    // without. If not, let us create a upstream issue
    // If it is the first page and no preURL we can use
    // start white, that gives us less variance in metrics in Chrome
    /*
    if (!options.preURL && visitedPageNumber === 0) {
      scriptArgs.push('--startwhite');
    }
    */

    if (options.visualElements) {
      scriptArgs.push('--herodata');
      scriptArgs.push(elementsFile);
    }

    if (createFilmstrip) {
      scriptArgs.push('-q');
      scriptArgs.push(filmstripQuality);
      scriptArgs.unshift('--dir', imageDirPath);
      if (fullSizeFilmstrip) {
        scriptArgs.push('--full');
      } else if (thumbsize !== 400) {
        scriptArgs.push('--thumbsize');
        scriptArgs.push(thumbsize);
      }
    }

    const visualMetricsLogFile = path.join(
      videoDir,
      index + '.visualmetrics.log'
    );

    scriptArgs.push('--logfile');
    scriptArgs.push(visualMetricsLogFile);
    if (options.verbose >= 1) {
      scriptArgs.push('-vvvv');
    } else {
      // Full -vvvv is really chatty so keep this level for now.
      scriptArgs.push('-vvv');
    }

    scriptArgs.unshift(getScript(options));

    log.debug('Running visualmetrics.py ' + scriptArgs.join(' '));
    log.info('Get visual metrics from the video');
    try {
      const result = await execa(process.env.PYTHON || 'python', scriptArgs);
      log.debug('visualmetrics.py output:' + result.stdout);
      if (options.verbose < 1) {
        try {
          await removeFile(visualMetricsLogFile);
        } catch (e) {
          log.error(
            'Could not remove the log file from VisualMetrics, does it exist?: %s',
            visualMetricsLogFile
          );
        }
      }
      return JSON.parse(result.stdout);
    } catch (e) {
      log.error('VisualMetrics failed to run', e);
      await copyFile(videoPath, videoPath + '.failed.mp4');

      if (options.visualElements) {
        await copyFile(elementsFile, elementsFile + '.failed.json');
      }

      // If something goes wrong, dump the visual metrics log to our log
      const visualMetricLog = await readFile(visualMetricsLogFile);
      log.error('Log from VisualMetrics: %s', visualMetricLog);
      throw e;
    }
  }
};
<|endoftext|>