<commit_before>const BaseWidget = require('./base');
const debug = require('debug')('windshaft:widget:aggregation');

const filteredQueryTpl = ctx => `
    filtered_source AS (
        SELECT *
        FROM (${ctx._query}) _cdb_filtered_source
        ${ctx._aggregationColumn && ctx._isFloatColumn ? `
        WHERE
            ${ctx._aggregationColumn} != 'infinity'::float
        AND
            ${ctx._aggregationColumn} != '-infinity'::float
        AND
            ${ctx._aggregationColumn} != 'NaN'::float` :
        ''
        }
    )
`;

const summaryQueryTpl = ctx => `
    summary AS (
        SELECT
            count(1) AS count,
            sum(CASE WHEN ${ctx._column} IS NULL THEN 1 ELSE 0 END) AS nulls_count
            ${ctx._isFloatColumn ? `,
            sum(
                CASE
                    WHEN ${ctx._aggregationColumn} = 'infinity'::float OR ${ctx._aggregationColumn} = '-infinity'::float
                    THEN 1
                    ELSE 0
                    END
            ) AS infinities_count,
            sum(CASE WHEN ${ctx._aggregationColumn} = 'NaN'::float THEN 1 ELSE 0 END) AS nans_count` :
            ''
            }
        FROM (${ctx._query}) _cdb_aggregation_nulls
    )
`;

const rankedCategoriesQueryTpl = ctx => `
    categories AS(
        SELECT
            ${ctx._column} AS category,
            ${ctx._aggregation} AS value,
            row_number() OVER (ORDER BY ${ctx._aggregation} desc) as rank
        FROM filtered_source
        ${ctx._aggregationColumn !== null ? `WHERE ${ctx._aggregationColumn} IS NOT NULL` : ''}
        GROUP BY ${ctx._column}
        ORDER BY 2 DESC
    )
`;

const categoriesSummaryMinMaxQueryTpl = () => `
    categories_summary_min_max AS(
        SELECT
            max(value) max_val,
            min(value) min_val
        FROM categories
    )
`;

const categoriesSummaryCountQueryTpl = ctx => `
    categories_summary_count AS(
        SELECT count(1) AS categories_count
        FROM (
            SELECT ${ctx._column} AS category
            FROM (${ctx._query}) _cdb_categories
            GROUP BY ${ctx._column}
        ) _cdb_categories_count
    )
`;

const specialNumericValuesColumns = () => `, nans_count, infinities_count`;

const rankedAggregationQueryTpl = ctx => `
    SELECT
        CAST(category AS text),
        value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank < ${ctx._limit}
    UNION ALL
    SELECT
        'Other' category,
        ${ctx._aggregationFn}(value) as value,
        true as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank >= ${ctx._limit}
    GROUP BY
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
`;

const aggregationQueryTpl = ctx => `
    SELECT
        CAST(${ctx._column} AS text) AS category,
        ${ctx._aggregation} AS value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    FROM (${ctx._query}) _cdb_aggregation_all, summary, categories_summary_min_max, categories_summary_count
    GROUP BY
        category,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    ORDER BY value DESC
`;

const CATEGORIES_LIMIT = 6;

const VALID_OPERATIONS = {
    count: [],
    sum: ['aggregationColumn'],
    avg: ['aggregationColumn'],
    min: ['aggregationColumn'],
    max: ['aggregationColumn']
};

const TYPE = 'aggregation';

/**
 {
     type: 'aggregation',
     options: {
         column: 'name',
         aggregation: 'count' // it could be, e.g., sum if column is numeric
     }
 }
 */
function Aggregation(query, options = {}, queries = {}) {
    if (typeof options.column !== 'string') {
        throw new Error(`Aggregation expects 'column' in widget options`);
    }

    if (typeof options.aggregation !== 'string') {
        throw new Error(`Aggregation expects 'aggregation' operation in widget options`);
    }

    if (!VALID_OPERATIONS[options.aggregation]) {
       throw new Error(`Aggregation does not support '${options.aggregation}' operation`);
    }

    var requiredOptions = VALID_OPERATIONS[options.aggregation];
    var missingOptions = requiredOptions.filter(requiredOption => !options.hasOwnProperty(requiredOption));

    if (missingOptions.length > 0) {
        throw new Error(`Aggregation '${options.aggregation}' is missing some options: ${missingOptions.join(',')}`);
    }

    BaseWidget.apply(this);

    this.query = query;
    this.queries = queries;
    this.column = options.column;
    this.aggregation = options.aggregation;
    this.aggregationColumn = options.aggregationColumn;
    this._isFloatColumn = null;
}

Aggregation.prototype = new BaseWidget();
Aggregation.prototype.constructor = Aggregation;

module.exports = Aggregation;

Aggregation.prototype.sql = function(psql, override, callback) {
    var self = this;

    if (!callback) {
        callback = override;
        override = {};
    }

    if (this.aggregationColumn && this._isFloatColumn === null) {
        this._isFloatColumn = false;
        this.getColumnType(psql, this.aggregationColumn, this.queries.no_filters, function (err, type) {
            if (!err && !!type) {
                self._isFloatColumn = type.float;
            }
            self.sql(psql, override, callback);
        });
        return null;
    }

    var _query = this.query;

    var aggregationSql;

    if (!!override.ownFilter) {
        aggregationSql = [
            this.getCategoriesCTESql(
                _query,
                this.column,
                this.aggregation,
                this.aggregationColumn,
                this._isFloatColumn
            ),
            aggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregation: this.getAggregationSql(),
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    } else {
        aggregationSql = [
            this.getCategoriesCTESql(
                _query,
                this.column,
                this.aggregation,
                this.aggregationColumn,
                this._isFloatColumn
            ),
            rankedAggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregationFn: this.aggregation !== 'count' ? this.aggregation : 'sum',
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    }

    debug(aggregationSql);

    return callback(null, aggregationSql);
};

Aggregation.prototype.getCategoriesCTESql = function() {
    return `
        WITH
            ${filteredQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: this.query,
                _column: this.column,
                _aggregationColumn: this.aggregation !== 'count' ? this.aggregationColumn : null
            })},
            ${summaryQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: this.query,
                _column: this.column,
                _aggregationColumn: this.aggregation !== 'count' ? this.aggregationColumn : null
            })},
            ${rankedCategoriesQueryTpl({
                _query: this.query,
                _column: this.column,
                _aggregation: this.getAggregationSql(),
                _aggregationColumn: this.aggregation !== 'count' ? this.aggregationColumn : null
            })},
            ${categoriesSummaryMinMaxQueryTpl({
                _query: this.query,
                _column: this.column
            })},
            ${categoriesSummaryCountQueryTpl({
                _query: this.query,
                _column: this.column
            })}
    `;
};

const aggregationFnQueryTpl = ctx => `${ctx._aggregationFn}(${ctx._aggregationColumn})`;

Aggregation.prototype.getAggregationSql = function() {
    return aggregationFnQueryTpl({
        _aggregationFn: this.aggregation,
        _aggregationColumn: this.aggregationColumn || 1
    });
};

Aggregation.prototype.format = function(result) {
    var categories = [];
    var count = 0;
    var nulls = 0;
    var nans = 0;
    var infinities = 0;
    var minValue = 0;
    var maxValue = 0;
    var categoriesCount = 0;

    if (result.rows.length) {
        var firstRow = result.rows[0];
        count = firstRow.count;
        nulls = firstRow.nulls_count;
        nans = firstRow.nans_count;
        infinities = firstRow.infinities_count;
        minValue = firstRow.min_val;
        maxValue = firstRow.max_val;
        categoriesCount = firstRow.categories_count;
        categories = result.rows.map(({ category, value, agg }) => ({ category, value, agg }));
    }

    return {
        aggregation: this.aggregation,
        count: count,
        nulls: nulls,
        nans: nans,
        infinities: infinities,
        min: minValue,
        max: maxValue,
        categoriesCount: categoriesCount,
        categories: categories
    };
};

const filterCategoriesQueryTpl = ctx => `
    SELECT
        ${ctx._column} AS category,
        ${ctx._value} AS value
    FROM (${ctx._query}) _cdb_aggregation_search
    WHERE CAST(${ctx._column} as text) ILIKE ${ctx._userQuery}
    GROUP BY ${ctx._column}
`;

const searchQueryTpl = ctx => `
    WITH
    search_unfiltered AS (
        ${ctx._searchUnfiltered}
    ),
    search_filtered AS (
        ${ctx._searchFiltered}
    ),
    search_union AS (
        SELECT * FROM search_unfiltered
        UNION ALL
        SELECT * FROM search_filtered
    )
    SELECT category, sum(value) AS value
    FROM search_union
    GROUP BY category
    ORDER BY value desc
`;

Aggregation.prototype.search = function(psql, userQuery, callback) {
    var self = this;

    var _userQuery = psql.escapeLiteral('%' + userQuery + '%');
    var _value = this.aggregation !== 'count' && this.aggregationColumn ?
        this.aggregation + '(' + this.aggregationColumn + ')' : 'count(1)';

    // TODO unfiltered will be wrong as filters are already applied at this point
    var query = searchQueryTpl({
        _searchUnfiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: '0',
            _userQuery: _userQuery
        }),
        _searchFiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: _value,
            _userQuery: _userQuery
        })
    });

    psql.query(query, function(err, result) {
        if (err) {
            return callback(err, result);
        }

        return callback(null, {type: self.getType(), categories: result.rows });
    }, true); // use read-only transaction
};

Aggregation.prototype.getType = function() {
    return TYPE;
};

Aggregation.prototype.toString = function() {
    return JSON.stringify({
        _type: TYPE,
        _query: this.query,
        _column: this.column,
        _aggregation: this.aggregation
    });
};
<commit_msg>Move categories CTE template out of aggregation class<commit_after>const BaseWidget = require('./base');
const debug = require('debug')('windshaft:widget:aggregation');

const filteredQueryTpl = ctx => `
    filtered_source AS (
        SELECT *
        FROM (${ctx._query}) _cdb_filtered_source
        ${ctx._aggregationColumn && ctx._isFloatColumn ? `
        WHERE
            ${ctx._aggregationColumn} != 'infinity'::float
        AND
            ${ctx._aggregationColumn} != '-infinity'::float
        AND
            ${ctx._aggregationColumn} != 'NaN'::float` :
        ''
        }
    )
`;

const summaryQueryTpl = ctx => `
    summary AS (
        SELECT
            count(1) AS count,
            sum(CASE WHEN ${ctx._column} IS NULL THEN 1 ELSE 0 END) AS nulls_count
            ${ctx._isFloatColumn ? `,
            sum(
                CASE
                    WHEN ${ctx._aggregationColumn} = 'infinity'::float OR ${ctx._aggregationColumn} = '-infinity'::float
                    THEN 1
                    ELSE 0
                    END
            ) AS infinities_count,
            sum(CASE WHEN ${ctx._aggregationColumn} = 'NaN'::float THEN 1 ELSE 0 END) AS nans_count` :
            ''
            }
        FROM (${ctx._query}) _cdb_aggregation_nulls
    )
`;

const rankedCategoriesQueryTpl = ctx => `
    categories AS(
        SELECT
            ${ctx._column} AS category,
            ${ctx._aggregation} AS value,
            row_number() OVER (ORDER BY ${ctx._aggregation} desc) as rank
        FROM filtered_source
        ${ctx._aggregationColumn !== null ? `WHERE ${ctx._aggregationColumn} IS NOT NULL` : ''}
        GROUP BY ${ctx._column}
        ORDER BY 2 DESC
    )
`;

const categoriesSummaryMinMaxQueryTpl = () => `
    categories_summary_min_max AS(
        SELECT
            max(value) max_val,
            min(value) min_val
        FROM categories
    )
`;

const categoriesSummaryCountQueryTpl = ctx => `
    categories_summary_count AS(
        SELECT count(1) AS categories_count
        FROM (
            SELECT ${ctx._column} AS category
            FROM (${ctx._query}) _cdb_categories
            GROUP BY ${ctx._column}
        ) _cdb_categories_count
    )
`;

const specialNumericValuesColumns = () => `, nans_count, infinities_count`;

const rankedAggregationQueryTpl = ctx => `
    SELECT
        CAST(category AS text),
        value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank < ${ctx._limit}
    UNION ALL
    SELECT
        'Other' category,
        ${ctx._aggregationFn}(value) as value,
        true as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank >= ${ctx._limit}
    GROUP BY
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
`;

const aggregationQueryTpl = ctx => `
    SELECT
        CAST(${ctx._column} AS text) AS category,
        ${ctx._aggregation} AS value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    FROM (${ctx._query}) _cdb_aggregation_all, summary, categories_summary_min_max, categories_summary_count
    GROUP BY
        category,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    ORDER BY value DESC
`;

const categoriesCTESqlTpl = ctx => `
    WITH
        ${filteredQueryTpl({
            _isFloatColumn: ctx.isFloatColumn,
            _query: ctx.query,
            _column: ctx.column,
            _aggregationColumn: ctx.aggregation !== 'count' ? ctx.aggregationColumn : null
        })},
        ${summaryQueryTpl({
            _isFloatColumn: ctx.isFloatColumn,
            _query: ctx.query,
            _column: ctx.column,
            _aggregationColumn: ctx.aggregation !== 'count' ? ctx.aggregationColumn : null
        })},
        ${rankedCategoriesQueryTpl({
            _query: ctx.query,
            _column: ctx.column,
            _aggregation: aggregationFnQueryTpl({
                aggregation: ctx.aggregation,
                aggregationColumn: ctx.aggregationColumn || 1
            }),
            _aggregationColumn: ctx.aggregation !== 'count' ? ctx.aggregationColumn : null
        })},
        ${categoriesSummaryMinMaxQueryTpl({
            _query: ctx.query,
            _column: ctx.column
        })},
        ${categoriesSummaryCountQueryTpl({
            _query: ctx.query,
            _column: ctx.column
        })}
`;

const aggregationFnQueryTpl = ctx => `${ctx.aggregation}(${ctx.aggregationColumn})`;

const CATEGORIES_LIMIT = 6;

const VALID_OPERATIONS = {
    count: [],
    sum: ['aggregationColumn'],
    avg: ['aggregationColumn'],
    min: ['aggregationColumn'],
    max: ['aggregationColumn']
};

const TYPE = 'aggregation';

/**
 {
     type: 'aggregation',
     options: {
         column: 'name',
         aggregation: 'count' // it could be, e.g., sum if column is numeric
     }
 }
 */
function Aggregation(query, options = {}, queries = {}) {
    if (typeof options.column !== 'string') {
        throw new Error(`Aggregation expects 'column' in widget options`);
    }

    if (typeof options.aggregation !== 'string') {
        throw new Error(`Aggregation expects 'aggregation' operation in widget options`);
    }

    if (!VALID_OPERATIONS[options.aggregation]) {
       throw new Error(`Aggregation does not support '${options.aggregation}' operation`);
    }

    var requiredOptions = VALID_OPERATIONS[options.aggregation];
    var missingOptions = requiredOptions.filter(requiredOption => !options.hasOwnProperty(requiredOption));

    if (missingOptions.length > 0) {
        throw new Error(`Aggregation '${options.aggregation}' is missing some options: ${missingOptions.join(',')}`);
    }

    BaseWidget.apply(this);

    this.query = query;
    this.queries = queries;
    this.column = options.column;
    this.aggregation = options.aggregation;
    this.aggregationColumn = options.aggregationColumn;
    this._isFloatColumn = null;
}

Aggregation.prototype = new BaseWidget();
Aggregation.prototype.constructor = Aggregation;

module.exports = Aggregation;

Aggregation.prototype.sql = function(psql, override, callback) {
    var self = this;

    if (!callback) {
        callback = override;
        override = {};
    }

    if (this.aggregationColumn && this._isFloatColumn === null) {
        this._isFloatColumn = false;
        this.getColumnType(psql, this.aggregationColumn, this.queries.no_filters, function (err, type) {
            if (!err && !!type) {
                self._isFloatColumn = type.float;
            }
            self.sql(psql, override, callback);
        });
        return null;
    }

    var _query = this.query;

    var aggregationSql;

    if (!!override.ownFilter) {
        aggregationSql = [
            categoriesCTESqlTpl({
                query: _query,
                column: this.column,
                aggregation: this.aggregation,
                aggregationColumn: this.aggregationColumn,
                isFloatColumn: this._isFloatColumn
            }),
            aggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregation: aggregationFnQueryTpl({
                    aggregation: this.aggregation,
                    aggregationColumn: this.aggregationColumn || 1
                }),
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    } else {
        aggregationSql = [
            categoriesCTESqlTpl({
                query: _query,
                column: this.column,
                aggregation: this.aggregation,
                aggregationColumn: this.aggregationColumn,
                isFloatColumn: this._isFloatColumn
            }),
            rankedAggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregationFn: this.aggregation !== 'count' ? this.aggregation : 'sum',
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    }

    debug(aggregationSql);

    return callback(null, aggregationSql);
};

Aggregation.prototype.format = function(result) {
    var categories = [];
    var count = 0;
    var nulls = 0;
    var nans = 0;
    var infinities = 0;
    var minValue = 0;
    var maxValue = 0;
    var categoriesCount = 0;

    if (result.rows.length) {
        var firstRow = result.rows[0];
        count = firstRow.count;
        nulls = firstRow.nulls_count;
        nans = firstRow.nans_count;
        infinities = firstRow.infinities_count;
        minValue = firstRow.min_val;
        maxValue = firstRow.max_val;
        categoriesCount = firstRow.categories_count;
        categories = result.rows.map(({ category, value, agg }) => ({ category, value, agg }));
    }

    return {
        aggregation: this.aggregation,
        count: count,
        nulls: nulls,
        nans: nans,
        infinities: infinities,
        min: minValue,
        max: maxValue,
        categoriesCount: categoriesCount,
        categories: categories
    };
};

const filterCategoriesQueryTpl = ctx => `
    SELECT
        ${ctx._column} AS category,
        ${ctx._value} AS value
    FROM (${ctx._query}) _cdb_aggregation_search
    WHERE CAST(${ctx._column} as text) ILIKE ${ctx._userQuery}
    GROUP BY ${ctx._column}
`;

const searchQueryTpl = ctx => `
    WITH
    search_unfiltered AS (
        ${ctx._searchUnfiltered}
    ),
    search_filtered AS (
        ${ctx._searchFiltered}
    ),
    search_union AS (
        SELECT * FROM search_unfiltered
        UNION ALL
        SELECT * FROM search_filtered
    )
    SELECT category, sum(value) AS value
    FROM search_union
    GROUP BY category
    ORDER BY value desc
`;

Aggregation.prototype.search = function(psql, userQuery, callback) {
    var self = this;

    var _userQuery = psql.escapeLiteral('%' + userQuery + '%');
    var _value = this.aggregation !== 'count' && this.aggregationColumn ?
        this.aggregation + '(' + this.aggregationColumn + ')' : 'count(1)';

    // TODO unfiltered will be wrong as filters are already applied at this point
    var query = searchQueryTpl({
        _searchUnfiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: '0',
            _userQuery: _userQuery
        }),
        _searchFiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: _value,
            _userQuery: _userQuery
        })
    });

    psql.query(query, function(err, result) {
        if (err) {
            return callback(err, result);
        }

        return callback(null, {type: self.getType(), categories: result.rows });
    }, true); // use read-only transaction
};

Aggregation.prototype.getType = function() {
    return TYPE;
};

Aggregation.prototype.toString = function() {
    return JSON.stringify({
        _type: TYPE,
        _query: this.query,
        _column: this.column,
        _aggregation: this.aggregation
    });
};
<|endoftext|>


<commit_before>var BaseWidget = require('./base');
var debug = require('debug')('windshaft:widget:aggregation');

const filteredQueryTpl = ctx => `
    filtered_source AS (
        SELECT *
        FROM (${ctx._query}) _cdb_filtered_source
        ${ctx._aggregationColumn && ctx._isFloatColumn ? `
        WHERE
            ${ctx._aggregationColumn} != 'infinity'::float
        AND
            ${ctx._aggregationColumn} != '-infinity'::float
        AND
            ${ctx._aggregationColumn} != 'NaN'::float` :
        ''
        }
    )
`;

const summaryQueryTpl = ctx => `
    summary AS (
        SELECT
            count(1) AS count,
            sum(CASE WHEN ${ctx._column} IS NULL THEN 1 ELSE 0 END) AS nulls_count
            ${ctx._isFloatColumn ? `,
            sum(
                CASE
                    WHEN ${ctx._aggregationColumn} = 'infinity'::float OR ${ctx._aggregationColumn} = '-infinity'::float
                    THEN 1
                    ELSE 0
                    END
            ) AS infinities_count,
            sum(CASE WHEN ${ctx._aggregationColumn} = 'NaN'::float THEN 1 ELSE 0 END) AS nans_count` :
            ''
            }
        FROM (${ctx._query}) _cdb_aggregation_nulls
    )
`;

const rankedCategoriesQueryTpl = ctx => `
    categories AS(
        SELECT
            ${ctx._column} AS category,
            ${ctx._aggregation} AS value,
            row_number() OVER (ORDER BY ${ctx._aggregation} desc) as rank
        FROM filtered_source
        ${ctx._aggregationColumn !== null ? `WHERE ${ctx._aggregationColumn} IS NOT NULL` : ''}
        GROUP BY ${ctx._column}
        ORDER BY 2 DESC
    )
`;

const categoriesSummaryMinMaxQueryTpl = () => `
    categories_summary_min_max AS(
        SELECT
            max(value) max_val,
            min(value) min_val
        FROM categories
    )
`;

const categoriesSummaryCountQueryTpl = ctx => `
    categories_summary_count AS(
        SELECT count(1) AS categories_count
        FROM (
            SELECT ${ctx._column} AS category
            FROM (${ctx._query}) _cdb_categories
            GROUP BY ${ctx._column}
        ) _cdb_categories_count
    )
`;

const specialNumericValuesColumns = () => `, nans_count, infinities_count`;

const rankedAggregationQueryTpl = ctx => `
    SELECT
        CAST(category AS text),
        value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank < ${ctx._limit}
    UNION ALL
    SELECT
        'Other' category,
        ${ctx._aggregationFn}(value) as value,
        true as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank >= ${ctx._limit}
    GROUP BY
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
`;

const aggregationQueryTpl = ctx => `
    SELECT
        CAST(${ctx._column} AS text) AS category,
        ${ctx._aggregation} AS value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    FROM (${ctx._query}) _cdb_aggregation_all, summary, categories_summary_min_max, categories_summary_count
    GROUP BY
        category,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    ORDER BY value DESC
`;

const CATEGORIES_LIMIT = 6;

const VALID_OPERATIONS = {
    count: [],
    sum: ['aggregationColumn'],
    avg: ['aggregationColumn'],
    min: ['aggregationColumn'],
    max: ['aggregationColumn']
};

const TYPE = 'aggregation';

/**
 {
     type: 'aggregation',
     options: {
         column: 'name',
         aggregation: 'count' // it could be, e.g., sum if column is numeric
     }
 }
 */
function Aggregation(query, options, queries) {
    options = options || {};

    if (typeof options.column !== 'string') {
        throw new Error('Aggregation expects `column` in widget options');
    }

    if (typeof options.aggregation !== 'string') {
        throw new Error('Aggregation expects `aggregation` operation in widget options');
    }

    if (!VALID_OPERATIONS[options.aggregation]) {
        throw new Error("Aggregation does not support '" + options.aggregation + "' operation");
    }

    var requiredOptions = VALID_OPERATIONS[options.aggregation];
    var missingOptions = requiredOptions.filter(requiredOption => !options.hasOwnProperty(requiredOption));

    if (missingOptions.length > 0) {
        throw new Error(
            "Aggregation '" + options.aggregation + "' is missing some options: " + missingOptions.join(',')
        );
    }

    BaseWidget.apply(this);

    this.query = query;
    this.queries = queries;
    this.column = options.column;
    this.aggregation = options.aggregation;
    this.aggregationColumn = options.aggregationColumn;
    this._isFloatColumn = null;
}

Aggregation.prototype = new BaseWidget();
Aggregation.prototype.constructor = Aggregation;

module.exports = Aggregation;

Aggregation.prototype.sql = function(psql, override, callback) {
    var self = this;

    if (!callback) {
        callback = override;
        override = {};
    }

    if (this.aggregationColumn && this._isFloatColumn === null) {
        this._isFloatColumn = false;
        this.getColumnType(psql, this.aggregationColumn, this.queries.no_filters, function (err, type) {
            if (!err && !!type) {
                self._isFloatColumn = type.float;
            }
            self.sql(psql, override, callback);
        });
        return null;
    }

    var _query = this.query;

    var aggregationSql;

    if (!!override.ownFilter) {
        aggregationSql = [
            this.getCategoriesCTESql(
                _query,
                this.column,
                this.aggregation,
                this.aggregationColumn,
                this._isFloatColumn
            ),
            aggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregation: this.getAggregationSql(),
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    } else {
        aggregationSql = [
            this.getCategoriesCTESql(
                _query,
                this.column,
                this.aggregation,
                this.aggregationColumn,
                this._isFloatColumn
            ),
            rankedAggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregationFn: this.aggregation !== 'count' ? this.aggregation : 'sum',
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    }

    debug(aggregationSql);

    return callback(null, aggregationSql);
};

Aggregation.prototype.getCategoriesCTESql = function(query, column, aggregation, aggregationColumn, isFloatColumn) {
    return [
        "WITH",
        [
            filteredQueryTpl({
                _isFloatColumn: isFloatColumn,
                _query: this.query,
                _column: this.column,
                _aggregationColumn: aggregation !== 'count' ? aggregationColumn : null
            }),
            summaryQueryTpl({
                _isFloatColumn: isFloatColumn,
                _query: query,
                _column: column,
                _aggregationColumn: aggregation !== 'count' ? aggregationColumn : null
            }),
            rankedCategoriesQueryTpl({
                _query: query,
                _column: column,
                _aggregation: this.getAggregationSql(),
                _aggregationColumn: aggregation !== 'count' ? aggregationColumn : null
            }),
            categoriesSummaryMinMaxQueryTpl({
                _query: query,
                _column: column
            }),
            categoriesSummaryCountQueryTpl({
                _query: query,
                _column: column
            })
        ].join(',\n')
    ].join('\n');
};

const aggregationFnQueryTpl = ctx => `${ctx._aggregationFn}(${ctx._aggregationColumn})`;

Aggregation.prototype.getAggregationSql = function() {
    return aggregationFnQueryTpl({
        _aggregationFn: this.aggregation,
        _aggregationColumn: this.aggregationColumn || 1
    });
};

Aggregation.prototype.format = function(result) {
    var categories = [];
    var count = 0;
    var nulls = 0;
    var nans = 0;
    var infinities = 0;
    var minValue = 0;
    var maxValue = 0;
    var categoriesCount = 0;

    if (result.rows.length) {
        var firstRow = result.rows[0];
        count = firstRow.count;
        nulls = firstRow.nulls_count;
        nans = firstRow.nans_count;
        infinities = firstRow.infinities_count;
        minValue = firstRow.min_val;
        maxValue = firstRow.max_val;
        categoriesCount = firstRow.categories_count;
        categories = result.rows.map(({ category, value, agg }) => ({ category, value, agg }));
    }

    return {
        aggregation: this.aggregation,
        count: count,
        nulls: nulls,
        nans: nans,
        infinities: infinities,
        min: minValue,
        max: maxValue,
        categoriesCount: categoriesCount,
        categories: categories
    };
};

const filterCategoriesQueryTpl = ctx => `
    SELECT
        ${ctx._column} AS category,
        ${ctx._value} AS value
    FROM (${ctx._query}) _cdb_aggregation_search
    WHERE CAST(${ctx._column} as text) ILIKE ${ctx._userQuery}
    GROUP BY ${ctx._column}
`;

const searchQueryTpl = ctx => `
    WITH
    search_unfiltered AS (
        ${ctx._searchUnfiltered}
    ),
    search_filtered AS (
        ${ctx._searchFiltered}
    ),
    search_union AS (
        SELECT * FROM search_unfiltered
        UNION ALL
        SELECT * FROM search_filtered
    )
    SELECT category, sum(value) AS value
    FROM search_union
    GROUP BY category
    ORDER BY value desc
`;

Aggregation.prototype.search = function(psql, userQuery, callback) {
    var self = this;

    var _userQuery = psql.escapeLiteral('%' + userQuery + '%');
    var _value = this.aggregation !== 'count' && this.aggregationColumn ?
        this.aggregation + '(' + this.aggregationColumn + ')' : 'count(1)';

    // TODO unfiltered will be wrong as filters are already applied at this point
    var query = searchQueryTpl({
        _searchUnfiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: '0',
            _userQuery: _userQuery
        }),
        _searchFiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: _value,
            _userQuery: _userQuery
        })
    });

    psql.query(query, function(err, result) {
        if (err) {
            return callback(err, result);
        }

        return callback(null, {type: self.getType(), categories: result.rows });
    }, true); // use read-only transaction
};

Aggregation.prototype.getType = function() {
    return TYPE;
};

Aggregation.prototype.toString = function() {
    return JSON.stringify({
        _type: TYPE,
        _query: this.query,
        _column: this.column,
        _aggregation: this.aggregation
    });
};
<commit_msg>Declare requirement with const keyword<commit_after>const BaseWidget = require('./base');
const debug = require('debug')('windshaft:widget:aggregation');

const filteredQueryTpl = ctx => `
    filtered_source AS (
        SELECT *
        FROM (${ctx._query}) _cdb_filtered_source
        ${ctx._aggregationColumn && ctx._isFloatColumn ? `
        WHERE
            ${ctx._aggregationColumn} != 'infinity'::float
        AND
            ${ctx._aggregationColumn} != '-infinity'::float
        AND
            ${ctx._aggregationColumn} != 'NaN'::float` :
        ''
        }
    )
`;

const summaryQueryTpl = ctx => `
    summary AS (
        SELECT
            count(1) AS count,
            sum(CASE WHEN ${ctx._column} IS NULL THEN 1 ELSE 0 END) AS nulls_count
            ${ctx._isFloatColumn ? `,
            sum(
                CASE
                    WHEN ${ctx._aggregationColumn} = 'infinity'::float OR ${ctx._aggregationColumn} = '-infinity'::float
                    THEN 1
                    ELSE 0
                    END
            ) AS infinities_count,
            sum(CASE WHEN ${ctx._aggregationColumn} = 'NaN'::float THEN 1 ELSE 0 END) AS nans_count` :
            ''
            }
        FROM (${ctx._query}) _cdb_aggregation_nulls
    )
`;

const rankedCategoriesQueryTpl = ctx => `
    categories AS(
        SELECT
            ${ctx._column} AS category,
            ${ctx._aggregation} AS value,
            row_number() OVER (ORDER BY ${ctx._aggregation} desc) as rank
        FROM filtered_source
        ${ctx._aggregationColumn !== null ? `WHERE ${ctx._aggregationColumn} IS NOT NULL` : ''}
        GROUP BY ${ctx._column}
        ORDER BY 2 DESC
    )
`;

const categoriesSummaryMinMaxQueryTpl = () => `
    categories_summary_min_max AS(
        SELECT
            max(value) max_val,
            min(value) min_val
        FROM categories
    )
`;

const categoriesSummaryCountQueryTpl = ctx => `
    categories_summary_count AS(
        SELECT count(1) AS categories_count
        FROM (
            SELECT ${ctx._column} AS category
            FROM (${ctx._query}) _cdb_categories
            GROUP BY ${ctx._column}
        ) _cdb_categories_count
    )
`;

const specialNumericValuesColumns = () => `, nans_count, infinities_count`;

const rankedAggregationQueryTpl = ctx => `
    SELECT
        CAST(category AS text),
        value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank < ${ctx._limit}
    UNION ALL
    SELECT
        'Other' category,
        ${ctx._aggregationFn}(value) as value,
        true as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
        FROM categories, summary, categories_summary_min_max, categories_summary_count
        WHERE rank >= ${ctx._limit}
    GROUP BY
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
`;

const aggregationQueryTpl = ctx => `
    SELECT
        CAST(${ctx._column} AS text) AS category,
        ${ctx._aggregation} AS value,
        false as agg,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    FROM (${ctx._query}) _cdb_aggregation_all, summary, categories_summary_min_max, categories_summary_count
    GROUP BY
        category,
        nulls_count,
        min_val,
        max_val,
        count,
        categories_count
        ${ctx._isFloatColumn ? `${specialNumericValuesColumns(ctx)}` : '' }
    ORDER BY value DESC
`;

const CATEGORIES_LIMIT = 6;

const VALID_OPERATIONS = {
    count: [],
    sum: ['aggregationColumn'],
    avg: ['aggregationColumn'],
    min: ['aggregationColumn'],
    max: ['aggregationColumn']
};

const TYPE = 'aggregation';

/**
 {
     type: 'aggregation',
     options: {
         column: 'name',
         aggregation: 'count' // it could be, e.g., sum if column is numeric
     }
 }
 */
function Aggregation(query, options, queries) {
    options = options || {};

    if (typeof options.column !== 'string') {
        throw new Error('Aggregation expects `column` in widget options');
    }

    if (typeof options.aggregation !== 'string') {
        throw new Error('Aggregation expects `aggregation` operation in widget options');
    }

    if (!VALID_OPERATIONS[options.aggregation]) {
        throw new Error("Aggregation does not support '" + options.aggregation + "' operation");
    }

    var requiredOptions = VALID_OPERATIONS[options.aggregation];
    var missingOptions = requiredOptions.filter(requiredOption => !options.hasOwnProperty(requiredOption));

    if (missingOptions.length > 0) {
        throw new Error(
            "Aggregation '" + options.aggregation + "' is missing some options: " + missingOptions.join(',')
        );
    }

    BaseWidget.apply(this);

    this.query = query;
    this.queries = queries;
    this.column = options.column;
    this.aggregation = options.aggregation;
    this.aggregationColumn = options.aggregationColumn;
    this._isFloatColumn = null;
}

Aggregation.prototype = new BaseWidget();
Aggregation.prototype.constructor = Aggregation;

module.exports = Aggregation;

Aggregation.prototype.sql = function(psql, override, callback) {
    var self = this;

    if (!callback) {
        callback = override;
        override = {};
    }

    if (this.aggregationColumn && this._isFloatColumn === null) {
        this._isFloatColumn = false;
        this.getColumnType(psql, this.aggregationColumn, this.queries.no_filters, function (err, type) {
            if (!err && !!type) {
                self._isFloatColumn = type.float;
            }
            self.sql(psql, override, callback);
        });
        return null;
    }

    var _query = this.query;

    var aggregationSql;

    if (!!override.ownFilter) {
        aggregationSql = [
            this.getCategoriesCTESql(
                _query,
                this.column,
                this.aggregation,
                this.aggregationColumn,
                this._isFloatColumn
            ),
            aggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregation: this.getAggregationSql(),
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    } else {
        aggregationSql = [
            this.getCategoriesCTESql(
                _query,
                this.column,
                this.aggregation,
                this.aggregationColumn,
                this._isFloatColumn
            ),
            rankedAggregationQueryTpl({
                _isFloatColumn: this._isFloatColumn,
                _query: _query,
                _column: this.column,
                _aggregationFn: this.aggregation !== 'count' ? this.aggregation : 'sum',
                _limit: CATEGORIES_LIMIT
            })
        ].join('\n');
    }

    debug(aggregationSql);

    return callback(null, aggregationSql);
};

Aggregation.prototype.getCategoriesCTESql = function(query, column, aggregation, aggregationColumn, isFloatColumn) {
    return [
        "WITH",
        [
            filteredQueryTpl({
                _isFloatColumn: isFloatColumn,
                _query: this.query,
                _column: this.column,
                _aggregationColumn: aggregation !== 'count' ? aggregationColumn : null
            }),
            summaryQueryTpl({
                _isFloatColumn: isFloatColumn,
                _query: query,
                _column: column,
                _aggregationColumn: aggregation !== 'count' ? aggregationColumn : null
            }),
            rankedCategoriesQueryTpl({
                _query: query,
                _column: column,
                _aggregation: this.getAggregationSql(),
                _aggregationColumn: aggregation !== 'count' ? aggregationColumn : null
            }),
            categoriesSummaryMinMaxQueryTpl({
                _query: query,
                _column: column
            }),
            categoriesSummaryCountQueryTpl({
                _query: query,
                _column: column
            })
        ].join(',\n')
    ].join('\n');
};

const aggregationFnQueryTpl = ctx => `${ctx._aggregationFn}(${ctx._aggregationColumn})`;

Aggregation.prototype.getAggregationSql = function() {
    return aggregationFnQueryTpl({
        _aggregationFn: this.aggregation,
        _aggregationColumn: this.aggregationColumn || 1
    });
};

Aggregation.prototype.format = function(result) {
    var categories = [];
    var count = 0;
    var nulls = 0;
    var nans = 0;
    var infinities = 0;
    var minValue = 0;
    var maxValue = 0;
    var categoriesCount = 0;

    if (result.rows.length) {
        var firstRow = result.rows[0];
        count = firstRow.count;
        nulls = firstRow.nulls_count;
        nans = firstRow.nans_count;
        infinities = firstRow.infinities_count;
        minValue = firstRow.min_val;
        maxValue = firstRow.max_val;
        categoriesCount = firstRow.categories_count;
        categories = result.rows.map(({ category, value, agg }) => ({ category, value, agg }));
    }

    return {
        aggregation: this.aggregation,
        count: count,
        nulls: nulls,
        nans: nans,
        infinities: infinities,
        min: minValue,
        max: maxValue,
        categoriesCount: categoriesCount,
        categories: categories
    };
};

const filterCategoriesQueryTpl = ctx => `
    SELECT
        ${ctx._column} AS category,
        ${ctx._value} AS value
    FROM (${ctx._query}) _cdb_aggregation_search
    WHERE CAST(${ctx._column} as text) ILIKE ${ctx._userQuery}
    GROUP BY ${ctx._column}
`;

const searchQueryTpl = ctx => `
    WITH
    search_unfiltered AS (
        ${ctx._searchUnfiltered}
    ),
    search_filtered AS (
        ${ctx._searchFiltered}
    ),
    search_union AS (
        SELECT * FROM search_unfiltered
        UNION ALL
        SELECT * FROM search_filtered
    )
    SELECT category, sum(value) AS value
    FROM search_union
    GROUP BY category
    ORDER BY value desc
`;

Aggregation.prototype.search = function(psql, userQuery, callback) {
    var self = this;

    var _userQuery = psql.escapeLiteral('%' + userQuery + '%');
    var _value = this.aggregation !== 'count' && this.aggregationColumn ?
        this.aggregation + '(' + this.aggregationColumn + ')' : 'count(1)';

    // TODO unfiltered will be wrong as filters are already applied at this point
    var query = searchQueryTpl({
        _searchUnfiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: '0',
            _userQuery: _userQuery
        }),
        _searchFiltered: filterCategoriesQueryTpl({
            _query: this.query,
            _column: this.column,
            _value: _value,
            _userQuery: _userQuery
        })
    });

    psql.query(query, function(err, result) {
        if (err) {
            return callback(err, result);
        }

        return callback(null, {type: self.getType(), categories: result.rows });
    }, true); // use read-only transaction
};

Aggregation.prototype.getType = function() {
    return TYPE;
};

Aggregation.prototype.toString = function() {
    return JSON.stringify({
        _type: TYPE,
        _query: this.query,
        _column: this.column,
        _aggregation: this.aggregation
    });
};
<|endoftext|>


<commit_before>var strutils = require('../../strutils')

function TeamcityReporter(silent, out){
  this.out = out || process.stdout
  this.silent = silent
  this.stoppedOnError = null
  this.id = 1
  this.total = 0
  this.pass = 0
  this.startTime = new Date()
  this.endTime = null
}
TeamcityReporter.prototype = {
  report: function(prefix, data){
    this.out.write("##teamcity[testStarted name='" + escape(data.name.trim()) + "']\n")
    this.display(prefix, data)
    this.total++
    if (data.passed) this.pass++
  },

  display: function(prefix, result){
    if (this.silent) return
    if (!result.passed) {
      this.out.write("##teamcity[testFailed name='" + escape(result.name.trim()) + "' message='"+ escape(result.error.message) +"' details='" + escape(result.error.stack) + "']\n")
    }
    this.out.write("##teamcity[testFinished name='" + escape(result.name.trim()) + "']\n")

  },
  finish: function(){
    if (this.silent) return
    this.endTime = new Date()
    this.out.write('\n\n')
    this.out.write("##teamcity[testSuiteFinished name='mocha.suite' duration='" + this.duration() + "']\n")
    this.out.write('\n\n')
  },
  duration: function(){
    return Math.round((this.endTime - this.startTime))
  }
}

/**
 * Borrowed from https://github.com/travisjeffery/mocha-teamcity-reporter
 * Escape the given `str`.
 */

function escape(str) {
  if (!str) return ''
  return str
    .toString()
    .replace(/\|/g, "||")
    .replace(/\n/g, "|n")
    .replace(/\r/g, "|r")
    .replace(/\[/g, "|[")
    .replace(/\]/g, "|]")
    .replace(/\u0085/g, "|x")
    .replace(/\u2028/g, "|l")
    .replace(/\u2029/g, "|p")
    .replace(/'/g, "|'")
}

module.exports = TeamcityReporter
<commit_msg>Add prefix to teamcity reporter<commit_after>var strutils = require('../../strutils')

function TeamcityReporter(silent, out){
  this.out = out || process.stdout
  this.silent = silent
  this.stoppedOnError = null
  this.id = 1
  this.total = 0
  this.pass = 0
  this.startTime = new Date()
  this.endTime = null
}
TeamcityReporter.prototype = {
  report: function(prefix, data){
    this.out.write("##teamcity[testStarted name='" + this._namify(prefix, data) + "']\n")
    this._display(prefix, data)
    this.total++
    if (data.passed) this.pass++
  },
  finish: function(){
    if (this.silent) return
    this.endTime = new Date()
    this.out.write('\n\n')
    this.out.write("##teamcity[testSuiteFinished name='mocha.suite' duration='" + this._duration() + "']\n")
    this.out.write('\n\n')
  },
  _display: function(prefix, result){
    if (this.silent) return
    if (!result.passed) {
      this.out.write("##teamcity[testFailed name='" + this._namify(prefix, result) + "' message='"+ escape(result.error.message) +"' details='" + escape(result.error.stack) + "']\n")
    }
    this.out.write("##teamcity[testFinished name='" + this._namify(prefix, result) + "']\n")

  },
  _namify: function(prefix, result) {
    var line = (prefix ? (prefix + ' - ') : '') +
      result.name.trim()
    return escape(line)
  },
  _duration: function(){
    return Math.round((this.endTime - this.startTime))
  }
}

/**
 * Borrowed from https://github.com/travisjeffery/mocha-teamcity-reporter
 * Escape the given `str`.
 */

function escape(str) {
  if (!str) return ''
  return str
    .toString()
    .replace(/\|/g, "||")
    .replace(/\n/g, "|n")
    .replace(/\r/g, "|r")
    .replace(/\[/g, "|[")
    .replace(/\]/g, "|]")
    .replace(/\u0085/g, "|x")
    .replace(/\u2028/g, "|l")
    .replace(/\u2029/g, "|p")
    .replace(/'/g, "|'")
}

module.exports = TeamcityReporter
<|endoftext|>


<commit_before>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { routeTo } from '../../actions/ui'
import { isNewUser } from '../../actions/user'

import AfterSignInScreen from './after-signin-screen'
import withLoggedInUserSupport from './with-logged-in-user-support'

/**
 * This screen is flashed just after user sign in while state.user.loggedInUser is fetched.
 * Once state.user.loggedInUser is available:
 * - For new users, route them to the account page (it will show account setup).
 * - For existing users, route them to the itinerary search that was in place before login.
 * TODO: Improve this screen.
 */
class AfterSignInSwitch extends Component {
  componentDidUpdate () {
    const { loggedInUser, routeTo } = this.props
    if (loggedInUser) {
      if (isNewUser(loggedInUser)) {
        routeTo('/account')
      } else {
        routeTo('/')
      }
    }
  }

  render () {
    return <AfterSignInScreen />
  }
}

// connect to the redux store

const mapStateToProps = (state, ownProps) => {
  return {
    loggedInUser: state.user.loggedInUser
  }
}

const mapDispatchToProps = {
  routeTo
}

export default withLoggedInUserSupport(
  connect(mapStateToProps, mapDispatchToProps)(AfterSignInSwitch)
)
<commit_msg>improvement(AfterSignInSwitch): Prevent /signedin URL from showing in browser history.<commit_after>import React, { Component } from 'react'
import { connect } from 'react-redux'

import { isNewUser } from '../../actions/user'

import AfterSignInScreen from './after-signin-screen'
import withLoggedInUserSupport from './with-logged-in-user-support'

/**
 * This screen is flashed just after user sign in while state.user.loggedInUser is fetched.
 * Once state.user.loggedInUser is available:
 * - For new users, route them to the account page (it will show account setup).
 * - For existing users, route them to the itinerary search that was in place before login.
 */
class AfterSignInSwitch extends Component {
  componentDidUpdate () {
    const { loggedInUser } = this.props

    if (loggedInUser) {
      const nextUrl = isNewUser(loggedInUser) ? '/account' : '/'
      // Prevent the current URL from showing in the browser history.
      window.location.replace(window.location.href.replace('#/signedin', `#${nextUrl}`))
    }
  }

  render () {
    return <AfterSignInScreen />
  }
}

// connect to the redux store

const mapStateToProps = (state, ownProps) => {
  return {
    loggedInUser: state.user.loggedInUser
  }
}

const mapDispatchToProps = {
}

export default withLoggedInUserSupport(
  connect(mapStateToProps, mapDispatchToProps)(AfterSignInSwitch)
)
<|endoftext|>


<commit_before>/*
YAML parser for Javascript
Author: Diogo Costa

This program is released under the MIT License as follows:

Copyright (c) 2011 Diogo Costa (costa.h4evr@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

/**
 * @name YAML
 * @namespace
*/

var YAML =
(function() {
    var errors = [],
        reference_blocks = [],
        processing_time = 0,
        regex =
        {
            "regLevel" : new RegExp("^([\\s\\-]+)"),
            "invalidLine" : new RegExp("^\\-\\-\\-|^\\.\\.\\.|^\\s*#.*|^\\s*$"),
            "dashesString" : new RegExp("^\\s*\\\"([^\\\"]*)\\\"\\s*$"),
            "quotesString" : new RegExp("^\\s*\\\'([^\\\']*)\\\'\\s*$"),
            "float" : new RegExp("^[+-]?[0-9]+\\.[0-9]+(e[+-]?[0-9]+(\\.[0-9]+)?)?$"),
            "integer" : new RegExp("^[+-]?[0-9]+$"),
            "array" : new RegExp("\\[\\s*(.*)\\s*\\]"),
            "map" : new RegExp("\\{\\s*(.*)\\s*\\}"),
            "key_value" : new RegExp("([a-z0-9_-][ a-z0-9_-]*):( .+)", "i"),
            "single_key_value" : new RegExp("^([a-z0-9_-][ a-z0-9_-]*):( .+?)$", "i"),
            "key" : new RegExp("([a-z0-9_-][ a-z0-9_-]+):( .+)?", "i"),
            "item" : new RegExp("^-\\s+"),
            "trim" : new RegExp("^\\s+|\\s+$"),
            "comment" : new RegExp("([^\\\'\\\"#]+([\\\'\\\"][^\\\'\\\"]*[\\\'\\\"])*)*(#.*)?")
        };

     /**
      * @class A block of lines of a given level.
      * @param {int} lvl The block's level.
      * @private
      */
    function Block(lvl) {
        return {
            /* The block's parent */
            parent: null,
            /* Number of children */
            length: 0,
            /* Block's level */
            level: lvl,
            /* Lines of code to process */
            lines: [],
            /* Blocks with greater level */
            children : [],
            /* Add a block to the children collection */
            addChild : function(obj) {
                this.children.push(obj);
                obj.parent = this;
                ++this.length;
            }
        };
    }

    // function to create an XMLHttpClient in a cross-browser manner
    function createXMLHTTPRequest() {
        var xmlhttp;

        try {
            // Mozilla / Safari / IE7
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            // IE
            var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
            'MSXML2.XMLHTTP.4.0',
            'MSXML2.XMLHTTP.3.0',
            'MSXML2.XMLHTTP',
            'Microsoft.XMLHTTP' );
            var success = false;
            for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
                try {
                xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                success = true;
                } catch (e) {}
            }
            if (!success) {
                throw new Error('Unable to create XMLHttpRequest.');
            }
        }

        return xmlhttp;
    }

    function fromURL(src, ondone) {
        var client = createXMLHTTPRequest();
        client.onreadystatechange = function() {
            if (this.readyState == 4 || this.status == 200) {
                var txt = this.responseText;
                ondone(YAML.eval(txt));
            }
        };
        client.open('GET', src);
        client.send();
    }

    function parser(str) {
        var regLevel = regex["regLevel"];
        var invalidLine = regex["invalidLine"];
        var lines = str.split("\n");
        var m;
        var level = 0, curLevel = 0;

        var blocks = [];

        var result = new Block(-1);
        var currentBlock = new Block(0);
        result.addChild(currentBlock);
        var levels = [];
        var line = "";

        blocks.push(currentBlock);
        levels.push(level);

        for(var i = 0, len = lines.length; i < len; ++i) {
            line = lines[i];

            if(line.match(invalidLine)) {
                continue;
            }

            if(m = regLevel.exec(line)) {
                level = m[1].length;
            } else
                level = 0;

            if(level > curLevel) {
                var oldBlock = currentBlock;
                currentBlock = new Block(level);
                oldBlock.addChild(currentBlock);
                blocks.push(currentBlock);
                levels.push(level);
            } else if(level < curLevel) {
                var added = false;

                var k = levels.length - 1;
                for(; k >= 0; --k) {
                    if(levels[k] == level) {
                        currentBlock = new Block(level);
                        blocks.push(currentBlock);
                        levels.push(level);
                        if(blocks[k].parent!= null)
                            blocks[k].parent.addChild(currentBlock);
                        added = true;
                        break;
                    }
                }

                if(!added) {
                    errors.push("Error: Invalid indentation at line " + i + ": " + line);
                    return;
                }
            }

            currentBlock.lines.push(line.replace(regex["trim"], ""));
            curLevel = level;
        }

        return result;
    }

    function processValue(val) {
        val = val.replace(regex["trim"], "");
        var m = null;

        if(val == 'true') {
            return true;
        } else if(val == 'false') {
            return false;
        } else if(val == '.NaN') {
            return Number.NaN;
        } else if(val == 'null') {
            return null;
        } else if(val == '.inf') {
            return Number.POSITIVE_INFINITY;
        } else if(val == '-.inf') {
            return Number.NEGATIVE_INFINITY;
        } else if(m = val.match(regex["dashesString"])) {
            return m[1];
        } else if(m = val.match(regex["quotesString"])) {
            return m[1];
        } else if(m = val.match(regex["float"])) {
            return parseFloat(m[0]);
        } else if(m = val.match(regex["integer"])) {
            return parseInt(m[0]);
        } else if( !isNaN(m = Date.parse(val))) {
            return new Date(m);
        } else if(m = val.match(regex["single_key_value"])) {
            var res = {};
            res[m[1]] = processValue(m[2]);
            return res;
        } else if(m = val.match(regex["array"])){
            var count = 0, c = ' ';
            var res = [];
            var content = "";
            var str = false;
            for(var j = 0, lenJ = m[1].length; j < lenJ; ++j) {
                c = m[1][j];
                if(c == '\'' || c == '"') {
                    if(str === false) {
                        str = c;
                        content += c;
                        continue;
                    } else if((c == '\'' && str == '\'') || (c == '"' && str == '"')) {
                        str = false;
                        content += c;
                        continue;
                    }
                } else if(str === false && (c == '[' || c == '{')) {
                    ++count;
                } else if(str === false && (c == ']' || c == '}')) {
                    --count;
                } else if(str === false && count == 0 && c == ',') {
                    res.push(processValue(content));
                    content = "";
                    continue;
                }

                content += c;
            }

            if(content.length > 0)
                res.push(processValue(content));
            return res;
        } else if(m = val.match(regex["map"])){
            var count = 0, c = ' ';
            var res = [];
            var content = "";
            var str = false;
            for(var j = 0, lenJ = m[1].length; j < lenJ; ++j) {
                c = m[1][j];
                if(c == '\'' || c == '"') {
                    if(str === false) {
                        str = c;
                        content += c;
                        continue;
                    } else if((c == '\'' && str == '\'') || (c == '"' && str == '"')) {
                        str = false;
                        content += c;
                        continue;
                    }
                } else if(str === false && (c == '[' || c == '{')) {
                    ++count;
                } else if(str === false && (c == ']' || c == '}')) {
                    --count;
                } else if(str === false && count == 0 && c == ',') {
                    res.push(content);
                    content = "";
                    continue;
                }

                content += c;
            }

            if(content.length > 0)
                res.push(content);

            var newRes = {};
            for(var j = 0, lenJ = res.length; j < lenJ; ++j) {
                if(m = res[j].match(regex["key_value"])) {
                    newRes[m[1]] = processValue(m[2]);
                }
            }

            return newRes;
        } else
            return val;
    }

    function processFoldedBlock(block) {
        var lines = block.lines;
        var children = block.children;
        var str = lines.join(" ");
        var chunks = [str];
        for(var i = 0, len = children.length; i < len; ++i) {
            chunks.push(processFoldedBlock(children[i]));
        }
        return chunks.join("\n");
    }

    function processLiteralBlock(block) {
        var lines = block.lines;
        var children = block.children;
        var str = lines.join("\n");
        for(var i = 0, len = children.length; i < len; ++i) {
            str += processLiteralBlock(children[i]);
        }
        return str;
    }

    function processBlock(blocks) {
        var m = null;
        var res = {};
        var lines = null;
        var children = null;
        var currentObj = null;

        var level = -1;

        var processedBlocks = [];

        var isMap = true;

        for(var j = 0, lenJ = blocks.length; j < lenJ; ++j) {

            if(level != -1 && level != blocks[j].level)
                continue;

            processedBlocks.push(j);

            level = blocks[j].level;
            lines = blocks[j].lines;
            children = blocks[j].children;
            currentObj = null;

            for(var i = 0, len = lines.length; i < len; ++i) {
                var line = lines[i];

                if(m = line.match(regex["key"])) {
                    var key = m[1];

                    if(key[0] == '-') {
                        key = key.replace(regex["item"], "");
                        if (isMap) {
                            isMap = false;
                            if (typeof(res.length) === "undefined") {
                                res = [];
                            }
                        }
                        if(currentObj != null) res.push(currentObj);
                        currentObj = {};
                        isMap = true;
                    }

                    if(typeof m[2] != "undefined") {
                        var value = m[2].replace(regex["trim"], "");
                        if(value[0] == '&') {
                            var nb = processBlock(children);
                            if(currentObj != null) currentObj[key] = nb;
                            else res[key] = nb;
                            reference_blocks[value.substr(1)] = nb;
                        } else if(value[0] == '|') {
                            if(currentObj != null) currentObj[key] = processLiteralBlock(children.shift());
                            else res[key] = processLiteralBlock(children.shift());
                        } else if(value[0] == '*') {
                            var v = value.substr(1);
                            var no = {};

                            if(typeof reference_blocks[v] == "undefined") {
                                errors.push("Reference '" + v + "' not found!");
                            } else {
                                for(var k in reference_blocks[v]) {
                                    no[k] = reference_blocks[v][k];
                                }

                                if(currentObj != null) currentObj[key] = no;
                                else res[key] = no;
                            }
                        } else if(value[0] == '>') {
                            if(currentObj != null) currentObj[key] = processFoldedBlock(children.shift());
                            else res[key] = processFoldedBlock(children.shift());
                        } else {
                            if(currentObj != null) currentObj[key] = processValue(value);
                            else res[key] = processValue(value);
                        }
                    } else {
                        if(currentObj != null) currentObj[key] = processBlock(children);
                        else res[key] = processBlock(children);
                    }
                } else if(line.match(/^-\s*$/)) {
                    if (isMap) {
                        isMap = false;
                        if (typeof(res.length) === "undefined") {
                            res = [];
                        }
                    }
                    if(currentObj != null) res.push(currentObj);
                    currentObj = {};
                    isMap = true;
                    continue;
                } else if(m = line.match(/^-\s*(.*)/)) {
                    if(currentObj != null)
                        currentObj.push(processValue(m[1]));
                    else {
                        if (isMap) {
                            isMap = false;
                            if (typeof(res.length) === "undefined") {
                                res = [];
                            }
                        }
                        res.push(processValue(m[1]));
                    }
                    continue;
                }
            }

            if(currentObj != null) {
                if (isMap) {
                    isMap = false;
                    if (typeof(res.length) === "undefined") {
                        res = [];
                    }
                }
                res.push(currentObj);
            }
        }

        for(var j = processedBlocks.length - 1; j >= 0; --j) {
            blocks.splice.call(blocks, processedBlocks[j], 1);
        }

        return res;
    }

    function semanticAnalysis(blocks) {
        var res = processBlock(blocks.children);
        return res;
    }

    function preProcess(src) {
        var m;
        var lines = src.split("\n");

        var r = regex["comment"];

        for(var i in lines) {
            if(m = lines[i].match(r)) {
/*                var cmt = "";
                if(typeof m[3] != "undefined")
                    lines[i] = m[1];
                else if(typeof m[3] != "undefined")
                    lines[i] = m[3];
                else
                    lines[i] = "";
                    */
                if(typeof m[3] !== "undefined") {
                    lines[i] = m[0].substr(0, m[0].length - m[3].length);
                }
            }
        }

        return lines.join("\n");
    }

    function eval(str) {
        errors = [];
        reference_blocks = [];
        processing_time = (new Date()).getTime();
        var pre = preProcess(str)
        var doc = parser(pre);
        var res = semanticAnalysis(doc);
        processing_time = (new Date()).getTime() - processing_time;

        return res;
    }

    return {
        /**
         * Load and parse a YAML file from a URL.
         * @param {String} src URL from where to load the YAML file
         * @param {Function} ondone Function that will be called when the file is parsed. The result is passed as an argument.
         * @function
         */
        fromURL : fromURL,

        /**
         * Parse a YAML file from a string.
         * @param {String} str String with the YAML file contents.
         * @function
         */
        eval : eval,

        /**
         * Get errors found when parsing the last file.
         * @function
         * @returns Errors found when parsing the last file.
         */
        getErrors : function() { return errors; },

        /**
         * Get the time it took to parse the last file.
         * @function
         * @returns Time in milliseconds.
         */
        getProcessingTime : function() { return processing_time; }
    }
})();
<commit_msg>Fixed fromURL code (see issue 4)<commit_after>/*
YAML parser for Javascript
Author: Diogo Costa

This program is released under the MIT License as follows:

Copyright (c) 2011 Diogo Costa (costa.h4evr@gmail.com)

Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
*/

/**
 * @name YAML
 * @namespace
*/

var YAML =
(function() {
    var errors = [],
        reference_blocks = [],
        processing_time = 0,
        regex =
        {
            "regLevel" : new RegExp("^([\\s\\-]+)"),
            "invalidLine" : new RegExp("^\\-\\-\\-|^\\.\\.\\.|^\\s*#.*|^\\s*$"),
            "dashesString" : new RegExp("^\\s*\\\"([^\\\"]*)\\\"\\s*$"),
            "quotesString" : new RegExp("^\\s*\\\'([^\\\']*)\\\'\\s*$"),
            "float" : new RegExp("^[+-]?[0-9]+\\.[0-9]+(e[+-]?[0-9]+(\\.[0-9]+)?)?$"),
            "integer" : new RegExp("^[+-]?[0-9]+$"),
            "array" : new RegExp("\\[\\s*(.*)\\s*\\]"),
            "map" : new RegExp("\\{\\s*(.*)\\s*\\}"),
            "key_value" : new RegExp("([a-z0-9_-][ a-z0-9_-]*):( .+)", "i"),
            "single_key_value" : new RegExp("^([a-z0-9_-][ a-z0-9_-]*):( .+?)$", "i"),
            "key" : new RegExp("([a-z0-9_-][ a-z0-9_-]+):( .+)?", "i"),
            "item" : new RegExp("^-\\s+"),
            "trim" : new RegExp("^\\s+|\\s+$"),
            "comment" : new RegExp("([^\\\'\\\"#]+([\\\'\\\"][^\\\'\\\"]*[\\\'\\\"])*)*(#.*)?")
        };

     /**
      * @class A block of lines of a given level.
      * @param {int} lvl The block's level.
      * @private
      */
    function Block(lvl) {
        return {
            /* The block's parent */
            parent: null,
            /* Number of children */
            length: 0,
            /* Block's level */
            level: lvl,
            /* Lines of code to process */
            lines: [],
            /* Blocks with greater level */
            children : [],
            /* Add a block to the children collection */
            addChild : function(obj) {
                this.children.push(obj);
                obj.parent = this;
                ++this.length;
            }
        };
    }

    // function to create an XMLHttpClient in a cross-browser manner
    function createXMLHTTPRequest() {
        var xmlhttp;

        try {
            // Mozilla / Safari / IE7
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            // IE
            var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
            'MSXML2.XMLHTTP.4.0',
            'MSXML2.XMLHTTP.3.0',
            'MSXML2.XMLHTTP',
            'Microsoft.XMLHTTP' );
            var success = false;
            for (var i=0;i < XMLHTTP_IDS.length && !success; i++) {
                try {
                xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]);
                success = true;
                } catch (e) {}
            }
            if (!success) {
                throw new Error('Unable to create XMLHttpRequest.');
            }
        }

        return xmlhttp;
    }

    function fromURL(src, ondone) {
        var client = createXMLHTTPRequest();
        client.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                var txt = this.responseText;
                ondone(YAML.eval(txt));
            }
        };
        client.open('GET', src);
        client.send();
    }

    function parser(str) {
        var regLevel = regex["regLevel"];
        var invalidLine = regex["invalidLine"];
        var lines = str.split("\n");
        var m;
        var level = 0, curLevel = 0;

        var blocks = [];

        var result = new Block(-1);
        var currentBlock = new Block(0);
        result.addChild(currentBlock);
        var levels = [];
        var line = "";

        blocks.push(currentBlock);
        levels.push(level);

        for(var i = 0, len = lines.length; i < len; ++i) {
            line = lines[i];

            if(line.match(invalidLine)) {
                continue;
            }

            if(m = regLevel.exec(line)) {
                level = m[1].length;
            } else
                level = 0;

            if(level > curLevel) {
                var oldBlock = currentBlock;
                currentBlock = new Block(level);
                oldBlock.addChild(currentBlock);
                blocks.push(currentBlock);
                levels.push(level);
            } else if(level < curLevel) {
                var added = false;

                var k = levels.length - 1;
                for(; k >= 0; --k) {
                    if(levels[k] == level) {
                        currentBlock = new Block(level);
                        blocks.push(currentBlock);
                        levels.push(level);
                        if(blocks[k].parent!= null)
                            blocks[k].parent.addChild(currentBlock);
                        added = true;
                        break;
                    }
                }

                if(!added) {
                    errors.push("Error: Invalid indentation at line " + i + ": " + line);
                    return;
                }
            }

            currentBlock.lines.push(line.replace(regex["trim"], ""));
            curLevel = level;
        }

        return result;
    }

    function processValue(val) {
        val = val.replace(regex["trim"], "");
        var m = null;

        if(val == 'true') {
            return true;
        } else if(val == 'false') {
            return false;
        } else if(val == '.NaN') {
            return Number.NaN;
        } else if(val == 'null') {
            return null;
        } else if(val == '.inf') {
            return Number.POSITIVE_INFINITY;
        } else if(val == '-.inf') {
            return Number.NEGATIVE_INFINITY;
        } else if(m = val.match(regex["dashesString"])) {
            return m[1];
        } else if(m = val.match(regex["quotesString"])) {
            return m[1];
        } else if(m = val.match(regex["float"])) {
            return parseFloat(m[0]);
        } else if(m = val.match(regex["integer"])) {
            return parseInt(m[0]);
        } else if( !isNaN(m = Date.parse(val))) {
            return new Date(m);
        } else if(m = val.match(regex["single_key_value"])) {
            var res = {};
            res[m[1]] = processValue(m[2]);
            return res;
        } else if(m = val.match(regex["array"])){
            var count = 0, c = ' ';
            var res = [];
            var content = "";
            var str = false;
            for(var j = 0, lenJ = m[1].length; j < lenJ; ++j) {
                c = m[1][j];
                if(c == '\'' || c == '"') {
                    if(str === false) {
                        str = c;
                        content += c;
                        continue;
                    } else if((c == '\'' && str == '\'') || (c == '"' && str == '"')) {
                        str = false;
                        content += c;
                        continue;
                    }
                } else if(str === false && (c == '[' || c == '{')) {
                    ++count;
                } else if(str === false && (c == ']' || c == '}')) {
                    --count;
                } else if(str === false && count == 0 && c == ',') {
                    res.push(processValue(content));
                    content = "";
                    continue;
                }

                content += c;
            }

            if(content.length > 0)
                res.push(processValue(content));
            return res;
        } else if(m = val.match(regex["map"])){
            var count = 0, c = ' ';
            var res = [];
            var content = "";
            var str = false;
            for(var j = 0, lenJ = m[1].length; j < lenJ; ++j) {
                c = m[1][j];
                if(c == '\'' || c == '"') {
                    if(str === false) {
                        str = c;
                        content += c;
                        continue;
                    } else if((c == '\'' && str == '\'') || (c == '"' && str == '"')) {
                        str = false;
                        content += c;
                        continue;
                    }
                } else if(str === false && (c == '[' || c == '{')) {
                    ++count;
                } else if(str === false && (c == ']' || c == '}')) {
                    --count;
                } else if(str === false && count == 0 && c == ',') {
                    res.push(content);
                    content = "";
                    continue;
                }

                content += c;
            }

            if(content.length > 0)
                res.push(content);

            var newRes = {};
            for(var j = 0, lenJ = res.length; j < lenJ; ++j) {
                if(m = res[j].match(regex["key_value"])) {
                    newRes[m[1]] = processValue(m[2]);
                }
            }

            return newRes;
        } else
            return val;
    }

    function processFoldedBlock(block) {
        var lines = block.lines;
        var children = block.children;
        var str = lines.join(" ");
        var chunks = [str];
        for(var i = 0, len = children.length; i < len; ++i) {
            chunks.push(processFoldedBlock(children[i]));
        }
        return chunks.join("\n");
    }

    function processLiteralBlock(block) {
        var lines = block.lines;
        var children = block.children;
        var str = lines.join("\n");
        for(var i = 0, len = children.length; i < len; ++i) {
            str += processLiteralBlock(children[i]);
        }
        return str;
    }

    function processBlock(blocks) {
        var m = null;
        var res = {};
        var lines = null;
        var children = null;
        var currentObj = null;

        var level = -1;

        var processedBlocks = [];

        var isMap = true;

        for(var j = 0, lenJ = blocks.length; j < lenJ; ++j) {

            if(level != -1 && level != blocks[j].level)
                continue;

            processedBlocks.push(j);

            level = blocks[j].level;
            lines = blocks[j].lines;
            children = blocks[j].children;
            currentObj = null;

            for(var i = 0, len = lines.length; i < len; ++i) {
                var line = lines[i];

                if(m = line.match(regex["key"])) {
                    var key = m[1];

                    if(key[0] == '-') {
                        key = key.replace(regex["item"], "");
                        if (isMap) {
                            isMap = false;
                            if (typeof(res.length) === "undefined") {
                                res = [];
                            }
                        }
                        if(currentObj != null) res.push(currentObj);
                        currentObj = {};
                        isMap = true;
                    }

                    if(typeof m[2] != "undefined") {
                        var value = m[2].replace(regex["trim"], "");
                        if(value[0] == '&') {
                            var nb = processBlock(children);
                            if(currentObj != null) currentObj[key] = nb;
                            else res[key] = nb;
                            reference_blocks[value.substr(1)] = nb;
                        } else if(value[0] == '|') {
                            if(currentObj != null) currentObj[key] = processLiteralBlock(children.shift());
                            else res[key] = processLiteralBlock(children.shift());
                        } else if(value[0] == '*') {
                            var v = value.substr(1);
                            var no = {};

                            if(typeof reference_blocks[v] == "undefined") {
                                errors.push("Reference '" + v + "' not found!");
                            } else {
                                for(var k in reference_blocks[v]) {
                                    no[k] = reference_blocks[v][k];
                                }

                                if(currentObj != null) currentObj[key] = no;
                                else res[key] = no;
                            }
                        } else if(value[0] == '>') {
                            if(currentObj != null) currentObj[key] = processFoldedBlock(children.shift());
                            else res[key] = processFoldedBlock(children.shift());
                        } else {
                            if(currentObj != null) currentObj[key] = processValue(value);
                            else res[key] = processValue(value);
                        }
                    } else {
                        if(currentObj != null) currentObj[key] = processBlock(children);
                        else res[key] = processBlock(children);
                    }
                } else if(line.match(/^-\s*$/)) {
                    if (isMap) {
                        isMap = false;
                        if (typeof(res.length) === "undefined") {
                            res = [];
                        }
                    }
                    if(currentObj != null) res.push(currentObj);
                    currentObj = {};
                    isMap = true;
                    continue;
                } else if(m = line.match(/^-\s*(.*)/)) {
                    if(currentObj != null)
                        currentObj.push(processValue(m[1]));
                    else {
                        if (isMap) {
                            isMap = false;
                            if (typeof(res.length) === "undefined") {
                                res = [];
                            }
                        }
                        res.push(processValue(m[1]));
                    }
                    continue;
                }
            }

            if(currentObj != null) {
                if (isMap) {
                    isMap = false;
                    if (typeof(res.length) === "undefined") {
                        res = [];
                    }
                }
                res.push(currentObj);
            }
        }

        for(var j = processedBlocks.length - 1; j >= 0; --j) {
            blocks.splice.call(blocks, processedBlocks[j], 1);
        }

        return res;
    }

    function semanticAnalysis(blocks) {
        var res = processBlock(blocks.children);
        return res;
    }

    function preProcess(src) {
        var m;
        var lines = src.split("\n");

        var r = regex["comment"];

        for(var i in lines) {
            if(m = lines[i].match(r)) {
/*                var cmt = "";
                if(typeof m[3] != "undefined")
                    lines[i] = m[1];
                else if(typeof m[3] != "undefined")
                    lines[i] = m[3];
                else
                    lines[i] = "";
                    */
                if(typeof m[3] !== "undefined") {
                    lines[i] = m[0].substr(0, m[0].length - m[3].length);
                }
            }
        }

        return lines.join("\n");
    }

    function eval(str) {
        errors = [];
        reference_blocks = [];
        processing_time = (new Date()).getTime();
        var pre = preProcess(str)
        var doc = parser(pre);
        var res = semanticAnalysis(doc);
        processing_time = (new Date()).getTime() - processing_time;

        return res;
    }

    return {
        /**
         * Load and parse a YAML file from a URL.
         * @param {String} src URL from where to load the YAML file
         * @param {Function} ondone Function that will be called when the file is parsed. The result is passed as an argument.
         * @function
         */
        fromURL : fromURL,

        /**
         * Parse a YAML file from a string.
         * @param {String} str String with the YAML file contents.
         * @function
         */
        eval : eval,

        /**
         * Get errors found when parsing the last file.
         * @function
         * @returns Errors found when parsing the last file.
         */
        getErrors : function() { return errors; },

        /**
         * Get the time it took to parse the last file.
         * @function
         * @returns Time in milliseconds.
         */
        getProcessingTime : function() { return processing_time; }
    }
})();
<|endoftext|>


<commit_before>import traverser from '../traverser';
import multiReplaceStatement from '../utils/multiReplaceStatement';
import VariableDeclaration from '../syntax/VariableDeclaration';

let logger;

export default function(ast, loggerInstance) {
  logger = loggerInstance;
  traverser.traverse(ast, {
    enter(node, parent) {
      if (node.type === 'VariableDeclaration' && node.declarations.length > 1) {
        splitDeclaration(node, parent);

        return traverser.VisitorOption.Skip;
      }
    }
  });
}

function splitDeclaration(node, parent) {
  const declNodes = node.declarations.map(declarator => {
    return new VariableDeclaration(node.kind, [declarator]);
  });

  try {
    multiReplaceStatement({
      parent,
      node,
      replacements: declNodes,
      preserveComments: true,
    });
  }
  catch (e) {
    logger.warn(parent, `Unable to split var statement in a ${parent.type}`, 'multi-var');
  }
}
<commit_msg>Remove global logger var from multiVar transform<commit_after>import traverser from '../traverser';
import multiReplaceStatement from '../utils/multiReplaceStatement';
import VariableDeclaration from '../syntax/VariableDeclaration';

export default function(ast, logger) {
  traverser.traverse(ast, {
    enter(node, parent) {
      if (node.type === 'VariableDeclaration' && node.declarations.length > 1) {
        splitDeclaration(node, parent, logger);

        return traverser.VisitorOption.Skip;
      }
    }
  });
}

function splitDeclaration(node, parent, logger) {
  const declNodes = node.declarations.map(declarator => {
    return new VariableDeclaration(node.kind, [declarator]);
  });

  try {
    multiReplaceStatement({
      parent,
      node,
      replacements: declNodes,
      preserveComments: true,
    });
  }
  catch (e) {
    logger.warn(parent, `Unable to split var statement in a ${parent.type}`, 'multi-var');
  }
}
<|endoftext|>