<commit_before>'use strict';

var app = require('angular').module('oyster', [
  require('./chrome.js')
]);

app.factory("FormRepo", FormRepo);

function FormRepo($q, Runtime) {
  function list() {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "LIST"
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function search(q) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "SEARCH",
        data: {
          query: q
        }
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function get(key, password) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "GET",
        data: {
          key: key,
          passphrase: password
        }
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function put(form) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "PUT",
        data: form
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function destroy(key) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "REMOVE",
        data: {
          key: key
        }
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  return {list: list, search: search, get: get, put: put, destroy: destroy};
}

app.controller("NewFormCtrl", NewFormCtrl);

function NewFormCtrl($scope, $window, Runtime, Tabs, FormRepo) {
  // Receive from background context menu handler
  Runtime.receive().then(function(form) {
    $scope.tabId = form.tabId;
    $scope.key = form.key;
    $scope.fields = form.fields;
  });

  $scope.addField = function() {
    $scope.fields.push({});
  };

  $scope.removeField = function(index) {
    $scope.fields.splice(index, 1);
  };

  $scope.save = function() {
    var form = {key: $scope.key, fields: $scope.fields};
    Tabs.sendMessage($scope.tabId, {
      type: "SET_FORM",
      data: form
    });
    FormRepo.put(form);
    $scope.close();
  };

  $scope.close = function() {
    $window.close();
  };
}

app.controller("FormSearchCtrl", FormSearchCtrl);

function FormSearchCtrl($scope, Tabs, FormRepo, $window) {
  $scope.password = "";
  Tabs.getCurrentActive().then(function(tab) {
    $scope.tabId = tab.id;
    FormRepo.search(tab.url).then(function(forms) {
      $scope.forms = forms;
      if($scope.forms.length < 1) {
        $scope.message = "No saved forms for this page";
      }
    }, function(err) {
      $scope.message = err;
    });
  });

  $scope.select = function(form) {
    $scope.selectedForm = form;
  };

  $scope.unselect = function() {
    $scope.selectedForm = null;
  };

  $scope.unlock = function() {
    FormRepo.get($scope.selectedForm.key, $scope.password).then(function(forms) {
      Tabs.sendMessage($scope.tabId, {
        type: "SET_FORM",
        data: forms
      });
      $scope.close();
    }, function(err) {
      $scope.message = err;
    });
  };

  $scope.close = function() {
    $window.close();
  };
}

app.controller("FormListCtrl", FormListCtrl);

function FormListCtrl($scope, FormRepo, $window, $log) {
  $scope.password = "";

  FormRepo.list().then(function(forms) {
    $scope.forms = forms;

    if($scope.forms.length < 1) {
      $scope.message = "No saved forms for this page";
    }
  }, function(err) {
    $scope.message = err;
  });

  $scope.new = function() {
    $scope.selectedForm = {
      fields: []
    };

    $scope.unlocked = true;
  };

  $scope.edit = function(form) {
    $scope.selectedForm = form;

    $scope.unlocked = false;
  };

  $scope.save = function() {
    var selectedForm = $scope.selectedForm;

    FormRepo.put($scope.selectedForm).then(function(data) {
      var index = 0;

      for (var form in $scope.forms) {
        if (form.key === selectedForm.key) {
          break;
        }

        index++;
      }

      if (index === $scope.forms.length) {
        $scope.forms.splice(index, 0, selectedForm);
      }
    }, function(err) {
      $scope.message = err;
    });

    $scope.cancel();
  };

  $scope.destroy = function(index) {
    if ($window.confirm("Are you sure?")) {
      var form = $scope.forms[index];

      FormRepo.destroy(form.key).then(function(data) {
        $scope.forms.splice(index, 1);
      }, function(err) {
        $scope.message = err;
      });
    }
  };

  $scope.cancel = function() {
    $scope.selectedForm = null;

    $scope.unlocked = true;
  };

  $scope.addField = function() {
    if ($scope.selectedForm) {
      $scope.selectedForm.fields.push({});
    }
  };

  $scope.removeField = function(index) {
    if ($scope.selectedForm) {
      $scope.selectedForm.fields.splice(index, 1);
    }
  };

  $scope.unlock = function() {
    FormRepo.get($scope.selectedForm.key, $scope.password).then(function(form) {
      if (form) {
        $scope.selectedForm = form;

        $scope.unlocked = true;
      } else {
        $scope.unlocked = false;
      }
    }, function(err) {
      $scope.message = err;
    });

    $scope.password = "";
  };
}

app.directive('focus', focus);

function focus($timeout) {
  function link(scope, element, attr) {
    scope.$watch(attr.focus, function(focusVal) {
      $timeout(function() {
        if(focusVal) {
          element[0].focus();
        } else {
          element[0].blur();
        }
      });
    });
  }

  return {
    restrict : 'A',
    link : link
  };
}
<commit_msg>Minor javascript fixups<commit_after>'use strict';

var app = require('angular').module('oyster', [
  require('./chrome.js')
]);

app.factory("FormRepo", FormRepo);

function FormRepo($q, Runtime) {
  function list() {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "LIST"
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function search(q) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "SEARCH",
        data: {
          query: q
        }
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function get(key, password) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "GET",
        data: {
          key: key,
          passphrase: password
        }
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function put(form) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "PUT",
        data: form
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  function destroy(key) {
    return $q(function(resolve, reject) {
      Runtime.sendNativeMessage('com.github.proglottis.oyster', {
        type: "REMOVE",
        data: {
          key: key
        }
      }).then(function(response) {
        if (response.type === "ERROR") {
          return reject(response.data);
        }
        resolve(response.data);
      }, reject);
    });
  }

  return {list: list, search: search, get: get, put: put, destroy: destroy};
}

app.controller("NewFormCtrl", NewFormCtrl);

function NewFormCtrl($scope, $window, Runtime, Tabs, FormRepo) {
  // Receive from background context menu handler
  Runtime.receive().then(function(form) {
    $scope.tabId = form.tabId;
    $scope.key = form.key;
    $scope.fields = form.fields;
  });

  $scope.addField = function() {
    $scope.fields.push({});
  };

  $scope.removeField = function(index) {
    $scope.fields.splice(index, 1);
  };

  $scope.save = function() {
    var form = {key: $scope.key, fields: $scope.fields};
    Tabs.sendMessage($scope.tabId, {
      type: "SET_FORM",
      data: form
    });
    FormRepo.put(form);
    $scope.close();
  };

  $scope.close = function() {
    $window.close();
  };
}

app.controller("FormSearchCtrl", FormSearchCtrl);

function FormSearchCtrl($scope, Tabs, FormRepo, $window) {
  $scope.password = "";
  Tabs.getCurrentActive().then(function(tab) {
    $scope.tabId = tab.id;
    FormRepo.search(tab.url).then(function(forms) {
      $scope.forms = forms;
      if($scope.forms.length < 1) {
        $scope.message = "No saved forms for this page";
      }
    }, function(err) {
      $scope.message = err;
    });
  });

  $scope.select = function(form) {
    $scope.selectedForm = form;
  };

  $scope.unselect = function() {
    $scope.selectedForm = null;
  };

  $scope.unlock = function() {
    FormRepo.get($scope.selectedForm.key, $scope.password).then(function(forms) {
      Tabs.sendMessage($scope.tabId, {
        type: "SET_FORM",
        data: forms
      });
      $scope.close();
    }, function(err) {
      $scope.message = err;
    });
  };

  $scope.close = function() {
    $window.close();
  };
}

app.controller("FormListCtrl", FormListCtrl);

function FormListCtrl($scope, FormRepo, $window, $log) {
  $scope.password = "";

  FormRepo.list().then(function(forms) {
    $scope.forms = forms;

    if($scope.forms.length < 1) {
      $scope.message = "No saved forms";
    }
  }, function(err) {
    $scope.message = err;
  });

  $scope.new = function() {
    $scope.selectedForm = {
      fields: []
    };

    $scope.unlocked = true;
  };

  $scope.edit = function(form) {
    $scope.selectedForm = form;

    $scope.unlocked = false;
  };

  $scope.save = function() {
    FormRepo.put($scope.selectedForm).then(function(data) {
      var index;
      for (index = 0; index < $scope.forms.length; index++) {
        if ($scope.forms[index].key === $scope.selectedForm.key) {
          break;
        }
      }

      if (index === $scope.forms.length) {
        $scope.forms.push($scope.selectedForm);
      }
      $scope.message = null;
    }, function(err) {
      $scope.message = err;
    }).finally(function() {
      $scope.cancel();
    });
  };

  $scope.destroy = function(index) {
    if ($window.confirm("Are you sure?")) {
      var form = $scope.forms[index];

      FormRepo.destroy(form.key).then(function(data) {
        $scope.forms.splice(index, 1);
      }, function(err) {
        $scope.message = err;
      });
    }
  };

  $scope.cancel = function() {
    $scope.selectedForm = null;

    $scope.unlocked = true;
  };

  $scope.addField = function() {
    if ($scope.selectedForm) {
      $scope.selectedForm.fields.push({});
    }
  };

  $scope.removeField = function(index) {
    if ($scope.selectedForm) {
      $scope.selectedForm.fields.splice(index, 1);
    }
  };

  $scope.unlock = function() {
    FormRepo.get($scope.selectedForm.key, $scope.password).then(function(form) {
      if (form) {
        $scope.selectedForm = form;

        $scope.unlocked = true;
      } else {
        $scope.unlocked = false;
      }
    }, function(err) {
      $scope.message = err;
    });

    $scope.password = "";
  };
}

app.directive('focus', focus);

function focus($timeout) {
  function link(scope, element, attr) {
    scope.$watch(attr.focus, function(focusVal) {
      $timeout(function() {
        if(focusVal) {
          element[0].focus();
        } else {
          element[0].blur();
        }
      });
    });
  }

  return {
    restrict : 'A',
    link : link
  };
}
<|endoftext|>


<commit_before>module.exports = function (grunt) {
  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-ember-template-compiler');
  grunt.loadNpmTasks('grunt-hashres');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-concurrent');
  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-bower-task');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-microlib');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-contrib-compass');

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    karma: {
        ci: { configFile: 'test/js/config/karma.conf.js', singleRun: true, browsers: ['PhantomJS'] },
      unit: { configFile: 'test/js/config/karma.conf.js', keepalive: true, browsers: ['Chrome'] },
      unitSpec: { configFile: 'test/js/config/karma.conf.js', keepalive: true, browsers: ['Chrome'], reporters: ['spec'] },
      chrome: { configFile: 'test/js/config/karma.conf.js', keepalive: true, browsers: ['Chrome'] }
      // e2e: { configFile: 'test/js/config/e2e.js', keepalive: true }, // End-to-end / Functional Tests
      // watch: { configFile: 'test/js/config/unit.js', singleRun:false, autoWatch: true, keepalive: true }
    },
    shell: {
      parse_templates: {
        options: {
          failOnError: true
        },
        command: 'rm -f ./static/build/js/templates/**/*.handlebars ; python ./parse_templates.py -d ./static/build/js/templates'
      }
    },
    concurrent: {
        dev: {
            tasks: ['watch:ember', 'karma:unit'],
            options: {
                logConcurrentOutput: true
            }
        }
    },
    watch: {
      ember: {
        files: ['Gruntfile.js', 'test/js/config/*.js', 'bluebottle/**/static/js/**/*.js', 'bluebottle/**/templates/**/*.hbs'],
        tasks: ['build'],
        options: {
          interrupt: true,
          debounceDelay: 250,
          atBegin: true
        }
      },
      scss: {
        files: ['bluebottle/common/static/**/*'],
        tasks: ['compass:dev'],
      }
    },
    hashres: {
      options: {
        renameFiles: true
      },
      prod: {
        src: ['static/build/js/lib/deps.min.js'],
        dest: 'ember/person/templates/index.html'
      }
    },
    bower: {
      install: {
        options: {
          targetDir: 'static/build/js/components',
          cleanTargetDir: true,
          cleanBowerDir: true,
          install: true,
          copy: true
        }
      },
      cleanup: {
        options: {
          targetDir: 'static/build/js/components',
          cleanTargetDir: true,
          cleanBowerDir: true,
          install: false,
          copy: false
        }
      }
    },
    concat: {
      dist: {
        src: [
          'bluebottle/common/static/js/vendor/jquery-1.8.3.js',
          'node_modules/jquery-mockjax/jquery.mockjax.js',

          // Vendor
          'bluebottle/common/static/js/vendor/handlebars-1.0.0.js',
          'bluebottle/common/static/js/vendor/ember-v1.0.0.js',
          'bluebottle/common/static/js/vendor/ember-data-v0.14.js',
          'bluebottle/common/static/js/vendor/ember-data-drf2-adapter.js',
          'bluebottle/common/static/js/vendor/ember-meta.js',
          'bluebottle/common/static/js/vendor/globalize.js',
          'bluebottle/common/static/jsi18n/en-us/*.js',

          // Plugins
          'bluebottle/common/static/js/plugins/ember-facebook.js',
          'bluebottle/common/static/js/plugins/ember.hashbang.js',
          'bluebottle/common/static/js/plugins/bb_modal.js',
          'bluebottle/common/static/js/plugins/apiary-adapter.js'
        ],
        dest: 'static/build/js/lib/deps.js'
      },
      test: {
        src: [
          'node_modules/qunitjs/qunit/qunit.js',
          'static/build/js/components/pavlov/pavlov.js',
          'static/build/js/components/ember-data-factory/dist/ember-data-factory-0.0.1.js',
          // Sion
          'node_modules/sinon/lib/sinon.js',
          'node_modules/sinon/lib/sinon/match.js',
          'node_modules/sinon/lib/sinon/spy.js',
          'node_modules/sinon/lib/sinon/call.js',
          'node_modules/sinon/lib/sinon/behavior.js',
          'node_modules/sinon/lib/sinon/stub.js',
          'node_modules/sinon/lib/sinon/mock.js',
          'node_modules/sinon/lib/sinon/assert.js',
          'node_modules/sinon/lib/sinon/util/event.js',
          'node_modules/sinon/lib/sinon/util/fake_xml_http_request.js',
          'node_modules/sinon/lib/sinon/util/fake_timers.js',
          'node_modules/sinon/lib/sinon/util/fake_server.js',
          'node_modules/sinon/lib/sinon/util/fake_server_with_clock.js',
          'node_modules/sinon/lib/sinon/collection.js',
          'node_modules/sinon/lib/sinon/sandbox.js',
          'node_modules/sinon/lib/sinon/test.js',
          'node_modules/sinon/lib/sinon/test_case.js',
          // 'node_modules/sinon-qunit/lib/sinon-qunit.js'
        ],
        dest: 'static/build/js/lib/test_deps.js'
      },
    },
    uglify: {
      options: {
        // the banner is inserted at the top of the output
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          '<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    emberhandlebars: {
      compile: {
        options: {
          templateName: function(sourceFile) {
            return sourceFile.match(/\/([0-9|a-z|\.|_]+)\.handlebars/i)[1];
          }
        },
        files: ['static/build/js/templates/*.handlebars'],
        dest: 'static/build/js/templates.js'
      }
    },
    compass: {
      // live
      dist: {
        options: {
          httpPath: '/static/assets/',
          basePath: 'bluebottle/common/static',
          sassDir: 'sass',
          cssDir: 'css',
          imagesDir: 'images',
          javascriptsDir: 'js',
          outputStyle: 'compressed',
          relativeAssets: true,
          noLineComments: true,
          environment: 'production',
          raw: 'preferred_syntax = :scss\n' // Use `raw` since it's not directly available
        }
      },
      // development
      dev: {
        options: {
          httpPath: '/static/assets/',
          basePath: 'bluebottle/common/static',
          sassDir: 'sass',
          cssDir: 'css',
          imagesDir: 'images',
          javascriptsDir: 'js',
          outputStyle: 'expanded',
          relativeAssets: true,
          noLineComments: false,
          raw: 'preferred_syntax = :scss\n' // Use `raw` since it's not directly available
        }
      }
    }
  });

  grunt.registerTask('default', ['concurrent:dev']);
  grunt.registerTask('build', ['bower:install', 'concat:dist', 'concat:test', 'shell:parse_templates']);
  grunt.registerTask('dev', ['build', 'karma:unit']);
  grunt.registerTask('travis', ['build', 'karma:ci']);
  grunt.registerTask('local', ['dev', 'watch']);
  grunt.registerTask('deploy', ['concat:dist', 'uglify:dist', 'hashres', 'compass:dist']);
};
<commit_msg>update gruntfile to handle sass/compass build<commit_after>module.exports = function (grunt) {
  require('time-grunt')(grunt);
  require('jit-grunt')(grunt);

  grunt.loadNpmTasks('grunt-contrib-concat');
  grunt.loadNpmTasks('grunt-ember-template-compiler');
  grunt.loadNpmTasks('grunt-hashres');
  grunt.loadNpmTasks('grunt-contrib-watch');
  grunt.loadNpmTasks('grunt-concurrent');
  grunt.loadNpmTasks('grunt-karma');
  grunt.loadNpmTasks('grunt-bower-task');
  grunt.loadNpmTasks('grunt-contrib-uglify');
  grunt.loadNpmTasks('grunt-microlib');
  grunt.loadNpmTasks('grunt-shell');
  grunt.loadNpmTasks('grunt-contrib-compass');

  var sassOutputStyle = grunt.option('output_style') || 'expanded',
    staticPath = './bluebottle/common/static/',
    compassPath = staticPath + 'sass',
    sassPath = staticPath + 'refactor-sass',
    cssOutputPath = staticPath + '/css';

  // Project configuration.
  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    karma: {
        ci: { configFile: 'test/js/config/karma.conf.js', singleRun: true, browsers: ['PhantomJS'] },
      unit: { configFile: 'test/js/config/karma.conf.js', keepalive: true, browsers: ['Chrome'] },
      unitSpec: { configFile: 'test/js/config/karma.conf.js', keepalive: true, browsers: ['Chrome'], reporters: ['spec'] },
      chrome: { configFile: 'test/js/config/karma.conf.js', keepalive: true, browsers: ['Chrome'] }
      // e2e: { configFile: 'test/js/config/e2e.js', keepalive: true }, // End-to-end / Functional Tests
      // watch: { configFile: 'test/js/config/unit.js', singleRun:false, autoWatch: true, keepalive: true }
    },
    shell: {
      parse_templates: {
        options: {
          failOnError: true
        },
        command: 'rm -f ./static/build/js/templates/**/*.handlebars ; python ./parse_templates.py -d ./static/build/js/templates'
      }
    },
    concurrent: {
        dev: {
            tasks: ['watch:ember', 'karma:unit'],
            options: {
                logConcurrentOutput: true
            }
        }
    },
    watch: {
      ember: {
        files: ['Gruntfile.js', 'test/js/config/*.js', 'bluebottle/**/static/js/**/*.js', 'bluebottle/**/templates/**/*.hbs'],
        tasks: ['build'],
        options: {
          interrupt: true,
          debounceDelay: 250,
          atBegin: true
        }
      },
      scss: {
        files: ['bluebottle/common/static/**/*'],
        tasks: ['compass:dev'],
      }
    },
    hashres: {
      options: {
        renameFiles: true
      },
      prod: {
        src: ['static/build/js/lib/deps.min.js'],
        dest: 'ember/person/templates/index.html'
      }
    },
    bower: {
      install: {
        options: {
          targetDir: 'static/build/js/components',
          cleanTargetDir: true,
          cleanBowerDir: true,
          install: true,
          copy: true
        }
      },
      cleanup: {
        options: {
          targetDir: 'static/build/js/components',
          cleanTargetDir: true,
          cleanBowerDir: true,
          install: false,
          copy: false
        }
      }
    },
    concat: {
      dist: {
        src: [
          'bluebottle/common/static/js/vendor/jquery-1.8.3.js',
          'node_modules/jquery-mockjax/jquery.mockjax.js',

          // Vendor
          'bluebottle/common/static/js/vendor/handlebars-1.0.0.js',
          'bluebottle/common/static/js/vendor/ember-v1.0.0.js',
          'bluebottle/common/static/js/vendor/ember-data-v0.14.js',
          'bluebottle/common/static/js/vendor/ember-data-drf2-adapter.js',
          'bluebottle/common/static/js/vendor/ember-meta.js',
          'bluebottle/common/static/js/vendor/globalize.js',
          'bluebottle/common/static/jsi18n/en-us/*.js',

          // Plugins
          'bluebottle/common/static/js/plugins/ember-facebook.js',
          'bluebottle/common/static/js/plugins/ember.hashbang.js',
          'bluebottle/common/static/js/plugins/bb_modal.js',
          'bluebottle/common/static/js/plugins/apiary-adapter.js'
        ],
        dest: 'static/build/js/lib/deps.js'
      },
      test: {
        src: [
          'node_modules/qunitjs/qunit/qunit.js',
          'static/build/js/components/pavlov/pavlov.js',
          'static/build/js/components/ember-data-factory/dist/ember-data-factory-0.0.1.js',
          // Sion
          'node_modules/sinon/lib/sinon.js',
          'node_modules/sinon/lib/sinon/match.js',
          'node_modules/sinon/lib/sinon/spy.js',
          'node_modules/sinon/lib/sinon/call.js',
          'node_modules/sinon/lib/sinon/behavior.js',
          'node_modules/sinon/lib/sinon/stub.js',
          'node_modules/sinon/lib/sinon/mock.js',
          'node_modules/sinon/lib/sinon/assert.js',
          'node_modules/sinon/lib/sinon/util/event.js',
          'node_modules/sinon/lib/sinon/util/fake_xml_http_request.js',
          'node_modules/sinon/lib/sinon/util/fake_timers.js',
          'node_modules/sinon/lib/sinon/util/fake_server.js',
          'node_modules/sinon/lib/sinon/util/fake_server_with_clock.js',
          'node_modules/sinon/lib/sinon/collection.js',
          'node_modules/sinon/lib/sinon/sandbox.js',
          'node_modules/sinon/lib/sinon/test.js',
          'node_modules/sinon/lib/sinon/test_case.js',
          // 'node_modules/sinon-qunit/lib/sinon-qunit.js'
        ],
        dest: 'static/build/js/lib/test_deps.js'
      },
    },
    uglify: {
      options: {
        // the banner is inserted at the top of the output
        banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n'
      },
      dist: {
        files: {
          '<%= pkg.name %>.min.js': ['<%= concat.dist.dest %>']
        }
      }
    },
    emberhandlebars: {
      compile: {
        options: {
          templateName: function(sourceFile) {
            return sourceFile.match(/\/([0-9|a-z|\.|_]+)\.handlebars/i)[1];
          }
        },
        files: ['static/build/js/templates/*.handlebars'],
        dest: 'static/build/js/templates.js'
      }
    },
    sass: {
      dist: {
        files: [{
          expand: true,
          cwd: sassPath,
          src: 'screen-refactor.scss',
          dest: cssOutputPath,
          ext: '.css'
        }]
      }
    },
    compass: {
      // live
      dist: {
        options: {
          httpPath: '/static/assets/',
          basePath: staticPath,
          sassDir: 'sass',
          cssDir: 'css',
          imagesDir: 'images',
          javascriptsDir: 'js',
          outputStyle: sassOutputStyle,
          relativeAssets: true,
          noLineComments: true,
          environment: 'production',
          raw: 'preferred_syntax = :scss\n', // Use `raw` since it's not directly available
          importPath: compassPath,
          force: true
        }
      },
      // development
      dev: {
        options: {
          httpPath: '/static/assets/',
          basePath: staticPath,
          sassDir: 'sass',
          cssDir: 'css',
          imagesDir: 'images',
          javascriptsDir: 'js',
          outputStyle: sassOutputStyle,
          relativeAssets: true,
          noLineComments: false,
          raw: 'preferred_syntax = :scss\n', // Use `raw` since it's not directly available
          importPath: compassPath,
          force: false,
          sourcemap: true
        }
      }
    }
  });

  grunt.registerTask('default', ['concurrent:dev']);
  grunt.registerTask('build', ['bower:install', 'concat:dist', 'concat:test', 'shell:parse_templates']);
  grunt.registerTask('dev', ['build', 'karma:unit']);
  grunt.registerTask('travis', ['build', 'karma:ci']);
  grunt.registerTask('local', ['dev', 'watch']);
  grunt.registerTask('deploy', ['concat:dist', 'uglify:dist', 'hashres', 'compass:dist']);
  grunt.registerTask('build:css', ['sass:dist', 'compass:dist']);
};<|endoftext|>


<commit_before>module.exports = function (grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON("package.json"),
		watch: {
			files: [
				"src/**/*.js",
				"tests/spec/**/*.js"
			],
			tasks: [
				"jshint",
				"karma:watch:run"
			]
		},
		jshint: {
			options: {
				strict: true,
				curly: true,
				eqeqeq: true,
				forin: true,
				immed: true,
				latedef: "nofunc",
				newcap: true,
				noarg: true,
				noempty: true,
				nonew: true,
				plusplus: true,
				quotmark: true,
				undef: true,
				validthis: true,
				maxparams: 3,
				maxdepth: 2,
				//maxstatements: 5,
				maxcomplexity: 5,
				globals: {
					require: false,
					define: false
				}
			},
			src: [
				"src/**/*.js"
			],
			tests: {
				files: {
					src: [
						"tests/runner.js",
						"tests/karma/runner.js",
						"tests/spec/**/*.js"
					]
				},
				options: {
					globals: {
						require: false,
						define: false,
						jasmine: false,
						describe: false,
						beforeEach: false,
						afterEach: false,
						it: false,
						expect: false,
						__karma__: false
					}
				}
			}
		},
		karma: {
			options: {
				files: [{
					pattern: "src/**/*.js",
					included: false
				}, {
					pattern: "tests/spec/**/*-test.js",
					included: false
				}, "tests/karma/runner.js"],
				frameworks: [
					"jasmine",
					"requirejs"
				]
			},
			watch: {
				browsers: [
					"PhantomJS"
				],
				hostname: process.env.IP,
				port: process.env.PORT,
				runnerPort: 0,
				background: true
			},
			phantom: {
				browsers: [
					"PhantomJS"
				],
				hostname: process.env.IP,
				port: process.env.PORT,
				runnerPort: 0,
				singleRun: true
			},
			coverage: {
				browsers: [
					"Chrome",
					"Firefox",
					"IE",
					"Safari",
					"PhantomJS"
                ],
				preprocessors: {
					"src/**/*.js": [
						"coverage"
					]
				},
				reporters: [
					"progress",
					"coverage"
				],
				coverageReporter: {
					type: "html",
					dir: "tests/coverage/"
				},
				singleRun: true
			}
		},
		dependo: {
			targetPath: "src",
			outputPath: "docs/deps",
			format: "amd"
		}
	});

	grunt.loadNpmTasks("grunt-contrib-watch");
	grunt.loadNpmTasks("grunt-contrib-jshint");
	grunt.loadNpmTasks("grunt-karma");
	grunt.loadNpmTasks("grunt-dependo");

	grunt.registerTask("default", [
		"jshint",
		"test"
	]);

	grunt.registerTask("test", [
		"karma:phantom"
	]);

	grunt.registerTask("coverage", [
		"karma:coverage"
	]);

	grunt.registerTask("startWatch", [
		"karma:watch:start",
		"watch"
	]);
};<commit_msg>alias jshint as lint and tweak karma config<commit_after>module.exports = function (grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON("package.json"),
		watch: {
			files: [
				"src/**/*.js",
				"tests/spec/**/*.js"
			],
			tasks: [
				//"lint",
				"karma:watch:run"
			]
		},
		jshint: {
			options: {
				strict: true,
				curly: true,
				eqeqeq: true,
				forin: true,
				immed: true,
				latedef: "nofunc",
				newcap: true,
				noarg: true,
				noempty: true,
				nonew: true,
				plusplus: true,
				quotmark: true,
				undef: true,
				validthis: true,
				maxparams: 3,
				maxdepth: 2,
				//maxstatements: 5,
				maxcomplexity: 5,
				globals: {
					define: true, // amdefine
					require: false,
					module: false
				}
			},
			src: [
				"src/**/*.js"
			],
			tests: {
				files: {
					src: [
						"tests/runner.js",
						"tests/karma/runner.js",
						"tests/spec/**/*.js"
					]
				},
				options: {
					globals: {
						require: false,
						define: false,
						jasmine: false,
						describe: false,
						beforeEach: false,
						afterEach: false,
						it: false,
						expect: false,
						__karma__: false
					}
				}
			}
		},
		karma: {
			options: {
				files: [{
					pattern: "src/**/*.js",
					included: false
				}, {
					pattern: "tests/spec/**/*-test.js",
					included: false
				}, "tests/karma/runner.js"],
				frameworks: [
					"jasmine",
					"requirejs"
				]
			},
			watch: {
				browsers: [
					"PhantomJS"
				],
				hostname: process.env.IP,
				port: process.env.PORT,
				runnerPort: 0,
				background: true
			},
			phantom: {
				browsers: [
					"PhantomJS"
				],
				hostname: process.env.IP,
				port: process.env.PORT,
				runnerPort: 0,
				singleRun: true
			},
			coverage: {
				browsers: [
					//"Chrome",
					//"Firefox",
					//"IE",
					//"Safari",
					"PhantomJS"
                ],
				preprocessors: {
					"src/**/*.js": [
						"coverage"
					]
				},
				reporters: [
					"progress",
					"coverage"
				],
				coverageReporter: {
					type: "html",
					dir: "tests/coverage/"
				},
				hostname: process.env.IP,
				port: process.env.PORT,
				runnerPort: 0,
				singleRun: true
			}
		},
		dependo: {
			targetPath: "src",
			outputPath: "docs/deps",
			format: "amd"
		}
	});

	grunt.loadNpmTasks("grunt-contrib-watch");
	grunt.loadNpmTasks("grunt-contrib-jshint");
	grunt.loadNpmTasks("grunt-karma");
	grunt.loadNpmTasks("grunt-dependo");

	grunt.registerTask("default", [
		"lint",
		"test"
	]);

	grunt.registerTask("lint", [
		"jshint"
	]);

	grunt.registerTask("test", [
		"karma:phantom"
	]);

	grunt.registerTask("coverage", [
		"karma:coverage"
	]);

	grunt.registerTask("startWatch", [
		"karma:watch:start",
		"watch"
	]);
};<|endoftext|>


<commit_before>const url = require('url');
const { API } = require('./Pagetest');
const credentials = require('./credentials');
const { isRateLimited } = require('./rateLimiter');
const { getAdSet } = require('./adBlocker');
const { toFile } = require('./download');
const { countHits } = require('./countHits');

const DEFAULT_ACTIVITY_TIMEOUT = 75;
const DEFAULT_TIMEOUT = 30;
const DEFAULT_TTL = 86000 / 2;

exports.call = function (db, data, req) {
    //Check if IP is rate-limited
    if (isRateLimited(req)) {
        throw new Abort({message: 'Too many requests', status: 429});
    }

    const { url, location, isClone, caching, isSpeedKitComparison, activityTimeout } = data;

    const baqendId = startTest(db, url, location, isClone, !caching, activityTimeout, isSpeedKitComparison);
    return { baqendId };
};

/**
 * @param db
 * @param {string} testUrl
 * @param {string} testLocation
 * @param {boolean} isClone
 * @param {boolean} isCachingDisabled
 * @param {number} activityTimeout
 * @param {boolean} isSpeedKitComparison
 * @return {string}
 */
function startTest(
    db,
    testUrl,
    testLocation,
    isClone,
    isCachingDisabled = true,
    activityTimeout = DEFAULT_ACTIVITY_TIMEOUT,
    isSpeedKitComparison = false
) {
    // Create a new test result
    const testResult = new db.TestResult();
    testResult.id = db.util.uuid();

    const testOptions = {
        connectivity: 'Native',
        location: testLocation,
        firstViewOnly: isCachingDisabled,
        runs: 1,
        video: true,
        disableOptimization: true,
        pageSpeed: false,
        requests: false,
        breakDown: false,
        domains: false,
        saveResponseBodies: false,
        tcpDump: false,
        timeline: true, //TODO: only for debugging
        priority: 0,
        duration: 1, //capture at least one second
        chromeTrace: false,
        netLog: false,
        disableHTTPHeaders: true,
        disableScreenshot: true,
        block: 'favicon', //exclude favicons for fair comparison, as not handled by SWs
        jpegQuality: 100,
        poll: 1, //poll every second
        timeout: 2 * DEFAULT_TIMEOUT //set timeout
    };

    const requirePrewarm = isClone;

    const testScript = createTestScript(testUrl, isClone, isCachingDisabled, activityTimeout, isSpeedKitComparison);

    Promise.resolve().then(() => {
        if (requirePrewarm) {
            const prewarmOptions = Object.assign({}, testOptions, {
                runs: 2,
                timeline: false,
                video: false,
                firstViewOnly: true,
                minimalResults: true
            });

            return API.runTest(testUrl, prewarmOptions, db).then((testId) => {
                return getPrewarmResult(db, testId);
            });
        }
    }).then((ttfb) => {
        return API.runTestWithoutWait(testScript, testOptions).then((testId) => {
            db.log.info(`Test started, testId: ${testId} script:\n${testScript}`);
            testResult.testId = testId;
            testResult.save();
            return API.waitOnTest(testId, db);
        }).then((testId) => {
            return getTestResult(db, testResult, testId, ttfb);
        }).then(() => {
            db.log.info(`Test completed, id: ${testResult.id}, testId: ${testResult.testId} script:\n${testScript}`);
        }).catch((e) => {
            db.log.warn(`Test failed, id: ${testResult.id}, testId: ${testResult.testId} script:\n${testScript}\n\n${e.stack}`);
            testResult.ready().then(() => {
                testResult.testDataMissing = true;
                testResult.save();
            });
        });
    });

    return testResult.key;
}

/**
 * @param {string} testUrl
 * @param {boolean} isClone
 * @param {boolean} isCachingDisabled
 * @param {number} activityTimeout
 * @param {boolean} isSpeedKitComparison
 * @return {string}
 */
function createTestScript(testUrl, isClone, isCachingDisabled = true, activityTimeout = DEFAULT_ACTIVITY_TIMEOUT, isSpeedKitComparison = false) {
    let hostname;
    try {
        hostname = url.parse(testUrl).hostname;
    } catch (e) {
        throw new Abort('Invalid Url specified: ' + e.message);
    }

    if (!isClone) {
        return `
      block /sw.js /sw.php
      setActivityTimeout ${activityTimeout}
      setTimeout ${DEFAULT_TIMEOUT}
      #expireCache ${DEFAULT_TTL}
      navigate ${testUrl}
    `;
    }

    let installNavigation = testUrl + '&noCaching=true&blockExternal=true';
    if (!isCachingDisabled) {
        installNavigation = testUrl.split('#')[0];
    }

    //SW always needs to be installed
    const installSW = `
    logData 0
    setTimeout ${DEFAULT_TIMEOUT}
    ${isSpeedKitComparison ? 'blockDomainsExcept ' + hostname : ''}
    navigate ${installNavigation}
    ${isSpeedKitComparison ? 'blockDomainsExcept' : ''}
    navigate about:blank
    ${isCachingDisabled ? 'clearcache' : ''}
    logData 1
  `;

    return `
    setActivityTimeout ${activityTimeout}
    ${installSW}
    setTimeout ${DEFAULT_TIMEOUT}
    navigate ${testUrl}
  `;
}

/**
 * @param db
 * @param {string} testId
 */
function getPrewarmResult(db, testId) {
    return API.getTestResults(testId, {
        requests: false,
        breakdown: false,
        domains: false,
        pageSpeed: false,
    }).then((result) => {
        const ttfb = result.data.runs['1'].firstView.TTFB;
        db.log.info('TTFB of prewarm: ' + ttfb + ' with testId ' + testId, result.data.runs['1'].firstView);
        return ttfb;
    });
}

/**
 * @param db
 * @param testResult
 * @param {string} testId
 * @param {string} ttfb
 */
function getTestResult(db, testResult, testId, ttfb) {
    db.log.info(`Pingback received for ${testId}`);

    if (testResult.firstView) {
        db.log.info(`Result already exists for ${testId}`);
        return;
    }

    testResult.testId = testId;

    const options = {
        requests: true,
        breakdown: false,
        domains: false,
        pageSpeed: false,
    };

    return API.getTestResults(testId, options).then((result) => {
        db.log.info('Saving test result for ' + testId, result.data);
        return createTestResult(db, testResult, result.data, ttfb);
    }).then((ignored) => {
        if (testResult.testDataMissing) {
            throw new Error('Test Data Missing');
        }

        db.log.info('creating video for ' + testId);
        return Promise.all([API.createVideo(testId + '-r:1-c:0'), API.createVideo(testId + '-r:1-c:1')]);
    }).then((result) => {
        db.log.info('videos created for ' + testId);

        testResult.videoIdFirstView = result[0].data.videoId;
        const videoFirstViewPromise = toFile(db,
            constructVideoLink(testId, testResult.videoIdFirstView), '/www/videoFirstView/' + testId + '.mp4');

        let videoRepeatViewPromise = Promise.resolve(true);
        if (result[1].data && result[1].data.videoId) {
            testResult.videoIdRepeatedView = result[1].data.videoId;
            videoRepeatViewPromise = toFile(db,
                constructVideoLink(testId, testResult.videoIdRepeatedView), '/www/videoRepeatView/' + testId + '.mp4');
        }

        return Promise.all([videoFirstViewPromise, videoRepeatViewPromise]).then((values) => {
            const [videoFirstView, videoRepeatView] = values;
            testResult.videoFileFirstView = videoFirstView;
            testResult.videoFileRepeatView = videoRepeatView;
            return testResult.save();
        });
    });
}

/**
 * @param {string} testId
 * @param {string} videoId
 * @return {string}
 */
function constructVideoLink(testId, videoId) {
    const date = testId.substr(0, 2) + '/' + testId.substr(2, 2) + '/' + testId.substr(4, 2);
    const videoLink = videoId.substr(videoId.indexOf('_') + 1, videoId.length);
    return `http://${credentials.wpt_dns}/results/video/${date}/${videoLink}/video.mp4`;
}

/**
 * @param db
 * @param testObject
 * @param testResult
 * @param {string} ttfb
 */
function createTestResult(db, testObject, testResult, ttfb) {
    testObject.location = testResult.location;
    testObject.url = testResult.testUrl;
    testObject.summaryUrl = testResult.summary;

    return createRun(db, testResult.runs['1'].firstView, ttfb).then((firstView) => {
        testObject.firstView = firstView;
        testObject.testDataMissing = testObject.firstView.lastVisualChange <= 0;

        if (!testResult.runs['1'].repeatView) {
            return testObject.save();
        }

        return createRun(db, testResult.runs['1'].repeatView, ttfb).then(repeatView => {
            testObject.repeatView = repeatView;
            testObject.testDataMissing = testObject.repeatView.lastVisualChange <= 0;
            return testObject.save();
        });
    });
}

/**
 * @param db
 * @param data
 * @param {string} ttfb
 */
function createRun(db, data, ttfb) {
    const run = new db.Run();
    run.loadTime = data.loadTime;
    run.ttfb = ttfb ? ttfb : data.TTFB;
    run.domLoaded = data.domContentLoadedEventStart;
    run.load = data.loadEventStart;
    run.fullyLoaded = data.fullyLoaded;
    run.firstPaint = data.firstPaint;
    run.startRender = data.render;
    run.lastVisualChange = data.lastVisualChange;
    run.speedIndex = data.SpeedIndex;
    run.requests = data.requests.length;
    run.bytes = data.bytesIn;
    run.hits = new db.Hits(countHits(data));
    run.domElements = data.domElements;
    run.basePageCDN = data.base_page_cdn;
    const completeness = new db.Completeness();
    completeness.p85 = data.visualComplete85;
    completeness.p90 = data.visualComplete90;
    completeness.p95 = data.visualComplete95;
    completeness.p99 = data.visualComplete99;
    completeness.p100 = data.visualComplete;
    run.visualCompleteness = completeness;

    run.domains = [];

    return createDomainList(data, run);
}

function createDomainList(data, run) {
    return getAdSet().then((adSet) => {
        for (const key of Object.keys(data.domains)) {
            const domainObject = data.domains[key];

            if (!isAdDomain(key, adSet)) {
                domainObject.url = key;
                run.domains.push(domainObject);
            }
        }

        return run;
    });
}

/**
 * @param {string} url
 * @param {Set<string>} adSet
 * @return {boolean}
 */
function isAdDomain(url, adSet) {
    const index = url.indexOf('.');
    if (index === -1) {
        return false;
    }

    if (adSet.has(url)) {
        return true;
    }

    return isAdDomain(url.substr(index + 1), adSet);
}

exports.startTest = startTest;
<commit_msg>change computation of TTFB when isSpeedKitComparison<commit_after>const url = require('url');
const { API } = require('./Pagetest');
const credentials = require('./credentials');
const { isRateLimited } = require('./rateLimiter');
const { getAdSet } = require('./adBlocker');
const { toFile } = require('./download');
const { countHits } = require('./countHits');

const DEFAULT_ACTIVITY_TIMEOUT = 75;
const DEFAULT_TIMEOUT = 30;
const DEFAULT_TTL = 86000 / 2;

exports.call = function (db, data, req) {
    //Check if IP is rate-limited
    if (isRateLimited(req)) {
        throw new Abort({message: 'Too many requests', status: 429});
    }

    const { url, location, isClone, caching, isSpeedKitComparison, activityTimeout } = data;

    const baqendId = startTest(db, url, location, isClone, !caching, activityTimeout, isSpeedKitComparison);
    return { baqendId };
};

/**
 * @param db
 * @param {string} testUrl
 * @param {string} testLocation
 * @param {boolean} isClone
 * @param {boolean} isCachingDisabled
 * @param {number} activityTimeout
 * @param {boolean} isSpeedKitComparison
 * @return {string}
 */
function startTest(
    db,
    testUrl,
    testLocation,
    isClone,
    isCachingDisabled = true,
    activityTimeout = DEFAULT_ACTIVITY_TIMEOUT,
    isSpeedKitComparison = false
) {
    // Create a new test result
    const testResult = new db.TestResult();
    testResult.id = db.util.uuid();

    const testOptions = {
        connectivity: 'Native',
        location: testLocation,
        firstViewOnly: isCachingDisabled,
        runs: 1,
        video: true,
        disableOptimization: true,
        pageSpeed: false,
        requests: false,
        breakDown: false,
        domains: false,
        saveResponseBodies: false,
        tcpDump: false,
        timeline: true, //TODO: only for debugging
        priority: 0,
        duration: 1, //capture at least one second
        chromeTrace: false,
        netLog: false,
        disableHTTPHeaders: true,
        disableScreenshot: true,
        block: 'favicon', //exclude favicons for fair comparison, as not handled by SWs
        jpegQuality: 100,
        poll: 1, //poll every second
        timeout: 2 * DEFAULT_TIMEOUT //set timeout
    };

    const requirePrewarm = isClone;

    const testScript = createTestScript(testUrl, isClone, isCachingDisabled, activityTimeout, isSpeedKitComparison);

    Promise.resolve().then(() => {
        if (requirePrewarm) {
            const prewarmOptions = Object.assign({}, testOptions, {
                runs: 2,
                timeline: false,
                video: false,
                firstViewOnly: true,
                minimalResults: true
            });

            return API.runTest(testUrl, prewarmOptions, db).then((testId) => {
                return getPrewarmResult(db, testId, isSpeedKitComparison);
            });
        }
    }).then((ttfb) => {
        return API.runTestWithoutWait(testScript, testOptions).then((testId) => {
            db.log.info(`Test started, testId: ${testId} script:\n${testScript}`);
            testResult.testId = testId;
            testResult.save();
            return API.waitOnTest(testId, db);
        }).then((testId) => {
            return getTestResult(db, testResult, testId, ttfb);
        }).then(() => {
            db.log.info(`Test completed, id: ${testResult.id}, testId: ${testResult.testId} script:\n${testScript}`);
        }).catch((e) => {
            db.log.warn(`Test failed, id: ${testResult.id}, testId: ${testResult.testId} script:\n${testScript}\n\n${e.stack}`);
            testResult.ready().then(() => {
                testResult.testDataMissing = true;
                testResult.save();
            });
        });
    });

    return testResult.key;
}

/**
 * @param {string} testUrl
 * @param {boolean} isClone
 * @param {boolean} isCachingDisabled
 * @param {number} activityTimeout
 * @param {boolean} isSpeedKitComparison
 * @return {string}
 */
function createTestScript(testUrl, isClone, isCachingDisabled = true, activityTimeout = DEFAULT_ACTIVITY_TIMEOUT, isSpeedKitComparison = false) {
    let hostname;
    try {
        hostname = url.parse(testUrl).hostname;
    } catch (e) {
        throw new Abort('Invalid Url specified: ' + e.message);
    }

    if (!isClone) {
        return `
      block /sw.js /sw.php
      setActivityTimeout ${activityTimeout}
      setTimeout ${DEFAULT_TIMEOUT}
      #expireCache ${DEFAULT_TTL}
      navigate ${testUrl}
    `;
    }

    let installNavigation = testUrl + '&noCaching=true&blockExternal=true';
    if (!isCachingDisabled) {
        installNavigation = testUrl.split('#')[0];
    }

    //SW always needs to be installed
    const installSW = `
    logData 0
    setTimeout ${DEFAULT_TIMEOUT}
    ${isSpeedKitComparison ? 'blockDomainsExcept ' + hostname : ''}
    navigate ${installNavigation}
    ${isSpeedKitComparison ? 'blockDomainsExcept' : ''}
    navigate about:blank
    ${isCachingDisabled ? 'clearcache' : ''}
    logData 1
  `;

    return `
    setActivityTimeout ${activityTimeout}
    ${installSW}
    setTimeout ${DEFAULT_TIMEOUT}
    navigate ${testUrl}
  `;
}

/**
 * @param db
 * @param {string} testId
 */
function getPrewarmResult(db, testId, isSpeedKitComparison) {
    return API.getTestResults(testId, {
        requests: false,
        breakdown: false,
        domains: false,
        pageSpeed: false,
    }).then((result) => {
        const ttfb = isSpeedKitComparison ? result.data.runs['2'].firstView.TTFB : result.data.runs['1'].firstView.TTFB;
        db.log.info('TTFB of prewarm: ' + ttfb + ' with testId ' + testId, result.data.runs['1'].firstView);
        return ttfb;
    });
}

/**
 * @param db
 * @param testResult
 * @param {string} testId
 * @param {string} ttfb
 */
function getTestResult(db, testResult, testId, ttfb) {
    db.log.info(`Pingback received for ${testId}`);

    if (testResult.firstView) {
        db.log.info(`Result already exists for ${testId}`);
        return;
    }

    testResult.testId = testId;

    const options = {
        requests: true,
        breakdown: false,
        domains: false,
        pageSpeed: false,
    };

    return API.getTestResults(testId, options).then((result) => {
        db.log.info('Saving test result for ' + testId, result.data);
        return createTestResult(db, testResult, result.data, ttfb);
    }).then((ignored) => {
        if (testResult.testDataMissing) {
            throw new Error('Test Data Missing');
        }

        db.log.info('creating video for ' + testId);
        return Promise.all([API.createVideo(testId + '-r:1-c:0'), API.createVideo(testId + '-r:1-c:1')]);
    }).then((result) => {
        db.log.info('videos created for ' + testId);

        testResult.videoIdFirstView = result[0].data.videoId;
        const videoFirstViewPromise = toFile(db,
            constructVideoLink(testId, testResult.videoIdFirstView), '/www/videoFirstView/' + testId + '.mp4');

        let videoRepeatViewPromise = Promise.resolve(true);
        if (result[1].data && result[1].data.videoId) {
            testResult.videoIdRepeatedView = result[1].data.videoId;
            videoRepeatViewPromise = toFile(db,
                constructVideoLink(testId, testResult.videoIdRepeatedView), '/www/videoRepeatView/' + testId + '.mp4');
        }

        return Promise.all([videoFirstViewPromise, videoRepeatViewPromise]).then((values) => {
            const [videoFirstView, videoRepeatView] = values;
            testResult.videoFileFirstView = videoFirstView;
            testResult.videoFileRepeatView = videoRepeatView;
            return testResult.save();
        });
    });
}

/**
 * @param {string} testId
 * @param {string} videoId
 * @return {string}
 */
function constructVideoLink(testId, videoId) {
    const date = testId.substr(0, 2) + '/' + testId.substr(2, 2) + '/' + testId.substr(4, 2);
    const videoLink = videoId.substr(videoId.indexOf('_') + 1, videoId.length);
    return `http://${credentials.wpt_dns}/results/video/${date}/${videoLink}/video.mp4`;
}

/**
 * @param db
 * @param testObject
 * @param testResult
 * @param {string} ttfb
 */
function createTestResult(db, testObject, testResult, ttfb) {
    testObject.location = testResult.location;
    testObject.url = testResult.testUrl;
    testObject.summaryUrl = testResult.summary;

    return createRun(db, testResult.runs['1'].firstView, ttfb).then((firstView) => {
        testObject.firstView = firstView;
        testObject.testDataMissing = testObject.firstView.lastVisualChange <= 0;

        if (!testResult.runs['1'].repeatView) {
            return testObject.save();
        }

        return createRun(db, testResult.runs['1'].repeatView, ttfb).then(repeatView => {
            testObject.repeatView = repeatView;
            testObject.testDataMissing = testObject.repeatView.lastVisualChange <= 0;
            return testObject.save();
        });
    });
}

/**
 * @param db
 * @param data
 * @param {string} ttfb
 */
function createRun(db, data, ttfb) {
    const run = new db.Run();
    run.loadTime = data.loadTime;
    run.ttfb = ttfb ? ttfb : data.TTFB;
    run.domLoaded = data.domContentLoadedEventStart;
    run.load = data.loadEventStart;
    run.fullyLoaded = data.fullyLoaded;
    run.firstPaint = data.firstPaint;
    run.startRender = data.render;
    run.lastVisualChange = data.lastVisualChange;
    run.speedIndex = data.SpeedIndex;
    run.requests = data.requests.length;
    run.bytes = data.bytesIn;
    run.hits = new db.Hits(countHits(data));
    run.domElements = data.domElements;
    run.basePageCDN = data.base_page_cdn;
    const completeness = new db.Completeness();
    completeness.p85 = data.visualComplete85;
    completeness.p90 = data.visualComplete90;
    completeness.p95 = data.visualComplete95;
    completeness.p99 = data.visualComplete99;
    completeness.p100 = data.visualComplete;
    run.visualCompleteness = completeness;

    run.domains = [];

    return createDomainList(data, run);
}

function createDomainList(data, run) {
    return getAdSet().then((adSet) => {
        for (const key of Object.keys(data.domains)) {
            const domainObject = data.domains[key];

            if (!isAdDomain(key, adSet)) {
                domainObject.url = key;
                run.domains.push(domainObject);
            }
        }

        return run;
    });
}

/**
 * @param {string} url
 * @param {Set<string>} adSet
 * @return {boolean}
 */
function isAdDomain(url, adSet) {
    const index = url.indexOf('.');
    if (index === -1) {
        return false;
    }

    if (adSet.has(url)) {
        return true;
    }

    return isAdDomain(url.substr(index + 1), adSet);
}

exports.startTest = startTest;
<|endoftext|>


<commit_before>var testRoute = Ember.Route.extend(Ember.SimpleAuth.ApplicationRouteMixin, {
  session: Ember.SimpleAuth.Session.create(),
  route:   null,

  transitionTo: function(targetRoute) {
    this.route = targetRoute;
  }
}).create();

var ajaxRequestUrl;
var ajaxRequestOptions;
var ajaxMock = function(url, options) {
  ajaxRequestUrl     = url;
  ajaxRequestOptions = options;
  return {
    always: function(callback) {
      callback();
    }
  };
};

module('Ember.SimpleAuth.ApplicationRouteMixin', {
  originalAjax: Ember.$.ajax,
  setup: function() {
    Ember.SimpleAuth.serverSessionRoute = '/session/route';
    Ember.$.ajax                        = ajaxMock;
    ajaxRequestUrl                      = undefined;
    ajaxRequestOptions                  = undefined;
  },
  teardown: function() {
    Ember.$.ajax = this.originalAjax;
  }
});

test('redirects to the login route on login', function() {
  testRoute._actions['login'].apply(testRoute);

  equal(testRoute.route, 'login', 'Ember.SimpleAuth.ApplicationRouteMixin redirects to the login route on login.');
});

test('sends a DELETE request to the correct route on logout', function() {
  testRoute._actions['logout'].apply(testRoute);

  equal(ajaxRequestUrl, '/session/route', 'Ember.SimpleAuth.ApplicationRouteMixin sends a request to the correct route on logout.');
  equal(ajaxRequestOptions.type, 'DELETE', 'Ember.SimpleAuth.ApplicationRouteMixin a DELETE request on logout.');
});

test('destroys the current session on logout', function() {
  testRoute.set('session.authToken', 'some token');
  testRoute._actions['logout'].apply(testRoute);

  equal(testRoute.get('session.isAuthenticated'), false, 'Ember.SimpleAuth.ApplicationRouteMixin destroy the current session on logout.');
});

test('redirects to the correct route on logout', function() {
  Ember.SimpleAuth.routeAfterLogout = 'some.route';
  testRoute._actions['logout'].apply(testRoute);

  equal(testRoute.route, 'some.route', 'Ember.SimpleAuth.ApplicationRouteMixin redirects to the correct route on logout.');
});
<commit_msg>better var name<commit_after>var testRoute = Ember.Route.extend(Ember.SimpleAuth.ApplicationRouteMixin, {
  session:        Ember.SimpleAuth.Session.create(),
  transitionedTo: null,

  transitionTo: function(targetRoute) {
    this.transitionedTo = targetRoute;
  }
}).create();

var ajaxRequestUrl;
var ajaxRequestOptions;
var ajaxMock = function(url, options) {
  ajaxRequestUrl     = url;
  ajaxRequestOptions = options;
  return {
    always: function(callback) {
      callback();
    }
  };
};

module('Ember.SimpleAuth.ApplicationRouteMixin', {
  originalAjax: Ember.$.ajax,
  setup: function() {
    Ember.SimpleAuth.serverSessionRoute = '/session/route';
    Ember.$.ajax                        = ajaxMock;
    ajaxRequestUrl                      = undefined;
    ajaxRequestOptions                  = undefined;
  },
  teardown: function() {
    Ember.$.ajax = this.originalAjax;
  }
});

test('redirects to the login route on login', function() {
  testRoute._actions['login'].apply(testRoute);

  equal(testRoute.transitionedTo, 'login', 'Ember.SimpleAuth.ApplicationRouteMixin redirects to the login route on login.');
});

test('sends a DELETE request to the correct route on logout', function() {
  testRoute._actions['logout'].apply(testRoute);

  equal(ajaxRequestUrl, '/session/route', 'Ember.SimpleAuth.ApplicationRouteMixin sends a request to the correct route on logout.');
  equal(ajaxRequestOptions.type, 'DELETE', 'Ember.SimpleAuth.ApplicationRouteMixin a DELETE request on logout.');
});

test('destroys the current session on logout', function() {
  testRoute.set('session.authToken', 'some token');
  testRoute._actions['logout'].apply(testRoute);

  equal(testRoute.get('session.isAuthenticated'), false, 'Ember.SimpleAuth.ApplicationRouteMixin destroy the current session on logout.');
});

test('redirects to the correct route on logout', function() {
  Ember.SimpleAuth.routeAfterLogout = 'some.route';
  testRoute._actions['logout'].apply(testRoute);

  equal(testRoute.transitionedTo, 'some.route', 'Ember.SimpleAuth.ApplicationRouteMixin redirects to the correct route on logout.');
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict
 */

import objectValues from '../polyfills/objectValues';
import inspect from '../jsutils/inspect';
import { astFromValue } from '../utilities/astFromValue';
import { print } from '../language/printer';
import {
  type GraphQLField,
  GraphQLObjectType,
  GraphQLEnumType,
  GraphQLList,
  GraphQLNonNull,
  isScalarType,
  isObjectType,
  isInterfaceType,
  isUnionType,
  isEnumType,
  isInputObjectType,
  isListType,
  isNonNullType,
  isAbstractType,
  isNamedType,
} from './definition';
import { GraphQLString, GraphQLBoolean } from './scalars';
import { DirectiveLocation } from '../language/directiveLocation';

export const __Schema = new GraphQLObjectType({
  name: '__Schema',
  description:
    'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.',
  fields: () => ({
    types: {
      description: 'A list of all types supported by this server.',
      type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))),
      resolve(schema) {
        return objectValues(schema.getTypeMap());
      },
    },
    queryType: {
      description: 'The type that query operations will be rooted at.',
      type: GraphQLNonNull(__Type),
      resolve: schema => schema.getQueryType(),
    },
    mutationType: {
      description:
        'If this server supports mutation, the type that mutation operations will be rooted at.',
      type: __Type,
      resolve: schema => schema.getMutationType(),
    },
    subscriptionType: {
      description:
        'If this server support subscription, the type that subscription operations will be rooted at.',
      type: __Type,
      resolve: schema => schema.getSubscriptionType(),
    },
    directives: {
      description: 'A list of all directives supported by this server.',
      type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))),
      resolve: schema => schema.getDirectives(),
    },
  }),
});

export const __Directive = new GraphQLObjectType({
  name: '__Directive',
  description:
    "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.",
  fields: () => ({
    name: {
      type: GraphQLNonNull(GraphQLString),
      resolve: obj => obj.name,
    },
    description: {
      type: GraphQLString,
      resolve: obj => obj.description,
    },
    locations: {
      type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))),
      resolve: obj => obj.locations,
    },
    args: {
      type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),
      resolve: directive => directive.args || [],
    },
  }),
});

export const __DirectiveLocation = new GraphQLEnumType({
  name: '__DirectiveLocation',
  description:
    'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.',
  values: {
    QUERY: {
      value: DirectiveLocation.QUERY,
      description: 'Location adjacent to a query operation.',
    },
    MUTATION: {
      value: DirectiveLocation.MUTATION,
      description: 'Location adjacent to a mutation operation.',
    },
    SUBSCRIPTION: {
      value: DirectiveLocation.SUBSCRIPTION,
      description: 'Location adjacent to a subscription operation.',
    },
    FIELD: {
      value: DirectiveLocation.FIELD,
      description: 'Location adjacent to a field.',
    },
    FRAGMENT_DEFINITION: {
      value: DirectiveLocation.FRAGMENT_DEFINITION,
      description: 'Location adjacent to a fragment definition.',
    },
    FRAGMENT_SPREAD: {
      value: DirectiveLocation.FRAGMENT_SPREAD,
      description: 'Location adjacent to a fragment spread.',
    },
    INLINE_FRAGMENT: {
      value: DirectiveLocation.INLINE_FRAGMENT,
      description: 'Location adjacent to an inline fragment.',
    },
    VARIABLE_DEFINITION: {
      value: DirectiveLocation.VARIABLE_DEFINITION,
      description: 'Location adjacent to a variable definition.',
    },
    SCHEMA: {
      value: DirectiveLocation.SCHEMA,
      description: 'Location adjacent to a schema definition.',
    },
    SCALAR: {
      value: DirectiveLocation.SCALAR,
      description: 'Location adjacent to a scalar definition.',
    },
    OBJECT: {
      value: DirectiveLocation.OBJECT,
      description: 'Location adjacent to an object type definition.',
    },
    FIELD_DEFINITION: {
      value: DirectiveLocation.FIELD_DEFINITION,
      description: 'Location adjacent to a field definition.',
    },
    ARGUMENT_DEFINITION: {
      value: DirectiveLocation.ARGUMENT_DEFINITION,
      description: 'Location adjacent to an argument definition.',
    },
    INTERFACE: {
      value: DirectiveLocation.INTERFACE,
      description: 'Location adjacent to an interface definition.',
    },
    UNION: {
      value: DirectiveLocation.UNION,
      description: 'Location adjacent to a union definition.',
    },
    ENUM: {
      value: DirectiveLocation.ENUM,
      description: 'Location adjacent to an enum definition.',
    },
    ENUM_VALUE: {
      value: DirectiveLocation.ENUM_VALUE,
      description: 'Location adjacent to an enum value definition.',
    },
    INPUT_OBJECT: {
      value: DirectiveLocation.INPUT_OBJECT,
      description: 'Location adjacent to an input object type definition.',
    },
    INPUT_FIELD_DEFINITION: {
      value: DirectiveLocation.INPUT_FIELD_DEFINITION,
      description: 'Location adjacent to an input object field definition.',
    },
  },
});

export const __Type = new GraphQLObjectType({
  name: '__Type',
  description:
    'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.',
  fields: () => ({
    kind: {
      type: GraphQLNonNull(__TypeKind),
      resolve(type) {
        if (isScalarType(type)) {
          return TypeKind.SCALAR;
        } else if (isObjectType(type)) {
          return TypeKind.OBJECT;
        } else if (isInterfaceType(type)) {
          return TypeKind.INTERFACE;
        } else if (isUnionType(type)) {
          return TypeKind.UNION;
        } else if (isEnumType(type)) {
          return TypeKind.ENUM;
        } else if (isInputObjectType(type)) {
          return TypeKind.INPUT_OBJECT;
        } else if (isListType(type)) {
          return TypeKind.LIST;
        } else if (isNonNullType(type)) {
          return TypeKind.NON_NULL;
        }

        // Not reachable. All possible types have been considered.
        /* istanbul ignore next */
        throw new Error(`Unexpected type: "${inspect((type: empty))}".`);
      },
    },
    name: {
      type: GraphQLString,
      resolve: obj => obj.name,
    },
    description: {
      type: GraphQLString,
      resolve: obj => obj.description,
    },
    fields: {
      type: GraphQLList(GraphQLNonNull(__Field)),
      args: {
        includeDeprecated: { type: GraphQLBoolean, defaultValue: false },
      },
      resolve(type, { includeDeprecated }) {
        if (isObjectType(type) || isInterfaceType(type)) {
          let fields = objectValues(type.getFields());
          if (!includeDeprecated) {
            fields = fields.filter(field => !field.deprecationReason);
          }
          return fields;
        }
        return null;
      },
    },
    interfaces: {
      type: GraphQLList(GraphQLNonNull(__Type)),
      resolve(type) {
        if (isObjectType(type)) {
          return type.getInterfaces();
        }
      },
    },
    possibleTypes: {
      type: GraphQLList(GraphQLNonNull(__Type)),
      resolve(type, args, context, { schema }) {
        if (isAbstractType(type)) {
          return schema.getPossibleTypes(type);
        }
      },
    },
    enumValues: {
      type: GraphQLList(GraphQLNonNull(__EnumValue)),
      args: {
        includeDeprecated: { type: GraphQLBoolean, defaultValue: false },
      },
      resolve(type, { includeDeprecated }) {
        if (isEnumType(type)) {
          let values = type.getValues();
          if (!includeDeprecated) {
            values = values.filter(value => !value.deprecationReason);
          }
          return values;
        }
      },
    },
    inputFields: {
      type: GraphQLList(GraphQLNonNull(__InputValue)),
      resolve(type) {
        if (isInputObjectType(type)) {
          return objectValues(type.getFields());
        }
      },
    },
    ofType: {
      type: __Type,
      resolve: obj => obj.ofType,
    },
  }),
});

export const __Field = new GraphQLObjectType({
  name: '__Field',
  description:
    'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.',
  fields: () => ({
    name: {
      type: GraphQLNonNull(GraphQLString),
      resolve: obj => obj.name,
    },
    description: {
      type: GraphQLString,
      resolve: obj => obj.description,
    },
    args: {
      type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),
      resolve: field => field.args || [],
    },
    type: {
      type: GraphQLNonNull(__Type),
      resolve: obj => obj.type,
    },
    isDeprecated: {
      type: GraphQLNonNull(GraphQLBoolean),
      resolve: obj => obj.isDeprecated,
    },
    deprecationReason: {
      type: GraphQLString,
      resolve: obj => obj.deprecationReason,
    },
  }),
});

export const __InputValue = new GraphQLObjectType({
  name: '__InputValue',
  description:
    'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.',
  fields: () => ({
    name: {
      type: GraphQLNonNull(GraphQLString),
      resolve: obj => obj.name,
    },
    description: {
      type: GraphQLString,
      resolve: obj => obj.description,
    },
    type: {
      type: GraphQLNonNull(__Type),
      resolve: obj => obj.type,
    },
    defaultValue: {
      type: GraphQLString,
      description:
        'A GraphQL-formatted string representing the default value for this input value.',
      resolve(inputVal) {
        const valueAST = astFromValue(inputVal.defaultValue, inputVal.type);
        return valueAST ? print(valueAST) : null;
      },
    },
  }),
});

export const __EnumValue = new GraphQLObjectType({
  name: '__EnumValue',
  description:
    'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.',
  fields: () => ({
    name: {
      type: GraphQLNonNull(GraphQLString),
      resolve: obj => obj.name,
    },
    description: {
      type: GraphQLString,
      resolve: obj => obj.description,
    },
    isDeprecated: {
      type: GraphQLNonNull(GraphQLBoolean),
      resolve: obj => obj.isDeprecated,
    },
    deprecationReason: {
      type: GraphQLString,
      resolve: obj => obj.deprecationReason,
    },
  }),
});

export const TypeKind = Object.freeze({
  SCALAR: 'SCALAR',
  OBJECT: 'OBJECT',
  INTERFACE: 'INTERFACE',
  UNION: 'UNION',
  ENUM: 'ENUM',
  INPUT_OBJECT: 'INPUT_OBJECT',
  LIST: 'LIST',
  NON_NULL: 'NON_NULL',
});

export const __TypeKind = new GraphQLEnumType({
  name: '__TypeKind',
  description: 'An enum describing what kind of type a given `__Type` is.',
  values: {
    SCALAR: {
      value: TypeKind.SCALAR,
      description: 'Indicates this type is a scalar.',
    },
    OBJECT: {
      value: TypeKind.OBJECT,
      description:
        'Indicates this type is an object. `fields` and `interfaces` are valid fields.',
    },
    INTERFACE: {
      value: TypeKind.INTERFACE,
      description:
        'Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.',
    },
    UNION: {
      value: TypeKind.UNION,
      description:
        'Indicates this type is a union. `possibleTypes` is a valid field.',
    },
    ENUM: {
      value: TypeKind.ENUM,
      description:
        'Indicates this type is an enum. `enumValues` is a valid field.',
    },
    INPUT_OBJECT: {
      value: TypeKind.INPUT_OBJECT,
      description:
        'Indicates this type is an input object. `inputFields` is a valid field.',
    },
    LIST: {
      value: TypeKind.LIST,
      description: 'Indicates this type is a list. `ofType` is a valid field.',
    },
    NON_NULL: {
      value: TypeKind.NON_NULL,
      description:
        'Indicates this type is a non-null. `ofType` is a valid field.',
    },
  },
});

/**
 * Note that these are GraphQLField and not GraphQLFieldConfig,
 * so the format for args is different.
 */

export const SchemaMetaFieldDef: GraphQLField<*, *> = {
  name: '__schema',
  type: GraphQLNonNull(__Schema),
  description: 'Access the current type schema of this server.',
  args: [],
  resolve: (source, args, context, { schema }) => schema,
};

export const TypeMetaFieldDef: GraphQLField<*, *> = {
  name: '__type',
  type: __Type,
  description: 'Request the type information of a single type.',
  args: [{ name: 'name', type: GraphQLNonNull(GraphQLString) }],
  resolve: (source, { name }, context, { schema }) => schema.getType(name),
};

export const TypeNameMetaFieldDef: GraphQLField<*, *> = {
  name: '__typename',
  type: GraphQLNonNull(GraphQLString),
  description: 'The name of the current Object type at runtime.',
  args: [],
  resolve: (source, args, context, { parentType }) => parentType.name,
};

export const introspectionTypes = Object.freeze([
  __Schema,
  __Directive,
  __DirectiveLocation,
  __Type,
  __Field,
  __InputValue,
  __EnumValue,
  __TypeKind,
]);

export function isIntrospectionType(type: mixed): boolean %checks {
  return (
    isNamedType(type) &&
    introspectionTypes.some(({ name }) => type.name === name)
  );
}
<commit_msg>Add typings to introspection resolvers (#1934)<commit_after>/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @flow strict
 */

import objectValues from '../polyfills/objectValues';
import inspect from '../jsutils/inspect';
import { astFromValue } from '../utilities/astFromValue';
import { print } from '../language/printer';
import {
  type GraphQLType,
  type GraphQLInputField,
  type GraphQLEnumValue,
  type GraphQLField,
  type GraphQLFieldConfigMap,
  GraphQLObjectType,
  GraphQLEnumType,
  GraphQLList,
  GraphQLNonNull,
  isScalarType,
  isObjectType,
  isInterfaceType,
  isUnionType,
  isEnumType,
  isInputObjectType,
  isListType,
  isNonNullType,
  isAbstractType,
  isNamedType,
} from './definition';
import { type GraphQLSchema } from './schema';
import { type GraphQLDirective } from './directives';
import { GraphQLString, GraphQLBoolean } from './scalars';
import { DirectiveLocation } from '../language/directiveLocation';

export const __Schema = new GraphQLObjectType({
  name: '__Schema',
  description:
    'A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.',
  fields: () =>
    ({
      types: {
        description: 'A list of all types supported by this server.',
        type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Type))),
        resolve(schema) {
          return objectValues(schema.getTypeMap());
        },
      },
      queryType: {
        description: 'The type that query operations will be rooted at.',
        type: GraphQLNonNull(__Type),
        resolve: schema => schema.getQueryType(),
      },
      mutationType: {
        description:
          'If this server supports mutation, the type that mutation operations will be rooted at.',
        type: __Type,
        resolve: schema => schema.getMutationType(),
      },
      subscriptionType: {
        description:
          'If this server support subscription, the type that subscription operations will be rooted at.',
        type: __Type,
        resolve: schema => schema.getSubscriptionType(),
      },
      directives: {
        description: 'A list of all directives supported by this server.',
        type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__Directive))),
        resolve: schema => schema.getDirectives(),
      },
    }: GraphQLFieldConfigMap<GraphQLSchema, mixed>),
});

export const __Directive = new GraphQLObjectType({
  name: '__Directive',
  description:
    "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\n\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.",
  fields: () =>
    ({
      name: {
        type: GraphQLNonNull(GraphQLString),
        resolve: obj => obj.name,
      },
      description: {
        type: GraphQLString,
        resolve: obj => obj.description,
      },
      locations: {
        type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__DirectiveLocation))),
        resolve: obj => obj.locations,
      },
      args: {
        type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),
        resolve: directive => directive.args || [],
      },
    }: GraphQLFieldConfigMap<GraphQLDirective, mixed>),
});

export const __DirectiveLocation = new GraphQLEnumType({
  name: '__DirectiveLocation',
  description:
    'A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.',
  values: {
    QUERY: {
      value: DirectiveLocation.QUERY,
      description: 'Location adjacent to a query operation.',
    },
    MUTATION: {
      value: DirectiveLocation.MUTATION,
      description: 'Location adjacent to a mutation operation.',
    },
    SUBSCRIPTION: {
      value: DirectiveLocation.SUBSCRIPTION,
      description: 'Location adjacent to a subscription operation.',
    },
    FIELD: {
      value: DirectiveLocation.FIELD,
      description: 'Location adjacent to a field.',
    },
    FRAGMENT_DEFINITION: {
      value: DirectiveLocation.FRAGMENT_DEFINITION,
      description: 'Location adjacent to a fragment definition.',
    },
    FRAGMENT_SPREAD: {
      value: DirectiveLocation.FRAGMENT_SPREAD,
      description: 'Location adjacent to a fragment spread.',
    },
    INLINE_FRAGMENT: {
      value: DirectiveLocation.INLINE_FRAGMENT,
      description: 'Location adjacent to an inline fragment.',
    },
    VARIABLE_DEFINITION: {
      value: DirectiveLocation.VARIABLE_DEFINITION,
      description: 'Location adjacent to a variable definition.',
    },
    SCHEMA: {
      value: DirectiveLocation.SCHEMA,
      description: 'Location adjacent to a schema definition.',
    },
    SCALAR: {
      value: DirectiveLocation.SCALAR,
      description: 'Location adjacent to a scalar definition.',
    },
    OBJECT: {
      value: DirectiveLocation.OBJECT,
      description: 'Location adjacent to an object type definition.',
    },
    FIELD_DEFINITION: {
      value: DirectiveLocation.FIELD_DEFINITION,
      description: 'Location adjacent to a field definition.',
    },
    ARGUMENT_DEFINITION: {
      value: DirectiveLocation.ARGUMENT_DEFINITION,
      description: 'Location adjacent to an argument definition.',
    },
    INTERFACE: {
      value: DirectiveLocation.INTERFACE,
      description: 'Location adjacent to an interface definition.',
    },
    UNION: {
      value: DirectiveLocation.UNION,
      description: 'Location adjacent to a union definition.',
    },
    ENUM: {
      value: DirectiveLocation.ENUM,
      description: 'Location adjacent to an enum definition.',
    },
    ENUM_VALUE: {
      value: DirectiveLocation.ENUM_VALUE,
      description: 'Location adjacent to an enum value definition.',
    },
    INPUT_OBJECT: {
      value: DirectiveLocation.INPUT_OBJECT,
      description: 'Location adjacent to an input object type definition.',
    },
    INPUT_FIELD_DEFINITION: {
      value: DirectiveLocation.INPUT_FIELD_DEFINITION,
      description: 'Location adjacent to an input object field definition.',
    },
  },
});

export const __Type = new GraphQLObjectType({
  name: '__Type',
  description:
    'The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\n\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.',
  fields: () =>
    ({
      kind: {
        type: GraphQLNonNull(__TypeKind),
        resolve(type) {
          if (isScalarType(type)) {
            return TypeKind.SCALAR;
          } else if (isObjectType(type)) {
            return TypeKind.OBJECT;
          } else if (isInterfaceType(type)) {
            return TypeKind.INTERFACE;
          } else if (isUnionType(type)) {
            return TypeKind.UNION;
          } else if (isEnumType(type)) {
            return TypeKind.ENUM;
          } else if (isInputObjectType(type)) {
            return TypeKind.INPUT_OBJECT;
          } else if (isListType(type)) {
            return TypeKind.LIST;
          } else if (isNonNullType(type)) {
            return TypeKind.NON_NULL;
          }

          // Not reachable. All possible types have been considered.
          /* istanbul ignore next */
          throw new Error(`Unexpected type: "${inspect((type: empty))}".`);
        },
      },
      name: {
        type: GraphQLString,
        resolve: obj => (obj.name !== undefined ? obj.name : undefined),
      },
      description: {
        type: GraphQLString,
        resolve: obj =>
          obj.description !== undefined ? obj.description : undefined,
      },
      fields: {
        type: GraphQLList(GraphQLNonNull(__Field)),
        args: {
          includeDeprecated: { type: GraphQLBoolean, defaultValue: false },
        },
        resolve(type, { includeDeprecated }) {
          if (isObjectType(type) || isInterfaceType(type)) {
            let fields = objectValues(type.getFields());
            if (!includeDeprecated) {
              fields = fields.filter(field => !field.deprecationReason);
            }
            return fields;
          }
          return null;
        },
      },
      interfaces: {
        type: GraphQLList(GraphQLNonNull(__Type)),
        resolve(type) {
          if (isObjectType(type)) {
            return type.getInterfaces();
          }
        },
      },
      possibleTypes: {
        type: GraphQLList(GraphQLNonNull(__Type)),
        resolve(type, args, context, { schema }) {
          if (isAbstractType(type)) {
            return schema.getPossibleTypes(type);
          }
        },
      },
      enumValues: {
        type: GraphQLList(GraphQLNonNull(__EnumValue)),
        args: {
          includeDeprecated: { type: GraphQLBoolean, defaultValue: false },
        },
        resolve(type, { includeDeprecated }) {
          if (isEnumType(type)) {
            let values = type.getValues();
            if (!includeDeprecated) {
              values = values.filter(value => !value.deprecationReason);
            }
            return values;
          }
        },
      },
      inputFields: {
        type: GraphQLList(GraphQLNonNull(__InputValue)),
        resolve(type) {
          if (isInputObjectType(type)) {
            return objectValues(type.getFields());
          }
        },
      },
      ofType: {
        type: __Type,
        resolve: obj => (obj.ofType !== undefined ? obj.ofType : undefined),
      },
    }: GraphQLFieldConfigMap<GraphQLType, mixed>),
});

export const __Field = new GraphQLObjectType({
  name: '__Field',
  description:
    'Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.',
  fields: () =>
    ({
      name: {
        type: GraphQLNonNull(GraphQLString),
        resolve: obj => obj.name,
      },
      description: {
        type: GraphQLString,
        resolve: obj => obj.description,
      },
      args: {
        type: GraphQLNonNull(GraphQLList(GraphQLNonNull(__InputValue))),
        resolve: field => field.args || [],
      },
      type: {
        type: GraphQLNonNull(__Type),
        resolve: obj => obj.type,
      },
      isDeprecated: {
        type: GraphQLNonNull(GraphQLBoolean),
        resolve: obj => obj.isDeprecated,
      },
      deprecationReason: {
        type: GraphQLString,
        resolve: obj => obj.deprecationReason,
      },
    }: GraphQLFieldConfigMap<GraphQLField<mixed, mixed>, mixed>),
});

export const __InputValue = new GraphQLObjectType({
  name: '__InputValue',
  description:
    'Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.',
  fields: () =>
    ({
      name: {
        type: GraphQLNonNull(GraphQLString),
        resolve: obj => obj.name,
      },
      description: {
        type: GraphQLString,
        resolve: obj => obj.description,
      },
      type: {
        type: GraphQLNonNull(__Type),
        resolve: obj => obj.type,
      },
      defaultValue: {
        type: GraphQLString,
        description:
          'A GraphQL-formatted string representing the default value for this input value.',
        resolve(inputVal) {
          const valueAST = astFromValue(inputVal.defaultValue, inputVal.type);
          return valueAST ? print(valueAST) : null;
        },
      },
    }: GraphQLFieldConfigMap<GraphQLInputField, mixed>),
});

export const __EnumValue = new GraphQLObjectType({
  name: '__EnumValue',
  description:
    'One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.',
  fields: () =>
    ({
      name: {
        type: GraphQLNonNull(GraphQLString),
        resolve: obj => obj.name,
      },
      description: {
        type: GraphQLString,
        resolve: obj => obj.description,
      },
      isDeprecated: {
        type: GraphQLNonNull(GraphQLBoolean),
        resolve: obj => obj.isDeprecated,
      },
      deprecationReason: {
        type: GraphQLString,
        resolve: obj => obj.deprecationReason,
      },
    }: GraphQLFieldConfigMap<GraphQLEnumValue, mixed>),
});

export const TypeKind = Object.freeze({
  SCALAR: 'SCALAR',
  OBJECT: 'OBJECT',
  INTERFACE: 'INTERFACE',
  UNION: 'UNION',
  ENUM: 'ENUM',
  INPUT_OBJECT: 'INPUT_OBJECT',
  LIST: 'LIST',
  NON_NULL: 'NON_NULL',
});

export const __TypeKind = new GraphQLEnumType({
  name: '__TypeKind',
  description: 'An enum describing what kind of type a given `__Type` is.',
  values: {
    SCALAR: {
      value: TypeKind.SCALAR,
      description: 'Indicates this type is a scalar.',
    },
    OBJECT: {
      value: TypeKind.OBJECT,
      description:
        'Indicates this type is an object. `fields` and `interfaces` are valid fields.',
    },
    INTERFACE: {
      value: TypeKind.INTERFACE,
      description:
        'Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.',
    },
    UNION: {
      value: TypeKind.UNION,
      description:
        'Indicates this type is a union. `possibleTypes` is a valid field.',
    },
    ENUM: {
      value: TypeKind.ENUM,
      description:
        'Indicates this type is an enum. `enumValues` is a valid field.',
    },
    INPUT_OBJECT: {
      value: TypeKind.INPUT_OBJECT,
      description:
        'Indicates this type is an input object. `inputFields` is a valid field.',
    },
    LIST: {
      value: TypeKind.LIST,
      description: 'Indicates this type is a list. `ofType` is a valid field.',
    },
    NON_NULL: {
      value: TypeKind.NON_NULL,
      description:
        'Indicates this type is a non-null. `ofType` is a valid field.',
    },
  },
});

/**
 * Note that these are GraphQLField and not GraphQLFieldConfig,
 * so the format for args is different.
 */

export const SchemaMetaFieldDef: GraphQLField<mixed, mixed> = {
  name: '__schema',
  type: GraphQLNonNull(__Schema),
  description: 'Access the current type schema of this server.',
  args: [],
  resolve: (source, args, context, { schema }) => schema,
};

export const TypeMetaFieldDef: GraphQLField<mixed, mixed> = {
  name: '__type',
  type: __Type,
  description: 'Request the type information of a single type.',
  args: [{ name: 'name', type: GraphQLNonNull(GraphQLString) }],
  resolve: (source, { name }, context, { schema }) => schema.getType(name),
};

export const TypeNameMetaFieldDef: GraphQLField<mixed, mixed> = {
  name: '__typename',
  type: GraphQLNonNull(GraphQLString),
  description: 'The name of the current Object type at runtime.',
  args: [],
  resolve: (source, args, context, { parentType }) => parentType.name,
};

export const introspectionTypes = Object.freeze([
  __Schema,
  __Directive,
  __DirectiveLocation,
  __Type,
  __Field,
  __InputValue,
  __EnumValue,
  __TypeKind,
]);

export function isIntrospectionType(type: mixed): boolean %checks {
  return (
    isNamedType(type) &&
    introspectionTypes.some(({ name }) => type.name === name)
  );
}
<|endoftext|>