Merge branch 'main' into main

This commit is contained in:
Henning Dieterichs 2022-07-21 11:31:18 +02:00 committed by GitHub
commit 75927c6de7
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
149 changed files with 92415 additions and 70714 deletions

1
.gitattributes vendored Normal file
View file

@ -0,0 +1 @@
* text=auto

View file

@ -27,11 +27,16 @@ body:
label: Monaco Editor Playground Code label: Monaco Editor Playground Code
description: Please provide the code to reproduce in the [monaco editor playground](https://microsoft.github.io/monaco-editor/playground.html) description: Please provide the code to reproduce in the [monaco editor playground](https://microsoft.github.io/monaco-editor/playground.html)
render: typescript render: typescript
- type: textarea
id: steps
attributes:
label: Reproduction Steps
description: Please describe the steps (in the playground) that lead to the problematic behavior
- type: textarea - type: textarea
id: actual-behavior id: actual-behavior
attributes: attributes:
label: Actual Behavior label: Actual (Problematic) Behavior
description: Please describe the actual behavior, as observed in the playground. description: Please describe the actual (problematic) behavior, as observed in the playground.
- type: textarea - type: textarea
id: expected-behavior id: expected-behavior

View file

@ -0,0 +1,7 @@
---
title: NPM Publishing Failed
assignees: []
labels: bug
---
NPM publishing failed. Check the last GitHub Action log.

View file

@ -11,7 +11,7 @@ jobs:
- uses: actions/setup-node@v2 - uses: actions/setup-node@v2
with: with:
node-version: 14 node-version: 16
- name: Cache node modules - name: Cache node modules
id: cacheNodeModules id: cacheNodeModules
@ -48,7 +48,10 @@ jobs:
run: npm run compile --prefix webpack-plugin run: npm run compile --prefix webpack-plugin
- name: Package using webpack plugin - name: Package using webpack plugin
run: npm run smoketest --prefix webpack-plugin run: npm run package-for-smoketest --prefix webpack-plugin
- name: Package using esbuild
run: npm run package-for-smoketest-esbuild
- name: Run smoke test - name: Run smoke test
run: npm run smoketest run: npm run smoketest

27
.github/workflows/locker.yml vendored Normal file
View file

@ -0,0 +1,27 @@
name: Locker
on:
schedule:
- cron: 21 23 * * * # 5:20pm Redmond
repository_dispatch:
types: [trigger-locker]
workflow_dispatch:
jobs:
main:
runs-on: ubuntu-latest
steps:
- name: Checkout Actions
uses: actions/checkout@v2
with:
repository: 'microsoft/vscode-github-triage-actions'
path: ./actions
ref: stable
- name: Install Actions
run: npm install --production --prefix ./actions
- name: Run Locker
uses: ./actions/locker
with:
daysSinceClose: 45
appInsightsKey: ${{secrets.TRIAGE_ACTIONS_APP_INSIGHTS}}
daysSinceUpdate: 3
ignoredLabel: '*out-of-scope'

View file

@ -0,0 +1,30 @@
name: Needs More Info Closer
on:
schedule:
- cron: 20 12 * * * # 5:20am Redmond
repository_dispatch:
types: [trigger-needs-more-info]
workflow_dispatch:
jobs:
main:
runs-on: ubuntu-latest
steps:
- name: Checkout Actions
uses: actions/checkout@v2
with:
repository: 'microsoft/vscode-github-triage-actions'
path: ./actions
ref: stable
- name: Install Actions
run: npm install --production --prefix ./actions
- name: Run Needs More Info Closer
uses: ./actions/needs-more-info-closer
with:
appInsightsKey: ${{secrets.TRIAGE_ACTIONS_APP_INSIGHTS}}
label: needs more info
closeDays: 7
additionalTeam: 'spahnke|rcjsuen'
closeComment: "This issue has been closed automatically because it needs more information and has not had recent activity. See also our [issue reporting](https://aka.ms/vscodeissuereporting) guidelines.\n\nHappy Coding!"
pingDays: 120
pingComment: "Hey @${assignee}, this issue might need further attention.\n\n@${author}, you can help us out by closing this issue if the problem no longer exists, or adding more information."

25
.github/workflows/pr-chat.yml vendored Normal file
View file

@ -0,0 +1,25 @@
name: PR Chat
on:
pull_request_target:
types: [opened, ready_for_review, closed]
jobs:
main:
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout Actions
uses: actions/checkout@v2
with:
repository: 'microsoft/vscode-github-triage-actions'
ref: stable
path: ./actions
- name: Install Actions
run: npm install --production --prefix ./actions
- name: Run Code Review Chat
uses: ./actions/code-review-chat
with:
token: ${{secrets.GITHUB_TOKEN}}
slack_token: ${{ secrets.SLACK_TOKEN }}
slack_bot_name: 'VSCodeBot'
notification_channel: codereview

View file

@ -12,12 +12,13 @@ on:
default: 'true' default: 'true'
jobs: jobs:
publish: publish:
if: ${{ github.repository == 'microsoft/monaco-editor' }}
name: Publish to npm name: Publish to npm
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/setup-node@v2 - uses: actions/setup-node@v2
with: with:
node-version: 14 node-version: 16
- name: (monaco-editor) checkout - name: (monaco-editor) checkout
uses: actions/checkout@v2 uses: actions/checkout@v2
@ -52,6 +53,11 @@ jobs:
working-directory: './vscode' working-directory: './vscode'
run: yarn --frozen-lockfile --network-timeout 180000 run: yarn --frozen-lockfile --network-timeout 180000
- name: (vscode) Download Playwright
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
working-directory: ./vscode
run: yarn playwright-install
- name: (vscode) Run Hygiene Checks - name: (vscode) Run Hygiene Checks
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
working-directory: './vscode' working-directory: './vscode'
@ -96,6 +102,11 @@ jobs:
working-directory: './vscode' working-directory: './vscode'
run: yarn gulp editor-distro run: yarn gulp editor-distro
- name: Editor ESM sources check
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
working-directory: './vscode/test/monaco'
run: yarn run esm-check
- name: (vscode) Typings validation prep - name: (vscode) Typings validation prep
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
working-directory: './vscode' working-directory: './vscode'
@ -110,21 +121,16 @@ jobs:
echo "import '../out-monaco-editor-core';" > a.ts echo "import '../out-monaco-editor-core';" > a.ts
../node_modules/.bin/tsc --noEmit ../node_modules/.bin/tsc --noEmit
- name: (vscode) Webpack Editor - name: (vscode) Package Editor with Webpack
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
working-directory: ./vscode/test/monaco working-directory: ./vscode/test/monaco
run: yarn run bundle run: yarn run bundle-webpack
- name: (vscode) Compile Editor Tests - name: (vscode) Compile Editor Tests
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
working-directory: ./vscode/test/monaco working-directory: ./vscode/test/monaco
run: yarn run compile run: yarn run compile
- name: (vscode) Download Playwright
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
working-directory: ./vscode
run: yarn playwright-install
- name: (vscode) Run Editor Tests - name: (vscode) Run Editor Tests
if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor_core == 'false' }}
timeout-minutes: 5 timeout-minutes: 5
@ -197,7 +203,7 @@ jobs:
- name: (monaco-editor) Package using webpack plugin - name: (monaco-editor) Package using webpack plugin
if: ${{ steps.state.outputs.skip_monaco_editor == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor == 'false' }}
working-directory: './monaco-editor' working-directory: './monaco-editor'
run: npm run smoketest --prefix webpack-plugin run: npm run package-for-smoketest --prefix webpack-plugin
- name: (monaco-editor) Run smoke test - name: (monaco-editor) Run smoke test
if: ${{ steps.state.outputs.skip_monaco_editor == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor == 'false' }}
@ -219,3 +225,11 @@ jobs:
if: ${{ steps.state.outputs.skip_monaco_editor == 'false' }} if: ${{ steps.state.outputs.skip_monaco_editor == 'false' }}
working-directory: './monaco-editor/release' working-directory: './monaco-editor/release'
run: npm publish --tag ${{ steps.state.outputs.dist_tag }} run: npm publish --tag ${{ steps.state.outputs.dist_tag }}
- name: Create Issue On Failure
if: failure()
uses: JasonEtco/create-an-issue@9e6213aec58987fa7d2f4deb8b256b99e63107a2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
filename: ./monaco-editor/.github/publish-failure-issue-template.md

View file

@ -16,7 +16,7 @@ jobs:
- uses: actions/setup-node@v2 - uses: actions/setup-node@v2
with: with:
node-version: 14 node-version: 16
- name: Cache node modules - name: Cache node modules
id: cacheNodeModules id: cacheNodeModules

View file

@ -9,7 +9,7 @@
/samples/browser-esm-webpack-small/dist/*.js /samples/browser-esm-webpack-small/dist/*.js
/samples/browser-esm-webpack-typescript/dist/*.js /samples/browser-esm-webpack-typescript/dist/*.js
/samples/browser-esm-webpack-typescript-react/dist/*.js /samples/browser-esm-webpack-typescript-react/dist/*.js
/src/typescript/lib/ /src/language/typescript/lib/
/test/manual/generated/ /test/manual/generated/
/website/lib/ /website/lib/
/website/typedoc/monaco.d.ts /website/typedoc/monaco.d.ts

View file

@ -1,6 +1,52 @@
# Monaco Editor Changelog # Monaco Editor Changelog
## [0.32.0] (TBD) ## [0.34.0] (Unreleased)
- Introduction of `IEditor.createDecorationsCollection` API
- New function `removeAllMarkers` to remove all markers
- Support for light high contrast theme
- Introduction of `BracketPairColorizationOptions.independentColorPoolPerBracketType`
- Introduction of `PositionAffinity.LeftOfInjectedText` and `PositionAffinity.RightOfInjectedText`
- Introduction of `IEditorOptions.showFoldingControls: 'never'`
- Introduction of `IDiffEditorBaseOptions.renderMarginRevertIcon: boolean`
- Inline Quick Suggestions
- Introduction of `IContentWidgetPosition.positionAffinity`
- Provider can now be registered for a `LanguageSelector`
### Breaking Changes
- `IEditorInlayHintsOptions` tweaks
- Iteration on `InlineCompletion` API
- `WorkspaceFileEdit` -> `IWorkspaceFileEdit`
- `oldUri` -> `oldResource`
- `newUri` -> `newResource`
- `WorkspaceTextEdit` -> `IWorkspaceTextEdit`
- `edit` -> `textEdit` (now supports `insertAsSnippet`)
- `modelVersionId?: number` -> `versionId: number | undefined`
- `InlayHint` API tweaks
- Soft deprecation of `ICodeEditor.deltaDecorations`, no adoption required. `IEditor.createDecorationsCollection` API should be used instead.
## [0.33.0]
- The first parameter of all `monaco.languages.register*Provider` functions has changed to take a `DocumentSelector` instead of a single `languageId`
- The `Environment.getWorker` function can now return a `Promise`
### Breaking Changes
- `InlayHintKind.Other` is removed.
### Thank you
Contributions to `monaco-editor`:
- [@Dan1ve (Daniel Veihelmann)](https://github.com/Dan1ve): Make Vite sample code Firefox compatible [PR #2991](https://github.com/microsoft/monaco-editor/pull/2991)
- [@philipturner (Philip Turner)](https://github.com/philipturner): Add `@noDerivative` modifier to Swift [PR #2957](https://github.com/microsoft/monaco-editor/pull/2957)
## [0.32.1] (04.02.2022)
- fixes [an issue with service initialization](https://github.com/microsoft/monaco-editor/issues/2941).
## [0.32.0] (03.02.2022)
### Breaking Changes ### Breaking Changes
@ -8,6 +54,24 @@
- `IDiffEditor.getDomNode()` has been renamed to `IDiffEditor.getContainerDomNode()`. - `IDiffEditor.getDomNode()` has been renamed to `IDiffEditor.getContainerDomNode()`.
- `InlayHint.text` has been replaced by `InlayHint.label` and `InlayHintsProvider.provideInlayHints` now returns an `InlayHintList`. - `InlayHint.text` has been replaced by `InlayHint.label` and `InlayHintsProvider.provideInlayHints` now returns an `InlayHintList`.
### Thank you
Contributions to `monaco-editor`:
- [@blutorange (Andre Wachsmuth)](https://github.com/blutorange): Implements #2383 Add syntax modes for FreeMarker template language [PR #2847](https://github.com/microsoft/monaco-editor/pull/2847)
- [@forensicmike (forensicmike1)](https://github.com/forensicmike): Add "cd monaco-editor" to the step by step commandline instructions for cloning and running the samples [PR #2894](https://github.com/microsoft/monaco-editor/pull/2894)
- [@juan-carlos-diaz](https://github.com/juan-carlos-diaz): Fix #2851 Highlight correctly the attributes and identifiers (with dashes) for Shell language [PR #2871](https://github.com/microsoft/monaco-editor/pull/2871)
- [@MasterOdin (Matthew Peveler)](https://github.com/MasterOdin): Only run publish workflow on main monaco-editor repo [PR #2926](https://github.com/microsoft/monaco-editor/pull/2926)
- [@philipturner (Philip Turner)](https://github.com/philipturner)
- Update Swift language specification to version 5.5 [PR #2855](https://github.com/microsoft/monaco-editor/pull/2855)
- Add @preconcurrency to Swift declaration attributes [PR #2924](https://github.com/microsoft/monaco-editor/pull/2924)
- [@rcjsuen (Remy Suen)](https://github.com/rcjsuen): Support hyphenated HTML tags in Markdown syntax [PR #2864](https://github.com/microsoft/monaco-editor/pull/2864)
- [@resistdesign (Ryan Graff)](https://github.com/resistdesign): doc: (samples) Simplify Browser ESM Parcel build [PR #2832](https://github.com/microsoft/monaco-editor/pull/2832)
- [@ValeraS (Valeriy)](https://github.com/ValeraS)
- fix(monaco-editor-webpack-plugin): load monaco-editor with webpack 4 [PR #2818](https://github.com/microsoft/monaco-editor/pull/2818)
- tune(monaco-editor-webpack-plugin): expose plugin options type [PR #2853](https://github.com/microsoft/monaco-editor/pull/2853)
- [@ZusorCode (Tobias Messner)](https://github.com/ZusorCode): Add .cjs extension for javascript files [PR #2929](https://github.com/microsoft/monaco-editor/pull/2929)
## [0.31.1] (14.12.2021) ## [0.31.1] (14.12.2021)
- Fixes [a problem with missing colors](https://github.com/microsoft/monaco-editor/issues/2822) - Fixes [a problem with missing colors](https://github.com/microsoft/monaco-editor/issues/2822)

View file

@ -73,7 +73,7 @@ Open [http://localhost:8080/monaco-editor/test/manual/?editor=src](http://localh
/src/monaco-editor> npm run compile --prefix webpack-plugin /src/monaco-editor> npm run compile --prefix webpack-plugin
# package using the webpack plugin # package using the webpack plugin
/src/monaco-editor> npm run smoketest --prefix webpack-plugin /src/monaco-editor> npm run package-for-smoketest --prefix webpack-plugin
# run the smoketest # run the smoketest
/src/monaco-editor> npm run smoketest-debug /src/monaco-editor> npm run smoketest-debug

View file

@ -13,14 +13,13 @@
- update `package.json` and bump `"version"` as necessary - update `package.json` and bump `"version"` as necessary
- update `package.json` and edit `"vscode"` to point to the vscode repo commit that should be shipped at `monaco-editor-core` (both `monaco-editor-core` and `monaco-editor` will be published under the same version defined in `package.json`). - update `package.json` and edit `"vscode"` to point to the vscode repo commit that should be shipped at `monaco-editor-core` (both `monaco-editor-core` and `monaco-editor` will be published under the same version defined in `package.json`).
- write entry in `CHANGELOG.md`
- API Changes / Breaking Changes / New and noteworthy
- Thank you ([use this tool](https://vscode-tools.azurewebsites.net/acknowledgement/))
- trigger a build using [`Publish to npm`](https://github.com/microsoft/monaco-editor/actions/workflows/publish.yml) and type false when asked "is nightly?" - trigger a build using [`Publish to npm`](https://github.com/microsoft/monaco-editor/actions/workflows/publish.yml) and type false when asked "is nightly?"
- if the publish succeeded, run `git tag 0.x.y` and `git push origin 0.x.y` - if the publish succeeded, run `git tag 0.x.y` and `git push origin 0.x.y`
- edit `package.json` and update the `"monaco-editor-core"` dev dependency. - edit `package.json` and update the `"monaco-editor-core"` dev dependency.
- run `npm install` - run `npm install`
- run `npm run release`
- write entry in `CHANGELOG.md`
- API Changes / Breaking Changes / New and noteworthy
- Thank you ([use this tool](https://vscode-tools.azurewebsites.net/acknowledgement/))
#### 8. Publish new webpack plugin #### 8. Publish new webpack plugin

View file

@ -3,11 +3,9 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import glob from 'glob';
import { tsc, dts, buildESM, buildAMD } from './utils';
const glob = require('glob'); import { copyFile, removeDir } from './fs';
const { tsc, dts, buildESM, buildAMD } = require('../build/utils');
const { copyFile, removeDir } = require('../build/fs');
removeDir(`out`); removeDir(`out`);
@ -15,20 +13,24 @@ tsc(`src/tsconfig.json`);
//#region Type Defintion //#region Type Defintion
dts(`out/amd/css/monaco.contribution.d.ts`, `out/release/css/monaco.d.ts`, 'monaco.languages.css');
dts( dts(
`out/amd/html/monaco.contribution.d.ts`, `out/amd/language/css/monaco.contribution.d.ts`,
`out/release/html/monaco.d.ts`, `out/release/css.d.ts`,
'monaco.languages.css'
);
dts(
`out/amd/language/html/monaco.contribution.d.ts`,
`out/release/html.d.ts`,
'monaco.languages.html' 'monaco.languages.html'
); );
dts( dts(
`out/amd/json/monaco.contribution.d.ts`, `out/amd/language/json/monaco.contribution.d.ts`,
`out/release/json/monaco.d.ts`, `out/release/json.d.ts`,
'monaco.languages.json' 'monaco.languages.json'
); );
dts( dts(
`out/amd/typescript/monaco.contribution.d.ts`, `out/amd/language/typescript/monaco.contribution.d.ts`,
`out/release/typescript/monaco.d.ts`, `out/release/typescript.d.ts`,
'monaco.languages.typescript' 'monaco.languages.typescript'
); );
@ -37,24 +39,29 @@ dts(
//#region css //#region css
buildESM({ buildESM({
base: 'css', base: 'language/css',
entryPoints: ['src/css/monaco.contribution.ts', 'src/css/cssMode.ts', 'src/css/css.worker.ts'], entryPoints: [
external: ['monaco-editor-core', '*/cssMode'] 'src/language/css/monaco.contribution.ts',
'src/language/css/cssMode.ts',
'src/language/css/css.worker.ts'
],
external: ['monaco-editor-core', '*/cssMode', '*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'css', base: 'language/css',
entryPoint: 'src/css/monaco.contribution.ts', entryPoint: 'src/language/css/monaco.contribution.ts',
amdModuleId: 'vs/language/css/monaco.contribution', amdModuleId: 'vs/language/css/monaco.contribution',
amdDependencies: ['vs/editor/editor.api'] amdDependencies: ['vs/editor/editor.api']
}); });
buildAMD({ buildAMD({
base: 'css', base: 'language/css',
entryPoint: 'src/css/cssMode.ts', entryPoint: 'src/language/css/cssMode.ts',
amdModuleId: 'vs/language/css/cssMode' amdModuleId: 'vs/language/css/cssMode',
external: ['*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'css', base: 'language/css',
entryPoint: 'src/css/cssWorker.ts', entryPoint: 'src/language/css/cssWorker.ts',
amdModuleId: 'vs/language/css/cssWorker' amdModuleId: 'vs/language/css/cssWorker'
}); });
@ -63,28 +70,29 @@ buildAMD({
//#region html //#region html
buildESM({ buildESM({
base: 'html', base: 'language/html',
entryPoints: [ entryPoints: [
'src/html/monaco.contribution.ts', 'src/language/html/monaco.contribution.ts',
'src/html/htmlMode.ts', 'src/language/html/htmlMode.ts',
'src/html/html.worker.ts' 'src/language/html/html.worker.ts'
], ],
external: ['monaco-editor-core', '*/htmlMode'] external: ['monaco-editor-core', '*/htmlMode', '*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'html', base: 'language/html',
entryPoint: 'src/html/monaco.contribution.ts', entryPoint: 'src/language/html/monaco.contribution.ts',
amdModuleId: 'vs/language/html/monaco.contribution', amdModuleId: 'vs/language/html/monaco.contribution',
amdDependencies: ['vs/editor/editor.api'] amdDependencies: ['vs/editor/editor.api']
}); });
buildAMD({ buildAMD({
base: 'html', base: 'language/html',
entryPoint: 'src/html/htmlMode.ts', entryPoint: 'src/language/html/htmlMode.ts',
amdModuleId: 'vs/language/html/htmlMode' amdModuleId: 'vs/language/html/htmlMode',
external: ['*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'html', base: 'language/html',
entryPoint: 'src/html/htmlWorker.ts', entryPoint: 'src/language/html/htmlWorker.ts',
amdModuleId: 'vs/language/html/htmlWorker' amdModuleId: 'vs/language/html/htmlWorker'
}); });
@ -93,28 +101,29 @@ buildAMD({
//#region json //#region json
buildESM({ buildESM({
base: 'json', base: 'language/json',
entryPoints: [ entryPoints: [
'src/json/monaco.contribution.ts', 'src/language/json/monaco.contribution.ts',
'src/json/jsonMode.ts', 'src/language/json/jsonMode.ts',
'src/json/json.worker.ts' 'src/language/json/json.worker.ts'
], ],
external: ['monaco-editor-core', '*/jsonMode'] external: ['monaco-editor-core', '*/jsonMode', '*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'json', base: 'language/json',
entryPoint: 'src/json/monaco.contribution.ts', entryPoint: 'src/language/json/monaco.contribution.ts',
amdModuleId: 'vs/language/json/monaco.contribution', amdModuleId: 'vs/language/json/monaco.contribution',
amdDependencies: ['vs/editor/editor.api'] amdDependencies: ['vs/editor/editor.api']
}); });
buildAMD({ buildAMD({
base: 'json', base: 'language/json',
entryPoint: 'src/json/jsonMode.ts', entryPoint: 'src/language/json/jsonMode.ts',
amdModuleId: 'vs/language/json/jsonMode' amdModuleId: 'vs/language/json/jsonMode',
external: ['*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'json', base: 'language/json',
entryPoint: 'src/json/jsonWorker.ts', entryPoint: 'src/language/json/jsonWorker.ts',
amdModuleId: 'vs/language/json/jsonWorker' amdModuleId: 'vs/language/json/jsonWorker'
}); });
@ -123,33 +132,34 @@ buildAMD({
//#region typescript //#region typescript
copyFile( copyFile(
`src/typescript/lib/typescriptServices-amd.js`, `src/language/typescript/lib/typescriptServices-amd.js`,
`out/amd/typescript/lib/typescriptServices.js` `out/amd/language/typescript/lib/typescriptServices.js`
); );
buildESM({ buildESM({
base: 'typescript', base: 'language/typescript',
entryPoints: [ entryPoints: [
'src/typescript/monaco.contribution.ts', 'src/language/typescript/monaco.contribution.ts',
'src/typescript/tsMode.ts', 'src/language/typescript/tsMode.ts',
'src/typescript/ts.worker.ts' 'src/language/typescript/ts.worker.ts'
], ],
external: ['monaco-editor-core', '*/tsMode'] external: ['monaco-editor-core', '*/tsMode', '*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'typescript', base: 'language/typescript',
entryPoint: 'src/typescript/monaco.contribution.ts', entryPoint: 'src/language/typescript/monaco.contribution.ts',
amdModuleId: 'vs/language/typescript/monaco.contribution', amdModuleId: 'vs/language/typescript/monaco.contribution',
amdDependencies: ['vs/editor/editor.api'] amdDependencies: ['vs/editor/editor.api']
}); });
buildAMD({ buildAMD({
base: 'typescript', base: 'language/typescript',
entryPoint: 'src/typescript/tsMode.ts', entryPoint: 'src/language/typescript/tsMode.ts',
amdModuleId: 'vs/language/typescript/tsMode' amdModuleId: 'vs/language/typescript/tsMode',
external: ['*/monaco.contribution']
}); });
buildAMD({ buildAMD({
base: 'typescript', base: 'language/typescript',
entryPoint: 'src/typescript/tsWorker.ts', entryPoint: 'src/language/typescript/tsWorker.ts',
amdModuleId: 'vs/language/typescript/tsWorker' amdModuleId: 'vs/language/typescript/tsWorker'
}); });

View file

@ -1,8 +0,0 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Resolves with the global monaco API
export = (<any>self).monaco;

View file

@ -3,18 +3,14 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import * as fs from 'fs';
import * as path from 'path';
const fs = require('fs');
const path = require('path');
const REPO_ROOT = path.join(__dirname, '../'); const REPO_ROOT = path.join(__dirname, '../');
const existingDirCache = new Set(); const existingDirCache = new Set();
/**
* @param {string} dirname export function ensureDir(dirname: string) {
*/
function ensureDir(dirname) {
/** @type {string[]} */ /** @type {string[]} */
const dirs = []; const dirs = [];
@ -32,15 +28,11 @@ function ensureDir(dirname) {
} }
}); });
} }
exports.ensureDir = ensureDir;
/** /**
* Copy a file. * Copy a file.
*
* @param {string} _source
* @param {string} _destination
*/ */
function copyFile(_source, _destination) { export function copyFile(_source: string, _destination: string) {
const source = path.join(REPO_ROOT, _source); const source = path.join(REPO_ROOT, _source);
const destination = path.join(REPO_ROOT, _destination); const destination = path.join(REPO_ROOT, _destination);
@ -49,15 +41,11 @@ function copyFile(_source, _destination) {
console.log(`Copied ${_source} to ${_destination}`); console.log(`Copied ${_source} to ${_destination}`);
} }
exports.copyFile = copyFile;
/** /**
* Remove a directory and all its contents. * Remove a directory and all its contents.
*
* @param {string} _dirPath
* @param {((filename:string)=>boolean)} [keep]
*/ */
function removeDir(_dirPath, keep) { export function removeDir(_dirPath: string, keep?: (filename: string) => boolean) {
if (typeof keep === 'undefined') { if (typeof keep === 'undefined') {
keep = () => false; keep = () => false;
} }
@ -68,18 +56,13 @@ function removeDir(_dirPath, keep) {
rmDir(dirPath, _dirPath); rmDir(dirPath, _dirPath);
console.log(`Deleted ${_dirPath}`); console.log(`Deleted ${_dirPath}`);
/** function rmDir(dirPath: string, relativeDirPath: string): boolean {
* @param {string} dirPath
* @param {string} relativeDirPath
* @returns {boolean}
*/
function rmDir(dirPath, relativeDirPath) {
let keepsFiles = false; let keepsFiles = false;
const entries = fs.readdirSync(dirPath); const entries = fs.readdirSync(dirPath);
for (const entry of entries) { for (const entry of entries) {
const filePath = path.join(dirPath, entry); const filePath = path.join(dirPath, entry);
const relativeFilePath = path.join(relativeDirPath, entry); const relativeFilePath = path.join(relativeDirPath, entry);
if (keep(relativeFilePath)) { if (keep!(relativeFilePath)) {
keepsFiles = true; keepsFiles = true;
continue; continue;
} }
@ -95,4 +78,3 @@ function removeDir(_dirPath, keep) {
return keepsFiles; return keepsFiles;
} }
} }
exports.removeDir = removeDir;

View file

@ -3,12 +3,10 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import path = require('path');
import fs = require('fs');
const path = require('path'); import child_process = require('child_process');
const fs = require('fs'); import { REPO_ROOT } from './utils';
const child_process = require('child_process');
const { REPO_ROOT } = require('./utils');
const generatedNote = `// const generatedNote = `//
// **NOTE**: Do not edit directly! This file is generated using \`npm run import-typescript\` // **NOTE**: Do not edit directly! This file is generated using \`npm run import-typescript\`
@ -16,7 +14,7 @@ const generatedNote = `//
`; `;
const TYPESCRIPT_LIB_SOURCE = path.join(REPO_ROOT, 'node_modules/typescript/lib'); const TYPESCRIPT_LIB_SOURCE = path.join(REPO_ROOT, 'node_modules/typescript/lib');
const TYPESCRIPT_LIB_DESTINATION = path.join(REPO_ROOT, 'src/typescript/lib'); const TYPESCRIPT_LIB_DESTINATION = path.join(REPO_ROOT, 'src/language/typescript/lib');
(function () { (function () {
try { try {
@ -74,6 +72,11 @@ export const typescriptVersion = "${typeScriptDependencyVersion}";\n`
'/* MONACOCHANGE */false/* END MONACOCHANGE */' '/* MONACOCHANGE */false/* END MONACOCHANGE */'
); );
tsServices = tsServices.replace(
/module.exports = ts;/m,
'/* MONACOCHANGE */ /*module.exports = ts;*/ /* END MONACOCHANGE */'
);
// Flag any new require calls (outside comments) so they can be corrected preemptively. // Flag any new require calls (outside comments) so they can be corrected preemptively.
// To avoid missing cases (or using an even more complex regex), temporarily remove comments // To avoid missing cases (or using an even more complex regex), temporarily remove comments
// about require() and then check for lines actually calling require(). // about require() and then check for lines actually calling require().

View file

@ -3,14 +3,12 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import glob = require('glob');
import path = require('path');
const glob = require('glob'); import fs = require('fs');
const path = require('path'); import cp = require('child_process');
const fs = require('fs');
const cp = require('child_process');
const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm'; const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const { REPO_ROOT } = require('../utils'); import { REPO_ROOT } from '../utils';
const files = glob.sync('**/package.json', { const files = glob.sync('**/package.json', {
cwd: REPO_ROOT, cwd: REPO_ROOT,
@ -29,18 +27,16 @@ for (const file of files) {
} }
function npmInstall(location) { function npmInstall(location) {
/** @type {'inherit'} */
const stdio = 'inherit'; const stdio = 'inherit';
const opts = {
env: process.env,
cwd: location,
stdio
};
const args = ['install']; const args = ['install'];
console.log(`Installing dependencies in ${location}...`); console.log(`Installing dependencies in ${location}...`);
console.log(`$ npm ${args.join(' ')}`); console.log(`$ npm ${args.join(' ')}`);
const result = cp.spawnSync(npm, args, opts); const result = cp.spawnSync(npm, args, {
env: process.env,
cwd: location,
stdio
});
if (result.error || result.status !== 0) { if (result.error || result.status !== 0) {
process.exit(1); process.exit(1);

View file

@ -3,12 +3,10 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import glob from 'glob';
import path from 'path';
const glob = require('glob'); import fs from 'fs';
const path = require('path'); import { REPO_ROOT } from '../utils';
const fs = require('fs');
const { REPO_ROOT } = require('../utils');
const files = glob.sync('**/package-lock.json', { const files = glob.sync('**/package-lock.json', {
cwd: REPO_ROOT, cwd: REPO_ROOT,

View file

@ -3,8 +3,8 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
const cp = require('child_process'); import cp = require('child_process');
const path = require('path'); import path = require('path');
function huskyInstall() { function huskyInstall() {
console.log(`Installing husky hooks...`); console.log(`Installing husky hooks...`);

View file

@ -3,24 +3,12 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import path = require('path');
import fs = require('fs');
/** import { REPO_ROOT, readFiles, writeFiles, IFile } from '../build/utils';
* @typedef { { src:string; built:string; releaseDev:string; releaseMin:string; } } ICorePaths import { removeDir } from '../build/fs';
* @typedef { { dev:string; min:string; esm: string; } } IPluginPaths import ts = require('typescript');
* @typedef { { name:string; contrib:string; modulePrefix:string; rootPath:string; paths:IPluginPaths } } IPlugin import { generateMetadata } from './releaseMetadata';
* @typedef { { METADATA: {CORE:{paths:ICorePaths}; PLUGINS:IPlugin[];} } } IMetadata
*/
/** @typedef {import('../build/utils').IFile} IFile */
const path = require('path');
const fs = require('fs');
const { REPO_ROOT, readFiles, writeFiles } = require('../build/utils');
const { removeDir } = require('../build/fs');
const ts = require('typescript');
/**@type { IMetadata } */
const metadata = require('../metadata.js');
const { generateMetadata } = require('./releaseMetadata');
removeDir(`release`); removeDir(`release`);
@ -76,33 +64,19 @@ generateMetadata();
/** /**
* Release to `dev` or `min`. * Release to `dev` or `min`.
* @param {'dev'|'min'} type
*/ */
function AMD_releaseOne(type) { function AMD_releaseOne(type: 'dev' | 'min') {
const coreFiles = readFiles(`node_modules/monaco-editor-core/${type}/**/*`, { const coreFiles = readFiles(`node_modules/monaco-editor-core/${type}/**/*`, {
base: `node_modules/monaco-editor-core/${type}` base: `node_modules/monaco-editor-core/${type}`
}); });
AMD_addPluginContribs(type, coreFiles); AMD_addPluginContribs(type, coreFiles);
writeFiles(coreFiles, `release/${type}`); writeFiles(coreFiles, `release/${type}`);
for (const plugin of metadata.METADATA.PLUGINS) { const pluginFiles = readFiles(`out/release/${type}/**/*`, {
AMD_releasePlugin(plugin, type, `release/${type}`); base: `out/release/${type}`,
} ignore: ['**/monaco.contribution.js']
} });
writeFiles(pluginFiles, `release/${type}`);
/**
* Release a plugin to `dev` or `min`.
* @param {IPlugin} plugin
* @param {'dev'|'min'} type
* @param {string} destinationPath
*/
function AMD_releasePlugin(plugin, type, destinationPath) {
const pluginPath = path.join(plugin.rootPath, plugin.paths[type]); // dev or min
const contribPath =
path.join(pluginPath, plugin.contrib.substring(plugin.modulePrefix.length)) + '.js';
const files = readFiles(`${pluginPath}/**/*`, { base: pluginPath, ignore: [contribPath] });
writeFiles(files, path.join(destinationPath, plugin.modulePrefix));
} }
/** /**
@ -110,11 +84,8 @@ function AMD_releasePlugin(plugin, type, destinationPath) {
* - rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main' * - rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
* - append monaco.contribution modules from plugins * - append monaco.contribution modules from plugins
* - append new AMD module 'vs/editor/editor.main' that stiches things together * - append new AMD module 'vs/editor/editor.main' that stiches things together
*
* @param {'dev'|'min'} type
* @param {IFile[]} files
*/ */
function AMD_addPluginContribs(type, files) { function AMD_addPluginContribs(type: 'dev' | 'min', files: IFile[]) {
for (const file of files) { for (const file of files) {
if (!/editor\.main\.js$/.test(file.path)) { if (!/editor\.main\.js$/.test(file.path)) {
continue; continue;
@ -125,25 +96,21 @@ function AMD_addPluginContribs(type, files) {
// Rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main' // Rename the AMD module 'vs/editor/editor.main' to 'vs/editor/edcore.main'
contents = contents.replace(/"vs\/editor\/editor\.main\"/, '"vs/editor/edcore.main"'); contents = contents.replace(/"vs\/editor\/editor\.main\"/, '"vs/editor/edcore.main"');
/** @type {string[]} */ const pluginFiles = readFiles(`out/release/${type}/**/monaco.contribution.js`, {
let extraContent = []; base: `out/release/${type}`
/** @type {string[]} */ });
let allPluginsModuleIds = [];
metadata.METADATA.PLUGINS.forEach(function (plugin) { const extraContent = pluginFiles.map((file) => {
allPluginsModuleIds.push(plugin.contrib); return file.contents
const pluginPath = path.join(plugin.rootPath, plugin.paths[type]); // dev or min .toString()
const contribPath = .replace(
path.join(REPO_ROOT, pluginPath, plugin.contrib.substring(plugin.modulePrefix.length)) + /define\((['"][a-z\/\-]+\/fillers\/monaco-editor-core['"]),\[\],/,
'.js'; "define($1,['vs/editor/editor.api'],"
let contribContents = fs.readFileSync(contribPath).toString(); );
});
contribContents = contribContents.replace( const allPluginsModuleIds = pluginFiles.map((file) => {
/define\((['"][a-z\/\-]+\/fillers\/monaco-editor-core['"]),\[\],/, return file.path.replace(/\.js$/, '');
"define($1,['vs/editor/editor.api'],"
);
extraContent.push(contribContents);
}); });
extraContent.push( extraContent.push(
@ -176,22 +143,16 @@ function ESM_release() {
ESM_addPluginContribs(coreFiles); ESM_addPluginContribs(coreFiles);
writeFiles(coreFiles, `release/esm`); writeFiles(coreFiles, `release/esm`);
for (const plugin of metadata.METADATA.PLUGINS) { ESM_releasePlugins();
ESM_releasePlugin(plugin, `release/esm`);
}
} }
/** /**
* Release a plugin to `esm`. * Release a plugin to `esm`.
* Adds a dependency to 'vs/editor/editor.api' in contrib files in order for `monaco` to be defined. * Adds a dependency to 'vs/editor/editor.api' in contrib files in order for `monaco` to be defined.
* Rewrites imports for 'monaco-editor-core/**' * Rewrites imports for 'monaco-editor-core/**'
* @param {IPlugin} plugin
* @param {string} destinationPath
*/ */
function ESM_releasePlugin(plugin, destinationPath) { function ESM_releasePlugins() {
const pluginPath = path.join(plugin.rootPath, plugin.paths['esm']); const files = readFiles(`out/release/esm/**/*`, { base: 'out/release/esm/' });
const files = readFiles(`${pluginPath}/**/*`, { base: pluginPath });
for (const file of files) { for (const file of files) {
if (!/(\.js$)|(\.ts$)/.test(file.path)) { if (!/(\.js$)|(\.ts$)/.test(file.path)) {
@ -217,10 +178,9 @@ function ESM_releasePlugin(plugin, destinationPath) {
importText = 'monaco-editor-core/esm/vs/editor/editor.api'; importText = 'monaco-editor-core/esm/vs/editor/editor.api';
} }
const myFileDestPath = path.join(plugin.modulePrefix, file.path);
const importFilePath = importText.substring('monaco-editor-core/esm/'.length); const importFilePath = importText.substring('monaco-editor-core/esm/'.length);
let relativePath = path let relativePath = path
.relative(path.dirname(myFileDestPath), importFilePath) .relative(path.dirname(file.path), importFilePath)
.replace(/\\/g, '/'); .replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) { if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath; relativePath = './' + relativePath;
@ -238,9 +198,8 @@ function ESM_releasePlugin(plugin, destinationPath) {
continue; continue;
} }
const myFileDestPath = path.join(plugin.modulePrefix, file.path);
const apiFilePath = 'vs/editor/editor.api'; const apiFilePath = 'vs/editor/editor.api';
let relativePath = path.relative(path.dirname(myFileDestPath), apiFilePath).replace(/\\/g, '/'); let relativePath = path.relative(path.dirname(file.path), apiFilePath).replace(/\\/g, '/');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) { if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath; relativePath = './' + relativePath;
} }
@ -251,14 +210,13 @@ function ESM_releasePlugin(plugin, destinationPath) {
} }
ESM_addImportSuffix(files); ESM_addImportSuffix(files);
writeFiles(files, path.join(destinationPath, plugin.modulePrefix)); writeFiles(files, `release/esm`);
} }
/** /**
* Adds `.js` to all import statements. * Adds `.js` to all import statements.
* @param {IFile[]} files
*/ */
function ESM_addImportSuffix(files) { function ESM_addImportSuffix(files: IFile[]) {
for (const file of files) { for (const file of files) {
if (!/\.js$/.test(file.path)) { if (!/\.js$/.test(file.path)) {
continue; continue;
@ -272,7 +230,8 @@ function ESM_addImportSuffix(files) {
const pos = info.importedFiles[i].pos; const pos = info.importedFiles[i].pos;
const end = info.importedFiles[i].end; const end = info.importedFiles[i].end;
if (/\.css$/.test(importText)) { if (/(\.css)|(\.js)$/.test(importText)) {
// A CSS import or an import already using .js
continue; continue;
} }
@ -286,9 +245,8 @@ function ESM_addImportSuffix(files) {
/** /**
* - Rename esm/vs/editor/editor.main.js to esm/vs/editor/edcore.main.js * - Rename esm/vs/editor/editor.main.js to esm/vs/editor/edcore.main.js
* - Create esm/vs/editor/editor.main.js that that stiches things together * - Create esm/vs/editor/editor.main.js that that stiches things together
* @param {IFile[]} files
*/ */
function ESM_addPluginContribs(files) { function ESM_addPluginContribs(files: IFile[]) {
for (const file of files) { for (const file of files) {
if (!/editor\.main\.js$/.test(file.path)) { if (!/editor\.main\.js$/.test(file.path)) {
continue; continue;
@ -298,20 +256,20 @@ function ESM_addPluginContribs(files) {
const mainFileDestPath = 'vs/editor/editor.main.js'; const mainFileDestPath = 'vs/editor/editor.main.js';
/** @type {string[]} */ const mainFileImports = readFiles(`out/release/esm/**/monaco.contribution.js`, {
let mainFileImports = []; base: `out/release/esm`
for (const plugin of metadata.METADATA.PLUGINS) { }).map((file) => {
const contribDestPath = plugin.contrib;
let relativePath = path let relativePath = path
.relative(path.dirname(mainFileDestPath), contribDestPath) .relative(path.dirname(mainFileDestPath), file.path)
.replace(/\\/g, '/'); .replace(/\\/g, '/')
.replace(/\.js$/, '');
if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) { if (!/(^\.\/)|(^\.\.\/)/.test(relativePath)) {
relativePath = './' + relativePath; relativePath = './' + relativePath;
} }
mainFileImports.push(relativePath); return relativePath;
} });
const mainFileContents = const mainFileContents =
mainFileImports.map((name) => `import '${name}';`).join('\n') + mainFileImports.map((name) => `import '${name}';`).join('\n') +
@ -334,17 +292,10 @@ function releaseDTS() {
let contents = monacodts.contents.toString(); let contents = monacodts.contents.toString();
/** @type {string[]} */ const extraContent = readFiles('out/release/*.d.ts', {
const extraContent = []; base: 'out/release/'
metadata.METADATA.PLUGINS.forEach(function (plugin) { }).map((file) => {
const dtsPath = path.join(plugin.rootPath, './monaco.d.ts'); return file.contents.toString().replace(/\/\/\/ <reference.*\n/m, '');
try {
let plugindts = fs.readFileSync(dtsPath).toString();
plugindts = plugindts.replace(/\/\/\/ <reference.*\n/m, '');
extraContent.push(plugindts);
} catch (err) {
return;
}
}); });
contents = contents =
@ -379,10 +330,8 @@ function releaseDTS() {
/** /**
* Transforms a .d.ts which uses internal modules (namespaces) to one which is usable with external modules * Transforms a .d.ts which uses internal modules (namespaces) to one which is usable with external modules
* This function is duplicated in the `vscode` repo. * This function is duplicated in the `vscode` repo.
* @param {string} contents
* @returns string
*/ */
function toExternalDTS(contents) { function toExternalDTS(contents: string): string {
let lines = contents.split(/\r\n|\r|\n/); let lines = contents.split(/\r\n|\r|\n/);
let killNextCloseCurlyBrace = false; let killNextCloseCurlyBrace = false;
for (let i = 0; i < lines.length; i++) { for (let i = 0; i < lines.length; i++) {
@ -426,10 +375,8 @@ function toExternalDTS(contents) {
/** /**
* Normalize line endings and ensure consistent 4 spaces indentation * Normalize line endings and ensure consistent 4 spaces indentation
* @param {string} contents
* @returns {string}
*/ */
function cleanFile(contents) { function cleanFile(contents: string): string {
return contents return contents
.split(/\r\n|\r|\n/) .split(/\r\n|\r|\n/)
.map(function (line) { .map(function (line) {

View file

@ -3,13 +3,11 @@
* Licensed under the MIT License. See LICENSE in the project root for license information. * Licensed under the MIT License. See LICENSE in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import glob = require('glob');
import path = require('path');
const glob = require('glob'); import fs = require('fs');
const path = require('path'); import { REPO_ROOT } from './utils';
const fs = require('fs'); import { ensureDir } from './fs';
const { REPO_ROOT } = require('./utils');
const { ensureDir } = require('./fs');
const customFeatureLabels = { const customFeatureLabels = {
'vs/editor/browser/controller/coreCommands': 'coreCommands', 'vs/editor/browser/controller/coreCommands': 'coreCommands',
@ -25,10 +23,7 @@ const customFeatureLabels = {
'vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess': 'quickHelp' 'vs/editor/standalone/browser/quickAccess/standaloneHelpQuickAccess': 'quickHelp'
}; };
/** function getBasicLanguages(): Promise<{ label: string; entry: string }[]> {
* @returns { Promise<{ label: string; entry: string; }[]> }
*/
function getBasicLanguages() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
glob( glob(
'./release/esm/vs/basic-languages/*/*.contribution.js', './release/esm/vs/basic-languages/*/*.contribution.js',
@ -54,10 +49,7 @@ function getBasicLanguages() {
}); });
} }
/** function readAdvancedLanguages(): Promise<string[]> {
* @returns { Promise<string[]> }
*/
function readAdvancedLanguages() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
glob( glob(
'./release/esm/vs/language/*/monaco.contribution.js', './release/esm/vs/language/*/monaco.contribution.js',
@ -78,10 +70,9 @@ function readAdvancedLanguages() {
}); });
} }
/** function getAdvancedLanguages(): Promise<
* @returns { Promise<{ label: string; entry: string; worker: { id: string; entry: string; }; }[]> } { label: string; entry: string; worker: { id: string; entry: string } }[]
*/ > {
function getAdvancedLanguages() {
return readAdvancedLanguages().then((languages) => { return readAdvancedLanguages().then((languages) => {
let result = []; let result = [];
for (const lang of languages) { for (const lang of languages) {
@ -112,11 +103,11 @@ function getAdvancedLanguages() {
} }
} }
function generateMetadata() { export function generateMetadata() {
return Promise.all([getBasicLanguages(), getAdvancedLanguages()]).then( return Promise.all([getBasicLanguages(), getAdvancedLanguages()]).then(
([basicLanguages, advancedLanguages]) => { ([basicLanguages, advancedLanguages]) => {
basicLanguages.sort(strcmp); basicLanguages.sort((a, b) => strcmp(a.entry, b.entry));
advancedLanguages.sort(strcmp); advancedLanguages.sort((a, b) => strcmp(a.entry, b.entry));
let i = 0, let i = 0,
len = basicLanguages.length; len = basicLanguages.length;
@ -197,13 +188,8 @@ exports.languages = ${JSON.stringify(languages, null, ' ')};
} }
); );
} }
exports.generateMetadata = generateMetadata;
/** function strcmp(a: string, b: string) {
* @tyoe {string} a
* @tyoe {string} b
*/
function strcmp(a, b) {
if (a < b) { if (a < b) {
return -1; return -1;
} }
@ -213,10 +199,7 @@ function strcmp(a, b) {
return 0; return 0;
} }
/** function getFeatures(): { label: string; entry: string | string[] }[] {
* @returns {{label:string;entry:string|string[];}[]}
*/
function getFeatures() {
const skipImports = [ const skipImports = [
'vs/editor/browser/widget/codeEditorWidget', 'vs/editor/browser/widget/codeEditorWidget',
'vs/editor/browser/widget/diffEditorWidget', 'vs/editor/browser/widget/diffEditorWidget',
@ -228,8 +211,7 @@ function getFeatures() {
'vs/editor/contrib/gotoSymbol/documentSymbols' 'vs/editor/contrib/gotoSymbol/documentSymbols'
]; ];
/** @type {string[]} */ let features: string[] = [];
let features = [];
const files = const files =
fs.readFileSync(path.join(REPO_ROOT, 'release/esm/vs/editor/edcore.main.js')).toString() + fs.readFileSync(path.join(REPO_ROOT, 'release/esm/vs/editor/edcore.main.js')).toString() +
fs.readFileSync(path.join(REPO_ROOT, 'release/esm/vs/editor/editor.all.js')).toString(); fs.readFileSync(path.join(REPO_ROOT, 'release/esm/vs/editor/editor.all.js')).toString();
@ -243,10 +225,22 @@ function getFeatures() {
} }
}); });
/** @type {{label:string;entry:any;}[]} */ let result: { label: string; entry: any }[] = features.map((feature) => {
let result = features.map((feature) => { /** @type {string} */ let label;
if (customFeatureLabels[feature]) {
label = customFeatureLabels[feature];
} else {
const m1 = feature.match(/^vs\/editor\/contrib\/([^\/]+)/);
if (m1) {
// for editor/contrib features, use the first segment
label = m1[1];
} else {
// for everything else, use the last segment folder
label = path.basename(path.dirname(feature));
}
}
return { return {
label: customFeatureLabels[feature] || path.basename(path.dirname(feature)), label: label,
entry: feature entry: feature
}; };
}); });

View file

@ -3,14 +3,12 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import fs = require('fs');
import path = require('path');
const fs = require('fs'); import http = require('http');
const path = require('path'); import yaserver = require('yaserver');
const http = require('http'); import { REPO_ROOT } from './utils';
const yaserver = require('yaserver'); import { ensureDir } from './fs';
const { REPO_ROOT } = require('./utils');
const { ensureDir } = require('./fs');
const WEBSITE_GENERATED_PATH = path.join(REPO_ROOT, 'website/playground/new-samples'); const WEBSITE_GENERATED_PATH = path.join(REPO_ROOT, 'website/playground/new-samples');
@ -100,7 +98,6 @@ function generateTestSamplesTask() {
'</div>', '</div>',
'<div style="clear:both"></div>', '<div style="clear:both"></div>',
'', '',
'<script src="../../metadata.js"></script>',
'<script src="dev-setup.js"></script>', '<script src="dev-setup.js"></script>',
'<script>', '<script>',
'loadEditor(function() {', 'loadEditor(function() {',
@ -148,7 +145,6 @@ function generateTestSamplesTask() {
); );
}) })
.join('<br/>\n'), .join('<br/>\n'),
'<script src="../../metadata.js"></script>',
'<script src="dev-setup.js"></script>', '<script src="dev-setup.js"></script>',
'</body>', '</body>',
'</html>' '</html>'
@ -159,11 +155,7 @@ function generateTestSamplesTask() {
); );
} }
/** function createSimpleServer(rootDir: string, port: number) {
* @param {string} rootDir
* @param {number} port
*/
function createSimpleServer(rootDir, port) {
yaserver yaserver
.createServer({ .createServer({
rootDir: rootDir rootDir: rootDir

7
build/tsconfig.json Normal file
View file

@ -0,0 +1,7 @@
{
"compilerOptions": {
"noEmit": true,
"esModuleInterop": true
},
"files": ["./**/*"]
}

View file

@ -3,26 +3,20 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import * as fs from 'fs';
import * as path from 'path';
import * as cp from 'child_process';
import * as esbuild from 'esbuild';
import alias from 'esbuild-plugin-alias';
import * as glob from 'glob';
import { ensureDir } from './fs';
const fs = require('fs'); export const REPO_ROOT = path.join(__dirname, '../');
const path = require('path');
const cp = require('child_process');
const esbuild = require('esbuild');
/** @type {any} */
const alias = require('esbuild-plugin-alias');
const glob = require('glob');
const { ensureDir } = require('./fs');
const REPO_ROOT = path.join(__dirname, '../');
exports.REPO_ROOT = REPO_ROOT;
/** /**
* Launch the typescript compiler synchronously over a project. * Launch the typescript compiler synchronously over a project.
*
* @param {string} _projectPath
*/ */
function tsc(_projectPath) { export function tsc(_projectPath: string) {
const projectPath = path.join(REPO_ROOT, _projectPath); const projectPath = path.join(REPO_ROOT, _projectPath);
console.log(`Launching compiler at ${_projectPath}...`); console.log(`Launching compiler at ${_projectPath}...`);
const res = cp.spawnSync( const res = cp.spawnSync(
@ -35,14 +29,11 @@ function tsc(_projectPath) {
process.exit(res.status); process.exit(res.status);
} }
} }
exports.tsc = tsc;
/** /**
* Launch prettier on a specific file. * Launch prettier on a specific file.
*
* @param {string} _filePath
*/ */
function prettier(_filePath) { export function prettier(_filePath: string) {
const filePath = path.join(REPO_ROOT, _filePath); const filePath = path.join(REPO_ROOT, _filePath);
cp.spawnSync( cp.spawnSync(
process.execPath, process.execPath,
@ -52,16 +43,11 @@ function prettier(_filePath) {
console.log(`Ran prettier over ${_filePath}`); console.log(`Ran prettier over ${_filePath}`);
} }
exports.prettier = prettier;
/** /**
* Transform an external .d.ts file to an internal .d.ts file * Transform an external .d.ts file to an internal .d.ts file
*
* @param {string} _source
* @param {string} _destination
* @param {string} namespace
*/ */
function dts(_source, _destination, namespace) { export function dts(_source: string, _destination: string, namespace: string) {
const source = path.join(REPO_ROOT, _source); const source = path.join(REPO_ROOT, _source);
const destination = path.join(REPO_ROOT, _destination); const destination = path.join(REPO_ROOT, _destination);
@ -100,12 +86,8 @@ function dts(_source, _destination, namespace) {
prettier(_destination); prettier(_destination);
} }
exports.dts = dts;
/** export function build(options: import('esbuild').BuildOptions) {
* @param {import('esbuild').BuildOptions} options
*/
function build(options) {
esbuild.build(options).then((result) => { esbuild.build(options).then((result) => {
if (result.errors.length > 0) { if (result.errors.length > 0) {
console.error(result.errors); console.error(result.errors);
@ -115,16 +97,8 @@ function build(options) {
} }
}); });
} }
exports.build = build;
/** export function buildESM(options: { base: string; entryPoints: string[]; external: string[] }) {
* @param {{
* base: string;
* entryPoints: string[];
* external: string[];
* }} options
*/
function buildESM(options) {
build({ build({
entryPoints: options.entryPoints, entryPoints: options.entryPoints,
bundle: true, bundle: true,
@ -138,7 +112,7 @@ function buildESM(options) {
}, },
external: options.external, external: options.external,
outbase: `src/${options.base}`, outbase: `src/${options.base}`,
outdir: `out/release/${options.base}/esm/`, outdir: `out/release/esm/vs/${options.base}/`,
plugins: [ plugins: [
alias({ alias({
'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts') 'vscode-nls': path.join(__dirname, 'fillers/vscode-nls.ts')
@ -146,20 +120,23 @@ function buildESM(options) {
] ]
}); });
} }
exports.buildESM = buildESM;
/** function buildOneAMD(
* @param {'dev'|'min'} type type: 'dev' | 'min',
* @param {{ options: {
* base: string; base: string;
* entryPoint: string; entryPoint: string;
* amdModuleId: string; amdModuleId: string;
* amdDependencies?: string[]; amdDependencies?: string[];
* }} options external?: string[];
*/ }
function buildOneAMD(type, options) { ) {
/** @type {import('esbuild').BuildOptions} */ if (!options.amdDependencies) {
const opts = { options.amdDependencies = [];
}
options.amdDependencies.unshift('require');
const opts: esbuild.BuildOptions = {
entryPoints: [options.entryPoint], entryPoints: [options.entryPoint],
bundle: true, bundle: true,
target: 'esnext', target: 'esnext',
@ -169,21 +146,22 @@ function buildOneAMD(type, options) {
}, },
globalName: 'moduleExports', globalName: 'moduleExports',
banner: { banner: {
js: `${bundledFileHeader}define("${options.amdModuleId}",[${(options.amdDependencies || []) js: `${bundledFileHeader}define("${options.amdModuleId}", [${(options.amdDependencies || [])
.map((dep) => `"${dep}"`) .map((dep) => `"${dep}"`)
.join(',')}],()=>{` .join(',')}],(require)=>{`
}, },
footer: { footer: {
js: 'return moduleExports;\n});' js: 'return moduleExports;\n});'
}, },
outbase: `src/${options.base}`, outbase: `src/${options.base}`,
outdir: `out/release/${options.base}/${type}/`, outdir: `out/release/${type}/vs/${options.base}/`,
plugins: [ plugins: [
alias({ alias({
'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'), 'vscode-nls': path.join(__dirname, '../build/fillers/vscode-nls.ts'),
'monaco-editor-core': path.join(__dirname, '../build/fillers/monaco-editor-core-amd.ts') 'monaco-editor-core': path.join(__dirname, '../src/fillers/monaco-editor-core-amd.ts')
}) })
] ],
external: ['vs/editor/editor.api', ...(options.external || [])]
}; };
if (type === 'min') { if (type === 'min') {
opts.minify = true; opts.minify = true;
@ -191,19 +169,16 @@ function buildOneAMD(type, options) {
build(opts); build(opts);
} }
/** export function buildAMD(options: {
* @param {{ base: string;
* base: string; entryPoint: string;
* entryPoint: string; amdModuleId: string;
* amdModuleId: string; amdDependencies?: string[];
* amdDependencies?: string[]; external?: string[];
* }} options }) {
*/
function buildAMD(options) {
buildOneAMD('dev', options); buildOneAMD('dev', options);
buildOneAMD('min', options); buildOneAMD('min', options);
} }
exports.buildAMD = buildAMD;
function getGitVersion() { function getGitVersion() {
const git = path.join(REPO_ROOT, '.git'); const git = path.join(REPO_ROOT, '.git');
@ -255,7 +230,7 @@ function getGitVersion() {
return refs[ref]; return refs[ref];
} }
const bundledFileHeader = (() => { export const bundledFileHeader = (() => {
const sha1 = getGitVersion(); const sha1 = getGitVersion();
const semver = require('../package.json').version; const semver = require('../package.json').version;
const headerVersion = semver + '(' + sha1 + ')'; const headerVersion = semver + '(' + sha1 + ')';
@ -272,16 +247,16 @@ const bundledFileHeader = (() => {
return BUNDLED_FILE_HEADER; return BUNDLED_FILE_HEADER;
})(); })();
exports.bundledFileHeader = bundledFileHeader;
/** @typedef {{ path:string; contents:Buffer;}} IFile */ export interface IFile {
path: string;
contents: Buffer;
}
/** export function readFiles(
* @param {string} pattern pattern: string,
* @param {{ base:string; ignore?:string[]; dot?:boolean; }} options options: { base: string; ignore?: string[]; dot?: boolean }
* @returns {IFile[]} ): IFile[] {
*/
function readFiles(pattern, options) {
let files = glob.sync(pattern, { cwd: REPO_ROOT, ignore: options.ignore, dot: options.dot }); let files = glob.sync(pattern, { cwd: REPO_ROOT, ignore: options.ignore, dot: options.dot });
// remove dirs // remove dirs
files = files.filter((file) => { files = files.filter((file) => {
@ -302,17 +277,11 @@ function readFiles(pattern, options) {
}; };
}); });
} }
exports.readFiles = readFiles;
/** export function writeFiles(files: IFile[], dest: string) {
* @param {IFile[]} files
* @param {string} dest
*/
function writeFiles(files, dest) {
for (const file of files) { for (const file of files) {
const fullPath = path.join(REPO_ROOT, dest, file.path); const fullPath = path.join(REPO_ROOT, dest, file.path);
ensureDir(path.dirname(fullPath)); ensureDir(path.dirname(fullPath));
fs.writeFileSync(fullPath, file.contents); fs.writeFileSync(fullPath, file.contents);
} }
} }
exports.writeFiles = writeFiles;

View file

@ -3,20 +3,15 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
//@ts-check import glob = require('glob');
import path = require('path');
import fs = require('fs');
import cp = require('child_process');
import CleanCSS from 'clean-css';
import { REPO_ROOT, readFiles, writeFiles } from './utils';
import { removeDir } from './fs';
/** @typedef {import('../build/utils').IFile} IFile */ const MONACO_EDITOR_VERSION: string = (() => {
const glob = require('glob');
const path = require('path');
const fs = require('fs');
const cp = require('child_process');
const CleanCSS = require('clean-css');
const { REPO_ROOT, readFiles, writeFiles } = require('./utils');
const { removeDir } = require('./fs');
/** @type {string} */
const MONACO_EDITOR_VERSION = (() => {
const output = cp.execSync(`npm show monaco-editor version`).toString(); const output = cp.execSync(`npm show monaco-editor version`).toString();
const version = output.split(/\r\n|\r|\n/g)[0]; const version = output.split(/\r\n|\r|\n/g)[0];
if (!/\d+\.\d+\.\d+/.test(version)) { if (!/\d+\.\d+\.\d+/.test(version)) {
@ -72,14 +67,12 @@ function checkSamples() {
} }
} }
/** function replaceWithRelativeResource(
* @param {string} dataPath dataPath: string,
* @param {string} contents contents: string,
* @param {RegExp} regex regex: RegExp,
* @param {(match:string, fileContents:Buffer)=>string} callback callback: (match: string, fileContents: Buffer) => string
* @returns {string} ): string {
*/
function replaceWithRelativeResource(dataPath, contents, regex, callback) {
return contents.replace(regex, function (_, m0) { return contents.replace(regex, function (_, m0) {
const filePath = path.join(REPO_ROOT, 'website', path.dirname(dataPath), m0); const filePath = path.join(REPO_ROOT, 'website', path.dirname(dataPath), m0);
return callback(m0, fs.readFileSync(filePath)); return callback(m0, fs.readFileSync(filePath));
@ -140,7 +133,7 @@ function generateWebsite() {
contents, contents,
/<link data-inline="yes-please" href="([^"]+)".*/g, /<link data-inline="yes-please" href="([^"]+)".*/g,
function (m0, fileContents) { function (m0, fileContents) {
const minifiedCSS = new CleanCSS().minify(fileContents.toString('utf8')).styles; const minifiedCSS = (new CleanCSS() as any).minify(fileContents.toString('utf8')).styles;
return `<style>${minifiedCSS}</style>`; return `<style>${minifiedCSS}</style>`;
} }
); );

View file

@ -192,27 +192,33 @@ Adding monaco editor to [Vite](https://vitejs.dev/) is simple since it has built
```js ```js
import * as monaco from 'monaco-editor'; import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import cssWorker from 'monaco-editor/esm/vs/language/css/css.worker?worker';
import htmlWorker from 'monaco-editor/esm/vs/language/html/html.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
self.MonacoEnvironment = { self.MonacoEnvironment = {
getWorker(_, label) { getWorker: function (workerId, label) {
if (label === 'json') { const getWorkerModule = (moduleUrl, label) => {
return new jsonWorker(); return new Worker(self.MonacoEnvironment.getWorkerUrl(moduleUrl), {
name: label,
type: 'module'
});
};
switch (label) {
case 'json':
return getWorkerModule('/monaco-editor/esm/vs/language/json/json.worker?worker', label);
case 'css':
case 'scss':
case 'less':
return getWorkerModule('/monaco-editor/esm/vs/language/css/css.worker?worker', label);
case 'html':
case 'handlebars':
case 'razor':
return getWorkerModule('/monaco-editor/esm/vs/language/html/html.worker?worker', label);
case 'typescript':
case 'javascript':
return getWorkerModule('/monaco-editor/esm/vs/language/typescript/ts.worker?worker', label);
default:
return getWorkerModule('/monaco-editor/esm/vs/editor/editor.worker?worker', label);
} }
if (label === 'css' || label === 'scss' || label === 'less') {
return new cssWorker();
}
if (label === 'html' || label === 'handlebars' || label === 'razor') {
return new htmlWorker();
}
if (label === 'typescript' || label === 'javascript') {
return new tsWorker();
}
return new editorWorker();
} }
}; };

View file

@ -1,82 +0,0 @@
(function () {
var METADATA = {
CORE: {
paths: {
src: '/vscode/out/vs',
'npm/dev': 'node_modules/monaco-editor-core/dev/vs',
'npm/min': 'node_modules/monaco-editor-core/min/vs',
built: '/vscode/out-monaco-editor-core/min/vs',
releaseDev: 'release/dev/vs',
releaseMin: 'release/min/vs'
}
},
PLUGINS: [
{
name: 'monaco-typescript',
contrib: 'vs/language/typescript/monaco.contribution',
modulePrefix: 'vs/language/typescript',
rootPath: './out/release/typescript',
paths: {
// use ./ to indicate it is relative to the `rootPath`
dev: './dev',
min: './min',
esm: './esm'
}
},
{
name: 'monaco-css',
contrib: 'vs/language/css/monaco.contribution',
modulePrefix: 'vs/language/css',
rootPath: './out/release/css',
paths: {
// use ./ to indicate it is relative to the `rootPath`
dev: './dev',
min: './min',
esm: './esm'
}
},
{
name: 'monaco-json',
contrib: 'vs/language/json/monaco.contribution',
modulePrefix: 'vs/language/json',
rootPath: './out/release/json',
paths: {
// use ./ to indicate it is relative to the `rootPath`
dev: './dev',
min: './min',
esm: './esm'
}
},
{
name: 'monaco-html',
contrib: 'vs/language/html/monaco.contribution',
modulePrefix: 'vs/language/html',
rootPath: './out/release/html',
paths: {
// use ./ to indicate it is relative to the `rootPath`
dev: './dev',
min: './min',
esm: './esm'
}
},
{
name: 'monaco-languages',
contrib: 'vs/basic-languages/monaco.contribution',
modulePrefix: 'vs/basic-languages',
rootPath: './out/release/basic-languages',
paths: {
// use ./ to indicate it is relative to the `rootPath`
dev: './dev',
min: './min',
esm: './esm'
}
}
]
};
if (typeof exports !== 'undefined') {
exports.METADATA = METADATA;
} else {
self.METADATA = METADATA;
}
})();

3789
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,25 +1,28 @@
{ {
"name": "monaco-editor", "name": "monaco-editor",
"version": "0.31.1", "version": "0.33.0",
"vscode": "5a1b4999493d49c857497ad481d73a737439f305", "vscode": "6a4e5cc26b29359472378c2a8951c33f4ea73244",
"private": true, "private": true,
"description": "A browser based code editor", "description": "A browser based code editor",
"author": "Microsoft Corporation", "author": "Microsoft Corporation",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"build-website": "node ./build/website.js && npm run typedoc", "build-website": "ts-node ./build/website && npm run typedoc",
"import-typescript": "node ./build/importTypescript.js", "import-typescript": "ts-node ./build/importTypescript",
"package-for-smoketest-esbuild": "ts-node ./test/smoke/package-esbuild",
"playwright-install": "node ./node_modules/playwright/install.js", "playwright-install": "node ./node_modules/playwright/install.js",
"playwright-install-deps": "playwright install-deps", "playwright-install-deps": "playwright install-deps",
"postinstall": "node ./build/postinstall.js", "postinstall": "ts-node ./build/postinstall",
"prettier-check": "prettier --check .", "prettier-check": "prettier --check .",
"prettier": "prettier --write .", "prettier": "prettier --write .",
"pretty-quick": "pretty-quick --staged", "pretty-quick": "pretty-quick --staged",
"release": "node ./build/build.js && node ./build/release.js", "release": "ts-node ./build/build && ts-node ./build/release",
"simpleserver": "node ./build/simpleserver", "simpleserver": "ts-node ./build/simpleserver",
"smoketest-debug": "node ./test/smoke/runner.js --debug-tests", "smoketest-debug": "node ./test/smoke/runner.js --debug-tests",
"smoketest": "node ./test/smoke/runner.js", "smoketest": "node ./test/smoke/runner.js",
"test": "mocha test/unit/all.js", "test": "mocha test/unit/all.js",
"deps-all-remove": "ts-node ./build/npm/removeAll",
"deps-all-install": "ts-node ./build/npm/installAll",
"typedoc": "cd website/typedoc && \"../../node_modules/.bin/typedoc\" --options ./typedoc.json", "typedoc": "cd website/typedoc && \"../../node_modules/.bin/typedoc\" --options ./typedoc.json",
"watch": "tsc -w -p ./src" "watch": "tsc -w -p ./src"
}, },
@ -30,31 +33,32 @@
"url": "https://github.com/microsoft/monaco-editor" "url": "https://github.com/microsoft/monaco-editor"
}, },
"devDependencies": { "devDependencies": {
"@types/mocha": "^9.0.0", "@types/mocha": "^9.1.0",
"@typescript/vfs": "^1.3.5", "@typescript/vfs": "^1.3.5",
"chai": "^4.3.4", "chai": "^4.3.6",
"clean-css": "^5.2.2", "clean-css": "^5.2.4",
"esbuild": "^0.13.13", "esbuild": "^0.14.49",
"esbuild-plugin-alias": "^0.2.1", "esbuild-plugin-alias": "^0.2.1",
"glob": "^7.2.0", "glob": "^7.2.0",
"husky": "^7.0.4", "husky": "^7.0.4",
"jsdom": "^18.1.0", "jsdom": "^19.0.0",
"jsonc-parser": "^3.0.0", "jsonc-parser": "^3.0.0",
"mocha": "^9.1.3", "mocha": "^9.2.0",
"monaco-editor-core": "0.32.0-dev.20220110", "monaco-editor-core": "0.34.0-dev.20220720",
"playwright": "^1.16.3", "playwright": "^1.18.1",
"prettier": "^2.4.1", "prettier": "^2.5.1",
"pretty-quick": "^3.1.1", "pretty-quick": "^3.1.3",
"requirejs": "^2.3.6", "requirejs": "^2.3.6",
"terser": "^5.10.0", "terser": "^5.14.2",
"typedoc": "^0.22.9", "ts-node": "^10.6.0",
"typescript": "4.4.4", "typedoc": "^0.22.11",
"vscode-css-languageservice": "^5.1.8", "typescript": "4.5.5",
"vscode-html-languageservice": "^4.1.1", "vscode-css-languageservice": "5.4.1",
"vscode-json-languageservice": "4.1.10", "vscode-html-languageservice": "4.2.4",
"vscode-languageserver-textdocument": "^1.0.2", "vscode-json-languageservice": "4.2.1",
"vscode-languageserver-textdocument": "^1.0.4",
"vscode-languageserver-types": "3.16.0", "vscode-languageserver-types": "3.16.0",
"vscode-uri": "3.0.2", "vscode-uri": "3.0.3",
"yaserver": "^0.4.0" "yaserver": "^0.4.0"
} }
} }

View file

@ -7,9 +7,9 @@
const esbuild = require('esbuild'); const esbuild = require('esbuild');
const path = require('path'); const path = require('path');
const { removeDir } = require('../../build/fs'); const fs = require('fs');
removeDir('samples/browser-esm-esbuild/dist', (entry) => /index.html$/.test(entry)); removeDir('dist', (entry) => /index.html$/.test(entry));
const workerEntryPoints = [ const workerEntryPoints = [
'vs/language/json/json.worker.js', 'vs/language/json/json.worker.js',
@ -50,3 +50,47 @@ function build(opts) {
} }
}); });
} }
/**
* Remove a directory and all its contents.
* @param {string} _dirPath
* @param {(filename: string) => boolean} [keep]
*/
function removeDir(_dirPath, keep) {
if (typeof keep === 'undefined') {
keep = () => false;
}
const dirPath = path.join(__dirname, _dirPath);
if (!fs.existsSync(dirPath)) {
return;
}
rmDir(dirPath, _dirPath);
console.log(`Deleted ${_dirPath}`);
/**
* @param {string} dirPath
* @param {string} relativeDirPath
* @returns {boolean}
*/
function rmDir(dirPath, relativeDirPath) {
let keepsFiles = false;
const entries = fs.readdirSync(dirPath);
for (const entry of entries) {
const filePath = path.join(dirPath, entry);
const relativeFilePath = path.join(relativeDirPath, entry);
if (keep(relativeFilePath)) {
keepsFiles = true;
continue;
}
if (fs.statSync(filePath).isFile()) {
fs.unlinkSync(filePath);
} else {
keepsFiles = rmDir(filePath, relativeFilePath) || keepsFiles;
}
}
if (!keepsFiles) {
fs.rmdirSync(dirPath);
}
return keepsFiles;
}
}

File diff suppressed because it is too large Load diff

View file

@ -4,7 +4,7 @@
"start": "parcel ./src/index.html" "start": "parcel ./src/index.html"
}, },
"devDependencies": { "devDependencies": {
"monaco-editor": "^0.31.0", "monaco-editor": "^0.32.0",
"parcel": "^2.0.1" "parcel": "^2.2.1"
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -8,13 +8,13 @@
}, },
"dependencies": {}, "dependencies": {},
"devDependencies": { "devDependencies": {
"monaco-editor": "^0.31.0", "monaco-editor": "^0.32.0",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"@types/react": "^17.0.35", "@types/react": "^17.0.39",
"@types/react-dom": "^17.0.11", "@types/react-dom": "^17.0.11",
"@vitejs/plugin-react": "^1.0.9", "@vitejs/plugin-react": "^1.1.4",
"typescript": "^4.4.4", "typescript": "^4.5.5",
"vite": "^2.6.14" "vite": "^2.7.13"
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -6,12 +6,12 @@
}, },
"dependencies": {}, "dependencies": {},
"devDependencies": { "devDependencies": {
"@babel/core": "^7.16.0", "@babel/core": "^7.17.0",
"@babel/preset-env": "^7.16.0", "@babel/preset-env": "^7.16.11",
"@babel/preset-react": "^7.16.0", "@babel/preset-react": "^7.16.7",
"@babel/preset-typescript": "^7.16.0", "@babel/preset-typescript": "^7.16.7",
"@pmmmwh/react-refresh-webpack-plugin": "^0.5.1", "@pmmmwh/react-refresh-webpack-plugin": "^0.5.4",
"@types/react": "^17.0.35", "@types/react": "^17.0.39",
"@types/react-dom": "^17.0.11", "@types/react-dom": "^17.0.11",
"babel-loader": "^8.2.3", "babel-loader": "^8.2.3",
"react": "^17.0.2", "react": "^17.0.2",

6327
samples/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -11,19 +11,19 @@
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"css-loader": "^5.2.7", "css-loader": "^5.2.7",
"electron": "^15.3.1", "electron": "^17.2.0",
"file-loader": "^6.2.0", "file-loader": "^6.2.0",
"glob": "^7.2.0", "glob": "^7.2.0",
"html-webpack-plugin": "^5.5.0", "html-webpack-plugin": "^5.5.0",
"monaco-editor-webpack-plugin": "^7.0.1", "monaco-editor-webpack-plugin": "^7.0.1",
"monaco-editor": "^0.31.1", "monaco-editor": "^0.32.1",
"style-loader": "^3.3.1", "style-loader": "^3.3.1",
"terser-webpack-plugin": "^5.2.5", "terser-webpack-plugin": "^5.3.1",
"ts-loader": "^9.2.6", "ts-loader": "^9.2.6",
"typescript": "^4.4.4", "typescript": "^4.5.5",
"webpack-cli": "^4.9.1", "webpack-cli": "^4.9.2",
"webpack-dev-server": "^4.5.0", "webpack-dev-server": "^4.7.4",
"webpack": "^5.64.1", "webpack": "^5.68.0",
"yaserver": "^0.4.0" "yaserver": "^0.4.0"
} }
} }

View file

@ -165,7 +165,7 @@ export const language = <languages.IMonarchLanguage>{
units: [ units: [
[ [
'(em|ex|ch|rem|vmin|vmax|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)?', '(em|ex|ch|rem|fr|vmin|vmax|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)?',
'attribute.value.unit', 'attribute.value.unit',
'@pop' '@pop'
] ]

View file

@ -10,7 +10,7 @@ declare var require: any;
registerLanguage({ registerLanguage({
id: 'javascript', id: 'javascript',
extensions: ['.js', '.es6', '.jsx', '.mjs'], extensions: ['.js', '.es6', '.jsx', '.mjs', '.cjs'],
firstLine: '^#!.*\\bnode', firstLine: '^#!.*\\bnode',
filenames: ['jakefile'], filenames: ['jakefile'],
aliases: ['JavaScript', 'javascript', 'js'], aliases: ['JavaScript', 'javascript', 'js'],

View file

@ -164,7 +164,7 @@ export const language = <languages.IMonarchLanguage>{
units: [ units: [
[ [
'(em|ex|ch|rem|vmin|vmax|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)?', '(em|ex|ch|rem|fr|vmin|vmax|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)?',
'attribute.value.unit', 'attribute.value.unit',
'@pop' '@pop'
] ]

View file

@ -187,7 +187,7 @@ export const language = <languages.IMonarchLanguage>{
units: [ units: [
[ [
'(em|ex|ch|rem|vmin|vmax|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)?', '(em|ex|ch|rem|fr|vmin|vmax|vw|vh|vm|cm|mm|in|px|pt|pc|deg|grad|rad|turn|s|ms|Hz|kHz|%)?',
'number', 'number',
'@pop' '@pop'
] ]

View file

@ -33,6 +33,40 @@ testTokenization('shell', [
{ startIndex: 14, type: 'white.shell' }, { startIndex: 14, type: 'white.shell' },
{ startIndex: 15, type: '' } { startIndex: 15, type: '' }
] ]
},
// Tests for case reported in bug #2851, do not confuse identifier(with dashes) with attribute
{
line: 'foo-bar --baz gorp -123 --abc-123',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 7, type: 'white.shell' },
{ startIndex: 8, type: 'attribute.name.shell' },
{ startIndex: 13, type: 'white.shell' },
{ startIndex: 14, type: '' },
{ startIndex: 18, type: 'white.shell' },
{ startIndex: 19, type: 'attribute.name.shell' },
{ startIndex: 23, type: 'white.shell' },
{ startIndex: 24, type: 'attribute.name.shell' }
]
},
// Bug #2851 add new definition 'Identifiers with dashes', here one test
{
line: 'foo | foo-bar | foo-bar-1 | foo-bar-2021-1',
tokens: [
{ startIndex: 0, type: '' },
{ startIndex: 3, type: 'white.shell' },
{ startIndex: 4, type: 'delimiter.shell' },
{ startIndex: 5, type: 'white.shell' },
{ startIndex: 6, type: '' },
{ startIndex: 13, type: 'white.shell' },
{ startIndex: 14, type: 'delimiter.shell' },
{ startIndex: 15, type: 'white.shell' },
{ startIndex: 16, type: '' },
{ startIndex: 25, type: 'white.shell' },
{ startIndex: 26, type: 'delimiter.shell' },
{ startIndex: 27, type: 'white.shell' },
{ startIndex: 28, type: '' }
]
} }
], ],

View file

@ -134,13 +134,19 @@ export const language = <languages.IMonarchLanguage>{
'zsh' 'zsh'
], ],
startingWithDash: /\-+\w+/,
identifiersWithDashes: /[a-zA-Z]\w+(?:@startingWithDash)+/,
// we include these common regular expressions // we include these common regular expressions
symbols: /[=><!~?&|+\-*\/\^;\.,]+/, symbols: /[=><!~?&|+\-*\/\^;\.,]+/,
// The main tokenizer for our languages // The main tokenizer for our languages
tokenizer: { tokenizer: {
root: [ root: [
{ include: '@whitespace' }, [/@identifiersWithDashes/, ''],
[/(\s)((?:@startingWithDash)+)/, ['white', 'attribute.name']],
[ [
/[a-zA-Z]\w*/, /[a-zA-Z]\w*/,
@ -153,14 +159,14 @@ export const language = <languages.IMonarchLanguage>{
} }
], ],
{ include: '@whitespace' },
{ include: '@strings' }, { include: '@strings' },
{ include: '@parameters' }, { include: '@parameters' },
{ include: '@heredoc' }, { include: '@heredoc' },
[/[{}\[\]()]/, '@brackets'], [/[{}\[\]()]/, '@brackets'],
[/-+\w+/, 'attribute.name'],
[/@symbols/, 'delimiter'], [/@symbols/, 'delimiter'],
{ include: '@numbers' }, { include: '@numbers' },

View file

@ -57,8 +57,8 @@ export const language = <languages.IMonarchLanguage>{
'@asyncHandler', '@asyncHandler',
'@available', '@available',
'@convention', '@convention',
'@derivative', // Swift for TensorFlow '@derivative',
'@differentiable', // Swift for TensorFlow '@differentiable',
'@discardableResult', '@discardableResult',
'@dynamicCallable', '@dynamicCallable',
'@dynamicMemberLookup', '@dynamicMemberLookup',
@ -68,10 +68,12 @@ export const language = <languages.IMonarchLanguage>{
'@inlinable', '@inlinable',
'@inline', '@inline',
'@main', '@main',
'@noDerivative',
'@nonobjc', '@nonobjc',
'@noreturn', '@noreturn',
'@objc', '@objc',
'@objcMembers', '@objcMembers',
'@preconcurrency',
'@propertyWrapper', '@propertyWrapper',
'@requires_stored_property_inits', '@requires_stored_property_inits',
'@resultBuilder', '@resultBuilder',
@ -318,11 +320,6 @@ export const language = <languages.IMonarchLanguage>{
[/./, 'identifier'] [/./, 'identifier']
], ],
// symbol: [
// [ /@symbols/, 'operator' ],
// [ /@operators/, 'operator' ]
// ],
invokedmethod: [ invokedmethod: [
[ [
/([.])(@identifier)/, /([.])(@identifier)/,

View file

@ -127,6 +127,7 @@ export const language = {
'null', 'null',
'number', 'number',
'object', 'object',
'out',
'package', 'package',
'private', 'private',
'protected', 'protected',

View file

@ -1,4 +1,4 @@
import type { languages } from '../../fillers/monaco-editor-core'; import { languages } from '../../fillers/monaco-editor-core';
export const conf: languages.LanguageConfiguration = { export const conf: languages.LanguageConfiguration = {
comments: { comments: {
@ -25,7 +25,15 @@ export const conf: languages.LanguageConfiguration = {
], ],
folding: { folding: {
offSide: true offSide: true
} },
onEnterRules: [
{
beforeText: /:\s*$/,
action: {
indentAction: languages.IndentAction.Indent
}
}
]
}; };
export const language = <languages.IMonarchLanguage>{ export const language = <languages.IMonarchLanguage>{

4
src/fillers/editor.api.d.ts vendored Normal file
View file

@ -0,0 +1,4 @@
declare module 'vs/editor/editor.api' {
const x: any;
export = x;
}

View file

@ -5,8 +5,7 @@
// Resolves with the global monaco API // Resolves with the global monaco API
declare var define: any; /// <reference path="./editor.api.d.ts" />
import * as api from 'vs/editor/editor.api';
define([], function () { export = api;
return (<any>self).monaco;
});

View file

@ -16,7 +16,7 @@ import {
IDisposable, IDisposable,
MarkerSeverity, MarkerSeverity,
IEvent IEvent
} from '../fillers/monaco-editor-core'; } from '../../fillers/monaco-editor-core';
export interface WorkerAccessor<T> { export interface WorkerAccessor<T> {
(...more: Uri[]): Promise<T>; (...more: Uri[]): Promise<T>;
@ -627,13 +627,14 @@ function toWorkspaceEdit(edit: lsTypes.WorkspaceEdit | null): languages.Workspac
if (!edit || !edit.changes) { if (!edit || !edit.changes) {
return void 0; return void 0;
} }
let resourceEdits: languages.WorkspaceTextEdit[] = []; let resourceEdits: languages.IWorkspaceTextEdit[] = [];
for (let uri in edit.changes) { for (let uri in edit.changes) {
const _uri = Uri.parse(uri); const _uri = Uri.parse(uri);
for (let e of edit.changes[uri]) { for (let e of edit.changes[uri]) {
resourceEdits.push({ resourceEdits.push({
resource: _uri, resource: _uri,
edit: { versionId: undefined,
textEdit: {
range: toRange(e.range), range: toRange(e.range),
text: e.newText text: e.newText
} }

View file

@ -7,7 +7,7 @@ import { WorkerManager } from './workerManager';
import type { CSSWorker } from './cssWorker'; import type { CSSWorker } from './cssWorker';
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import * as languageFeatures from '../common/lspLanguageFeatures'; import * as languageFeatures from '../common/lspLanguageFeatures';
import { Uri, IDisposable, languages } from '../fillers/monaco-editor-core'; import { Uri, IDisposable, languages } from '../../fillers/monaco-editor-core';
export function setupMode(defaults: LanguageServiceDefaults): IDisposable { export function setupMode(defaults: LanguageServiceDefaults): IDisposable {
const disposables: IDisposable[] = []; const disposables: IDisposable[] = [];
@ -106,6 +106,22 @@ export function setupMode(defaults: LanguageServiceDefaults): IDisposable {
) )
); );
} }
if (modeConfiguration.documentFormattingEdits) {
providers.push(
languages.registerDocumentFormattingEditProvider(
languageId,
new languageFeatures.DocumentFormattingEditProvider(worker)
)
);
}
if (modeConfiguration.documentRangeFormattingEdits) {
providers.push(
languages.registerDocumentRangeFormattingEditProvider(
languageId,
new languageFeatures.DocumentRangeFormattingEditProvider(worker)
)
);
}
} }
registerProviders(); registerProviders();

View file

@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import type { worker } from '../fillers/monaco-editor-core'; import type { worker } from '../../fillers/monaco-editor-core';
import * as cssService from 'vscode-css-languageservice'; import * as cssService from 'vscode-css-languageservice';
import { Options } from './monaco.contribution'; import { Options } from './monaco.contribution';
@ -12,7 +12,7 @@ export class CSSWorker {
private _ctx: worker.IWorkerContext; private _ctx: worker.IWorkerContext;
private _languageService: cssService.LanguageService; private _languageService: cssService.LanguageService;
private _languageSettings: cssService.LanguageSettings; private _languageSettings: Options;
private _languageId: string; private _languageId: string;
constructor(ctx: worker.IWorkerContext, createData: ICreateData) { constructor(ctx: worker.IWorkerContext, createData: ICreateData) {
@ -53,10 +53,10 @@ export class CSSWorker {
// --- language service host --------------- // --- language service host ---------------
async doValidation(uri: string): Promise<cssService.Diagnostic[]> { async doValidation(uri: string): Promise<cssService.Diagnostic[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (document) { if (document) {
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let diagnostics = this._languageService.doValidation(document, stylesheet); const diagnostics = this._languageService.doValidation(document, stylesheet);
return Promise.resolve(diagnostics); return Promise.resolve(diagnostics);
} }
return Promise.resolve([]); return Promise.resolve([]);
@ -65,63 +65,63 @@ export class CSSWorker {
uri: string, uri: string,
position: cssService.Position position: cssService.Position
): Promise<cssService.CompletionList | null> { ): Promise<cssService.CompletionList | null> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return null; return null;
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let completions = this._languageService.doComplete(document, position, stylesheet); const completions = this._languageService.doComplete(document, position, stylesheet);
return Promise.resolve(completions); return Promise.resolve(completions);
} }
async doHover(uri: string, position: cssService.Position): Promise<cssService.Hover | null> { async doHover(uri: string, position: cssService.Position): Promise<cssService.Hover | null> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return null; return null;
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let hover = this._languageService.doHover(document, position, stylesheet); const hover = this._languageService.doHover(document, position, stylesheet);
return Promise.resolve(hover); return Promise.resolve(hover);
} }
async findDefinition( async findDefinition(
uri: string, uri: string,
position: cssService.Position position: cssService.Position
): Promise<cssService.Location | null> { ): Promise<cssService.Location | null> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return null; return null;
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let definition = this._languageService.findDefinition(document, position, stylesheet); const definition = this._languageService.findDefinition(document, position, stylesheet);
return Promise.resolve(definition); return Promise.resolve(definition);
} }
async findReferences(uri: string, position: cssService.Position): Promise<cssService.Location[]> { async findReferences(uri: string, position: cssService.Position): Promise<cssService.Location[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let references = this._languageService.findReferences(document, position, stylesheet); const references = this._languageService.findReferences(document, position, stylesheet);
return Promise.resolve(references); return Promise.resolve(references);
} }
async findDocumentHighlights( async findDocumentHighlights(
uri: string, uri: string,
position: cssService.Position position: cssService.Position
): Promise<cssService.DocumentHighlight[]> { ): Promise<cssService.DocumentHighlight[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let highlights = this._languageService.findDocumentHighlights(document, position, stylesheet); const highlights = this._languageService.findDocumentHighlights(document, position, stylesheet);
return Promise.resolve(highlights); return Promise.resolve(highlights);
} }
async findDocumentSymbols(uri: string): Promise<cssService.SymbolInformation[]> { async findDocumentSymbols(uri: string): Promise<cssService.SymbolInformation[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let symbols = this._languageService.findDocumentSymbols(document, stylesheet); const symbols = this._languageService.findDocumentSymbols(document, stylesheet);
return Promise.resolve(symbols); return Promise.resolve(symbols);
} }
async doCodeActions( async doCodeActions(
@ -129,21 +129,21 @@ export class CSSWorker {
range: cssService.Range, range: cssService.Range,
context: cssService.CodeActionContext context: cssService.CodeActionContext
): Promise<cssService.Command[]> { ): Promise<cssService.Command[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let actions = this._languageService.doCodeActions(document, range, context, stylesheet); const actions = this._languageService.doCodeActions(document, range, context, stylesheet);
return Promise.resolve(actions); return Promise.resolve(actions);
} }
async findDocumentColors(uri: string): Promise<cssService.ColorInformation[]> { async findDocumentColors(uri: string): Promise<cssService.ColorInformation[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let colorSymbols = this._languageService.findDocumentColors(document, stylesheet); const colorSymbols = this._languageService.findDocumentColors(document, stylesheet);
return Promise.resolve(colorSymbols); return Promise.resolve(colorSymbols);
} }
async getColorPresentations( async getColorPresentations(
@ -151,12 +151,12 @@ export class CSSWorker {
color: cssService.Color, color: cssService.Color,
range: cssService.Range range: cssService.Range
): Promise<cssService.ColorPresentation[]> { ): Promise<cssService.ColorPresentation[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let colorPresentations = this._languageService.getColorPresentations( const colorPresentations = this._languageService.getColorPresentations(
document, document,
stylesheet, stylesheet,
color, color,
@ -168,23 +168,23 @@ export class CSSWorker {
uri: string, uri: string,
context?: { rangeLimit?: number } context?: { rangeLimit?: number }
): Promise<cssService.FoldingRange[]> { ): Promise<cssService.FoldingRange[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let ranges = this._languageService.getFoldingRanges(document, context); const ranges = this._languageService.getFoldingRanges(document, context);
return Promise.resolve(ranges); return Promise.resolve(ranges);
} }
async getSelectionRanges( async getSelectionRanges(
uri: string, uri: string,
positions: cssService.Position[] positions: cssService.Position[]
): Promise<cssService.SelectionRange[]> { ): Promise<cssService.SelectionRange[]> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return []; return [];
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let ranges = this._languageService.getSelectionRanges(document, positions, stylesheet); const ranges = this._languageService.getSelectionRanges(document, positions, stylesheet);
return Promise.resolve(ranges); return Promise.resolve(ranges);
} }
async doRename( async doRename(
@ -192,17 +192,30 @@ export class CSSWorker {
position: cssService.Position, position: cssService.Position,
newName: string newName: string
): Promise<cssService.WorkspaceEdit | null> { ): Promise<cssService.WorkspaceEdit | null> {
let document = this._getTextDocument(uri); const document = this._getTextDocument(uri);
if (!document) { if (!document) {
return null; return null;
} }
let stylesheet = this._languageService.parseStylesheet(document); const stylesheet = this._languageService.parseStylesheet(document);
let renames = this._languageService.doRename(document, position, newName, stylesheet); const renames = this._languageService.doRename(document, position, newName, stylesheet);
return Promise.resolve(renames); return Promise.resolve(renames);
} }
async format(
uri: string,
range: cssService.Range | null,
options: cssService.CSSFormatConfiguration
): Promise<cssService.TextEdit[]> {
const document = this._getTextDocument(uri);
if (!document) {
return [];
}
const settings = { ...this._languageSettings.format, ...options };
const textEdits = this._languageService.format(document, range! /* TODO */, settings);
return Promise.resolve(textEdits);
}
private _getTextDocument(uri: string): cssService.TextDocument | null { private _getTextDocument(uri: string): cssService.TextDocument | null {
let models = this._ctx.getMirrorModels(); const models = this._ctx.getMirrorModels();
for (let model of models) { for (const model of models) {
if (model.uri.toString() === uri) { if (model.uri.toString() === uri) {
return cssService.TextDocument.create( return cssService.TextDocument.create(
uri, uri,

View file

@ -4,7 +4,22 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as mode from './cssMode'; import * as mode from './cssMode';
import { languages, Emitter, IEvent } from '../fillers/monaco-editor-core'; import { languages, Emitter, IEvent } from '../../fillers/monaco-editor-core';
export interface CSSFormatConfiguration {
/** separate selectors with newline (e.g. "a,\nbr" or "a, br"): Default: true */
newlineBetweenSelectors?: boolean;
/** add a new line after every css rule: Default: true */
newlineBetweenRules?: boolean;
/** ensure space around selector separators: '>', '+', '~' (e.g. "a>b" -> "a > b"): Default: false */
spaceAroundSelectorSeparator?: boolean;
/** put braces on the same line as rules (`collapse`), or put braces on own line, Allman / ANSI style (`expand`). Default `collapse` */
braceStyle?: 'collapse' | 'expand';
/** whether existing line breaks before elements should be preserved. Default: true */
preserveNewLines?: boolean;
/** maximum number of line breaks to be preserved in one chunk. Default: unlimited */
maxPreserveNewLines?: number;
}
export interface Options { export interface Options {
readonly validate?: boolean; readonly validate?: boolean;
@ -32,6 +47,11 @@ export interface Options {
* Configures the CSS data types known by the langauge service. * Configures the CSS data types known by the langauge service.
*/ */
readonly data?: CSSDataConfiguration; readonly data?: CSSDataConfiguration;
/**
* Settings for the CSS formatter.
*/
readonly format?: CSSFormatConfiguration;
} }
export interface ModeConfiguration { export interface ModeConfiguration {
@ -89,6 +109,16 @@ export interface ModeConfiguration {
* Defines whether the built-in selection range provider is enabled. * Defines whether the built-in selection range provider is enabled.
*/ */
readonly selectionRanges?: boolean; readonly selectionRanges?: boolean;
/**
* Defines whether the built-in document formatting edit provider is enabled.
*/
readonly documentFormattingEdits?: boolean;
/**
* Defines whether the built-in document formatting range edit provider is enabled.
*/
readonly documentRangeFormattingEdits?: boolean;
} }
export interface LanguageServiceDefaults { export interface LanguageServiceDefaults {
@ -180,7 +210,15 @@ const optionsDefault: Required<Options> = {
float: 'ignore', float: 'ignore',
idSelector: 'ignore' idSelector: 'ignore'
}, },
data: { useDefaultDataProvider: true } data: { useDefaultDataProvider: true },
format: {
newlineBetweenSelectors: true,
newlineBetweenRules: true,
spaceAroundSelectorSeparator: false,
braceStyle: 'collapse',
maxPreserveNewLines: undefined,
preserveNewLines: true
}
}; };
const modeConfigurationDefault: Required<ModeConfiguration> = { const modeConfigurationDefault: Required<ModeConfiguration> = {
@ -194,7 +232,9 @@ const modeConfigurationDefault: Required<ModeConfiguration> = {
colors: true, colors: true,
foldingRanges: true, foldingRanges: true,
diagnostics: true, diagnostics: true,
selectionRanges: true selectionRanges: true,
documentFormattingEdits: true,
documentRangeFormattingEdits: true
}; };
export const cssDefaults: LanguageServiceDefaults = new LanguageServiceDefaultsImpl( export const cssDefaults: LanguageServiceDefaults = new LanguageServiceDefaultsImpl(

View file

@ -5,7 +5,7 @@
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import type { CSSWorker } from './cssWorker'; import type { CSSWorker } from './cssWorker';
import { editor, IDisposable, Uri } from '../fillers/monaco-editor-core'; import { editor, IDisposable, Uri } from '../../fillers/monaco-editor-core';
const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min

View file

@ -7,7 +7,7 @@ import { WorkerManager } from './workerManager';
import type { HTMLWorker } from './htmlWorker'; import type { HTMLWorker } from './htmlWorker';
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import * as languageFeatures from '../common/lspLanguageFeatures'; import * as languageFeatures from '../common/lspLanguageFeatures';
import { Uri, IDisposable, languages } from '../fillers/monaco-editor-core'; import { Uri, IDisposable, languages } from '../../fillers/monaco-editor-core';
class HTMLCompletionAdapter extends languageFeatures.CompletionAdapter<HTMLWorker> { class HTMLCompletionAdapter extends languageFeatures.CompletionAdapter<HTMLWorker> {
constructor(worker: languageFeatures.WorkerAccessor<HTMLWorker>) { constructor(worker: languageFeatures.WorkerAccessor<HTMLWorker>) {

View file

@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information. * Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import { worker } from '../fillers/monaco-editor-core'; import { worker } from '../../fillers/monaco-editor-core';
import * as htmlService from 'vscode-html-languageservice'; import * as htmlService from 'vscode-html-languageservice';
import type { Options } from './monaco.contribution'; import type { Options } from './monaco.contribution';
import { IHTMLDataProvider } from 'vscode-html-languageservice'; import { IHTMLDataProvider } from 'vscode-html-languageservice';

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as mode from './htmlMode'; import * as mode from './htmlMode';
import { languages, Emitter, IEvent, IDisposable } from '../fillers/monaco-editor-core'; import { languages, Emitter, IEvent, IDisposable } from '../../fillers/monaco-editor-core';
export interface HTMLFormatConfiguration { export interface HTMLFormatConfiguration {
readonly tabSize: number; readonly tabSize: number;
@ -27,11 +27,11 @@ export interface CompletionConfiguration {
export interface Options { export interface Options {
/** /**
* If set, comments are tolerated. If set to false, syntax errors will be emitted for comments. * Settings for the HTML formatter.
*/ */
readonly format?: HTMLFormatConfiguration; readonly format?: HTMLFormatConfiguration;
/** /**
* A list of known schemas and/or associations of schemas to file names. * Code completion settings.
*/ */
readonly suggest?: CompletionConfiguration; readonly suggest?: CompletionConfiguration;
/** /**

View file

@ -5,7 +5,7 @@
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import type { HTMLWorker } from './htmlWorker'; import type { HTMLWorker } from './htmlWorker';
import { Uri, IDisposable, editor } from '../fillers/monaco-editor-core'; import { Uri, IDisposable, editor } from '../../fillers/monaco-editor-core';
const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min

View file

@ -8,7 +8,7 @@ import type { JSONWorker } from './jsonWorker';
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import * as languageFeatures from '../common/lspLanguageFeatures'; import * as languageFeatures from '../common/lspLanguageFeatures';
import { createTokenizationSupport } from './tokenization'; import { createTokenizationSupport } from './tokenization';
import { Uri, IDisposable, languages, editor } from '../fillers/monaco-editor-core'; import { Uri, IDisposable, languages, editor } from '../../fillers/monaco-editor-core';
class JSONDiagnosticsAdapter extends languageFeatures.DiagnosticsAdapter<JSONWorker> { class JSONDiagnosticsAdapter extends languageFeatures.DiagnosticsAdapter<JSONWorker> {
constructor( constructor(

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as jsonService from 'vscode-json-languageservice'; import * as jsonService from 'vscode-json-languageservice';
import type { worker } from '../fillers/monaco-editor-core'; import type { worker } from '../../fillers/monaco-editor-core';
import { URI } from 'vscode-uri'; import { URI } from 'vscode-uri';
import { DiagnosticsOptions } from './monaco.contribution'; import { DiagnosticsOptions } from './monaco.contribution';

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as mode from './jsonMode'; import * as mode from './jsonMode';
import { Emitter, IEvent, languages } from '../fillers/monaco-editor-core'; import { Emitter, IEvent, languages } from '../../fillers/monaco-editor-core';
// --- JSON configuration and defaults --------- // --- JSON configuration and defaults ---------

View file

@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/ *--------------------------------------------------------------------------------------------*/
import * as json from 'jsonc-parser'; import * as json from 'jsonc-parser';
import { languages } from '../fillers/monaco-editor-core'; import { languages } from '../../fillers/monaco-editor-core';
export function createTokenizationSupport(supportComments: boolean): languages.TokensProvider { export function createTokenizationSupport(supportComments: boolean): languages.TokensProvider {
return { return {

View file

@ -5,7 +5,7 @@
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import type { JSONWorker } from './jsonWorker'; import type { JSONWorker } from './jsonWorker';
import { IDisposable, Uri, editor } from '../fillers/monaco-editor-core'; import { IDisposable, Uri, editor } from '../../fillers/monaco-editor-core';
const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min const STOP_WHEN_IDLE_FOR = 2 * 60 * 1000; // 2min

View file

@ -23,7 +23,7 @@ import {
IRange, IRange,
MarkerTag, MarkerTag,
MarkerSeverity MarkerSeverity
} from '../fillers/monaco-editor-core'; } from '../../fillers/monaco-editor-core';
//#region utils copied from typescript to prevent loading the entire typescriptServices --- //#region utils copied from typescript to prevent loading the entire typescriptServices ---
@ -1124,12 +1124,13 @@ export class CodeActionAdaptor extends FormatHelper implements languages.CodeAct
context: languages.CodeActionContext, context: languages.CodeActionContext,
codeFix: ts.CodeFixAction codeFix: ts.CodeFixAction
): languages.CodeAction { ): languages.CodeAction {
const edits: languages.WorkspaceTextEdit[] = []; const edits: languages.IWorkspaceTextEdit[] = [];
for (const change of codeFix.changes) { for (const change of codeFix.changes) {
for (const textChange of change.textChanges) { for (const textChange of change.textChanges) {
edits.push({ edits.push({
resource: model.uri, resource: model.uri,
edit: { versionId: undefined,
textEdit: {
range: this._textSpanToRange(model, textChange.span), range: this._textSpanToRange(model, textChange.span),
text: textChange.newText text: textChange.newText
} }
@ -1197,13 +1198,14 @@ export class RenameAdapter extends Adapter implements languages.RenameProvider {
return; return;
} }
const edits: languages.WorkspaceTextEdit[] = []; const edits: languages.IWorkspaceTextEdit[] = [];
for (const renameLocation of renameLocations) { for (const renameLocation of renameLocations) {
const model = this._libFiles.getOrCreateModel(renameLocation.fileName); const model = this._libFiles.getOrCreateModel(renameLocation.fileName);
if (model) { if (model) {
edits.push({ edits.push({
resource: model.uri, resource: model.uri,
edit: { versionId: undefined,
textEdit: {
range: this._textSpanToRange(model, renameLocation.textSpan), range: this._textSpanToRange(model, renameLocation.textSpan),
text: newName text: newName
} }
@ -1259,7 +1261,7 @@ export class InlayHintsAdapter extends Adapter implements languages.InlayHintsPr
case 'Type': case 'Type':
return languages.InlayHintKind.Type; return languages.InlayHintKind.Type;
default: default:
return languages.InlayHintKind.Other; return languages.InlayHintKind.Type;
} }
} }
} }

View file

@ -55,6 +55,7 @@ libFileSet['lib.es2020.string.d.ts'] = true;
libFileSet['lib.es2020.symbol.wellknown.d.ts'] = true; libFileSet['lib.es2020.symbol.wellknown.d.ts'] = true;
libFileSet['lib.es2021.d.ts'] = true; libFileSet['lib.es2021.d.ts'] = true;
libFileSet['lib.es2021.full.d.ts'] = true; libFileSet['lib.es2021.full.d.ts'] = true;
libFileSet['lib.es2021.intl.d.ts'] = true;
libFileSet['lib.es2021.promise.d.ts'] = true; libFileSet['lib.es2021.promise.d.ts'] = true;
libFileSet['lib.es2021.string.d.ts'] = true; libFileSet['lib.es2021.string.d.ts'] = true;
libFileSet['lib.es2021.weakref.d.ts'] = true; libFileSet['lib.es2021.weakref.d.ts'] = true;

File diff suppressed because one or more lines are too long

View file

@ -2,4 +2,4 @@
// **NOTE**: Do not edit directly! This file is generated using `npm run import-typescript` // **NOTE**: Do not edit directly! This file is generated using `npm run import-typescript`
// //
export const typescriptVersion = "4.4.4"; export const typescriptVersion = "4.5.5";

View file

@ -5,7 +5,7 @@
import type * as mode from './tsMode'; import type * as mode from './tsMode';
import { typescriptVersion as tsversion } from './lib/typescriptServicesMetadata'; // do not import the whole typescriptServices here import { typescriptVersion as tsversion } from './lib/typescriptServicesMetadata'; // do not import the whole typescriptServices here
import { languages, Emitter, IEvent, IDisposable, Uri } from '../fillers/monaco-editor-core'; import { languages, Emitter, IEvent, IDisposable, Uri } from '../../fillers/monaco-editor-core';
//#region enums copied from typescript to prevent loading the entire typescriptServices --- //#region enums copied from typescript to prevent loading the entire typescriptServices ---

View file

@ -5,7 +5,7 @@
import * as edworker from 'monaco-editor-core/esm/vs/editor/editor.worker'; import * as edworker from 'monaco-editor-core/esm/vs/editor/editor.worker';
import { ICreateData, create } from './tsWorker'; import { ICreateData, create } from './tsWorker';
import { worker } from '../fillers/monaco-editor-core'; import { worker } from '../../fillers/monaco-editor-core';
self.onmessage = () => { self.onmessage = () => {
// ignore the first message // ignore the first message

View file

@ -7,7 +7,7 @@ import { WorkerManager } from './workerManager';
import type { TypeScriptWorker } from './tsWorker'; import type { TypeScriptWorker } from './tsWorker';
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import * as languageFeatures from './languageFeatures'; import * as languageFeatures from './languageFeatures';
import { languages, Uri } from '../fillers/monaco-editor-core'; import { languages, Uri } from '../../fillers/monaco-editor-core';
let javaScriptWorker: (...uris: Uri[]) => Promise<TypeScriptWorker>; let javaScriptWorker: (...uris: Uri[]) => Promise<TypeScriptWorker>;
let typeScriptWorker: (...uris: Uri[]) => Promise<TypeScriptWorker>; let typeScriptWorker: (...uris: Uri[]) => Promise<TypeScriptWorker>;

View file

@ -11,7 +11,7 @@ import {
IExtraLibs, IExtraLibs,
TypeScriptWorker as ITypeScriptWorker TypeScriptWorker as ITypeScriptWorker
} from './monaco.contribution'; } from './monaco.contribution';
import { Uri, worker } from '../fillers/monaco-editor-core'; import { Uri, worker } from '../../fillers/monaco-editor-core';
/** /**
* Loading a default lib as a source file will mess up TS completely. * Loading a default lib as a source file will mess up TS completely.
@ -181,6 +181,14 @@ export class TypeScriptWorker implements ts.LanguageServiceHost, ITypeScriptWork
return fileName === this.getDefaultLibFileName(this._compilerOptions); return fileName === this.getDefaultLibFileName(this._compilerOptions);
} }
readFile(path: string): string | undefined {
return this._getScriptText(path);
}
fileExists(path: string): boolean {
return this._getScriptText(path) !== undefined;
}
async getLibFiles(): Promise<Record<string, string>> { async getLibFiles(): Promise<Record<string, string>> {
return libFileMap; return libFileMap;
} }

View file

@ -5,7 +5,7 @@
import { LanguageServiceDefaults } from './monaco.contribution'; import { LanguageServiceDefaults } from './monaco.contribution';
import type { TypeScriptWorker } from './tsWorker'; import type { TypeScriptWorker } from './tsWorker';
import { editor, Uri, IDisposable } from '../fillers/monaco-editor-core'; import { editor, Uri, IDisposable } from '../../fillers/monaco-editor-core';
export class WorkerManager { export class WorkerManager {
private _modeId: string; private _modeId: string;

File diff suppressed because one or more lines are too long

View file

@ -13,7 +13,6 @@
></div> ></div>
<div style="clear: both"></div> <div style="clear: both"></div>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
loadEditor(function () { loadEditor(function () {

View file

@ -1,44 +1,196 @@
//@ts-check
(function () { (function () {
let IS_FILE_PROTOCOL = window.location.protocol === 'file:'; const corePaths = {
let DIRNAME = null; src: '/vscode/out/vs',
if (IS_FILE_PROTOCOL) { 'npm/dev': 'node_modules/monaco-editor-core/dev/vs',
let port = window.location.port; 'npm/min': 'node_modules/monaco-editor-core/min/vs',
if (port.length > 0) { built: '/vscode/out-monaco-editor-core/min/vs',
port = ':' + port; releaseDev: 'release/dev/vs',
} releaseMin: 'release/min/vs'
DIRNAME = };
window.location.protocol + const pluginPaths = {
'//' + src: 'out/amd',
window.location.hostname + dev: 'out/release/dev/vs',
port + min: 'out/release/min/vs'
window.location.pathname.substr(0, window.location.pathname.lastIndexOf('/')); };
const parsedQuery = parseQueryString();
const editorQueryName = 'editor';
const pluginsQueryName = 'plugins';
const defaultEditorQueryValue = 'npm/dev';
const defaultPluginsQueryValue = 'src';
const editorQueryValue = parsedQuery[editorQueryName] || defaultEditorQueryValue;
const pluginsQueryValue = parsedQuery[pluginsQueryName] || defaultPluginsQueryValue;
const corePath = resolvePath(corePaths[editorQueryValue]);
const pluginPath = resolvePath(pluginPaths[pluginsQueryValue]);
const isRelease = /release/.test(editorQueryValue);
let bases = document.getElementsByTagName('base'); (function () {
if (bases.length > 0) { let div = document.createElement('div');
DIRNAME = DIRNAME + '/' + bases[0].getAttribute('href'); div.className = 'dev-setup-control';
} div.style.position = 'fixed';
} div.style.top = '0';
div.style.right = '0';
div.style.background = 'lightgray';
div.style.padding = '5px 20px 5px 5px';
div.style.zIndex = '1000';
let LOADER_OPTS = (function () { div.innerHTML =
function parseQueryString() { '<ul><li>' +
let str = window.location.search; renderLoadingOptions(true) +
str = str.replace(/^\?/, ''); (isRelease ? '' : `</li><li>${renderLoadingOptions(false)}`) +
let pieces = str.split(/&/); '</li></ul>';
let result = {};
pieces.forEach(function (piece) { document.body.appendChild(div);
let config = piece.split(/=/);
result[config[0]] = config[1]; let aElements = document.getElementsByTagName('a');
for (let i = 0; i < aElements.length; i++) {
let aElement = aElements[i];
if (aElement.className === 'loading-opts') {
aElement.href += window.location.search;
}
}
})();
/** @type {any} */
const global = self;
global.getCodiconPath = () => {
return `${corePath}/base/browser/ui/codicons/codicon/codicon.ttf`;
};
/**
*
* @param {()=>void} callback
* @param {string} [PATH_PREFIX]
*/
global.loadEditor = (callback, PATH_PREFIX) => {
PATH_PREFIX = PATH_PREFIX || '';
loadScript(`${PATH_PREFIX}${corePath}/loader.js`, () => {
global.AMD = true;
/** @type {{[name:string]: string;}} */
const loaderPathsConfig = {};
if (isRelease) {
loaderPathsConfig['vs'] = `${PATH_PREFIX}${corePath}`;
} else {
loaderPathsConfig[
'vs/fillers/monaco-editor-core'
] = `${PATH_PREFIX}/monaco-editor/out/amd/fillers/monaco-editor-core-amd`;
loaderPathsConfig['vs/language'] = `${PATH_PREFIX}${pluginPath}/language`;
loaderPathsConfig['vs/basic-language'] = `${PATH_PREFIX}${pluginPath}/basic-language`;
loaderPathsConfig['vs'] = `${PATH_PREFIX}${corePath}`;
}
console.log('LOADER CONFIG: ');
console.log(JSON.stringify(loaderPathsConfig, null, '\t'));
/** @type {any} */
const req = require;
req.config({
paths: loaderPathsConfig
// 'vs/nls' : {
// availableLanguages: {
// '*': 'de'
// }
// }
}); });
return result;
} req(['vs/editor/editor.main'], () => {
let overwrites = parseQueryString(); if (isRelease) {
let result = {}; callback();
result['editor'] = overwrites['editor'] || 'npm/dev'; return;
METADATA.PLUGINS.map(function (plugin) { }
result[plugin.name] = overwrites[plugin.name] || 'dev'; // At this point we've loaded the monaco-editor-core
req(
[
'vs/basic-languages/monaco.contribution',
'vs/language/css/monaco.contribution',
'vs/language/html/monaco.contribution',
'vs/language/json/monaco.contribution',
'vs/language/typescript/monaco.contribution'
],
callback
);
});
});
};
function parseQueryString() {
const str = window.location.search.replace(/^\?/, '');
const pieces = str.split(/&/);
/** @type {{[name:string]: string;}} */
const result = {};
pieces.forEach((piece) => {
const config = piece.split(/=/);
result[config[0]] = config[1];
}); });
return result; return result;
})(); }
/**
* @param {string} path
*/
function resolvePath(path) {
if (/^\//.test(path)) {
return path;
}
return `/monaco-editor/${path}`;
}
/**
* @param {boolean} isEditor
*/
function renderLoadingOptions(isEditor) {
const name = isEditor ? 'editor' : 'plugins';
const paths = isEditor ? corePaths : pluginPaths;
const selectedPath = isEditor ? editorQueryValue : pluginsQueryValue;
return (
'<strong style="width:130px;display:inline-block;">' +
name +
'</strong>:&#160;&#160;&#160;' +
Object.keys(paths)
.map((path) => {
if (path === selectedPath) {
return '<strong>' + path + '</strong>';
}
return '<a href="' + generateUrlForLoadingOption(isEditor, path) + '">' + path + '</a>';
})
.join('&#160;&#160;&#160;')
);
}
/**
* @param {boolean} isEditor
* @param {string} value
*/
function generateUrlForLoadingOption(isEditor, value) {
/** @type {{[name:string]: string;}} */
const newQueryOptions = {};
const newEditorQueryValue = isEditor ? value : editorQueryValue;
const newPluginsQueryValue = isEditor ? pluginsQueryValue : value;
if (newEditorQueryValue !== defaultEditorQueryValue) {
newQueryOptions[editorQueryName] = newEditorQueryValue;
}
if (newPluginsQueryValue !== defaultPluginsQueryValue) {
newQueryOptions[pluginsQueryName] = newPluginsQueryValue;
}
let search = Object.keys(newQueryOptions)
.map((key) => `${key}=${newQueryOptions[key]}`)
.join('&amp;');
if (search.length > 0) {
search = '?' + search;
}
return toHREF(search);
}
/**
* @param {string} search
*/
function toHREF(search) { function toHREF(search) {
let port = window.location.port; let port = window.location.port;
if (port.length > 0) { if (port.length > 0) {
@ -55,190 +207,12 @@
); );
} }
function Component(name, modulePrefix, paths, rootPath, contrib) {
this.name = name;
this.modulePrefix = modulePrefix;
this.paths = paths;
this.rootPath = rootPath;
this.contrib = contrib;
this.selectedPath = LOADER_OPTS[name];
}
Component.prototype.isRelease = function () {
return /release/.test(this.selectedPath);
};
Component.prototype.getResolvedPath = function (PATH_PREFIX) {
let resolvedPath = this.paths[this.selectedPath];
if (/\.\//.test(resolvedPath)) {
// starts with ./ => treat as relative to the root path
if (IS_FILE_PROTOCOL) {
resolvedPath = DIRNAME + '/../' + this.rootPath + '/' + resolvedPath;
} else {
resolvedPath = PATH_PREFIX + '/monaco-editor/' + this.rootPath + '/' + resolvedPath;
}
} else if (
this.selectedPath === 'npm/dev' ||
this.selectedPath === 'npm/min' ||
this.isRelease()
) {
if (IS_FILE_PROTOCOL) {
resolvedPath = DIRNAME + '/../' + resolvedPath;
} else {
resolvedPath = PATH_PREFIX + '/monaco-editor/' + resolvedPath;
}
} else {
if (IS_FILE_PROTOCOL) {
resolvedPath = DIRNAME + '/../..' + resolvedPath;
} else {
resolvedPath = PATH_PREFIX + resolvedPath;
}
}
return resolvedPath;
};
Component.prototype.generateLoaderConfig = function (dest, PATH_PREFIX) {
dest[this.modulePrefix] = this.getResolvedPath(PATH_PREFIX);
};
Component.prototype.generateUrlForPath = function (pathName) {
let NEW_LOADER_OPTS = {};
Object.keys(LOADER_OPTS).forEach(function (key) {
NEW_LOADER_OPTS[key] = LOADER_OPTS[key] === 'npm/dev' ? undefined : LOADER_OPTS[key];
});
NEW_LOADER_OPTS[this.name] = pathName === 'npm/dev' ? undefined : pathName;
let search = Object.keys(NEW_LOADER_OPTS)
.map(function (key) {
let value = NEW_LOADER_OPTS[key];
if (value) {
return key + '=' + value;
}
return '';
})
.filter(function (assignment) {
return !!assignment;
})
.join('&amp;');
if (search.length > 0) {
search = '?' + search;
}
return toHREF(search);
};
Component.prototype.renderLoadingOptions = function () {
return (
'<strong style="width:130px;display:inline-block;">' +
this.name +
'</strong>:&#160;&#160;&#160;' +
Object.keys(this.paths)
.map(
function (pathName) {
if (pathName === this.selectedPath) {
return '<strong>' + pathName + '</strong>';
}
return '<a href="' + this.generateUrlForPath(pathName) + '">' + pathName + '</a>';
}.bind(this)
)
.join('&#160;&#160;&#160;')
);
};
let RESOLVED_CORE = new Component('editor', 'vs', METADATA.CORE.paths);
self.RESOLVED_CORE_PATH = RESOLVED_CORE.getResolvedPath('');
let RESOLVED_PLUGINS = METADATA.PLUGINS.map(function (plugin) {
return new Component(
plugin.name,
plugin.modulePrefix,
plugin.paths,
plugin.rootPath,
plugin.contrib
);
});
METADATA = null;
function loadScript(path, callback) { function loadScript(path, callback) {
let script = document.createElement('script'); const script = document.createElement('script');
script.onload = callback; script.onload = callback;
script.async = true; script.async = true;
script.type = 'text/javascript'; script.type = 'text/javascript';
script.src = path; script.src = path;
document.head.appendChild(script); document.head.appendChild(script);
} }
(function () {
let allComponents = [RESOLVED_CORE];
if (!RESOLVED_CORE.isRelease()) {
allComponents = allComponents.concat(RESOLVED_PLUGINS);
}
let div = document.createElement('div');
div.className = 'dev-setup-control';
div.style.position = 'fixed';
div.style.top = 0;
div.style.right = 0;
div.style.background = 'lightgray';
div.style.padding = '5px 20px 5px 5px';
div.style.zIndex = '1000';
div.innerHTML =
'<ul><li>' +
allComponents
.map(function (component) {
return component.renderLoadingOptions();
})
.join('</li><li>') +
'</li></ul>';
document.body.appendChild(div);
let aElements = document.getElementsByTagName('a');
for (let i = 0; i < aElements.length; i++) {
let aElement = aElements[i];
if (aElement.className === 'loading-opts') {
aElement.href += window.location.search;
}
}
})();
self.getCodiconPath = function (PATH_PREFIX) {
PATH_PREFIX = PATH_PREFIX || '';
const result = RESOLVED_CORE.getResolvedPath(PATH_PREFIX);
return result + '/base/browser/ui/codicons/codicon/codicon.ttf';
};
self.loadEditor = function (callback, PATH_PREFIX) {
PATH_PREFIX = PATH_PREFIX || '';
loadScript(RESOLVED_CORE.getResolvedPath(PATH_PREFIX) + '/loader.js', function () {
let loaderPathsConfig = {};
if (!RESOLVED_CORE.isRelease()) {
RESOLVED_PLUGINS.forEach(function (plugin) {
plugin.generateLoaderConfig(loaderPathsConfig, PATH_PREFIX);
});
}
RESOLVED_CORE.generateLoaderConfig(loaderPathsConfig, PATH_PREFIX);
console.log('LOADER CONFIG: ');
console.log(JSON.stringify(loaderPathsConfig, null, '\t'));
require.config({
paths: loaderPathsConfig
// 'vs/nls' : {
// availableLanguages: {
// '*': 'de'
// }
// }
});
require(['vs/editor/editor.main'], function () {
if (!RESOLVED_CORE.isRelease()) {
// At this point we've loaded the monaco-editor-core
require(RESOLVED_PLUGINS.map(function (plugin) {
return plugin.contrib;
}), function () {
// At this point we've loaded all the plugins
callback();
});
} else {
callback();
}
});
});
};
})(); })();

View file

@ -10,7 +10,6 @@
></div> ></div>
<div style="clear: both"></div> <div style="clear: both"></div>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
loadEditor(function () { loadEditor(function () {

View file

@ -0,0 +1,29 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body style="height: 100%">
<div
style="
position: absolute;
left: 10px;
top: 10px;
width: 400px;
height: 200px;
border: 1px solid silver;
"
id="editor"
></div>
<script src="dev-setup.js"></script>
<script>
loadEditor(function () {
monaco.editor.create(document.getElementById('editor'), {
value: `function hello()\n{\treturn 5;\n}`,
language: 'javascript'
});
});
</script>
</body>
</html>

23
test/manual/iframe.html Normal file
View file

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<h2>Monaco Editor in iframe</h2>
<input type="text" style="position: absolute; top: 60px; left: 20px" />
<iframe
src="./iframe-inner.html"
style="
position: absolute;
left: 20px;
top: 100px;
width: calc(100% - 40px);
height: 300px;
border: 1px solid silver;
"
></iframe>
</body>
</html>

View file

@ -11,6 +11,8 @@
<a class="loading-opts" href="./diff.html">[Diff]</a> &#160;|&#160; <a class="loading-opts" href="./diff.html">[Diff]</a> &#160;|&#160;
<a class="loading-opts" href="./typescript/index.html">[TypeScript]</a> &#160;|&#160; <a class="loading-opts" href="./typescript/index.html">[TypeScript]</a> &#160;|&#160;
<a class="loading-opts" href="./typescript/custom-worker.html">[TS Worker]</a> <a class="loading-opts" href="./typescript/custom-worker.html">[TS Worker]</a>
&#160;|&#160;
<a class="loading-opts" href="./iframe.html">[iframe]</a>
<br />&#160;|&#160; <br />&#160;|&#160;
<a class="loading-opts" href="./cross-origin.html">[cross origin]</a> &#160;|&#160; <a class="loading-opts" href="./cross-origin.html">[cross origin]</a> &#160;|&#160;
<a class="loading-opts" href="./mouse-fixed.html">[fixed element]</a> &#160;|&#160; <a class="loading-opts" href="./mouse-fixed.html">[fixed element]</a> &#160;|&#160;
@ -32,7 +34,6 @@
></div> ></div>
<div style="clear: both"></div> <div style="clear: both"></div>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
loadEditor(function () { loadEditor(function () {

View file

@ -1,8 +1,8 @@
/// <reference path="../../release/monaco.d.ts" /> /// <reference path="../../release/monaco.d.ts" />
define(['require', './samples'], function (require, SAMPLES) { define(['require', './samples'], function (require, SAMPLES) {
var domutils = require('vs/base/browser/dom'); const domutils = require('vs/base/browser/dom');
var model = monaco.editor.createModel('', 'plaintext'); let model = monaco.editor.createModel('', 'plaintext');
monaco.languages.typescript.typescriptDefaults.setInlayHintsOptions({ monaco.languages.typescript.typescriptDefaults.setInlayHintsOptions({
includeInlayParameterNameHints: 'all', includeInlayParameterNameHints: 'all',

View file

@ -18,7 +18,6 @@
id="Editor" id="Editor"
></div> ></div>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
loadEditor(function () { loadEditor(function () {

View file

@ -273,7 +273,6 @@
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p> </p>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
loadEditor(function () { loadEditor(function () {

View file

@ -191,7 +191,6 @@
<div style="clear: both"></div> <div style="clear: both"></div>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
loadEditor(function () { loadEditor(function () {

View file

@ -13,7 +13,6 @@
></div> ></div>
<div style="clear: both"></div> <div style="clear: both"></div>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
const container = document.getElementById('container'); const container = document.getElementById('container');

View file

@ -16,7 +16,6 @@
<body style="transform: scale(0.75)"> <body style="transform: scale(0.75)">
<div id="editor"></div> <div id="editor"></div>
<script src="../../metadata.js"></script>
<script src="dev-setup.js"></script> <script src="dev-setup.js"></script>
<script> <script>
loadEditor(function () { loadEditor(function () {

View file

@ -19,7 +19,6 @@
<button id="logDTS">Log DTS</button> <button id="logDTS">Log DTS</button>
<button id="getAST">Print AST to console</button> <button id="getAST">Print AST to console</button>
<script src="../../../metadata.js"></script>
<script src="../dev-setup.js"></script> <script src="../dev-setup.js"></script>
<script> <script>

View file

@ -11,7 +11,6 @@
<textarea style="font-family: monospace" id="compilerOpts" cols="60" rows="30"></textarea><br /> <textarea style="font-family: monospace" id="compilerOpts" cols="60" rows="30"></textarea><br />
<button id="updateCompilerSettingsBtn">Update compiler settings</button> <button id="updateCompilerSettingsBtn">Update compiler settings</button>
<script src="../../../metadata.js"></script>
<script src="../dev-setup.js"></script> <script src="../dev-setup.js"></script>
<script> <script>
function getDefaultCode() { function getDefaultCode() {

View file

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
</head>
<body>
<div id="editor-container" style="position: absolute; width: 500px; height: 400px"></div>
<script type="text/javascript" src="out/index.js"></script>
</body>
</html>

View file

@ -0,0 +1,21 @@
import * as monaco from '../../../release/esm/vs/editor/editor.main.js';
self.MonacoEnvironment = {
getWorkerUrl: function (moduleId, label) {
if (label === 'json') {
return './out/vs/language/json/json.worker.js';
}
if (label === 'css' || label === 'scss' || label === 'less') {
return './out/vs/language/css/css.worker.js';
}
if (label === 'html' || label === 'handlebars' || label === 'razor') {
return './out/vs/language/html/html.worker.js';
}
if (label === 'typescript' || label === 'javascript') {
return './out/vs/language/typescript/ts.worker.js';
}
return './out/vs/editor/editor.worker.js';
}
};
window.monacoAPI = monaco;

View file

@ -0,0 +1,58 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as esbuild from 'esbuild';
import * as path from 'path';
import { removeDir } from '../../build/fs';
removeDir('test/smoke/esbuild/out', (entry) => /esbuild.html$/.test(entry));
const workerEntryPoints = [
'vs/language/json/json.worker.js',
'vs/language/css/css.worker.js',
'vs/language/html/html.worker.js',
'vs/language/typescript/ts.worker.js',
'vs/editor/editor.worker.js'
];
build({
entryPoints: workerEntryPoints.map((entry) => path.join(__dirname, `../../release/esm/${entry}`)),
bundle: true,
format: 'iife',
logLevel: 'silent',
outbase: path.join(__dirname, '../../release/esm/'),
outdir: path.join(__dirname, 'esbuild/out')
});
build({
entryPoints: [path.join(__dirname, 'esbuild/index.js')],
bundle: true,
format: 'iife',
logLevel: 'silent',
outdir: path.join(__dirname, 'esbuild/out'),
loader: {
'.ttf': 'file'
}
});
function build(opts: esbuild.BuildOptions) {
esbuild.build(opts).then((result) => {
const errors = result.errors;
const warnings = result.warnings.filter((w) => {
return (
w.text !==
'Top-level "this" will be replaced with undefined since this file is an ECMAScript module'
);
});
if (errors.length > 0) {
console.log(`errors:`);
console.error(errors);
}
if (warnings.length > 0) {
console.log(`warnings:`);
console.error(warnings);
}
});
}

View file

@ -38,7 +38,7 @@ async function runTests() {
// uncomment to shortcircuit and run a specific combo // uncomment to shortcircuit and run a specific combo
// await runTest('webpack', 'chromium'); return; // await runTest('webpack', 'chromium'); return;
for (const type of ['amd', 'webpack']) { for (const type of ['amd', 'webpack' /*, 'esbuild'*/]) {
await runTest(type, 'chromium'); await runTest(type, 'chromium');
await runTest(type, 'firefox'); await runTest(type, 'firefox');
// await runTest(type, 'webkit'); // await runTest(type, 'webkit');

View file

@ -16,7 +16,9 @@ const TESTS_TYPE = process.env.TESTS_TYPE || 'amd';
const URL = const URL =
TESTS_TYPE === 'amd' TESTS_TYPE === 'amd'
? `http://127.0.0.1:${PORT}/test/smoke/amd.html` ? `http://127.0.0.1:${PORT}/test/smoke/amd.html`
: `http://127.0.0.1:${PORT}/test/smoke/webpack/webpack.html`; : TESTS_TYPE === 'webpack'
? `http://127.0.0.1:${PORT}/test/smoke/webpack/webpack.html`
: `http://127.0.0.1:${PORT}/test/smoke/esbuild/esbuild.html`;
suite(`Smoke Test '${TESTS_TYPE}' on '${browserType}'`, () => { suite(`Smoke Test '${TESTS_TYPE}' on '${browserType}'`, () => {
/** @type {playwright.Browser} */ /** @type {playwright.Browser} */

Some files were not shown because too many files have changed in this diff Show more