<commit_before>/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd

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";

/** @module interactive-auth */
const q = require("q");
const url = require("url");

const utils = require("./utils");

const EMAIL_STAGE_TYPE = "m.login.email.identity";
const MSISDN_STAGE_TYPE = "m.login.msisdn";

/**
 * Abstracts the logic used to drive the interactive auth process.
 *
 *
Components implementing an interactive auth flow should instantiate one of
 * these, passing in the necessary callbacks to the constructor. They should
 * then call attemptAuth, which will return a promise which will resolve or
 * reject when the interactive-auth process completes.
 *
 *
Meanwhile, calls will be made to the startAuthStage and doRequest
 * callbacks, and information gathered from the user can be submitted with
 * submitAuthDict.
 *
 * @constructor
 * @alias module:interactive-auth
 *
 * @param {object} opts  options object
 *
 * @param {object} opts.matrixClient A matrix client to use for the auth process
 *
 * @param {object?} opts.authData error response from the last request. If
 *    null, a request will be made with no auth before starting.
 *
 * @param {function(object?): module:client.Promise} opts.doRequest
 *     called with the new auth dict to submit the request. Should return a
 *     promise which resolves to the successful response or rejects with a
 *     MatrixError.
 *
 * @param {function(string, object?)} opts.stateUpdated
 *     called when the status of the UI auth changes, ie. when the state of
 *     an auth stage changes of when the auth flow moves to a new stage.
 *     The arguments are: the login type (eg m.login.password); and an object
 *     which is either an error or an informational object specific to the
 *     login type. If the 'errcode' key is defined, the object is an error,
 *     and has keys:
 *         errcode: string, the textual error code, eg. M_UNKNOWN
 *         error: string, human readable string describing the error
 *
 *     The login type specific objects are as follows:
 *         m.login.email.identity:
 *          * emailSid: string, the sid of the active email auth session
 *
 * @param {object?} opts.inputs Inputs provided by the user and used by different
 *     stages of the auto process. The inputs provided will affect what flow is chosen.
 *
 * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
 *     using email verification will be chosen.
 *
 * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
 *     the country that opts.phoneNumber should be resolved relative to.
 *
 * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
 *     using phone number validation will be chosen.
 *
 * @param {string?} opts.sessionId If resuming an existing interactive auth session,
 *     the sessionId of that session.
 *
 * @param {string?} opts.clientSecret If resuming an existing interactive auth session,
 *     the client secret for that session
 *
 * @param {string?} opts.emailSid If returning from having completed m.login.email.identity
 *     auth, the sid for the email verification session.
 *
 */
function InteractiveAuth(opts) {
    this._matrixClient = opts.matrixClient;
    this._data = opts.authData || {};
    this._requestCallback = opts.doRequest;
    // startAuthStage included for backwards compat
    this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
    this._completionDeferred = null;
    this._inputs = opts.inputs || {};

    if (opts.sessionId) this._data.session = opts.sessionId;
    this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
    this._emailSid = opts.emailSid;
    if (this._emailSid === undefined) this._emailSid = null;

    this._currentStage = null;
}

InteractiveAuth.prototype = {
    /**
     * begin the authentication process.
     *
     * @return {module:client.Promise}  which resolves to the response on success,
     * or rejects with the error on failure.
     */
    attemptAuth: function() {
        this._completionDeferred = q.defer();

        // if we have no flows, try a request (we'll have
        // just a session ID in _data if resuming)
        if (!this._data.flows) {
            this._doRequest(this._data);
        } else {
            this._startNextAuthStage();
        }

        return this._completionDeferred.promise;
    },

    /**
     * Poll to check if the auth session or current stage has been
     * completed out-of-band. If so, the attemptAuth promise will
     * be resolved.
     */
    poll: function() {
        if (!this._data.session) return;

        let authDict = {};
        if (this._currentStage == EMAIL_STAGE_TYPE) {
            // The email can be validated out-of-band, but we need to provide the
            // creds so the HS can go & check it.
            if (this._emailSid) {
                const idServerParsedUrl = url.parse(
                    this._matrixClient.getIdentityServerUrl(),
                );
                authDict = {
                    type: EMAIL_STAGE_TYPE,
                    threepid_creds: {
                        sid: this._emailSid,
                        client_secret: this._clientSecret,
                        id_server: idServerParsedUrl.host,
                    },
                };
            }
        }

        this.submitAuthDict(authDict, true);
    },

    /**
     * get the auth session ID
     *
     * @return {string} session id
     */
    getSessionId: function() {
        return this._data ? this._data.session : undefined;
    },

    getClientSecret: function() {
        return this._clientSecret;
    },

    /**
     * get the server params for a given stage
     *
     * @param {string} loginType login type for the stage
     * @return {object?} any parameters from the server for this stage
     */
    getStageParams: function(loginType) {
        let params = {};
        if (this._data && this._data.params) {
            params = this._data.params;
        }
        return params[loginType];
    },

    /**
     * submit a new auth dict and fire off the request. This will either
     * make attemptAuth resolve/reject, or cause the startAuthStage callback
     * to be called for a new stage.
     *
     * @param {object} authData new auth dict to send to the server. Should
     *    include a `type` propterty denoting the login type, as well as any
     *    other params for that stage.
     * @param {bool} ignoreFailure If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    submitAuthDict: function(authData, ignoreFailure) {
        if (!this._completionDeferred) {
            throw new Error("submitAuthDict() called before attemptAuth()");
        }

        // use the sessionid from the last request.
        const auth = {
            session: this._data.session,
        };
        utils.extend(auth, authData);

        this._doRequest(auth, ignoreFailure);
    },

    setEmailSid: function(sid) {
        this._emailSid = sid;
    },

    /**
     * Fire off a request, and either resolve the promise, or call
     * startAuthStage.
     *
     * @private
     * @param {object?} auth new auth dict, including session id
     * @param {bool?} ignoreFailure If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    _doRequest: function(auth, ignoreFailure) {
        const self = this;

        // hackery to make sure that synchronous exceptions end up in the catch
        // handler (without the additional event loop entailed by q.fcall or an
        // extra q().then)
        let prom;
        try {
            prom = this._requestCallback(auth);
        } catch (e) {
            prom = q.reject(e);
        }

        prom = prom.then(
            function(result) {
                console.log("result from request: ", result);
                self._completionDeferred.resolve(result);
            }, function(error) {
                // sometimes UI auth errors don't come with flows
                const errorFlows = error.data ? error.data.flows : null;
                const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows);
                if (error.httpStatus !== 401 || !error.data || !haveFlows) {
                    // doesn't look like an interactive-auth failure. fail the whole lot.
                    throw error;
                }
                // if the error didn't come with flows or session ID,
                // copy over the ones we have
                if (!error.data.flows) error.data.flows = self._data.flows;
                if (!error.data.session) error.data.session = self._data.session;
                self._data = error.data;
                self._startNextAuthStage();
            },
        );
        if (!ignoreFailure) {
            prom = prom.catch(this._completionDeferred.reject);
        } else {
            // We ignore all failures here (even non-UI auth related ones)
            // since we don't want to suddenly fail if the internet connection
            // had a blip whilst we were polling
            prom = prom.catch((error) => {
                console.log("Ignoring error from UI auth: " + error);
            });
        }
        prom.done();
    },

    /**
     * Pick the next stage and call the callback
     *
     * @private
     */
    _startNextAuthStage: function() {
        const nextStage = this._chooseStage();
        if (!nextStage) {
            throw new Error("No incomplete flows from the server");
        }
        this._currentStage = nextStage;

        if (this._data.errcode || this._data.error) {
            this._stateUpdatedCallback(nextStage, {
                errcode: this._data.errcode || "",
                error: this._data.error || "",
            });
            return;
        }

        const stageStatus = {};
        if (nextStage == EMAIL_STAGE_TYPE) {
            stageStatus.emailSid = this._emailSid;
        }
        this._stateUpdatedCallback(nextStage, stageStatus);
    },

    /**
     * Pick the next auth stage
     *
     * @private
     * @return {string?} login type
     */
    _chooseStage: function() {
        const flow = this._chooseFlow();
        console.log("Active flow => %s", JSON.stringify(flow));
        const nextStage = this._firstUncompletedStage(flow);
        console.log("Next stage: %s", nextStage);
        return nextStage;
    },

    /**
     * Pick one of the flows from the returned list
     * If a flow using all of the inputs is found, it will
     * be returned, otherwise, null will be returned.
     *
     * Only flows using all given inputs are chosen because it
     * is likley to be surprising if the user provides a
     * credential and it is not used. For example, for registration,
     * this could result in the email not being used which would leave
     * the account with no means to reset a password.
     *
     * @private
     * @return {object} flow
     */
    _chooseFlow: function() {
        const flows = this._data.flows || [];

        // we've been given an email or we've already done an email part
        const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
        const haveMsisdn = (
            Boolean(this._inputs.phoneCountry) &&
            Boolean(this._inputs.phoneNumber)
        );

        for (const flow of flows) {
            let flowHasEmail = false;
            let flowHasMsisdn = false;
            for (const stage of flow.stages) {
                if (stage === EMAIL_STAGE_TYPE) {
                    flowHasEmail = true;
                } else if (stage == MSISDN_STAGE_TYPE) {
                    flowHasMsisdn = true;
                }
            }

            if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
                return flow;
            }
        }
        return null;
    },

    /**
     * Get the first uncompleted stage in the given flow
     *
     * @private
     * @param {object} flow
     * @return {string} login type
     */
    _firstUncompletedStage: function(flow) {
        const completed = (this._data || {}).completed || [];
        for (let i = 0; i < flow.stages.length; ++i) {
            const stageType = flow.stages[i];
            if (completed.indexOf(stageType) === -1) {
                return stageType;
            }
        }
    },
};

/** */
module.exports = InteractiveAuth;
<commit_msg>More docs<commit_after>/*
Copyright 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd

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";

/** @module interactive-auth */
const q = require("q");
const url = require("url");

const utils = require("./utils");

const EMAIL_STAGE_TYPE = "m.login.email.identity";
const MSISDN_STAGE_TYPE = "m.login.msisdn";

/**
 * Abstracts the logic used to drive the interactive auth process.
 *
 *
Components implementing an interactive auth flow should instantiate one of
 * these, passing in the necessary callbacks to the constructor. They should
 * then call attemptAuth, which will return a promise which will resolve or
 * reject when the interactive-auth process completes.
 *
 *
Meanwhile, calls will be made to the startAuthStage and doRequest
 * callbacks, and information gathered from the user can be submitted with
 * submitAuthDict.
 *
 * @constructor
 * @alias module:interactive-auth
 *
 * @param {object} opts  options object
 *
 * @param {object} opts.matrixClient A matrix client to use for the auth process
 *
 * @param {object?} opts.authData error response from the last request. If
 *    null, a request will be made with no auth before starting.
 *
 * @param {function(object?): module:client.Promise} opts.doRequest
 *     called with the new auth dict to submit the request. Should return a
 *     promise which resolves to the successful response or rejects with a
 *     MatrixError.
 *
 * @param {function(string, object?)} opts.stateUpdated
 *     called when the status of the UI auth changes, ie. when the state of
 *     an auth stage changes of when the auth flow moves to a new stage.
 *     The arguments are: the login type (eg m.login.password); and an object
 *     which is either an error or an informational object specific to the
 *     login type. If the 'errcode' key is defined, the object is an error,
 *     and has keys:
 *         errcode: string, the textual error code, eg. M_UNKNOWN
 *         error: string, human readable string describing the error
 *
 *     The login type specific objects are as follows:
 *         m.login.email.identity:
 *          * emailSid: string, the sid of the active email auth session
 *
 * @param {object?} opts.inputs Inputs provided by the user and used by different
 *     stages of the auto process. The inputs provided will affect what flow is chosen.
 *
 * @param {string?} opts.inputs.emailAddress An email address. If supplied, a flow
 *     using email verification will be chosen.
 *
 * @param {string?} opts.inputs.phoneCountry An ISO two letter country code. Gives
 *     the country that opts.phoneNumber should be resolved relative to.
 *
 * @param {string?} opts.inputs.phoneNumber A phone number. If supplied, a flow
 *     using phone number validation will be chosen.
 *
 * @param {string?} opts.sessionId If resuming an existing interactive auth session,
 *     the sessionId of that session.
 *
 * @param {string?} opts.clientSecret If resuming an existing interactive auth session,
 *     the client secret for that session
 *
 * @param {string?} opts.emailSid If returning from having completed m.login.email.identity
 *     auth, the sid for the email verification session.
 *
 */
function InteractiveAuth(opts) {
    this._matrixClient = opts.matrixClient;
    this._data = opts.authData || {};
    this._requestCallback = opts.doRequest;
    // startAuthStage included for backwards compat
    this._stateUpdatedCallback = opts.stateUpdated || opts.startAuthStage;
    this._completionDeferred = null;
    this._inputs = opts.inputs || {};

    if (opts.sessionId) this._data.session = opts.sessionId;
    this._clientSecret = opts.clientSecret || this._matrixClient.generateClientSecret();
    this._emailSid = opts.emailSid;
    if (this._emailSid === undefined) this._emailSid = null;

    this._currentStage = null;
}

InteractiveAuth.prototype = {
    /**
     * begin the authentication process.
     *
     * @return {module:client.Promise}  which resolves to the response on success,
     * or rejects with the error on failure.
     */
    attemptAuth: function() {
        this._completionDeferred = q.defer();

        // if we have no flows, try a request (we'll have
        // just a session ID in _data if resuming)
        if (!this._data.flows) {
            this._doRequest(this._data);
        } else {
            this._startNextAuthStage();
        }

        return this._completionDeferred.promise;
    },

    /**
     * Poll to check if the auth session or current stage has been
     * completed out-of-band. If so, the attemptAuth promise will
     * be resolved.
     */
    poll: function() {
        if (!this._data.session) return;

        let authDict = {};
        if (this._currentStage == EMAIL_STAGE_TYPE) {
            // The email can be validated out-of-band, but we need to provide the
            // creds so the HS can go & check it.
            if (this._emailSid) {
                const idServerParsedUrl = url.parse(
                    this._matrixClient.getIdentityServerUrl(),
                );
                authDict = {
                    type: EMAIL_STAGE_TYPE,
                    threepid_creds: {
                        sid: this._emailSid,
                        client_secret: this._clientSecret,
                        id_server: idServerParsedUrl.host,
                    },
                };
            }
        }

        this.submitAuthDict(authDict, true);
    },

    /**
     * get the auth session ID
     *
     * @return {string} session id
     */
    getSessionId: function() {
        return this._data ? this._data.session : undefined;
    },

    /**
     * get the client secret used for validation sessions
     * with the ID server.
     *
     * @return {string} client secret
     */
    getClientSecret: function() {
        return this._clientSecret;
    },

    /**
     * get the server params for a given stage
     *
     * @param {string} loginType login type for the stage
     * @return {object?} any parameters from the server for this stage
     */
    getStageParams: function(loginType) {
        let params = {};
        if (this._data && this._data.params) {
            params = this._data.params;
        }
        return params[loginType];
    },

    /**
     * submit a new auth dict and fire off the request. This will either
     * make attemptAuth resolve/reject, or cause the startAuthStage callback
     * to be called for a new stage.
     *
     * @param {object} authData new auth dict to send to the server. Should
     *    include a `type` propterty denoting the login type, as well as any
     *    other params for that stage.
     * @param {bool} ignoreFailure If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    submitAuthDict: function(authData, ignoreFailure) {
        if (!this._completionDeferred) {
            throw new Error("submitAuthDict() called before attemptAuth()");
        }

        // use the sessionid from the last request.
        const auth = {
            session: this._data.session,
        };
        utils.extend(auth, authData);

        this._doRequest(auth, ignoreFailure);
    },

    /**
     * Sets the sid for the email validation session
     * This must be set in order to successfully poll for completion
     * of the email validation.
     * Specific to m.login.email.identity
     */
    setEmailSid: function(sid) {
        this._emailSid = sid;
    },

    /**
     * Fire off a request, and either resolve the promise, or call
     * startAuthStage.
     *
     * @private
     * @param {object?} auth new auth dict, including session id
     * @param {bool?} ignoreFailure If true, this request failing will not result
     *    in the attemptAuth promise being rejected. This can be set to true
     *    for requests that just poll to see if auth has been completed elsewhere.
     */
    _doRequest: function(auth, ignoreFailure) {
        const self = this;

        // hackery to make sure that synchronous exceptions end up in the catch
        // handler (without the additional event loop entailed by q.fcall or an
        // extra q().then)
        let prom;
        try {
            prom = this._requestCallback(auth);
        } catch (e) {
            prom = q.reject(e);
        }

        prom = prom.then(
            function(result) {
                console.log("result from request: ", result);
                self._completionDeferred.resolve(result);
            }, function(error) {
                // sometimes UI auth errors don't come with flows
                const errorFlows = error.data ? error.data.flows : null;
                const haveFlows = Boolean(self._data.flows) || Boolean(errorFlows);
                if (error.httpStatus !== 401 || !error.data || !haveFlows) {
                    // doesn't look like an interactive-auth failure. fail the whole lot.
                    throw error;
                }
                // if the error didn't come with flows or session ID,
                // copy over the ones we have
                if (!error.data.flows) error.data.flows = self._data.flows;
                if (!error.data.session) error.data.session = self._data.session;
                self._data = error.data;
                self._startNextAuthStage();
            },
        );
        if (!ignoreFailure) {
            prom = prom.catch(this._completionDeferred.reject);
        } else {
            // We ignore all failures here (even non-UI auth related ones)
            // since we don't want to suddenly fail if the internet connection
            // had a blip whilst we were polling
            prom = prom.catch((error) => {
                console.log("Ignoring error from UI auth: " + error);
            });
        }
        prom.done();
    },

    /**
     * Pick the next stage and call the callback
     *
     * @private
     */
    _startNextAuthStage: function() {
        const nextStage = this._chooseStage();
        if (!nextStage) {
            throw new Error("No incomplete flows from the server");
        }
        this._currentStage = nextStage;

        if (this._data.errcode || this._data.error) {
            this._stateUpdatedCallback(nextStage, {
                errcode: this._data.errcode || "",
                error: this._data.error || "",
            });
            return;
        }

        const stageStatus = {};
        if (nextStage == EMAIL_STAGE_TYPE) {
            stageStatus.emailSid = this._emailSid;
        }
        this._stateUpdatedCallback(nextStage, stageStatus);
    },

    /**
     * Pick the next auth stage
     *
     * @private
     * @return {string?} login type
     */
    _chooseStage: function() {
        const flow = this._chooseFlow();
        console.log("Active flow => %s", JSON.stringify(flow));
        const nextStage = this._firstUncompletedStage(flow);
        console.log("Next stage: %s", nextStage);
        return nextStage;
    },

    /**
     * Pick one of the flows from the returned list
     * If a flow using all of the inputs is found, it will
     * be returned, otherwise, null will be returned.
     *
     * Only flows using all given inputs are chosen because it
     * is likley to be surprising if the user provides a
     * credential and it is not used. For example, for registration,
     * this could result in the email not being used which would leave
     * the account with no means to reset a password.
     *
     * @private
     * @return {object} flow
     */
    _chooseFlow: function() {
        const flows = this._data.flows || [];

        // we've been given an email or we've already done an email part
        const haveEmail = Boolean(this._inputs.emailAddress) || Boolean(this._emailSid);
        const haveMsisdn = (
            Boolean(this._inputs.phoneCountry) &&
            Boolean(this._inputs.phoneNumber)
        );

        for (const flow of flows) {
            let flowHasEmail = false;
            let flowHasMsisdn = false;
            for (const stage of flow.stages) {
                if (stage === EMAIL_STAGE_TYPE) {
                    flowHasEmail = true;
                } else if (stage == MSISDN_STAGE_TYPE) {
                    flowHasMsisdn = true;
                }
            }

            if (flowHasEmail == haveEmail && flowHasMsisdn == haveMsisdn) {
                return flow;
            }
        }
        return null;
    },

    /**
     * Get the first uncompleted stage in the given flow
     *
     * @private
     * @param {object} flow
     * @return {string} login type
     */
    _firstUncompletedStage: function(flow) {
        const completed = (this._data || {}).completed || [];
        for (let i = 0; i < flow.stages.length; ++i) {
            const stageType = flow.stages[i];
            if (completed.indexOf(stageType) === -1) {
                return stageType;
            }
        }
    },
};

/** */
module.exports = InteractiveAuth;
<|endoftext|>


<commit_before>describe("Cyllene", function() {
    describe("variable substitution", function() {
        it("replaces placeholders with assigned values", function() {
            var template = new Cyllene("Good evening, {{name}}. {{message}}.");
            var locals = { name: "Daniel", message: "I've been expecting you" };
            expect(template.render(locals)).toEqual("Good evening, Daniel. I've been expecting you.");
        });

        it("escapes values in double curly brackets", function() {
            var template = new Cyllene("Harmless {{comment}}");
            var locals = { comment: 'opinion' };
            expect(template.render(locals)).toEqual('Harmless <b onclick="dojs();">opinion</b>');
        });

        it("does not escape values in triple curly brackets", function() {
            var template = new Cyllene("Hello {{{greeting}}}");
            var locals = { greeting: 'world!.' };
            expect(template.render(locals)).toEqual('Hello world!.');
        });
    });

    describe("code execution", function() {
        it("handles one liners", function() {
            var template = new Cyllene("And then he said: `{{ greeting.say() }}`.");
            var locals = {
                greeting: {
                    say: function() { return "hello"; }
                }
            };
            expect(template.render(locals)).toEqual("And then he said: `hello`.");
        });

        describe("blocks", function() {
            var template;

            beforeEach(function() {
                template = new Cyllene(" \
                    {% if(currentUser.state == 'banished'): %} \
                        You're not allowed to view this page.\
                    {% else if(currentUser.state == 'unapproved'): %} \
                        Account pending approval. \
                    {% else: %} \
                        Welcome back {{ currentUser.name }}.\
                    {% endif; %}\
                ");
            });

            it("output contents in current context", function() {
                var locals = {
                    currentUser: {
                        state: "banished"
                    }
                };
                expect(template.render(locals).trim()).toEqual("You're not allowed to view this page.");
            });

            it("handles else if statements", function() {
                var locals = {
                    currentUser: {
                        state: "unapproved"
                    }
                };
                expect(template.render(locals).trim()).toEqual("Account pending approval.");
            });

            it("handles mixed expressions", function() {
                var locals = {
                    currentUser: {
                        state: "active",
                        name: "Daniel"
                    }
                };
                expect(template.render(locals).trim()).toEqual("Welcome back Daniel.");
            });
        });
    });
});
<commit_msg>Test helper support<commit_after>describe("Cyllene", function() {
    describe("variable substitution", function() {
        it("replaces placeholders with assigned values", function() {
            var template = new Cyllene("Good evening, {{name}}. {{message}}.");
            var locals = { name: "Daniel", message: "I've been expecting you" };
            expect(template.render(locals)).toEqual("Good evening, Daniel. I've been expecting you.");
        });

        it("escapes values in double curly brackets", function() {
            var template = new Cyllene("Harmless {{comment}}");
            var locals = { comment: 'opinion' };
            expect(template.render(locals)).toEqual('Harmless <b onclick="dojs();">opinion</b>');
        });

        it("does not escape values in triple curly brackets", function() {
            var template = new Cyllene("Hello {{{greeting}}}");
            var locals = { greeting: 'world!.' };
            expect(template.render(locals)).toEqual('Hello world!.');
        });
    });

    describe("code execution", function() {
        it("handles one liners", function() {
            var template = new Cyllene("And then he said: `{{ greeting.say() }}`.");
            var locals = {
                greeting: {
                    say: function() { return "hello"; }
                }
            };
            expect(template.render(locals)).toEqual("And then he said: `hello`.");
        });

        describe("blocks", function() {
            var template;

            beforeEach(function() {
                template = new Cyllene(" \
                    {% if(currentUser.state == 'banished'): %} \
                        You're not allowed to view this page.\
                    {% else if(currentUser.state == 'unapproved'): %} \
                        Account pending approval. \
                    {% else: %} \
                        Welcome back {{ currentUser.name }}.\
                    {% endif; %}\
                ");
            });

            it("output contents in current context", function() {
                var locals = {
                    currentUser: {
                        state: "banished"
                    }
                };
                expect(template.render(locals).trim()).toEqual("You're not allowed to view this page.");
            });

            it("handles else if statements", function() {
                var locals = {
                    currentUser: {
                        state: "unapproved"
                    }
                };
                expect(template.render(locals).trim()).toEqual("Account pending approval.");
            });

            it("handles mixed expressions", function() {
                var locals = {
                    currentUser: {
                        state: "active",
                        name: "Daniel"
                    }
                };
                expect(template.render(locals).trim()).toEqual("Welcome back Daniel.");
            });
        });
    });

    describe("helper", function() {
        beforeEach(function() {
            Cyllene.helpers.capitalize = function(text) {
                return text.charAt(0).toUpperCase() + text.slice(1);
            };
        });

        afterEach(function() {
            delete Cyllene.helpers.capitalize;
        });

        it("is applied within the template", function() {
            var template = new Cyllene("Welcome back {{ capitalize(name) }}.");
            var locals = { name: "daniel" };
            expect(template.render(locals)).toEqual("Welcome back Daniel.");
        });
    });
});
<|endoftext|>


<commit_before>// @flow

interface Store {

  /**
   * @description Begin a transaction
   */
  begin(): Array<any>;

  /**
   * @description End a transaction
   */
  end(transaction: Array<any>, callback: () => void): any;

  /**
   * @description Cleans the whole storage
   */
  clean(callback: () => void): any;

  /**
   * @description Get contents from bucket's key
   */
  get(bucket: string, key: mixed, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets and returns a mapping of bucket to union
   */
  unions(bucket: Array<any>, keys: Array<any>, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets and returns a mapping of bucket to union
   */
  union(bucket: string, keys: Array<any>, callback: () => void): any;

  /**
   * @description Add values to a given key inside a bucket
   */
  add(transaction: Array<any>, bucket: string, key: string | number, values: string | number | Array<any>): any;

  /**
   * @description Delete given key(s) at the bucket
   */
  del(transaction: Array<any>, bucket: string, keys: string | Array<any>): any;

  /**
   * @description Removes values from a given key inside a bucket
   */
  remove(transaction: Array<any>, bucket: string, key: string | number, values: string | number | Array<any>): any;
}
<commit_msg>feat(interfaces/store.js) mixed type replace with string | number<commit_after>// @flow

interface Store {

  /**
   * @description Begin a transaction
   */
  begin(): Array<any>;

  /**
   * @description End a transaction
   */
  end(transaction: Array<any>, callback: () => void): any;

  /**
   * @description Cleans the whole storage
   */
  clean(callback: () => void): any;

  /**
   * @description Get contents from bucket's key
   */
  get(bucket: string, key: string | number, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets and returns a mapping of bucket to union
   */
  unions(bucket: Array<any>, keys: Array<any>, callback: () => void): any;

  /**
   * @description Get union of contents of the specified keys in each of the specified buckets and returns a mapping of bucket to union
   */
  union(bucket: string, keys: Array<any>, callback: () => void): any;

  /**
   * @description Add values to a given key inside a bucket
   */
  add(transaction: Array<any>, bucket: string, key: string | number, values: string | number | Array<any>): any;

  /**
   * @description Delete given key(s) at the bucket
   */
  del(transaction: Array<any>, bucket: string, keys: string | Array<any>): any;

  /**
   * @description Removes values from a given key inside a bucket
   */
  remove(transaction: Array<any>, bucket: string, key: string | number, values: string | number | Array<any>): any;
}
<|endoftext|>


<commit_before>JARS.internal('Module', function moduleSetup(InternalsManager) {
    'use strict';

    var getInternal = InternalsManager.get,
        System = getInternal('System'),
        SourceManager = getInternal('SourceManager'),
        DependenciesResolver = getInternal('DependenciesResolver'),
        ModuleQueue = getInternal('ModuleQueue'),
        ModuleDependencies = getInternal('ModuleDependencies'),
        ModuleBundle = getInternal('ModuleBundle'),
        ModuleConfig = getInternal('ModuleConfig'),
        ModuleLogger = getInternal('ModuleLogger'),
        ModuleState = getInternal('ModuleState'),
        SEPARATOR = '" -> "',
        MSG_RECOVERING = 'failed to load and tries to recover...',
        // Errors when module is aborted
        MSG_MODULE_ABORTED = 'given path "${path}" after ${sec} second(s) - file may not exist',
        MSG_MODULE_DEPENDENCY_ABORTED = 'dependency "${dep}"',
        MSG_MODULE_CIRCULAR_DEPENDENCIES_ABORTED = 'circular dependencies "${deps}"';

    /**
     * @callback FactoryCallback
     *
     * @memberof JARS.internals.Module
     *
     * @param {...*} dependencyRefs
     *
     * @return {*}
     */

    /**
     * @class
     *
     * @memberof JARS.internals
     *
     * @param {JARS.internals.Loader} loader
     * @param {string} moduleName
     * @param {boolean} [isRoot=false]
     */
    function Module(loader, moduleName, isRoot) {
        var module = this,
            dependencies, bundleConfig, logger, state, parent;

        module.loader = loader;
        module.name = moduleName;
        module.isRoot = isRoot || false;

        module.logger = logger = new ModuleLogger(moduleName);
        module.state = state = new ModuleState(logger);
        module.queue = new ModuleQueue(moduleName, state);

        module.deps = dependencies = new ModuleDependencies(module, logger);

        parent = dependencies.parent;
        module.bundle = new ModuleBundle(module, parent && parent.bundle.config);
        bundleConfig = module.bundle.config;
        module.config = module.isRoot ? bundleConfig : new ModuleConfig(module, bundleConfig);
    }

    Module.prototype = {
        constructor: Module,
        /**
         * @param {string} [fileType]
         *
         * @return {string}
         */
        getFullPath: function(fileType) {
            var module = this,
                config = module.config,
                cache = config.get('cache') ? '' : '?_=' + new Date().getTime(),
                path = config.get('basePath') + config.get('dirPath') + config.get('versionDir'),
                fileName = config.get('fileName') + config.get('minified') + (fileType || config.get('extension')) + cache;

            return path + fileName;
        },

        load: function() {
            var module = this;

            module.setupAutoAbort();

            SourceManager.loadSource(module.name, module.getFullPath());
        },
        /**
         * @param {JARS.internals.ModuleQueue.SuccessCallback} onModuleLoaded
         * @param {JARS.internals.ModuleQueue.FailCallback} onModuleAborted
         */
        request: function(onModuleLoaded, onModuleAborted) {
            var module = this;

            if (module.state.trySetRequested({
                path: module.getFullPath()
            })) {
                module.load();
            }

            module.queue.add(onModuleLoaded, onModuleAborted);
        },
        /**
         * @return {boolean}
         */
        findRecover: function() {
            var module = this,
                loader = module.loader,
                moduleName = module.name,
                nextRecover = module.nextRecover,
                foundRecover = nextRecover === false ? nextRecover : module.config.get('recover', nextRecover),
                recoverModuleName, parent;

            if (foundRecover) {
                recoverModuleName = foundRecover.restrict;

                // This is a recover on a higher level
                if (recoverModuleName !== moduleName) {
                    parent = loader.getModule(recoverModuleName).deps.parent;
                    // extract the next recovermodule
                    module.nextRecover = parent ? parent.name : false;

                    // Only recover this module
                    foundRecover.restrict = moduleName;
                }

                module.updateConfig(foundRecover);

                // Restore module recover association
                foundRecover.restrict = recoverModuleName;

                module.logger.warn(MSG_RECOVERING);

                module.load();
            }
            else {
                module.nextRecover = false;
            }

            return !!foundRecover;
        },
        /**
         * @param {(string|string[])} [dependencyOrArray]
         */
        abort: function(dependencyOrArray) {
            var module = this,
                state = module.state,
                isRegistered = state.isRegistered(),
                isDependenciesArray = System.isArray(dependencyOrArray),
                message;

            if (!module.isRoot && ((state.isLoading() && !module.findRecover()) || isRegistered)) {
                message = isRegistered ? (isDependenciesArray ? MSG_MODULE_CIRCULAR_DEPENDENCIES_ABORTED : MSG_MODULE_DEPENDENCY_ABORTED) : MSG_MODULE_ABORTED;

                state.setAborted(message, isRegistered ? (isDependenciesArray ? {
                    deps: dependencyOrArray.join(SEPARATOR)
                } : {
                    dep: dependencyOrArray
                }) : {
                    path: SourceManager.removeSource(module.name),

                    sec: module.config.get('timeout')
                });

                module.queue.notifyError();
            }
        },

        setupAutoAbort: function() {
            var module = this;

            module.timeoutID = System.env.global.setTimeout(function abortModule() {
                module.abort();
            }, module.config.get('timeout') * 1000);
        },

        clearAutoAbort: function() {
            var module = this;

            module.timeoutID && System.env.global.clearTimeout(module.timeoutID);
        },
        /**
         * @param {JARS.internals.ModuleDependencies.Declaration} dependencies
         */
        $import: function(dependencies) {
            var module = this;

            if (!module.state.isRegistered()) {
                module.deps.add(dependencies);
            }
        },
        /**
         * @param {JARS.internals.Module.FactoryCallback} factory
         */
        $export: function(factory) {
            var module = this,
                state = module.state,
                dependencies = module.deps,
                loader = module.loader,
                moduleName = module.name,
                parentRef;

            if (state.trySetRegistered()) {
                module.clearAutoAbort();

                if(!module.isRoot && module.config.get('checkCircularDeps') && dependencies.hasCircular()) {
                    module.abort(dependencies.getCircular());
                }
                else {
                    dependencies.request(function onDependenciesLoaded(dependencyRefs) {
                        if (state.isRegistered() && !state.isLoaded()) {
                            if(module.isRoot) {
                                module.ref = {};
                            }
                            else {
                                parentRef = dependencyRefs.shift();

                                loader.setCurrentModuleName(moduleName);

                                module.ref = parentRef[DependenciesResolver.removeParentName(moduleName)] = factory ? factory.apply(parentRef, dependencyRefs) || {} : {};

                                loader.setCurrentModuleName();
                            }

                            state.setLoaded();
                            module.queue.notify();
                        }
                    });
                }
            }
        },
        /**
         * @param {JARS.internals.ModuleBundle.Declaration} bundleModules
         */
        defineBundle: function(bundleModules) {
            this.bundle.add(bundleModules);
        }
    };

    return Module;
});
<commit_msg>Remove duplicate circular dependencies check<commit_after>JARS.internal('Module', function moduleSetup(InternalsManager) {
    'use strict';

    var getInternal = InternalsManager.get,
        System = getInternal('System'),
        SourceManager = getInternal('SourceManager'),
        DependenciesResolver = getInternal('DependenciesResolver'),
        ModuleQueue = getInternal('ModuleQueue'),
        ModuleDependencies = getInternal('ModuleDependencies'),
        ModuleBundle = getInternal('ModuleBundle'),
        ModuleConfig = getInternal('ModuleConfig'),
        ModuleLogger = getInternal('ModuleLogger'),
        ModuleState = getInternal('ModuleState'),
        SEPARATOR = '" -> "',
        MSG_RECOVERING = 'failed to load and tries to recover...',
        // Errors when module is aborted
        MSG_MODULE_ABORTED = 'given path "${path}" after ${sec} second(s) - file may not exist',
        MSG_MODULE_DEPENDENCY_ABORTED = 'dependency "${dep}"',
        MSG_MODULE_CIRCULAR_DEPENDENCIES_ABORTED = 'circular dependencies "${deps}"';

    /**
     * @callback FactoryCallback
     *
     * @memberof JARS.internals.Module
     *
     * @param {...*} dependencyRefs
     *
     * @return {*}
     */

    /**
     * @class
     *
     * @memberof JARS.internals
     *
     * @param {JARS.internals.Loader} loader
     * @param {string} moduleName
     * @param {boolean} [isRoot=false]
     */
    function Module(loader, moduleName, isRoot) {
        var module = this,
            dependencies, bundleConfig, logger, state, parent;

        module.loader = loader;
        module.name = moduleName;
        module.isRoot = isRoot || false;

        module.logger = logger = new ModuleLogger(moduleName);
        module.state = state = new ModuleState(logger);
        module.queue = new ModuleQueue(moduleName, state);

        module.deps = dependencies = new ModuleDependencies(module, logger);

        parent = dependencies.parent;
        module.bundle = new ModuleBundle(module, parent && parent.bundle.config);
        bundleConfig = module.bundle.config;
        module.config = module.isRoot ? bundleConfig : new ModuleConfig(module, bundleConfig);
    }

    Module.prototype = {
        constructor: Module,
        /**
         * @param {string} [fileType]
         *
         * @return {string}
         */
        getFullPath: function(fileType) {
            var module = this,
                config = module.config,
                cache = config.get('cache') ? '' : '?_=' + new Date().getTime(),
                path = config.get('basePath') + config.get('dirPath') + config.get('versionDir'),
                fileName = config.get('fileName') + config.get('minified') + (fileType || config.get('extension')) + cache;

            return path + fileName;
        },

        load: function() {
            var module = this;

            module.setupAutoAbort();

            SourceManager.loadSource(module.name, module.getFullPath());
        },
        /**
         * @param {JARS.internals.ModuleQueue.SuccessCallback} onModuleLoaded
         * @param {JARS.internals.ModuleQueue.FailCallback} onModuleAborted
         */
        request: function(onModuleLoaded, onModuleAborted) {
            var module = this;

            if (module.state.trySetRequested({
                path: module.getFullPath()
            })) {
                module.load();
            }

            module.queue.add(onModuleLoaded, onModuleAborted);
        },
        /**
         * @return {boolean}
         */
        findRecover: function() {
            var module = this,
                loader = module.loader,
                moduleName = module.name,
                nextRecover = module.nextRecover,
                foundRecover = nextRecover === false ? nextRecover : module.config.get('recover', nextRecover),
                recoverModuleName, parent;

            if (foundRecover) {
                recoverModuleName = foundRecover.restrict;

                // This is a recover on a higher level
                if (recoverModuleName !== moduleName) {
                    parent = loader.getModule(recoverModuleName).deps.parent;
                    // extract the next recovermodule
                    module.nextRecover = parent ? parent.name : false;

                    // Only recover this module
                    foundRecover.restrict = moduleName;
                }

                module.updateConfig(foundRecover);

                // Restore module recover association
                foundRecover.restrict = recoverModuleName;

                module.logger.warn(MSG_RECOVERING);

                module.load();
            }
            else {
                module.nextRecover = false;
            }

            return !!foundRecover;
        },
        /**
         * @param {(string|string[])} [dependencyOrArray]
         */
        abort: function(dependencyOrArray) {
            var module = this,
                state = module.state,
                isRegistered = state.isRegistered(),
                isDependenciesArray = System.isArray(dependencyOrArray),
                message;

            if (!module.isRoot && ((state.isLoading() && !module.findRecover()) || isRegistered)) {
                message = isRegistered ? (isDependenciesArray ? MSG_MODULE_CIRCULAR_DEPENDENCIES_ABORTED : MSG_MODULE_DEPENDENCY_ABORTED) : MSG_MODULE_ABORTED;

                state.setAborted(message, isRegistered ? (isDependenciesArray ? {
                    deps: dependencyOrArray.join(SEPARATOR)
                } : {
                    dep: dependencyOrArray
                }) : {
                    path: SourceManager.removeSource(module.name),

                    sec: module.config.get('timeout')
                });

                module.queue.notifyError();
            }
        },

        setupAutoAbort: function() {
            var module = this;

            module.timeoutID = System.env.global.setTimeout(function abortModule() {
                module.abort();
            }, module.config.get('timeout') * 1000);
        },

        clearAutoAbort: function() {
            var module = this;

            module.timeoutID && System.env.global.clearTimeout(module.timeoutID);
        },
        /**
         * @param {JARS.internals.ModuleDependencies.Declaration} dependencies
         */
        $import: function(dependencies) {
            var module = this;

            if (!module.state.isRegistered()) {
                module.deps.add(dependencies);
            }
        },
        /**
         * @param {JARS.internals.Module.FactoryCallback} factory
         */
        $export: function(factory) {
            var module = this,
                state = module.state,
                loader = module.loader,
                moduleName = module.name,
                parentRef;

            if (state.trySetRegistered()) {
                module.clearAutoAbort();

                module.deps.request(function onDependenciesLoaded(dependencyRefs) {
                    if (state.isRegistered() && !state.isLoaded()) {
                        if(module.isRoot) {
                            module.ref = {};
                        }
                        else {
                            parentRef = dependencyRefs.shift();

                            loader.setCurrentModuleName(moduleName);

                            module.ref = parentRef[DependenciesResolver.removeParentName(moduleName)] = factory ? factory.apply(parentRef, dependencyRefs) || {} : {};

                            loader.setCurrentModuleName();
                        }

                        state.setLoaded();
                        module.queue.notify();
                    }
                });
            }
        },
        /**
         * @param {JARS.internals.ModuleBundle.Declaration} bundleModules
         */
        defineBundle: function(bundleModules) {
            this.bundle.add(bundleModules);
        }
    };

    return Module;
});
<|endoftext|>


<commit_before>export default function() {

	return {
		user:
			{
				_id: '59824b41172824a3e8d0d5d6', //heroku
				name: 'Buddy Elf',
				email: 'testUser@nog.com',
				iconUrl: '../src/img/buddy_elf.png'
			}
	}
}

				// _id: '598246abbee2c891bd2cedc8', //local dev
				// name: 'SantaDev',
<commit_msg>add santa user test data<commit_after>export default function() {

	return {
		user:
			{
				_id: '59824b41172824a3e8d0d5d6', //heroku
				name: 'Buddy Elf',
				email: 'testUser@nog.com',
				iconUrl: '../src/img/buddy_elf.png'
			}
	}
}

				// _id: '598296cd172824a3e8d0d5e4', //heroku
				// name: 'Santa',
				// email: 'santa@nog.com',
				// iconUrl: '../src/img/Santa_profile.jpg'

				// _id: '598246abbee2c891bd2cedc8', //local dev
				// name: 'SantaDev',
<|endoftext|>


<commit_before>import { createAction, handleActions } from 'redux-actions';

// ------------------------------------
// Constants
// ------------------------------------
export const CREATE_PATIENT = 'CREATE_PATIENT';

// ------------------------------------
// Actions
// ------------------------------------
export const createPatient = createAction(
  CREATE_PATIENT,
  (patientName) => {
    return {patientName};
  }
);

export const actions = {
  createPatient
};

// ------------------------------------
// Reducer
// ------------------------------------
export default handleActions({
  [CREATE_PATIENT]: (state, action) => {
    console.log(action.payload.patientName);
    return [
      ...state,
      { name: action.payload.patientName }
    ];
  }
}, 1);
<commit_msg>Remove debug statement!<commit_after>import { createAction, handleActions } from 'redux-actions';

// ------------------------------------
// Constants
// ------------------------------------
export const CREATE_PATIENT = 'CREATE_PATIENT';

// ------------------------------------
// Actions
// ------------------------------------
export const createPatient = createAction(
  CREATE_PATIENT,
  (patientName) => {
    return {patientName};
  }
);

export const actions = {
  createPatient
};

// ------------------------------------
// Reducer
// ------------------------------------
export default handleActions({
  [CREATE_PATIENT]: (state, action) => {
    return [
      ...state,
      { name: action.payload.patientName }
    ];
  }
}, 1);
<|endoftext|>


<commit_before>// Listens for socket connections. Passes queries to streamer for monitoring.
// Watches for updates to sourceErrorCount

var express = require('express');
var http = require('http');
var socketIo = require('socket.io');
var passportSocketIo = require('passport.socketio');
var authentication = require('./authentication');
var _ = require('underscore');
var streamer = require('./streamer');
var Source = require('../../models/source');
var Query = require('../../models/query');
var ReportQuery = require('../../models/query/report-query');
var IncidentQuery = require('../../models/query/incident-query');
var SocketQueryGroup = require('./socket-query-group');
var fetchingController = require('./v1/fetching-controller');
var Trend = require('../../models/trend');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var logger = require('../logger');

// override the emit function to add logging
var emit = socketIo.Socket.prototype.emit;
socketIo.Socket.prototype.emit = function (event, data) {
  logger.debug(event, data);
  emit.apply(this, arguments);
}

var SocketHandler = function(app, server, auth) {
  this.app = app || express();
  this.server = server || http.createServer(app);
  this.auth = auth || authentication(app);

  this.queryGroups = {};

  this.io = socketIo.listen(this.server);
  this._configureSocketIO();

  var self = this;
  this.io.sockets.on('connection', function(socket) {
    self.clientQuery = null;
    self.emitAllErrorsCount(socket);

    self._streamerQueryListen('query', ReportQuery, socket);
    self._streamerQueryListen('incidentQuery', IncidentQuery, socket);

    self._streamerQueryCheck('reports', ReportQuery, socket);
    self._streamerQueryCheck('incidents', IncidentQuery, socket);

    self.streamerSocketForward('sourceErrorCountUpdated', socket);
    self.streamerSocketForward('reportStatusChanged', socket);
    self.streamerSocketForward('reportIncidentChanged', socket);
    self.streamerSocketForward('trend', socket);

    // Send fetching status to the client
    socket.emit('fetchingStatusUpdate', {fetching: false});
    fetchingController.on('fetching:start', function() {
      socket.emit('fetchingStatusUpdate', {fetching: true});
    });
    fetchingController.on('fetching:stop', function() {
      socket.emit('fetchingStatusUpdate', {fetching: false});
    });

    // Send source updates back to client
    self.on('sourceErrorCountUpdated', function() {
      self.emitAllErrorsCount(socket);
    });

    // Remove client from query list
    socket.on('disconnect', function() {
      self.removeClient(self.clientQuery, socket.id);
    });
  });
};

util.inherits(SocketHandler, EventEmitter);

// Listen for query events from client
SocketHandler.prototype._streamerQueryListen = function(event, QueryType, socket) {
  var self = this;

  socket.on(event, function(queryData) {
    // Remove client from prior query to avoid multiple streams
    self.removeClient(self.clientQuery, socket.id);
    // Instantiate and normalize client query
    var query = new QueryType(queryData);
    self.clientQuery = query.normalize();
    // Track query and add client as listener
    self.clientQuery.hash = self.addClient(query, socket.id);
  });
}

// Send data back to client for matching queries
SocketHandler.prototype._streamerQueryCheck = function(event, QueryType, socket) {
  var self = this;

  streamer.on(event, function(query, data) {
    var clientQuery = self.clientQuery;
    // Determine if current client query matches the query
    if (QueryType.compare(query, new QueryType(clientQuery)) &&
      self.queryGroups[clientQuery.hash] &&
      self.queryGroups[clientQuery.hash].has(socket.id)) {
      socket.emit(event, data);
    }
  });
}

SocketHandler.prototype.addListeners = function(type, emitter) {
  switch (type) {
    case 'sourceLocal':
      this._addSourceLocalListeners(emitter);
      break;
    case 'source':
      this._addSourceListeners(emitter);
      break;
    case 'trends':
      this._addTrendsListeners(emitter);
      break;
  }
};

// Forward streamer data directly to client
SocketHandler.prototype.streamerSocketForward = function(event, socket) {
  streamer.on(event, function(data) {
    socket.emit(event, data);
  });
};

// Add a client as a listener to a query
SocketHandler.prototype.addClient = function(query, id) {
  if (!query || query === {}) return;
  var hash = query.hash || Query.hash(query);
  // Store a list of clients listening to each query
  if (!_.has(this.queryGroups, hash)) {
    this.queryGroups[hash] = new SocketQueryGroup(query, id);
    // Track query in streamer
    streamer.addQuery(query);
  } else {
    this.queryGroups[hash].add(id);
  }
  return hash;
};

// Remove a client from listening to queries
SocketHandler.prototype.removeClient = function(query, id) {
  if (!query || !query.hash || !_.has(this.queryGroups, query.hash)) return;
  this.queryGroups[query.hash].remove(id);
  // Destroy query if no clients are listening
  if (this.queryGroups[query.hash].isEmpty()) {
    delete this.queryGroups[query.hash];
    streamer.removeQuery(query);
  }
};

SocketHandler.prototype.emitAllErrorsCount = function(emitter) {
  // Send total error counts on client connect
  Source.countAllErrors(function(err, count) {
    if (!err) emitter.emit('sourceErrorCountUpdated', {unreadErrorCount: count});
  });
};

SocketHandler.prototype._configureSocketIO = function() {
  var self = this;
  var io = this.io;
  io.configure(function() {
    io.enable('browser client minification');
    io.enable('browser client etag');
    io.enable('browser client gzip');
    io.set('log level', 1);
    // enable all transports (optional if you want flashsocket support, please note that some hosting
    // providers do not allow you to create servers that listen on a port different than 80 or their
    // default port)
    io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);
  });

  // Authorize sockets
  io.set('authorization', passportSocketIo.authorize({
    cookieParser: express.cookieParser,
    key: self.auth.key,
    secret: self.auth.secret,
    store: self.auth.store,
    success: function(data, accept) {
      accept(null, true);
    },
    fail: function(data, message, error, accept) {
      if (self.auth.adminParty) accept(null, true);
      else accept(message, false);
    }
  }));
};

SocketHandler.prototype._addSourceLocalListeners = function(emitter) {
  var self = this;

  // Listens to changes in source metadata
  emitter.on('source:save', function() {
    emitAllSources(self);
  });
  emitter.on('source:remove', function() {
    process.nextTick(function() {
      emitAllSources(self);
    });
  });

  // Listens to updates to any source error count
  emitter.on('sourceErrorCountUpdated', function() {
    self.emit('sourceErrorCountUpdated');
  });
};

SocketHandler.prototype._addSourceListeners = function(emitter) {
  var self = this;

  // Listens to changes in source metadata
  emitter.on('source:save', function() {
    emitAllSources(self);
  });
  emitter.on('source:remove', function() {
    process.nextTick(function() {
      emitAllSources(self);
    });
  });

  // Send sources to client
  this.on('sources', function(sources) {
    self.io.sockets.emit('sources', sources);
  });

  // Listens to updates to any source error count
  emitter.on('sourceErrorCountUpdated', function() {
    self.emit('sourceErrorCountUpdated');
  });
};

function emitAllSources(emitter) {
  Source.find({}, '-events', {lean: true}, function(err, sources) {
    if (!err && sources) emitter.emit('sources', sources);
  });
}

SocketHandler.prototype._addTrendsListeners = function(emitter) {
  var self = this;

  // Clean-up old listeners
  emitter.removeAllListeners('trend');

  // Send trends to client
  this.on('trend', function(trend) {
    self.io.sockets.emit('trend', trend);
  });

  // Listens to new trends being analyzed
  emitter.on('trend', function() {
    Trend.findPaginatedCounts(function(err, trends) {
      if (err) self.emit('error', err);
      else self.emit('trend', trends);
    });
  });
};

module.exports = function(app, server, auth) {
  return new SocketHandler(app, server, auth);
};
<commit_msg>more cleanup to socket-handler<commit_after>// Listens for socket connections. Passes queries to streamer for monitoring.
// Watches for updates to sourceErrorCount

var express = require('express');
var http = require('http');
var socketIo = require('socket.io');
var passportSocketIo = require('passport.socketio');
var authentication = require('./authentication');
var _ = require('underscore');
var streamer = require('./streamer');
var Source = require('../../models/source');
var Query = require('../../models/query');
var ReportQuery = require('../../models/query/report-query');
var IncidentQuery = require('../../models/query/incident-query');
var SocketQueryGroup = require('./socket-query-group');
var fetchingController = require('./v1/fetching-controller');
var Trend = require('../../models/trend');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var logger = require('../logger');

// override the emit function to add logging
var emit = socketIo.Socket.prototype.emit;
socketIo.Socket.prototype.emit = function (event, data) {
  logger.debug(event, data);
  emit.apply(this, arguments);
}

var SocketHandler = function(app, server, auth) {
  this.app = app || express();
  this.server = server || http.createServer(app);
  this.auth = auth || authentication(app);
  this.queryGroups = {};

  this.io = socketIo.listen(this.server);
  this._configureSocketIO();
  this.io.sockets.on('connection', this._connect.bind(this));

  // available listener bindings
  this.bindings = {
    sourceLocal: this._addSourceLocalListeners,
    source: this._addSourceListeners,
    trends: this._addTrendsListeners
  };
};

util.inherits(SocketHandler, EventEmitter);

SocketHandler.prototype.addListeners = function(type, emitter) {
  if (!this.bindings[type]) return;
  this.bindings[type].call(this, emitter);
};

// Forward streamer data directly to client
SocketHandler.prototype.streamerSocketForward = function(event, socket) {
  streamer.on(event, function(data) {
    socket.emit(event, data);
  });
};

// Add a client as a listener to a query
SocketHandler.prototype.addClient = function(query, id) {
  if (!query || query === {}) return;
  var hash = query.hash || Query.hash(query);
  // Store a list of clients listening to each query
  if (!_.has(this.queryGroups, hash)) {
    this.queryGroups[hash] = new SocketQueryGroup(query, id);
    // Track query in streamer
    streamer.addQuery(query);
  } else {
    this.queryGroups[hash].add(id);
  }
  return hash;
};

// Remove a client from listening to queries
SocketHandler.prototype.removeClient = function(query, id) {
  if (!query || !query.hash || !_.has(this.queryGroups, query.hash)) return;
  this.queryGroups[query.hash].remove(id);
  // Destroy query if no clients are listening
  if (this.queryGroups[query.hash].isEmpty()) {
    delete this.queryGroups[query.hash];
    streamer.removeQuery(query);
  }
};

SocketHandler.prototype.emitAllErrorsCount = function(emitter) {
  // Send total error counts on client connect
  Source.countAllErrors(function(err, count) {
    if (!err) emitter.emit('sourceErrorCountUpdated', {unreadErrorCount: count});
  });
};

SocketHandler.prototype._configureSocketIO = function() {
  var self = this;
  var io = this.io;
  io.configure(function() {
    io.enable('browser client minification');
    io.enable('browser client etag');
    io.enable('browser client gzip');
    io.set('log level', 1);
    // enable all transports (optional if you want flashsocket support, please note that some hosting
    // providers do not allow you to create servers that listen on a port different than 80 or their
    // default port)
    io.set('transports', ['websocket', 'flashsocket', 'htmlfile', 'xhr-polling', 'jsonp-polling']);
  });

  // Authorize sockets
  io.set('authorization', passportSocketIo.authorize({
    cookieParser: express.cookieParser,
    key: self.auth.key,
    secret: self.auth.secret,
    store: self.auth.store,
    success: function(data, accept) {
      accept(null, true);
    },
    fail: function(data, message, error, accept) {
      if (self.auth.adminParty) accept(null, true);
      else accept(message, false);
    }
  }));
};

SocketHandler.prototype._connect = function (socket) {
  var self = this;

  this.clientQuery = null;
  this.emitAllErrorsCount(socket);

  this._streamerQueryListen('query', ReportQuery, socket);
  this._streamerQueryListen('incidentQuery', IncidentQuery, socket);

  this._streamerQueryCheck('reports', ReportQuery, socket);
  this._streamerQueryCheck('incidents', IncidentQuery, socket);

  this.streamerSocketForward('sourceErrorCountUpdated', socket);
  this.streamerSocketForward('reportStatusChanged', socket);
  this.streamerSocketForward('reportIncidentChanged', socket);
  this.streamerSocketForward('trend', socket);

  // Send fetching status to the client
  socket.emit('fetchingStatusUpdate', {fetching: false});
  fetchingController.on('fetching:start', function() {
    socket.emit('fetchingStatusUpdate', {fetching: true});
  });

  fetchingController.on('fetching:stop', function() {
    socket.emit('fetchingStatusUpdate', {fetching: false});
  });

  // Send source updates back to client
  self.on('sourceErrorCountUpdated', function() {
    self.emitAllErrorsCount(socket);
  });

  // Remove client from query list
  socket.on('disconnect', function() {
    self.removeClient(self.clientQuery, socket.id);
  });
}

// Listen for query events from client
SocketHandler.prototype._streamerQueryListen = function(event, QueryType, socket) {
  var self = this;

  socket.on(event, function(queryData) {
    // Remove client from prior query to avoid multiple streams
    self.removeClient(self.clientQuery, socket.id);
    // Instantiate and normalize client query
    var query = new QueryType(queryData);
    self.clientQuery = query.normalize();
    // Track query and add client as listener

    self.clientQuery.hash = self.addClient(query, socket.id);
  });
}

// Send data back to client for matching queries
SocketHandler.prototype._streamerQueryCheck = function(event, QueryType, socket) {
  var self = this;

  streamer.on(event, function(query, data) {
    var clientQuery = self.clientQuery;
    console.log('_streamerQueryCheck', event, data);
    // Determine if current client query matches the query
    if (QueryType.compare(query, new QueryType(clientQuery)) &&
      self.queryGroups[clientQuery.hash] &&
      self.queryGroups[clientQuery.hash].has(socket.id)) {
      socket.emit(event, data);
    }
  });
}

SocketHandler.prototype._addSourceLocalListeners = function(emitter) {
  var self = this;

  // Listens to changes in source metadata
  emitter.on('source:save', function() {
    emitAllSources(self);
  });
  emitter.on('source:remove', function() {
    process.nextTick(function() {
      emitAllSources(self);
    });
  });

  // Listens to updates to any source error count
  emitter.on('sourceErrorCountUpdated', function() {
    self.emit('sourceErrorCountUpdated');
  });
};

SocketHandler.prototype._addSourceListeners = function(emitter) {
  var self = this;

  // Listens to changes in source metadata
  emitter.on('source:save', function() {
    emitAllSources(self);
  });
  emitter.on('source:remove', function() {
    process.nextTick(function() {
      emitAllSources(self);
    });
  });

  // Send sources to client
  this.on('sources', function(sources) {
    self.io.sockets.emit('sources', sources);
  });

  // Listens to updates to any source error count
  emitter.on('sourceErrorCountUpdated', function() {
    self.emit('sourceErrorCountUpdated');
  });
};

function emitAllSources(emitter) {
  Source.find({}, '-events', {lean: true}, function(err, sources) {
    if (!err && sources) emitter.emit('sources', sources);
  });
}

SocketHandler.prototype._addTrendsListeners = function(emitter) {
  var self = this;

  // Clean-up old listeners
  emitter.removeAllListeners('trend');

  // Send trends to client
  this.on('trend', function(trend) {
    self.io.sockets.emit('trend', trend);
  });

  // Listens to new trends being analyzed
  emitter.on('trend', function() {
    Trend.findPaginatedCounts(function(err, trends) {
      if (err) self.emit('error', err);
      else self.emit('trend', trends);
    });
  });
};

module.exports = function(app, server, auth) {
  return new SocketHandler(app, server, auth);
};
<|endoftext|>


<commit_before>import fs from 'fs'
import {spawn} from 'child_process'
import canvasToBuffer from 'electron-canvas-to-buffer'
import navcodec from 'navcodec'

import React from 'react'
import ReactDOM from 'react-dom'

import devtron from 'devtron'
import installExtension, {REACT_DEVELOPER_TOOLS} from 'electron-devtools-installer'

import AppComponent from './components/app'
import store from './store'

import Delir from 'delir-core'
import {join} from 'path';

window.addEventListener('DOMContentLoaded', async () => {
    devtron.install()
    await installExtension(REACT_DEVELOPER_TOOLS)

    const plugreg = new Delir.Services.PluginRegistory()
    let result = await plugreg.loadPackageDir(join(process.cwd(), 'src/delir-core/src/plugins'))
    console.log(result)

    window.app = {store}
    store.pluginRegistry = plugreg
    store.renderer = new Delir.SessionRenderer({
        pluginRegistory: plugreg,
    })

    ReactDOM.render(
        React.createElement(AppComponent, {store}, []),
        document.querySelector('#root')
    )

    const audioCtx = new AudioContext()
    const canvas = document.querySelector('canvas')

    store.renderer.setDestinationCanvas(canvas)
    store.renderer.setDestinationAudioContext(audioCtx)
    store.renderer.render()

    console.log(navcodec)

    // const stream = await navcodec.openStream('navcodec.mp4')
    // const buffer = await stream.next()
    // const mediaInfo = await navcodec.open('navcodec.mp4')
    //
    // canvas.width = mediaInfo.width
    // canvas.height = mediaInfo.height

    console.time('in')

    // let encount4 = 0
    // console.info(mediaInfo.width * mediaInfo.height * 4, view.length);
    // for (let idx = 0, len = mediaInfo.width * mediaInfo.height * 4; idx < len; idx++) {
    //     // if (idx % 4 === 3) {
    //     //     imageData.data[idx] = 255;
    //     //     encount4++;
    //     //     // console.info('encount');
    //     //     continue;
    //     // }
    //
    //     imageData.data[idx] = srcView[idx];
    // }

    // imageData.data.set(buf)
    // ctx.putImageData(imageData, 0, 0)
    // console.info(imageData, mediaInfo.width, mediaInfo.height)
    // console.info(new ImageData(view, mediaInfo.width, mediaInfo.height));
    // ctx.putImageData(new ImageData(view, mediaInfo.width, mediaInfo.height), 0, 0, 0, 0, mediaInfo.width, mediaInfo.height);
    console.timeEnd('in')

    return ;

    // // Out to render
    // const srcView = new Uint8ClampedArray(buffer)
    // const buf = new ArrayBuffer(mediaInfo.width * mediaInfo.height * 4)
    // const view = new Uint8ClampedArray(buf)
    // const imageData = ctx.createImageData(mediaInfo.width, mediaInfo.height)
    //
    //
    // const VIDEO_DURATION_SEC = 1
    // const OUTPUT_FRAMES = VIDEO_DURATION_SEC * 30
    //
    // const cRand = () => ((Math.random() * 256) | 0).toString(16)
    //
    // const canvas = document.querySelector('#canvas')
    // const ctx = canvas.getContext('2d')
    //
    // // try { fs.unlinkSync('test.mp4') } catch (e) {}
    //
    // // const encoder = spawn('ffmpeg', `-i pipe:0 -r ${OUTPUT_FRAMES} -c:v mjpeg -c:v libx264 -r ${OUTPUT_FRAMES} -s 640x360 test.mp4`.split(' '))
    // // encoder.stderr.on('data', data => console.log(data.toString()))
    //
    // // for (let i = 0; i < OUTPUT_FRAMES; i++) {
    // //     ctx.fillStyle = '#' + [cRand(), cRand(), cRand()].join('')
    // //     ctx.fillRect(0, 0, 640, 360)
    // //
    // //     let buffer = canvasToBuffer(canvas, 'image/jpeg')
    // //     encoder.stdin.write(buffer)
    // // }
    //
    // // encoder.stdin.end()
    // console.log('done')
});
<commit_msg>comment out test codes<commit_after>import fs from 'fs'
import {spawn} from 'child_process'
import canvasToBuffer from 'electron-canvas-to-buffer'
// import navcodec from 'navcodec'

import React from 'react'
import ReactDOM from 'react-dom'

import devtron from 'devtron'
import installExtension, {REACT_DEVELOPER_TOOLS} from 'electron-devtools-installer'

import AppComponent from './components/app'
import store from './store'

import Delir from 'delir-core'
import {join} from 'path';

window.addEventListener('DOMContentLoaded', async () => {
    devtron.install()
    await installExtension(REACT_DEVELOPER_TOOLS)

    const plugreg = new Delir.Services.PluginRegistory()
    let result = await plugreg.loadPackageDir(join(process.cwd(), 'src/delir-core/src/plugins'))
    console.log(result)

    window.app = {store}
    store.pluginRegistry = plugreg
    store.renderer = new Delir.SessionRenderer({
        pluginRegistory: plugreg,
    })

    ReactDOM.render(
        React.createElement(AppComponent, {store}, []),
        document.querySelector('#root')
    )

    //
    // delir-core rendering test
    //

    // const audioCtx = new AudioContext()
    // const canvas = document.querySelector('canvas')
    //
    // store.renderer.setDestinationCanvas(canvas)
    // store.renderer.setDestinationAudioContext(audioCtx)
    // store.renderer.render()
    //
    // console.log(navcodec)

    //
    // navcodec rendering test
    //
    // const stream = await navcodec.openStream('navcodec.mp4')
    // const mediaInfo = await navcodec.open('navcodec.mp4')
    //
    // const canvas = document.querySelector('canvas')
    // console.log(canvas);
    // const ctx = canvas.getContext('2d')
    // // document.body.appendChild(canvas)
    //
    // canvas.width = mediaInfo.width
    // canvas.height = mediaInfo.height
    //
    // console.time('in')
    //
    // // let frame = 0
    // // let lastUpdate = Date.now()
    // const render = async () => {
    //     console.time('in')
    //     let buffer = await stream.next()
    //     let srcView = new Uint8ClampedArray(buffer[0])
    //     // console.log(srcView);
    //     let imageData = ctx.createImageData(mediaInfo.width, mediaInfo.height)
    //     // console.dir(imageData);
    //
    //     // let encount4 = 0
    //     // console.info(mediaInfo.width * mediaInfo.height * 4, srcView.length);
    //     for (let idx = 0, len = Math.min(srcView.length, imageData.data.length); idx < len; idx++) {
    //         // if (idx % 4 === 3) {
    //         //     imageData.data[idx] = 255;
    //         //     encount4++;
    //         //     // console.info('encount');
    //         //     continue;
    //         // }
    //
    //         imageData.data[idx] = srcView[idx];
    //     }
    //
    //     ctx.putImageData(imageData, 0, 0)
    //     imageData = null
    //     srcView = null
    //     buffer = null
    //     console.timeEnd('in')
    //     // await new Promise(resolve => setTimeout(resolve, 1000))
    //     setTimeout(render, 1000/40)
    // }
    //
    // requestAnimationFrame(render)

    // imageData.data.set(buf)
    // console.log(srcView);
    // ctx.putImageData(imageData, 0, 0)
    // console.info(imageData, mediaInfo.width, mediaInfo.height)
    // console.info(new ImageData(view, mediaInfo.width, mediaInfo.height));
    // ctx.putImageData(new ImageData(view, mediaInfo.width, mediaInfo.height), 0, 0, 0, 0, mediaInfo.width, mediaInfo.height);
    // console.timeEnd('in')

    //
    // deream export rendering test
    //

    // const buf = new ArrayBuffer(mediaInfo.width * mediaInfo.height * 4)
    // const view = new Uint8ClampedArray(buf)
    //
    //
    //
    // const VIDEO_DURATION_SEC = 1
    // const OUTPUT_FRAMES = VIDEO_DURATION_SEC * 30
    //
    // const cRand = () => ((Math.random() * 256) | 0).toString(16)
    //
    // const canvas = document.querySelector('#canvas')
    // const ctx = canvas.getContext('2d')
    //
    // // try { fs.unlinkSync('test.mp4') } catch (e) {}
    //
    // // const encoder = spawn('ffmpeg', `-i pipe:0 -r ${OUTPUT_FRAMES} -c:v mjpeg -c:v libx264 -r ${OUTPUT_FRAMES} -s 640x360 test.mp4`.split(' '))
    // // encoder.stderr.on('data', data => console.log(data.toString()))
    //
    // // for (let i = 0; i < OUTPUT_FRAMES; i++) {
    // //     ctx.fillStyle = '#' + [cRand(), cRand(), cRand()].join('')
    // //     ctx.fillRect(0, 0, 640, 360)
    // //
    // //     let buffer = canvasToBuffer(canvas, 'image/jpeg')
    // //     encoder.stdin.write(buffer)
    // // }
    //
    // // encoder.stdin.end()
    // console.log('done')
});
<|endoftext|>


<commit_before>if(typeof module === "object"){
 var Terraformer = require("../dist/node/terraformer.js");
 Terraformer.WKT = require("../dist/node/Parsers/WKT/index.js");
}

describe("WKT Parser", function() {

  it("should parse a POINT", function(){
    var input = "POINT (30 10)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([30,10]);
    expect(output).toBeInstanceOfClass(Terraformer.Point);
    expect(output.type).toEqual("Point");
  });

  it("should parse a LINESTRING", function(){
    var input = "LINESTRING (30 10, 10 30, 40 40)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [30,10], [10,30], [40,40] ]);
    expect(output).toBeInstanceOfClass(Terraformer.LineString);
    expect(output.type).toEqual("LineString");
  });

  it("should parse a POLYGON", function(){
    var input = "POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [ [30, 10], [10, 20], [20, 40], [40, 40], [30, 10] ] ]);
    expect(output).toBeInstanceOfClass(Terraformer.Polygon);
    expect(output.type).toEqual("Polygon");
  });

  it("should parse a POLYGON with a hole", function(){
    var input = "POLYGON ((35 10, 10 20, 15 40, 45 45, 35 10),(20 30, 35 35, 30 20, 20 30))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [ [35, 10],[10, 20],[15, 40],[45, 45],[35, 10] ],
      [ [20, 30],[35, 35],[30, 20],[20, 30] ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.Polygon);
    expect(output.type).toEqual("Polygon");
  });

  it("should parse a MULTIPOINT", function(){
    var input = "MULTIPOINT ((10 40), (40 30), (20 20), (30 10))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40],[40, 30], [20,20], [30,10] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTIPOINT with alternate syntax", function(){
    var input = "MULTIPOINT (10 40, 40 30, 20 20, 30 10)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40],[40, 30], [20,20], [30,10] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTILINESTRING with alternate syntax", function(){
    var input = "MULTILINESTRING ((10 10, 20 20, 10 40),(40 40, 30 30, 40 20, 30 10))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [ [10,10],[20,20],[10,40] ],
      [ [40,40],[30,30],[40,20],[30,10] ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiLineString);
    expect(output.type).toEqual("MultiLineString");
  });

  it("should parse a MULTIPOLYGON", function(){
    var input = "MULTIPOLYGON (((30 20, 10 40, 45 40, 30 20)),((15 5, 40 10, 10 20, 5 10, 15 5)))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [
        [ [30,20],[10,40],[45,40],[30,20] ]
      ],
      [
        [ [15,5],[40,10],[10,20],[5,10],[15,5] ]
      ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPolygon);
    expect(output.type).toEqual("MultiPolygon");
  });

  it("should parse a MULTIPOLYGON with a hole", function(){
    var input = "MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 45 20, 30 5, 10 10, 10 30, 20 35),(30 20, 20 25, 20 15, 30 20)))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [
        [ [40,40], [20,45], [45,30], [40,40] ]
      ],
      [
        [ [20,35],[45,20],[30,5] ,[10,10],[10,30],[20,35] ],
        [ [30,20], [20,25], [20,15],[30,20] ]
      ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPolygon);
    expect(output.type).toEqual("MultiPolygon");
  });

});<commit_msg>add a ton of test coverage<commit_after>if(typeof module === "object"){
 var Terraformer = require("../dist/node/terraformer.js");
 Terraformer.WKT = require("../dist/node/Parsers/WKT/index.js");
}

describe("WKT Convert", function () {

  it("should convert a POINT", function () {
    var input = {
      type: "Point",
      coordinates: [ 30, 10 ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POINT (30 10)");
  });

  it("should convert a POINT with Z", function () {
    var input = {
      type: "Point",
      coordinates: [ 30, 10, 10 ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POINT Z (30 10 10)");
  });

  it("should convert a POINT with M (nonstandard)", function () {
    var input = {
      properties: { m: true },
      type: "Point",
      coordinates: [ 30, 10, 10 ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POINT M (30 10 10)");
  });

  it("should convert a POINT with Z and M", function () {
    var input = {
      type: "Point",
      coordinates: [ 30, 10, 10, 12 ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POINT ZM (30 10 10 12)");
  });

  it("should convert an empty POINT", function () {
    var input = {
      type: "Point",
      coordinates: [ ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POINT EMPTY");
  });

  it("should convert a POLYGON", function () {
    var input = {
      type: "Polygon",
      coordinates: [ [ [ 30, 10 ], [ 20, 20 ], [ 30, 20 ] ] ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POLYGON ((30 10, 20 20, 30 20))");
  });

  it("should convert a POLYGON with Z", function () {
    var input = {
      type: "Polygon",
      coordinates: [ [ [ 30, 10, 1 ], [ 20, 20, 2 ], [ 30, 20, 3 ] ] ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POLYGON Z ((30 10 1, 20 20 2, 30 20 3))");
  });

  it("should convert a POLYGON with ZM", function () {
    var input = {
      type: "Polygon",
      coordinates: [ [ [ 30, 10, 1, 3 ], [ 20, 20, 2, 2 ], [ 30, 20, 3, 1 ] ] ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POLYGON ZM ((30 10 1 3, 20 20 2 2, 30 20 3 1))");
  });

  it("should convert a POLYGON with M (nonstandard)", function () {
    var input = {
      properties: { m: true },
      type: "Polygon",
      coordinates: [ [ [ 30, 10, 1 ], [ 20, 20, 2 ], [ 30, 20, 3 ] ] ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POLYGON M ((30 10 1, 20 20 2, 30 20 3))");
  });

  it("should convert an EMPTY POLYGON", function () {
    var input = {
      type: "Polygon",
      coordinates: [ ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("POLYGON EMPTY");
  });

  it("should convert a MULTIPOINT", function () {
    var input = {
      type: "MultiPoint",
      coordinates: [ [ 30, 10 ], [ 20, 20 ], [ 30, 20 ] ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("MULTIPOINT (30 10, 20 20, 30 20)");
  });

  it("should convert a LINESTRING", function () {
    var input = {
      type: "LineString",
      coordinates: [ [ 30, 10 ], [ 20, 20 ], [ 30, 20 ] ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("LINESTRING (30 10, 20 20, 30 20)");
  });

  it("should convert a MULTILINESTRING", function () {
    var input = {
      type: "MultiLineString",
      coordinates: [ [ [ 30, 10 ], [ 20, 20 ], [ 30, 20 ] ] ]
    };

    var output = Terraformer.WKT.convert(input);

    expect(output).toEqual("MULTILINESTRING ((30 10, 20 20, 30 20))");
  });

  it("should convert a MULTIPOLYGON", function () {
    var input = { "type": "MultiPolygon",
      "coordinates": [
        [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],
        [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
         [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]]
      ]
    };
    var output = Terraformer.WKT.convert(input);
    expect(output).toEqual("MULTIPOLYGON (((102 2, 103 2, 103 3, 102 3, 102 2)), ((100 0, 101 0, 101 1, 100 1, 100 0), (100.2 0.2, 100.8 0.2, 100.8 0.8, 100.2 0.8, 100.2 0.2)))");
  });

});

describe("WKT Parser", function() {

  it("should parse a POINT", function(){
    var input = "POINT (30 10)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([30,10]);
    expect(output).toBeInstanceOfClass(Terraformer.Point);
    expect(output.type).toEqual("Point");
  });

  it("should parse a POINT with a Z coordinate", function(){
    var input = "POINT (30 10 20)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([30,10,20]);
    expect(output).toBeInstanceOfClass(Terraformer.Point);
    expect(output.type).toEqual("Point");
  });

  it("should parse a POINT with Z and M coordinates", function(){
    var input = "POINT (30 10 20 15)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([30,10,20,15]);
    expect(output).toBeInstanceOfClass(Terraformer.Point);
    expect(output.type).toEqual("Point");
  });

  it("should parse a LINESTRING", function(){
    var input = "LINESTRING (30 10, 10 30, 40 40)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [30,10], [10,30], [40,40] ]);
    expect(output).toBeInstanceOfClass(Terraformer.LineString);
    expect(output.type).toEqual("LineString");
  });

  it("should parse a LINESTRING with a Z coordinate", function(){
    var input = "LINESTRING (30 10 5, 10 30 15, 40 40 25)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [30,10,5], [10,30,15], [40,40,25] ]);
    expect(output).toBeInstanceOfClass(Terraformer.LineString);
    expect(output.type).toEqual("LineString");
  });

  it("should parse a LINESTRING with Z and M coordinates", function(){
    var input = "LINESTRING (30 10 5 2, 10 30 15 8, 40 40 25 16)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [30,10,5,2], [10,30,15,8], [40,40,25,16] ]);
    expect(output).toBeInstanceOfClass(Terraformer.LineString);
    expect(output.type).toEqual("LineString");
  });

  it("should parse a POLYGON", function(){
    var input = "POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [ [30, 10], [10, 20], [20, 40], [40, 40], [30, 10] ] ]);
    expect(output).toBeInstanceOfClass(Terraformer.Polygon);
    expect(output.type).toEqual("Polygon");
  });

  it("should parse a POLYGON with a Z coordinate", function(){
    var input = "POLYGON ((30 10 4, 10 20 6, 20 40 8, 40 40 1, 30 10 3))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [ [30, 10, 4], [10, 20, 6], [20, 40, 8], [40, 40, 1], [30, 10, 3] ] ]);
    expect(output).toBeInstanceOfClass(Terraformer.Polygon);
    expect(output.type).toEqual("Polygon");
  });

  it("should parse a POLYGON with Z and M coordinates", function(){
    var input = "POLYGON ((30 10 4 1, 10 20 6 3, 20 40 8 5, 40 40 1 7, 30 10 3 9))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [ [30, 10, 4, 1], [10, 20, 6, 3], [20, 40, 8, 5], [40, 40, 1, 7], [30, 10, 3, 9] ] ]);
    expect(output).toBeInstanceOfClass(Terraformer.Polygon);
    expect(output.type).toEqual("Polygon");
  });

  it("should parse a POLYGON with a hole", function(){
    var input = "POLYGON ((35 10, 10 20, 15 40, 45 45, 35 10),(20 30, 35 35, 30 20, 20 30))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [ [35, 10],[10, 20],[15, 40],[45, 45],[35, 10] ],
      [ [20, 30],[35, 35],[30, 20],[20, 30] ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.Polygon);
    expect(output.type).toEqual("Polygon");
  });

  it("should parse a MULTIPOINT", function(){
    var input = "MULTIPOINT ((10 40), (40 30), (20 20), (30 10))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40],[40, 30], [20,20], [30,10] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTIPOINT with a Z coordinate", function(){
    var input = "MULTIPOINT ((10 40 1), (40 30 2), (20 20 3), (30 10 4))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40, 1],[40, 30, 2], [20, 20, 3], [30, 10, 4] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTIPOINT with Z and M coordinates", function(){
    var input = "MULTIPOINT ((10 40 1 8), (40 30 2 9), (20 20 3 8), (30 10 4 9))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40, 1, 8],[40, 30, 2, 9], [20, 20, 3, 8], [30, 10, 4, 9] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTIPOINT with alternate syntax", function(){
    var input = "MULTIPOINT (10 40, 40 30, 20 20, 30 10)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40],[40, 30], [20,20], [30,10] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTIPOINT with alternate syntax and Z coordinates", function(){
    var input = "MULTIPOINT (10 40 1, 40 30 2, 20 20 3, 30 10 4)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40, 1],[40, 30, 2], [20, 20, 3], [30, 10, 4] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTIPOINT with alternate syntax and Z and M coordinates", function(){
    var input = "MULTIPOINT (10 40 1 2, 40 30 2 3, 20 20 3 4, 30 10 4 5)";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([ [10, 40, 1, 2],[40, 30, 2, 3], [20, 20, 3, 4], [30, 10, 4, 5] ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPoint);
    expect(output.type).toEqual("MultiPoint");
  });

  it("should parse a MULTILINESTRING with alternate syntax", function(){
    var input = "MULTILINESTRING ((10 10, 20 20, 10 40),(40 40, 30 30, 40 20, 30 10))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [ [10,10],[20,20],[10,40] ],
      [ [40,40],[30,30],[40,20],[30,10] ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiLineString);
    expect(output.type).toEqual("MultiLineString");
  });

  it("should parse a MULTILINESTRING with alternate syntax and Z coordinates", function(){
    var input = "MULTILINESTRING ((10 10 10, 20 20 20, 10 40 30),(40 40 30, 30 30 20, 40 20 10, 30 10 10))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [ [10,10,10],[20,20,20],[10,40,30] ],
      [ [40,40,30],[30,30,20],[40,20,10],[30,10,10] ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiLineString);
    expect(output.type).toEqual("MultiLineString");
  });

  it("should parse a MULTILINESTRING with alternate syntax and Z and M coordinates", function(){
    var input = "MULTILINESTRING ((10 10 10 5, 20 20 20 4, 10 40 30 3),(40 40 30 2, 30 30 20 1, 40 20 10 2, 30 10 10 3))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [ [10,10,10,5],[20,20,20,4],[10,40,30,3] ],
      [ [40,40,30,2],[30,30,20,1],[40,20,10,2],[30,10,10,3] ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiLineString);
    expect(output.type).toEqual("MultiLineString");
  });

  it("should parse a MULTIPOLYGON", function(){
    var input = "MULTIPOLYGON (((30 20, 10 40, 45 40, 30 20)),((15 5, 40 10, 10 20, 5 10, 15 5)))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [
        [ [30,20],[10,40],[45,40],[30,20] ]
      ],
      [
        [ [15,5],[40,10],[10,20],[5,10],[15,5] ]
      ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPolygon);
    expect(output.type).toEqual("MultiPolygon");
  });

  it("should parse a MULTIPOLYGON with a Z coordinate", function(){
    var input = "MULTIPOLYGON (((30 20 1, 10 40 2, 45 40 3, 30 20 4)),((15 5, 40 10, 10 20, 5 10, 15 5)))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [
        [ [30,20,1],[10,40,2],[45,40,3],[30,20,4] ]
      ],
      [
        [ [15,5],[40,10],[10,20],[5,10],[15,5] ]
      ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPolygon);
    expect(output.type).toEqual("MultiPolygon");
  });

  it("should parse a MULTIPOLYGON with Z and M coordinates", function(){
    var input = "MULTIPOLYGON (((30 20 1 0, 10 40 2 1, 45 40 3 2, 30 20 4 3)),((15 5, 40 10, 10 20, 5 10, 15 5)))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [
        [ [30,20,1,0],[10,40,2,1],[45,40,3,2],[30,20,4,3] ]
      ],
      [
        [ [15,5],[40,10],[10,20],[5,10],[15,5] ]
      ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPolygon);
    expect(output.type).toEqual("MultiPolygon");
  });

  it("should parse a MULTIPOLYGON with a hole", function(){
    var input = "MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 45 20, 30 5, 10 10, 10 30, 20 35),(30 20, 20 25, 20 15, 30 20)))";
    var output = new Terraformer.WKT.parse(input);
    expect(output.coordinates).toEqual([
      [
        [ [40,40], [20,45], [45,30], [40,40] ]
      ],
      [
        [ [20,35],[45,20],[30,5] ,[10,10],[10,30],[20,35] ],
        [ [30,20], [20,25], [20,15],[30,20] ]
      ]
    ]);
    expect(output).toBeInstanceOfClass(Terraformer.MultiPolygon);
    expect(output.type).toEqual("MultiPolygon");
  });

});<|endoftext|>