This repository has been archived by the owner on Nov 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 100
/
index.ts
295 lines (261 loc) · 10.2 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import * as path from 'path';
import * as webpack from 'webpack';
import * as loaderUtils from 'loader-utils';
import * as fs from 'fs';
import { AddWorkerEntryPointPlugin } from './plugins/AddWorkerEntryPointPlugin';
import { languagesArr, EditorLanguage } from './languages';
import { featuresArr, EditorFeature, NegatedEditorFeature } from './features';
import { IFeatureDefinition } from './types';
const INCLUDE_LOADER_PATH = require.resolve('./loaders/include');
const EDITOR_MODULE: IFeatureDefinition = {
label: 'editorWorkerService',
entry: undefined,
worker: {
id: 'vs/editor/editor',
entry: 'vs/editor/editor.worker'
},
};
const languagesById: { [language: string]: IFeatureDefinition; } = {};
languagesArr.forEach(language => languagesById[language.label] = language);
const featuresById: { [feature: string]: IFeatureDefinition; } = {};
featuresArr.forEach(feature => featuresById[feature.label] = feature);
/**
* Return a resolved path for a given Monaco file.
*/
function resolveMonacoPath(filePath: string): string {
try {
return require.resolve(path.join('monaco-editor/esm', filePath));
} catch(err) {
try {
return require.resolve(path.join(process.cwd(), 'node_modules/monaco-editor/esm', filePath));
} catch(err){
return require.resolve(filePath);
}
}
}
/**
* Return the interpolated final filename for a worker, respecting the file name template.
*/
function getWorkerFilename(filename: string, entry: string): string {
return loaderUtils.interpolateName(<any>{ resourcePath: entry }, filename, {
content: fs.readFileSync(resolveMonacoPath(entry))
});
}
function getFeaturesIds(userFeatures: string[]): string[] {
function notContainedIn(arr: string[]) {
return (element: string) => arr.indexOf(element) === -1;
}
let featuresIds: string[];
if (userFeatures.length) {
const excludedFeatures = userFeatures.filter(f => f[0] === '!').map(f => f.slice(1));
if (excludedFeatures.length) {
featuresIds = Object.keys(featuresById).filter(notContainedIn(excludedFeatures))
} else {
featuresIds = userFeatures;
}
} else {
featuresIds = Object.keys(featuresById);
}
return featuresIds;
}
interface IMonacoEditorWebpackPluginOpts {
/**
* Include only a subset of the languages supported.
*/
languages?: EditorLanguage[];
/**
* Custom languages (outside of the ones shipped with the `monaco-editor`).
*/
customLanguages?: IFeatureDefinition[];
/**
* Include only a subset of the editor features.
* Use e.g. '!contextmenu' to exclude a certain feature.
*/
features?: (EditorFeature | NegatedEditorFeature)[];
/**
* Specify a filename template to use for generated files.
* Use e.g. '[name].worker.[contenthash].js' to include content-based hashes.
*/
filename?: string;
/**
* Override the public path from which files generated by this plugin will be served.
* This wins out over Webpack's dynamic runtime path and can be useful to avoid attempting to load workers cross-
* origin when using a CDN for other static resources.
* Use e.g. '/' if you want to load your resources from the current origin.
*/
publicPath?: string;
/**
* Specify whether the editor API should be exposed through a global `monaco` object or not. This
* option is applicable to `0.22.0` and newer version of `monaco-editor`. Since `0.22.0`, the ESM
* version of the monaco editor does no longer define a global `monaco` object unless
* `global.MonacoEnvironment = { globalAPI: true }` is set ([change
* log](https://github.com/microsoft/monaco-editor/blob/main/CHANGELOG.md#0220-29012021)).
*/
globalAPI?: boolean;
}
interface IInternalMonacoEditorWebpackPluginOpts {
languages: IFeatureDefinition[];
features: IFeatureDefinition[];
filename: string;
publicPath: string;
globalAPI: boolean;
}
class MonacoEditorWebpackPlugin implements webpack.WebpackPluginInstance {
private readonly options: IInternalMonacoEditorWebpackPluginOpts;
constructor(options: IMonacoEditorWebpackPluginOpts = {}) {
const languages = options.languages || Object.keys(languagesById);
const customLanguages = options.customLanguages || [];
const features = getFeaturesIds(options.features || []);
this.options = {
languages: coalesce(languages.map(id => languagesById[id])).concat(customLanguages),
features: coalesce(features.map(id => featuresById[id])),
filename: options.filename || "[name].worker.js",
publicPath: options.publicPath || '',
globalAPI: options.globalAPI || false,
};
}
apply(compiler: webpack.Compiler): void {
const { languages, features, filename, publicPath, globalAPI } = this.options;
const compilationPublicPath = getCompilationPublicPath(compiler);
const modules = [EDITOR_MODULE].concat(languages).concat(features);
const workers: ILabeledWorkerDefinition[] = [];
modules.forEach((module) => {
if (module.worker) {
workers.push({
label: module.label,
id: module.worker.id,
entry: module.worker.entry
});
}
});
const rules = createLoaderRules(languages, features, workers, filename, publicPath, compilationPublicPath, globalAPI);
const plugins = createPlugins(workers, filename);
addCompilerRules(compiler, rules);
addCompilerPlugins(compiler, plugins);
}
}
interface ILabeledWorkerDefinition {
label: string;
id: string;
entry: string;
}
function addCompilerRules(compiler: webpack.Compiler, rules: webpack.RuleSetRule[]): void {
const compilerOptions = compiler.options;
if (!compilerOptions.module) {
compilerOptions.module = <any>{ rules: rules };
} else {
const moduleOptions = compilerOptions.module;
moduleOptions.rules = (moduleOptions.rules || []).concat(rules);
}
}
function addCompilerPlugins(compiler: webpack.Compiler, plugins: webpack.WebpackPluginInstance[]) {
plugins.forEach((plugin) => plugin.apply(compiler));
}
function getCompilationPublicPath(compiler: webpack.Compiler): string {
if (compiler.options.output && compiler.options.output.publicPath) {
if (typeof compiler.options.output.publicPath === 'string') {
return compiler.options.output.publicPath;
} else {
console.warn(`Cannot handle options.publicPath (expected a string)`);
}
}
return '';
}
function createLoaderRules(languages: IFeatureDefinition[], features: IFeatureDefinition[], workers: ILabeledWorkerDefinition[], filename: string, pluginPublicPath: string, compilationPublicPath: string, globalAPI: boolean): webpack.RuleSetRule[] {
if (!languages.length && !features.length) {
return [];
}
const languagePaths = flatArr(coalesce(languages.map(language => language.entry)));
const featurePaths = flatArr(coalesce(features.map(feature => feature.entry)));
const workerPaths = fromPairs(workers.map(({ label, entry }) => [label, getWorkerFilename(filename, entry)]));
if (workerPaths['typescript']) {
// javascript shares the same worker
workerPaths['javascript'] = workerPaths['typescript'];
}
if (workerPaths['css']) {
// scss and less share the same worker
workerPaths['less'] = workerPaths['css'];
workerPaths['scss'] = workerPaths['css'];
}
if (workerPaths['html']) {
// handlebars, razor and html share the same worker
workerPaths['handlebars'] = workerPaths['html'];
workerPaths['razor'] = workerPaths['html'];
}
// Determine the public path from which to load worker JS files. In order of precedence:
// 1. Plugin-specific public path.
// 2. Dynamic runtime public path.
// 3. Compilation public path.
const pathPrefix = Boolean(pluginPublicPath)
? JSON.stringify(pluginPublicPath)
: `typeof __webpack_public_path__ === 'string' ` +
`? __webpack_public_path__ ` +
`: ${JSON.stringify(compilationPublicPath)}`
const globals = {
'MonacoEnvironment': `(function (paths) {
function stripTrailingSlash(str) {
return str.replace(/\\/$/, '');
}
return {
globalAPI: ${globalAPI},
getWorkerUrl: function (moduleId, label) {
var pathPrefix = ${pathPrefix};
var result = (pathPrefix ? stripTrailingSlash(pathPrefix) + '/' : '') + paths[label];
if (/^((http:)|(https:)|(file:)|(\\/\\/))/.test(result)) {
var currentUrl = String(window.location);
var currentOrigin = currentUrl.substr(0, currentUrl.length - window.location.hash.length - window.location.search.length - window.location.pathname.length);
if (result.substring(0, currentOrigin.length) !== currentOrigin) {
var js = '/*' + label + '*/importScripts("' + result + '");';
var blob = new Blob([js], { type: 'application/javascript' });
return URL.createObjectURL(blob);
}
}
return result;
}
};
})(${JSON.stringify(workerPaths, null, 2)})`,
};
return [
{
test: /monaco-editor[/\\]esm[/\\]vs[/\\]editor[/\\]editor.(api|main).js/,
use: [{
loader: INCLUDE_LOADER_PATH,
options: {
globals,
pre: featurePaths.map((importPath) => resolveMonacoPath(importPath)),
post: languagePaths.map((importPath) => resolveMonacoPath(importPath)),
},
}],
},
];
}
function createPlugins(workers: ILabeledWorkerDefinition[], filename: string): AddWorkerEntryPointPlugin[] {
return (
(<AddWorkerEntryPointPlugin[]>[])
.concat(workers.map(({ id, entry }) =>
new AddWorkerEntryPointPlugin({
id,
entry: resolveMonacoPath(entry),
filename: getWorkerFilename(filename, entry),
plugins: [
new webpack.optimize.LimitChunkCountPlugin({ maxChunks: 1 }),
],
})
))
);
}
function flatArr<T>(items: (T | T[])[]): T[] {
return items.reduce((acc: T[], item: T | T[]) => {
if (Array.isArray(item)) {
return (<T[]>[]).concat(acc).concat(item);
}
return (<T[]>[]).concat(acc).concat([item]);
}, <T[]>[]);
}
function fromPairs<T>(values: [string, T][]): { [key: string]: T; } {
return values.reduce((acc, [key, value]) => Object.assign(acc, { [key]: value }), <{ [key: string]: T; }>{});
}
function coalesce<T>(array: ReadonlyArray<T | undefined | null>): T[] {
return <T[]>array.filter(Boolean);
}
export = MonacoEditorWebpackPlugin;