Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TS lib CompilerOption should load declarations for requested libs #579

Closed
TedDriggs opened this issue Sep 6, 2017 · 4 comments
Closed
Labels
feature-request Request for new features or functionality typescript
Milestone

Comments

@TedDriggs
Copy link

monaco-editor version: 0.10.0
Browser: Chrome 60.0
OS: macOS
Steps or JS usage snippet reproducing the issue:

This snippet was run with the code below pasted into the monaco playground

// validation settings
monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({
	noSemanticValidation: false,
	noSyntaxValidation: false
});

// compiler options
monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
	target: monaco.languages.typescript.ScriptTarget.ES2016,
    lib: ['ES2016'],
	allowNonTsExtensions: true
});

var jsCode = [
	'[1, 2].map(i => i);',
].join('\n');

monaco.editor.create(document.getElementById("container"), {
	value: jsCode,
	language: "javascript"
});

Expected: The map method should get completions and should be considered valid, as it exists in the 'ES2016' lib.

Observed: An error appears that map is not defined.

@alexdima alexdima added typescript feature-request Request for new features or functionality labels Nov 13, 2017
@alexdima alexdima added this to the Backlog Candidates milestone Dec 10, 2019
@alexdima alexdima changed the title lib CompilerOption should load declarations for requested libs TS lib CompilerOption should load declarations for requested libs Dec 10, 2019
@jquintozamora
Copy link

jquintozamora commented Jun 19, 2020

Do we have any news on that?

Do we still have to load all libs with addExtraLib ?

@Jerska
Copy link

Jerska commented Aug 31, 2020

It seems like addExtraLib manually is still needed.
Object.values was reported as an error, even though we had:

monaco.languages.typescript.javascriptDefaults.setCompilerOptions({
  target: monaco.languages.typescript.ScriptTarget.ES2020,
  // ...
});

The issue is that, compared to when the initial solution was posted, each lib file has been splitted in multiple files, referencing each other.
Copy / Pasting all the lib files by hand was going to prove painful and error-prone to import all libs required for es2020, so I came up with this basic script:

async function fetchRaw(rawPrefix, entryFiles) {
  const DEPENDENCY_REGEXP = /^\/\/\/ <reference lib="([^"]*)" \/>$/;
  const fetched = {};
  const toFetch = [...entryFiles];
  while (toFetch.length > 0) {
    const file = toFetch.pop();
    const rawUrl = `${rawPrefix}${file}`;
    const response = await fetch(rawUrl);
    const text = await response.text();
    const lines = text.split('\n');
    const dependencies = lines.filter(l => l.match(DEPENDENCY_REGEXP)).map(l => `lib.${l.match(DEPENDENCY_REGEXP)[1]}.d.ts`);
    fetched[file] = { name: file, text, dependencies };
    console.log(`Fetched ${file}`, dependencies);
    for (let dep of dependencies) {
      if (!fetched[dep]) toFetch.push(dep);
    }
  }
  return fetched;
}

async function getExtraLibs(rawPrefix, entryFiles) {
  const fetched = await fetchRaw(rawPrefix, entryFiles);
  const fetchedArr = Object.values(fetched);
  const alreadyPrinted = [];
  const statements = [];
  loopUntilEmpty: while (fetchedArr.length > 0) {
    for (let i = 0; i < fetchedArr.length; ++i) {
      const fetchedFile = fetchedArr[i];
	    const nbUnprintedDependencies = fetchedFile.dependencies
        .reduce((res, dep) => res + (alreadyPrinted.includes(dep) ? 0 : 1), 0);
      if (nbUnprintedDependencies > 0) continue;
      fetchedArr.splice(i, 1);
      statements.push(`monaco.languages.typescript.javascriptDefaults.addExtraLib(\n${JSON.stringify(fetchedFile.text)},\n${JSON.stringify(fetchedFile.name)}\n);`);
      alreadyPrinted.push(fetchedFile.name);
      console.log(`Printed ${fetchedFile.name}`);
      continue loopUntilEmpty;
    }
    // continue loopUntilEmpty should prevent us from reaching this code
    throw new Error('Circular dependency loop');
  }
  document.open();
  document.write('<!DOCTYPE html><html><body><textarea id="content" style="font-family: monospace; border: 1px solid #ccc; background: #e8e8e8; padding: 8px 16px; width: 100%; height: 100vh; "></textarea><br /></body></html>');
  document.getElementById('content').value = statements.join('\n');
}

getExtraLibs("https://raw.githubusercontent.com/microsoft/TypeScript/master/lib/", ["lib.es2020.d.ts"]).then(console.log).catch(console.error);

Output:

monaco.languages.typescript.javascriptDefaults.addExtraLib(
  "/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// <reference no-default-lib=\"true\"/>\n\n\ndeclare namespace Intl {\n\n    /**\n     * [BCP 47 language tag](http://tools.ietf.org/html/rfc5646) definition.\n     *\n     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#locales_argument).\n     *\n     * [Wikipedia](https://en.wikipedia.org/wiki/IETF_language_tag).\n     */\n    type BCP47LanguageTag = string;\n\n    /**\n     * Unit to use in the relative time internationalized message.\n     *\n     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format#Parameters).\n     *\n     * [Specification](https://tc39.es/ecma402/#sec-singularrelativetimeunit).\n     */\n    type RelativeTimeFormatUnit =\n        | \"year\" | \"years\"\n        | \"quarter\" | \"quarters\"\n        | \"month\" | \"months\"\n        | \"week\" | \"weeks\"\n        | \"day\" | \"days\"\n        | \"hour\" | \"hours\"\n        | \"minute\" | \"minutes\"\n        | \"second\" | \"seconds\"\n        ;\n\n    /**\n     * The locale matching algorithm to use.\n     *\n     * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation).\n     *\n     * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat).\n     */\n    type RelativeTimeFormatLocaleMatcher = \"lookup\" | \"best fit\";\n\n    /**\n     * The format of output message.\n     *\n     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).\n     *\n     * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat).\n     */\n    type RelativeTimeFormatNumeric = \"always\" | \"auto\";\n\n    /**\n     * The length of the internationalized message.\n     *\n     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).\n     *\n     * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat).\n     */\n    type RelativeTimeFormatStyle = \"long\" | \"short\" | \"narrow\";\n\n    /**\n     * An object with some or all of properties of `options` parameter\n     * of `Intl.RelativeTimeFormat` constructor.\n     *\n     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters).\n     *\n     * [Specification](https://tc39.es/ecma402/#sec-InitializeRelativeTimeFormat).\n     */\n    interface RelativeTimeFormatOptions {\n        localeMatcher?: RelativeTimeFormatLocaleMatcher;\n        numeric?: RelativeTimeFormatNumeric;\n        style?: RelativeTimeFormatStyle;\n    }\n\n    /**\n     * An object with properties reflecting the locale\n     * and formatting options computed during initialization\n     * of the `Intel.RelativeTimeFormat` object\n     *\n     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions#Description).\n     *\n     * [Specification](https://tc39.es/ecma402/#table-relativetimeformat-resolvedoptions-properties)\n     */\n    interface ResolvedRelativeTimeFormatOptions {\n        locale: BCP47LanguageTag;\n        style: RelativeTimeFormatStyle;\n        numeric: RelativeTimeFormatNumeric;\n        numberingSystem: string;\n    }\n\n    /**\n     * An object representing the relative time format in parts\n     * that can be used for custom locale-aware formatting.\n     *\n     * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts#Using_formatToParts).\n     *\n     * [Specification](https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts).\n     */\n    interface RelativeTimeFormatPart {\n        type: string;\n        value: string;\n        unit?: RelativeTimeFormatUnit;\n    }\n\n    interface RelativeTimeFormat {\n        /**\n         * Formats a value and a unit according to the locale\n         * and formatting options of the given\n         * [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat)\n         * object.\n         *\n         * While this method automatically provides the correct plural forms,\n         * the grammatical form is otherwise as neutral as possible.\n         * It is the caller's responsibility to handle cut-off logic\n         * such as deciding between displaying \"in 7 days\" or \"in 1 week\".\n         * This API does not support relative dates involving compound units.\n         * e.g \"in 5 days and 4 hours\".\n         *\n         * @param value -  Numeric value to use in the internationalized relative time message\n         *\n         * @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit)\n         *  to use in the relative time internationalized message.\n         *  Possible values are: `\"year\"`, `\"quarter\"`, `\"month\"`, `\"week\"`,\n         *  `\"day\"`, `\"hour\"`, `\"minute\"`, `\"second\"`.\n         *  Plural forms are also permitted.\n         *\n         * @throws `RangeError` if `unit` was given something other than `unit` possible values\n         *\n         * @returns Internationalized relative time message as string\n         *\n         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/format).\n         *\n         * [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.format).\n         */\n        format(\n            value: number,\n            unit: RelativeTimeFormatUnit,\n        ): string;\n\n        /**\n         *  A version of the format method which it returns an array of objects\n         *  which represent \"parts\" of the object,\n         *  separating the formatted number into its constituent parts\n         *  and separating it from other surrounding text.\n         *  These objects have two properties:\n         * `type` a NumberFormat formatToParts type, and `value`,\n         *  which is the String which is the component of the output.\n         *  If a \"part\" came from NumberFormat,\n         *  it will have a unit property which indicates the `unit` being formatted;\n         *  literals which are part of the larger frame will not have this property.\n         *\n         *  @param value - Numeric value to use in the internationalized relative time message\n         *\n         *  @param unit - [Unit](https://tc39.es/ecma402/#sec-singularrelativetimeunit)\n         *   to use in the relative time internationalized message.\n         *   Possible values are: `\"year\"`, `\"quarter\"`, `\"month\"`, `\"week\"`,\n         *   `\"day\"`, `\"hour\"`, `\"minute\"`, `\"second\"`.\n         *   Plural forms are also permitted.\n         *\n         *  @throws `RangeError` if `unit` was given something other than `unit` possible values\n         *\n         *  @returns Array of [FormatRelativeTimeToParts](https://tc39.es/ecma402/#sec-FormatRelativeTimeToParts)\n         *\n         *  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/formatToParts).\n         *\n         *  [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.prototype.formatToParts).\n         */\n        formatToParts(\n            value: number,\n            unit: RelativeTimeFormatUnit,\n        ): RelativeTimeFormatPart[];\n\n        /**\n         * Provides access to the locale and options computed during initialization of this `Intl.RelativeTimeFormat` object.\n         *\n         * @returns A new object with properties reflecting the locale\n         *  and formatting options computed during initialization\n         *  of the `Intel.RelativeTimeFormat` object.\n         *\n         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/resolvedOptions).\n         *\n         * [Specification](https://tc39.es/ecma402/#sec-intl.relativetimeformat.prototype.resolvedoptions)\n         */\n        resolvedOptions(): ResolvedRelativeTimeFormatOptions;\n    }\n\n    /**\n     * The [`Intl.RelativeTimeFormat`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat)\n     * object is a constructor for objects that enable language-sensitive relative time formatting.\n     *\n     * Part of [Intl object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl)\n     * namespace and the [ECMAScript Internationalization API](https://www.ecma-international.org/publications/standards/Ecma-402.htm).\n     *\n     * [Compatibility](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat#Browser_compatibility).\n     *\n     * [Polyfills](https://github.com/tc39/proposal-intl-relative-time#polyfills).\n     */\n    const RelativeTimeFormat: {\n        /**\n         * Constructor creates [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat)\n         * objects\n         *\n         * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.\n         *  For the general form and interpretation of the locales argument,\n         *  see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).\n         *\n         * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters)\n         *  with some or all of options of the formatting.\n         *  An object with some or all of the following properties:\n         *  - `localeMatcher` - The locale matching algorithm to use.\n         *    Possible values are `\"lookup\"` and `\"best fit\"`; the default is `\"best fit\"`.\n         *    For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation).\n         *  - `numeric` - The format of output message.\n         *    Possible values are: `\"always\"` (default, e.g., `1 day ago`) or `\"auto\"` (e.g., `yesterday`).\n         *    The `\"auto\"` value allows to not always have to use numeric values in the output.\n         *  - `style` - The length of the internationalized message. Possible values are:\n         *    `\"long\"` (default, e.g., in 1 month),\n         *    `\"short\"` (e.g., in 1 mo.)\n         *    or `\"narrow\"` (e.g., in 1 mo.). The narrow style could be similar to the short style for some locales.\n         *\n         * @returns [Intl.RelativeTimeFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RelativeTimeFormat) object.\n         *\n         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat).\n         *\n         * [Specification](https://tc39.es/ecma402/#sec-intl-relativetimeformat-constructor).\n         */\n        new(\n            locales?: BCP47LanguageTag | BCP47LanguageTag[],\n            options?: RelativeTimeFormatOptions,\n        ): RelativeTimeFormat;\n\n        /**\n         * Returns an array containing those of the provided locales\n         * that are supported in date and time formatting\n         * without having to fall back to the runtime's default locale.\n         *\n         * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.\n         *  For the general form and interpretation of the locales argument,\n         *  see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).\n         *\n         * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/RelativeTimeFormat#Parameters)\n         *  with some or all of options of the formatting.\n         *  An object with some or all of the following properties:\n         *  - `localeMatcher` - The locale matching algorithm to use.\n         *    Possible values are `\"lookup\"` and `\"best fit\"`; the default is `\"best fit\"`.\n         *    For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation).\n         *  - `numeric` - The format of output message.\n         *    Possible values are: `\"always\"` (default, e.g., `1 day ago`) or `\"auto\"` (e.g., `yesterday`).\n         *    The `\"auto\"` value allows to not always have to use numeric values in the output.\n         *  - `style` - The length of the internationalized message. Possible values are:\n         *    `\"long\"` (default, e.g., in 1 month),\n         *    `\"short\"` (e.g., in 1 mo.)\n         *    or `\"narrow\"` (e.g., in 1 mo.). The narrow style could be similar to the short style for some locales.\n         *\n         * @returns An array containing those of the provided locales\n         *  that are supported in date and time formatting\n         *  without having to fall back to the runtime's default locale.\n         *\n         * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat/supportedLocalesOf).\n         *\n         * [Specification](https://tc39.es/ecma402/#sec-Intl.RelativeTimeFormat.supportedLocalesOf).\n         */\n        supportedLocalesOf(\n            locales: BCP47LanguageTag | BCP47LanguageTag[],\n            options?: RelativeTimeFormatOptions,\n        ): BCP47LanguageTag[];\n    };\n\n    interface NumberFormatOptions {\n        notation?: string;\n        unit?: string;\n        unitDisplay?: string;\n    }\n\n    interface ResolvedNumberFormatOptions {\n        notation?: string;\n        unit?: string;\n        unitDisplay?: string;\n    }\n}\n",
  "lib.es2020.intl.d.ts"
);
monaco.languages.typescript.javascriptDefaults.addExtraLib(
  "/*! *****************************************************************************\nCopyright (c) Microsoft Corporation. All rights reserved.\nLicensed under the Apache License, Version 2.0 (the \"License\"); you may not use\nthis file except in compliance with the License. You may obtain a copy of the\nLicense at http://www.apache.org/licenses/LICENSE-2.0\n\nTHIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\nKIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED\nWARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,\nMERCHANTABLITY OR NON-INFRINGEMENT.\n\nSee the Apache Version 2.0 License for specific language governing permissions\nand limitations under the License.\n***************************************************************************** */\n\n\n\n/// <reference no-default-lib=\"true\"/>\n\n\ninterface SymbolConstructor {\n    /**\n     * A reference to the prototype.\n     */\n    readonly prototype: Symbol;\n\n    /**\n     * Returns a new unique Symbol value.\n     * @param  description Description of the new Symbol object.\n     */\n    (description?: string | number): symbol;\n\n    /**\n     * Returns a Symbol object from the global symbol registry matching the given key if found.\n     * Otherwise, returns a new symbol with this key.\n     * @param key key to search for.\n     */\n    for(key: string): symbol;\n\n    /**\n     * Returns a key from the global symbol registry matching the given Symbol if found.\n     * Otherwise, returns a undefined.\n     * @param sym Symbol to find the key for.\n     */\n    keyFor(sym: symbol): string | undefined;\n}\n\ndeclare var Symbol: SymbolConstructor;",
  "lib.es2015.symbol.d.ts"
);
// ...

Just run this code in a new browser tab to have the list of addExtraLib statements.
Depending on which lib you want to import, find the correct filename in https://github.com/microsoft/TypeScript/tree/master/lib and modify the second param of getExtraLibs.
You'll then be able to modify your compilerOptions to include lib: ['es2020'].

@alexdima
Copy link
Member

This might just work after microsoft/monaco-typescript#68

@sonallux
Copy link

This might just work after microsoft/monaco-typescript#68

Yes, this works now using the latest monaco-editor@0.21.0. I can now just set the TS compiler option to lib: ['es2019'] and the correct libs are loaded.

@alexdima alexdima modified the milestones: Backlog, August 2020 Sep 21, 2020
@vscodebot vscodebot bot locked and limited conversation to collaborators Nov 5, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
feature-request Request for new features or functionality typescript
Projects
None yet
Development

No branches or pull requests

5 participants