/*
promise dependencies are loaded
- PURPOSE: to preload dependencies for synchronous require injections
- takes list of 'dependencies' as input and loads each of them into cache
- waits untill all are fully loaded in cache before resolving
542312
async function(dependencies, relative_path_root, search_for_dependencies){ // load dependencies for synchronous injected require types
        /*
            normalize input
        */
        if(typeof dependencies == "undefined") dependencies = [];

        /*
            define dependency options to be used for caching the modules
                - pass relative path root
        */
        var dependency_options = {
            relative_path_root:relative_path_root, // pass relative path root
            search_for_dependencies:search_for_dependencies, // NOTE: this will always be : true. We inject it though to make it clear why that is the case.
                                                             //     and do not worry - if a future module states that it should search for its dependencies, we still will, as the option will be overwritten by that modules settings
        };

        /*
            create promises to cache each
        */
        var promises_to_cache_each = [];
        for(var i = 0; i < dependencies.length; i++){ // promise to load each dependency
            let dependency = dependencies[i]; //
            var this_promise = window.clientside_require.asynchronous_require(dependency, dependency_options) // call async require to cache the module
                .catch((err)=>{
                    console.warn("could not load dependency " + dependency + " found in " + relative_path_root);
                })
            promises_to_cache_each.push(this_promise);
        }

        /*
            resolve only after all are loaded
        */
        return Promise.all(promises_to_cache_each); // note that we do not await each promise individually so that multiple dependencies can load at a time
    }
470579
function(){
		// If a task is currently loading this fileUrl,
		// wait for it to complete
		var loadingTask = this.context.loadingPaths[this.fileUrl];
		if (!loadingTask) return;

		var task = this;
		return loadingTask.promise.then(function() {
			task._fetchedPackage = loadingTask.getPackage();

			var firstTaskFailed = loadingTask.hadErrorLoading();
			var currentTaskIsCompatible = task.isCompatibleVersion();
			var firstTaskIsNotCompatible = !loadingTask.isCompatibleVersion();

			// Do not flag the current task as failed if:
			//
			//	- Current task fetches a version in rage and
			//	- First task had no error loading at all or
			//	- First task fetched an incompatible version
			//
			// otherwise, assume current task will fail for the same reason as
			// the first did
			if (currentTaskIsCompatible && (!firstTaskFailed || firstTaskIsNotCompatible)) {
				task.failed = false;
				task.error = null;
			}
			else if (!currentTaskIsCompatible) {
				task.failed = true;
				task.error = new Error("Incompatible package version requested");
			}
			else if (firstTaskFailed) {
				task.failed = true;
				task.error = loadingTask.error;
			}
		});
	}
1219571
function promiseSequence(promiseFactories) {
    return __awaiter(this, void 0, void 0, function* () {
        const ret = [];
        for (const f of promiseFactories) {
            ret.push(yield f());
        }
        return ret;
    });
}
1252548
function main(options = util.getDefaultOptions()) {
  createLogger(options.debug);
  log.info(`Preparing '${options.sdk}' schemas in version '${options.version || 'latest'}'...`);

  let allLibs = {};

  // do the downloading and encapsulate in Promise
  const dlPromise = new Promise((resolve, reject) => {
    download.allLibsFile(options)
      .then((allLibsJSON) => {
        allLibs = allLibsJSON;
        download.schemas(options, allLibs)
          .then((values) => {
            resolve(values);
          })
          .catch((e) => {
            reject(e);
          });
      })
      .catch((e) => {
        reject(e);
      });
  });


  dlPromise.then(() => {
    log.info('Yay, all schema files were successfully downloaded!');
    if (options.upgrade) {
      upgrade(options, allLibs);
    }
    if (options.link) {
      link(options, allLibs);
    }
  }, (e) => {
    log.error('Damn... Something went all wrong while downloading the schema files!');
    log.error(`Are you sure the version '${options.version}' is still available on '${options.sdk}' download pages?`);
    log.error(e);
  });
}
514760
function createImportPromise(loader, name, promise) {
    var importPromises = loader._loader.importPromises;
    return importPromises[name] = promise.then(function(m) {
      importPromises[name] = undefined;
      return m;
    }, function(e) {
      importPromises[name] = undefined;
      throw e;
    });
  }
1312305
function Promise () {
	this.deferred = false;
	this.handlers = [];
	this.state    = promise.state.PENDING;
	this.value    = null;
}
583109
function () {
		var that = this,
				independent, 
				dependencyNotRequired;
		
		promiseIndependent = this.saveFixturesFromArray(independentFixtures);
		promiseDelayedDependency = this.saveFixturesFromArray(delayedDependencyFixtures);
		
		promise = Q.all([ promiseIndependent, promiseDelayedDependency ])
			.then(function(models) {
				return that.saveFixturesFromArray(requiredDependencyFixtures);
			});
		
		return promise;
	}
112661
function() {
        var self = this;

        return new Promise(function(resolve, reject) {
            var config = {};

            for (var i = 0; i < self._modules.length; i++) {
                var module = self._modules[i];

                var storedModule = config[module.name] = {
                    dependencies: module.dependencies
                };

                if (module.condition) {
                    storedModule.condition = module.condition;
                }

                if (!self._options.ignorePath) {
                    if (module.fullPath) {
                        storedModule.fullPath = upath.toUnix(module.fullPath);
                    } else {
                        var dirname = path.dirname(module.name);

                        var modulePath = module.path || (dirname !== '.' ? dirname + '/' + module.file : module.file);

                        storedModule.path = upath.toUnix(modulePath);
                    }
                }
            }

            resolve(config);
        });
    }
489732
async function(request, modules_root, options){
        /*
            extract request details for this request
        */
        var request_details = await this.utils.promise_to_decompose_request(
            request, // a relative path, absolute path, or module name
            modules_root, // defines where to look for modules
            options.relative_path_root, // defines where the relative path should start from
            options.search_for_dependencies // modules can define to not search for dependencies on their own, overriding the user
        );

        /*
            load dependencies into cache before loading the main file
                - recursive operation
        */
        if(request_details.search_for_dependencies){
            // this is the main (and most obvious) downside to synchronous_require; waiting until all dependencies load.
            var dependency_relative_path_root = request_details.path.substring(0, request_details.path.lastIndexOf("/")) + "/";
            await this.promise_dependencies_are_loaded(request_details.dependencies, dependency_relative_path_root, request_details.search_for_dependencies); // wait untill dependencies are loaded
        }

        /*
            retreive content with loader functions
                - handles scoping and env setup of js files (retreives content based on CommonJS exports)
                - supports js, css, html, json, txt, etc
        */
        var content = await this.utils.loader_functions[request_details.type](request_details.path);

        /*
            resolve with content
        */
        return content;
    }
207831
async function fetchAllDependents (name) {
  let pkg = await npm.getLatest(name)
  let deps = Object.keys(pkg.dependencies || {})
  if (!deps.length) return []
  let promises = []
  for (let dep of deps) {
    promises.push(fetchAllDependents(dep))
  }
  for (let subdeps of await Promise.all(promises)) {
    deps = deps.concat(subdeps)
  }
  return _.uniq(deps.sort())
}
397624
function resolvePromise(promise, state, value) {
        var onceWrapper = once();
        if (promise === value) {
            throw new TypeError(TYPE_ERROR);
        }
        if (promise[symbolState] === UNRESOLVED) {
            // should only get value.then once based on promise spec.
            var then = null;
            try {
                if (typeof value === 'object' || typeof value === 'function') {
                    then = value && value.then;
                }
            }
            catch (err) {
                onceWrapper(function () {
                    resolvePromise(promise, false, err);
                })();
                return promise;
            }
            // if (value instanceof ZoneAwarePromise) {
            if (state !== REJECTED && value instanceof ZoneAwarePromise &&
                value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
                value[symbolState] !== UNRESOLVED) {
                clearRejectedNoCatch(value);
                resolvePromise(promise, value[symbolState], value[symbolValue]);
            }
            else if (state !== REJECTED && typeof then === 'function') {
                try {
                    then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
                }
                catch (err) {
                    onceWrapper(function () {
                        resolvePromise(promise, false, err);
                    })();
                }
            }
            else {
                promise[symbolState] = state;
                var queue = promise[symbolValue];
                promise[symbolValue] = value;
                if (promise[symbolFinally] === symbolFinally) {
                    // the promise is generated by Promise.prototype.finally
                    if (state === RESOLVED) {
                        // the state is resolved, should ignore the value
                        // and use parent promise value
                        promise[symbolState] = promise[symbolParentPromiseState];
                        promise[symbolValue] = promise[symbolParentPromiseValue];
                    }
                }
                // record task information in value when error occurs, so we can
                // do some additional work such as render longStackTrace
                if (state === REJECTED && value instanceof Error) {
                    // check if longStackTraceZone is here
                    var trace = Zone.currentTask && Zone.currentTask.data &&
                        Zone.currentTask.data[creationTrace];
                    if (trace) {
                        // only keep the long stack trace into error when in longStackTraceZone
                        ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
                    }
                }
                for (var i = 0; i < queue.length;) {
                    scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
                }
                if (queue.length == 0 && state == REJECTED) {
                    promise[symbolState] = REJECTED_NO_CATCH;
                    try {
                        // try to print more readable error log
                        throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
                            (value && value.stack ? '\n' + value.stack : ''));
                    }
                    catch (err) {
                        var error_1 = err;
                        error_1.rejection = value;
                        error_1.promise = promise;
                        error_1.zone = Zone.current;
                        error_1.task = Zone.currentTask;
                        _uncaughtPromiseErrors.push(error_1);
                        api.scheduleMicroTask(); // to make sure that it is running
                    }
                }
            }
        }
        // Resolving an already resolved promise is a noop.
        return promise;
    }
494535
function load(ctx, loader, params, onUpdate) {
    // Create an object that holds the loadedData promise, so we can compare on handleLoadResult, and ignore promises that
    // did not originate from the very last load that happened.
    const loadedData = {
        loading: true, // Start off "loading", but once the promise below resolves, this value is false.
    };

    loadedData.promise = loader(params, handleLoadResult.bind(null, ctx, loadedData, onUpdate, undefined)) // Do not affect loading status.
                                  .then(handleLoadResult.bind(null, ctx, loadedData, onUpdate, false, undefined)) // Success, not loading.
                                 .catch(handleLoadResult.bind(null, ctx, loadedData, onUpdate, false)); // Failed, not loading.

    // Return promise for data.
    return loadedData.promise;
}
1181878
function injectDependencies(globalConfig) {
  config = globalConfig;
  var stream = config.get('stream');

  globalDependenciesSorted = config.get('global-dependencies-sorted');
  ignorePath = config.get('ignore-path');
  fileTypes = config.get('file-types');

  if (stream.src) {
    config.set('stream', {
      src: injectScriptsStream(stream.path, stream.src, stream.fileType),
      fileType: stream.fileType
    });
  } else {
    config.get('src').forEach(injectScripts);
  }

  return config;
}
429764
function (dependencies, extension) {
            if (dependencies) {
                for (var i = dependencies.length - 1; i >= 0; i--) {
                    this.addDependency(dependencies[i], extension);
                }
            }
        }
983767
function resolveOrEnqueuePromise( PromiseInterface $promise, callable $resultCallback = null )
	{
		if ($this->next_async_request)
		{
			$promise = $promise->then(function($result) use ($resultCallback) {
				return $resultCallback ? $resultCallback($result) : null;
			});
			$this->next_async_request->setPromise($promise);
			return $this->next_async_request = null;
		}
		return $resultCallback ? $resultCallback($promise->wait()) : null;
	}
1255160
function loadImplementation(implementation){
  var impl = null

  if(shouldPreferGlobalPromise(implementation)){
    // if no implementation or env specified use global.Promise
    impl = {
      Promise: global.Promise,
      implementation: 'global.Promise'
    }
  } else if(implementation){
    // if implementation specified, require it
    var lib = require(implementation)
    impl = {
      Promise: lib.Promise || lib,
      implementation: implementation
    }
  } else {
    // try to auto detect implementation. This is non-deterministic
    // and should prefer other branches, but this is our last chance
    // to load something without throwing error
    impl = tryAutoDetect()
  }

  if(impl === null){
    throw new Error('Cannot find any-promise implementation nor'+
      ' global.Promise. You must install polyfill or call'+
      ' require("any-promise/register") with your preferred'+
      ' implementation, e.g. require("any-promise/register/bluebird")'+
      ' on application load prior to any require("any-promise").')
  }

  return impl
}
690306
function fetchUnmetDependencies() {
        var runAgain = false;
        for (var id in dependencyMap) {
            _.forEach(dependencyMap[id], function (depId) {
                if (!dependencyMap[depId] && !injectedMap[depId]) {
                    try {
                        loadExternalModule(id, depId);
                    } catch (err) {
                        throw new Error('Error loading dependency ' + depId + ' for ' + id + ': ' + err.message);
                    }

                    runAgain = true;
                }
            });
        }

        if (runAgain) { //continue until all we don't have any more unmet dependencies
            fetchUnmetDependencies();
        }
    }