Example #1
0
  lookup: function(repo) {
    var self = this;

    var newLookup = false;
    var lookupCache;
    var latestKey = 'latest';
    var repoPath = repo[0] == '@' ? '@' + encodeURIComponent(repo.substr(1)) : encodeURIComponent(repo);

    return asp(fs.readFile)(path.resolve(self.tmpDir, repo + '.json'))
    .then(function(lookupJSON) {
      lookupCache = JSON.parse(lookupJSON.toString());
    }).catch(function(e) {
      if (e.code == 'ENOENT' || e instanceof SyntaxError)
        return;
      throw e;
    })
    .then(function() {
      var registryInfo = self.registryInfo(repo);

      return asp(request)(auth.injectRequestOptions({
        uri: registryInfo.url + '/' + repoPath,
        gzip: true,
        strictSSL: self.strictSSL,
        headers: lookupCache ? {
          'if-none-match': lookupCache.eTag
        } : {}
      }, registryInfo.auth)).then(function(res) {
        if (res.statusCode == 304)
          return { versions: lookupCache.versions,
                   latest: lookupCache.latest };

        if (res.statusCode == 404)
          return { notfound: true };

        if (res.statusCode == 401)
          throw 'Invalid authentication details. Run %jspm registry config ' + self.name + '% to reconfigure.';

        if (res.statusCode != 200)
          throw 'Invalid status code ' + res.statusCode;

        var versions = {};
        var latest;
        var packageData;

        try {
          var json = JSON.parse(res.body);
          var distTags = json['dist-tags'] || {};
          packageData = json.versions;
          latest = distTags[latestKey];
        }
        catch(e) {
          throw 'Unable to parse package.json';
        }

        for (var v in packageData) {
          if (packageData[v].dist && packageData[v].dist.shasum)
            versions[v] = {
              hash: packageData[v].dist.shasum,
              meta: packageData[v],
              stable: !packageData[v].deprecated
            };
        }

        if (res.headers.etag) {
          newLookup = true;
          lookupCache = {
            eTag: res.headers.etag,
            versions: versions,
            latest: latest,
          };
        }

        return { versions: versions,
                 latest: latest };
      }, function(err) {
        if (err.code == 'ENOTFOUND' && err.toString().indexOf('getaddrinfo') != -1 || err.code == 'ECONNRESET') {
          err.retriable = true;
          err.hideStack = true;
        }
        throw err;
      });
    })
    .then(function(response) {
      // save lookupCache
      if (newLookup) {
        var lookupJSON = JSON.stringify(lookupCache);
        var outputPath = path.resolve(self.tmpDir, repo + '.json');
        return asp(mkdirp)(path.dirname(outputPath))
        .then(function() {
          return asp(fs.writeFile)(outputPath, lookupJSON);
        })
        .then(function() {
          return response;
        });
      }

      return response;
    });
  },
Example #2
0
portfinder.basePort = 9005;

var FIFTEEN_MINUTES_IN_MS = 15 * 60 * 1000;
var SCOPES = [
  scopes.EMAIL,
  scopes.OPENID,
  scopes.CLOUD_PROJECTS_READONLY,
  scopes.FIREBASE_PLATFORM
];

if (previews.functions) {
  SCOPES.push(scopes.CLOUD_PLATFORM);
}

var _nonce = _.random(1, 2 << 29).toString();
var _getPort = RSVP.denodeify(portfinder.getPort);

// in-memory cache, so we have it for successive calls
var lastAccessToken = {};

var _getCallbackUrl = function(port) {
  if (_.isUndefined(port)) {
    return 'urn:ietf:wg:oauth:2.0:oob';
  }
  return 'http://localhost:' + port;
};

var _getLoginUrl = function(callbackUrl) {
  return api.authOrigin + '/o/oauth2/auth?' + _.map({
    client_id: api.clientId,
    scope: SCOPES.join(' '),
'use strict';

const RSVP = require('rsvp');
const ember = require('../helpers/ember');
const fs = require('fs-extra');
const path = require('path');
let remove = RSVP.denodeify(fs.remove);
let root = process.cwd();
let tmproot = path.join(root, 'tmp');
const Blueprint = require('../../lib/models/blueprint');
const BlueprintNpmTask = require('ember-cli-internal-test-helpers/lib/helpers/disable-npm-on-blueprint');
const mkTmpDirIn = require('../../lib/utilities/mk-tmp-dir-in');

const chai = require('../chai');
let expect = chai.expect;
let file = chai.file;

describe('Acceptance: ember generate in-repo-addon', function() {
  this.timeout(20000);

  before(function() {
    BlueprintNpmTask.disableNPM(Blueprint);
  });

  after(function() {
    BlueprintNpmTask.restoreNPM(Blueprint);
  });

  beforeEach(function() {
    return mkTmpDirIn(tmproot).then(function(tmpdir) {
      process.chdir(tmpdir);
Example #4
0
 .then(function() {
   return asp(fs.rename)(tmpDir, dir);
 });
Example #5
0
 .then(function() {
   return asp(fs.writeFile)(file, source + '\n//# sourceMappingURL=' + relFile.split('/').pop() + '.map');
 })
var fs = require('fs');
var path = require('path');
var RSVP = require('rsvp');
var rimraf = RSVP.denodeify(require('rimraf'));
var helpers = require('broccoli-kitchen-sink-helpers');
var symlinkOrCopy = require('symlink-or-copy');
var assign = require('lodash-node/modern/object/assign');
var CoreObject = require('core-object');
var debugGenerator = require('debug');
var Key = require('./key');
var readCompatAPI = require('broccoli-read-compat');

var CachingWriter = {};

CachingWriter.init = function(inputTrees, options) {
  this._lastKeys = [];
  this._shouldBeIgnoredCache = Object.create(null);

  this.debug = debugGenerator('broccoli-caching-writer:' + (this.description || this.constructor.name));

  if (options) {
    for (var key in options) {
      if (options.hasOwnProperty(key)) {
        this[key] = options[key];
      }
    }
  }

  if (!inputTrees) {
    throw new Error('no inputTree was provided');
  }
Example #7
0
'use strict';

/**
@module ember-cli
*/
const RSVP = require('rsvp');
const path = require('path');
const findup = require('find-up');
const resolve = RSVP.denodeify(require('resolve'));
const fs = require('fs-extra');
const existsSync = require('exists-sync');
const _ = require('ember-cli-lodash-subset');
const logger = require('heimdalljs-logger')('ember-cli:project');
const versionUtils = require('../utilities/version-utils');
const emberCLIVersion = versionUtils.emberCLIVersion;
const findAddonByName = require('../utilities/find-addon-by-name');
const Instrumentation = require('./instrumentation');
const experiments = require('../experiments');
const heimdall = require('heimdalljs');

let processCwd = process.cwd();
// ensure NULL_PROJECT is a singleton
let NULL_PROJECT;

class Project {
  /**
    The Project model is tied to your package.json. It is instantiated
    by giving {{#crossLink "Project/closestSync:method"}}{{/crossLink}}
    the path to your project.

    @class Project
Example #8
0
require('mocha-as-promised')()
var chai = require('chai')
chai.use(require('chai-as-promised'))
var expect = chai.expect

var RSVP = require('rsvp')
var Promise = RSVP.Promise
var fs = { mkdir: RSVP.denodeify(require('fs').mkdir),
           stat: RSVP.denodeify(require('fs').stat) }
var slickTemp = require('./index.js')
var rimraf = RSVP.denodeify(require('rimraf'))

describe('Unit tests:', function() {

  describe('remove()', function() {
    var thing = { coolDir: 'really-cool-directory' }

    it('should remove an existing directory', function() {

      return Promise.resolve()

      .then(function() { // Create directory manually
        return fs.mkdir(thing.coolDir)
      })

      .then(function() { // Call remove()
        return slickTemp.remove(thing, 'coolDir')
      })

      .then(function() { // Check if removing it worked
        expect(thing).to.have.property('coolDir', null)
Example #9
0
'use strict';

var path = require('path');
var cproc = require('child_process');
var through = require('through2');
var convert = require('convert-source-map');
var EventEmitter = require('events').EventEmitter;
var sm = require('source-map');
var crypto = require('crypto');
var fs = require('fs');
var _ = require('lodash');
var RSVP = require('rsvp');
var readFile = RSVP.denodeify(fs.readFile);
var has = require('./lib/has');

function hashStr(str) {
  var hasher = crypto.createHash('sha256');
  hasher.update(str);
  return hasher.digest('base64').slice(0, 20);
}

var readManagerTemplate = _.once(function() {
  return readFile(path.join(__dirname, 'hmr-manager-template.js'), 'utf8');
});

var validUpdateModes = ['websocket', 'ajax', 'fs', 'none'];
var updateModesNeedingUrl = ['ajax'];

function makeIdentitySourceMap(content, resourcePath) {
  var map = new sm.SourceMapGenerator();
  map.setSourceContent(resourcePath, content);
Example #10
0
var RSVP = require('rsvp');
var request = RSVP.denodeify(require('request'));
var twitter = require('twitter');
var auth = require('./auth.js');
var twit = new twitter({
	consumer_key: auth.consumer_key,
	consumer_secret: auth.consumer_secret,
	access_token_key: auth.access_token_key,
	access_token_secret: auth.access_token_secret
});

var do_expanding = false;

var twitter_get = function(url) {
	return new RSVP.Promise(function(resolve, reject) {
		twit.get(url, function(data) {
			if (data.statusCode) {
				console.log(data);	
				reject();
			}
			resolve(data);
		});
	});
};

function strip_utm_params(url) {
	return url.split('?utm')[0].split('&utm')[0];
}

function expand_url(short_url) {
	if (do_expanding) {
/* jshint node: true */
'use strict';

var RSVP = require('rsvp');
var path = require('path');
var sauceConnectLauncher = require('sauce-connect-launcher');
var sauceConnectLauncherPromise = RSVP.denodeify(sauceConnectLauncher);

module.exports = {
  name: 'sauce:connect',
  aliases: ['start-sauce-connect'],
  works: 'insideProject',
  description: 'Connect to sauce using sauce-connect https://docs.saucelabs.com/reference/sauce-connect/.',

  availableOptions: [],

  run: function() {
    var self = this;
    var opts = {
      username: process.env.SAUCE_USERNAME,
      accessKey: process.env.SAUCE_ACCESS_KEY,
      verbose: true,
      logger: function(message) {
        self.ui.writeLine(message, 'INFO');
      },
      pidfile: path.join(this.project.root, 'sc_client.pid')
    };

    if (process.env.TRAVIS_JOB_NUMBER) {
      opts.tunnelIdentifier = process.env.TRAVIS_JOB_NUMBER;
    }
Example #12
0
GzipFilter.prototype.processString = function(str) {
  return RSVP.denodeify(zlib.gzip)(str);
};
Example #13
0
 .then(function() {
   return asp(fs.writeFile)(outputPath, lookupJSON);
 })
Example #14
0
    .then(function() {
      var registryInfo = self.registryInfo(repo);

      return asp(request)(auth.injectRequestOptions({
        uri: registryInfo.url + '/' + repoPath,
        gzip: true,
        strictSSL: self.strictSSL,
        headers: lookupCache ? {
          'if-none-match': lookupCache.eTag
        } : {}
      }, registryInfo.auth)).then(function(res) {
        if (res.statusCode == 304)
          return { versions: lookupCache.versions,
                   latest: lookupCache.latest };

        if (res.statusCode == 404)
          return { notfound: true };

        if (res.statusCode == 401)
          throw 'Invalid authentication details. Run %jspm registry config ' + self.name + '% to reconfigure.';

        if (res.statusCode != 200)
          throw 'Invalid status code ' + res.statusCode;

        var versions = {};
        var latest;
        var packageData;

        try {
          var json = JSON.parse(res.body);
          var distTags = json['dist-tags'] || {};
          packageData = json.versions;
          latest = distTags[latestKey];
        }
        catch(e) {
          throw 'Unable to parse package.json';
        }

        for (var v in packageData) {
          if (packageData[v].dist && packageData[v].dist.shasum)
            versions[v] = {
              hash: packageData[v].dist.shasum,
              meta: packageData[v],
              stable: !packageData[v].deprecated
            };
        }

        if (res.headers.etag) {
          newLookup = true;
          lookupCache = {
            eTag: res.headers.etag,
            versions: versions,
            latest: latest,
          };
        }

        return { versions: versions,
                 latest: latest };
      }, function(err) {
        if (err.code == 'ENOTFOUND' && err.toString().indexOf('getaddrinfo') != -1 || err.code == 'ECONNRESET') {
          err.retriable = true;
          err.hideStack = true;
        }
        throw err;
      });
    })
Example #15
0
 .then(function() {
   return asp(rimraf)(config.pjson.dist);
 })
Example #16
0
/* eslint-env node */
'use strict';

const rsvp = require('rsvp');
const fs = require('fs');
const path = require('path');
const writeFile = rsvp.denodeify(fs.writeFile);
const chalk = require('chalk');

const bs3Version = '^3.3.7';

module.exports = {
  normalizeEntityName() {
  },

  afterInstall() {
    return this.addDependencies()
      .then(() => this.addPreprocessorImport());
  },

  addDependencies() {
    let dependencies = this.project.dependencies();

    let promises = [
    ];

    if ('ember-cli-sass' in dependencies) {
      promises.push(this.addPackageToProject('bootstrap-sass', bs3Version));
    } else {
      promises.push(this.addBowerPackageToProject('bootstrap', bs3Version));
    }
Example #17
0
 .then(function() {
   return asp(ncp)(config.pjson.lib, config.pjson.dist);
 })
Example #18
0
 .then(function() {
   return asp(fs.readFile)(path.resolve(config.pjson.packages, '.loaderversions'));
 })
Example #19
0
var glob = require('glob');
var Mocha = require('mocha');
var RSVP = require('rsvp');
var rimraf = require('rimraf');
var mochaOnlyDetector = require('mocha-only-detector');

if (process.env.EOLNEWLINE) {
  require('os').EOL = '\n';
}

rimraf.sync('.node_modules-tmp');
rimraf.sync('.bower_components-tmp');

var root = 'tests/{unit,acceptance}';
var _checkOnlyInTests = RSVP.denodeify(mochaOnlyDetector.checkFolder.bind(null, root + '/**/*{-test,-slow}.js'));
var optionOrFile = process.argv[2];
var mocha = new Mocha({
  timeout: 5000,
  reporter: 'spec'
});
var testFiles = glob.sync(root + '/**/*-test.js');
var jshintPosition = testFiles.indexOf('tests/unit/jshint-test.js');
var jshint = testFiles.splice(jshintPosition, 1);

testFiles = jshint.concat(testFiles);

if (optionOrFile === 'all') {
  addFiles(mocha, testFiles);
  addFiles(mocha, '/**/*-slow.js');
} else if (optionOrFile === 'jshint')  {
Example #20
0
 return asp(fs.readFile)(path.resolve(loaderFilesCacheDir, file)).then(function(source) {
   if (transform)
     source = transform(source.toString());
   ui.log('info', '  `' + name + '`');
   return asp(fs.writeFile)(path.resolve(config.pjson.packages, name), source);
 });
Example #21
0
 .then(function() {
   return asp(rimraf)(dir);
 })
Example #22
0
 .then(function() {
   return asp(mkdirp)(config.pjson.packages);
 })
Example #23
0
      .then(function(stats) {
        if (stats.isSymbolicLink())
          return;

        return asp(fs.readFile)(file)
        .then(function(source) {
          source += '';
          
          return Promise.resolve()
          // add shim config if necessary
          .then(function() {
            if (!options.shim)
              return;

            var match;

            if (!(match = matchWithWildcard(options.shim, relModule)))
              return;

            var curShim = options.shim[match];
            if (curShim instanceof Array)
              curShim = { deps: curShim };

            // NB backwards-compatible with shim.imports
            curShim.deps = curShim.deps || curShim.imports;

            if (typeof curShim.deps == 'string')
              curShim.deps = [curShim.deps];

            var depStr = '"format global";' + nl;
            if (curShim.deps)
              for (var i = 0; i < curShim.deps.length; i++)
                depStr += '"deps ' + curShim.deps[i] + '";' + nl;

            if (curShim.exports)
              depStr += '"exports ' + curShim.exports + '";' + nl;

            changed = true;
            source = depStr + source;

            return true;
          })

          // add any format hint if provided
          // only add format hint if detection would fail
          // also set the format here if not set
          // NB all regexs should apply after removing comments
          // also ideally format injection should be post-minification
          // in case of minification quirks
          .then(function(shimmed) {
            // don't add format if already shimmed!
            if (shimmed)
              return;

            var detected = detectFormat(source);

            // don't rewrite meta
            if (detected.meta) {
              format = detected.format;
              return;
            }

            if (options.alwaysIncludeFormat || !format || detected.format != format) {
              changed = true;
              source = '"format ' + (format || detected.format) + '";' + nl + source;
            }

            format = detected.format;
          })

          // apply map config
          .then(function() {
            // ES6
            if (format == 'es6') {
              source = source.replace(es6DepRegEx, function(statement, start, type, str, singleString, doubleString) {
                var name = singleString || doubleString;
                var mapped = applyMap(name, map, relFile, options.removeJSExtensions);

                if (!mapped)
                  return statement;

                changed = true;
                return statement.replace(new RegExp('"' + name + '"|\'' + name + '\'', 'g'), '\'' + mapped + '\'');
              });
            }

            // AMD
            else if (format == 'amd') {
              amdDefineRegEx.lastIndex = 0;
              var defineStatement = amdDefineRegEx.exec(source);
              if (defineStatement) {
                if (!defineStatement[2])
                  return;
                
                var depArray = eval(defineStatement[2]);
                depArray.map(function(name) {
                  var mapped = applyMap(name, map, relFile, options.removeJSExtensions);
                  if (!mapped)
                    return name;

                  changed = true;
                  return mapped;
                });

                if (changed)
                  source = source.replace(defineStatement[2], JSON.stringify(depArray));
              }
            }

            // CommonJS
            else if (format == 'cjs') {
              source = source.replace(cjsRequireRegEx, function(statement, singleString, doubleString) {
                var name = singleString || doubleString;
                name = name.substr(1, name.length - 2);
                var mapped = applyMap(name, map, relFile, options.removeJSExtensions);

                if (!mapped)
                  return statement;

                changed = true;
                return statement.replace(new RegExp('"' + name + '"|\'' + name + '\'', 'g'), '\'' + mapped + '\'');
              });
            }

            // Global? (including shim?)
            else {
            }
          })

          
          // if changed, save these meta-updates into the original file
          .then(function() {

            // ensure there is a comment at the beginning of the file
            // this is necessary to protect the source map when wrapping
            if (!source.match(initialCommentRegEx)) {
              source = '\/* *\/ \n' + source;
              changed = true;
            }

            if (changed)
              return asp(fs.writeFile)(file, source);
          })

          // transpile
          .then(function() {
            if (!options.transpile)
              return;

            traceur.options.sourceMaps = true;
            traceur.options.modules = 'instantiate';

            try {
              var compiler = new traceur.Compiler({
                moduleName: '',
                modules: 'instantiate'
              });

              source = compiler.compile(source, relFile, path.basename(relFile.replace(/\.js$/, '.src.js')));
              sourceMap = compiler.getSourceMap();
            }
            catch(e) {
              // an error in one compiled file doesn't stop all compilation

              if (!e.stack)
                compileErrors +=  + '\n';
              else
                compileErrors += e.stack + '\n' + relFile + ': Unable to transpile ES6\n';
            }
          })

          // minify
          .then(function() {
            if (!options.minify)
              return;

            try {
              var ast = uglify.parse(source, { filename: path.basename(relFile.replace(/\.js$/, '.src.js')) });
              
              ast.figure_out_scope();

              ast = ast.transform(uglify.Compressor({
                warnings: false,
                evaluate: false
              }));

              ast.figure_out_scope();
              ast.compute_char_frequency();
              ast.mangle_names({
                except: ['require']
              });

              var source_map = uglify.SourceMap({
                file: path.basename(relFile),
                orig: sourceMap
              });

              source = ast.print_to_string({
                ascii_only: true, // for some reason non-ascii broke esprima
                comments: function(node, comment) {
                  return comment.line == 1 && comment.col == 0;
                },
                source_map: source_map
              });
              sourceMap = source_map.toString();
            }
            catch(e) {
              // an error in one compiled file doesn't stop all compilation
              compileErrors += relFile + ': Unable to minify file\n';
            }
          })

          // finally, if compiled, rename to the new file with source maps
          .then(function() {
            if (!options.minify && !options.transpile)
              return;

            // rename the original with meta changes to .src.js
            return asp(fs.rename)(file, file.replace(/\.js$/, '.src.js'))

            // write .js as the current source, with a source map comment
            .then(function() {
              return asp(fs.writeFile)(file, source + '\n//# sourceMappingURL=' + relFile.split('/').pop() + '.map');
            })

            // write the source map to .js.map
            .then(function() {
              return asp(fs.writeFile)(file + '.map', sourceMap);
            });
          })
        }, function(e) {
          if (e.code == 'EISDIR')
            return;
          else
            throw e;
        });
      }, function(e) {
Example #24
0
 .then(function() {
   // delete old versions
   return asp(fs.readdir)(config.pjson.packages);
 })
Example #25
0
 .then(function() {
   return asp(fs.writeFile)(file + '.map', sourceMap);
 });
Example #26
0
 }).map(function(file) {
   return asp(fs.unlink)(path.resolve(config.pjson.packages, file));
 }));
Example #27
0
'use strict';

var walkSync = require('./utilities/walk-sync').walkSync;
var fs = require('fs-extra');
var chalk = require('chalk');
var RSVP = require('rsvp');
var path = require('path');
var stat = RSVP.denodeify(fs.stat);
var outputFile = RSVP.denodeify(fs.outputFile);
var sequence = require('./utilities/sequence');
var FileInfo = require('./models/file-info');
var npmInstall = require('./actions/npm-install');
var bowerInstall = require('./actions/bower-install');

function writeFile(content, dest) {
  return outputFile(dest, content);
}

function isFile(info) {
  return stat(info.inputPath).invoke('isFile');
}

function Blueprint(blueprintPath, ui) {
  if (!fs.existsSync(blueprintPath)) {
    throw new Error('Unknown Blueprint: ' + blueprintPath);
  }

  this.blueprintPath = blueprintPath;
  this.ui = ui;
}
Example #28
0
  .then(function() {
    ui.log('info', '\nUsing loader versions:');
    ui.log('info', '  `systemjs@' + using.system + '`');

    return asp(fs.writeFile)(path.resolve(config.pjson.packages, '.loaderversions'), systemVersion);
  })
Example #29
0
'use strict';

const fs = require('fs-extra');
const chalk = require('chalk');
const Command = require('../models/command');
const RSVP = require('rsvp');
const Project = require('../models/project');
const SilentError = require('silent-error');
const validProjectName = require('../utilities/valid-project-name');
const normalizeBlueprint = require('../utilities/normalize-blueprint-option');
const mergeBlueprintOptions = require('../utilities/merge-blueprint-options');

const rmdir = RSVP.denodeify(fs.remove);
const Promise = RSVP.Promise;

module.exports = Command.extend({
  name: 'new',
  description: `Creates a new directory and runs ${chalk.green('ember init')} in it.`,
  works: 'outsideProject',

  availableOptions: [
    { name: 'dry-run',    type: Boolean, default: false, aliases: ['d'] },
    { name: 'verbose',    type: Boolean, default: false, aliases: ['v'] },
    { name: 'blueprint',  type: String,  default: 'app', aliases: ['b'] },
    { name: 'skip-npm',   type: Boolean, default: false, aliases: ['sn'] },
    { name: 'skip-bower', type: Boolean, default: false, aliases: ['sb'] },
    { name: 'skip-git',   type: Boolean, default: false, aliases: ['sg'] },
    { name: 'directory',  type: String,                  aliases: ['dir'] },
  ],

  anonymousOptions: [
var chai = require('chai');
var expect = chai.expect;
var RSVP = require('rsvp');
var AddonTestApp = require('ember-cli-addon-tests').AddonTestApp;
var request = require('request');
var get = RSVP.denodeify(request);

describe('cookies', function() {
  this.timeout(300000);

  var app;

  before(function() {

    app = new AddonTestApp();

    return app.create('cookies')
      .then(function() {
        return app.startServer({
          command: 'fastboot',
          additionalArguments: ['--serve-assets']
        });
      });
  });

  after(function() {
    return app.stopServer();
  });

  it('makes cookies available via a service', function() {
    var jar = request.jar();