@likec4/language-server 1.48.0 → 1.49.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.
Files changed (78) hide show
  1. package/browser/package.json +2 -2
  2. package/browser-worker/package.json +2 -2
  3. package/dist/THIRD-PARTY-LICENSES.md +178 -0
  4. package/dist/_chunks/ConfigurableLayouter.mjs +1 -1956
  5. package/dist/_chunks/LikeC4FileSystem.mjs +3 -0
  6. package/dist/_chunks/LikeC4Views.mjs +34 -0
  7. package/dist/_chunks/ProjectsManager.mjs +1 -0
  8. package/dist/_chunks/WithMCPServer.mjs +481 -0
  9. package/dist/_chunks/icons.mjs +2 -5211
  10. package/dist/_chunks/{LikeC4LanguageServices.d.mts → index.d.mts} +1836 -707
  11. package/dist/_chunks/libs/@msgpack/msgpack.mjs +1 -805
  12. package/dist/_chunks/libs/eventemitter3.mjs +1 -243
  13. package/dist/_chunks/libs/fast-equals.mjs +1 -446
  14. package/dist/_chunks/libs/p-queue.mjs +1 -449
  15. package/dist/_chunks/libs/parse-ms.mjs +1 -36
  16. package/dist/_chunks/libs/picomatch.mjs +1 -1673
  17. package/dist/_chunks/libs/pretty-ms.mjs +1 -80
  18. package/dist/_chunks/libs/remeda.mjs +1 -482
  19. package/dist/_chunks/libs/strip-indent.mjs +1 -15
  20. package/dist/_chunks/libs/ufo.mjs +1 -166
  21. package/dist/_chunks/logger.mjs +1 -0
  22. package/dist/_chunks/rolldown-runtime.mjs +1 -42
  23. package/dist/_chunks/utils.mjs +1 -0
  24. package/dist/browser/index.d.mts +10 -0
  25. package/dist/browser/index.mjs +1 -0
  26. package/dist/browser/worker.mjs +1 -0
  27. package/dist/bundled.d.mts +2 -3
  28. package/dist/bundled.mjs +1 -51
  29. package/dist/filesystem/index.d.mts +2 -4
  30. package/dist/filesystem/index.mjs +1 -3
  31. package/dist/index.d.mts +38 -3
  32. package/dist/index.mjs +1 -48
  33. package/dist/likec4lib.d.mts +10 -3
  34. package/dist/likec4lib.mjs +1 -4
  35. package/dist/mcp/index.d.mts +2 -4
  36. package/dist/mcp/index.mjs +1 -3
  37. package/dist/module.d.mts +126 -4
  38. package/dist/module.mjs +1 -3
  39. package/dist/protocol.d.mts +314 -1
  40. package/dist/protocol.mjs +1 -3
  41. package/filesystem/package.json +4 -0
  42. package/mcp/package.json +4 -0
  43. package/module/package.json +4 -0
  44. package/package.json +79 -56
  45. package/LICENSE +0 -21
  46. package/dist/LikeC4LanguageServices.d.mts +0 -4
  47. package/dist/LikeC4LanguageServices.mjs +0 -3
  48. package/dist/_chunks/LikeC4LanguageServices.mjs +0 -725
  49. package/dist/_chunks/ast.d.mts +0 -1444
  50. package/dist/_chunks/ast.mjs +0 -2375
  51. package/dist/_chunks/ast2.mjs +0 -176
  52. package/dist/_chunks/common-exports.mjs +0 -0
  53. package/dist/_chunks/filesystem.mjs +0 -58
  54. package/dist/_chunks/grammar.mjs +0 -8
  55. package/dist/_chunks/libs/@hono/node-server.mjs +0 -436
  56. package/dist/_chunks/libs/hono.mjs +0 -1829
  57. package/dist/_chunks/likec4lib.mjs +0 -9
  58. package/dist/_chunks/mcp.mjs +0 -33
  59. package/dist/_chunks/module.mjs +0 -28
  60. package/dist/_chunks/module2.mjs +0 -6576
  61. package/dist/_chunks/protocol.d.mts +0 -311
  62. package/dist/_chunks/protocol.mjs +0 -78
  63. package/dist/ast.d.mts +0 -4
  64. package/dist/ast.mjs +0 -4
  65. package/dist/browser-worker.mjs +0 -6
  66. package/dist/browser.d.mts +0 -11
  67. package/dist/browser.mjs +0 -27
  68. package/dist/common-exports.d.mts +0 -4
  69. package/dist/common-exports.mjs +0 -5
  70. package/dist/generated/ast.d.mts +0 -2
  71. package/dist/generated/ast.mjs +0 -3
  72. package/dist/generated/grammar.d.mts +0 -6
  73. package/dist/generated/grammar.mjs +0 -3
  74. package/dist/generated/module.d.mts +0 -14
  75. package/dist/generated/module.mjs +0 -3
  76. package/dist/generated-lib/icons.d.mts +0 -4
  77. package/dist/generated-lib/icons.mjs +0 -3
  78. /package/dist/{browser-worker.d.mts → browser/worker.d.mts} +0 -0
@@ -1,725 +0,0 @@
1
- import { r as __toESM } from "./rolldown-runtime.mjs";
2
- import { r as isLikeC4Builtin } from "./likec4lib.mjs";
3
- import { C as t$5, F as t$2, M as n, N as t$4, P as t, _ as e$1, i as t$3, o as e, u as t$1 } from "./libs/remeda.mjs";
4
- import { t as deepEqual } from "./libs/fast-equals.mjs";
5
- import { t as require_picomatch } from "./libs/picomatch.mjs";
6
- import { a as joinRelativeURL, c as withTrailingSlash, d as withoutProtocol, f as withoutTrailingSlash, i as isRelative, o as joinURL, s as parseFilename, t as cleanDoubleSlashes } from "./libs/ufo.mjs";
7
- import { errorFromLogRecord, getMessageOnlyFormatter, getTextFormatter, loggable, logger, wrapError } from "@likec4/log";
8
- import { Disposable, OperationCancelled, URI, WorkspaceCache, isOperationCancelled } from "langium";
9
- import { BiMap, DefaultMap, compareNaturalHierarchically, invariant, memoizeProp, nonNullable, nonexhaustive } from "@likec4/core/utils";
10
- import { DiagnosticSeverity } from "vscode-languageserver-types";
11
- import { isLikeC4Config, normalizeIncludeConfig, validateProjectConfig } from "@likec4/config";
12
- import { LikeC4Model } from "@likec4/core/model";
13
- import { nonexhaustive as nonexhaustive$1 } from "@likec4/core";
14
- import { computeProjectsView } from "@likec4/core/compute-view";
15
-
16
- //#region src/logger.ts
17
- const logger$3 = logger.getChild("server");
18
- /**
19
- * Logs an error as warning (not critical)
20
- */
21
- function logWarnError(err) {
22
- logger$3.warn(loggable(err));
23
- }
24
- function getLspConnectionSink(connection, props) {
25
- const format = props?.formatter ?? getTextFormatter({ format: ({ category, message }) => {
26
- return `${category} ${message}`;
27
- } });
28
- return (logObj) => {
29
- try {
30
- switch (logObj.level) {
31
- case "trace":
32
- case "debug":
33
- connection.console.debug(format(logObj));
34
- break;
35
- case "info":
36
- connection.console.info(format(logObj));
37
- break;
38
- case "warning":
39
- connection.console.warn(format(logObj));
40
- break;
41
- case "error":
42
- case "fatal":
43
- connection.console.error(format(logObj));
44
- break;
45
- default: nonexhaustive(logObj.level);
46
- }
47
- } catch (e) {
48
- console.error("Error while logging to LSP connection:", e);
49
- }
50
- };
51
- }
52
- function getTelemetrySink(connection) {
53
- const messageOnly = getMessageOnlyFormatter();
54
- return (logObj) => {
55
- try {
56
- switch (logObj.level) {
57
- case "error":
58
- case "fatal": {
59
- const err = errorFromLogRecord(logObj);
60
- if (err) connection.telemetry.logEvent({
61
- eventName: "error",
62
- message: `${err.name}: ${err.message}`,
63
- category: logObj.category.join("."),
64
- ...err.stack && { stack: err.stack }
65
- });
66
- else connection.telemetry.logEvent({
67
- eventName: "error",
68
- message: messageOnly(logObj),
69
- category: logObj.category.join(".")
70
- });
71
- break;
72
- }
73
- }
74
- } catch (e) {
75
- console.error("Error while logging to LSP connection:", e);
76
- }
77
- };
78
- }
79
-
80
- //#endregion
81
- //#region src/workspace/ProjectsManager.ts
82
- var import_picomatch = /* @__PURE__ */ __toESM(require_picomatch(), 1);
83
- const logger$2 = logger$3.getChild("ProjectsManager");
84
- function normalizeUri(uri) {
85
- if (URI.isUri(uri)) return uri.toString();
86
- else if (typeof uri === "string") return uri.startsWith("file://") ? uri : URI.file(uri).toString();
87
- else return uri.uri.toString();
88
- }
89
- /**
90
- * Compare function to ensure consistent order
91
- */
92
- const compare = compareNaturalHierarchically("/", true);
93
- const compareUri = (a, b) => compare(withoutTrailingSlash(a.path), withoutTrailingSlash(b.path));
94
- /**
95
- * Returns a predicate that checks if the given path is included in the project folder.
96
- */
97
- function isParentFolderFor(uri) {
98
- const path = normalizeUri(uri);
99
- return (p) => path.startsWith(p.folder);
100
- }
101
- function ProjectFolder(folder) {
102
- folder = normalizeUri(folder);
103
- return withTrailingSlash(folder);
104
- }
105
- const DefaultProject = {
106
- id: "default",
107
- config: {
108
- name: "default",
109
- exclude: ["**/node_modules/**"]
110
- },
111
- exclude: (0, import_picomatch.default)("**/node_modules/**", { dot: true }),
112
- includeConfig: {
113
- paths: [],
114
- maxDepth: 3,
115
- fileThreshold: 30
116
- }
117
- };
118
- var ProjectsManager = class ProjectsManager {
119
- /**
120
- * The global project ID used for all documents
121
- * that are not part of a specific project.
122
- */
123
- static DefaultProjectId = DefaultProject.id;
124
- #updateListeners = [];
125
- /**
126
- * Configured default project ID.
127
- * (it is used in CLI and Vite plugin)
128
- */
129
- #defaultProjectId = void 0;
130
- /**
131
- * Cached default project.
132
- */
133
- #defaultProject = void 0;
134
- /**
135
- * The mapping between project config files and project IDs.
136
- */
137
- #projectIdToFolder = new BiMap();
138
- /**
139
- * Registered projects.
140
- * Sorted descending by the number of segments in the folder path.
141
- * This ensures that the most specific project is used for a document.
142
- */
143
- #projects = [];
144
- /**
145
- * This is a cached lookup for performance.
146
- */
147
- #lookupById = new DefaultMap((id) => {
148
- if (id === ProjectsManager.DefaultProjectId) {
149
- const folder = ProjectFolder(this.getWorkspaceFolder());
150
- return {
151
- id,
152
- config: DefaultProject.config,
153
- folder,
154
- folderUri: URI.parse(folder),
155
- exclude: DefaultProject.exclude,
156
- includeConfig: DefaultProject.includeConfig
157
- };
158
- }
159
- return nonNullable(this.#projects.find((p) => p.id === id), `Project ${id} not found`);
160
- });
161
- #excludedDocuments = /* @__PURE__ */ new WeakMap();
162
- constructor(services) {
163
- this.services = services;
164
- logger$2.debug`created`;
165
- }
166
- /**
167
- * Returns:
168
- * - configured default project ID if set
169
- * - the default project ID if there are no projects.
170
- * - the ID of the only project
171
- * - undefined if there are multiple projects.
172
- */
173
- get defaultProjectId() {
174
- if (this.#defaultProjectId) return this.#defaultProjectId;
175
- if (this.#projects.length > 1) return;
176
- return this.#projects[0]?.id ?? ProjectsManager.DefaultProjectId;
177
- }
178
- set defaultProjectId(id) {
179
- if (id === this.#defaultProjectId) return;
180
- this.#defaultProject = void 0;
181
- if (!id || id === ProjectsManager.DefaultProjectId) {
182
- logger$2.debug`reset default project ID`;
183
- this.#defaultProjectId = void 0;
184
- return;
185
- }
186
- invariant(this.#projects.find((p) => p.id === id), `Project "${id}" not found`);
187
- logger$2.debug`set default project ID to ${id}`;
188
- this.#defaultProjectId = id;
189
- }
190
- get default() {
191
- if (!this.#defaultProject) {
192
- const id = this.defaultProjectId ?? ProjectsManager.DefaultProjectId;
193
- this.#defaultProject = this.#lookupById.get(id);
194
- }
195
- return this.#defaultProject;
196
- }
197
- get all() {
198
- if (t(this.#projects, 1)) {
199
- const ids = [...t$1(this.#projects, e("id")), DefaultProject.id];
200
- if (this.#defaultProjectId) {
201
- const idx = ids.findIndex((p) => p === this.#defaultProjectId);
202
- if (idx > 0) {
203
- const [defaultProject] = ids.splice(idx, 1);
204
- return [defaultProject, ...ids];
205
- }
206
- }
207
- return ids;
208
- }
209
- return [DefaultProject.id];
210
- }
211
- getProject(arg) {
212
- const id = typeof arg === "string" ? arg : arg.likec4ProjectId || this.belongsTo(arg);
213
- const project = this.#lookupById.get(id);
214
- return {
215
- id,
216
- folderUri: project.folderUri,
217
- config: project.config,
218
- ...project.includePaths && { includePaths: t$1(project.includePaths, e("uri")) }
219
- };
220
- }
221
- /**
222
- * Returns all projects that include the specified folder, or inside the folder.
223
- */
224
- findAllProjectsByFolder(folder) {
225
- const projectFolder = ProjectFolder(folder);
226
- const isInsideOrIncludes = (p) => p.folder.startsWith(projectFolder) || projectFolder.startsWith(p.folder);
227
- return this.#projects.filter(isInsideOrIncludes);
228
- }
229
- /**
230
- * Validates and ensures the project ID.
231
- * If no project ID is specified, returns default project ID
232
- * If there are multiple projects and default project is not set, throws an error
233
- */
234
- ensureProjectId(projectId) {
235
- if (projectId === ProjectsManager.DefaultProjectId) return this.defaultProjectId ?? ProjectsManager.DefaultProjectId;
236
- if (projectId) {
237
- invariant(this.#projectIdToFolder.has(projectId), `Project ID ${projectId} is not registered`);
238
- return projectId;
239
- }
240
- return nonNullable(this.defaultProjectId, () => `Specify exact project, known: [${[...this.#projectIdToFolder.keys()].join(", ")}]`);
241
- }
242
- /**
243
- * Validates and ensures the project.
244
- */
245
- ensureProject(projectId) {
246
- projectId = this.ensureProjectId(projectId);
247
- return this.getProject(projectId);
248
- }
249
- hasMultipleProjects() {
250
- return this.#projects.length > 1;
251
- }
252
- /**
253
- * Checks if the specified document should be excluded from processing.
254
- */
255
- isExcluded(document) {
256
- if (typeof document === "string" || URI.isUri(document)) {
257
- let docUriAsString = normalizeUri(document);
258
- const project = this.findProjectForDocument(docUriAsString);
259
- if (!project.exclude) return false;
260
- const input = withoutProtocol(docUriAsString);
261
- return project.exclude(input);
262
- }
263
- let isExcluded = this.#excludedDocuments.get(document);
264
- if (isExcluded === void 0) {
265
- isExcluded = this.isExcluded(document.uri);
266
- this.#excludedDocuments.set(document, isExcluded);
267
- }
268
- return isExcluded;
269
- }
270
- /**
271
- * Checks if the specified document is included by the project:
272
- * - if the document belongs to the project and is not excluded
273
- * - if the document is included by the project
274
- */
275
- isIncluded(projectId, document) {
276
- if (typeof document !== "string" && !URI.isUri(document)) return this.isIncluded(projectId, document.uri);
277
- if (this.belongsTo(document) === projectId) return !this.isExcluded(document);
278
- let includePaths = this.#lookupById.get(projectId)?.includePaths;
279
- if (!includePaths) return false;
280
- return includePaths.some(isParentFolderFor(document));
281
- }
282
- /**
283
- * Checks if it is a config file and it is not excluded by default exclude pattern
284
- *
285
- * @param entry The file system entry to check
286
- */
287
- isConfigFile(entry) {
288
- const filename = parseFilename(entry.toString(), { strict: false })?.toLowerCase();
289
- const isConfigFile = !!filename && isLikeC4Config(filename);
290
- if (isConfigFile) {
291
- if (DefaultProject.exclude(entry.path)) {
292
- logger$2.debug`exclude config file ${entry.path}`;
293
- return false;
294
- }
295
- }
296
- return isConfigFile;
297
- }
298
- /**
299
- * Registers likec4 project by config file.
300
- */
301
- async registerConfigFile(configFile, cancelToken) {
302
- if (DefaultProject.exclude(configFile.path)) throw new Error(`Path to ${configFile.fsPath} is excluded by: ${DefaultProject.config.exclude.join(", ")}`);
303
- if (!this.isConfigFile(configFile)) throw new Error(`${configFile.fsPath} is not a valid LikeC4 config filename.`);
304
- try {
305
- const config = await this.services.workspace.FileSystemProvider.loadProjectConfig(configFile);
306
- const path = joinRelativeURL(configFile.path, "..");
307
- const folderUri = configFile.with({ path });
308
- return await this.registerProject({
309
- config,
310
- folderUri
311
- }, cancelToken);
312
- } catch (error) {
313
- if (!isOperationCancelled(error)) {
314
- this.services.lsp.Connection?.window.showErrorMessage(`LikeC4: Failed to register project at ${configFile.fsPath}`);
315
- throw wrapError(error, `Failed to register project config ${configFile.fsPath}:\n`);
316
- }
317
- return Promise.reject(error);
318
- }
319
- }
320
- /**
321
- * Registers (or reloads) likec4 project by config file or config object.
322
- * If there is some project registered at same folder, it will be reloaded.
323
- */
324
- async registerProject(opts, cancelToken) {
325
- const config = validateProjectConfig(opts.config);
326
- const folder = ProjectFolder(opts.folderUri);
327
- let project = this.#projects.find((p) => p.folder === folder);
328
- if (project && deepEqual(project.config, config)) return project;
329
- let mustReset = false;
330
- let id;
331
- if (!project) {
332
- if (this.#projectIdToFolder.has(config.name)) logger$2.warn`Project "${config.name}" already exists, generating unique ID`;
333
- id = this.uniqueProjectId(config.name);
334
- const includeConfig = normalizeIncludeConfig(config.include);
335
- project = {
336
- id,
337
- config,
338
- folder,
339
- folderUri: URI.parse(folder),
340
- includeConfig
341
- };
342
- mustReset = this.#projects.some((p) => p.folder.startsWith(folder) || folder.startsWith(p.folder));
343
- this.#projects = t$2([...this.#projects, project], t$3((a, b) => compareUri(a.folderUri, b.folderUri)));
344
- logger$2.info`register project ${project.id} folder: ${folder}`;
345
- } else {
346
- mustReset = true;
347
- if (project.config.name !== config.name) {
348
- this.#projectIdToFolder.delete(project.id);
349
- logger$2.info`unregister project ${project.id} folder: ${folder}`;
350
- id = this.uniqueProjectId(config.name);
351
- project.id = id;
352
- logger$2.info`re-register project ${project.id} folder: ${folder}`;
353
- } else {
354
- id = project.id;
355
- logger$2.info`update project ${project.id} on config change`;
356
- }
357
- project.config = config;
358
- const includeConfig = normalizeIncludeConfig(config.include);
359
- project.includeConfig = includeConfig;
360
- }
361
- if (e$1(config.exclude)) project.exclude = DefaultProject.exclude;
362
- else if (t(config.exclude, 1)) {
363
- const patterns = t$1(config.exclude, (p) => {
364
- if (!isRelative(p) && !p.startsWith("**")) p = joinURL("**", p);
365
- return cleanDoubleSlashes(joinRelativeURL(project.folderUri.path, p));
366
- });
367
- project.exclude = (0, import_picomatch.default)(patterns, {
368
- contains: true,
369
- dot: true
370
- });
371
- }
372
- if (project.includeConfig.paths && t(project.includeConfig.paths, 1)) {
373
- project.includePaths = t$1(project.includeConfig.paths, (includePath) => {
374
- const resolvedPath = joinRelativeURL(project.folderUri.path, includePath);
375
- const uri = project.folderUri.with({ path: resolvedPath });
376
- return {
377
- uri,
378
- folder: ProjectFolder(uri)
379
- };
380
- });
381
- logger$2.debug`project ${project.id} include paths: ${project.includePaths.map((p) => p.uri.fsPath).join(", ")}`;
382
- for (const includePath of project.includePaths) for (const otherProject of this.#projects) {
383
- if (otherProject.id === project.id) continue;
384
- if (includePath.folder.startsWith(otherProject.folder) || otherProject.folder.startsWith(includePath.folder)) {
385
- mustReset = true;
386
- logger$2.warn("Project \"{projectId}\" include path \"{includePath}\" overlaps with project \"{otherProjectId}\" folder. Files in overlapping areas will only belong to one project.", {
387
- projectId: project.id,
388
- includePath: includePath.folder,
389
- otherProjectId: otherProject.id
390
- });
391
- }
392
- if (otherProject.includePaths) {
393
- for (const otherIncludePath of otherProject.includePaths) if (includePath.folder.startsWith(otherIncludePath.folder) || otherIncludePath.folder.startsWith(includePath.folder)) {
394
- mustReset = true;
395
- logger$2.warn("Project \"{projectId}\" include path \"{includePath}\" overlaps with project \"{otherProjectId}\" include path \"{otherIncludePath}\". Files in overlapping areas will only belong to one project.", {
396
- projectId: project.id,
397
- includePath: includePath.folder,
398
- otherProjectId: otherProject.id,
399
- otherIncludePath: otherIncludePath.folder
400
- });
401
- }
402
- }
403
- }
404
- } else delete project.includePaths;
405
- this.#defaultProject = void 0;
406
- this.#projectIdToFolder.set(project.id, folder);
407
- this.#lookupById.clear();
408
- if (this.#activeReload) return project;
409
- if (mustReset) await this.rebuidProject(project.id, cancelToken).catch((error) => {
410
- if (isOperationCancelled(error)) return Promise.reject(error);
411
- logger$2.warn("Failed to rebuild project {projectId} after config change", {
412
- projectId: project.id,
413
- error
414
- });
415
- return Promise.resolve();
416
- });
417
- this.notifyListeners();
418
- return project;
419
- }
420
- /**
421
- * Determines which project the given document belongs to.
422
- * If the document does not belong to any project, returns the default project ID.
423
- */
424
- belongsTo(document) {
425
- if (URI.isUri(document) || typeof document === "string") {
426
- const documentUri = normalizeUri(document);
427
- return this.findProjectForDocument(documentUri).id;
428
- }
429
- return this.documentBelongsTo.get(document, () => {
430
- return this.findProjectForDocument(normalizeUri(document.uri));
431
- }).id;
432
- }
433
- #activeReload = null;
434
- async reloadProjects(cancelToken) {
435
- if (this.#activeReload) {
436
- logger$2.debug`reload projects is already in progress, waiting`;
437
- return await this.#activeReload.catch(() => {});
438
- }
439
- logger$2.debug`schedule reload projects`;
440
- this.#activeReload = Promise.resolve().then(() => this._reloadProjects(cancelToken)).catch((error) => {
441
- if (!isOperationCancelled(error)) logger$2.warn("Failed to reload projects", { error });
442
- return Promise.reject(error);
443
- }).finally(() => {
444
- this.#activeReload = null;
445
- this.notifyListeners();
446
- });
447
- return await this.#activeReload;
448
- }
449
- async _reloadProjects(cancelToken) {
450
- const folders = this.services.workspace.WorkspaceManager.workspaceFolders;
451
- if (!folders) {
452
- logger$2.warn("No workspace folders found");
453
- return;
454
- }
455
- logger$2.debug`start reload projects`;
456
- const configFiles = [];
457
- for (const folder of folders) try {
458
- logger$2.debug`scan projects in folder ${folder.uri}`;
459
- const files = await this.services.workspace.FileSystemProvider.scanProjectFiles(URI.parse(folder.uri));
460
- for (const file of files) if (file.isFile && this.isConfigFile(file.uri)) {
461
- logger$2.debug`found config ${file.uri.fsPath}`;
462
- configFiles.push(file.uri);
463
- }
464
- } catch (error) {
465
- logger$2.error("Failed to scanProjectFiles, {folder}", {
466
- folder: folder.uri,
467
- error
468
- });
469
- }
470
- if (configFiles.length === 0 && this.#projects.length !== 0) logger$2.warning("No config files found, but some projects were registered before");
471
- configFiles.sort(compareUri);
472
- this.#projects = [];
473
- this.#projectIdToFolder.clear();
474
- this.#lookupById.clear();
475
- for (const uri of configFiles) {
476
- if (cancelToken?.isCancellationRequested) break;
477
- await this.registerConfigFile(uri, cancelToken).catch((error) => {
478
- if (!isOperationCancelled(error)) logger$2.warn(loggable(error));
479
- });
480
- }
481
- this.reset();
482
- if (cancelToken?.isCancellationRequested) throw OperationCancelled;
483
- await this.services.workspace.WorkspaceManager.rebuildAll(cancelToken);
484
- }
485
- uniqueProjectId(name) {
486
- let id = name;
487
- let i = 1;
488
- while (this.#projectIdToFolder.has(id)) id = `${name}-${i++}`;
489
- return id;
490
- }
491
- reset() {
492
- logger$2.debug("reset");
493
- this.#defaultProject = void 0;
494
- if (this.#defaultProjectId && !this.#projectIdToFolder.has(this.#defaultProjectId)) this.#defaultProjectId = void 0;
495
- this.services.workspace.LangiumDocuments.resetProjectIds();
496
- this.documentBelongsTo.clear();
497
- this.mappingsToProject.clear();
498
- this.#lookupById.clear();
499
- this.#excludedDocuments = /* @__PURE__ */ new WeakMap();
500
- }
501
- async rebuidProject(projectId, cancelToken) {
502
- this.#defaultProject = void 0;
503
- const project = this.#projects.find((p) => p.id === projectId) ?? this.default;
504
- if (project.id !== projectId) logger$2.warn`Project ${projectId} not found, rebuilding default project ${project.id}`;
505
- const log = logger$2.getChild(project.id);
506
- const folder = project.folder;
507
- const includePaths = project.includePaths;
508
- const allDocs = this.services.workspace.LangiumDocuments.allKnownDocuments.filter((doc) => !isLikeC4Builtin(doc.uri)).toArray();
509
- if (allDocs.length === 0) return;
510
- const docs = t$2(allDocs, n((doc) => {
511
- if (project.exclude?.(doc.uri.path)) return false;
512
- const docUriStr = normalizeUri(doc.uri);
513
- if (docUriStr.startsWith(folder)) return true;
514
- if (includePaths && includePaths.some(isParentFolderFor(docUriStr))) return true;
515
- const docdir = withTrailingSlash(joinRelativeURL(docUriStr, ".."));
516
- return docdir.startsWith(folder) || folder.startsWith(docdir);
517
- }), t$1((d) => d.uri));
518
- if (docs.length === 0) {
519
- log.debug("no documents in project, skipping rebuild");
520
- return;
521
- }
522
- log.info("rebuild project documents: {docs}", { docs: docs.length });
523
- this.reset();
524
- await this.services.workspace.DocumentBuilder.update(docs, [], cancelToken).catch((error) => {
525
- log.warn("Failed to rebuild project", { error });
526
- });
527
- }
528
- findProjectForDocument(documentUri) {
529
- return this.mappingsToProject.get(documentUri, () => {
530
- const hasThisDoc = isParentFolderFor(documentUri);
531
- const project = this.#projects.find(hasThisDoc);
532
- if (project) return project;
533
- return this.#projects.find(({ includePaths }) => {
534
- return !!includePaths && includePaths.some(hasThisDoc);
535
- }) ?? this.default;
536
- });
537
- }
538
- get mappingsToProject() {
539
- return memoizeProp(this, "_mappingsToProject", () => new WorkspaceCache(this.services));
540
- }
541
- /**
542
- * The mapping between documents and projects they belong to.
543
- * Lazy-created due to initialization order of the LanguageServer
544
- */
545
- get documentBelongsTo() {
546
- return memoizeProp(this, "_documentBelongsTo", () => new WorkspaceCache(this.services));
547
- }
548
- /**
549
- * Returns all include paths from all projects.
550
- * Used by WorkspaceManager to scan additional directories for C4 files.
551
- */
552
- getAllIncludePaths() {
553
- const result = [];
554
- for (const project of this.#projects) if (project.includePaths) for (const includePath of project.includePaths) result.push({
555
- projectId: project.id,
556
- includePath: includePath.uri,
557
- includeConfig: project.includeConfig
558
- });
559
- return result;
560
- }
561
- /**
562
- * Register a listener to be called when the projects configuration has changed.
563
- * @returns A disposable that can be used to unregister the callback.
564
- */
565
- onProjectsUpdate(callback) {
566
- this.#updateListeners.push(callback);
567
- return Disposable.create(() => {
568
- const index = this.#updateListeners.indexOf(callback);
569
- if (index >= 0) this.#updateListeners.splice(index, 1);
570
- });
571
- }
572
- getWorkspaceFolder() {
573
- try {
574
- return this.services.workspace.WorkspaceManager.workspaceUri;
575
- } catch (error) {
576
- logger$2.warn("Failed to get workspace URI, using default folder", { error });
577
- return URI.file("/");
578
- }
579
- }
580
- notifyListeners() {
581
- for (const listener of this.#updateListeners) try {
582
- listener();
583
- } catch (e) {
584
- logger$2.warn(loggable(e));
585
- }
586
- }
587
- };
588
-
589
- //#endregion
590
- //#region src/LikeC4LanguageServices.ts
591
- const logger$1 = logger$3.getChild("LanguageServices");
592
- /**
593
- * Public Language Services
594
- */
595
- var DefaultLikeC4LanguageServices = class {
596
- builder;
597
- editor;
598
- projectsManager;
599
- constructor(services) {
600
- this.services = services;
601
- this.builder = services.likec4.ModelBuilder;
602
- this.projectsManager = services.shared.workspace.ProjectsManager;
603
- this.editor = services.likec4.ModelChanges;
604
- }
605
- get views() {
606
- return this.services.likec4.Views;
607
- }
608
- get workspaceUri() {
609
- return this.services.shared.workspace.WorkspaceManager.workspaceUri;
610
- }
611
- projects() {
612
- const projectsManager = this.services.shared.workspace.ProjectsManager;
613
- const projectsWithDocs = t$2(this.services.shared.workspace.LangiumDocuments.groupedByProject(), t$4(), t$1(([projectId, docs]) => {
614
- const id = projectId;
615
- const { folderUri, config } = projectsManager.getProject(id);
616
- return {
617
- id,
618
- folder: folderUri,
619
- title: config.title ?? config.name,
620
- documents: t$1(docs, e("uri")),
621
- config
622
- };
623
- }));
624
- if (t(projectsWithDocs, 2) && projectsManager.defaultProjectId) {
625
- const idx = projectsWithDocs.findIndex((p) => p.id === projectsManager.defaultProjectId);
626
- if (idx > 0) {
627
- const [defaultProject] = projectsWithDocs.splice(idx, 1);
628
- return [defaultProject, ...projectsWithDocs];
629
- }
630
- return projectsWithDocs;
631
- }
632
- if (t(projectsWithDocs, 1)) return projectsWithDocs;
633
- const { folderUri, config } = projectsManager.getProject(ProjectsManager.DefaultProjectId);
634
- const documents = t$1(this.services.shared.workspace.LangiumDocuments.projectDocuments(ProjectsManager.DefaultProjectId).toArray(), e("uri"));
635
- return [{
636
- id: ProjectsManager.DefaultProjectId,
637
- folder: folderUri,
638
- title: config.title ?? config.name,
639
- documents,
640
- config
641
- }];
642
- }
643
- project(projectId) {
644
- projectId = this.projectsManager.ensureProjectId(projectId);
645
- const { folderUri, config } = this.services.shared.workspace.ProjectsManager.getProject(projectId);
646
- const documents = t$1(this.services.shared.workspace.LangiumDocuments.projectDocuments(projectId).toArray(), e("uri"));
647
- return {
648
- id: projectId,
649
- folder: folderUri,
650
- title: config.title ?? config.name,
651
- documents,
652
- config
653
- };
654
- }
655
- async diagrams(project, cancelToken) {
656
- const projectId = this.projectsManager.ensureProjectId(project);
657
- return await this.views.diagrams(projectId, cancelToken);
658
- }
659
- async computedModel(project, cancelToken) {
660
- const projectId = this.projectsManager.ensureProjectId(project);
661
- return await this.builder.computeModel(projectId, cancelToken);
662
- }
663
- async layoutedModel(project, cancelToken) {
664
- const projectId = this.projectsManager.ensureProjectId(project);
665
- const model = await this.builder.computeModel(projectId, cancelToken);
666
- if (!model) throw new Error("Failed to compute model, empty project?");
667
- const layouted = await this.views.layoutAllViews(projectId, cancelToken);
668
- return LikeC4Model.create({
669
- ...model.$data,
670
- _stage: "layouted",
671
- views: t$2(layouted, t$1(e("diagram")), t$5(e("id")))
672
- });
673
- }
674
- async projectsOverview(cancelToken) {
675
- const allProjects = this.services.shared.workspace.ProjectsManager.all;
676
- const models = [];
677
- for (const project of allProjects) {
678
- const model = await this.builder.computeModel(project, cancelToken);
679
- if (cancelToken?.isCancellationRequested) throw new Error("Operation cancelled");
680
- if (model === LikeC4Model.EMPTY) {
681
- logger$1.debug(`Project ${project} is empty, skipping`);
682
- continue;
683
- }
684
- models.push(model);
685
- }
686
- if (!t(models, 1)) throw new Error("No models found");
687
- const projectsView = computeProjectsView(models);
688
- return await this.views.layouter.layoutProjectsView(projectsView);
689
- }
690
- getErrors() {
691
- return this.services.shared.workspace.LangiumDocuments.allExcludingBuiltin.toArray().flatMap((doc) => {
692
- return (doc.diagnostics ?? []).filter((d) => d.severity === DiagnosticSeverity.Error).map(({ message, range }) => ({
693
- message,
694
- line: range.start.line,
695
- range,
696
- sourceFsPath: doc.uri.fsPath
697
- }));
698
- });
699
- }
700
- locate(params) {
701
- switch (true) {
702
- case "element" in params: return this.services.likec4.ModelLocator.locateElement(params.element, params.projectId);
703
- case "relation" in params: return this.services.likec4.ModelLocator.locateRelation(params.relation, params.projectId);
704
- case "view" in params: return this.services.likec4.ModelLocator.locateView(params.view, params.projectId);
705
- case "deployment" in params: return this.services.likec4.ModelLocator.locateDeploymentElement(params.deployment, params.projectId);
706
- default: nonexhaustive$1(params);
707
- }
708
- }
709
- async dispose() {
710
- try {
711
- logger$1.debug("disposing LikeC4LanguageServices");
712
- await this.services.shared.workspace.FileSystemWatcher.dispose();
713
- if (this.services.mcp.Server.isStarted) await this.services.mcp.Server.stop();
714
- this.services.Rpc.dispose();
715
- this.services.likec4.ModelBuilder.dispose();
716
- } catch (e) {
717
- logger$1.error(loggable(e));
718
- } finally {
719
- logger$1.debug("LikeC4LanguageServices disposed");
720
- }
721
- }
722
- };
723
-
724
- //#endregion
725
- export { logWarnError as a, getTelemetrySink as i, ProjectsManager as n, logger$3 as o, getLspConnectionSink as r, DefaultLikeC4LanguageServices as t };