<commit_before>$.extend({
  keys: function(obj){
    var a = [];
    $.each(obj, function(k){ a.push(k) });
    return a;
  }
});

if (!Array.indexOf) Array.prototype.indexOf = function(obj) {
  for(var i = 0; i < this.length; i++){
    if(this[i] == obj) {
      return i;
    }
  }
  return -1;
}

if (!Array.find_matches) Array.find_matches = function(a) {
  var i, m = [];
  a = a.sort();
  i = a.length
  while(i--) {
    if (a[i - 1] == a[i]) {
      m.push(a[i]);
    }
  }
  if (m.length == 0) {
    return false;
  }
  return m;
}

function VariantOptions(params) {

  var options = params['options'];
  var allow_backorders = !params['track_inventory_levels'] ||  params['allow_backorders'];
  var allow_select_outofstock = params['allow_select_outofstock'];
  var default_instock = params['default_instock'];

  var variant, divs, parent, index = 0;
  var selection = [];
  var buttons;

  var enable_submit = null;
  if (params['enable_submit']) {
    enable_submit = params['enable_submit'];
  } else {
    enable_submit = function() { return true; }
  }

  function init() {
    divs = $('#product-variants .variant-options');
    disable(divs.find('a.option-value').addClass('locked'));
    update();
    enable(parent.find('a.option-value'));
    toggle();
    $('.clear-option a.clear-button').hide().click(handle_clear);

    if (default_instock) {
      divs.each(function(){
        $(this).find("ul.variant-option-values li a.in-stock:first").click();
      });
    }
  }

  function get_index(parent) {
    return parseInt($(parent).attr('class').replace(/[^\d]/g, ''));
  }

  function update(i) {
    index = isNaN(i) ? index : i;
    parent = $(divs.get(index));
    buttons = parent.find('a.option-value');
    parent.find('a.clear-button').hide();
  }

  function disable(btns) {
    return btns.removeClass('selected');
  }

  function enable(btns) {
    bt = btns.not('.unavailable').removeClass('locked').unbind('click')
    if (!allow_select_outofstock && !allow_backorders)
      bt = bt.filter('.in-stock')
    return bt.click(handle_click).filter('.auto-click').removeClass('auto-click').click();
  }

  function advance() {
    index++
    update();
    inventory(buttons.removeClass('locked'));
    enable(buttons);
  }

  function inventory(btns) {
    var keys, variants, count = 0, selected = {};
    var sels = $.map(divs.find('a.selected'), function(i) { return i.rel });
    $.each(sels, function(key, value) {
      key = value.split('-');
      var v = options[key[0]][key[1]];
      keys = $.keys(v);
      var m = Array.find_matches(selection.concat(keys));
      if (selection.length == 0) {
        selection = keys;
      } else if (m) {
        selection = m;
      }
    });
    btns.removeClass('in-stock out-of-stock unavailable').each(function(i, element) {
      variants = get_variant_objects(element.rel);
      keys = $.keys(variants);
      if (keys.length == 0) {
        disable($(element).addClass('unavailable locked').unbind('click'));
      } else if (keys.length == 1) {
        _var = variants[keys[0]];
        $(element).addClass((allow_backorders || _var.count) ? selection.length == 1 ? 'in-stock auto-click' : 'in-stock' : 'out-of-stock');
      } else if (allow_backorders) {
        $(element).addClass('in-stock');
      } else {
        $.each(variants, function(key, value) { count += value.count });
        $(element).addClass(count ? 'in-stock' : 'out-of-stock');
      }
    });
  }

  function get_variant_objects(rels) {
    var i, ids, obj, variants = {};
    if (typeof(rels) == 'string') { rels = [rels]; }
    var otid, ovid, opt, opv;
    i = rels.length;
    try {
      while (i--) {
        ids = rels[i].split('-');
        otid = ids[0];
        ovid = ids[1];
        opt = options[otid];
        if (opt) {
          opv = opt[ovid];
          ids = $.keys(opv);
          if (opv && ids.length) {
            var j = ids.length;
            while (j--) {
              obj = opv[ids[j]];
              if (obj && $.keys(obj).length && 0 <= selection.indexOf(obj.id.toString())) {
                variants[obj.id] = obj;
              }
            }
          }
        }
      }
    } catch(error) {
      //console.log(error);
    }
    return variants;
  }

  function to_f(string) {
    return parseFloat(string.replace(/[^\d\.]/g, ''));
  }

  function find_variant() {
    var selected = divs.find('a.selected');
    var variants = get_variant_objects(selected.get(0).rel);
    if (selected.length == divs.length) {
      return variant = variants[selection[0]];
    } else {
      var prices = [];
      $.each(variants, function(key, value) { prices.push(value.price) });
      prices = $.unique(prices).sort(function(a, b) {
        return to_f(a) < to_f(b) ? -1 : 1;
      });
      if (prices.length == 1) {
        $('#product-price .price').html('' + prices[0] + '');
      } else {
        $('#product-price .price').html('' + prices[0] + ' - ' + prices[prices.length - 1] + '');
      }
      return false;
    }
  }

  function toggle() {
    if (variant) {
      $('#variant_id, form[data-form-type="variant"] input[name$="[variant_id]"]').val(variant.id).change();
      var oldprice = $('#product-price .price').text();
      $('#product-price .price').removeClass('unselected');
      $('#product-price .price').text(variant.price);
      if (variant.retail_price.length > 0)
        $('#product-price .retail').text(variant.retail_price);
      if (oldprice != variant.price) { // highlight price change
          $('#product-price .price').addClass("price-highlight",200);
          $('#product-price .price').removeClass("price-highlight",800);
      }
      if (enable_submit()) {
        if (variant.on_demand || variant.count > 0 || allow_backorders)
          $('#cart-form button[type=submit]').attr('disabled', false).fadeTo(100, 1);
        $('form[data-form-type="variant"] button[type=submit]').attr('disabled', false).fadeTo(100, 1);
      }
      try {
        show_variant_images(variant.id);
      } catch(error) {
        // depends on modified version of product.js
      }
    } else {
      $('#variant_id, form[data-form-type="variant"] input[name$="[variant_id]"]').val('').change();
      $('#cart-form button[type=submit], form[data-form-type="variant"] button[type=submit]').attr('disabled', true).fadeTo(0, 0.5);
    }
  }

  function clear(i) {
    variant = null;
    update(i);
    enable(buttons.removeClass('selected'));
    toggle();
    parent.nextAll().each(function(index, element) {
      disable($(element).find('a.option-value').show().removeClass('in-stock out-of-stock').addClass('locked').unbind('click'));
      $(element).find('a.clear-button').hide();
    });
    show_all_variant_images();
  }

  function handle_clear(evt) {
    evt.preventDefault();
    clear(get_index(this));
  }

  function handle_click(evt) {
    evt.preventDefault();
    variant = null;
    selection = [];
    var a = $(this);
    if (!parent.has(a).length) {
      clear(divs.index(a.parents('.variant-options:first')));
    }
    disable(buttons);
    var a = enable(a.addClass('selected'));
    parent.find('a.clear-button').css('display', 'block');
    advance();
    if (find_variant()) {
      toggle();
    }
  }

  this.selected_variant = function() {
    return variant;
  }

  $(document).ready(init);

};
<commit_msg>Handle cases where inventory count can be < 0<commit_after>$.extend({
  keys: function(obj){
    var a = [];
    $.each(obj, function(k){ a.push(k) });
    return a;
  }
});

if (!Array.indexOf) Array.prototype.indexOf = function(obj) {
  for(var i = 0; i < this.length; i++){
    if(this[i] == obj) {
      return i;
    }
  }
  return -1;
}

if (!Array.find_matches) Array.find_matches = function(a) {
  var i, m = [];
  a = a.sort();
  i = a.length
  while(i--) {
    if (a[i - 1] == a[i]) {
      m.push(a[i]);
    }
  }
  if (m.length == 0) {
    return false;
  }
  return m;
}

function VariantOptions(params) {

  var options = params['options'];
  var allow_backorders = !params['track_inventory_levels'] ||  params['allow_backorders'];
  var allow_select_outofstock = params['allow_select_outofstock'];
  var default_instock = params['default_instock'];

  var variant, divs, parent, index = 0;
  var selection = [];
  var buttons;

  var enable_submit = null;
  if (params['enable_submit']) {
    enable_submit = params['enable_submit'];
  } else {
    enable_submit = function() { return true; }
  }

  function init() {
    divs = $('#product-variants .variant-options');
    disable(divs.find('a.option-value').addClass('locked'));
    update();
    enable(parent.find('a.option-value'));
    toggle();
    $('.clear-option a.clear-button').hide().click(handle_clear);

    if (default_instock) {
      divs.each(function(){
        $(this).find("ul.variant-option-values li a.in-stock:first").click();
      });
    }
  }

  function get_index(parent) {
    return parseInt($(parent).attr('class').replace(/[^\d]/g, ''));
  }

  function update(i) {
    index = isNaN(i) ? index : i;
    parent = $(divs.get(index));
    buttons = parent.find('a.option-value');
    parent.find('a.clear-button').hide();
  }

  function disable(btns) {
    return btns.removeClass('selected');
  }

  function enable(btns) {
    bt = btns.not('.unavailable').removeClass('locked').unbind('click')
    if (!allow_select_outofstock && !allow_backorders)
      bt = bt.filter('.in-stock')
    return bt.click(handle_click).filter('.auto-click').removeClass('auto-click').click();
  }

  function advance() {
    index++
    update();
    inventory(buttons.removeClass('locked'));
    enable(buttons);
  }

  function inventory(btns) {
    var keys, variants, count = 0, selected = {};
    var sels = $.map(divs.find('a.selected'), function(i) { return i.rel });
    $.each(sels, function(key, value) {
      key = value.split('-');
      var v = options[key[0]][key[1]];
      keys = $.keys(v);
      var m = Array.find_matches(selection.concat(keys));
      if (selection.length == 0) {
        selection = keys;
      } else if (m) {
        selection = m;
      }
    });
    btns.removeClass('in-stock out-of-stock unavailable').each(function(i, element) {
      variants = get_variant_objects(element.rel);
      keys = $.keys(variants);
      if (keys.length == 0) {
        disable($(element).addClass('unavailable locked').unbind('click'));
      } else if (keys.length == 1) {
        _var = variants[keys[0]];
        $(element).addClass((allow_backorders || _var.count > 0) ? selection.length == 1 ? 'in-stock auto-click' : 'in-stock' : 'out-of-stock');
      } else if (allow_backorders) {
        $(element).addClass('in-stock');
      } else {
        $.each(variants, function(key, value) { count += value.count });
        $(element).addClass(count > 0 ? 'in-stock' : 'out-of-stock');
      }
    });
  }

  function get_variant_objects(rels) {
    var i, ids, obj, variants = {};
    if (typeof(rels) == 'string') { rels = [rels]; }
    var otid, ovid, opt, opv;
    i = rels.length;
    try {
      while (i--) {
        ids = rels[i].split('-');
        otid = ids[0];
        ovid = ids[1];
        opt = options[otid];
        if (opt) {
          opv = opt[ovid];
          ids = $.keys(opv);
          if (opv && ids.length) {
            var j = ids.length;
            while (j--) {
              obj = opv[ids[j]];
              if (obj && $.keys(obj).length && 0 <= selection.indexOf(obj.id.toString())) {
                variants[obj.id] = obj;
              }
            }
          }
        }
      }
    } catch(error) {
      //console.log(error);
    }
    return variants;
  }

  function to_f(string) {
    return parseFloat(string.replace(/[^\d\.]/g, ''));
  }

  function find_variant() {
    var selected = divs.find('a.selected');
    var variants = get_variant_objects(selected.get(0).rel);
    if (selected.length == divs.length) {
      return variant = variants[selection[0]];
    } else {
      var prices = [];
      $.each(variants, function(key, value) { prices.push(value.price) });
      prices = $.unique(prices).sort(function(a, b) {
        return to_f(a) < to_f(b) ? -1 : 1;
      });
      if (prices.length == 1) {
        $('#product-price .price').html('' + prices[0] + '');
      } else {
        $('#product-price .price').html('' + prices[0] + ' - ' + prices[prices.length - 1] + '');
      }
      return false;
    }
  }

  function toggle() {
    if (variant) {
      $('#variant_id, form[data-form-type="variant"] input[name$="[variant_id]"]').val(variant.id).change();
      var oldprice = $('#product-price .price').text();
      $('#product-price .price').removeClass('unselected');
      $('#product-price .price').text(variant.price);
      if (variant.retail_price.length > 0)
        $('#product-price .retail').text(variant.retail_price);
      if (oldprice != variant.price) { // highlight price change
          $('#product-price .price').addClass("price-highlight",200);
          $('#product-price .price').removeClass("price-highlight",800);
      }
      if (enable_submit()) {
        if (variant.on_demand || variant.count > 0 || allow_backorders)
          $('#cart-form button[type=submit]').attr('disabled', false).fadeTo(100, 1);
        $('form[data-form-type="variant"] button[type=submit]').attr('disabled', false).fadeTo(100, 1);
      }
      try {
        show_variant_images(variant.id);
      } catch(error) {
        // depends on modified version of product.js
      }
    } else {
      $('#variant_id, form[data-form-type="variant"] input[name$="[variant_id]"]').val('').change();
      $('#cart-form button[type=submit], form[data-form-type="variant"] button[type=submit]').attr('disabled', true).fadeTo(0, 0.5);
    }
  }

  function clear(i) {
    variant = null;
    update(i);
    enable(buttons.removeClass('selected'));
    toggle();
    parent.nextAll().each(function(index, element) {
      disable($(element).find('a.option-value').show().removeClass('in-stock out-of-stock').addClass('locked').unbind('click'));
      $(element).find('a.clear-button').hide();
    });
    show_all_variant_images();
  }

  function handle_clear(evt) {
    evt.preventDefault();
    clear(get_index(this));
  }

  function handle_click(evt) {
    evt.preventDefault();
    variant = null;
    selection = [];
    var a = $(this);
    if (!parent.has(a).length) {
      clear(divs.index(a.parents('.variant-options:first')));
    }
    disable(buttons);
    var a = enable(a.addClass('selected'));
    parent.find('a.clear-button').css('display', 'block');
    advance();
    if (find_variant()) {
      toggle();
    }
  }

  this.selected_variant = function() {
    return variant;
  }

  $(document).ready(init);

};
<|endoftext|>


<commit_before>const { parse } = require('graphql/language');
const capitalize = require('lodash/upperFirst');
const { list, one, write, addInputTypes } = require('./utils');

const hasDirective = (ast, model, directive) => {
  const schema = ast.definitions.find(({ name }) => name && name.value === model);
  return schema.directives.filter(({ name }) => name && name.value === 'state').length;
};
module.exports = ({ adapter, resolvers }) => ({
  // Type
  collection: {
    name: 'mongodb',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Model {
            id: String
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
    },
  },
  tags: {
    name: 'mongodb',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Model {
            tags: [String]
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
    },
  },
  state: {
    name: 'state',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Model {
            state: DOCUMENT_STATE
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
    },
    hooks: {
      before: (args, { model, isMutation, returnType }, { ast }) => {
        if (!isMutation && returnType.toString().indexOf('[') === 0 && hasDirective(ast, model, 'state')) {
          const query = (args.query || {});
          if (!query.state) {
            query.state = { eq: 'PUBLISHED' };
            args.query = query;
          }
          return args;
        }
      },
    },
  },
  stamp: {
    name: 'stamp',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Stamps {
            createdAt: DateTime
            updatedAt: DateTime
            createdBy: User @relation
            updatedBy: User @relation
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
      leave(node) {
        resolvers.Query = resolvers.Query || {};
        resolvers.Mutation = resolvers.Mutation || {};
        resolvers[node.name.value] = resolvers[node.name.value] || {};
      },
    },
  },
  // Field
  relation: { // aggregation
    name: 'relation',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node, directive, { resolvers, parent, ancestors, ast }) {
        const parentName = ancestors[ancestors.length - 1].name.value;
        const isList = node.type.kind === 'ListType';
        const type = isList ? node.type.type : node.type;
        const collectionName = type.name.value;

        if (directive.arguments.find(x => x.name.value === 'ignore')) return;
        if (!resolvers[parentName]) resolvers[parentName] = {};

        // one-to-one / one-to-many
        if (!isList) {
          const idType = parse(`
            type ___Field {
              ${node.name.value}Id: String
            }
          `).definitions[0];
          idType.fields.forEach(field => parent.push(field));

          // one-to-many property set (parent -> [children])
          if (directive.arguments.length > 0) {
            const property = directive.arguments.find(x => x.name.value === 'property');
            const relationType = directive.arguments.find(x => x.name.value === 'type');
            if (property && relationType && relationType.value.value) {
              const relIsList = relationType.value.value === 'one-to-many';
              const propType = relIsList ? parse(`
                type ___Field {
                  ${property.value.value}: [${parentName}]
                }
              `).definitions[0] : parse(`
                type ___Field {
                  ${property.value.value}: ${parentName}
                }
              `).definitions[0];

              const def = ast.definitions.find(x => x.name && x.name.value === node.type.name.value);
              propType.fields.forEach(field => def.fields.push(field));
              resolvers[parentName][property.value.value] = relIsList ? list(collectionName, property.value.value, node.name.value) : one(collectionName, property.value.value, node.name.value);
            }
          }
        } else {
          addInputTypes(collectionName, ast);
          const argType = parse(`
            type Query {
              func(query: ${collectionName}Query, sort: ${collectionName}Sort, limit: Int, skip: Int): [${collectionName}]
            }
          `).definitions[0].fields[0];
          argType.arguments.forEach(field => node.arguments.push(field));
          const idType = parse(`
            type ___Field {
              ${node.name.value}Ids: [String]
            }
          `).definitions[0];
          idType.fields.forEach(field => parent.push(field));
        }
        resolvers[parentName][node.name.value] = isList
          ? list(collectionName, node.name.value)
          : one(collectionName, node.name.value);
      },
    },
  },
  // Query/Mutation
  query: {
    name: 'query',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter2(node, directive, { ast }) {
        const isList = node.type.kind === 'ListType';
        const type = isList ? node.type.type : node.type;
        const collectionName = type.name.value;
        addInputTypes(collectionName, ast);

        const field = isList ? parse(`
          type Query {
            func(query: ${collectionName}Query, sort: ${collectionName}Sort, limit: Int, skip: Int): [${collectionName}]
          }
        `).definitions[0].fields[0] : parse(`
          type Query {
            func(id: String, query: ${collectionName}Query): ${collectionName}
          }
        `).definitions[0].fields[0];

        node.arguments = node.arguments.concat(field.arguments);
        resolvers.Query[node.name.value] = isList
          ? list(collectionName)
          : one(collectionName);
      },
    },
  },
  mutate: {
    name: 'mutate',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter2(node, directive, { ast }) {
        const type = node.type;
        const collectionName = type.name.value;

        const field = parse(`
          type Mutation {
            func(id: String, input: ${capitalize(type.name.value)}Input, operationType: OPERATION_TYPE): ${type.name.value}
          }
        `).definitions[0].fields[0];

        node.arguments = node.arguments.concat(field.arguments);
        resolvers.Mutation[node.name.value] = write(collectionName, node.name.value);
      },
    },
  },
});

<commit_msg>set document state of new objects<commit_after>const { parse } = require('graphql/language');
const capitalize = require('lodash/upperFirst');
const { list, one, write, addInputTypes } = require('./utils');

const hasDirective = (ast, model, directive) => {
  const schema = ast.definitions.find(({ name }) => name && name.value === model);
  return schema.directives.filter(({ name }) => name && name.value === 'state').length;
};
module.exports = ({ adapter, resolvers }) => ({
  // Type
  collection: {
    name: 'mongodb',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Model {
            id: String
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
    },
  },
  tags: {
    name: 'mongodb',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Model {
            tags: [String]
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
    },
  },
  state: {
    name: 'state',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Model {
            state: DOCUMENT_STATE
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
    },
    hooks: {
      before: (args, { model, isMutation, returnType }, { ast }) => {
        if (!isMutation && returnType.toString().indexOf('[') === 0 && hasDirective(ast, model, 'state')) {
          const query = (args.query || {});
          if (!query.state) {
            query.state = { eq: 'PUBLISHED' };
            args.query = query;
          }
          return args;
        }
        else if (isMutation && args.input && !args.input.state) {
          args.input.state = 'DRAFT';
          return args;
        }
      },
    },
  },
  stamp: {
    name: 'stamp',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node) {
        const type = parse(`
          type ___Stamps {
            createdAt: DateTime
            updatedAt: DateTime
            createdBy: User @relation
            updatedBy: User @relation
          }
        `).definitions[0];
        node.fields = node.fields.concat(type.fields);
      },
      leave(node) {
        resolvers.Query = resolvers.Query || {};
        resolvers.Mutation = resolvers.Mutation || {};
        resolvers[node.name.value] = resolvers[node.name.value] || {};
      },
    },
  },
  // Field
  relation: { // aggregation
    name: 'relation',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter(node, directive, { resolvers, parent, ancestors, ast }) {
        const parentName = ancestors[ancestors.length - 1].name.value;
        const isList = node.type.kind === 'ListType';
        const type = isList ? node.type.type : node.type;
        const collectionName = type.name.value;

        if (directive.arguments.find(x => x.name.value === 'ignore')) return;
        if (!resolvers[parentName]) resolvers[parentName] = {};

        // one-to-one / one-to-many
        if (!isList) {
          const idType = parse(`
            type ___Field {
              ${node.name.value}Id: String
            }
          `).definitions[0];
          idType.fields.forEach(field => parent.push(field));

          // one-to-many property set (parent -> [children])
          if (directive.arguments.length > 0) {
            const property = directive.arguments.find(x => x.name.value === 'property');
            const relationType = directive.arguments.find(x => x.name.value === 'type');
            if (property && relationType && relationType.value.value) {
              const relIsList = relationType.value.value === 'one-to-many';
              const propType = relIsList ? parse(`
                type ___Field {
                  ${property.value.value}: [${parentName}]
                }
              `).definitions[0] : parse(`
                type ___Field {
                  ${property.value.value}: ${parentName}
                }
              `).definitions[0];

              const def = ast.definitions.find(x => x.name && x.name.value === node.type.name.value);
              propType.fields.forEach(field => def.fields.push(field));
              resolvers[parentName][property.value.value] = relIsList ? list(collectionName, property.value.value, node.name.value) : one(collectionName, property.value.value, node.name.value);
            }
          }
        } else {
          addInputTypes(collectionName, ast);
          const argType = parse(`
            type Query {
              func(query: ${collectionName}Query, sort: ${collectionName}Sort, limit: Int, skip: Int): [${collectionName}]
            }
          `).definitions[0].fields[0];
          argType.arguments.forEach(field => node.arguments.push(field));
          const idType = parse(`
            type ___Field {
              ${node.name.value}Ids: [String]
            }
          `).definitions[0];
          idType.fields.forEach(field => parent.push(field));
        }
        resolvers[parentName][node.name.value] = isList
          ? list(collectionName, node.name.value)
          : one(collectionName, node.name.value);
      },
    },
  },
  // Query/Mutation
  query: {
    name: 'query',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter2(node, directive, { ast }) {
        const isList = node.type.kind === 'ListType';
        const type = isList ? node.type.type : node.type;
        const collectionName = type.name.value;
        addInputTypes(collectionName, ast);

        const field = isList ? parse(`
          type Query {
            func(query: ${collectionName}Query, sort: ${collectionName}Sort, limit: Int, skip: Int): [${collectionName}]
          }
        `).definitions[0].fields[0] : parse(`
          type Query {
            func(id: String, query: ${collectionName}Query): ${collectionName}
          }
        `).definitions[0].fields[0];

        node.arguments = node.arguments.concat(field.arguments);
        resolvers.Query[node.name.value] = isList
          ? list(collectionName)
          : one(collectionName);
      },
    },
  },
  mutate: {
    name: 'mutate',
    description: 'Marks a type as a relative.',
    resolveStatic: {
      enter2(node, directive, { ast }) {
        const type = node.type;
        const collectionName = type.name.value;

        const field = parse(`
          type Mutation {
            func(id: String, input: ${capitalize(type.name.value)}Input, operationType: OPERATION_TYPE): ${type.name.value}
          }
        `).definitions[0].fields[0];

        node.arguments = node.arguments.concat(field.arguments);
        resolvers.Mutation[node.name.value] = write(collectionName, node.name.value);
      },
    },
  },
});

<|endoftext|>


<commit_before>define([
"sq_",
"sqGrid/view/GridHeadEle",
"sqGrid/view/GridRow",
"sqGrid/model/GridHeadEle",
"text!../templates/GridView.html"
], function(sq_, GridHeadEleView, GridRowView, GridHeadEleModel, tplStr){
	return Backbone.View.extend({
		tagName: 'table',

		className: 'table table-striped table-hover sq-grid',

		headEleView: null,

		rowViews: null,

		_selectedRows: null,

		_defaultNls: {
		},

		nls: null,

//		template: sq_.template(tplStr, {
//			nlsObject: {}
//		}),

		initialize: function(params){
			var t = this;
			if(!params){
				params = [];
			}

			t.nls = {};
			$.extend(t.nls, t._defaultNls, params["nls"]);
			t.template = sq_.template(tplStr, {
				nlsObject: t.nls
			});

			t.rowViews = [];
			t.headEleView = [];
			t.columnsStructure = params["columnsStructure"];
			t.collection = params["collection"];
			t.serverSideSort = params["serverSideSort"];
			t.indirectSort = params["indirectSort"];
			t.canClearState = params["canClearState"];
			t.multiSelect = params["multiSelect"];

			t._selectedRows = [];
			t._columnsInfoMap = {};
			var rowContentTplStr = "";
			for(var i = 0; i < t.columnsStructure.length; i++){
				var ci = t.columnsStructure[i];
				t._columnsInfoMap[ci.name] = ci;
				rowContentTplStr += '<%= data.';
				rowContentTplStr += ci.name;
				rowContentTplStr += ' %>	';
			}

			t.rowContentTemplate = sq_.template(rowContentTplStr, {
				nlsObject: {}
			});

		},

		remove: function(){
			var rowViews = this.rowViews;
			if(rowViews){
				for(var i = 0; i < rowViews.length; i++){
					rowViews[i].remove();
				}
			}
			var headEleView = this.headEleView;
			if(headEleView){
				for(var i = 0; i < headEleView.length; i++){
					headEleView[i].remove();
				}
			}
			t._selectedRows = [];
			Backbone.View.prototype.remove.apply(this, arguments);
		},

		render: function(){
			var t = this;
			t.$el.html(this.template({}));
			// Render Header
			t.renderHead();

//			t.listenTo(t.collection, "add", function(model, collection, options){
//				var gridRowView = new GridRowView({
//					model: model,
//					contentTemplate: t.rowContentTemplate
//				});
//				t.rowViews.push[gridRowView];
//				t.$("tbody").append(gridRowView.render().$el);
//			});
			if(t.serverSideSort){
				t.listenTo(t.collection, "reset", function(collection, options){
					console.log();
					while(t.rowViews.length > 0){
						var rv = t.rowViews.pop();
						rv.remove();
					}

					t.collection.each(function(model){
						var gridRowView = new GridRowView({
							model: model,
							gridView: t,
							contentTemplate: t.rowContentTemplate
						});
						t.rowViews.push(gridRowView);
						t.$("tbody").append(gridRowView.render(t.columnsStructure).$el);
					});

					t._selectedRows = [];
					t.trigger("onRedraw");
				});
			}else{
				// TODO: Check what event should be bind to if serverSideSort = false
				t.listenTo(t.collection, "sort", function(collection, options){
					console.log("sort");
					while(t.rowViews.length > 0){
						var rv = t.rowViews.pop();
						rv.remove();
					}

					t.collection.each(function(model){
						var gridRowView = new GridRowView({
							model: model,
							gridView: t,
							contentTemplate: t.rowContentTemplate
						});
						t.rowViews.push(gridRowView);
						t.$("tbody").append(gridRowView.render(t.columnsStructure).$el);
					});

					t._selectedRows = [];
				});
			}

			// TODO: Add add, remove logic
			t.listenTo(t.collection, "remove", function(model, collection, options){
				console.log("remove");
				for(var i = 0; i < t.rowViews.length; i++){
					if(t.rowViews[i].model == model){
						t.rowViews.splice(i,1);
						break;
					}
				}

				for(var i = 0; i < t._selectedRows.length; i++){
					if(t._selectedRows[i].model == model){
						t._selectedRows.splice(i,1);
						break;
					}
				}
			});

			t.listenTo(t.collection, "change", function(model, options){
				console.log("change");
			});

			t.listenTo(t.collection, "reset", function(model, options){
				console.log("reset");
			});

			return this;
		},

		renderHead: function(){
			var t = this;
			var cs = t.columnsStructure;
			for(var i = 0; i < cs.length; i++){
				var ci = cs[i];
				ci.id = i;
				var ghem = new GridHeadEleModel(ci);
				var ghev = new GridHeadEleView({
					model: ghem,
					gridView: t
				});
				t.$("thead tr").append(ghev.render().$el);
				t.headEleView.push(ghev);
			}
		},

//		resetHeadSort: function(){
//			var t = this;
//			t.$(".fa-long-arrow-up").toggleClass("hidden", true);
//			t.$(".fa-long-arrow-down").toggleClass("hidden", true);
//		},

		updateHeadSort: function(columnName, sortType){
			var t = this;
			for(var i = 0; i < t.headEleView.length; i++){
				var hev = t.headEleView[i];
				var name = hev.model.get("name");
				var sortable = hev.model.get("sortable");
				if(columnName == name){
					hev.model.set("sortType", sortType);
				}else{
					hev.model.set("sortType", null);
				}
			}
		},

		getSelectedRows: function(){
			return this._selectedRows;
		},

		clickRow: function(gridRowView, e){
			var t = this;
			var selectedRowsCount = t._selectedRows.length;
			if(t.multiSelect && e.ctrlKey){
				if(gridRowView.model.get("selected")){
					// Deselect Row
					t._deselectSingleRow(gridRowView);
				}else{
					// Select Row
					t._selectSingleRow(gridRowView);
				}
			}else if(t.multiSelect && selectedRowsCount > 1){
				for(var i = 0; i < t.rowViews.length; i++){
					if(t.rowViews[i] == gridRowView){
						// Select Row
						t._selectSingleRow(t.rowViews[i]);
					}else{
						// Deselect Row
						t._deselectSingleRow(t.rowViews[i]);
					}
				}
			}else{
				if(gridRowView.model.get("selected")){
					// Deselect Row
					t._deselectSingleRow(gridRowView);
				}else{
					// Select Row
					for(var i = 0; i < t.rowViews.length; i++){
						if(t.rowViews[i] == gridRowView){
							// Select Row
							t._selectSingleRow(t.rowViews[i]);
						}else{
							// Deselect Row
							t._deselectSingleRow(t.rowViews[i]);
						}
					}
				}
			}

			t.trigger("onClickRow");
		},

		_selectSingleRow: function(gridRowView){
			var t = this;
			var needAdd= true;
			gridRowView.model.set({"selected": true}, {silent: true});
			gridRowView.$el.toggleClass("sq-row-selected", true);

			for(var i = 0; i < t._selectedRows.length; i++){
				if(t._selectedRows[i].model == gridRowView.model){
					needAdd = false;
					break;
				}
			}
			if(needAdd){
				t._selectedRows.push(gridRowView);
				t.trigger("onSelectRow", gridRowView.model);
			}
		},

		_deselectSingleRow: function(gridRowView){
			var t = this;
			gridRowView.model.set({"selected": false}, {silent: true});
			gridRowView.$el.toggleClass("sq-row-selected", false);
			for(var i = 0; i < t._selectedRows.length; i++){
				if(t._selectedRows[i].model == gridRowView.model){
					t._selectedRows.splice(i,1);
					t.trigger("onDeselectRow", gridRowView.model);
					break;
				}
			}
		}
	});
})
<commit_msg>Add i18n support.<commit_after>define([
"sq_",
"sqGrid/view/GridHeadEle",
"sqGrid/view/GridRow",
"sqGrid/model/GridHeadEle",
"text!../templates/GridView.html"
], function(sq_, GridHeadEleView, GridRowView, GridHeadEleModel, tplStr){
	return Backbone.View.extend({
		tagName: 'table',

		className: 'table table-striped table-hover sq-grid',

		headEleView: null,

		rowViews: null,

		_selectedRows: null,

		_defaultNls: {
			"SORT": "Sort",
			"ASCENDING": "Ascending",
			"DESCENDING": "Descending",
			"SORT_ASCENDING": "Sort Ascending",
			"SORT_DESCENDING": "Sort Descending",
			"CLEAR_SORT": "Clear Sort"
		},

		nls: null,

//		template: sq_.template(tplStr, {
//			nlsObject: {}
//		}),

		initialize: function(params){
			var t = this;
			if(!params){
				params = [];
			}

			t.nls = {};
			$.extend(t.nls, t._defaultNls, params["nls"]);
			t.template = sq_.template(tplStr, {
				nlsObject: t.nls
			});

			t.rowViews = [];
			t.headEleView = [];
			t.columnsStructure = params["columnsStructure"];
			t.collection = params["collection"];
			t.serverSideSort = params["serverSideSort"];
			t.indirectSort = params["indirectSort"];
			t.canClearState = params["canClearState"];
			t.multiSelect = params["multiSelect"];

			t._selectedRows = [];
			t._columnsInfoMap = {};
			var rowContentTplStr = "";
			for(var i = 0; i < t.columnsStructure.length; i++){
				var ci = t.columnsStructure[i];
				t._columnsInfoMap[ci.name] = ci;
				rowContentTplStr += '<%= data.';
				rowContentTplStr += ci.name;
				rowContentTplStr += ' %>	';
			}

			t.rowContentTemplate = sq_.template(rowContentTplStr, {
				nlsObject: {}
			});

		},

		remove: function(){
			var rowViews = this.rowViews;
			if(rowViews){
				for(var i = 0; i < rowViews.length; i++){
					rowViews[i].remove();
				}
			}
			var headEleView = this.headEleView;
			if(headEleView){
				for(var i = 0; i < headEleView.length; i++){
					headEleView[i].remove();
				}
			}
			t._selectedRows = [];
			Backbone.View.prototype.remove.apply(this, arguments);
		},

		render: function(){
			var t = this;
			t.$el.html(this.template({}));
			// Render Header
			t.renderHead();

//			t.listenTo(t.collection, "add", function(model, collection, options){
//				var gridRowView = new GridRowView({
//					model: model,
//					contentTemplate: t.rowContentTemplate
//				});
//				t.rowViews.push[gridRowView];
//				t.$("tbody").append(gridRowView.render().$el);
//			});
			if(t.serverSideSort){
				t.listenTo(t.collection, "reset", function(collection, options){
					console.log();
					while(t.rowViews.length > 0){
						var rv = t.rowViews.pop();
						rv.remove();
					}

					t.collection.each(function(model){
						var gridRowView = new GridRowView({
							model: model,
							gridView: t,
							contentTemplate: t.rowContentTemplate
						});
						t.rowViews.push(gridRowView);
						t.$("tbody").append(gridRowView.render(t.columnsStructure).$el);
					});

					t._selectedRows = [];
					t.trigger("onRedraw");
				});
			}else{
				// TODO: Check what event should be bind to if serverSideSort = false
				t.listenTo(t.collection, "sort", function(collection, options){
					console.log("sort");
					while(t.rowViews.length > 0){
						var rv = t.rowViews.pop();
						rv.remove();
					}

					t.collection.each(function(model){
						var gridRowView = new GridRowView({
							model: model,
							gridView: t,
							contentTemplate: t.rowContentTemplate
						});
						t.rowViews.push(gridRowView);
						t.$("tbody").append(gridRowView.render(t.columnsStructure).$el);
					});

					t._selectedRows = [];
				});
			}

			// TODO: Add add, remove logic
			t.listenTo(t.collection, "remove", function(model, collection, options){
				console.log("remove");
				for(var i = 0; i < t.rowViews.length; i++){
					if(t.rowViews[i].model == model){
						t.rowViews.splice(i,1);
						break;
					}
				}

				for(var i = 0; i < t._selectedRows.length; i++){
					if(t._selectedRows[i].model == model){
						t._selectedRows.splice(i,1);
						break;
					}
				}
			});

			t.listenTo(t.collection, "change", function(model, options){
				console.log("change");
			});

			t.listenTo(t.collection, "reset", function(model, options){
				console.log("reset");
			});

			return this;
		},

		renderHead: function(){
			var t = this;
			var cs = t.columnsStructure;
			for(var i = 0; i < cs.length; i++){
				var ci = cs[i];
				ci.id = i;
				var ghem = new GridHeadEleModel(ci);
				var ghev = new GridHeadEleView({
					model: ghem,
					gridView: t,
					nls: {
						"SORT": t.nls["SORT"],
						"ASCENDING": t.nls["ASCENDING"],
						"DESCENDING": t.nls["DESCENDING"],
						"SORT_ASCENDING": t.nls["SORT_ASCENDING"],
						"SORT_DESCENDING": t.nls["SORT_DESCENDING"],
						"CLEAR_SORT": t.nls["CLEAR_SORT"],
					}
				});
				t.$("thead tr").append(ghev.render().$el);
				t.headEleView.push(ghev);
			}
		},

//		resetHeadSort: function(){
//			var t = this;
//			t.$(".fa-long-arrow-up").toggleClass("hidden", true);
//			t.$(".fa-long-arrow-down").toggleClass("hidden", true);
//		},

		updateHeadSort: function(columnName, sortType){
			var t = this;
			for(var i = 0; i < t.headEleView.length; i++){
				var hev = t.headEleView[i];
				var name = hev.model.get("name");
				var sortable = hev.model.get("sortable");
				if(columnName == name){
					hev.model.set("sortType", sortType);
				}else{
					hev.model.set("sortType", null);
				}
			}
		},

		getSelectedRows: function(){
			return this._selectedRows;
		},

		clickRow: function(gridRowView, e){
			var t = this;
			var selectedRowsCount = t._selectedRows.length;
			if(t.multiSelect && e.ctrlKey){
				if(gridRowView.model.get("selected")){
					// Deselect Row
					t._deselectSingleRow(gridRowView);
				}else{
					// Select Row
					t._selectSingleRow(gridRowView);
				}
			}else if(t.multiSelect && selectedRowsCount > 1){
				for(var i = 0; i < t.rowViews.length; i++){
					if(t.rowViews[i] == gridRowView){
						// Select Row
						t._selectSingleRow(t.rowViews[i]);
					}else{
						// Deselect Row
						t._deselectSingleRow(t.rowViews[i]);
					}
				}
			}else{
				if(gridRowView.model.get("selected")){
					// Deselect Row
					t._deselectSingleRow(gridRowView);
				}else{
					// Select Row
					for(var i = 0; i < t.rowViews.length; i++){
						if(t.rowViews[i] == gridRowView){
							// Select Row
							t._selectSingleRow(t.rowViews[i]);
						}else{
							// Deselect Row
							t._deselectSingleRow(t.rowViews[i]);
						}
					}
				}
			}

			t.trigger("onClickRow");
		},

		_selectSingleRow: function(gridRowView){
			var t = this;
			var needAdd= true;
			gridRowView.model.set({"selected": true}, {silent: true});
			gridRowView.$el.toggleClass("sq-row-selected", true);

			for(var i = 0; i < t._selectedRows.length; i++){
				if(t._selectedRows[i].model == gridRowView.model){
					needAdd = false;
					break;
				}
			}
			if(needAdd){
				t._selectedRows.push(gridRowView);
				t.trigger("onSelectRow", gridRowView.model);
			}
		},

		_deselectSingleRow: function(gridRowView){
			var t = this;
			gridRowView.model.set({"selected": false}, {silent: true});
			gridRowView.$el.toggleClass("sq-row-selected", false);
			for(var i = 0; i < t._selectedRows.length; i++){
				if(t._selectedRows[i].model == gridRowView.model){
					t._selectedRows.splice(i,1);
					t.trigger("onDeselectRow", gridRowView.model);
					break;
				}
			}
		}
	});
})
<|endoftext|>


<commit_before>var Nav = require('./po/nav'),
	db = require('./testdata'),
	ProductList = require('./po/productList'),
	server = require('./server');

describe('Searching', function(){
	var nav, productList;

	beforeEach(server.boot);
	afterEach(server.shutdown);

	beforeEach(function(done){
		nav = new Nav();
		productList = new ProductList();

		var that = this;
		db.clearDB(function(err){
			if (err) return done(err);
			db.createProducts(function(err, prods){
				if (err) return done(err);
				that.products = prods;
				done();
			});
		});
	});

	it('allows finding items', function(){
		var that = this;
		browser.get('#/');
		// GIVEN I am a user
		// WHEN I search for an item
		nav.searchBox.sendKeys('galaxy');
		nav.searchButton.click();
		// THEN I am shown a list of products for which the names contain my
		// search keyword, case insensitive
		productList.productNames.map(function(row){
			return row.getText();
		}).then(function(names){
			if(names[0] === that.products[0].name){
				expect(names[1]).toBe(that.products[1].name);
			}else{
				expect(names[0]).toBe(that.products[1].name);
				expect(names[1]).toBe(that.products[0].name);
			}
		});
	});

	it('gives suggestions', function(){
		browser.get('#/');
		var that = this;

		// GIVEN I am a user
		// WHEN I type my search keyword
		nav.searchBox.sendKeys('alax'); //We will get back the two galaxy phones in the dataset
		nav.searchSuggestions.then(function(suggests){

			// THEN I am shown some results as I am typing
			expect(suggests.length).toBe(2);

			suggests[0].getText().then(function(text){
				var suggest;
				if(text === that.products[0].name){
					suggest = suggests[0];
				}else{
					suggest = suggests[1];
				}
				// AND by clicking on one of them I am shown that product
				suggest.click();
				productList.productNames.then(function(names){
					expect(names.length).toBe(1);
					expect(names[0].getText()).toBe(that.products[0].name);
				});
			});

		});
	});

});<commit_msg>Ignore this commit<commit_after>var Nav = require('./po/nav'),
	db = require('./testdata'),
	ProductList = require('./po/productList'),
	server = require('./server');

describe('Searching', function(){
	var nav, productList;

	beforeEach(server.boot);
	afterEach(server.shutdown);

	beforeEach(function(done){
		nav = new Nav();
		productList = new ProductList();

		var that = this;
		db.clearDB(function(err){
			if (err) return done(err);
			db.createProducts(function(err, prods){
				if (err) return done(err);
				that.products = prods;
				done();
			});
		});
	});

	it('allows finding items', function(){
		var that = this;
		browser.get('#/');
		// GIVEN I am a user
		// WHEN I search for an item
		nav.searchBox.sendKeys('galaxy');
		nav.searchButton.click();
		// THEN I am shown a list of products for which the names contain my
		// search keyword, case insensitive
		productList.productNames.map(function(row){
			return row.getText();
		}).then(function(names){
			if(names[0] === that.products[0].name){
				expect(names[1]).toBe(that.products[1].name);
			}else{
				expect(names[0]).toBe(that.products[1].name);
				expect(names[1]).toBe(that.products[0].name);
			}
		});
	});

	it('gives suggestions', function(){
		browser.get('#/');
		var that = this;

		// GIVEN I am a user
		// WHEN I type my search keyword
		nav.searchBox.sendKeys('alax'); //We will get back the two galaxy phones in the dataset
		nav.searchSuggestions.then(function(suggests){

			// THEN I am shown some results as I am typing
			expect(suggests.length).toBe(2);

			suggests[0].getText().then(function(text){
				var suggest;
				if(text === that.products[0].name){
					suggest = suggests[0];
				}else{
					suggest = suggests[1];
				}
				// AND by clicking on one of them I am shown that product
				suggest.click();
				productList.productNames.then(function(names){
					expect(names.length).toBe(1);
					expect(names[0].getText()).toBe(that.products[0].name);
				});
			});

		});
	});

});
<|endoftext|>


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

function start() {
  require('../lib/launcher')();
}

var cmd = process.argv[2];
if (cmd === 'start') {

  start();

} else if (cmd === '-v' || cmd === '--version') {

  console.log('v%s (eslint_d v%s)',
    require('eslint/package.json').version,
    require('../package.json').version);

} else if (cmd === '-h' || cmd === '--help') {

  var options = require('../lib/options');
  console.log(options.generateHelp());

} else {

  var client = require('../lib/client');
  if (cmd === 'restart') {
    client.stop(function () {
      process.nextTick(start);
    });
  } else {
    var commands = ['stop', 'status', 'restart'];
    if (commands.indexOf(cmd) === -1) {
      var concat = require('concat-stream');
      var useStdIn = (process.argv.indexOf('--stdin') > -1);

      if (useStdIn) {
        process.stdin.pipe(concat({ encoding: 'string' }, function (text) {
          client.lint(process.argv.slice(2), text);
        }));
      } else {
        client.lint(process.argv.slice(2));
      }
    } else {
      client[cmd](process.argv.slice(3));
    }
  }

}
<commit_msg>Move require into conditional.<commit_after>#!/usr/bin/env node
'use strict';

function start() {
  require('../lib/launcher')();
}

var cmd = process.argv[2];
if (cmd === 'start') {

  start();

} else if (cmd === '-v' || cmd === '--version') {

  console.log('v%s (eslint_d v%s)',
    require('eslint/package.json').version,
    require('../package.json').version);

} else if (cmd === '-h' || cmd === '--help') {

  var options = require('../lib/options');
  console.log(options.generateHelp());

} else {

  var client = require('../lib/client');
  if (cmd === 'restart') {
    client.stop(function () {
      process.nextTick(start);
    });
  } else {
    var commands = ['stop', 'status', 'restart'];
    if (commands.indexOf(cmd) === -1) {
      var useStdIn = (process.argv.indexOf('--stdin') > -1);

      if (useStdIn) {
        var concat = require('concat-stream');
        process.stdin.pipe(concat({ encoding: 'string' }, function (text) {
          client.lint(process.argv.slice(2), text);
        }));
      } else {
        client.lint(process.argv.slice(2));
      }
    } else {
      client[cmd](process.argv.slice(3));
    }
  }

}
<|endoftext|>


<commit_before>var chai = require('chai')
var sinon = require('sinon')

var expect = chai.expect
chai.use(require('sinon-chai'))
chai.use(require('chai-properties'))

var controllers = require('../autoBlock')

describe('step .with', () => {
  var sandbox

  beforeEach(() => {
    sandbox = sinon.sandbox.create()
  })

  afterEach(() => {
    sandbox.restore()
  })

  it('object notation', (done) => {
    var one = sinon.stub().callsArgWith(1, null, 'alpha')
    var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'})

    var three = (results, cb) => {
      expect(results).to.have.properties({
        a: 'alpha',
        b: {
          c: 'delta'
        }
      })

      cb()
    }

    var final = (err, response) => {
      expect(err).to.not.exist
      done()
    }

    var controller = {
      data: {
        event: { foo: 'bar' }
      },
      done: final
    }

    controller.block = {
      'one': {
        func: one
      },
      'two': {
        func: two
      },
      'three': {
        func: three,
        with: {
          'a': 'one',
          'b.c': 'two.beta'
        }
      }
    }

    controllers.run(controller)
  })

  it('array notation', (done) => {
    var one = sinon.stub().callsArgWith(1, null, 'alpha')
    var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'})

    var three = (a, b, cb) => {
      expect(a).to.eql('alpha')
      expect(b).to.eql('delta')

      cb()
    }

    var final = (err, response) => {
      expect(err).to.not.exist
      done()
    }

    var controller = {
      data: {
        event: { foo: 'bar' }
      },
      done: final
    }

    controller.block = {
      'one': {
        func: one
      },
      'two': {
        func: two
      },
      'three': {
        func: three,
        with: ['one', 'two.beta']
      }
    }

    controllers.run(controller)
  })

  it('missing', (done) => {
    var one = sinon.stub().callsArgWith(1, null, 'alpha')
    var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'})

    var three = (results, cb) => {
      expect(results).to.have.properties({
        a: 'alpha',
        b: {
          c: 'delta'
        }
      })

      cb()
    }

    var final = (err, response) => {
      expect(err).to.not.exist
      done()
    }

    var controller = {
      data: {
        event: { foo: 'bar' }
      },
      done: final
    }

    controller.block = {
      'one': {
        func: one
      },
      'two': {
        func: two
      },
      'three': {
        func: three,
        with: {
          'a': 'one',
          'b.c': 'two.beta'
        }
      }
    }

    controllers.run(controller)
  })
})
<commit_msg>Fix test<commit_after>var chai = require('chai')
var sinon = require('sinon')

var expect = chai.expect
chai.use(require('sinon-chai'))
chai.use(require('chai-properties'))

var controllers = require('../autoBlock')

describe('step .with', () => {
  var sandbox

  beforeEach(() => {
    sandbox = sinon.sandbox.create()
  })

  afterEach(() => {
    sandbox.restore()
  })

  it('object notation', (done) => {
    var one = sinon.stub().callsArgWith(1, null, 'alpha')
    var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'})

    var three = (results, cb) => {
      expect(results).to.have.properties({
        a: 'alpha',
        b: {
          c: 'delta'
        }
      })

      cb()
    }

    var final = (err, response) => {
      expect(err).to.not.exist
      done()
    }

    var controller = {
      data: {
        event: { foo: 'bar' }
      },
      done: final
    }

    controller.block = {
      'one': {
        func: one
      },
      'two': {
        func: two
      },
      'three': {
        func: three,
        with: {
          'a': 'one',
          'b.c': 'two.beta'
        }
      }
    }

    controllers.run(controller)
  })

  it('array notation', (done) => {
    var one = sinon.stub().callsArgWith(1, null, 'alpha')
    var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'})

    var three = (a, b, cb) => {
      expect(a).to.eql('alpha')
      expect(b).to.eql('delta')

      cb()
    }

    var final = (err, response) => {
      expect(err).to.not.exist
      done()
    }

    var controller = {
      data: {
        event: { foo: 'bar' }
      },
      done: final
    }

    controller.block = {
      'one': {
        func: one
      },
      'two': {
        func: two
      },
      'three': {
        func: three,
        with: ['one', 'two.beta']
      }
    }

    controllers.run(controller)
  })

  it('missing', (done) => {
    var one = sinon.stub().callsArgWith(1, null, 'alpha')
    var two = sinon.stub().callsArgWith(1, null, {'beta': 'delta'})

    var three = (results, cb) => {
      expect(results).to.have.properties({
        b: {
          c: 'delta'
        }
      })

      cb()
    }

    var final = (err, response) => {
      expect(err).to.not.exist
      done()
    }

    var controller = {
      data: {
        event: { foo: 'bar' }
      },
      done: final
    }

    controller.block = {
      'one': {
        func: one
      },
      'two': {
        func: two
      },
      'three': {
        func: three,
        with: {
          'a': 'one.alpha',
          'b.c': 'two.beta'
        }
      }
    }

    controllers.run(controller)
  })
})
<|endoftext|>


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

var minimist = require('minimist')
  , fs       = require('fs')
  , path     = require('path')
  , exorcist = require('../')
  ;

function onerror(err) {
  console.error(err.toString());
  process.exit(err.errno || 1);
}

function usage() {
  var usageFile = path.join(__dirname, 'usage.txt');
  fs.createReadStream(usageFile).pipe(process.stdout);
  return;
}

(function damnYouEsprima() {

var argv = minimist(process.argv.slice(2)
  , { boolean: [ 'h', 'help', 'e', 'error-on-missing' ]
    , string: [ 'url', 'u', 'root', 'r', 'base', 'b' ]
  });

if (argv.h || argv.help) return usage();

var mapfile = argv._.shift();
if (!mapfile) {
  console.error('Missing map file');
  return usage();
}

var url            = argv.url            || argv.u
  , root           = argv.root           || argv.r
  , base           = argv.base           || argv.b
  , errorOnMissing = argv.errorOnMissing || argv.e;

mapfile = path.resolve(mapfile);

process.stdin
  .pipe(exorcist(mapfile, url, root, base, errorOnMissing))
  .on('error', onerror)
  .on('missing-map', console.error.bind(console))
  .pipe(process.stdout);

})()
<commit_msg>Fix `error on missing` argument so it works from CLI (#43)<commit_after>#!/usr/bin/env node
'use strict';

var minimist = require('minimist')
  , fs       = require('fs')
  , path     = require('path')
  , exorcist = require('../')
  ;

function onerror(err) {
  console.error(err.toString());
  process.exit(err.errno || 1);
}

function usage() {
  var usageFile = path.join(__dirname, 'usage.txt');
  fs.createReadStream(usageFile).pipe(process.stdout);
  return;
}

(function damnYouEsprima() {

var argv = minimist(process.argv.slice(2)
  , { boolean: [ 'h', 'help', 'e', 'error-on-missing' ]
    , string: [ 'url', 'u', 'root', 'r', 'base', 'b' ]
  });

if (argv.h || argv.help) return usage();

var mapfile = argv._.shift();
if (!mapfile) {
  console.error('Missing map file');
  return usage();
}

var url            = argv.url            || argv.u
  , root           = argv.root           || argv.r
  , base           = argv.base           || argv.b
  , errorOnMissing = argv.errorOnMissing || argv.e || argv['error-on-missing'];

mapfile = path.resolve(mapfile);

process.stdin
  .pipe(exorcist(mapfile, url, root, base, errorOnMissing))
  .on('error', onerror)
  .on('missing-map', console.error.bind(console))
  .pipe(process.stdout);

})()
<|endoftext|>


<commit_before>/*INSTALL-
ffmpeg - npm install ffmpeg-binaries
an opus encoder, choose one from below:
npm install opusscript
npm install node-opus*/

//https://listen.moe/stream
//http://momori.animenfo.com:8000/;?.mp3
//id canal musica = 375842517566095360

module.exports = (client, message, args) => {

    let channel = client.channels.get('375842517566095360');
            //if (message.member.voiceChannel) {
                if (channel) {

              channel.join()
                .then(connection => {
                  message.reply('Eu conectei no canal com sucesso!');
                  connection.playArbitraryInput('http://momori.animenfo.com:8000/;?.mp3');
                  //connection.playFile('./radio/anime01.pls');
                })
                .catch(console.log);
                } /*else {
              message.reply('Você precisa estar em um canal de voz para digitar o comando!');
            }  */

};<commit_msg><commit_after>/*INSTALL-
ffmpeg - npm install ffmpeg-binaries
an opus encoder, choose one from below:
npm install opusscript
npm install node-opus*/

//Radio Moe : https://listen.moe/stream
//Radio AnimeNfo : http://momori.animenfo.com:8000/;?.mp3
//Radio Initial D : http://go2id.net:9001/index.html?sid=1

//id canal musica = 375842517566095360

module.exports = (client, message, args) => {

    let channel = client.channels.get('375842517566095360');
            //if (message.member.voiceChannel) {
                if (channel) {

              channel.join()
                .then(connection => {
                  message.reply('Eu conectei no canal com sucesso!');
                  connection.playArbitraryInput('http://go2id.net:9001/index.html?sid=1');
                  //connection.playFile('./radio/anime01.pls');
                })
                .catch(console.log);
                } /*else {
              message.reply('Você precisa estar em um canal de voz para digitar o comando!');
            }  */

};<|endoftext|>


<commit_before>import Ember from 'ember';

const { computed } = Ember;

export default Ember.Component.extend({
  localClassNames: ['canvas-channel-list'],
  isEditingChannels: false,

  canvasChannels: computed('channelIds.[]', 'channels.[]', function() {
    return this.get('channelIds')
               .map(id => this.get('channels').findBy('id', id))
               .compact();
  }),

  channelList: computed('canvasChannels.[]', function() {
    return this.get('canvasChannels')
               .mapBy('name')
               .join(', ');
  }),

  selectedChannels: computed(function() {
    return this.get('canvasChannels');
  }),

  actions: {
    persistChannels() {
      this.set('isEditingChannels', false);
      this.get('updateCanvasChannels')(this.get('selectedChannels'));
    }
  }
});
<commit_msg>Remove unused channelList property<commit_after>import Ember from 'ember';

const { computed } = Ember;

export default Ember.Component.extend({
  localClassNames: ['canvas-channel-list'],
  isEditingChannels: false,

  canvasChannels: computed('channelIds.[]', 'channels.[]', function() {
    return this.get('channelIds')
               .map(id => this.get('channels').findBy('id', id))
               .compact();
  }),

  selectedChannels: computed(function() {
    return this.get('canvasChannels');
  }),

  actions: {
    persistChannels() {
      this.set('isEditingChannels', false);
      this.get('updateCanvasChannels')(this.get('selectedChannels'));
    }
  }
});
<|endoftext|>


<commit_before>define(['scripts/gameStates/SummaryState'], function(SummaryState){
  'use strict';

  describe('SummaryState', function(){
    var summaryState, game = {
      $player1: {possessive: 'Your'},
      $player2: {possessive: 'Robo\'s'}
    };
    describe('Constructor', function(){
      it('should define the summary state', function(){
        summaryState = new SummaryState({});

        expect(summaryState).toBeDefined();
      });
    });
  });
});
<commit_msg>jshint unused var<commit_after>define(['scripts/gameStates/SummaryState'], function(SummaryState){
  'use strict';

  describe('SummaryState', function(){
    describe('Constructor', function(){
      it('should define the summary state', function(){
        summaryState = new SummaryState({});

        expect(summaryState).toBeDefined();
      });
    });
  });
});
<|endoftext|>


<commit_before>import { assert } from 'chai';
import * as library from './../index.js';
import InvalidRouteCollectionError from './../lib/error/InvalidRouteCollectionError.js';
import InvalidRouteError from './../lib/error/InvalidRouteError.js';
import RouteMissingError from './../lib/error/RouteMissingError.js';
import InvalidParameterError from './../lib/error/InvalidParameterError.js';
import RouteMatch from './../lib/model/routeMatch.js';

describe('RouteCollection', function () {
    describe('Instantiation', function () {

        it('Throws an Error when instantiated with a non-array routes collection', function () {
            var nonArrayValues = [1, 'test', {}, /[a-z]+/];

            for (let i = 0, l = nonArrayValues.length; i < l; i++) {
                try {
                    var test = new library.RouteCollection(nonArrayValues[i]);

                    assert.notOk(`No Error was thrown when providing the value: ${nonArrayValues[i].toString()}`);
                } catch (error) {
                    assert.ok(error instanceof InvalidRouteCollectionError);
                }
            }
        });

        it('Throws an Error when instantiated with an array that does contain non-route instances', function () {
            var arrayWithNonAcceptedValue = ['non accepted value'];

            try {
                new library.RouteCollection(arrayWithNonAcceptedValue);

                assert.notOk(`No Error was trown when providing the value: ${arrayWithNonAcceptedValue.toString()}`);
            } catch (error) {
                assert.ok(error instanceof InvalidRouteError);
            }
        });

        it('Allows instantiation with an array with routes', function () {
            var instance = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(instance instanceof library.RouteCollection, 'Could not instantiate with valid route collection');
        });
    });

    describe('Counting routes', function () {
        it('Returns the valid number of routes in the collection when there are no items in it', function () {
            var myRouteCollection = new library.RouteCollection();

            assert.ok(myRouteCollection.count() === 0);
        });

        it('Returns the valid number of routes in the collection with items in it', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.count() === 1);
        });
    });

    describe('Retrieving routes from the collection', function () {
        it('Allows me to retrieve my routes from the collection by name', function () {
            var myRoute = new library.Route('some_route', '/some-path');

            var myRouteCollection = new library.RouteCollection([myRoute]);

            assert.ok(myRouteCollection.findByName('some_route') === myRoute);
        });

        it('Returns a supplied default value when the route was not found', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var defaultValue = 'default value';

            assert.ok(myRouteCollection.findByName('a_non_existant_route', defaultValue) === defaultValue);
        });

        it('Returns null when the route was not found and no default value was supplied', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.findByName('a_non_existant_route') === null);
        });

        it('Allows me to retrieve routes from the collection using a callback function', function () {
            var otherRoute = new library.Route('some_other_route', '/some-other-path');

            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path'),
                otherRoute
            ]);

            var found = myRouteCollection.find(function (route) {
                return route.name.match(/other/) !== null;
            });

            assert.ok(found === otherRoute);
        });

        it('Allows me to retrieve all routes from a collection at once', function () {
            var myRoute = new library.Route('some_route', '/some-path');

            var myRouteCollection = new library.RouteCollection([
                myRoute
            ]);

            assert.ok(myRouteCollection.count() === 1);

            var anArrayWithAllRoutes = myRouteCollection.all();

            assert.ok(anArrayWithAllRoutes.indexOf(myRoute) !== -1);
        });
    });

    describe('Removing routes from the collection', function () {
        it('Allows me to remove a route from the collection', function () {
            var myRoute = new library.Route('some_route', '/some-path');

            var myRouteCollection = new library.RouteCollection([
                myRoute
            ]);

            assert.ok(myRouteCollection.count() === 1);

            myRouteCollection.remove(myRoute);

            assert.ok(myRouteCollection.count() === 0);
        });

        it('Allows me to remove a route from the collection by name', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.count() === 1);

            myRouteCollection.removeByName('some_route');

            assert.ok(myRouteCollection.count() === 0);
        });

        it('Allows me to remove all routes from the collection at once', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.count() === 1);

            myRouteCollection.clear();

            assert.ok(myRouteCollection.count() === 0);
        });
    });

    describe('Adding routes to an existing collection', function () {
        it('Has more routes in it when a new route was added', function () {
            var myRouteCollection = new library.RouteCollection([]);

            myRouteCollection.add(new library.Route('some_route', '/some-path'));

            assert.ok(myRouteCollection.count() === 1);
        });
    });

    describe('Loping through the routes in the collection', function () {
        it('Allows you to loop through all items', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var count = 0;

            myRouteCollection.each(function (route) {
                assert.ok(route instanceof library.Route);

                count++;
            });

            assert.ok(myRouteCollection.count() === count);
        });
    });
});

describe('UrlMatcher', function () {
    describe('Instantiation', function () {
        it('Throws an Error when instantiated without route collection', function () {
            try {
                new library.UrlMatcher();

                assert.nogOk('UrlGenerator could be instantiated without route collection');
            } catch (error) {
                assert.ok(error instanceof InvalidRouteCollectionError);
            }
        });

        it('Instantiates when providing a valid instance of Route Collection', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher instanceof library.UrlMatcher);
        });
    });

    describe('Matching urls', function () {
        it('Returns null when no route matches', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher.match('/some-other-route') === null);
        });

        it('Returns a RouteMatch instance when a route matches', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher.match('/some-path') instanceof RouteMatch);
        });

        it('Allows you to to define route parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/user/:id')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            var match = myUrlMatcher.match('/user/10');

            assert.ok(match instanceof RouteMatch);
            assert.ok(typeof match.params['id'] !== 'undefined');
            assert.ok(parseInt(match.params['id']) === 10);
        });

        it('Allows you to specify a regex against route parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/user/:id(\\d+)')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher.match('/user/12') instanceof RouteMatch);
            assert.ok(myUrlMatcher.match('/user/test') === null);
        });

        it('Supports query parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/user/:id(\\d+)')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            var match = myUrlMatcher.match('/user/12?test=10&test2=water');

            assert.ok(match instanceof RouteMatch);

            assert.ok(typeof match.params['test'] !== 'undefined');
            assert.ok(match.params['test'] === '10');

            assert.ok(typeof match.params['test2'] !== 'undefined');
            assert.ok(match.params['test2'] === 'water');
        });
    });
});

describe('UrlGenerator', function () {
    describe('Instantiation', function () {
        it('Throws an error when instantiated without a route collection', function () {
            try {
                new library.UrlGenerator();

                assert.notOk('Should not get to this point');
            } catch (error) {
                assert.ok(error instanceof InvalidRouteCollectionError);
            }
        });

        it('Allows instantiation with a route collection', function () {
            var myUrlGenerator = new library.UrlGenerator(new library.RouteCollection());

            assert.ok(myUrlGenerator instanceof library.UrlGenerator);
        });
    });

    describe('Generating urls', function () {
        it('throws an error when you try to generate an url for an non-existant route', function () {
            var myRouteCollection = new library.RouteCollection([]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            try {
                myUrlGenerator.generate('non_existant_route');

                assert.notOk('Should not get to this point');
            } catch (error) {
                assert.ok(error instanceof RouteMissingError);
            }
        });

        it('Generates an url without parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('home', '/')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            assert.ok(myUrlGenerator.generate('home') === '/');
        });

        it('Generates an url with parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('user_detail', '/user/:id')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            var generatedPath = myUrlGenerator.generate('user_detail', {
                id: 10
            });

            assert.ok(generatedPath === '/user/10');
        });

        it('Validates if the supplied parameters match the required pattern', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('user_detail', '/user/:id(\\d+)')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            try {
                myUrlGenerator.generate('user_detail', {
                    id: 'not_allowed_value'
                });
            } catch (error) {
                assert.ok(error instanceof InvalidParameterError);
            }
        });

        it('Adds extra parameters as query parameters to the url', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('home', '/')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            var generatedUrl = myUrlGenerator.generate('home', {
                test: 'other'
            });

            assert.ok(generatedUrl === '/?test=other');
        });
    });
});
<commit_msg>Supply a payload to the route match when set on route<commit_after>import { assert } from 'chai';
import * as library from './../index.js';
import InvalidRouteCollectionError from './../lib/error/InvalidRouteCollectionError.js';
import InvalidRouteError from './../lib/error/InvalidRouteError.js';
import RouteMissingError from './../lib/error/RouteMissingError.js';
import InvalidParameterError from './../lib/error/InvalidParameterError.js';
import RouteMatch from './../lib/model/routeMatch.js';

describe('RouteCollection', function () {
    describe('Instantiation', function () {

        it('Throws an Error when instantiated with a non-array routes collection', function () {
            var nonArrayValues = [1, 'test', {}, /[a-z]+/];

            for (let i = 0, l = nonArrayValues.length; i < l; i++) {
                try {
                    var test = new library.RouteCollection(nonArrayValues[i]);

                    assert.notOk(`No Error was thrown when providing the value: ${nonArrayValues[i].toString()}`);
                } catch (error) {
                    assert.ok(error instanceof InvalidRouteCollectionError);
                }
            }
        });

        it('Throws an Error when instantiated with an array that does contain non-route instances', function () {
            var arrayWithNonAcceptedValue = ['non accepted value'];

            try {
                new library.RouteCollection(arrayWithNonAcceptedValue);

                assert.notOk(`No Error was trown when providing the value: ${arrayWithNonAcceptedValue.toString()}`);
            } catch (error) {
                assert.ok(error instanceof InvalidRouteError);
            }
        });

        it('Allows instantiation with an array with routes', function () {
            var instance = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(instance instanceof library.RouteCollection, 'Could not instantiate with valid route collection');
        });
    });

    describe('Counting routes', function () {
        it('Returns the valid number of routes in the collection when there are no items in it', function () {
            var myRouteCollection = new library.RouteCollection();

            assert.ok(myRouteCollection.count() === 0);
        });

        it('Returns the valid number of routes in the collection with items in it', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.count() === 1);
        });
    });

    describe('Retrieving routes from the collection', function () {
        it('Allows me to retrieve my routes from the collection by name', function () {
            var myRoute = new library.Route('some_route', '/some-path');

            var myRouteCollection = new library.RouteCollection([myRoute]);

            assert.ok(myRouteCollection.findByName('some_route') === myRoute);
        });

        it('Returns a supplied default value when the route was not found', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var defaultValue = 'default value';

            assert.ok(myRouteCollection.findByName('a_non_existant_route', defaultValue) === defaultValue);
        });

        it('Returns null when the route was not found and no default value was supplied', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.findByName('a_non_existant_route') === null);
        });

        it('Allows me to retrieve routes from the collection using a callback function', function () {
            var otherRoute = new library.Route('some_other_route', '/some-other-path');

            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path'),
                otherRoute
            ]);

            var found = myRouteCollection.find(function (route) {
                return route.name.match(/other/) !== null;
            });

            assert.ok(found === otherRoute);
        });

        it('Allows me to retrieve all routes from a collection at once', function () {
            var myRoute = new library.Route('some_route', '/some-path');

            var myRouteCollection = new library.RouteCollection([
                myRoute
            ]);

            assert.ok(myRouteCollection.count() === 1);

            var anArrayWithAllRoutes = myRouteCollection.all();

            assert.ok(anArrayWithAllRoutes.indexOf(myRoute) !== -1);
        });
    });

    describe('Removing routes from the collection', function () {
        it('Allows me to remove a route from the collection', function () {
            var myRoute = new library.Route('some_route', '/some-path');

            var myRouteCollection = new library.RouteCollection([
                myRoute
            ]);

            assert.ok(myRouteCollection.count() === 1);

            myRouteCollection.remove(myRoute);

            assert.ok(myRouteCollection.count() === 0);
        });

        it('Allows me to remove a route from the collection by name', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.count() === 1);

            myRouteCollection.removeByName('some_route');

            assert.ok(myRouteCollection.count() === 0);
        });

        it('Allows me to remove all routes from the collection at once', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            assert.ok(myRouteCollection.count() === 1);

            myRouteCollection.clear();

            assert.ok(myRouteCollection.count() === 0);
        });
    });

    describe('Adding routes to an existing collection', function () {
        it('Has more routes in it when a new route was added', function () {
            var myRouteCollection = new library.RouteCollection([]);

            myRouteCollection.add(new library.Route('some_route', '/some-path'));

            assert.ok(myRouteCollection.count() === 1);
        });
    });

    describe('Loping through the routes in the collection', function () {
        it('Allows you to loop through all items', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var count = 0;

            myRouteCollection.each(function (route) {
                assert.ok(route instanceof library.Route);

                count++;
            });

            assert.ok(myRouteCollection.count() === count);
        });
    });
});

describe('UrlMatcher', function () {
    describe('Instantiation', function () {
        it('Throws an Error when instantiated without route collection', function () {
            try {
                new library.UrlMatcher();

                assert.nogOk('UrlGenerator could be instantiated without route collection');
            } catch (error) {
                assert.ok(error instanceof InvalidRouteCollectionError);
            }
        });

        it('Instantiates when providing a valid instance of Route Collection', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher instanceof library.UrlMatcher);
        });
    });

    describe('Matching urls', function () {
        it('Returns null when no route matches', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher.match('/some-other-route') === null);
        });

        it('Returns a RouteMatch instance when a route matches', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/some-path')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher.match('/some-path') instanceof RouteMatch);
        });

        it('Allows you to to define route parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/user/:id')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            var match = myUrlMatcher.match('/user/10');

            assert.ok(match instanceof RouteMatch);
            assert.ok(typeof match.params['id'] !== 'undefined');
            assert.ok(parseInt(match.params['id']) === 10);
        });

        it('Allows you to specify a regex against route parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/user/:id(\\d+)')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            assert.ok(myUrlMatcher.match('/user/12') instanceof RouteMatch);
            assert.ok(myUrlMatcher.match('/user/test') === null);
        });

        it('Supports query parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('some_route', '/user/:id(\\d+)')
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            var match = myUrlMatcher.match('/user/12?test=10&test2=water');

            assert.ok(match instanceof RouteMatch);

            assert.ok(typeof match.params['test'] !== 'undefined');
            assert.ok(match.params['test'] === '10');

            assert.ok(typeof match.params['test2'] !== 'undefined');
            assert.ok(match.params['test2'] === 'water');
        });
    });

    describe('supplying route playloads', function () {
        it('supplies the route\'s payload, when the route is matched', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('home', '/', {
                    _controller: 'home',
                    _action: 'index'
                })
            ]);

            var myUrlMatcher = new library.UrlMatcher(myRouteCollection);

            var match = myUrlMatcher.match('/');

            assert.ok(typeof match.routePayload['_controller'] !== 'undefined');
            assert.ok(match.routePayload._controller === 'home');

            assert.ok(typeof match.routePayload['_action'] !== 'undefined');
            assert.ok(match.routePayload._action === 'index');
        })
    })
});

describe('UrlGenerator', function () {
    describe('Instantiation', function () {
        it('Throws an error when instantiated without a route collection', function () {
            try {
                new library.UrlGenerator();

                assert.notOk('Should not get to this point');
            } catch (error) {
                assert.ok(error instanceof InvalidRouteCollectionError);
            }
        });

        it('Allows instantiation with a route collection', function () {
            var myUrlGenerator = new library.UrlGenerator(new library.RouteCollection());

            assert.ok(myUrlGenerator instanceof library.UrlGenerator);
        });
    });

    describe('Generating urls', function () {
        it('throws an error when you try to generate an url for an non-existant route', function () {
            var myRouteCollection = new library.RouteCollection([]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            try {
                myUrlGenerator.generate('non_existant_route');

                assert.notOk('Should not get to this point');
            } catch (error) {
                assert.ok(error instanceof RouteMissingError);
            }
        });

        it('Generates an url without parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('home', '/')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            assert.ok(myUrlGenerator.generate('home') === '/');
        });

        it('Generates an url with parameters', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('user_detail', '/user/:id')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            var generatedPath = myUrlGenerator.generate('user_detail', {
                id: 10
            });

            assert.ok(generatedPath === '/user/10');
        });

        it('Validates if the supplied parameters match the required pattern', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('user_detail', '/user/:id(\\d+)')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            try {
                myUrlGenerator.generate('user_detail', {
                    id: 'not_allowed_value'
                });
            } catch (error) {
                assert.ok(error instanceof InvalidParameterError);
            }
        });

        it('Adds extra parameters as query parameters to the url', function () {
            var myRouteCollection = new library.RouteCollection([
                new library.Route('home', '/')
            ]);

            var myUrlGenerator = new library.UrlGenerator(myRouteCollection);

            var generatedUrl = myUrlGenerator.generate('home', {
                test: 'other'
            });

            assert.ok(generatedUrl === '/?test=other');
        });
    });
});
<|endoftext|>