<commit_before>import {isBrowser, isNode} from './environment.js';
import Timer from './Timer.js';
import Logger from './Logger.js';
import getLoadControlClass from './LoadControl.js';
import Action from './Action.js';
import stringify from './stringify.js';
import {resetAssertCount, bumpAssertCount, getAssertCount, assert} from './assert.js';
import {getUrlArgs, argsToOptions, processOptions} from './config.js';
import testTypes from './testTypes.js';
import {defTest, orderTests} from './defTests.js';
import {queueActions, getQueuedActions, run, runDefault, getCapabilities} from './runners.js';
import {capabilities} from './capabilities.js';

const defaultOptions = {
    nameSeparator: '/',
    quitOnFirstFail: false,
    include: [],
    logExcludes: true,
    concurrent: false,
    autoRun: true,
    load: [],
    provider: false,
    capabilities: capabilities,
    cap: [],
    capPreset: [],
    user: {}
};

// the test stack which is populated with defTest, defBrowserTest, defBrowserTestRef, defNodeTest, and defRemoteTest
let smokeTests = [];

const LoadControl = getLoadControlClass(
    // log
    // eslint-disable-next-line no-use-before-define
    (...args) => (smoke.logger.log('smoke:load', 0, args)),

    // onResourceLoadComplete
    control => {
        smokeTests.forEach(test => {
            if (!('order' in test)) {
                test.order = 10000 + control.order;
            }
        });
    },

    // onLoadingComplete
    () => (smokeTests = orderTests(smokeTests)),
);

function pause(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

async function loaderIdle() {
    while (!LoadControl.loadingError) {
        const loadingPromise = LoadControl.loadingPromise;
        // eslint-disable-next-line no-await-in-loop
        await loadingPromise;
        // eslint-disable-next-line no-await-in-loop
        await pause(20);
        if (loadingPromise === LoadControl.loadingPromise) {
            break;
        }
    }
    return LoadControl.loadingError;
}

const smoke = {
    get oem() {
        return 'altoviso';
    },
    get version() {
        return '1.2.0';
    },
    isBrowser,
    isNode,

    // eslint-disable-next-line no-undef
    isAmd: isBrowser && typeof define !== 'undefined' && define.amd,

    options: defaultOptions,

    Timer,
    Logger,
    logger: new Logger(defaultOptions),

    testTypes,
    get tests() {
        return smokeTests;
    },

    resetAssertCount,
    bumpAssertCount,
    getAssertCount,
    assert,

    pause,

    stringify,

    Action,

    injectScript: LoadControl.injectScript,
    injectCss: LoadControl.injectCss,
    loadNodeModule: LoadControl.loadNodeModule,
    loadAmdModule: LoadControl.loadAmdModule,

    get loadingPromise() {
        return LoadControl.loadingPromise.proxy;
    },

    get loaderIdle() {
        return loaderIdle();
    },

    get loadedResources() {
        const result = [];
        for (const control of LoadControl.injections.values()) {
            result.push({
                resource: control.resourceName,
                loadedName: control.loadedName,
                status: control.status,
                promise: control.promise.proxy,
                errorInfo: control.errorInfo
            });
        }
        return result;
    },

    get loadedResourcesCount() {
        return LoadControl.injections.size;
    },

    getLoadedResource(resourceName) {
        let control = LoadControl.injections.get(resourceName);
        if (control) {
            control = {
                resource: control.resourceName,
                loadedName: control.loadedName,
                status: control.status,
                promise: control.promise.proxy,
                errorInfo: control.errorInfo
            };
        }
        return control;
    },

    get loadingComplete() {
        return LoadControl.loadingPromise.resolved;
    },

    get loadingError() {
        return LoadControl.loadingError;
    },

    argsToOptions,

    getUrlArgs,
    processOptions,

    configureBrowser() {
        return smoke.configure(smoke.getUrlArgs());
    },

    configure(argsOrOptions, dest) {
        const options = Array.isArray(argsOrOptions) ? smoke.argsToOptions(argsOrOptions) : argsOrOptions;
        dest = dest || smoke.options;
        smoke.processOptions(options, dest);
        if (dest === smoke.options) {
            if (smoke.options.remotelyControlled) {
                delete smoke.options.concurrent;
            }
            smoke.logger.updateOptions(dest);
        }
        (dest.load || []).slice().forEach(resource => {
            if (/\.css/i.test(resource)) {
                if (isNode) {
                    smoke.logger.log('smoke:info', 0, ['CSS resource ignored on node']);
                } else {
                    smoke.injectCss(resource);
                }
            } else if (smoke.isAmd && !/\.[^./]+$/.test(resource)) {
                // assume resource is an AMD module if an AMD loader is present and resource does not have a file type
                smoke.loadAmdModule(resource);
            } else if (isNode) {
                if (/\.es6\.js$/.test(resource)) {
                    smoke.logger.log('smoke:info', 0, ['es6 resource ignored on node']);
                } else {
                    smoke.loadNodeModule(resource);
                }
            } else {
                smoke.injectScript(resource);
            }
        });

        return smoke.loadingPromise;
    },

    checkConfig(options) {
        options = { ...options || smoke.options };
        options.capabilities =
            getCapabilities(options.capabilities, options.provider, options.cap, options.capPreset, smoke.logger)[0];
        options.load = [];
        for (const control of LoadControl.injections.values()) {
            options.load.push(
                `${control.resourceName}:${
                    control.status === false ? 'failed' : (control.status === true ? 'loaded' : control.status)}`
            );
        }
        options.tests = smoke.tests.map(test => test.id);
        // eslint-disable-next-line no-console
        console.log(isNode ? smoke.stringify(options) : options);
    },

    defTest(...args) {
        // add a test definition that works on both the browser and node
        defTest(testTypes.both, smoke.logger, smokeTests, ...args);
    },

    defBrowserTest(...args) {
        defTest(testTypes.browser, smoke.logger, smokeTests, ...args);
    },

    defBrowserTestRef(...args) {
        // define test ids that can be run remotely without having to load those tests locally
        // this is important because some tests use JS6 import/export which node cannot consume
        args.forEach(test => {
            if (typeof test !== 'string') {
                smoke.logger.log('smoke:bad-test-spec', 0, ['arguments to defBrowserTestRef must be strings']);
            } else {
                defTest(testTypes.browser, smoke.logger, smokeTests, { id: test, test: _ => _ });
            }
        });
    },

    defNodeTest(...args) {
        // add a test definition that can _only_ run in node
        defTest(testTypes.node, smoke.logger, smokeTests, ...args);
    },

    defRemoteTest(...args) {
        // add a test definition controls a remote browser
        defTest(testTypes.remote, smoke.logger, smokeTests, ...args);
    },

    queueActions,
    getQueuedActions,

    run(testInstruction, logger, options, remote, resetLog) {
        // autoRun is canceled after the first run (prevents running twice when user configs call runDefault explicitly)
        smoke.options.autoRun = false;
        return run(
            smokeTests,
            testInstruction,
            logger || options.logger || smoke.logger,
            options || smoke.options,
            remote, resetLog
        );
    },

    runDefault() {
        // autoRun is canceled after the first run (prevents running twice when user configs call runDefault explicitly)
        if (smoke.options.checkConfig) {
            smoke.checkConfig();
            smoke.options.autoRun = false;
            return Promise.resolve(smoke.logger);
        } else {
            smoke.options.autoRun = false;
            return runDefault(smokeTests, smoke.options, smoke.options.logger || smoke.logger);
        }
    }

};

async function defaultStart() {
    if (!smoke.options.autoRun) {
        return;
    }

    const options = smoke.argsToOptions(isNode ? process.argv.slice(2) : smoke.getUrlArgs());

    // set LoadControl.injectRelativePrefix...
    if (options.root) {
        const root = options.root;
        LoadControl.injectRelativePrefix = /\/$/.test(root) ? root : `${root}/`;
    } else if (isBrowser) {
        if (/\/node_modules\/bd-smoke\/browser-runner(-amd)?\.html$/.test(window.location.pathname)) {
            LoadControl.injectRelativePrefix = options.root = '../../';
        } else {
            smoke.logger.log('smoke:info', 0, ['smoke not being run by the default runner; therefore no idea how to set root; suggest you set it explicitly']);
        }
    } else {
        LoadControl.injectRelativePrefix = options.root = `${process.cwd()}/`;
    }
    smoke.logger.log('smoke:info', 0, [`root directory for relative injection paths:${LoadControl.injectRelativePrefix}`]);

    await smoke.configure(options);
    if (!smoke.loadedResourcesCount) {
        await smoke.configure({ load: `./smoke.config.${smoke.isUMD || smoke.isGlobal ? 'js' : 'es6.js'}` });
    }

    // wait until nothing was loaded for 20ms; this gives loaded files a chance to use autoRun
    // as they see fit...for example, loading "A" may cause loading "B" if autoRun is true (as so forth)
    // loaded files can set autoRun to false to prevent the behavior below
    const loadError = await loaderIdle();
    if (!loadError) {
        if (!smoke.loadingError && smoke.options.autoRun && !smoke.options.remotelyControlled) {
            const result = await smoke.runDefault();
            if (smoke.options.checkConfig) {
                smoke.logger.log('smoke:exitCode', 0, ['only printed configuration, no tests ran', 0]);
                isNode && process.exit(0);
            } else if (result.ranRemote) {
                const exitCode = result.remoteLogs.failCount +
                    result.remoteLogs.scaffoldFailCount +
                    result.localLog.failCount +
                    result.localLog.scaffoldFailCount;
                smoke.logger.log('smoke:exitCode', 0, ['default tests run on remote browser(s) completed', exitCode]);
                isNode && process.exit(exitCode);
            } else {
                const exitCode = result.localLog.failCount + result.localLog.scaffoldFailCount;
                smoke.logger.log('smoke:exitCode', 0, ['default tests run locally completed', exitCode]);
                isNode && process.exit(exitCode);
            }
        }
    } else {
        isNode && process.exit(-1);
    }
}

// let another process that loaded smoke take over and set autoRun to false to prevent the default behavior
// TODO: this might not work in AMD since smoke could be loaded as a dependent of the module that sets autoRun to false
// and other modules may have to be loaded before that module
smoke.pause(10).then(defaultStart);

export default smoke;
<commit_msg>ref: prepare for patch release<commit_after>import {isBrowser, isNode} from './environment.js';
import Timer from './Timer.js';
import Logger from './Logger.js';
import getLoadControlClass from './LoadControl.js';
import Action from './Action.js';
import stringify from './stringify.js';
import {resetAssertCount, bumpAssertCount, getAssertCount, assert} from './assert.js';
import {getUrlArgs, argsToOptions, processOptions} from './config.js';
import testTypes from './testTypes.js';
import {defTest, orderTests} from './defTests.js';
import {queueActions, getQueuedActions, run, runDefault, getCapabilities} from './runners.js';
import {capabilities} from './capabilities.js';

const defaultOptions = {
    nameSeparator: '/',
    quitOnFirstFail: false,
    include: [],
    logExcludes: true,
    concurrent: false,
    autoRun: true,
    load: [],
    provider: false,
    capabilities: capabilities,
    cap: [],
    capPreset: [],
    user: {}
};

// the test stack which is populated with defTest, defBrowserTest, defBrowserTestRef, defNodeTest, and defRemoteTest
let smokeTests = [];

const LoadControl = getLoadControlClass(
    // log
    // eslint-disable-next-line no-use-before-define
    (...args) => (smoke.logger.log('smoke:load', 0, args)),

    // onResourceLoadComplete
    control => {
        smokeTests.forEach(test => {
            if (!('order' in test)) {
                test.order = 10000 + control.order;
            }
        });
    },

    // onLoadingComplete
    () => (smokeTests = orderTests(smokeTests)),
);

function pause(ms) {
    return new Promise(resolve => {
        setTimeout(resolve, ms);
    });
}

async function loaderIdle() {
    while (!LoadControl.loadingError) {
        const loadingPromise = LoadControl.loadingPromise;
        // eslint-disable-next-line no-await-in-loop
        await loadingPromise;
        // eslint-disable-next-line no-await-in-loop
        await pause(20);
        if (loadingPromise === LoadControl.loadingPromise) {
            break;
        }
    }
    return LoadControl.loadingError;
}

const smoke = {
    get oem() {
        return 'altoviso';
    },
    get version() {
        return '1.2.1';
    },
    isBrowser,
    isNode,

    // eslint-disable-next-line no-undef
    isAmd: isBrowser && typeof define !== 'undefined' && define.amd,

    options: defaultOptions,

    Timer,
    Logger,
    logger: new Logger(defaultOptions),

    testTypes,
    get tests() {
        return smokeTests;
    },

    resetAssertCount,
    bumpAssertCount,
    getAssertCount,
    assert,

    pause,

    stringify,

    Action,

    injectScript: LoadControl.injectScript,
    injectCss: LoadControl.injectCss,
    loadNodeModule: LoadControl.loadNodeModule,
    loadAmdModule: LoadControl.loadAmdModule,

    get loadingPromise() {
        return LoadControl.loadingPromise.proxy;
    },

    get loaderIdle() {
        return loaderIdle();
    },

    get loadedResources() {
        const result = [];
        for (const control of LoadControl.injections.values()) {
            result.push({
                resource: control.resourceName,
                loadedName: control.loadedName,
                status: control.status,
                promise: control.promise.proxy,
                errorInfo: control.errorInfo
            });
        }
        return result;
    },

    get loadedResourcesCount() {
        return LoadControl.injections.size;
    },

    getLoadedResource(resourceName) {
        let control = LoadControl.injections.get(resourceName);
        if (control) {
            control = {
                resource: control.resourceName,
                loadedName: control.loadedName,
                status: control.status,
                promise: control.promise.proxy,
                errorInfo: control.errorInfo
            };
        }
        return control;
    },

    get loadingComplete() {
        return LoadControl.loadingPromise.resolved;
    },

    get loadingError() {
        return LoadControl.loadingError;
    },

    argsToOptions,

    getUrlArgs,
    processOptions,

    configureBrowser() {
        return smoke.configure(smoke.getUrlArgs());
    },

    configure(argsOrOptions, dest) {
        const options = Array.isArray(argsOrOptions) ? smoke.argsToOptions(argsOrOptions) : argsOrOptions;
        dest = dest || smoke.options;
        smoke.processOptions(options, dest);
        if (dest === smoke.options) {
            if (smoke.options.remotelyControlled) {
                delete smoke.options.concurrent;
            }
            smoke.logger.updateOptions(dest);
        }
        (dest.load || []).slice().forEach(resource => {
            if (/\.css/i.test(resource)) {
                if (isNode) {
                    smoke.logger.log('smoke:info', 0, ['CSS resource ignored on node']);
                } else {
                    smoke.injectCss(resource);
                }
            } else if (smoke.isAmd && !/\.[^./]+$/.test(resource)) {
                // assume resource is an AMD module if an AMD loader is present and resource does not have a file type
                smoke.loadAmdModule(resource);
            } else if (isNode) {
                if (/\.es6\.js$/.test(resource)) {
                    smoke.logger.log('smoke:info', 0, ['es6 resource ignored on node']);
                } else {
                    smoke.loadNodeModule(resource);
                }
            } else {
                smoke.injectScript(resource);
            }
        });

        return smoke.loadingPromise;
    },

    checkConfig(options) {
        options = { ...options || smoke.options };
        options.capabilities =
            getCapabilities(options.capabilities, options.provider, options.cap, options.capPreset, smoke.logger)[0];
        options.load = [];
        for (const control of LoadControl.injections.values()) {
            options.load.push(
                `${control.resourceName}:${
                    control.status === false ? 'failed' : (control.status === true ? 'loaded' : control.status)}`
            );
        }
        options.tests = smoke.tests.map(test => test.id);
        // eslint-disable-next-line no-console
        console.log(isNode ? smoke.stringify(options) : options);
    },

    defTest(...args) {
        // add a test definition that works on both the browser and node
        defTest(testTypes.both, smoke.logger, smokeTests, ...args);
    },

    defBrowserTest(...args) {
        defTest(testTypes.browser, smoke.logger, smokeTests, ...args);
    },

    defBrowserTestRef(...args) {
        // define test ids that can be run remotely without having to load those tests locally
        // this is important because some tests use JS6 import/export which node cannot consume
        args.forEach(test => {
            if (typeof test !== 'string') {
                smoke.logger.log('smoke:bad-test-spec', 0, ['arguments to defBrowserTestRef must be strings']);
            } else {
                defTest(testTypes.browser, smoke.logger, smokeTests, { id: test, test: _ => _ });
            }
        });
    },

    defNodeTest(...args) {
        // add a test definition that can _only_ run in node
        defTest(testTypes.node, smoke.logger, smokeTests, ...args);
    },

    defRemoteTest(...args) {
        // add a test definition controls a remote browser
        defTest(testTypes.remote, smoke.logger, smokeTests, ...args);
    },

    queueActions,
    getQueuedActions,

    run(testInstruction, logger, options, remote, resetLog) {
        // autoRun is canceled after the first run (prevents running twice when user configs call runDefault explicitly)
        smoke.options.autoRun = false;
        return run(
            smokeTests,
            testInstruction,
            logger || options.logger || smoke.logger,
            options || smoke.options,
            remote, resetLog
        );
    },

    runDefault() {
        // autoRun is canceled after the first run (prevents running twice when user configs call runDefault explicitly)
        if (smoke.options.checkConfig) {
            smoke.checkConfig();
            smoke.options.autoRun = false;
            return Promise.resolve(smoke.logger);
        } else {
            smoke.options.autoRun = false;
            return runDefault(smokeTests, smoke.options, smoke.options.logger || smoke.logger);
        }
    }

};

async function defaultStart() {
    if (!smoke.options.autoRun) {
        return;
    }

    const options = smoke.argsToOptions(isNode ? process.argv.slice(2) : smoke.getUrlArgs());

    // set LoadControl.injectRelativePrefix...
    if (options.root) {
        const root = options.root;
        LoadControl.injectRelativePrefix = /\/$/.test(root) ? root : `${root}/`;
    } else if (isBrowser) {
        if (/\/node_modules\/bd-smoke\/browser-runner(-amd)?\.html$/.test(window.location.pathname)) {
            LoadControl.injectRelativePrefix = options.root = '../../';
        } else {
            smoke.logger.log('smoke:info', 0, ['smoke not being run by the default runner; therefore no idea how to set root; suggest you set it explicitly']);
        }
    } else {
        LoadControl.injectRelativePrefix = options.root = `${process.cwd()}/`;
    }
    smoke.logger.log('smoke:info', 0, [`root directory for relative injection paths:${LoadControl.injectRelativePrefix}`]);

    await smoke.configure(options);
    if (!smoke.loadedResourcesCount) {
        await smoke.configure({ load: `./smoke.config.${smoke.isUMD || smoke.isGlobal ? 'js' : 'es6.js'}` });
    }

    // wait until nothing was loaded for 20ms; this gives loaded files a chance to use autoRun
    // as they see fit...for example, loading "A" may cause loading "B" if autoRun is true (as so forth)
    // loaded files can set autoRun to false to prevent the behavior below
    const loadError = await loaderIdle();
    if (!loadError) {
        if (!smoke.loadingError && smoke.options.autoRun && !smoke.options.remotelyControlled) {
            const result = await smoke.runDefault();
            if (smoke.options.checkConfig) {
                smoke.logger.log('smoke:exitCode', 0, ['only printed configuration, no tests ran', 0]);
                isNode && process.exit(0);
            } else if (result.ranRemote) {
                const exitCode = result.remoteLogs.failCount +
                    result.remoteLogs.scaffoldFailCount +
                    result.localLog.failCount +
                    result.localLog.scaffoldFailCount;
                smoke.logger.log('smoke:exitCode', 0, ['default tests run on remote browser(s) completed', exitCode]);
                isNode && process.exit(exitCode);
            } else {
                const exitCode = result.localLog.failCount + result.localLog.scaffoldFailCount;
                smoke.logger.log('smoke:exitCode', 0, ['default tests run locally completed', exitCode]);
                isNode && process.exit(exitCode);
            }
        }
    } else {
        isNode && process.exit(-1);
    }
}

// let another process that loaded smoke take over and set autoRun to false to prevent the default behavior
// TODO: this might not work in AMD since smoke could be loaded as a dependent of the module that sets autoRun to false
// and other modules may have to be loaded before that module
smoke.pause(10).then(defaultStart);

export default smoke;
<|endoftext|>


<commit_before>var _ = require('@sailshq/lodash');

module.exports = {
  // A virtual "piece type" only used to display a universal manage modal
  // for documents that are commit-ready. No "modified-document" piece is ever
  // really inserted into the database. -Tom
  extend: 'apostrophe-pieces',
  name: 'modified-document',
  label: 'Document',
  pluralLabel: 'Modified',
  sort: {
    updatedAt: -1
  },
  beforeConstruct: function(self, options) {
    options.addFilters = [
      {
        name: 'submitted'
      },
      {
        name: 'type'
      }
    ].concat(options.addFilters || []);
    options.addFields = [
      {
        name: 'type',
        type: 'select',
        // Patched after all types are known
        choices: []
      }
    ].concat(options.addFields || []);
  },
  construct: function(self, options) {
    var superComposeFilters = self.composeFilters;
    self.options.batchOperations = _.filter(self.options.batchOperations, function(operation) {
      // Only operations that make sense here should come through
      return _.includes([ 'submit', 'commit', 'force-export', 'revert-to-live' ], operation.name);
    });
    self.composeFilters = function() {
      // Move trash filter to end of list
      self.options.addFilters = _.filter(self.options.addFilters || [], function(filter) {
        return (filter.name !== 'trash');
      }).concat(_.filter(self.options.addFilters || [], { name: 'trash' }));
      superComposeFilters();
    };
    self.getManagerControls = function(req) {
      // Committables are not real things and cannot be "added"
      return [
        {
          type: 'minor',
          label: 'Finished',
          action: 'cancel'
        }
      ];
    };
    // Clarify that this is not a real piece type to be written to the db, it is
    // an interface to "manage" all piece types with just workflow operations
    self.addGenerateTask = function() {};
    self.insert = function() {
      throw 'This is a virtual piece type never stored to the db';
    };
    self.update = function() {
      throw 'This is a virtual piece type never stored to the db';
    };
    self.on('apostrophe:modulesReady', 'populateTypes', function() {
      const field = _.find(self.schema, { name: 'type' });
      const types = Object.keys(self.apos.docs.managers);
      field.choices = types.map(function(type) {
        const manager = self.apos.docs.getManager(type);
        let label;
        if (self.apos.instanceOf(manager, 'apostrophe-custom-pages')) {
          const def = _.find(self.apos.pages.options.types, { name: type });
          if (def) {
            label = def.label;
          }
        }
        return {
          value: type,
          label: label || manager.pluralLabel || manager.label || type
        };
      });
    });
    self.addToAdminBar = function() {
      self.apos.adminBar.add(self.__meta.name, self.pluralLabel);
      const group = _.find(self.apos.adminBar.groups, { label: 'Workflow' });
      if (group) {
        console.log('found group');
        group.items.push(self.__meta.name);
      }
    };
  }
};
<commit_msg>run quiet<commit_after>var _ = require('@sailshq/lodash');

module.exports = {
  // A virtual "piece type" only used to display a universal manage modal
  // for documents that are commit-ready. No "modified-document" piece is ever
  // really inserted into the database. -Tom
  extend: 'apostrophe-pieces',
  name: 'modified-document',
  label: 'Document',
  pluralLabel: 'Modified',
  sort: {
    updatedAt: -1
  },
  beforeConstruct: function(self, options) {
    options.addFilters = [
      {
        name: 'submitted'
      },
      {
        name: 'type'
      }
    ].concat(options.addFilters || []);
    options.addFields = [
      {
        name: 'type',
        type: 'select',
        // Patched after all types are known
        choices: []
      }
    ].concat(options.addFields || []);
  },
  construct: function(self, options) {
    var superComposeFilters = self.composeFilters;
    self.options.batchOperations = _.filter(self.options.batchOperations, function(operation) {
      // Only operations that make sense here should come through
      return _.includes([ 'submit', 'commit', 'force-export', 'revert-to-live' ], operation.name);
    });
    self.composeFilters = function() {
      // Move trash filter to end of list
      self.options.addFilters = _.filter(self.options.addFilters || [], function(filter) {
        return (filter.name !== 'trash');
      }).concat(_.filter(self.options.addFilters || [], { name: 'trash' }));
      superComposeFilters();
    };
    self.getManagerControls = function(req) {
      // Committables are not real things and cannot be "added"
      return [
        {
          type: 'minor',
          label: 'Finished',
          action: 'cancel'
        }
      ];
    };
    // Clarify that this is not a real piece type to be written to the db, it is
    // an interface to "manage" all piece types with just workflow operations
    self.addGenerateTask = function() {};
    self.insert = function() {
      throw 'This is a virtual piece type never stored to the db';
    };
    self.update = function() {
      throw 'This is a virtual piece type never stored to the db';
    };
    self.on('apostrophe:modulesReady', 'populateTypes', function() {
      const field = _.find(self.schema, { name: 'type' });
      const types = Object.keys(self.apos.docs.managers);
      field.choices = types.map(function(type) {
        const manager = self.apos.docs.getManager(type);
        let label;
        if (self.apos.instanceOf(manager, 'apostrophe-custom-pages')) {
          const def = _.find(self.apos.pages.options.types, { name: type });
          if (def) {
            label = def.label;
          }
        }
        return {
          value: type,
          label: label || manager.pluralLabel || manager.label || type
        };
      });
    });
    self.addToAdminBar = function() {
      self.apos.adminBar.add(self.__meta.name, self.pluralLabel);
      const group = _.find(self.apos.adminBar.groups, { label: 'Workflow' });
      if (group) {
        group.items.push(self.__meta.name);
      }
    };
  }
};
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var debug = require( 'debug' )( 'bundle-pkg-list:main' );
var browserify = require( 'browserify' );
var copy = require( '@stdlib/utils/copy' );
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var isFunction = require( '@stdlib/assert/is-function' );
var isArray = require( '@stdlib/assert/is-array' );
var browserifyString = require( '@stdlib/_tools/browserify/string' );
var validate = require( './validate.js' );
var defaults = require( './defaults.json' );
var unique = require( './unique.js' );
var setdiff = require( './setdiff.js' );
var treeFilter = require( './tree_filter.js' );
var namespaces = require( './namespaces.js' );
var toFlatNamespace = require( './to_flat.js' );
var toTreeNamespace = require( './to_tree.js' );
var fileStringRequire = require( './file_string_require.js' );

// MAIN //

/**
* Returns a custom bundle.
*
* @param {StringArray} pkgs - list of packages to bundle
* @param {Options} [options] - function options
* @param {string} [options.namespace="tree"] - specifies whether the namespace should be a "tree", "flat", or "none"
* @param {string} [options.bundler="browserify"] - bundler
* @param {string} [options.standalone] - standalone browserify bundle export name
* @param {string} [options.requireName="require"] - name of function exposed to supporting external loading of modules from a browserify bundle
* @param {string} [options.exportName="@stdlib/stdlib"] - bundle target name which is used to load a bundle from the external environment
* @param {Array} [options.transforms] - transforms to apply when bundling
* @param {Array} [options.plugins] - plugins to apply when bundling
* @param {StringArray} [options.external] - module(s) to omit from a generated bundle which can be assumed to be present in a separate external bundle
* @param {Callback} clbk - callback to invoke upon completion
* @throws {TypeError} first argument must be an array of strings
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {RangeError} must provide a recognized `namespace` option
* @throws {RangeError} must provide a recognized `bundler` option
* @throws {TypeError} last argument must be a function
* @returns {void}
*
* @example
* var pkgs = [
*     '@stdlib/math/base/special/erf',
*     '@stdlib/math/base/special/gamma'
* ];
*
* bundle( pkgs, onBundle );
*
* function onBundle( error, bundle ) {
*     if ( error ) {
*         throw error;
*     }
*     console.log( bundle.toString() );
* }
*/
function bundle( pkgs, options, clbk ) {
	var bopts;
	var opts;
	var err;
	var out;
	var cb;
	var b;
	var v;
	var i;

	if ( !isStringArray( pkgs ) ) {
		throw new TypeError( 'invalid input argument. First argument must be an array of strings. Value: `'+pkgs+'`.' );
	}
	opts = copy( defaults );
	if ( arguments.length > 2 ) {
		cb = clbk;
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	} else {
		cb = options;
	}
	if ( !isFunction( cb ) ) {
		throw new TypeError( 'invalid input argument. Last argument must be a function. Value: `'+cb+'`.' );
	}
	debug( 'Options: %s', JSON.stringify( opts ) );

	// Sort the packages in lexicographic order (e.g., [ '@stdlib/math/base', '@stdlib/math' ] => [ '@stdlib/math', '@stdlib/math/base' ] ):
	pkgs.sort();

	// Remove duplicates:
	pkgs = unique( pkgs );

	// If we do not need to generate a namespace for a browserify bundle, we will generate a bundle which allows a bundle consumer to `require` each package individually...
	if ( opts.namespace === 'none' && opts.bundler === 'browserify' ) {
		bopts = {
			'externalRequireName': opts.requireName,
			'require': pkgs
		};
		debug( 'Browserify options: %s', JSON.stringify( bopts ) );
		b = browserify( bopts );
		if ( opts.transforms ) {
			for ( i = 0; i < opts.transforms.length; i++ ) {
				v = opts.transforms[ i ];
				if ( isArray( v ) ) {
					b.transform( v[ 0 ], v[ 1 ] );
				} else {
					b.transform( v );
				}
			}
		}
		if ( opts.plugins ) {
			for ( i = 0; i < opts.plugins.length; i++ ) {
				v = opts.plugins[ i ];
				if ( isArray( v ) ) {
					b.plugin( v[ 0 ], v[ 1 ] );
				} else {
					b.plugin( v );
				}
			}
		}
		if ( opts.external ) {
			b.external( opts.external );
		}
		return b.bundle( onBundle );
	}

	// Generate a namespace...
	if ( opts.namespace === 'flat' ) {
		debug( 'Generating a flat namespace...' );

		debug( 'Excluding namespace packages...' );
		pkgs = setdiff( namespaces, pkgs );

		out = toFlatNamespace( pkgs );
	} else {
		debug( 'Generating a tree namespace...' );

		debug( 'Filtering namespace packages...' );
		pkgs = treeFilter( pkgs );

		out = toTreeNamespace( pkgs );
	}
	debug( 'Finished generating a namespace.' );

	debug( 'Generating an entry file...' );
	out = fileStringRequire( out );
	debug( 'Finished generating an entry file.' );

	debug( 'Generating bundle...' );
	if ( opts.bundler === 'browserify' ) {
		bopts = {
			'externalRequireName': opts.requireName,
			'exportName': opts.exportName,
			'transforms': opts.transforms,
			'plugins': opts.plugins
		};
		if ( opts.external ) {
			bopts.external = opts.external;
		}
		if ( opts.standalone ) {
			bopts.standalone = opts.standalone;
		}
		debug( 'Browserify options: %s', JSON.stringify( bopts ) );
		return browserifyString( out, bopts, onBundle );
	}
	// TODO: support other bundlers

	/**
	* Callback invoked upon generating a browserify bundle.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {(string|Buffer)} bundle - bundle
	* @returns {void}
	*/
	function onBundle( error, bundle ) {
		if ( error ) {
			debug( 'Encountered an error when generating a browserify bundle: %s', error.message );
			return done( error );
		}
		debug( 'Successfully generated a browserify bundle.' );
		done( null, bundle );
	} // end FUNCTION onBundle()

	/**
	* Callback invoked upon completion.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {(string|Buffer)} bundle - bundle
	* @returns {void}
	*/
	function done( error, bundle ) {
		if ( error ) {
			return cb( error );
		}
		cb( null, bundle );
	} // end FUNCTION done()
} // end FUNCTION bundle()

// EXPORTS //

module.exports = bundle;
<commit_msg>Support specifying a standalone bundle or a bundle export name, not both<commit_after>'use strict';

// MODULES //

var debug = require( 'debug' )( 'bundle-pkg-list:main' );
var browserify = require( 'browserify' );
var copy = require( '@stdlib/utils/copy' );
var isStringArray = require( '@stdlib/assert/is-string-array' ).primitives;
var isFunction = require( '@stdlib/assert/is-function' );
var isArray = require( '@stdlib/assert/is-array' );
var browserifyString = require( '@stdlib/_tools/browserify/string' );
var validate = require( './validate.js' );
var defaults = require( './defaults.json' );
var unique = require( './unique.js' );
var setdiff = require( './setdiff.js' );
var treeFilter = require( './tree_filter.js' );
var namespaces = require( './namespaces.js' );
var toFlatNamespace = require( './to_flat.js' );
var toTreeNamespace = require( './to_tree.js' );
var fileStringRequire = require( './file_string_require.js' );

// MAIN //

/**
* Returns a custom bundle.
*
* @param {StringArray} pkgs - list of packages to bundle
* @param {Options} [options] - function options
* @param {string} [options.namespace="tree"] - specifies whether the namespace should be a "tree", "flat", or "none"
* @param {string} [options.bundler="browserify"] - bundler
* @param {string} [options.standalone] - standalone browserify bundle export name
* @param {string} [options.requireName="require"] - name of function exposed to supporting external loading of modules from a browserify bundle
* @param {string} [options.exportName="@stdlib/stdlib"] - bundle target name which is used to load a bundle from the external environment
* @param {Array} [options.transforms] - transforms to apply when bundling
* @param {Array} [options.plugins] - plugins to apply when bundling
* @param {StringArray} [options.external] - module(s) to omit from a generated bundle which can be assumed to be present in a separate external bundle
* @param {Callback} clbk - callback to invoke upon completion
* @throws {TypeError} first argument must be an array of strings
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {RangeError} must provide a recognized `namespace` option
* @throws {RangeError} must provide a recognized `bundler` option
* @throws {TypeError} last argument must be a function
* @returns {void}
*
* @example
* var pkgs = [
*     '@stdlib/math/base/special/erf',
*     '@stdlib/math/base/special/gamma'
* ];
*
* bundle( pkgs, onBundle );
*
* function onBundle( error, bundle ) {
*     if ( error ) {
*         throw error;
*     }
*     console.log( bundle.toString() );
* }
*/
function bundle( pkgs, options, clbk ) {
	var bopts;
	var opts;
	var err;
	var out;
	var cb;
	var b;
	var v;
	var i;

	if ( !isStringArray( pkgs ) ) {
		throw new TypeError( 'invalid input argument. First argument must be an array of strings. Value: `'+pkgs+'`.' );
	}
	opts = copy( defaults );
	if ( arguments.length > 2 ) {
		cb = clbk;
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	} else {
		cb = options;
	}
	if ( !isFunction( cb ) ) {
		throw new TypeError( 'invalid input argument. Last argument must be a function. Value: `'+cb+'`.' );
	}
	debug( 'Options: %s', JSON.stringify( opts ) );

	// Sort the packages in lexicographic order (e.g., [ '@stdlib/math/base', '@stdlib/math' ] => [ '@stdlib/math', '@stdlib/math/base' ] ):
	pkgs.sort();

	// Remove duplicates:
	pkgs = unique( pkgs );

	// If we do not need to generate a namespace for a browserify bundle, we will generate a bundle which allows a bundle consumer to `require` each package individually...
	if ( opts.namespace === 'none' && opts.bundler === 'browserify' ) {
		bopts = {
			'externalRequireName': opts.requireName,
			'require': pkgs
		};
		debug( 'Browserify options: %s', JSON.stringify( bopts ) );
		b = browserify( bopts );
		if ( opts.transforms ) {
			for ( i = 0; i < opts.transforms.length; i++ ) {
				v = opts.transforms[ i ];
				if ( isArray( v ) ) {
					b.transform( v[ 0 ], v[ 1 ] );
				} else {
					b.transform( v );
				}
			}
		}
		if ( opts.plugins ) {
			for ( i = 0; i < opts.plugins.length; i++ ) {
				v = opts.plugins[ i ];
				if ( isArray( v ) ) {
					b.plugin( v[ 0 ], v[ 1 ] );
				} else {
					b.plugin( v );
				}
			}
		}
		if ( opts.external ) {
			b.external( opts.external );
		}
		return b.bundle( onBundle );
	}

	// Generate a namespace...
	if ( opts.namespace === 'flat' ) {
		debug( 'Generating a flat namespace...' );

		debug( 'Excluding namespace packages...' );
		pkgs = setdiff( namespaces, pkgs );

		out = toFlatNamespace( pkgs );
	} else {
		debug( 'Generating a tree namespace...' );

		debug( 'Filtering namespace packages...' );
		pkgs = treeFilter( pkgs );

		out = toTreeNamespace( pkgs );
	}
	debug( 'Finished generating a namespace.' );

	debug( 'Generating an entry file...' );
	out = fileStringRequire( out );
	debug( 'Finished generating an entry file.' );

	debug( 'Generating bundle...' );
	if ( opts.bundler === 'browserify' ) {
		bopts = {
			'requireName': opts.requireName,
			'transforms': opts.transforms,
			'plugins': opts.plugins
		};
		if ( opts.standalone ) {
			bopts.standalone = opts.standalone;
		} else if ( opts.exportName ) {
			bopts.exportName = opts.exportName;
		}
		if ( opts.external ) {
			bopts.external = opts.external;
		}
		debug( 'Browserify options: %s', JSON.stringify( bopts ) );
		return browserifyString( out, bopts, onBundle );
	}
	// TODO: support other bundlers

	/**
	* Callback invoked upon generating a browserify bundle.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {(string|Buffer)} bundle - bundle
	* @returns {void}
	*/
	function onBundle( error, bundle ) {
		if ( error ) {
			debug( 'Encountered an error when generating a browserify bundle: %s', error.message );
			return done( error );
		}
		debug( 'Successfully generated a browserify bundle.' );
		done( null, bundle );
	} // end FUNCTION onBundle()

	/**
	* Callback invoked upon completion.
	*
	* @private
	* @param {(Error|null)} error - error object
	* @param {(string|Buffer)} bundle - bundle
	* @returns {void}
	*/
	function done( error, bundle ) {
		if ( error ) {
			return cb( error );
		}
		cb( null, bundle );
	} // end FUNCTION done()
} // end FUNCTION bundle()

// EXPORTS //

module.exports = bundle;
<|endoftext|>


<commit_before>/**
* @license Apache-2.0
*
* Copyright (c) 2019 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 bench = require( '@stdlib/bench' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pkg = require( './../package.json' ).name;
var iterLength = require( './../lib' );

// FUNCTIONS //

function createIterator( arr ) {
	var len;
	var it;
	var i;

	len = arr.length;
	i = -1;

	it = {};
	it.next = next;
	it.reset = reset;

	return it;

	function next() {
		i += 1;
		if ( i < len ) {
			return {
				'value': arr[ i ],
				'done': false
			};
		}
		i = -1; // reset index
		return {
			'done': true
		};
	}

	function reset() {
		i = -1;
	}
}

// MAIN //

bench( pkg, function benchmark( b ) {
	var arr;
	var v;
	var i;

	arr = createIterator( [ 0, 0, 0, 0, 0, 1 ] );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		v = iterLength( arr );
		if ( isnan( v ) ) {
			b.fail( 'should not be NaN' );
		}
		arr.reset();
	}
	b.toc();
	if ( isnan( v ) ) {
		b.fail( 'should not be NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::loop', function benchmark( b ) {
	var values;
	var count;
	var arr;
	var v;
	var i;

	values = [ 0, 0, 0, 0, 0, 1 ];
	arr = createIterator( values );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		v = {};
		count = 0;
		while ( v && !v.done ) {
			v = arr.next();
			count += 1;
		}
		if ( count !== values.length ) {
			b.fail( 'unexpected result' );
		}
		arr.reset();
	}
	b.toc();
	if ( count !== values.length ) {
		b.fail( 'unexpected result' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<commit_msg>Fix loop benchmark<commit_after>/**
* @license Apache-2.0
*
* Copyright (c) 2019 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 bench = require( '@stdlib/bench' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pkg = require( './../package.json' ).name;
var iterLength = require( './../lib' );

// FUNCTIONS //

function createIterator( arr ) {
	var len;
	var it;
	var i;

	len = arr.length;
	i = -1;

	it = {};
	it.next = next;
	it.reset = reset;

	return it;

	function next() {
		i += 1;
		if ( i < len ) {
			return {
				'value': arr[ i ],
				'done': false
			};
		}
		i = -1; // reset index
		return {
			'done': true
		};
	}

	function reset() {
		i = -1;
	}
}

// MAIN //

bench( pkg, function benchmark( b ) {
	var arr;
	var v;
	var i;

	arr = createIterator( [ 0, 0, 0, 0, 0, 1 ] );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		v = iterLength( arr );
		if ( isnan( v ) ) {
			b.fail( 'should not be NaN' );
		}
		arr.reset();
	}
	b.toc();
	if ( isnan( v ) ) {
		b.fail( 'should not be NaN' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});

bench( pkg+'::loop', function benchmark( b ) {
	var values;
	var count;
	var arr;
	var v;
	var i;

	values = [ 0, 0, 0, 0, 0, 1 ];
	arr = createIterator( values );

	b.tic();
	for ( i = 0; i < b.iterations; i++ ) {
		v = {};
		count = 0;
		while ( v && !v.done ) {
			v = arr.next();
			if ( v.done ) {
				break;
			}
			count += 1;
		}
		if ( count !== values.length ) {
			b.fail( 'unexpected result' );
		}
		arr.reset();
	}
	b.toc();
	if ( count !== values.length ) {
		b.fail( 'unexpected result' );
	}
	b.pass( 'benchmark finished' );
	b.end();
});
<|endoftext|>


<commit_before>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace gumbel
*/
var gumbel = {};

/**
* @name cdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/cdf}
*/
setReadOnly( gumbel, 'cdf', require( '@stdlib/math/base/dist/gumbel/cdf' ) );

/**
* @name logcdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/logcdf}
*/
setReadOnly( gumbel, 'logcdf', require( '@stdlib/math/base/dist/gumbel/logcdf' ) );

/**
* @name logpdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/logpdf}
*/
setReadOnly( gumbel, 'logpdf', require( '@stdlib/math/base/dist/gumbel/logpdf' ) );

/**
* @name mgf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/mgf}
*/
setReadOnly( gumbel, 'mgf', require( '@stdlib/math/base/dist/gumbel/mgf' ) );

/**
* @name pdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/pdf}
*/
setReadOnly( gumbel, 'pdf', require( '@stdlib/math/base/dist/gumbel/pdf' ) );

/**
* @name quantile
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/quantile}
*/
setReadOnly( gumbel, 'quantile', require( '@stdlib/math/base/dist/gumbel/quantile' ) );

// EXPORTS //

module.exports = gumbel;
<commit_msg>Add modules to Gumbel namespace<commit_after>'use strict';

/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );

// MAIN //

/**
* Top-level namespace.
*
* @namespace gumbel
*/
var gumbel = {};

/**
* @name cdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/cdf}
*/
setReadOnly( gumbel, 'cdf', require( '@stdlib/math/base/dist/gumbel/cdf' ) );

/**
* @name entropy
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/entropy}
*/
setReadOnly( gumbel, 'entropy', require( '@stdlib/math/base/dist/gumbel/entropy' ) );

/**
* @name kurtosis
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/kurtosis}
*/
setReadOnly( gumbel, 'kurtosis', require( '@stdlib/math/base/dist/gumbel/kurtosis' ) );

/**
* @name logcdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/logcdf}
*/
setReadOnly( gumbel, 'logcdf', require( '@stdlib/math/base/dist/gumbel/logcdf' ) );

/**
* @name logpdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/logpdf}
*/
setReadOnly( gumbel, 'logpdf', require( '@stdlib/math/base/dist/gumbel/logpdf' ) );

/**
* @name mean
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/mean}
*/
setReadOnly( gumbel, 'mean', require( '@stdlib/math/base/dist/gumbel/mean' ) );

/**
* @name median
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/median}
*/
setReadOnly( gumbel, 'median', require( '@stdlib/math/base/dist/gumbel/median' ) );

/**
* @name mgf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/mgf}
*/
setReadOnly( gumbel, 'mgf', require( '@stdlib/math/base/dist/gumbel/mgf' ) );

/**
* @name mode
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/mode}
*/
setReadOnly( gumbel, 'mode', require( '@stdlib/math/base/dist/gumbel/mode' ) );

/**
* @name pdf
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/pdf}
*/
setReadOnly( gumbel, 'pdf', require( '@stdlib/math/base/dist/gumbel/pdf' ) );

/**
* @name quantile
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/quantile}
*/
setReadOnly( gumbel, 'quantile', require( '@stdlib/math/base/dist/gumbel/quantile' ) );

/**
* @name skewness
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/skewness}
*/
setReadOnly( gumbel, 'skewness', require( '@stdlib/math/base/dist/gumbel/skewness' ) );

/**
* @name variance
* @memberof gumbel
* @readonly
* @type {Function}
* @see {@link module:@stdlib/math/base/dist/gumbel/variance}
*/
setReadOnly( gumbel, 'variance', require( '@stdlib/math/base/dist/gumbel/variance' ) );

// EXPORTS //

module.exports = gumbel;
<|endoftext|>


<commit_before>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isArrayLike = require( '@stdlib/assert/is-array-like' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var deepCopy = require( '@stdlib/utils/copy' );
var floor = require( '@stdlib/math/base/special/floor' );
var randu = require( '@stdlib/math/base/random/randu' ).factory;
var defaults = require( './defaults.json' );
var validate = require( './validate.js' );

// MAIN //

/**
* Returns a function to create a random permutation of elements from an array-like object.
*
* @param {Options} [config] - function options
* @param {PositiveInteger} [config.seed] - integer-valued seed
* @param {string} [config.copy="shallow"] - default copy option (`deep`, `shallow` or `none`)
* @throws {TypeError} options argument must be an object
* @returns {Function} shuffle function
*
* @example
* var shuffle = factory({
*     'seed': 249
* });
* var data = [ 3, 8, 4, 8 ];
* var out = shuffle( data );
* // returns [ 4, 3, 8, 8 ]
*/
function factory( config ) {
	var conf;
	var rand;
	var err;

	conf = deepCopy( defaults );
	if ( arguments.length ) {
		err = validate( conf, config );
		if ( err ) {
			throw err;
		}
	}
	if ( config && config.seed ) {
		rand = randu({
			'seed': config.seed
		});
	} else {
		rand = randu();
	}

	/**
	* Returns a random permutation of elements in `arr`.
	*
	* @private
	* @param {ArrayLike} arr - array-like object to shuffle
	* @param {Options} [options] - function options
	* @param {string} [options.copy] - string indicating whether to return a copy (`deep`,`shallow` or `none`)
	* @throws {TypeError} first argument must be array-like
	* @throws {TypeError} `options` must be an object
	* @throws {TypeError} must provide valid options
	* @returns {ArrayLike} the shuffled array-like object
	*
	* @example
	* var data = [ 1, 2, 3 ];
	* var out = shuffle( data );
	* // e.g., returns [ 3, 1, 2 ]
	*
	* @example
	* var data = [ 1, 2, 3 ];
	* var out = shuffle( data, {
	*     'copy': 'none'
	* });
	* var bool = ( data === out );
	* // returns true
	*/
	function shuffle( arr, options ) {
		var strflg;
		var level;
		var copy;
		var opts;
		var err;
		var out;
		var tmp;
		var N;
		var i;
		var j;

		if ( !isArrayLike( arr ) ) {
			throw new TypeError( 'invalid input argument. First argument must be array-like. Value: `' + arr + '`.' );
		}
		if ( arguments.length > 1 ) {
			opts = {};
			err = validate( opts, options );
			if ( err ) {
				throw err;
			}
		}
		copy = ( opts && opts.copy ) ? opts.copy : conf.copy;

		strflg = isString( arr );
		if ( strflg ) {
			arr = arr.split( '' );
			copy = 'none';
		}

		level = 0;
		if ( copy === 'shallow' ) {
			level += 1;
		} else if ( copy === 'deep' ) {
			level += 2;
		}
		N = arr.length;
		out = deepCopy( arr, level );
		// Note: we skip the first element, as no further swaps are possible given that all other indices are excluded from swapping...
		for ( i = N - 1; i > 0; i-- ) {
			// Generate an integer index on the interval [0,i]:
			j = floor( rand() * (i+1.0) );
			// Swap elements:
			tmp = out[ i ];
			out[ i ] = out[ j ];
			out[ j ] = tmp;
		}

		if ( strflg ) {
			out = arr.join( '' );
		}
		return out;
	} // end FUNCTION shuffle()

	setReadOnly( shuffle, 'SEED', rand.SEED );
	setReadOnly( shuffle, 'PRNG', rand );
	return shuffle;
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<commit_msg>Add missing empty lines<commit_after>'use strict';

// MODULES //

var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var isArrayLike = require( '@stdlib/assert/is-array-like' );
var isString = require( '@stdlib/assert/is-string' ).isPrimitive;
var deepCopy = require( '@stdlib/utils/copy' );
var floor = require( '@stdlib/math/base/special/floor' );
var randu = require( '@stdlib/math/base/random/randu' ).factory;
var defaults = require( './defaults.json' );
var validate = require( './validate.js' );

// MAIN //

/**
* Returns a function to create a random permutation of elements from an array-like object.
*
* @param {Options} [config] - function options
* @param {PositiveInteger} [config.seed] - integer-valued seed
* @param {string} [config.copy="shallow"] - default copy option (`deep`, `shallow` or `none`)
* @throws {TypeError} options argument must be an object
* @returns {Function} shuffle function
*
* @example
* var shuffle = factory({
*     'seed': 249
* });
* var data = [ 3, 8, 4, 8 ];
* var out = shuffle( data );
* // returns [ 4, 3, 8, 8 ]
*/
function factory( config ) {
	var conf;
	var rand;
	var err;

	conf = deepCopy( defaults );
	if ( arguments.length ) {
		err = validate( conf, config );
		if ( err ) {
			throw err;
		}
	}
	if ( config && config.seed ) {
		rand = randu({
			'seed': config.seed
		});
	} else {
		rand = randu();
	}

	/**
	* Returns a random permutation of elements in `arr`.
	*
	* @private
	* @param {ArrayLike} arr - array-like object to shuffle
	* @param {Options} [options] - function options
	* @param {string} [options.copy] - string indicating whether to return a copy (`deep`,`shallow` or `none`)
	* @throws {TypeError} first argument must be array-like
	* @throws {TypeError} `options` must be an object
	* @throws {TypeError} must provide valid options
	* @returns {ArrayLike} the shuffled array-like object
	*
	* @example
	* var data = [ 1, 2, 3 ];
	* var out = shuffle( data );
	* // e.g., returns [ 3, 1, 2 ]
	*
	* @example
	* var data = [ 1, 2, 3 ];
	* var out = shuffle( data, {
	*     'copy': 'none'
	* });
	* var bool = ( data === out );
	* // returns true
	*/
	function shuffle( arr, options ) {
		var strflg;
		var level;
		var copy;
		var opts;
		var err;
		var out;
		var tmp;
		var N;
		var i;
		var j;

		if ( !isArrayLike( arr ) ) {
			throw new TypeError( 'invalid input argument. First argument must be array-like. Value: `' + arr + '`.' );
		}
		if ( arguments.length > 1 ) {
			opts = {};
			err = validate( opts, options );
			if ( err ) {
				throw err;
			}
		}
		copy = ( opts && opts.copy ) ? opts.copy : conf.copy;

		strflg = isString( arr );
		if ( strflg ) {
			arr = arr.split( '' );
			copy = 'none';
		}

		level = 0;
		if ( copy === 'shallow' ) {
			level += 1;
		} else if ( copy === 'deep' ) {
			level += 2;
		}
		N = arr.length;
		out = deepCopy( arr, level );

		// Note: we skip the first element, as no further swaps are possible given that all other indices are excluded from swapping...
		for ( i = N - 1; i > 0; i-- ) {
			// Generate an integer index on the interval [0,i]:
			j = floor( rand() * (i+1.0) );

			// Swap elements:
			tmp = out[ i ];
			out[ i ] = out[ j ];
			out[ j ] = tmp;
		}

		if ( strflg ) {
			out = arr.join( '' );
		}
		return out;
	} // end FUNCTION shuffle()

	setReadOnly( shuffle, 'SEED', rand.SEED );
	setReadOnly( shuffle, 'PRNG', rand );
	return shuffle;
} // end FUNCTION factory()

// EXPORTS //

module.exports = factory;
<|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 Readable = require( 'readable-stream' ).Readable;
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isError = require( '@stdlib/assert/is-error' );
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var rarcsine = require( '@stdlib/random/iterators/arcsine' );
var string2buffer = require( '@stdlib/buffer/from-string' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var debug = require( './debug.js' );

// FUNCTIONS //

/**
* Returns the PRNG seed.
*
* @private
* @returns {Uint32Array} seed
*/
function getSeed() {
	return this.PRNG.seed; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
	return this.PRNG.seedLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
	return this.PRNG.stateLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
	return this.PRNG.byteLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the current pseudorandom number generator state.
*
* @private
* @returns {Uint32Array} current state
*/
function getState() {
	return this.PRNG.state; // eslint-disable-line no-invalid-this
}

/**
* Sets the pseudorandom number generator state.
*
* @private
* @param {Uint32Array} s - generator state
* @throws {TypeError} must provide a `Uint32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
	this.PRNG.state = s; // eslint-disable-line no-invalid-this
}

/**
* Implements the `_read` method.
*
* @private
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
function read() {
	/* eslint-disable no-invalid-this */
	var FLG;
	var r;

	FLG = true;
	while ( FLG ) {
		r = this._prng.next();
		if ( r.done ) {
			debug( 'Finished generating pseudorandom numbers.' );
			return this.push( null );
		}
		this._iter += 1;

		r = r.value.toString();
		debug( 'Generated a new pseudorandom number. Value: %s. Iter: %d.', r, this._iter );

		if ( this._objectMode === false ) {
			if ( this._iter === 1 ) {
				r = string2buffer( r );
			} else {
				r = string2buffer( this._sep+r );
			}
		}
		FLG = this.push( r );
	}

	/* eslint-enable no-invalid-this */
}

/**
* Gracefully destroys a stream, providing backwards compatibility.
*
* @private
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
function destroy( error ) {
	/* eslint-disable no-invalid-this */
	var self;
	if ( this._destroyed ) {
		debug( 'Attempted to destroy an already destroyed stream.' );
		return this;
	}
	self = this;
	this._destroyed = true;

	// TODO: replace with polyfill
	process.nextTick( close );

	return this;

	/**
	* Closes a stream.
	*
	* @private
	*/
	function close() {
		if ( error ) {
			debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
			self.emit( 'error', error );
		}
		debug( 'Closing the stream...' );
		self.emit( 'close' );
	}

	/* eslint-enable no-invalid-this */
}

// MAIN //

/**
* Stream constructor for generating a stream of pseudorandom numbers drawn from an arcsine distribution.
*
* @constructor
* @param {number} a - minimum support
* @param {number} b - maximum support
* @param {Options} [options] - stream options
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in the internal buffer before ceasing to generate additional pseudorandom numbers
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} `a` must be a number
* @throws {TypeError} `b` must be a number
* @throws {RangeError} `a` must be less than `b`
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/utils/inspect' );
*
* function log( chunk ) {
*    console.log( chunk );
* }
*
* var opts = {
*     'iter': 10
* };
*
* var stream = new RandomStream( 2.0, 5.0, opts );
*
* stream.pipe( inspectStream( log )  );
*/
function RandomStream( a, b, options ) {
	var opts;
	var err;
	if ( !( this instanceof RandomStream ) ) {
		if ( arguments.length > 2 ) {
			return new RandomStream( a, b, options );
		}
		return new RandomStream( a, b );
	}
	if ( !isNumber( a ) || isnan( a ) ) {
		throw new TypeError( 'invalid argument. First argument must be a number primitive and not `NaN`. Value: `'+a+'`.' );
	}
	if ( !isNumber( b ) || isnan( b ) ) {
		throw new TypeError( 'invalid argument. Second argument must be a number primitive and not `NaN`. Value: `'+b+'`.' );
	}
	if ( a >= b ) {
		throw new RangeError( 'invalid argument. Minimum support `a` must be less than maximum support `b`. Value: `['+a+','+b+']`.');
	}
	opts = copy( DEFAULTS );
	if ( arguments.length > 2 ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// Make the stream a readable stream:
	debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
	Readable.call( this, opts );

	// Destruction state:
	setNonEnumerable( this, '_destroyed', false );

	// Cache whether the stream is operating in object mode:
	setNonEnumerable( this, '_objectMode', opts.objectMode );

	// Cache the separator:
	setNonEnumerable( this, '_sep', opts.sep );

	// Initialize an iteration counter:
	setNonEnumerable( this, '_iter', 0 );

	// Create the underlying PRNG iterator:
	setNonEnumerableReadOnly( this, '_prng', rarcsine( a, b, opts ) );
	setReadOnly( this, 'PRNG', this._prng.PRNG );

	return this;
}

/*
* Inherit from the `Readable` prototype.
*/
inherit( RandomStream, Readable );

/**
* PRNG seed.
*
* @name seed
* @memberof RandomStream.prototype
* @type {Uint32Array}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed );

/**
* PRNG seed length.
*
* @name seedLength
* @memberof RandomStream.prototype
* @type {PositiveInteger}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength );

/**
* Current pseudorandom number generator state.
*
* @name state
* @memberof RandomStream.prototype
* @type {Uint32Array}
* @throws {TypeError} must provide a `Uint32Array`
* @throws {Error} must provide a valid state
*/
setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState );

/**
* PRNG state length.
*
* @name stateLength
* @memberof RandomStream.prototype
* @type {PositiveInteger}
*/
setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength );

/**
* PRNG state size (in bytes).
*
* @name byteLength
* @memberof RandomStream.prototype
* @type {PositiveInteger}
*/
setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize );

/**
* Implements the `_read` method.
*
* @private
* @name _read
* @memberof RandomStream.prototype
* @type {Function}
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
defineProperty( RandomStream.prototype, '_read', {
	'configurable': false,
	'enumerable': false,
	'writable': false,
	'value': read
});

/**
* Gracefully destroys a stream, providing backwards compatibility.
*
* @name destroy
* @memberof RandomStream.prototype
* @type {Function}
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
defineProperty( RandomStream.prototype, 'destroy', {
	'configurable': false,
	'enumerable': false,
	'writable': false,
	'value': destroy
});

// EXPORTS //

module.exports = RandomStream;
<commit_msg>Update descriptions<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 Readable = require( 'readable-stream' ).Readable;
var isNumber = require( '@stdlib/assert/is-number' ).isPrimitive;
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var isError = require( '@stdlib/assert/is-error' );
var copy = require( '@stdlib/utils/copy' );
var inherit = require( '@stdlib/utils/inherit' );
var defineProperty = require( '@stdlib/utils/define-property' );
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
var setNonEnumerable = require( '@stdlib/utils/define-nonenumerable-property' );
var setNonEnumerableReadOnly = require( '@stdlib/utils/define-nonenumerable-read-only-property' );
var setReadOnlyAccessor = require( '@stdlib/utils/define-read-only-accessor' );
var setReadWriteAccessor = require( '@stdlib/utils/define-read-write-accessor' );
var rarcsine = require( '@stdlib/random/iterators/arcsine' );
var string2buffer = require( '@stdlib/buffer/from-string' );
var DEFAULTS = require( './defaults.json' );
var validate = require( './validate.js' );
var debug = require( './debug.js' );

// FUNCTIONS //

/**
* Returns the PRNG seed.
*
* @private
* @returns {Uint32Array} seed
*/
function getSeed() {
	return this.PRNG.seed; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG seed length.
*
* @private
* @returns {PositiveInteger} seed length
*/
function getSeedLength() {
	return this.PRNG.seedLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG state length.
*
* @private
* @returns {PositiveInteger} state length
*/
function getStateLength() {
	return this.PRNG.stateLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the PRNG state size (in bytes).
*
* @private
* @returns {PositiveInteger} state size (in bytes)
*/
function getStateSize() {
	return this.PRNG.byteLength; // eslint-disable-line no-invalid-this
}

/**
* Returns the current PRNG state.
*
* @private
* @returns {Uint32Array} current state
*/
function getState() {
	return this.PRNG.state; // eslint-disable-line no-invalid-this
}

/**
* Sets the PRNG state.
*
* @private
* @param {Uint32Array} s - generator state
* @throws {TypeError} must provide a `Uint32Array`
* @throws {Error} must provide a valid state
*/
function setState( s ) {
	this.PRNG.state = s; // eslint-disable-line no-invalid-this
}

/**
* Implements the `_read` method.
*
* @private
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
function read() {
	/* eslint-disable no-invalid-this */
	var FLG;
	var r;

	FLG = true;
	while ( FLG ) {
		r = this._prng.next();
		if ( r.done ) {
			debug( 'Finished generating pseudorandom numbers.' );
			return this.push( null );
		}
		this._iter += 1;

		r = r.value.toString();
		debug( 'Generated a new pseudorandom number. Value: %s. Iter: %d.', r, this._iter );

		if ( this._objectMode === false ) {
			if ( this._iter === 1 ) {
				r = string2buffer( r );
			} else {
				r = string2buffer( this._sep+r );
			}
		}
		FLG = this.push( r );
	}

	/* eslint-enable no-invalid-this */
}

/**
* Gracefully destroys a stream, providing backwards compatibility.
*
* @private
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
function destroy( error ) {
	/* eslint-disable no-invalid-this */
	var self;
	if ( this._destroyed ) {
		debug( 'Attempted to destroy an already destroyed stream.' );
		return this;
	}
	self = this;
	this._destroyed = true;

	// TODO: replace with polyfill
	process.nextTick( close );

	return this;

	/**
	* Closes a stream.
	*
	* @private
	*/
	function close() {
		if ( error ) {
			debug( 'Stream was destroyed due to an error. Error: %s.', ( isError( error ) ) ? error.message : JSON.stringify( error ) );
			self.emit( 'error', error );
		}
		debug( 'Closing the stream...' );
		self.emit( 'close' );
	}

	/* eslint-enable no-invalid-this */
}

// MAIN //

/**
* Stream constructor for generating a stream of pseudorandom numbers drawn from an arcsine distribution.
*
* @constructor
* @param {number} a - minimum support
* @param {number} b - maximum support
* @param {Options} [options] - stream options
* @param {string} [options.sep='\n'] - separator used to join streamed data
* @param {boolean} [options.objectMode=false] - specifies whether the stream should operate in object mode
* @param {(string|null)} [options.encoding=null] - specifies how `Buffer` objects should be decoded to strings
* @param {NonNegativeNumber} [options.highWaterMark] - specifies the maximum number of bytes to store in the internal buffer before ceasing to generate additional pseudorandom numbers
* @param {NonNegativeInteger} [options.iter] - number of iterations
* @param {PRNGSeedMT19937} [options.seed] - pseudorandom number generator seed
* @param {PRNGStateMT19937} [options.state] - pseudorandom number generator state
* @param {boolean} [options.copy=true] - boolean indicating whether to copy a provided pseudorandom number generator state
* @throws {TypeError} `a` must be a number
* @throws {TypeError} `b` must be a number
* @throws {RangeError} `a` must be less than `b`
* @throws {TypeError} options argument must be an object
* @throws {TypeError} must provide valid options
* @throws {Error} must provide a valid state
* @returns {RandomStream} Stream instance
*
* @example
* var inspectStream = require( '@stdlib/streams/utils/inspect' );
*
* function log( chunk ) {
*    console.log( chunk );
* }
*
* var opts = {
*     'iter': 10
* };
*
* var stream = new RandomStream( 2.0, 5.0, opts );
*
* stream.pipe( inspectStream( log )  );
*/
function RandomStream( a, b, options ) {
	var opts;
	var err;
	if ( !( this instanceof RandomStream ) ) {
		if ( arguments.length > 2 ) {
			return new RandomStream( a, b, options );
		}
		return new RandomStream( a, b );
	}
	if ( !isNumber( a ) || isnan( a ) ) {
		throw new TypeError( 'invalid argument. First argument must be a number primitive and not `NaN`. Value: `'+a+'`.' );
	}
	if ( !isNumber( b ) || isnan( b ) ) {
		throw new TypeError( 'invalid argument. Second argument must be a number primitive and not `NaN`. Value: `'+b+'`.' );
	}
	if ( a >= b ) {
		throw new RangeError( 'invalid argument. Minimum support `a` must be less than maximum support `b`. Value: `['+a+','+b+']`.');
	}
	opts = copy( DEFAULTS );
	if ( arguments.length > 2 ) {
		err = validate( opts, options );
		if ( err ) {
			throw err;
		}
	}
	// Make the stream a readable stream:
	debug( 'Creating a readable stream configured with the following options: %s.', JSON.stringify( opts ) );
	Readable.call( this, opts );

	// Destruction state:
	setNonEnumerable( this, '_destroyed', false );

	// Cache whether the stream is operating in object mode:
	setNonEnumerable( this, '_objectMode', opts.objectMode );

	// Cache the separator:
	setNonEnumerable( this, '_sep', opts.sep );

	// Initialize an iteration counter:
	setNonEnumerable( this, '_iter', 0 );

	// Create the underlying PRNG iterator:
	setNonEnumerableReadOnly( this, '_prng', rarcsine( a, b, opts ) );
	setReadOnly( this, 'PRNG', this._prng.PRNG );

	return this;
}

/*
* Inherit from the `Readable` prototype.
*/
inherit( RandomStream, Readable );

/**
* PRNG seed.
*
* @name seed
* @memberof RandomStream.prototype
* @type {Uint32Array}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seed', getSeed );

/**
* PRNG seed length.
*
* @name seedLength
* @memberof RandomStream.prototype
* @type {PositiveInteger}
*/
setReadOnlyAccessor( RandomStream.prototype, 'seedLength', getSeedLength );

/**
* PRNG state getter/setter.
*
* @name state
* @memberof RandomStream.prototype
* @type {Uint32Array}
* @throws {TypeError} must provide a `Uint32Array`
* @throws {Error} must provide a valid state
*/
setReadWriteAccessor( RandomStream.prototype, 'state', getState, setState );

/**
* PRNG state length.
*
* @name stateLength
* @memberof RandomStream.prototype
* @type {PositiveInteger}
*/
setReadOnlyAccessor( RandomStream.prototype, 'stateLength', getStateLength );

/**
* PRNG state size (in bytes).
*
* @name byteLength
* @memberof RandomStream.prototype
* @type {PositiveInteger}
*/
setReadOnlyAccessor( RandomStream.prototype, 'byteLength', getStateSize );

/**
* Implements the `_read` method.
*
* @private
* @name _read
* @memberof RandomStream.prototype
* @type {Function}
* @param {number} size - number (of bytes) to read
* @returns {void}
*/
defineProperty( RandomStream.prototype, '_read', {
	'configurable': false,
	'enumerable': false,
	'writable': false,
	'value': read
});

/**
* Gracefully destroys a stream, providing backwards compatibility.
*
* @name destroy
* @memberof RandomStream.prototype
* @type {Function}
* @param {(string|Object|Error)} [error] - error
* @returns {RandomStream} Stream instance
*/
defineProperty( RandomStream.prototype, 'destroy', {
	'configurable': false,
	'enumerable': false,
	'writable': false,
	'value': destroy
});

// EXPORTS //

module.exports = RandomStream;
<|endoftext|>