/*
Extracts main symbol information from a library api.json.
Also collects deprecated, experimental and since api's.
Returns a promise that resolves with an array of symbols.
19267
function createSymbolSummaryForLib(lib) {
		let file = path.join(unpackedTestresourcesRoot, lib.replace(/\./g, "/"), "designtime/api.json");

		return readJSONFile(file).then(function (apijson) {
			if (!apijson.hasOwnProperty("symbols") || !Array.isArray(apijson.symbols)) {
				// Ignore libraries with invalid api.json content like empty object or non-array "symbols" property.
				return [];
			}
			return apijson.symbols.map(symbol => {
				let oReturn = {
					name: symbol.name,
					kind: symbol.kind,
					visibility: symbol.visibility,
					extends: symbol.extends,
					implements: symbol.implements,
					lib: lib
				};
				// We add deprecated member only when the control is deprecated to keep file size at check
				if (symbol.deprecated) {
					oReturn.deprecated = true;
				}
				collectLists(symbol);
				return oReturn;
			});
		})
	}
1237879
function getLibraryPromise(oChainObject) {
		return new Promise(function(oResolve) {
			fs.readFile(oChainObject.libraryFile, 'utf8', (oError, oData) => {
				oChainObject.libraryFileData = oData;
				oResolve(oChainObject);
			});
		});
	}
805063
function(pkg_name, pkg_ver){

    var pkg_info = null;
    var dep_type = null;
    var cmd = BOWER_INFO_CMD.replace("{name}", pkg_name).replace("{ver}", pkg_ver) + ' --json';

    try {
        var response = execSync(cmd, {stdio: [null]});

        pkg_info = JSON.parse(response.toString());

        if(pkg_info && _.size(pkg_info) > 0){
            console.info('      - Fetched info for '.green + pkg_name.bold.green + ' from Bower'.grey);
        }else{
            console.warn('      ^ Could not fetch info for '.grey + pkg_name.red.bold);
        }
    }
    catch (err) {
        console.warn('      ^ Err! Could not fetch info for '.grey + pkg_name.red.bold);
    }

    return pkg_info;
}
449237
function resolvePromise(promise, state, value) {
        var onceWrapper = once();
        if (promise === value) {
            throw new TypeError('Promise resolved with itself');
        }
        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.apply(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;
                // 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) {
                    value[__symbol__('currentTask')] = Zone.currentTask;
                }
                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 {
                        throw new Error('Uncaught (in promise): ' + 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;
    }
103323
def extract_symbol_app(parser, _, args):  # pragma: no cover
    

    parser.add_argument('file', help='ELF file to extract a symbol from')
    parser.add_argument('symbol', help='the symbol to extract')
    args = parser.parse_args(args)
    return ELF(args.file).get_symbol(args.symbol).content
870316
function resolve() {
    var promises = [];
    var args = flatten(arguments);
    for (var i = 0; i < args.length; i ++) {
      promises.push(Esquire.resolve(args[i], true, true));
    }

    /* Await for resolution of dependencies */
    return Promise.all(promises).then(function(result) {
      var modules = {};
      for (var i = 0; i < result.length; i ++) {
        var resolved = result[i];
        for (var name in resolved) {
          var module = resolved[name];
          if (module.$$dynamic) continue;
          modules[name] = resolved[name];
        }
      }
      return modules;
    });
  }
556715
function(project) {
        return request.read(project.resourceUrl)
            .then(function(response) {
                // consume resource data
                if(response.status !== 200) return Promise.reject(response);

                let data;
                try {
                    data = JSON.parse(response.data);
                } catch(err) {
                    return Promise.reject(err);
                }

                for(let resource of data) {
                    try {
                        resource.slug = resource.slug.toLowerCase();
                        switch (resource.slug) {
                            case 'obs':
                            case 'ulb':
                                resource.status.translate_mode = 'all';
                                break;
                            default:
                                resource.status.translate_mode = 'gl';
                        }

                        resource.status.pub_date = resource.status.publish_date;
                        resource.translation_words_assignments_url = resource.tw_cat;
                        resource.type = 'book';
                        resource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('book'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.source
                        }];
                        library.addResource(resource, project.id);

                        // coerce notes to resource
                        let helpResource = {
                            slug: 'tn',
                            name: 'translationNotes',
                            type: 'help',
                            status: resource.status,
                            formats: [{
                                package_version: rc.tools.spec.version,
                                mime_type: rc.tools.typeToMime('help'),
                                modified_at: resource.date_modified,
                                imported: 0,
                                url: resource.notes
                            }]
                        };
                        helpResource.status.translate_mode = 'gl';
                        helpResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tn',
                            version: resource.status.version
                        }];
                        if (resource.notes) {
                            library.addResource(helpResource, project.id);
                        }

                        // coerce questions to resource
                        helpResource.slug = 'tq';
                        helpResource.name = 'translationQuestions';
                        helpResource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('help'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.checking_questions
                        }];
                        helpResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tq',
                            version: resource.status.version
                        }];
                        if (resource.checking_questions) {
                            library.addResource(helpResource, project.id);
                        }

                        // add words project (this is insert/update so it will only be added once)
                        // TRICKY: obs tw has not been unified with bible tw yet so we add it as separate project.
                        let wordsProjectId = library.addProject({
                            slug: project.slug === 'obs' ? 'bible-obs' : 'bible',
                            name: 'translationWords' + (project.slug === 'obs' ? ' OBS' : ''),
                            desc: '',
                            icon: '',
                            sort: 100,
                            chunks_url: '',
                            categories: []
                        }, project.source_language_id);

                        // add resource to words project
                        let dictResource = _.clone(helpResource);
                        dictResource.slug = 'tw';
                        dictResource.name = 'translationWords';
                        dictResource.type = 'dict';
                        dictResource.formats = [{
                            package_version: rc.tools.spec.version,
                            mime_type: rc.tools.typeToMime('dict'),
                            modified_at: resource.date_modified,
                            imported: 0,
                            url: resource.terms
                        }];
                        dictResource.status.source_translations = [{
                            language_slug: project.source_language_slug,
                            resource_slug: 'tw',
                            version: resource.status.version
                        }];
                        if (resource.terms) {
                            library.addResource(dictResource, wordsProjectId);
                        }
                    } catch (err) {
                        return Promise.reject(err);
                    }
                }
            });
    }
1269417
function extractCodeBlocks(filepath) {
  return new Promise(function(fulfill, reject) {
    fs.readFile(filepath, 'utf8', function(err, text) {
      if (err) {
        console.log(err);
        reject(err);
      } else {
        var converter = new showdown.Converter();
        var html = converter.makeHtml(text);
        var $ = cheerio.load(html);
        var codeBlocks = $('pre code').map(function(index, elem) {
          var language = ($(elem).attr('class') || 'none language-none').split(' ')[0];
          return {
            filename: buildFilename(filepath, elem, $),
            content: $(elem).text(),
            language: language
          };
        });
        fulfill(codeBlocks.toArray());
      }
    });
  });
}
257680
function parsePackageJson(path) {
    return fs.readFile(path)
        .catch(function () {
            var err = new Error(common.i18n.t('errors.utils.parsepackagejson.couldNotReadPackage'));
            err.context = path;

            return Promise.reject(err);
        })
        .then(function (source) {
            var hasRequiredKeys, json, err;

            try {
                json = JSON.parse(source);

                hasRequiredKeys = json.name && json.version;

                if (!hasRequiredKeys) {
                    err = new Error(common.i18n.t('errors.utils.parsepackagejson.nameOrVersionMissing'));
                    err.context = path;
                    err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'});

                    return Promise.reject(err);
                }

                return json;
            } catch (parseError) {
                err = new Error(common.i18n.t('errors.utils.parsepackagejson.themeFileIsMalformed'));
                err.context = path;
                err.help = common.i18n.t('errors.utils.parsepackagejson.willBeRequired', {url: 'https://docs.ghost.org/api/handlebars-themes/'});

                return Promise.reject(err);
            }
        });
}
174663
function checkSourceInfo () {
  return new Promise((resolve, reject) => {
    let ok = pjson.name === oldInfo.packageName
    ok = ok && readSync('android/app/src/main/AndroidManifest.xml').includes(`package="${oldInfo.packageID}"`)

    if (!ok) {
      reject(new Error('The App name is already modified.'))
      return
    }

    console.log()
    console.log('---------------------------------------------------------')
    console.log('New project parameters:')
    console.log('---------------------------------------------------------')
    console.log('App display name :', newInfo.appName)
    console.log('Project name     :', newInfo.projectName)
    console.log('Package name     :', newInfo.packageName)
    console.log('Package id       :', newInfo.packageID)
    console.log('---------------------------------------------------------')

    let r = null
    try {
      r = readline.createInterface({
        input: process.stdin,
        output: process.stdout,
      })
      r.question('Is this correct?', (answer) => {
        r.close()
        resolve(answer)
      })
    } catch (e) {
      if (r) {
        r.close()
      }
      reject(e)
    }
  })
}
1080681
function getMain(src, options, dest) {
    var meta = grunt.file.readJSON(path.join(src, 'package.json'))
    if (!meta.main) {
      fail.fatal(
        'No main property specified by ' + path.normalize(src.replace(options.srcPrefix, ''))
      )
    }
    var files = typeof meta.main === 'string' ? [meta.main] : meta.main
    return files.map(function(source) {
      return {
        src: path.join(src, source),
        dest: dest
      }
    })
  }
1109559
function callApi(endpoint, schema) {
  if (endpoint.indexOf(API_ROOT) === -1) {
    endpoint = API_ROOT + endpoint;
  }

  return fetch(endpoint)
    .then(response =>
      response.json().then(json => ({ json, response}))
    ).then(({ json, response }) => {
      if (!response.ok) {
        return Promise.reject(json);
      }

      const camelizedJson = camelizeKeys(json);
      const nextPageUrl = getNextPageUrl(response) || undefined;

      return Object.assign({},
        normalize(camelizedJson, schema),
        { nextPageUrl }
      );
    });
}
401372
function parseDiagram(diagramXML) {
  return new Promise((resolve, reject) => {
    moddle.fromXML(diagramXML, (error, moddleElement, context) => {

      if (error) {
        return resolve({
          error
        });
      }

      const warnings = context.warnings || [];

      return resolve({
        moddleElement,
        warnings
      });
    });
  });
}
115451
function getResults(result, objects) {
		
		// if there are no results, resolve an empty array
		if (!result) {
			return new Promise(function(resolve, reject) {
				resolve([]);
			});
		}
		
		// if the result object is undefined or not an array, make it one
		result.objects = result.objects || [];
		result.objects = Array.isArray(result.objects) ? result.objects : [result.objects];
		objects        = _.union(objects, result.objects);
		
		// if the result has a token, there are more results, continue to get them
		if (result.token) {
			return _client.method('ContinueRetrievePropertiesEx', {
				_this: _client._sc.propertyCollector,
				token: result.token
			})
			.then(function(results) {
				return getResults(results, objects);
			});
		}
		
		// if there are no more results, return the formatted results
		else {
			return new Promise(function(resolve, reject) {
				resolve(env.format(objects));
			});
		}
	}
154697
function extractTypeSourcesFromMarkdown(mdSource) {
  var types = lang.string.lines(mdSource).reduce((typesAkk, line) => {
    if (line.trim().startsWith("//")) return typesAkk;
    if (typesAkk.current && !line.trim().length) {
      typesAkk.types.push(typesAkk.current); typesAkk.current = [];
    } else if (typesAkk.current && line.indexOf("```") > -1) {
      typesAkk.types.push(typesAkk.current); typesAkk.current = null;
    } else if (!typesAkk.current && line.indexOf("```js") > -1) {
      typesAkk.current = [];
    } else if (typesAkk.current) typesAkk.current.push(line);
    return typesAkk;
  }, {current: null, types: []}).types;
  return lang.arr.invoke(types, "join", "\n");
}
1372443
function _fetchCSLJSONEntries (dois) {
  let errored = []
  let entries = []

  return dois.reduce((promise, doi) => {
    return promise
      .then(() => _fetchDOI(doi))
      .then(csl => entries.push(JSON.parse(csl)))
      .catch(() => errored.push(doi))
  }, Promise.resolve())
    .then(() => {
      if (errored.length > 0) {
        let err = new Error(`Could not resolve some DOI's`)
        err.dois = errored
        throw err
      } else {
        return entries
      }
    })
}
209656
function getAPIJSONPromise(oChainObject) {
		return new Promise(function(oResolve, oReject) {
			fs.readFile(sInputFile, 'utf8', (oError, sFileData) => {
				if (oError) {
					oReject(oError);
				} else {
					oChainObject.fileData = JSON.parse(sFileData);
					oResolve(oChainObject);
				}
			});
		});
	}