const path = Plugin.path;
const Future = Npm.require('fibers/future');
const LRU = Npm.require('lru-cache');
const async = Npm.require('async');

// MultiFileCachingCompiler is like CachingCompiler, but for implementing
// languages which allow files to reference each other, such as CSS
// preprocessors with `@import` directives.
//
// Like CachingCompiler, you should subclass MultiFileCachingCompiler and define
// the following methods: getCacheKey, compileOneFile, addCompileResult, and
// compileResultSize.  compileOneFile gets an additional allFiles argument and
// returns an array of referenced import paths in addition to the CompileResult.
// You may also override isRoot and getAbsoluteImportPath to customize
// MultiFileCachingCompiler further.
MultiFileCachingCompiler = class MultiFileCachingCompiler
extends CachingCompilerBase {
  constructor({
    compilerName,
    defaultCacheSize,
    maxParallelism
  }) {
    super({compilerName, defaultCacheSize, maxParallelism});

    // Maps from absolute import path to { compileResult, cacheKeys }, where
    // cacheKeys is an object mapping from absolute import path to hashed
    // cacheKey for each file referenced by this file (including itself).
    this._cache = new LRU({
      max: this._cacheSize,
      // We ignore the size of cacheKeys here.
      length: (value) => this.compileResultSize(value.compileResult),
    });
  }

  // Your subclass must override this method to define the transformation from
  // InputFile to its cacheable CompileResult).
  //
  // Arguments:
  //   - inputFile is the InputFile to process
  //   - allFiles is a a Map mapping from absolute import path to InputFile of
  //     all files being processed in the target
  // Returns an object with keys:
  //   - compileResult: the CompileResult (the cacheable data type specific to
  //     your subclass).
  //   - referencedImportPaths: an array of absolute import paths of files
  //     which were refererenced by the current file.  The current file
  //     is included implicitly.
  //
  // This method is not called on files when a valid cache entry exists in
  // memory or on disk.
  //
  // On a compile error, you should call `inputFile.error` appropriately and
  // return null; this will not be cached.
  //
  // This method should not call `inputFile.addJavaScript` and similar files!
  // That's what addCompileResult is for.
  compileOneFile(inputFile, allFiles) {
    throw Error(
      'MultiFileCachingCompiler subclass should implement compileOneFile!');
  }

  // Your subclass may override this to declare that a file is not a "root" ---
  // ie, it can be included from other files but is not processed on its own. In
  // this case, MultiFileCachingCompiler won't waste time trying to look for a
  // cache for its compilation on disk.
  isRoot(inputFile) {
    return true;
  }

  // Returns the absolute import path for an InputFile. By default, this is a
  // path is a path of the form "{package}/path/to/file" for files in packages
  // and "{}/path/to/file" for files in apps. Your subclass may override and/or
  // call this method.
  getAbsoluteImportPath(inputFile) {
    if (inputFile.getPackageName() === null) {
      return '{}/' + inputFile.getPathInPackage();
    }
    return '{' + inputFile.getPackageName() + '}/'
      + inputFile.getPathInPackage();
  }

  // The processFilesForTarget method from the Plugin.registerCompiler API.
  processFilesForTarget(inputFiles) {
    const allFiles = new Map;
    const cacheKeyMap = new Map;
    const cacheMisses = [];

    inputFiles.forEach((inputFile) => {
      const importPath = this.getAbsoluteImportPath(inputFile);
      allFiles.set(importPath, inputFile);
      cacheKeyMap.set(importPath, this._deepHash(this.getCacheKey(inputFile)));
    });

    const allProcessedFuture = new Future;
    async.eachLimit(inputFiles, this._maxParallelism, (inputFile, cb) => {
      let error = null;
      try {
        // If this isn't a root, skip it (and definitely don't waste time
        // looking for a cache file that won't be there).
        if (!this.isRoot(inputFile)) {
          return;
        }

        const absoluteImportPath = this.getAbsoluteImportPath(inputFile);
        let cacheEntry = this._cache.get(absoluteImportPath);
        if (! cacheEntry) {
          cacheEntry = this._readCache(absoluteImportPath);
          if (cacheEntry) {
            this._cacheDebug(`Loaded ${ absoluteImportPath }`);
          }
        }
        if (! (cacheEntry && this._cacheEntryValid(cacheEntry, cacheKeyMap))) {
          cacheMisses.push(inputFile.getDisplayPath());

          const compileOneFileReturn = this.compileOneFile(inputFile, allFiles);
          if (! compileOneFileReturn) {
            // compileOneFile should have called inputFile.error.
            //  We don't cache failures for now.
            return;
          }
          const {compileResult, referencedImportPaths} = compileOneFileReturn;

          cacheEntry = {
            compileResult,
            cacheKeys: {
              // Include the hashed cache key of the file itself...
              [absoluteImportPath]: cacheKeyMap.get(absoluteImportPath)
            }
          };

          // ... and of the other referenced files.
          referencedImportPaths.forEach((path) => {
            if (!cacheKeyMap.has(path)) {
              throw Error(`Unknown absolute import path ${ path }`);
            }
            cacheEntry.cacheKeys[path] = cacheKeyMap.get(path);
          });

          // Save the cache entry.
          this._cache.set(absoluteImportPath, cacheEntry);
          this._writeCacheAsync(absoluteImportPath, cacheEntry);
        }

        this.addCompileResult(inputFile, cacheEntry.compileResult);
      } catch (e) {
        error = e;
      } finally {
        cb(error);
      }
    }, allProcessedFuture.resolver());
    allProcessedFuture.wait();

    if (this._cacheDebugEnabled) {
      cacheMisses.sort();
      this._cacheDebug(
        `Ran (#${ ++this._callCount }) on: ${ JSON.stringify(cacheMisses) }`);
    }
  }

  _cacheEntryValid(cacheEntry, cacheKeyMap) {
    return Object.keys(cacheEntry.cacheKeys).every(
      (path) => cacheEntry.cacheKeys[path] === cacheKeyMap.get(path)
    );
  }

  // The format of a cache file on disk is the JSON-stringified cacheKeys
  // object, a newline, followed by the CompileResult as returned from
  // this.stringifyCompileResult.
  _cacheFilename(absoluteImportPath) {
    return path.join(this._diskCache,
                     this._deepHash(absoluteImportPath) + '.cache');
  }
  // Loads a {compileResult, cacheKeys} cache entry from disk. Returns the whole
  // cache entry and loads it into the in-memory cache too.
  _readCache(absoluteImportPath) {
    if (! this._diskCache) {
      return null;
    }
    const cacheFilename = this._cacheFilename(absoluteImportPath);
    const raw = this._readFileOrNull(cacheFilename);
    if (!raw) {
      return null;
    }

    // Split on newline.
    const newlineIndex = raw.indexOf('\n');
    if (newlineIndex === -1) {
      return null;
    }
    const cacheKeysString = raw.substring(0, newlineIndex);
    const compileResultString = raw.substring(newlineIndex + 1);

    const cacheKeys = this._parseJSONOrNull(cacheKeysString);
    if (!cacheKeys) {
      return null;
    }
    const compileResult = this.parseCompileResult(compileResultString);
    if (! compileResult) {
      return null;
    }

    const cacheEntry = {compileResult, cacheKeys};
    this._cache.set(absoluteImportPath, cacheEntry);
    return cacheEntry;
  }
  _writeCacheAsync(absoluteImportPath, cacheEntry) {
    if (! this._diskCache) {
      return null;
    }
    const cacheFilename = this._cacheFilename(absoluteImportPath);
    const cacheContents =
            JSON.stringify(cacheEntry.cacheKeys) + '\n'
            + this.stringifyCompileResult(cacheEntry.compileResult);
    this._writeFileAsync(cacheFilename, cacheContents);
  }
}


* @param  {Object} dependencies An object where the keys are package

*   2. Http(s) URLs to a git commit by SHA.

*   3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)

keep keep keep keep replace keep keep keep

var selftest = require('../tool-testing/selftest.js');
var utils = require('../utils/utils.js');

import { sha1 } from '../fs/watch.js';
import httpHelpers from '../utils/http-helpers';

selftest.define('subset generator', function () {
  var out = [];
  utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {
    out.push(x);
  });
  selftest.expectEqual(out, [
    [],
    [ 'a' ],
    [ 'b' ],
    [ 'c' ],
    [ 'a', 'b' ],
    [ 'a', 'c' ],
    [ 'b', 'c' ],
    [ 'a', 'b', 'c' ]
  ]);
  out = [];
  utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {
    out.push(x);
    if (x[1] === 'c') {
      // stop iterating
      return true;
    }
  });
  selftest.expectEqual(out, [
    [],
    [ 'a' ],
    [ 'b' ],
    [ 'c' ],
    [ 'a', 'b' ],
    [ 'a', 'c' ]
  ]);
});

selftest.define("url has scheme", function () {
  // URL scheme must start with a letter, and then can be followed by
  // any number of alphanumerics, +, -, . RFC 2396 Appendix A.
  selftest.expectEqual(utils.hasScheme("http://example.com"), true);
  selftest.expectEqual(utils.hasScheme("https://example.com"), true);
  selftest.expectEqual(utils.hasScheme("ddp://example.com"), true);
  selftest.expectEqual(utils.hasScheme("http://example.com:80"), true);
  selftest.expectEqual(utils.hasScheme("https://example.com:443"), true);
  selftest.expectEqual(utils.hasScheme("ddp://example.com:443"), true);
  selftest.expectEqual(utils.hasScheme("ddp://example"), true);
  selftest.expectEqual(utils.hasScheme("ddp://"), true);
  selftest.expectEqual(utils.hasScheme("example.comhttp://"), true);
  selftest.expectEqual(utils.hasScheme("example+com+http://"), true);
  selftest.expectEqual(utils.hasScheme("example-com+http://"), true);

  selftest.expectEqual(utils.hasScheme("example"), false);
  selftest.expectEqual(utils.hasScheme("example.com"), false);
  selftest.expectEqual(utils.hasScheme("example.com:443"), false);
  selftest.expectEqual(utils.hasScheme("http:/example"), false);
  selftest.expectEqual(utils.hasScheme("http:example"), false);
  selftest.expectEqual(utils.hasScheme("example_com+http://"), false);
});

selftest.define("parse url", function () {
  selftest.expectEqual(utils.parseUrl("http://localhost:3000"), {
    hostname: "localhost",
    port: "3000",
    protocol: "http"
  });
  selftest.expectEqual(utils.parseUrl("https://localhost:3000"), {
    hostname: "localhost",
    port: "3000",
    protocol: "https"
  });
  selftest.expectEqual(utils.parseUrl("localhost:3000"), {
    hostname: "localhost",
    port: "3000",
    protocol: undefined
  });
  selftest.expectEqual(utils.parseUrl("3000"), {
    hostname: undefined,
    port: "3000",
    protocol: undefined
  });
  selftest.expectEqual(utils.parseUrl("3000example.com:3000"), {
    hostname: "3000example.com",
    port: "3000",
    protocol: undefined
  });
  selftest.expectEqual(utils.parseUrl("http://example.com:3000"), {
    hostname: "example.com",
    port: "3000",
    protocol: "http"
  });
  selftest.expectEqual(utils.parseUrl("https://example.com:3000"), {
    hostname: "example.com",
    port: "3000",
    protocol: "https"
  });
  selftest.expectEqual(utils.parseUrl("example.com:3000"), {
    hostname: "example.com",
    port: "3000",
    protocol: undefined
  });
  selftest.expectEqual(utils.parseUrl("127.0.0.1:3000"), {
    hostname: "127.0.0.1",
    port: "3000",
    protocol: undefined
  });
  selftest.expectEqual(utils.parseUrl("[::]:3000"), {
    hostname: "::",
    port: "3000",
    protocol: undefined
  });
  selftest.expectEqual(utils.parseUrl("http://[::]:3000"), {
    hostname: "::",
    port: "3000",
    protocol: "http"
  });
  selftest.expectEqual(utils.parseUrl("https://[::]:3000"), {
    hostname: "::",
    port: "3000",
    protocol: "https"
  });
  selftest.expectEqual(utils.parseUrl("[0000:0000:0000:0000:0000:0000:0000:0001]:3000"), {
    hostname: "0000:0000:0000:0000:0000:0000:0000:0001",
    port: "3000",
    protocol: undefined
  });

  // tests for defaults
  selftest.expectEqual(utils.parseUrl("http://example.com:3000", {
    hostname: "foo.com",
    port: "4000",
    protocol: "https"
  }), {
    hostname: "example.com",
    port: "3000",
    protocol: "http"
  });
  selftest.expectEqual(utils.parseUrl("example.com:3000", {
    port: "4000",
    protocol: "https"
  }), {
    hostname: "example.com",
    port: "3000",
    protocol: "https"
  });
  selftest.expectEqual(utils.parseUrl("3000", {
    port: "4000",
    protocol: "https",
    hostname: "example.com"
  }), {
    hostname: "example.com",
    port: "3000",
    protocol: "https"
  });
});

selftest.define("resume downloads", ['net'], function () {
  // A reasonably big file that (I think) should take more than 1s to download
  // and that we know the size of
  const url = 'https://warehouse.meteor.com/builds/EXSxwGqYjjJKh3WMJ/1467929945102/DRyKg3bYHL/babel-compiler-6.8.4-os+web.browser+web.cordova.tgz';

  let interruptCount = 0;
  let bytesSinceLastInterrupt = 0;

  const resumedPromise = Promise.resolve().then(
    () => httpHelpers.getUrlWithResuming({
      url: url,
      encoding: null,
      retryDelaySecs: 1,
      onRequest(request) {
        request.on("data", chunk => {
          bytesSinceLastInterrupt += chunk.length
          if (bytesSinceLastInterrupt > 500000) {
            bytesSinceLastInterrupt = 0;
            ++interruptCount;
            request.emit('error', 'pretend-http-error');
            request.emit('end');
            request.abort();
          }
        });
      }
    })
  );

  const normalPromise = Promise.resolve().then(
    () => httpHelpers.getUrl({
      url,
      encoding: null,
    })
  );

  Promise.all([
    resumedPromise,
    normalPromise,
  ]).then(bodies => {
    selftest.expectTrue(interruptCount > 1);

    selftest.expectEqual(
      bodies[0].length,
      bodies[1].length
    );

    selftest.expectEqual(
      sha1(bodies[0]),
      sha1(bodies[1])
    );
  }).await();
});


selftest.define("parse url", function () {

keep keep keep keep add keep keep keep keep

selftest.define("isNpmUrl", function () {


# browser-policy-content
[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/browser-policy-content) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/browser-policy-content)
***

This is one of a family of packages that can be used to easily
configure an app's browser-side security policies. The documentation
is in the
[browser-policy](https://atmospherejs.com/meteor/browser-policy)
package.


# accounts-ui-unstyled
[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/accounts-ui-unstyled) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/accounts-ui-unstyled)
***

A version of `accounts-ui` without the CSS, so that you can add your
own styling. See the [`accounts-ui`
README](https://atmospherejs.com/meteor/accounts-ui) and the
Meteor Accounts [project page](https://www.meteor.com/accounts) for
details.


var Fiber = require("fibers");
var _ = require("underscore");

var config = require('./config.js');
var files = require('../fs/files.js');
var auth = require('./auth.js');
var ServiceConnection = require('./service-connection.js');
var httpHelpers = require('../utils/http-helpers.js');
var Console = require('../console/console.js').Console;

// The name of the package that you add to your app to opt out of
// sending stats.
var OPT_OUT_PACKAGE_NAME = "package-stats-opt-out";

// Return a list of packages used by this app, both directly and
// indirectly. Formatted as a list of objects with 'name', 'version'
// and 'direct', which is how the `recordAppPackages` method on the
// stats server expects to get this list.
var packageList = function (projectContext) {
  var versions = [];
  projectContext.packageMap.eachPackage(function (name, info) {
    versions.push({
      name: name,
      version: info.version,
      local: info.kind === 'local',
      direct: !! projectContext.projectConstraintsFile.getConstraint(name)
    });
  });
  return versions;
};

// Options:
// - what: one of "sdk.bundle", "sdk.deploy", "sdk.run".
// - projectContext: the ProjectContext. prepareProjectForBuild
//   must have run successfully. We must extract all necessary data
//   from this before yielding.
// - site: If it's a deploy, the name of the site ("foo.meteor.com") that we're
//   deploying to.
var recordPackages = function (options) {
  // Before doing anything, look at the app's dependencies to see if the
  // opt-out package is there; if present, we don't record any stats.
  var packages = packageList(options.projectContext);
  if (_.findWhere(packages, { name: OPT_OUT_PACKAGE_NAME })) {
    // Print some output for the 'report-stats' self-test.
    if (process.env.METEOR_PACKAGE_STATS_TEST_OUTPUT) {
      process.stdout.write("PACKAGE STATS NOT SENT\n");
    }
    return;
  }

  var appIdentifier = options.projectContext.appIdentifier;

  // We do this inside a new fiber to avoid blocking anything on talking
  // to the package stats server. If we can't connect, for example, we
  // don't care; we'll just miss out on recording these packages.
  // This also gives it its own buildmessage state.
  // However, we do make sure to have already extracted the package list from
  // projectContext, since it might mutate out from under us otherwise.
  Fiber(function () {

    var details = {
      what: options.what,
      userAgent: httpHelpers.getUserAgent(),
      sessionId: auth.getSessionId(config.getAccountsDomain()),
      site: options.site
    };

    try {
      var conn = connectToPackagesStatsServer();
      var accountsConfiguration = auth.getAccountsConfiguration(conn);

      if (auth.isLoggedIn()) {
        try {
          auth.loginWithTokenOrOAuth(
            conn,
            accountsConfiguration,
            config.getPackageStatsServerUrl(),
            config.getPackageStatsServerDomain(),
            "package-stats-server"
          );
        } catch (err) {
          // Do nothing. If we can't log in, we should continue and report
          // stats anonymously.
          //
          // We log other errors with `logErrorIfInCheckout`, but login
          // errors can happen in normal operation when nothing is wrong
          // (e.g. login token expired or revoked) so we don't log them.
        }
      }

      var result = conn.call("recordAppPackages",
                             appIdentifier,
                             packages,
                             details);

      // If the stats server sent us a new session, save it for use on
      // subsequent requests.
      if (result && result.newSessionId) {
        auth.setSessionId(config.getAccountsDomain(), result.newSessionId);
      }

      if (process.env.METEOR_PACKAGE_STATS_TEST_OUTPUT) {
        // Print some output for the 'report-stats' self-test.
        process.stdout.write("PACKAGE STATS SENT\n");
      }
    } catch (err) {
      logErrorIfInCheckout(err);
      // Do nothing. A failure to record package stats shouldn't be
      // visible to the end user and shouldn't affect whatever command
      // they are running.
    } finally {
      conn && conn.close();
    }
  }).run();
};

var logErrorIfInCheckout = function (err) {
  if (files.inCheckout() || process.env.METEOR_PACKAGE_STATS_TEST_OUTPUT) {
    Console.warn("Failed to record package usage.");
    Console.warn(
      "(This error is hidden when you are not running Meteor from a",
      "checkout.)");
    var printErr = err.stack || err;
    Console.rawWarn(printErr + "\n");
    Console.warn();
    Console.warn();
  }
};

// Used in a test (and can only be used against the testing packages
// server) to fetch one package stats entry for a given application.
var getPackagesForAppIdInTest = function (projectContext) {
  var conn = connectToPackagesStatsServer();
  var result;
  try {
    result = conn.call(
      "getPackagesForAppId",
      projectContext.appIdentifier);
    if (result && result.details) {
      result.details.packages = _.sortBy(result.details.packages, "name");
    }
  } finally {
    conn.close();
  }

  return result;
};

var connectToPackagesStatsServer = function () {
  return new ServiceConnection(
    config.getPackageStatsServerUrl(),
    {_dontPrintErrors: true}
  );
};

exports.recordPackages = recordPackages;
exports.packageList = packageList; // for use in the "stats" self-test.
exports.getPackagesForAppIdInTest = getPackagesForAppIdInTest;


// These are the various protocols that NPM supports, which we use to download NPM dependencies

return exports.isUrlWithSha(x) || /^(git|git\+ssh|git\+http|git\+https)?:\/\//.test(x);

keep keep keep keep replace keep keep keep keep

import { ensureOnlyValidVersions } from "../utils/utils.js";
import buildmessage from "../utils/buildmessage.js";
import NpmDiscards from "./npm-discards.js";

const nodeRequire = require;

export class PackageNpm {
  /**
   * @summary Class of the 'Npm' object visible in package.js
   * @locus package.js
   * @instanceName Npm
   * @showInstanceName true
   */
  constructor() {
    // Files to be stripped from the installed NPM dependency tree. See
    // the Npm.strip comment below for further usage information.
    this._discards = new NpmDiscards;
    this._dependencies = null;
  }

  /**
   * @summary Specify which [NPM](https://www.npmjs.org/) packages
   * your Meteor package depends on.
   * @param  {Object} dependencies An object where the keys are package
   * names and the values are one of:
   *   1. Version numbers in string form
   *   2. Http(s) URLs to a git commit by SHA.
   *   3. Git URLs in the format described [here](https://docs.npmjs.com/files/package.json#git-urls-as-dependencies)
   *
   * Https URL example:
   *
   * ```js
   * Npm.depends({
   *   moment: "2.8.3",
   *   async: "https://github.com/caolan/async/archive/71fa2638973dafd8761fa5457c472a312cc820fe.tar.gz"
   * });
   * ```
   *
   * Git URL example:
   *
   * ```js
   * Npm.depends({
   *   moment: "2.8.3",
   *   async: "git+https://github.com/caolan/async#master"
   * });
   * ```
   * @locus package.js
   */
  depends(dependencies) {
    // XXX make dependencies be separate between use and test, so that
    // production doesn't have to ship all of the npm modules used by test
    // code
    if (this._dependencies) {
      buildmessage.error("Npm.depends may only be called once per package",
                         { useMyCaller: true });
      // recover by ignoring the Npm.depends line
      return;
    }

    if (typeof dependencies !== 'object') {
      buildmessage.error("the argument to Npm.depends should be an " +
                         "object, like this: {gcd: '0.0.0'}",
                         { useMyCaller: true });
      // recover by ignoring the Npm.depends line
      return;
    }

    // don't allow npm fuzzy versions so that there is complete
    // consistency when deploying a meteor app
    //
    // XXX use something like seal or lockdown to have *complete*
    // confidence we're running the same code?
    try {
      ensureOnlyValidVersions(dependencies, {
        forCordova: false
      });

    } catch (e) {
      buildmessage.error(e.message, {
        useMyCaller: true,
        downcase: true
      });

      // recover by ignoring the Npm.depends line
      return;
    }

    this._dependencies = dependencies;
  }

  // The `Npm.strip` method makes up for packages that have missing
  // or incomplete .npmignore files by telling the bundler to strip out
  // certain unnecessary files and/or directories during `meteor build`.
  //
  // The `discards` parameter should be an object whose keys are
  // top-level package names and whose values are arrays of strings
  // (or regular expressions) that match paths in that package's
  // directory that should be stripped before installation. For
  // example:
  //
  //   Npm.strip({
  //     connect: [/*\.wmv$/],
  //     useragent: ["tests/"]
  //   });
  //
  // This means (1) "remove any files with the `.wmv` extension from
  // the 'connect' package directory" and (2) "remove the 'tests'
  // directory from the 'useragent' package directory."
  strip(discards) {
    this._discards.merge(discards);
  }

  require(name) {
    try {
      return nodeRequire(name); // from the dev bundle
    } catch (e) {
      buildmessage.error(
        "can't find npm module '" + name +
          "'. In package.js, Npm.require can only find built-in modules.",
        { useMyCaller: true });
      // recover by, uh, returning undefined, which is likely to
      // have some knock-on effects
    }
  }
}


Package.describe({
  summary: "Dictionary data structure allowing non-string keys",
  version: '1.1.0'
});

Package.onUse(function (api) {
  api.use('ecmascript');
  api.use('ejson');
  api.mainModule('id-map.js');
  api.export('IdMap');
});


# jquery
[Source code of released version](https://github.com/meteor/meteor/tree/master/packages/jquery) | [Source code of development version](https://github.com/meteor/meteor/tree/devel/packages/jquery)
***

[jQuery](http://jquery.com/) is a fast and concise JavaScript
Library that simplifies HTML document traversing, event handling,
animating, and Ajax interactions for rapid web development.

The `jquery` package adds the jQuery library to the client JavaScript
bundle. It has no effect on the server.

This package is automatically included in every new Meteor app by `meteor create`.

In addition to the `jquery` package, Meteor provides several jQuery
plugins as separate packages. These include:

* [`jquery-waypoints`](http://imakewebthings.com/jquery-waypoints/)


BUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins

# OS Check. Put here because here is where we download the precompiled

if [ "$UNAME" != "Linux" -a "$UNAME" != "Darwin" ] ; then

keep keep replace keep keep keep keep keep

// This file exists because it is the file in the tool that is not automatically
// transpiled by Babel

require('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js

// Install a global ES6-compliant Promise constructor that knows how to
// run all its callbacks in Fibers.
global.Promise = require("meteor-promise");

// Include helpers from NPM so that the compiler doesn't need to add boilerplate
// at the top of every file
require("meteor-babel").installRuntime();

// Installs source map support with a hook to add functions to look for source
// maps in custom places
require('./source-map-retriever-stack.js');

// Run the Meteor command line tool
require('./main.js');


/* CSS declarations go here */

* { margin: 0; padding: 0 }

#grid td {
  width: 20px;
  height: 20px;
  vertical-align: middle;
  text-align: center;
}

.color0 { background: #eee; }
.color1 { background: #d8f; }
.color2 { background: #8c3; }
.color3 { background: #39d; }
.color4 { background: #d96; }
.color5 { background: #a95; }


var _ = require('underscore');
var packageClient = require('./package-client.js');
var watch = require('./watch.js');
var archinfo = require('./archinfo.js');
var isopack = require('./isopack.js');
var buildmessage = require('./buildmessage.js');
var tropohouse = require('./tropohouse.js');
var files = require('./files.js');
var utils = require('./utils.js');
var catalog = require('./catalog.js');
var PackageSource = require('./package-source.js');
var VersionParser = require('./package-version-parser.js');

// LocalCatalog represents packages located in the application's
// package directory, other package directories specified via an
// environment variable, and core packages in the repo if meteor is
// being run from a git checkout.
var LocalCatalog = function (options) {
  var self = this;
  options = options || {};

  // Package server data.  Maps package name to a {packageSource, packageRecord,
  // versionRecord} object.
  self.packages = {};

  self.initialized = false;

    // Local directories to search for package source trees
  self.localPackageSearchDirs = null;

  // Package source trees added explicitly through a directory (not through a
  // parent search directory). We mainly use this to allow the user to run
  // test-packages against a package in a specific directory.
  self.explicitlyAddedLocalPackageDirs = [];

  // All packages found either by localPackageSearchDirs or
  // explicitlyAddedLocalPackageDirs. There is a hierarchy of packages, as
  // detailed below and there can only be one local version of a package at a
  // time. This refers to the package by the specific package directory that we
  // need to process.
  self.effectiveLocalPackageDirs = [];

  // A WatchSet that detects when the set of packages and their locations
  // changes. ie, the listings of 'packages' directories, and the contents of
  // package.js files underneath.  It does NOT track the rest of the source of
  // the packages: that wouldn't be helpful to the runner since it would be too
  // coarse to tell if a change is client-only or not.  (But any change to the
  // layout of where packages live counts as a non-client-only change.)
  self.packageLocationWatchSet = new watch.WatchSet;

  self._nextId = 1;
};

_.extend(LocalCatalog.prototype, {
  toString: function () {
    var self = this;
    return "LocalCatalog [localPackageSearchDirs="
      + self.localPackageSearchDirs + "]";
  },

  // Initialize the Catalog. This must be called before any other
  // Catalog function.

  // options:
  //  - localPackageSearchDirs: an array of paths on local disk, that contain
  //    subdirectories, that each contain a source tree for a package that
  //    should override the packages on the package server. For example, if
  //    there is a package 'foo' that we find through localPackageSearchDirs,
  //    then we will ignore all versions of 'foo' that we find through the
  //    package server. Directories that don't exist (or paths that aren't
  //    directories) will be silently ignored.
  //  - explicitlyAddedLocalPackageDirs: an array of paths which THEMSELVES
  //    are package source trees.  Takes precedence over packages found
  //    via localPackageSearchDirs.
  //  - buildingIsopackets: true if we are building isopackets
  initialize: function (options) {
    var self = this;
    buildmessage.assertInCapture();

    options = options || {};

    self.localPackageSearchDirs = _.map(
      options.localPackageSearchDirs, function (p) {
        return files.pathResolve(p);
      });
    self.explicitlyAddedLocalPackageDirs = _.map(
      options.explicitlyAddedLocalPackageDirs, function (p) {
        return files.pathResolve(p);
      });

    self._computeEffectiveLocalPackages();
    self._loadLocalPackages(options.buildingIsopackets);
    self.initialized = true;
  },

  // Throw if the catalog's self.initialized value has not been set to true.
  _requireInitialized: function () {
    var self = this;

    if (! self.initialized)
      throw new Error("catalog not initialized yet?");
  },

  // Return an array with the names of all of the packages that we know about,
  // in no particular order.
  getAllPackageNames: function (options) {
    var self = this;
    self._requireInitialized();

    return _.keys(self.packages);
  },

  // Return an array with the names of all of the non-test packages that we know
  // about, in no particular order.
  getAllNonTestPackageNames: function (options) {
    var self = this;
    self._requireInitialized();

    var ret = [];
    _.each(self.packages, function (record, name) {
      record.versionRecord.isTest || ret.push(name);
    });
    return ret;
  },

  // Returns general (non-version-specific) information about a
  // package, or null if there is no such package.
  getPackage: function (name, options) {
    var self = this;
    self._requireInitialized();
    options = options || {};

    if (!_.has(self.packages, name))
      return null;
    return self.packages[name].packageRecord;
  },

  // Given a package, returns an array of the versions available (ie, the one
  // version we have, or an empty array).
  getSortedVersions: function (name) {
    var self = this;
    self._requireInitialized();

    if (!_.has(self.packages, name))
      return [];
    return [self.packages[name].versionRecord.version];
  },

  // Given a package, returns an array of the version records available (ie, the
  // one version we have, or an empty array).
  getSortedVersionRecords: function (name) {
    var self = this;
    self._requireInitialized();

    if (!_.has(self.packages, name))
      return [];
    return [self.packages[name].versionRecord];
  },

  // Return information about a particular version of a package, or
  // null if there is no such package or version.
  getVersion: function (name, version) {
    var self = this;
    self._requireInitialized();

    if (!_.has(self.packages, name))
      return null;
    var versionRecord = self.packages[name].versionRecord;
    if (versionRecord.version !== version)
      return null;
    return versionRecord;
  },

  // As getVersion, but returns info on the latest version of the
  // package, or null if the package doesn't exist or has no versions.
  getLatestVersion: function (name) {
    var self = this;

    if (!_.has(self.packages, name))
      return null;
    return self.packages[name].versionRecord;
  },

  getVersionBySourceRoot: function (sourceRoot) {
    var self = this;
    var packageObj = _.find(self.packages, function (p) {
      return p.packageSource.sourceRoot === sourceRoot;
    });
    if (! packageObj)
      return null;
    return packageObj.versionRecord;
  },

  // Compute self.effectiveLocalPackageDirs from self.localPackageSearchDirs and
  // self.explicitlyAddedLocalPackageDirs.
  _computeEffectiveLocalPackages: function () {
    var self = this;
    buildmessage.assertInCapture();

    self.effectiveLocalPackageDirs = [];

    buildmessage.enterJob("looking for packages", function () {
      _.each(self.explicitlyAddedLocalPackageDirs, function (explicitDir) {
        var packageJs = watch.readAndWatchFile(
          self.packageLocationWatchSet,
          files.pathJoin(explicitDir, 'package.js'));
        // We asked specifically for this directory, but it has no package!
        if (packageJs === null) {
          buildmessage.error("package has no package.js file", {
            file: explicitDir
          });
          return;  // recover by ignoring
        }
        self.effectiveLocalPackageDirs.push(explicitDir);
      });

      _.each(self.localPackageSearchDirs, function (searchDir) {
        var possiblePackageDirs = watch.readAndWatchDirectory(
          self.packageLocationWatchSet, {
            absPath: searchDir,
            include: [/\/$/]
          });
        // Not a directory? Ignore.
        if (possiblePackageDirs === null)
          return;

        _.each(possiblePackageDirs, function (subdir) {
          // readAndWatchDirectory adds a slash to the end of directory names to
          // differentiate them from filenames. Remove it.
          subdir = subdir.substr(0, subdir.length - 1);
          var absPackageDir = files.pathJoin(searchDir, subdir);

          // Consider a directory to be a package source tree if it contains
          // 'package.js'. (We used to support isopacks in
          // localPackageSearchDirs, but no longer.)
          var packageJs = watch.readAndWatchFile(
            self.packageLocationWatchSet,
            files.pathJoin(absPackageDir, 'package.js'));
          if (packageJs !== null) {
            // Let earlier package directories override later package
            // directories.

            // We don't know the name of the package, so we can't deal with
            // duplicates yet. We are going to have to rely on the fact that we
            // are putting these in in order, to be processed in order.
            self.effectiveLocalPackageDirs.push(absPackageDir);
          }
        });
      });
    });
  },

  _loadLocalPackages: function (buildingIsopackets) {
    var self = this;
    buildmessage.assertInCapture();

    // Load the package source from a directory. We don't know the names of our
    // local packages until we do this.
    //
    // THIS MUST BE RUN IN LOAD ORDER. Let's say that we have two directories
    // for mongo-livedata. The first one processed by this function will be
    // canonical.  The second one will be ignored.
    //
    // (note: this is the behavior that we want for overriding things in
    //  checkout.  It is not clear that you get good UX if you have two packages
    //  with the same name in your app. We don't check that.)
    var initSourceFromDir = function (packageDir, definiteName) {
      var packageSource = new PackageSource;
      buildmessage.enterJob({
        title: "reading package from `" + packageDir + "`",
        rootPath: packageDir
      }, function () {
        var initFromPackageDirOptions = {
          buildingIsopackets: !! buildingIsopackets
        };
        // If we specified a name, then we know what we want to get and should
        // pass that into the options. Otherwise, we will use the 'name'
        // attribute from package-source.js.
        if (definiteName) {
          initFromPackageDirOptions.name = definiteName;
        }
        packageSource.initFromPackageDir(packageDir, initFromPackageDirOptions);
        if (buildmessage.jobHasMessages())
          return;  // recover by ignoring

        // Now that we have initialized the package from package.js, we know its
        // name.
        var name = packageSource.name;

        // We should only have one package dir for each name; in this case, we
        // are going to take the first one we get (since we preserved the order
        // in which we loaded local package dirs when running this function.)
        if (_.has(self.packages, name))
          return;

        self.packages[name] = {
          packageSource: packageSource,
          packageRecord: {
            _id: "PID" + self._nextId++,
            name: name,
            maintainers: null,
            lastUpdated: null
          },
          versionRecord: {
            _id: "VID" + self._nextId++,
            packageName: name,
            testName: packageSource.testName,
            version: packageSource.version,
            publishedBy: null,
            description: packageSource.metadata.summary,
            git: packageSource.metadata.git,
            dependencies: packageSource.getDependencyMetadata(),
            source: null,
            lastUpdated: null,
            published: null,
            isTest: packageSource.isTest,
            debugOnly: packageSource.debugOnly,
            containsPlugins: packageSource.containsPlugins()
          }
        };

        // If this is NOT a test package AND it has tests (tests will be
        // marked as test packages by package source, so we will not recurse
        // infinitely), then process that too.
        if (!packageSource.isTest && packageSource.testName) {
          initSourceFromDir(packageSource.sourceRoot, packageSource.testName);
        }
      });
    };

    // Load the package sources for packages and their tests into
    // self.packages.
    //
    // XXX We should make this work with parallel: true; right now it seems to
    // hit node problems.
    buildmessage.forkJoin(
      { 'title': 'initializing packages', parallel: false },
      self.effectiveLocalPackageDirs,
      function (dir) {
        initSourceFromDir(dir);
      });
  },

  getPackageSource: function (name) {
    var self = this;
    if (! _.has(self.packages, name))
      return null;
    return self.packages[name].packageSource;
  }
});

exports.LocalCatalog = LocalCatalog;


// Not yet upgrading Underscore from 1.5.2 to 1.7.0 (which should be done

// in the package too) because we should consider using lodash instead

// (and there are backwards-incompatible changes either way).

keep keep keep replace keep keep keep keep

#!/bin/bash

BUNDLE_VERSION=0.4.34 # Achtung! Versions through 0.4.38 are used on branch batch-plugins

# OS Check. Put here because here is where we download the precompiled
# bundles that are arch specific.
UNAME=$(uname)
if [ "$UNAME" != "Linux" -a "$UNAME" != "Darwin" ] ; then
    echo "Sorry, this OS is not supported."
    exit 1
fi

if [ "$UNAME" = "Darwin" ] ; then
    if [ "i386" != "$(uname -p)" -o "1" != "$(sysctl -n hw.cpu64bit_capable 2>/dev/null || echo 0)" ] ; then

        # Can't just test uname -m = x86_64, because Snow Leopard can
        # return other values.
        echo "Only 64-bit Intel processors are supported at this time."
        exit 1
    fi
    ARCH="x86_64"
elif [ "$UNAME" = "Linux" ] ; then
    ARCH="$(uname -m)"
    if [ "$ARCH" != "i686" -a "$ARCH" != "x86_64" ] ; then
        echo "Unsupported architecture: $ARCH"
        echo "Meteor only supports i686 and x86_64 for now."
        exit 1
    fi
fi
PLATFORM="${UNAME}_${ARCH}"

# Find the script dir, following symlinks. Note that symlink can be relative or
# absolute. Too bad 'readlink -f' and 'realpath' (the command-line program) are
# not portable.  We don't stress about infinite loops or bad links, because the
# OS has already resolved this symlink chain once in order to actually run the
# shell script.
ORIG_DIR="$(pwd)"
SCRIPT="$0"
while true; do
  # The symlink might be relative, so we have to actually cd to the right place
  # each time in order to resolve it.
  cd "$(dirname "$SCRIPT")"
  if [ ! -L "$(basename "$SCRIPT")" ]; then
    SCRIPT_DIR="$(pwd -P)"
    break
  fi
  SCRIPT="$(readlink "$(basename "$SCRIPT")")"
done
cd "$ORIG_DIR"

function install_dev_bundle {
    set -e
    trap "echo Failed to install dependency kit." EXIT

    TARBALL="dev_bundle_${PLATFORM}_${BUNDLE_VERSION}.tar.gz"
    BUNDLE_TMPDIR="$SCRIPT_DIR/dev_bundle.xxx"

    rm -rf "$BUNDLE_TMPDIR"
    mkdir "$BUNDLE_TMPDIR"

    # duplicated in scripts/windows/download-dev-bundle.ps1:
    DEV_BUNDLE_URL_ROOT="https://d3sqy0vbqsdhku.cloudfront.net/"
    # If you set $USE_TEST_DEV_BUNDLE_SERVER then we will download
    # dev bundles copied by copy-dev-bundle-from-jenkins.sh without --prod.
    # It still only does this if the version number has changed
    # (setting it won't cause it to automatically delete a prod dev bundle).
    if [ -n "$USE_TEST_DEV_BUNDLE_SERVER" ] ; then
        DEV_BUNDLE_URL_ROOT="https://s3.amazonaws.com/com.meteor.static/test/"
    fi

    if [ -f "$SCRIPT_DIR/$TARBALL" ] ; then
        echo "Skipping download and installing kit from $SCRIPT_DIR/$TARBALL" >&2
        tar -xzf "$SCRIPT_DIR/$TARBALL" -C "$BUNDLE_TMPDIR"
    elif [ -n "$SAVE_DEV_BUNDLE_TARBALL" ] ; then
        # URL duplicated in tools/server/target.sh.in
        curl -# "$DEV_BUNDLE_URL_ROOT$TARBALL" >"$SCRIPT_DIR/$TARBALL"
        tar -xzf "$SCRIPT_DIR/$TARBALL" -C "$BUNDLE_TMPDIR"
    else
        curl -# "$DEV_BUNDLE_URL_ROOT$TARBALL" | tar -xzf - -C "$BUNDLE_TMPDIR"
    fi

    test -x "${BUNDLE_TMPDIR}/bin/node" # bomb out if it didn't work, eg no net

    # Delete old dev bundle and rename the new one on top of it.
    rm -rf "$SCRIPT_DIR/dev_bundle"
    mv "$BUNDLE_TMPDIR" "$SCRIPT_DIR/dev_bundle"

    echo "Installed dependency kit v${BUNDLE_VERSION} in dev_bundle." >&2
    echo >&2

    trap - EXIT
    set +e
}

if [ -d "$SCRIPT_DIR/.git" ] || [ -f "$SCRIPT_DIR/.git" ]; then
    # In a checkout.
    if [ ! -d "$SCRIPT_DIR/dev_bundle" ] ; then
        echo "It's the first time you've run Meteor from a git checkout." >&2
        echo "I will download a kit containing all of Meteor's dependencies." >&2
        install_dev_bundle
    elif [ ! -f "$SCRIPT_DIR/dev_bundle/.bundle_version.txt" ] ||
        grep -qvx "$BUNDLE_VERSION" "$SCRIPT_DIR/dev_bundle/.bundle_version.txt" ; then
        echo "Your dependency kit is out of date. I will download the new one." >&2
        install_dev_bundle
    fi

    export BABEL_CACHE_DIR="$SCRIPT_DIR/.babel-cache"
fi

DEV_BUNDLE="$SCRIPT_DIR/dev_bundle"
METEOR="$SCRIPT_DIR/tools/main-transpile-wrapper.js"

# Bump our file descriptor ulimit as high as it will go. This is a
# temporary workaround for dependancy watching holding open too many
# files: https://app.asana.com/0/364581412985/472479912325
if [ "$(ulimit -n)" != "unlimited" ] ; then
    ulimit -n 16384 > /dev/null 2>&1 || \
    ulimit -n 8192 > /dev/null 2>&1 || \
    ulimit -n 4096 > /dev/null 2>&1 || \
    ulimit -n 2048 > /dev/null 2>&1 || \
    ulimit -n 1024 > /dev/null 2>&1 || \
    ulimit -n 512 > /dev/null 2>&1
fi

# We used to set $NODE_PATH here to include the node_modules from the dev
# bundle, but now we just get them from the symlink at tools/node_modules. This
# is better because node_modules directories found via the ancestor walk from
# the script take precedence over $NODE_PATH; it used to be that users would
# screw up their meteor installs by have a ~/node_modules

exec "$DEV_BUNDLE/bin/node" "$METEOR" "$@"


// Like _.isArray, but doesn't regard polyfilled Uint8Arrays on old browsers as
// arrays.
// XXX maybe this should be EJSON.isArray
isArray = function (x) {
  return _.isArray(x) && !EJSON.isBinary(x);
};

// XXX maybe this should be EJSON.isObject, though EJSON doesn't know about
// RegExp
// XXX note that _type(undefined) === 3!!!!
isPlainObject = LocalCollection._isPlainObject = function (x) {
  return x && LocalCollection._f._type(x) === 3;
};

isIndexable = function (x) {
  return isArray(x) || isPlainObject(x);
};

// Returns true if this is an object with at least one key and all keys begin
// with $.  Unless inconsistentOK is set, throws if some keys begin with $ and
// others don't.
isOperatorObject = function (valueSelector, inconsistentOK) {
  if (!isPlainObject(valueSelector))
    return false;

  var theseAreOperators = undefined;
  _.each(valueSelector, function (value, selKey) {
    var thisIsOperator = selKey.substr(0, 1) === '$';
    if (theseAreOperators === undefined) {
      theseAreOperators = thisIsOperator;
    } else if (theseAreOperators !== thisIsOperator) {
      if (!inconsistentOK)
        throw new Error("Inconsistent operator: " +
                        JSON.stringify(valueSelector));
      theseAreOperators = false;
    }
  });
  return !!theseAreOperators;  // {} has no operators
};

// string can be converted to integer
isNumericKey = function (s) {
  return /^[0-9]+$/.test(s);
};


.overlay.share {
  .wrapper-camera {
    .position(absolute, auto, 0, 0, 0, 100%);
    text-align: center;

    .btn-camera {
      margin-bottom: .5rem;
    }
    .subtext-camera {
      .font-s2;
      color: @color-medium;
      margin-bottom: .75rem;
    }
  }

  .bg-image {
    //.position(absolute, 3rem, 0, 0, 0, 100%, 50%);
    position: relative;
    margin-top: 3rem;
    height: 50%;
  }

  .form-share {
    .background-image(linear-gradient(top, rgba(255,255,255,.9), rgba(255,255,255,1) 10%, @color-empty 100%));
    .position(absolute, auto, 0, 0, 0, 100%);
    .transform(translate3d(0,0,0));// Gpu rendering
    min-height: 50%;
    padding-bottom: 3rem;

    .form-group {
      .display(flex);
      .flex-wrap(wrap);

      margin-bottom: 3rem;

      .avatar,
      .message-share {
        .flex(1);
      }
      .message-share {
        width: 100%;
      }

      .avatar {
        height: 2.5rem;
        width: 2.5rem;
        max-width: 2.5rem;
        float: left;
        margin-left: 1rem;
        margin-top: 1rem;
      }

      .message-share {
        height: 12em;
        resize: none;
      }
    }

    .wrapper-checkbox {
      .position(absolute, auto, auto, 3rem, auto, 100%, 3rem);
      border-top: 1px solid @color-rare;
      border-bottom: 1px solid @color-rare;

      .checkbox { padding: 1rem; }
    }
  }

  .btn-primary { .position(absolute, auto, 0, 0, 0, 100%); }
}


#!/bin/bash

# Get the path to this script in SCRIPT_DIR, preserving cwd
ORIG_DIR=$(pwd)
cd "$(dirname "$0")"
SCRIPT_DIR=$(pwd -P)
cd "$ORIG_DIR"

# Find the top of the tools tree (not to be confused with the 'tools'
# directory in that tree)
TOOLS_DIR="$SCRIPT_DIR/../../.."

# Find our binary dependencies (node).
DEV_BUNDLE="$TOOLS_DIR/dev_bundle"

# Have at it!
export NODE_PATH="$DEV_BUNDLE/lib/node_modules"
exec "$DEV_BUNDLE/bin/node" "$SCRIPT_DIR/fake-mongod.js" "$@"


keep keep keep replace replace keep keep keep keep

"meteor-babel": "0.3.2",
"meteor-promise": "0.2.4",


var CurrentFoo = new Meteor.EnvironmentVariable;

Tinytest.add("environment - dynamic variables", function (test) {
  test.equal(CurrentFoo.get(), undefined);

  CurrentFoo.withValue(17, function () {
    test.equal(CurrentFoo.get(), 17);

    CurrentFoo.withValue(22, function () {
      test.equal(CurrentFoo.get(), 22);
    });

    test.equal(CurrentFoo.get(), 17);
  });

  test.equal(CurrentFoo.get(), undefined);
});

Tinytest.add("environment - bindEnvironment", function (test) {
  var raised_f;

  var f = CurrentFoo.withValue(17, function () {
    return Meteor.bindEnvironment(function (flag) {
      test.equal(CurrentFoo.get(), 17);
      if (flag)
        throw "test";
      return 12;
    }, function (e) {
      test.equal(CurrentFoo.get(), 17);
      raised_f = e;
    });
  });

  var test_f = function () {
    raised_f = null;

    test.equal(f(false), 12);
    test.equal(raised_f, null);

    test.equal(f(true), undefined);
    test.equal(raised_f, "test");
  };

  // At top level

  test.equal(CurrentFoo.get(), undefined);
  test_f();

  // Inside a withValue

  CurrentFoo.withValue(22, function () {
    test.equal(CurrentFoo.get(), 22);
    test_f();
    test.equal(CurrentFoo.get(), 22);
  });

  test.equal(CurrentFoo.get(), undefined);

  // Multiple environment-bound functions on the stack (in the nodejs
  // implementation, this needs to avoid creating additional fibers)

  var raised_g;

  var g = CurrentFoo.withValue(99, function () {
    return Meteor.bindEnvironment(function (flag) {
      test.equal(CurrentFoo.get(), 99);

      if (flag)
        throw "trial";

      test_f();
      return 88;
    }, function (e) {
      test.equal(CurrentFoo.get(), 99);
      raised_g = e;
    });
  });

  var test_g = function () {
    raised_g = null;

    test.equal(g(false), 88);
    test.equal(raised_g, null);

    test.equal(g(true), undefined);
    test.equal(raised_g, "trial");
  };

  test_g();

  CurrentFoo.withValue(77, function () {
    test.equal(CurrentFoo.get(), 77);
    test_g();
    test.equal(CurrentFoo.get(), 77);
  });

  test.equal(CurrentFoo.get(), undefined);
});

Tinytest.addAsync("environment - bare bindEnvironment",
                  function (test, onComplete) {
  // this will have to create a fiber in nodejs
  CurrentFoo.withValue(68, function () {
    var f = Meteor.bindEnvironment(function () {
      test.equal(CurrentFoo.get(), 68);
      onComplete();
    }, function () {});

    setTimeout(f, 0);
  });
});


Package.describe({
  name: "~package-name~", // replaced via `Sandbox.prototype.createPackage`
  summary: 'This is a pre-release version of this package!',
  version: '1.3.0-rc.1',
  git: 'www.github.com/fake-user/meteor',
  documentation: null
});


if (path === "tools/main-transpile-wrapper.js" || path === "tools/source-map-retriever-stack.js") {

inputFileContents = inputFileContents.replace(/.+#RemoveInProd.+/, "");

var transpiled = babel.compile(inputFileContents, _.extend(babel.getDefaultOptions(), {

var babelOptions = babel.getDefaultOptions({

// These feature flags must be kept in sync with the babelOptions

// used in tools/main-transpile-wrapper.js.


/* This file is only loaded on Cordova-bundled apps and is used only in case
 * autoupdate package is used.
 * It checks if File plugin is installed and a newer version of the app code can
 * be found on persistent storage. In that case those files are dynamically
 * added to the page.
 * Otherwise a normal app code is loaded (shipped with the app initially).
 */

(function () {
  var DEBUG_TAG = 'METEOR CORDOVA DEBUG (meteor_cordova_loader.js) ';
  var log = function (msg) {
    console.log(DEBUG_TAG + msg);
  };
  var uriToPath = function (uri) {
    return decodeURI(uri).replace(/^file:\/\//g, '');
  };
  var readFile = function (url, cb) {
    window.resolveLocalFileSystemURL(url, function (fileEntry) {
      var success = function (file) {
        var reader = new FileReader();
        reader.onloadend = function (evt) {
          var result = evt.target.result;
          cb(null, result);
        };
        reader.onerror = fail;
        reader.readAsText(file);
      };
      var fail = function (evt) {
        cb(new Error("Failed to load entry: " + url), null);
      };
      fileEntry.file(success, fail);
    },
    // error callback
    function (err) { cb(new Error("Failed to resolve entry: " + url), null);
    });
  };

  var loadTries = 0;
  var loadFromLocation = function (location) {
    var cordovaRoot =
      uriToPath(window.location.href).replace(/\/index.html$/, '/');

    var httpd = cordova && cordova.plugins && cordova.plugins.CordovaUpdate;

    var retry = function () {
      loadTries++;
      if (loadTries > 10) {
        // XXX: If this means the app fails, we should probably do exponential backoff
        // or at least show a message
        log('Failed to start the server (too many retries)');
      } else {
        log('Starting the server (retry #' + loadTries + ')');
        loadFromLocation(location);
      }
    };

    httpd.startServer({
      'www_root' : location,
      'cordovajs_root': cordovaRoot
    }, function (url) {
      // go to the new proxy url
      log("Loading from url: " + url);
      window.location = url;
    }, function (error) {
      // failed to start a server, is port already in use?
      log("Failed to start the server: " + error);
      retry();
    });
  };

  // Fallback to the bundled assets from the disk. If an error is passed as an
  // argument, then there was a problem reading from the manifest files. If
  // no error is passed, then we simply do not have any new versions.
  var fallback = function (err) {
    if (err) {
      log("Couldn't load from the manifest, falling back to the bundled assets.");
    } else {
      log('No new versions saved to disk.');
    }
    var location = cordova.file.applicationDirectory + 'www/application/';
    location = uriToPath(location);

    loadFromLocation(location);
  };

  var loadVersion = function (version, localPathPrefix) {
    var versionPrefix = localPathPrefix + version + '/';
    var location = uriToPath(versionPrefix);
    loadFromLocation(location);
  };

  var loadApp = function (localPathPrefix) {
    readFile(localPathPrefix + 'version', function (err, version) {
      if (err) {
        log("Error reading version file " + err);
        fallback(err);
        return;
      }

      loadVersion(version, localPathPrefix);
    });
  };

  document.addEventListener("deviceready", function () {
    var startLoading = function () {
      if (! cordova.file) {
        // If the plugin didn't actually load, try again later.
        // See a larger comment with details in
        // packages/meteor/startup_client.js
        setTimeout(startLoading, 20);
        return;
      }

      var localPathPrefix = cordova.file.dataDirectory + 'meteor/';
      loadApp(localPathPrefix);
    };

    startLoading();
  }, false);
})();


body {
    margin: 0px;
    background-color: #f4f4f4;
    font-family: Helvetica, Arial, sans-serif;
}

/* base styles */

input {
    height: 50px;
    width: 300px;
    font-size: 2em;
    border: 2px solid black;
    padding: 5px;
}

button {
    position: relative;
    bottom: 3px;
    margin: 10px;
    height: 50px;
    background-color:#E6EFC2;
    border:1px solid #dedede;
    font-weight:bold;
    cursor:pointer;
    font-size: 1.5em;
}

button:hover {
    background-color:#D6DFb2;
    border:1px solid #C6D880;
}

button:active {
    background-color:#529214;
    border:1px solid #529214;
    color:#fff;
}

/*******/

#main {
    margin: 20px;
}

#left {
    float: left;
    width: 40%;
}

#right {
    float: left;
    width: 50%;
}

#clock {
    width: 100%;
    height: 100px;
    text-align: center;
    font-size: 3em;
}

#board {
    margin: auto;
    border:4px solid #999999;
    border-radius: 4px;
    -moz-border-radius: 4px;
    padding:2px;

    width:400px;
    height:400px;
    background-color:#999999;
}

.square {
    cursor: pointer;
    width:84px;
    height:84px;
    border:4px solid #eeeee8;
    border-radius: 4px;
    -moz-border-radius: 4px;
    margin: 4px;
    float:left;
    text-align: center;
    background-color:#eeeee8;
    font-size: 65px;
}

.square.last_in_path {
    color: #ff0000;
}

.square.in_path {
    color: #990000;
}

#login {
    margin: 100px auto;
    text-align: center;
}

#login .error {
    color: red;
}

#lobby {
    margin: 100px auto;
    text-align: center;
}

#postgame {
    height: 100px;
    text-align: center;
}

#scratchpad {
    height: 100px;
}

#scratchpad input {
    width: 70%;
}

#scratchpad h1 {
    float: left;
}

#scores {
    float: left;
    width: 100%;
    background-color: #eeeee8;
    border: 1px solid black;
    padding: 0.5em;
}

#scores .player {
    float: left;
    width: 100%;
}

#scores .header {
    font-size: 1.25em;
}

#scores .unnamed {
    color: #444;
    font-style: italic;
}

#scores .winner {
    background-color: yellow;
}

#scores .winner_text {
    float: right;
}

#scores .word {
    float: left;
    font-size: 1.25em;
    padding: 0.25em;
    margin: 0.5em;
    border: 1px solid #030;
}

#scores .word.good {
    background-color: #0a0;
}

#scores .word.bad {
    text-decoration: line-through;
}

#scores .word span.score {
    width: 1em;
}

#scores .word.bad span.score {
    background-image: 'circle-ball-dark-antialiased.gif';
}


var sourceMapUrlComment = "//# sourceMappingURL=" + files.pathBasename(path + ".map");

keep keep keep replace replace keep keep keep

var transpiled = babel.compile(inputFileContents, babelOptions);


// This file exists because it is the file in the tool that is not automatically

require('meteor-babel/register'); // #RemoveInProd this line is removed in isopack.js

// Install a global ES6-compliant Promise constructor that knows how to

keep keep keep replace keep keep keep keep keep

babelRegister(); // #RemoveInProd this line is removed in isopack.js


/**
 * @summary Generate an absolute URL pointing to the application. The server reads from the `ROOT_URL` environment variable to determine where it is running. This is taken care of automatically for apps deployed with `meteor deploy`, but must be provided when using `meteor build`.
 * @locus Anywhere
 * @param {String} [path] A path to append to the root URL. Do not include a leading "`/`".
 * @param {Object} [options]
 * @param {Boolean} options.secure Create an HTTPS URL.
 * @param {Boolean} options.replaceLocalhost Replace localhost with 127.0.0.1. Useful for services that don't recognize localhost as a domain name.
 * @param {String} options.rootUrl Override the default ROOT_URL from the server environment. For example: "`http://foo.example.com`"
 */
Meteor.absoluteUrl = function (path, options) {
  // path is optional
  if (!options && typeof path === 'object') {
    options = path;
    path = undefined;
  }
  // merge options with defaults
  options = _.extend({}, Meteor.absoluteUrl.defaultOptions, options || {});

  var url = options.rootUrl;
  if (!url)
    throw new Error("Must pass options.rootUrl or set ROOT_URL in the server environment");

  if (!/^http[s]?:\/\//i.test(url)) // url starts with 'http://' or 'https://'
    url = 'http://' + url; // we will later fix to https if options.secure is set

  if (!/\/$/.test(url)) // url ends with '/'
    url += '/';

  if (path)
    url += path;

  // turn http to https if secure option is set, and we're not talking
  // to localhost.
  if (options.secure &&
      /^http:/.test(url) && // url starts with 'http:'
      !/http:\/\/localhost[:\/]/.test(url) && // doesn't match localhost
      !/http:\/\/127\.0\.0\.1[:\/]/.test(url)) // or 127.0.0.1
    url = url.replace(/^http:/, 'https:');

  if (options.replaceLocalhost)
    url = url.replace(/^http:\/\/localhost([:\/].*)/, 'http://127.0.0.1$1');

  return url;
};

// allow later packages to override default options
Meteor.absoluteUrl.defaultOptions = { };
if (typeof __meteor_runtime_config__ === "object" &&
    __meteor_runtime_config__.ROOT_URL)
  Meteor.absoluteUrl.defaultOptions.rootUrl = __meteor_runtime_config__.ROOT_URL;

Meteor._relativeToSiteRootUrl = function (link) {
  if (typeof __meteor_runtime_config__ === "object" &&
      link.substr(0, 1) === "/")
    link = (__meteor_runtime_config__.ROOT_URL_PATH_PREFIX || "") + link;
  return link;
};


====================================================================
For the license for Meteor itself, see LICENSE.txt in the root of
the repository.  This file contains the licenses for externally
maintained libraries.
====================================================================

----------
nan: https://github.com/rvagg/nan
----------

Copyright 2013, NAN contributors:
  - Rod Vagg <https://github.com/rvagg>
  - Benjamin Byholm <https://github.com/kkoopa>
  - Trevor Norris <https://github.com/trevnorris>
  - Nathan Rajlich <https://github.com/TooTallNate>
  - Brett Lawson <https://github.com/brett19>
  - Ben Noordhuis <https://github.com/bnoordhuis>
(the "Original Author")
All rights reserved.

MIT +no-false-attribs License

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

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

Distributions of all or part of the Software intended to be used
by the recipients as they would use the unmodified Software,
containing modifications that substantially alter, remove, or
disable functionality of the Software, outside of the documented
configuration mechanisms provided by the Software, shall be
modified such that the Original Author's bug reporting email
addresses and urls are either replaced with the contact information
of the parties responsible for the changes, or removed entirely.

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

Except where noted, this license applies to any and all software
programs and associated documentation files created by the
Original Author, when distributed with the Software.


Package.describe({
  summary: "Wrapper around the bcrypt npm package",
  version: '0.7.8_2',
  documentation: null
});

Npm.depends({
  bcrypt: '0.7.8'
});

Package.onUse(function (api) {
  api.export('NpmModuleBcrypt', 'server');
  api.addFiles('wrapper.js', 'server');
});