modern-monaco 0.3.8 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -216,7 +216,7 @@ const monaco = await init({
216
216
 
217
217
  monaco.editor.create(document.getElementById("editor"), {
218
218
  theme: "one-light",
219
- })
219
+ });
220
220
  // update the editor theme
221
221
  monaco.editor.setTheme("one-dark-pro");
222
222
  ```
@@ -382,10 +382,22 @@ export interface LSPConfig {
382
382
  };
383
383
  /** HTML language configuration. */
384
384
  html?: {
385
- attributeDefaultValue?: "empty" | "singlequotes" | "doublequotes";
385
+ /** Defines whether the standard HTML tags are shown. Default is true. */
386
+ useDefaultDataProvider?: boolean;
387
+ /** Provides a set of custom data providers. */
388
+ dataProviders?: { [providerId: string]: HTMLDataV1 };
389
+ /** Provides a set of custom HTML tags. */
386
390
  customTags?: ITagData[];
387
- hideAutoCompleteProposals?: boolean;
391
+ /** The default value for empty attributes. Default is "empty". */
392
+ attributeDefaultValue?: "empty" | "singlequotes" | "doublequotes";
393
+ /** Whether to hide end tag suggestions. Default is false. */
388
394
  hideEndTagSuggestions?: boolean;
395
+ /** Whether to hide auto complete proposals. Default is false. */
396
+ hideAutoCompleteProposals?: boolean;
397
+ /** Whether to show the import map code lens. Default is true. */
398
+ importMapCodeLens?: boolean;
399
+ /** Options for the diagnostics. */
400
+ diagnosticsOptions?: DiagnosticsOptions;
389
401
  };
390
402
  /** CSS language configuration. */
391
403
  css?: {
@@ -393,11 +405,15 @@ export interface LSPConfig {
393
405
  useDefaultDataProvider?: boolean;
394
406
  /** Provides a set of custom data providers. */
395
407
  dataProviders?: { [providerId: string]: CSSDataV1 };
408
+ /** A list of valid properties that not defined in the standard CSS properties. */
409
+ validProperties?: string[];
410
+ /** Options for the diagnostics. */
411
+ diagnosticsOptions?: DiagnosticsOptions;
396
412
  };
397
413
  /** JSON language configuration. */
398
414
  json?: {
399
- /** By default, the validator will return syntax and semantic errors. Set to false to disable the validator. */
400
- validate?: boolean;
415
+ /** Whether to show the import map code lens. Default is true. */
416
+ importMapCodeLens?: boolean;
401
417
  /** Defines whether comments are allowed or not. Default is disallowed. */
402
418
  allowComments?: boolean;
403
419
  /** A list of known schemas and/or associations of schemas to file names. */
@@ -410,17 +426,48 @@ export interface LSPConfig {
410
426
  schemaValidation?: SeverityLevel;
411
427
  /** The severity of problems that occurred when resolving and loading schemas. Default is "warning". */
412
428
  schemaRequest?: SeverityLevel;
429
+ /** Options for the diagnostics. */
430
+ diagnosticsOptions?: DiagnosticsOptions;
413
431
  };
414
432
  /** TypeScript language configuration. */
415
433
  typescript?: {
434
+ /** The default import maps. */
435
+ importMap?: ImportMap;
416
436
  /** The compiler options. */
417
437
  compilerOptions?: ts.CompilerOptions;
418
- /** The global import map. */
419
- importMap?: ImportMap;
438
+ /** Options for the diagnostics. */
439
+ diagnosticsOptions?: DiagnosticsOptions;
420
440
  };
421
441
  }
422
442
  ```
423
443
 
444
+ You can also set the diagnostics options for each language by adding the `diagnosticsOptions` option to the `lsp` options:
445
+
446
+ ```js
447
+ lazy({
448
+ lsp: {
449
+ css: {
450
+ diagnosticsOptions: {
451
+ // filter out unknown property errors
452
+ filter: (diagnostic) => diagnostic.code !== "unknownProperty",
453
+ },
454
+ },
455
+ json: {
456
+ diagnosticsOptions: {
457
+ // disable syntax and semantic validation
458
+ validate: false,
459
+ },
460
+ },
461
+ typescript: {
462
+ diagnosticsOptions: {
463
+ // ignore type not found errors (code 2307)
464
+ codesToIgnore: [2307],
465
+ },
466
+ },
467
+ },
468
+ });
469
+ ```
470
+
424
471
  ### Import Maps
425
472
 
426
473
  modern-monaco uses [import maps](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type/importmap) to resolve **bare specifier** imports in JavaScript/TypeScript. By default, modern-monaco detects the `importmap` from the root `index.html` in the workspace.
package/dist/cache.mjs CHANGED
@@ -23,6 +23,11 @@ var IndexedDB = class {
23
23
  const tx = db.transaction("store", "readwrite").objectStore("store");
24
24
  await promisifyIDBRequest(tx.put(file));
25
25
  }
26
+ async delete(url) {
27
+ const db = await this.#db;
28
+ const tx = db.transaction("store", "readwrite").objectStore("store");
29
+ await promisifyIDBRequest(tx.delete(url));
30
+ }
26
31
  };
27
32
  var MemoryCache = class {
28
33
  #cache = /* @__PURE__ */ new Map();
@@ -32,6 +37,9 @@ var MemoryCache = class {
32
37
  async put(file) {
33
38
  this.#cache.set(file.url, file);
34
39
  }
40
+ async delete(url) {
41
+ this.#cache.delete(url);
42
+ }
35
43
  };
36
44
  var Cache = class {
37
45
  _db;
@@ -43,41 +51,60 @@ var Cache = class {
43
51
  }
44
52
  }
45
53
  async fetch(url) {
46
- url = normalizeURL(url);
47
54
  const storedRes = await this.query(url);
48
55
  if (storedRes) {
49
56
  return storedRes;
50
57
  }
51
58
  const res = await fetch(url);
52
- if (res.ok) {
53
- const file = {
54
- url: url.href,
55
- content: null,
56
- ctime: Date.now()
57
- };
58
- if (res.redirected) {
59
- file.headers = [["location", res.url]];
60
- this._db.put(file);
59
+ if (!res.ok || !res.headers.has("cache-control")) {
60
+ return res;
61
+ }
62
+ const cacheControl = res.headers.get("cache-control");
63
+ const maxAgeStr = cacheControl.match(/max-age=(\d+)/)?.[1];
64
+ if (!maxAgeStr) {
65
+ return res;
66
+ }
67
+ const maxAge = parseInt(maxAgeStr);
68
+ if (isNaN(maxAge) || maxAge <= 0) {
69
+ return res;
70
+ }
71
+ const createdAt = Date.now();
72
+ const expiresAt = createdAt + maxAge * 1e3;
73
+ const file = {
74
+ url: res.url,
75
+ content: null,
76
+ createdAt,
77
+ expiresAt,
78
+ headers: []
79
+ };
80
+ if (res.redirected) {
81
+ await this._db.put({
82
+ ...file,
83
+ url: url instanceof URL ? url.href : url,
84
+ // raw url
85
+ headers: [["location", res.url]]
86
+ });
87
+ }
88
+ for (const header of ["content-type", "x-typescript-types"]) {
89
+ if (res.headers.has(header)) {
90
+ file.headers.push([header, res.headers.get(header)]);
61
91
  }
62
- const content = await res.arrayBuffer();
63
- const headers = [...res.headers.entries()].filter(
64
- ([k]) => ["cache-control", "content-type", "content-length", "x-typescript-types"].includes(k)
65
- );
66
- file.url = res.url;
67
- file.headers = headers;
68
- file.content = content;
69
- this._db.put(file);
70
- const resp = new Response(content, { headers });
71
- defineProperty(resp, "url", res.url);
72
- defineProperty(resp, "redirected", res.redirected);
73
- return resp;
74
92
  }
75
- return res;
93
+ file.content = await res.arrayBuffer();
94
+ await this._db.put(file);
95
+ const resp = new Response(file.content, { headers: file.headers });
96
+ defineProperty(resp, "url", res.url);
97
+ defineProperty(resp, "redirected", res.redirected);
98
+ return resp;
76
99
  }
77
100
  async query(key) {
78
101
  const url = normalizeURL(key).href;
79
102
  const file = await this._db.get(url);
80
- if (file && file.headers) {
103
+ if (file) {
104
+ if (file.expiresAt < Date.now()) {
105
+ await this._db.delete(url);
106
+ return null;
107
+ }
81
108
  const headers = new Headers(file.headers);
82
109
  if (headers.has("location")) {
83
110
  const redirectedUrl = headers.get("location");
package/dist/core.mjs CHANGED
@@ -1,46 +1,5 @@
1
- // node_modules/@esm.sh/import-map/dist/import-map.mjs
2
- function parseImportMapFromJson(json, baseURL) {
3
- const importMap = {
4
- $baseURL: new URL(baseURL ?? ".", "file:///").href,
5
- imports: {},
6
- scopes: {}
7
- };
8
- const v = JSON.parse(json);
9
- if (isObject(v)) {
10
- const { imports, scopes } = v;
11
- if (isObject(imports)) {
12
- validateImports(imports);
13
- importMap.imports = imports;
14
- }
15
- if (isObject(scopes)) {
16
- validateScopes(scopes);
17
- importMap.scopes = scopes;
18
- }
19
- }
20
- return importMap;
21
- }
22
- function validateImports(imports) {
23
- for (const [k, v] of Object.entries(imports)) {
24
- if (!v || typeof v !== "string") {
25
- delete imports[k];
26
- }
27
- }
28
- }
29
- function validateScopes(imports) {
30
- for (const [k, v] of Object.entries(imports)) {
31
- if (isObject(v)) {
32
- validateImports(v);
33
- } else {
34
- delete imports[k];
35
- }
36
- }
37
- }
38
- function isObject(v) {
39
- return typeof v === "object" && v !== null && !Array.isArray(v);
40
- }
41
-
42
1
  // package.json
43
- var version = "0.3.8";
2
+ var version = "0.4.0";
44
3
 
45
4
  // src/core.ts
46
5
  import { getExtnameFromLanguageId, getLanguageIdFromPath, grammars, initShiki, setDefaultWasmLoader, themes } from "./shiki.mjs";
@@ -270,13 +229,13 @@ function lazy(options) {
270
229
  editor.onDidScrollChange(debunce(storeViewState, 500));
271
230
  workspace.history.onChange((state) => {
272
231
  if (editor.getModel()?.uri.toString() !== state.current) {
273
- workspace._openTextDocument(state.current, editor);
232
+ workspace._openTextDocument(monaco, editor, state.current);
274
233
  }
275
234
  });
276
235
  }
277
236
  if (filename && workspace) {
278
237
  try {
279
- const model = await workspace._openTextDocument(filename, editor);
238
+ const model = await workspace._openTextDocument(monaco, editor, filename);
280
239
  if (code && code !== model.getValue()) {
281
240
  model.setValue(code);
282
241
  }
@@ -288,7 +247,7 @@ function lazy(options) {
288
247
  await workspace.fs.createDirectory(dirname);
289
248
  }
290
249
  await workspace.fs.writeFile(filename, code);
291
- workspace._openTextDocument(filename, editor);
250
+ workspace._openTextDocument(monaco, editor, filename);
292
251
  } else {
293
252
  editor.setModel(monaco.editor.createModel(""));
294
253
  }
@@ -334,7 +293,7 @@ async function loadMonaco(highlighter, workspace, lsp) {
334
293
  let importmapEl = null;
335
294
  if (importmapEl = document.querySelector("script[type='importmap']")) {
336
295
  try {
337
- const { imports = {} } = parseImportMapFromJson(importmapEl.textContent);
296
+ const { imports = {} } = JSON.parse(importmapEl.textContent);
338
297
  if (imports["modern-monaco/editor-core"]) {
339
298
  editorCoreModuleUrl = imports["modern-monaco/editor-core"];
340
299
  }
@@ -385,7 +344,7 @@ async function loadMonaco(highlighter, workspace, lsp) {
385
344
  openCodeEditor: async (editor, resource, selectionOrPosition) => {
386
345
  if (workspace && resource.scheme === "file") {
387
346
  try {
388
- await workspace._openTextDocument(resource.toString(), editor, selectionOrPosition);
347
+ await workspace._openTextDocument(monaco, editor, resource.toString(), selectionOrPosition);
389
348
  return true;
390
349
  } catch (err) {
391
350
  if (err instanceof NotFoundError) {
@@ -187738,7 +187738,7 @@ var QuickPickItemElement = class extends BaseQuickPickItemElement {
187738
187738
  this._onChecked = _onChecked;
187739
187739
  this.item = item;
187740
187740
  this._separator = _separator;
187741
- this._checked = false;
187741
+ this._checked = item.picked;
187742
187742
  this.onChecked = hasCheckbox ? Event.map(Event.filter(this._onChecked.event, (e) => e.element === this), (e) => e.checked) : Event.None;
187743
187743
  this._saneDetail = item.detail;
187744
187744
  this._labelHighlights = item.highlights?.label;
@@ -205419,7 +205419,7 @@ var QuickPickItemKind = /* @__PURE__ */ ((QuickPickItemKind2) => {
205419
205419
  return QuickPickItemKind2;
205420
205420
  })(QuickPickItemKind || {});
205421
205421
  function showInputBox(options2 = {}) {
205422
- const { placeHolder, title, value, password, ignoreFocusOut, validateInput } = options2;
205422
+ const { placeHolder, title, value, password, ignoreFocusOut, validateInput, prompt } = options2;
205423
205423
  const quickInputService = StandaloneServices.get(IQuickInputService);
205424
205424
  const box = quickInputService.createInputBox();
205425
205425
  const validateValue = validateInput ? (value2) => {
@@ -205442,6 +205442,9 @@ function showInputBox(options2 = {}) {
205442
205442
  if (placeHolder) {
205443
205443
  box.placeholder = placeHolder;
205444
205444
  }
205445
+ if (prompt) {
205446
+ box.prompt = prompt;
205447
+ }
205445
205448
  if (password) {
205446
205449
  box.password = true;
205447
205450
  }
@@ -205476,7 +205479,7 @@ function showInputBox(options2 = {}) {
205476
205479
  });
205477
205480
  }
205478
205481
  function showQuickPick(items, options2 = {}) {
205479
- const { placeHolder, title, ignoreFocusOut, matchOnDescription, matchOnDetail, canPickMany, onDidSelectItem } = options2;
205482
+ const { placeHolder, title, ignoreFocusOut, matchOnDescription, matchOnDetail, canPickMany, onDidSelectItem, prompt } = options2;
205480
205483
  const quickInputService = StandaloneServices.get(IQuickInputService);
205481
205484
  const pick = quickInputService.createQuickPick();
205482
205485
  if (title) {
@@ -205485,6 +205488,9 @@ function showQuickPick(items, options2 = {}) {
205485
205488
  if (placeHolder) {
205486
205489
  pick.placeholder = placeHolder;
205487
205490
  }
205491
+ if (prompt) {
205492
+ pick.prompt = prompt;
205493
+ }
205488
205494
  if (ignoreFocusOut) {
205489
205495
  pick.ignoreFocusOut = true;
205490
205496
  }
@@ -205509,7 +205515,7 @@ function showQuickPick(items, options2 = {}) {
205509
205515
  if (onDidSelectItem) {
205510
205516
  pick.onDidChangeActive((v) => {
205511
205517
  v.forEach((item) => {
205512
- onDidSelectItem(convertPickItem(item?._kind_string ? item.label : item));
205518
+ onDidSelectItem(convertPickItem(item?.plainMode ? item.label : item));
205513
205519
  });
205514
205520
  });
205515
205521
  }
@@ -205517,10 +205523,10 @@ function showQuickPick(items, options2 = {}) {
205517
205523
  return new Promise((resolve3) => {
205518
205524
  pick.onDidAccept(() => {
205519
205525
  if (canPickMany) {
205520
- resolve3(pick.selectedItems.map((item) => item._kind_string ? item.label : item));
205526
+ resolve3(pick.selectedItems.map((item) => item.plainMode ? item.label : item));
205521
205527
  } else {
205522
205528
  let selectedItem = pick.selectedItems[0];
205523
- resolve3(selectedItem?._kind_string ? selectedItem.label : selectedItem);
205529
+ resolve3(selectedItem?.plainMode ? selectedItem.label : selectedItem);
205524
205530
  }
205525
205531
  pick.dispose();
205526
205532
  });
@@ -205589,7 +205595,7 @@ function normalizeUri(uri) {
205589
205595
  }
205590
205596
  function convertPickItem(item) {
205591
205597
  if (typeof item === "string") {
205592
- return { type: "item", label: item, _kind_string: true };
205598
+ return { type: "item", label: item, plainMode: true };
205593
205599
  }
205594
205600
  if (item.kind === -1 /* Separator */) {
205595
205601
  return { type: "separator", ...item };
@@ -1230,7 +1230,7 @@ function lspRequest(req, token) {
1230
1230
  });
1231
1231
  }
1232
1232
  var registry = /* @__PURE__ */ new Map();
1233
- function registerBasicFeatures(languageId, worker, completionTriggerCharacters, workspace) {
1233
+ function registerBasicFeatures(languageId, worker, completionTriggerCharacters, workspace, diagnosticsOptions) {
1234
1234
  const { editor, languages } = monaco;
1235
1235
  const onDispose = async (model) => {
1236
1236
  const workerProxy = await worker.withSyncedResources([]);
@@ -1246,7 +1246,9 @@ function registerBasicFeatures(languageId, worker, completionTriggerCharacters,
1246
1246
  onDispose(model);
1247
1247
  }
1248
1248
  });
1249
- registerDiagnostics(languageId, worker);
1249
+ if (diagnosticsOptions?.validate ?? true) {
1250
+ registerDiagnostics(languageId, worker, diagnosticsOptions);
1251
+ }
1250
1252
  languages.registerCompletionItemProvider(languageId, new CompletionAdapter(worker, completionTriggerCharacters));
1251
1253
  languages.registerHoverProvider(languageId, new HoverAdapter(worker));
1252
1254
  languages.registerDocumentSymbolProvider(languageId, new DocumentSymbolAdapter(worker));
@@ -1277,14 +1279,28 @@ function registerBasicFeatures(languageId, worker, completionTriggerCharacters,
1277
1279
  });
1278
1280
  }
1279
1281
  }
1280
- function registerDiagnostics(languageId, worker) {
1282
+ function registerDiagnostics(languageId, worker, options) {
1281
1283
  const { editor } = monaco;
1282
1284
  const modelChangeListeners = /* @__PURE__ */ new Map();
1283
1285
  const doValidate = async (model) => {
1284
1286
  const workerProxy = await worker.withSyncedResources([model.uri]);
1285
1287
  const diagnostics = await workerProxy.doValidation(model.uri.toString());
1286
1288
  if (diagnostics && !model.isDisposed()) {
1287
- const markers = diagnostics.map(diagnosticToMarker);
1289
+ let markers = diagnostics.map(diagnosticToMarker);
1290
+ if (options?.filter) {
1291
+ markers = markers.filter(options.filter);
1292
+ }
1293
+ if (options?.codesToIgnore) {
1294
+ markers = markers.filter((marker) => {
1295
+ const code = typeof marker.code === "string" ? marker.code : marker.code?.value;
1296
+ for (const codeToIgnore of options.codesToIgnore) {
1297
+ if (code && code === String(codeToIgnore)) {
1298
+ return false;
1299
+ }
1300
+ }
1301
+ return true;
1302
+ });
1303
+ }
1288
1304
  monaco.editor.setModelMarkers(model, languageId, markers);
1289
1305
  }
1290
1306
  };
@@ -1,12 +1,20 @@
1
1
  // src/lsp/css/setup.ts
2
2
  import * as client from "../client.mjs";
3
3
  async function setup(monaco, languageId, languageSettings, formattingOptions, workspace) {
4
+ const validProperties = languageSettings?.validProperties;
5
+ const dataProviders = { ...languageSettings?.dataProviders };
6
+ if (validProperties) {
7
+ dataProviders["#valid-properties"] = {
8
+ version: 1.1,
9
+ properties: validProperties.map((property) => ({ name: property }))
10
+ };
11
+ }
4
12
  const { tabSize, insertSpaces, insertFinalNewline, trimFinalNewlines } = formattingOptions ?? {};
5
13
  const createData = {
6
14
  language: languageId,
7
15
  data: {
8
- useDefaultDataProvider: true,
9
- ...languageSettings
16
+ useDefaultDataProvider: languageSettings?.useDefaultDataProvider ?? true,
17
+ dataProviders
10
18
  },
11
19
  format: {
12
20
  tabSize,
@@ -25,7 +33,7 @@ async function setup(monaco, languageId, languageSettings, formattingOptions, wo
25
33
  host: client.createHost(workspace)
26
34
  });
27
35
  client.init(monaco);
28
- client.registerBasicFeatures(languageId, worker, ["/", "-", ":", "("], workspace);
36
+ client.registerBasicFeatures(languageId, worker, ["/", "-", ":", "("], workspace, languageSettings?.diagnosticsOptions);
29
37
  client.registerCodeAction(languageId, worker);
30
38
  client.registerColorPresentation(languageId, worker);
31
39
  client.registerDocumentLinks(languageId, worker);