@standarx/graph 0.0.0-stage → 1.0.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 (127) hide show
  1. package/LICENSE +21 -0
  2. package/README.fr.md +436 -0
  3. package/README.md +435 -2
  4. package/THIRD_PARTY_NOTICES.md +22 -0
  5. package/assets/fonts/Inter-Regular.ttf +0 -0
  6. package/assets/fonts/Inter-SemiBold.ttf +0 -0
  7. package/assets/fonts/OFL.txt +92 -0
  8. package/dist/adapter-0bggwh8x.js +393 -0
  9. package/dist/cli-4m00785g.js +20 -0
  10. package/dist/cli-5v9761s9.js +330 -0
  11. package/dist/cli-9f1pdw5q.js +462 -0
  12. package/dist/cli-a4ax1vkc.js +172 -0
  13. package/dist/cli-b4n941t8.js +1439 -0
  14. package/dist/cli-eqq7a3wz.js +1144 -0
  15. package/dist/cli-gh5166k6.js +1565 -0
  16. package/dist/cli-kzp16pt5.js +207 -0
  17. package/dist/cli-mzmjkk5v.js +11 -0
  18. package/dist/cli-njgyf690.js +1060 -0
  19. package/dist/cli-nkm2j980.js +141 -0
  20. package/dist/cli-nyckgf1t.js +4 -0
  21. package/dist/cli-sfdqkbd1.js +433 -0
  22. package/dist/cli-txrzzr2q.js +0 -0
  23. package/dist/cli-vecew2na.js +709 -0
  24. package/dist/cli-wt9dmbhm.js +560 -0
  25. package/dist/cli-xhdxp3cj.js +387 -0
  26. package/dist/cli-ywgtv1cg.js +39 -0
  27. package/dist/cli.d.ts +2 -0
  28. package/dist/cli.js +415 -0
  29. package/dist/core/index.d.ts +6 -0
  30. package/dist/core/index.js +93 -0
  31. package/dist/core/spatial.d.ts +16 -0
  32. package/dist/core/threshold.d.ts +1 -0
  33. package/dist/core/view.d.ts +80 -0
  34. package/dist/export/index.d.ts +18 -0
  35. package/dist/export/index.js +172 -0
  36. package/dist/export/pdf.d.ts +5 -0
  37. package/dist/export/png.d.ts +4 -0
  38. package/dist/format/index.d.ts +4 -0
  39. package/dist/format/index.js +71 -0
  40. package/dist/format/json-schema.d.ts +2 -0
  41. package/dist/format/schema.d.ts +787 -0
  42. package/dist/format/semantic/er.d.ts +3 -0
  43. package/dist/format/semantic/graph.d.ts +3 -0
  44. package/dist/format/semantic/sequence.d.ts +3 -0
  45. package/dist/format/semantic/shared.d.ts +14 -0
  46. package/dist/format/semantic/state.d.ts +3 -0
  47. package/dist/format/semantic/tree.d.ts +3 -0
  48. package/dist/format/transition-label.d.ts +2 -0
  49. package/dist/format/validate.d.ts +11 -0
  50. package/dist/html/index.d.ts +3 -0
  51. package/dist/html/index.js +127 -0
  52. package/dist/html/layout-worker.d.ts +1 -0
  53. package/dist/html/layout-worker.generated.d.ts +1 -0
  54. package/dist/html/mount.d.ts +12 -0
  55. package/dist/html/page.d.ts +14 -0
  56. package/dist/html/render.d.ts +7 -0
  57. package/dist/html/runtime.d.ts +1 -0
  58. package/dist/html/runtime.generated.d.ts +1 -0
  59. package/dist/html/shell.d.ts +10 -0
  60. package/dist/html/svg-adapter.d.ts +8 -0
  61. package/dist/html/ui.d.ts +34 -0
  62. package/dist/language/analysis.d.ts +38 -0
  63. package/dist/language/complete.d.ts +3 -0
  64. package/dist/language/docs.d.ts +11 -0
  65. package/dist/language/format.d.ts +17 -0
  66. package/dist/language/hover.d.ts +3 -0
  67. package/dist/language/index.d.ts +6 -0
  68. package/dist/language/index.js +1385 -0
  69. package/dist/language/navigation.d.ts +9 -0
  70. package/dist/language/positions.d.ts +7 -0
  71. package/dist/language/symbols.d.ts +3 -0
  72. package/dist/language/types.d.ts +34 -0
  73. package/dist/layout/elk.d.ts +35 -0
  74. package/dist/layout/er.d.ts +3 -0
  75. package/dist/layout/font-metrics.d.ts +9 -0
  76. package/dist/layout/graph.d.ts +3 -0
  77. package/dist/layout/index.d.ts +5 -0
  78. package/dist/layout/index.js +17 -0
  79. package/dist/layout/measure.d.ts +10 -0
  80. package/dist/layout/sequence.d.ts +3 -0
  81. package/dist/layout/shapes.d.ts +16 -0
  82. package/dist/layout/shared.d.ts +31 -0
  83. package/dist/layout/state.d.ts +3 -0
  84. package/dist/layout/tree.d.ts +3 -0
  85. package/dist/layout/types.d.ts +198 -0
  86. package/dist/layout-worker.generated-emmvgfb1.js +34 -0
  87. package/dist/mermaid/common.d.ts +36 -0
  88. package/dist/mermaid/er.d.ts +3 -0
  89. package/dist/mermaid/graph.d.ts +4 -0
  90. package/dist/mermaid/index.d.ts +6 -0
  91. package/dist/mermaid/index.js +6 -0
  92. package/dist/mermaid/mindmap.d.ts +3 -0
  93. package/dist/mermaid/sequence.d.ts +3 -0
  94. package/dist/mermaid/state.d.ts +3 -0
  95. package/dist/remark/index.d.ts +9 -0
  96. package/dist/remark/index.js +104 -0
  97. package/dist/shared/errors.d.ts +6 -0
  98. package/dist/shared/package-root.d.ts +5 -0
  99. package/dist/svg/escape.d.ts +1 -0
  100. package/dist/svg/index.d.ts +3 -0
  101. package/dist/svg/index.js +25 -0
  102. package/dist/svg/render.d.ts +9 -0
  103. package/dist/svg/theme.d.ts +62 -0
  104. package/dist/svg-adapter-gq5vmp6q.js +227 -0
  105. package/dist/text/build.d.ts +10 -0
  106. package/dist/text/canonical.d.ts +10 -0
  107. package/dist/text/errors.d.ts +33 -0
  108. package/dist/text/highlight.d.ts +13 -0
  109. package/dist/text/index.d.ts +33 -0
  110. package/dist/text/index.js +27 -0
  111. package/dist/text/lexer.d.ts +29 -0
  112. package/dist/text/parser.d.ts +160 -0
  113. package/dist/text/print.d.ts +6 -0
  114. package/dist/text/slug.d.ts +1 -0
  115. package/dist/text/syntax.d.ts +8 -0
  116. package/dist/version.d.ts +1 -0
  117. package/dist/webgl/adapter.d.ts +4 -0
  118. package/dist/webgl/index.d.ts +7 -0
  119. package/dist/webgl/index.js +15 -0
  120. package/dist/webgl/runtime.d.ts +1 -0
  121. package/dist/webgl/runtime.generated.d.ts +1 -0
  122. package/grammars/standargraph.tmLanguage.json +599 -0
  123. package/language-configuration.json +35 -0
  124. package/licenses/EPL-2.0.txt +277 -0
  125. package/licenses/MPL-2.0.txt +373 -0
  126. package/package.json +133 -4
  127. package/schema/graph-document.v1.json +1737 -0
@@ -0,0 +1,1385 @@
1
+ import {
2
+ STOP,
3
+ LineMap,
4
+ Sink,
5
+ IDENT,
6
+ normalize,
7
+ Lexer,
8
+ KINDS,
9
+ FLAGS,
10
+ CARDINALITIES2,
11
+ OPERATOR_WORDS,
12
+ OPERATOR_RULES,
13
+ operatorOf,
14
+ parseSyntaxPartial
15
+ } from "../cli-njgyf690.js";
16
+ import {
17
+ SHAPES2,
18
+ DirectionSchema2,
19
+ PSEUDO2,
20
+ TREE_LAYOUTS2
21
+ } from "../cli-kzp16pt5.js";
22
+
23
+ // src/text/syntax.ts
24
+ function parseTree(source) {
25
+ const text = normalize(source);
26
+ const sink = new Sink(new LineMap(text));
27
+ const ast = parseSyntaxPartial(text, sink);
28
+ return { ast, errors: sink.sorted(), text };
29
+ }
30
+
31
+ // src/language/positions.ts
32
+ function clamp(value, low, high) {
33
+ if (!(value > low))
34
+ return low;
35
+ return value < high ? value : high;
36
+ }
37
+ function converter(source) {
38
+ const text = normalize(source);
39
+ const shift = source.charCodeAt(0) === 65279 ? 1 : 0;
40
+ const starts = [0];
41
+ for (let index = 0;index < text.length; index++) {
42
+ if (text.charCodeAt(index) === 10)
43
+ starts.push(index + 1);
44
+ }
45
+ const lineOf = (offset) => {
46
+ let low = 0;
47
+ let high = starts.length - 1;
48
+ while (low < high) {
49
+ const middle = low + high + 1 >> 1;
50
+ if (starts[middle] <= offset)
51
+ low = middle;
52
+ else
53
+ high = middle - 1;
54
+ }
55
+ return low;
56
+ };
57
+ return {
58
+ text,
59
+ position(offset) {
60
+ const at = clamp(offset, 0, text.length);
61
+ const line = lineOf(at);
62
+ return { line, character: at - starts[line] + (line === 0 ? shift : 0) };
63
+ },
64
+ offset(position) {
65
+ const line = Math.floor(clamp(position.line, 0, starts.length - 1));
66
+ const start = starts[line];
67
+ const end = line + 1 < starts.length ? starts[line + 1] - 1 : text.length;
68
+ const column = clamp(position.character - (line === 0 ? shift : 0), 0, end - start);
69
+ return start + Math.floor(column);
70
+ }
71
+ };
72
+ }
73
+
74
+ // src/language/analysis.ts
75
+ function isPunct(token, text) {
76
+ return token !== undefined && token.kind === "PUNCT" && token.text === text;
77
+ }
78
+ function opensBlock(line, alone) {
79
+ const last = line[line.length - 1];
80
+ if (last === undefined)
81
+ return false;
82
+ if (isPunct(last, "{"))
83
+ return true;
84
+ return last.kind === "IDENT" && last.text === "do" && (alone || line.length > 1);
85
+ }
86
+ function scanBlock(text, lines, from) {
87
+ const lexer = new Lexer(text, new Sink(lines));
88
+ lexer.seek(from);
89
+ let depth = 0;
90
+ let open = from;
91
+ let end = from;
92
+ let first = true;
93
+ let line = [];
94
+ try {
95
+ for (;; ) {
96
+ const token = lexer.next();
97
+ if (token.kind !== "NEWLINE" && token.kind !== "EOF") {
98
+ line.push(token);
99
+ end = token.end;
100
+ continue;
101
+ }
102
+ if (first) {
103
+ first = false;
104
+ if (!opensBlock(line, true))
105
+ return;
106
+ depth = 1;
107
+ open = line[line.length - 1].start;
108
+ } else if (line.length > 0) {
109
+ const head = line[0];
110
+ const closes = isPunct(head, "}") || line.length === 1 && head.kind === "IDENT" && head.text === "end";
111
+ if (closes) {
112
+ depth--;
113
+ if (depth === 0)
114
+ return { open, end: head.end, close: head.start };
115
+ } else if (opensBlock(line, false)) {
116
+ depth++;
117
+ }
118
+ }
119
+ line = [];
120
+ if (token.kind === "EOF")
121
+ return { open, end };
122
+ }
123
+ } catch (error) {
124
+ if (error !== STOP)
125
+ throw error;
126
+ return first ? undefined : { open, end };
127
+ }
128
+ }
129
+ function build(source) {
130
+ const { ast, text } = parseTree(source);
131
+ const conv = converter(source);
132
+ const lines = new LineMap(text);
133
+ const registry = new Map;
134
+ const occurrences = [];
135
+ const sites = [];
136
+ const touch = (kind, ident, mention) => {
137
+ const key = `${kind}:${ident.value}`;
138
+ let item = registry.get(key);
139
+ if (!item) {
140
+ item = {
141
+ kind,
142
+ id: ident.value,
143
+ attrs: [],
144
+ declared: false,
145
+ definition: ident.range,
146
+ incoming: 0,
147
+ outgoing: 0
148
+ };
149
+ registry.set(key, item);
150
+ }
151
+ occurrences.push({ range: ident.range, item });
152
+ if (mention && !item.declared) {
153
+ item.declared = true;
154
+ item.definition = ident.range;
155
+ item.label = mention.label?.value;
156
+ item.attrs = mention.attrs;
157
+ }
158
+ return item;
159
+ };
160
+ const connect = (from, to) => {
161
+ if (from)
162
+ from.outgoing++;
163
+ if (to)
164
+ to.incoming++;
165
+ };
166
+ const graph = (statements) => {
167
+ for (const statement of statements) {
168
+ if (statement.t === "group") {
169
+ touch("group", statement.id, statement);
170
+ sites.push({ context: "group", attrs: statement.attrs });
171
+ graph(statement.body);
172
+ } else if (statement.t === "node") {
173
+ touch("node", statement.id, statement);
174
+ sites.push({ context: "node", attrs: statement.attrs });
175
+ } else {
176
+ const items = statement.ids.map((id) => touch("node", id));
177
+ for (let index = 0;index < statement.ops.length; index++)
178
+ connect(items[index], items[index + 1]);
179
+ sites.push({ context: "edge", attrs: statement.attrs });
180
+ }
181
+ }
182
+ };
183
+ const sequence = (statements) => {
184
+ for (const statement of statements) {
185
+ if (statement.t === "participant") {
186
+ touch("participant", statement.id, statement);
187
+ sites.push({ context: "participant", attrs: statement.attrs });
188
+ } else {
189
+ connect(touch("participant", statement.from), touch("participant", statement.to));
190
+ sites.push({ context: "message", attrs: statement.attrs });
191
+ }
192
+ }
193
+ };
194
+ const state = (statements) => {
195
+ for (const statement of statements) {
196
+ if (statement.t === "state") {
197
+ touch("state", statement.id, statement);
198
+ sites.push({ context: "state", attrs: statement.attrs });
199
+ if (statement.body)
200
+ state(statement.body);
201
+ } else {
202
+ const from = statement.from.star ? undefined : touch("state", statement.from);
203
+ const to = statement.to.star ? undefined : touch("state", statement.to);
204
+ connect(from, to);
205
+ sites.push({ context: "transition", attrs: statement.attrs });
206
+ }
207
+ }
208
+ };
209
+ const er = (statements) => {
210
+ for (const statement of statements) {
211
+ if (statement.t === "entity") {
212
+ touch("entity", statement.id, statement);
213
+ sites.push({ context: "entity", attrs: statement.attrs });
214
+ for (const line of statement.attributes ?? [])
215
+ sites.push({ context: "attribute", attrs: line.attrs });
216
+ } else {
217
+ connect(touch("entity", statement.from), touch("entity", statement.to));
218
+ sites.push({ context: "relation", attrs: statement.attrs });
219
+ }
220
+ }
221
+ };
222
+ sites.push({ context: "header", attrs: ast.header.attrs });
223
+ switch (ast.kind) {
224
+ case "graph":
225
+ graph(ast.body);
226
+ break;
227
+ case "sequence":
228
+ sequence(ast.body);
229
+ break;
230
+ case "state":
231
+ state(ast.body);
232
+ break;
233
+ case "er":
234
+ er(ast.body);
235
+ break;
236
+ case "tree":
237
+ for (const line of ast.body)
238
+ sites.push({ context: "treeNode", attrs: line.attrs });
239
+ break;
240
+ }
241
+ const seen = new Set;
242
+ const unique = occurrences.filter((occurrence) => {
243
+ if (seen.has(occurrence.range.start))
244
+ return false;
245
+ seen.add(occurrence.range.start);
246
+ return true;
247
+ });
248
+ unique.sort((a, b) => a.range.start - b.range.start);
249
+ const placed = new Set;
250
+ for (const occurrence of unique) {
251
+ const { item } = occurrence;
252
+ if (placed.has(item))
253
+ continue;
254
+ placed.add(item);
255
+ if (!item.declared)
256
+ item.definition = occurrence.range;
257
+ }
258
+ return {
259
+ ast,
260
+ conv,
261
+ items: [...registry.values()],
262
+ occurrences: unique,
263
+ sites,
264
+ block: (from) => scanBlock(text, lines, from)
265
+ };
266
+ }
267
+ var last;
268
+ function analyze(source) {
269
+ if (last !== undefined && last.source === source)
270
+ return last.value;
271
+ const value = build(source);
272
+ last = { source, value };
273
+ return value;
274
+ }
275
+ function occurrenceAt(analysis, offset) {
276
+ let touching;
277
+ for (const occurrence of analysis.occurrences) {
278
+ if (offset >= occurrence.range.start && offset < occurrence.range.end)
279
+ return occurrence;
280
+ if (offset === occurrence.range.end)
281
+ touching ??= occurrence;
282
+ }
283
+ return touching;
284
+ }
285
+
286
+ // src/language/docs.ts
287
+ var KIND_DOCS = {
288
+ graph: "Graph diagram: nodes, groups and edges laid out automatically.",
289
+ sequence: "Sequence diagram: participants exchanging messages in order.",
290
+ state: "State machine: states, nested states and transitions.",
291
+ er: "Entity-relation diagram: entities with attributes and the relations between them.",
292
+ tree: "Tree or mind map: one root and indented child lines."
293
+ };
294
+ var DIRECTION = "Layout direction: down, right, up or left.";
295
+ var LAYOUT = "Tree layout: tree or mindmap.";
296
+ var ID = "Explicit id of this item, used instead of the generated one.";
297
+ var TYPE = "Free-form type of this item, used for styling and grouping (for example page, service or database).";
298
+ var SHAPE = "Node shape: box, rect, pill, diamond, circle, ellipse, hexagon, parallelogram, cylinder, document or subroutine.";
299
+ var LINK = "URL or path this item links to.";
300
+ var DESCRIPTION = "Longer description shown with this item.";
301
+ var HEADER_DOCS = {
302
+ graph: { direction: DIRECTION },
303
+ sequence: {},
304
+ state: { direction: DIRECTION },
305
+ er: { direction: DIRECTION },
306
+ tree: { direction: DIRECTION, layout: LAYOUT }
307
+ };
308
+ var FIELD_DOCS = {
309
+ node: {
310
+ type: TYPE,
311
+ shape: SHAPE,
312
+ link: LINK,
313
+ description: DESCRIPTION,
314
+ x: "Fixed horizontal position of the node; goes together with y.",
315
+ y: "Fixed vertical position of the node; goes together with x."
316
+ },
317
+ group: {},
318
+ edge: { id: "Explicit id of this edge.", type: "Free-form type of this edge." },
319
+ participant: { type: TYPE },
320
+ message: {},
321
+ state: {
322
+ type: TYPE,
323
+ pseudo: "Pseudo-state kind: initial, final, choice, fork, join or history.",
324
+ actions: 'List of actions run by this state, for example ["entry / start"].',
325
+ description: DESCRIPTION,
326
+ link: LINK
327
+ },
328
+ transition: {
329
+ id: "Explicit id of this transition.",
330
+ guard: "Condition that must hold for the transition to fire.",
331
+ action: "Action run when the transition fires.",
332
+ type: "Free-form type of this transition."
333
+ },
334
+ entity: { type: TYPE, description: DESCRIPTION, link: LINK },
335
+ attribute: { note: "Free-text note about this attribute." },
336
+ relation: { id: "Explicit id of this relation.", type: "Free-form type of this relation." },
337
+ treeNode: { id: ID, type: TYPE, shape: SHAPE, description: DESCRIPTION, link: LINK }
338
+ };
339
+ var META_DOCS = {
340
+ source: "Provenance: where this information comes from (file, URL or tool output).",
341
+ confidence: "Provenance confidence: confirmed, inferred or unknown. Needs source.",
342
+ tool: "Provenance: the tool that produced this information. Needs source.",
343
+ coverage: "Share of the subject that is covered, a number from 0 to 1.",
344
+ freshness: "When this information was last verified, as an ISO 8601 date-time."
345
+ };
346
+ function attributeDoc(context, key, kind) {
347
+ const own = context === "header" ? HEADER_DOCS[kind] : FIELD_DOCS[context];
348
+ if (Object.hasOwn(own, key))
349
+ return own[key];
350
+ if (context === "attribute")
351
+ return;
352
+ if (Object.hasOwn(META_DOCS, key))
353
+ return META_DOCS[key];
354
+ if (key.startsWith("data.") && key.length > 5) {
355
+ return "Custom data value stored under meta.data (string, number or boolean).";
356
+ }
357
+ return;
358
+ }
359
+ var DATA_NAMESPACE_DOC = "Free metadata: data.<name>=value stores a custom string, number or boolean under meta.data.";
360
+ var KEYWORD_DOCS = {
361
+ group: 'Group of nodes: group id "Label" { ... }.',
362
+ initial: "Initial pseudo-state, the start of a state machine: initial -> state.",
363
+ final: "Final pseudo-state, the end of a state machine: state -> final."
364
+ };
365
+ var FLAG_DOCS = {
366
+ pk: "Primary key.",
367
+ fk: "Foreign key.",
368
+ uk: "Unique key.",
369
+ null: "The attribute accepts null values."
370
+ };
371
+ var OPERATOR_DOCS = {
372
+ "->": "Directed link: an edge, a synchronous message or a transition.",
373
+ "--": "Undirected edge, or an identifying relation.",
374
+ "->>": "Asynchronous message.",
375
+ "-->": "Reply message.",
376
+ "..": "Non-identifying relation."
377
+ };
378
+ var CARDINALITY_DOCS = {
379
+ "1": "Exactly one.",
380
+ "0..1": "Zero or one.",
381
+ "1..*": "One or more.",
382
+ "0..*": "Zero or more."
383
+ };
384
+ var DIRECTIONS = DirectionSchema2.anyOf.map((literal) => literal.const);
385
+ var CONFIDENCES = ["confirmed", "inferred", "unknown"];
386
+ function attributeKeys(context, kind) {
387
+ const own = context === "header" ? HEADER_DOCS[kind] : FIELD_DOCS[context];
388
+ const keys = Object.keys(own);
389
+ if (context !== "attribute")
390
+ keys.push(...Object.keys(META_DOCS));
391
+ return keys;
392
+ }
393
+ function attributeValues(context, key, kind) {
394
+ if (context === "attribute")
395
+ return;
396
+ if (key === "confidence")
397
+ return CONFIDENCES;
398
+ if (key.startsWith("data.") && key.length > 5)
399
+ return ["true", "false"];
400
+ if (context === "header") {
401
+ if (key === "direction" && Object.hasOwn(HEADER_DOCS[kind], key))
402
+ return DIRECTIONS;
403
+ if (key === "layout" && kind === "tree")
404
+ return TREE_LAYOUTS2;
405
+ return;
406
+ }
407
+ if (key === "shape" && (context === "node" || context === "treeNode"))
408
+ return SHAPES2;
409
+ if (key === "pseudo" && context === "state")
410
+ return PSEUDO2;
411
+ return;
412
+ }
413
+
414
+ // src/language/complete.ts
415
+ var ORDER = ["keyword", "operator", "property", "value", "reference"];
416
+ var NAMESPACE = {
417
+ graph: "node",
418
+ sequence: "participant",
419
+ state: "state",
420
+ er: "entity",
421
+ tree: undefined
422
+ };
423
+ var UNSUGGESTED = new Set(["id", "x", "y", "coverage", "actions"]);
424
+ function lineState(text) {
425
+ let quote = "";
426
+ let comment = false;
427
+ for (let index = 0;index < text.length; index++) {
428
+ const char = text[index];
429
+ if (comment) {
430
+ if (char === `
431
+ `)
432
+ comment = false;
433
+ } else if (quote !== "") {
434
+ if (char === "\\")
435
+ index++;
436
+ else if (char === quote)
437
+ quote = "";
438
+ } else if (char === '"' || char === "`") {
439
+ quote = char;
440
+ } else if (char === "#") {
441
+ comment = true;
442
+ }
443
+ }
444
+ if (comment)
445
+ return "comment";
446
+ return quote === "" ? "code" : "string";
447
+ }
448
+ function bracketScan(text, offset) {
449
+ const stack = [];
450
+ let quote = "";
451
+ let comment = false;
452
+ let index = 0;
453
+ const step = (limit, stopWhenFlat) => {
454
+ for (;index < limit; index++) {
455
+ const char = text[index];
456
+ if (comment) {
457
+ if (char === `
458
+ `)
459
+ comment = false;
460
+ } else if (quote !== "") {
461
+ if (char === "\\")
462
+ index++;
463
+ else if (char === quote)
464
+ quote = "";
465
+ } else if (char === '"' || char === "`") {
466
+ quote = char;
467
+ } else if (char === "#") {
468
+ comment = true;
469
+ } else if (char === "[" || char === "(") {
470
+ stack.push({ char, at: index });
471
+ } else if (char === "]" || char === ")") {
472
+ if (stack[stack.length - 1]?.char === (char === "]" ? "[" : "("))
473
+ stack.pop();
474
+ if (stopWhenFlat && !stack.some((entry) => entry.char === "["))
475
+ return true;
476
+ }
477
+ }
478
+ return false;
479
+ };
480
+ step(offset, false);
481
+ const outer = stack.find((entry) => entry.char === "[");
482
+ if (outer === undefined)
483
+ return;
484
+ const closed = step(text.length, true);
485
+ const found = text.indexOf(`
486
+ `, closed ? index : offset);
487
+ return { open: outer.at, end: found < 0 ? text.length : found };
488
+ }
489
+ function lexLine(text) {
490
+ const sink = new Sink(new LineMap(text));
491
+ sink.muted = 1;
492
+ const lexer = new Lexer(text, sink);
493
+ const tokens = [];
494
+ for (;; ) {
495
+ const token = lexer.next();
496
+ if (token.kind === "EOF")
497
+ break;
498
+ if (token.kind === "NEWLINE")
499
+ continue;
500
+ if (token.kind === "ERROR" && token.text === "[")
501
+ continue;
502
+ tokens.push(token);
503
+ }
504
+ return tokens;
505
+ }
506
+ function isPunct2(token, text) {
507
+ return token !== undefined && token.kind === "PUNCT" && token.text === text;
508
+ }
509
+ function isIdLike(token) {
510
+ return token !== undefined && (token.kind === "IDENT" || token.kind === "QUOTED_ID");
511
+ }
512
+ function isCard(token) {
513
+ return token !== undefined && (token.kind === "CARD" || token.kind === "NUMBER");
514
+ }
515
+ function operatorAt(tokens, index) {
516
+ const token = tokens[index];
517
+ if (token === undefined || operatorOf(token) === undefined)
518
+ return false;
519
+ return token.kind !== "IDENT" || index > 0;
520
+ }
521
+ function quoteId(id) {
522
+ IDENT.lastIndex = 0;
523
+ const match = IDENT.exec(id);
524
+ if (match && match[0].length === id.length)
525
+ return id;
526
+ return `\`${id.replace(/\\/g, "\\\\").replace(/`/g, "\\`")}\``;
527
+ }
528
+ function quoteString(value) {
529
+ return `"${value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\t/g, "\\t")}"`;
530
+ }
531
+ function blockDepth(lines) {
532
+ let depth = 0;
533
+ for (const line of lines) {
534
+ const tokens = lexLine(line);
535
+ const first = tokens[0];
536
+ const last = tokens[tokens.length - 1];
537
+ if (first === undefined || last === undefined)
538
+ continue;
539
+ if (isPunct2(first, "}") || tokens.length === 1 && first.kind === "IDENT" && first.text === "end") {
540
+ depth = Math.max(0, depth - 1);
541
+ } else if (isPunct2(last, "{") || last.kind === "IDENT" && last.text === "do" && tokens.length > 1) {
542
+ depth++;
543
+ }
544
+ }
545
+ return depth;
546
+ }
547
+ function operatorItems(kind) {
548
+ const items = [];
549
+ for (const symbol of OPERATOR_RULES[kind].allowed) {
550
+ const documentation = OPERATOR_DOCS[symbol];
551
+ items.push({ label: symbol, kind: "operator", documentation });
552
+ for (const [word, target] of OPERATOR_WORDS) {
553
+ if (target === symbol)
554
+ items.push({ label: word, kind: "operator", documentation });
555
+ }
556
+ }
557
+ return items;
558
+ }
559
+ function cardinalityItems() {
560
+ return [...CARDINALITIES2.keys()].map((label) => ({
561
+ label,
562
+ kind: "value",
563
+ documentation: CARDINALITY_DOCS[label]
564
+ }));
565
+ }
566
+ function keyword(label) {
567
+ return { label, kind: "keyword", documentation: KEYWORD_DOCS[label] };
568
+ }
569
+ function references(analysis, kind, typing) {
570
+ const namespace = NAMESPACE[kind];
571
+ if (namespace === undefined)
572
+ return [];
573
+ const items = [];
574
+ for (const item of analysis.items) {
575
+ if (item.kind !== namespace)
576
+ continue;
577
+ const elsewhere = analysis.occurrences.some((occurrence) => occurrence.item === item && (occurrence.range.end <= typing.start || occurrence.range.start >= typing.end));
578
+ if (!elsewhere)
579
+ continue;
580
+ const entry = { label: item.id, kind: "reference" };
581
+ if (item.label !== undefined)
582
+ entry.detail = item.label;
583
+ const text = quoteId(item.id);
584
+ if (text !== item.id)
585
+ entry.insertText = text;
586
+ items.push(entry);
587
+ }
588
+ return items;
589
+ }
590
+ function usedDataKeys(analysis) {
591
+ const keys = new Set;
592
+ for (const site of analysis.sites) {
593
+ if (site.context === "attribute")
594
+ continue;
595
+ for (const attr of site.attrs) {
596
+ if (attr.key.startsWith("data.") && attr.key.length > 5)
597
+ keys.add(attr.key);
598
+ }
599
+ }
600
+ return [...keys];
601
+ }
602
+ function existingValues(analysis, key) {
603
+ const items = [];
604
+ for (const site of analysis.sites) {
605
+ for (const attr of site.attrs) {
606
+ if (attr.key !== key)
607
+ continue;
608
+ const { value } = attr;
609
+ if (value.type === "string")
610
+ items.push({ label: quoteString(value.value), kind: "value" });
611
+ else if (value.type === "ident" || value.type === "number") {
612
+ items.push({ label: String(value.value), kind: "value" });
613
+ }
614
+ }
615
+ }
616
+ return items;
617
+ }
618
+ function attrContext(kind, head, depth) {
619
+ const hasOperator = head.some((_, index) => operatorAt(head, index));
620
+ switch (kind) {
621
+ case "graph":
622
+ if (head[0]?.kind === "IDENT" && head[0].text === "group")
623
+ return "group";
624
+ return hasOperator ? "edge" : "node";
625
+ case "sequence":
626
+ return hasOperator ? "message" : "participant";
627
+ case "state":
628
+ return hasOperator ? "transition" : "state";
629
+ case "er":
630
+ if (depth > 0)
631
+ return "attribute";
632
+ return hasOperator || head.some(isCard) ? "relation" : "entity";
633
+ case "tree":
634
+ return "treeNode";
635
+ }
636
+ }
637
+ function openBracket(tokens) {
638
+ const stack = [];
639
+ for (let index = 0;index < tokens.length; index++) {
640
+ const token = tokens[index];
641
+ if (isPunct2(token, "["))
642
+ stack.push(index);
643
+ else if (isPunct2(token, "]"))
644
+ stack.pop();
645
+ }
646
+ if (stack.length === 0)
647
+ return;
648
+ return stack.length === 1 ? stack[0] : -1;
649
+ }
650
+ function bracketState(tokens, from) {
651
+ let state = "key";
652
+ let key = "";
653
+ for (let index = from + 1;index < tokens.length; index++) {
654
+ const token = tokens[index];
655
+ if (state === "key") {
656
+ if (isIdLike(token)) {
657
+ key = token.value;
658
+ state = "eq";
659
+ } else if (!isPunct2(token, ",")) {
660
+ state = "bad";
661
+ }
662
+ } else if (state === "eq") {
663
+ state = isPunct2(token, "=") ? "value" : "bad";
664
+ } else if (state === "value") {
665
+ state = token.kind === "STRING" || token.kind === "NUMBER" || token.kind === "IDENT" ? "after" : "bad";
666
+ } else if (state === "after") {
667
+ state = isPunct2(token, ",") ? "key" : "bad";
668
+ }
669
+ }
670
+ const openStart = tokens[from].start;
671
+ if (state === "key" || state === "value")
672
+ return { state, key, openStart };
673
+ return { state: "closed", key, openStart };
674
+ }
675
+ function presentKeys(line, openStart, typingStart) {
676
+ const tokens = lexLine(line);
677
+ const keys = new Set;
678
+ let depth = 0;
679
+ for (let index = 0;index < tokens.length; index++) {
680
+ const token = tokens[index];
681
+ if (token.start < openStart)
682
+ continue;
683
+ if (isPunct2(token, "[")) {
684
+ depth++;
685
+ } else if (isPunct2(token, "]")) {
686
+ depth--;
687
+ if (depth <= 0)
688
+ break;
689
+ } else if (depth === 1 && isIdLike(token) && token.start !== typingStart && isPunct2(tokens[index + 1], "=")) {
690
+ keys.add(token.value);
691
+ }
692
+ }
693
+ return keys;
694
+ }
695
+ function sorted(items, word) {
696
+ const seen = new Set;
697
+ return items.filter((item) => {
698
+ if (!item.label.startsWith(word))
699
+ return false;
700
+ const id = `${item.kind}:${item.label}`;
701
+ if (seen.has(id))
702
+ return false;
703
+ seen.add(id);
704
+ return true;
705
+ }).sort((a, b) => {
706
+ const byKind = ORDER.indexOf(a.kind) - ORDER.indexOf(b.kind);
707
+ if (byKind !== 0)
708
+ return byKind;
709
+ return a.label < b.label ? -1 : a.label > b.label ? 1 : 0;
710
+ });
711
+ }
712
+ function bracketItems(analysis, bracket, context, kind, line, typingStart, word) {
713
+ if (bracket.state === "closed")
714
+ return [];
715
+ if (bracket.state === "key") {
716
+ const present = presentKeys(line, bracket.openStart, typingStart);
717
+ const items = attributeKeys(context, kind).filter((key) => !present.has(key)).map((key) => ({
718
+ label: key,
719
+ kind: "property",
720
+ documentation: attributeDoc(context, key, kind),
721
+ insertText: `${key}=`
722
+ }));
723
+ if (context !== "attribute") {
724
+ if (word.startsWith("data.")) {
725
+ for (const key of usedDataKeys(analysis)) {
726
+ if (present.has(key))
727
+ continue;
728
+ items.push({
729
+ label: key,
730
+ kind: "property",
731
+ documentation: attributeDoc(context, key, kind),
732
+ insertText: `${key}=`
733
+ });
734
+ }
735
+ } else {
736
+ items.push({ label: "data.", kind: "property", documentation: DATA_NAMESPACE_DOC, insertText: "data." });
737
+ }
738
+ }
739
+ return items;
740
+ }
741
+ const closed = attributeValues(context, bracket.key, kind);
742
+ if (closed !== undefined) {
743
+ const items = closed.map((label) => ({ label, kind: "value" }));
744
+ if (bracket.key.startsWith("data."))
745
+ items.push(...existingValues(analysis, bracket.key));
746
+ return items;
747
+ }
748
+ if (UNSUGGESTED.has(bracket.key) || context === "attribute")
749
+ return [];
750
+ return existingValues(analysis, bracket.key);
751
+ }
752
+ function statementItems(analysis, kind, before, depth, typing) {
753
+ if (kind === "tree")
754
+ return [];
755
+ const count = before.length;
756
+ const last = before[count - 1];
757
+ if (kind === "er" && depth > 0) {
758
+ if (count < 2)
759
+ return [];
760
+ if (isPunct2(last, "]") && !isPunct2(before[count - 2], "["))
761
+ return [];
762
+ const present = new Set(before.slice(1).map((token) => token.text));
763
+ return [...FLAGS].filter((flag) => !present.has(flag)).map((flag) => ({ label: flag, kind: "keyword", documentation: FLAG_DOCS[flag] }));
764
+ }
765
+ if (count === 0) {
766
+ const items = references(analysis, kind, typing);
767
+ if (kind === "graph")
768
+ items.push(keyword("group"));
769
+ if (kind === "state")
770
+ items.push(keyword("initial"));
771
+ return items;
772
+ }
773
+ const beforeLast = before[count - 2];
774
+ if (operatorAt(before, count - 1) && (isIdLike(beforeLast) || isCard(beforeLast) || isPunct2(beforeLast, "*"))) {
775
+ const items = references(analysis, kind, typing);
776
+ if (kind === "er")
777
+ items.push(...cardinalityItems());
778
+ if (kind === "state")
779
+ items.push(keyword("final"));
780
+ return items;
781
+ }
782
+ if (kind === "er" && count >= 3 && isCard(last) && operatorAt(before, count - 2)) {
783
+ return references(analysis, kind, typing);
784
+ }
785
+ if (kind === "graph" && count >= 3 && isIdLike(last) && operatorAt(before, count - 2)) {
786
+ return operatorItems(kind);
787
+ }
788
+ if (count === 1 && (isIdLike(last) || isPunct2(last, "*"))) {
789
+ const items = operatorItems(kind);
790
+ if (kind === "er")
791
+ items.push(...cardinalityItems());
792
+ return items;
793
+ }
794
+ if (kind === "er" && count === 2 && isIdLike(before[0]) && isCard(last))
795
+ return operatorItems(kind);
796
+ return [];
797
+ }
798
+ function complete(source, position) {
799
+ const analysis = analyze(source);
800
+ const { conv, ast } = analysis;
801
+ const text = conv.text;
802
+ const offset = conv.offset(position);
803
+ const scan = bracketScan(text, offset);
804
+ const lineStart = scan !== undefined ? text.lastIndexOf(`
805
+ `, scan.open) + 1 : offset === 0 ? 0 : text.lastIndexOf(`
806
+ `, offset - 1) + 1;
807
+ const lineEndAt = scan !== undefined ? scan.end : text.indexOf(`
808
+ `, offset);
809
+ const line = text.slice(lineStart, lineEndAt < 0 ? text.length : lineEndAt);
810
+ const prefix = text.slice(lineStart, offset);
811
+ if (lineState(prefix) !== "code")
812
+ return [];
813
+ const before = lexLine(prefix);
814
+ const tail = before[before.length - 1];
815
+ let word = "";
816
+ let wordStart = prefix.length;
817
+ const stem = before[before.length - 2];
818
+ if (tail !== undefined && tail.end === prefix.length && tail.kind === "ERROR" && tail.text === "." && stem !== undefined && stem.kind === "IDENT" && stem.end === tail.start) {
819
+ word = `${stem.text}.`;
820
+ wordStart = stem.start;
821
+ before.pop();
822
+ before.pop();
823
+ } else if (tail !== undefined && tail.end === prefix.length) {
824
+ const partialOperator = tail.kind === "ERROR" && /^[-.>]+$/.test(tail.text);
825
+ if (tail.kind === "IDENT" || partialOperator) {
826
+ word = tail.text;
827
+ wordStart = tail.start;
828
+ before.pop();
829
+ }
830
+ }
831
+ const open = openBracket(before);
832
+ if (open === -1)
833
+ return [];
834
+ const isFirst = text.slice(0, lineStart).split(`
835
+ `).every((earlier) => lexLine(earlier).length === 0);
836
+ if (isFirst) {
837
+ if (before.length === 0) {
838
+ const kinds = KINDS.map((label) => ({ label, kind: "keyword", documentation: KIND_DOCS[label] }));
839
+ return sorted(kinds, word);
840
+ }
841
+ const named = before[0];
842
+ if (open === undefined || named.kind !== "IDENT" || !KINDS.includes(named.text))
843
+ return [];
844
+ const items = bracketItems(analysis, bracketState(before, open), "header", named.text, line, wordStart, word);
845
+ return sorted(items, word);
846
+ }
847
+ const kind = ast.kind;
848
+ const depth = blockDepth(text.slice(0, lineStart).split(`
849
+ `));
850
+ if (open !== undefined) {
851
+ const context = attrContext(kind, before.slice(0, open), depth);
852
+ return sorted(bracketItems(analysis, bracketState(before, open), context, kind, line, wordStart, word), word);
853
+ }
854
+ const typing = { start: lineStart + wordStart, end: offset };
855
+ return sorted(statementItems(analysis, kind, before, depth, typing), word);
856
+ }
857
+ // src/language/format.ts
858
+ var DEFAULT_INDENT = 2;
859
+ var NO_SPACE_BEFORE = new Set(["]", ")", ",", "=", "("]);
860
+ var NO_SPACE_AFTER = new Set(["[", "(", "="]);
861
+ function isPunct3(token, text) {
862
+ return token !== undefined && token.kind === "PUNCT" && token.text === text;
863
+ }
864
+ function needsSpace(previous, token, next) {
865
+ if (token.kind === "PUNCT") {
866
+ if (NO_SPACE_BEFORE.has(token.text))
867
+ return false;
868
+ if (token.text === "[" && isPunct3(next, "]") && (previous.kind === "IDENT" || isPunct3(previous, ")"))) {
869
+ return false;
870
+ }
871
+ }
872
+ return !(previous.kind === "PUNCT" && NO_SPACE_AFTER.has(previous.text));
873
+ }
874
+ function join(tokens) {
875
+ let out = "";
876
+ for (let index = 0;index < tokens.length; index++) {
877
+ const token = tokens[index];
878
+ if (index > 0 && needsSpace(tokens[index - 1], token, tokens[index + 1]))
879
+ out += " ";
880
+ out += token.text;
881
+ }
882
+ return out;
883
+ }
884
+ function openers(ast) {
885
+ const ends = new Set;
886
+ const visit = (statements) => {
887
+ for (const statement of statements) {
888
+ const node = statement;
889
+ if (node.body !== undefined) {
890
+ ends.add(node.range.end);
891
+ visit(node.body);
892
+ } else if (node.attributes !== undefined) {
893
+ ends.add(node.range.end);
894
+ }
895
+ }
896
+ };
897
+ if (ast.kind !== "tree")
898
+ visit(ast.body);
899
+ return ends;
900
+ }
901
+ function treeLevels(ast) {
902
+ const levels = [];
903
+ if (ast.kind !== "tree")
904
+ return levels;
905
+ for (const line of ast.body)
906
+ levels.push(line.parent < 0 ? 0 : levels[line.parent] + 1);
907
+ return levels;
908
+ }
909
+ function layout(text, ast, unit) {
910
+ const sink = new Sink(new LineMap(text));
911
+ const comments = [];
912
+ const lexer = new Lexer(text, sink, comments);
913
+ const openerEnds = openers(ast);
914
+ const levels = treeLevels(ast);
915
+ const lines = [];
916
+ let cursor = 0;
917
+ let depth = 0;
918
+ const indentOf = (level) => " ".repeat(unit * level);
919
+ const take = (from, to) => {
920
+ while (cursor < comments.length && comments[cursor].start < from)
921
+ cursor++;
922
+ const taken = [];
923
+ while (cursor < comments.length && comments[cursor].start < to)
924
+ taken.push(comments[cursor++]);
925
+ return taken;
926
+ };
927
+ const commentText = (comment) => text.slice(comment.start, comment.end).trimEnd();
928
+ const render = (tokens, found) => {
929
+ const last = tokens[tokens.length - 1];
930
+ let body = "";
931
+ let trailing;
932
+ let inner = false;
933
+ for (const comment of found) {
934
+ if (last !== undefined && comment.start < last.end)
935
+ inner = true;
936
+ else
937
+ trailing ??= comment;
938
+ }
939
+ if (last !== undefined) {
940
+ body = inner ? text.slice(tokens[0].start, last.end).split(`
941
+ `).map((line) => line.trimEnd()).join(`
942
+ `) : join(tokens);
943
+ }
944
+ if (trailing === undefined)
945
+ return body;
946
+ return body === "" ? commentText(trailing) : `${body} ${commentText(trailing)}`;
947
+ };
948
+ let group = [];
949
+ let lineStart = 0;
950
+ let headerDone = false;
951
+ let resume = 0;
952
+ for (;; ) {
953
+ const token = lexer.next();
954
+ if (token.kind !== "NEWLINE" && token.kind !== "EOF") {
955
+ group.push(token);
956
+ continue;
957
+ }
958
+ const found = take(lineStart, token.start);
959
+ if (group.length === 0) {
960
+ lines.push(found.length > 0 ? indentOf(depth) + commentText(found[0]) : "");
961
+ } else {
962
+ const first = group[0];
963
+ const closes = depth > 0 && (isPunct3(first, "}") || group.length === 1 && first.kind === "IDENT" && first.text === "end");
964
+ if (closes)
965
+ depth--;
966
+ lines.push(indentOf(depth) + render(group, found));
967
+ let previousEnd = -1;
968
+ for (const item of group) {
969
+ if (openerEnds.has(previousEnd))
970
+ depth++;
971
+ previousEnd = item.end;
972
+ }
973
+ headerDone = true;
974
+ }
975
+ group = [];
976
+ lineStart = token.end;
977
+ resume = token.end;
978
+ if (token.kind === "EOF")
979
+ break;
980
+ if (ast.kind === "tree" && headerDone)
981
+ break;
982
+ }
983
+ if (ast.kind === "tree") {
984
+ let position = resume;
985
+ let next = 0;
986
+ while (position < text.length) {
987
+ let end = text.indexOf(`
988
+ `, position);
989
+ if (end < 0)
990
+ end = text.length;
991
+ let start = position;
992
+ while (start < end && (text[start] === " " || text[start] === "\t"))
993
+ start++;
994
+ if (start >= end) {
995
+ lines.push("");
996
+ } else if (text[start] === "#") {
997
+ const level = next < levels.length ? levels[next] : 0;
998
+ lines.push(indentOf(level) + text.slice(start, end).trimEnd());
999
+ } else {
1000
+ const node = ast.body[next];
1001
+ if (node === undefined || node.range.start !== start)
1002
+ return;
1003
+ const level = levels[next];
1004
+ next++;
1005
+ const labelEnd = node.label.range.end;
1006
+ lexer.seek(labelEnd);
1007
+ const tokens = [];
1008
+ let terminator = lexer.next();
1009
+ while (terminator.kind !== "NEWLINE" && terminator.kind !== "EOF") {
1010
+ tokens.push(terminator);
1011
+ terminator = lexer.next();
1012
+ }
1013
+ const found = take(labelEnd, terminator.start);
1014
+ const rest = render(tokens, found);
1015
+ const label = text.slice(start, labelEnd);
1016
+ lines.push(indentOf(level) + label + (rest === "" ? "" : ` ${rest}`));
1017
+ position = terminator.end;
1018
+ continue;
1019
+ }
1020
+ position = end + 1;
1021
+ }
1022
+ }
1023
+ if (sink.errors.length > 0)
1024
+ return;
1025
+ return lines;
1026
+ }
1027
+ function tidy(lines) {
1028
+ let first = 0;
1029
+ while (first < lines.length && lines[first] === "")
1030
+ first++;
1031
+ let last = lines.length;
1032
+ while (last > first && lines[last - 1] === "")
1033
+ last--;
1034
+ const kept = [];
1035
+ for (let index = first;index < last; index++) {
1036
+ const line = lines[index];
1037
+ if (line === "" && kept[kept.length - 1] === "")
1038
+ continue;
1039
+ kept.push(line);
1040
+ }
1041
+ return kept;
1042
+ }
1043
+ function formatText(source, options = {}) {
1044
+ const { ast, errors, text } = parseTree(source);
1045
+ if (errors.some((error) => error.code !== "E_VALIDATE"))
1046
+ return;
1047
+ let lines;
1048
+ try {
1049
+ lines = layout(text, ast, options.indent ?? DEFAULT_INDENT);
1050
+ } catch (error) {
1051
+ if (error !== STOP)
1052
+ throw error;
1053
+ return;
1054
+ }
1055
+ if (lines === undefined)
1056
+ return;
1057
+ const eol = source.includes(`\r
1058
+ `) ? `\r
1059
+ ` : `
1060
+ `;
1061
+ const bom = source.charCodeAt(0) === 65279 ? String.fromCharCode(65279) : "";
1062
+ const body = `${tidy(lines).join(`
1063
+ `)}
1064
+ `;
1065
+ return bom + (eol === `
1066
+ ` ? body : body.replaceAll(`
1067
+ `, eol));
1068
+ }
1069
+ function endOf(source) {
1070
+ let line = 0;
1071
+ let lineStart = 0;
1072
+ for (let index = 0;index < source.length; index++) {
1073
+ if (source.charCodeAt(index) === 10) {
1074
+ line++;
1075
+ lineStart = index + 1;
1076
+ }
1077
+ }
1078
+ return { line, character: source.length - lineStart };
1079
+ }
1080
+ function format(source, options = {}) {
1081
+ const formatted = formatText(source, options);
1082
+ if (formatted === undefined || formatted === source)
1083
+ return [];
1084
+ return [{ range: { start: { line: 0, character: 0 }, end: endOf(source) }, newText: formatted }];
1085
+ }
1086
+ // src/language/hover.ts
1087
+ function show(value) {
1088
+ if (value.type === "list")
1089
+ return `[${value.items.map(show).join(", ")}]`;
1090
+ return String(value.value);
1091
+ }
1092
+ function within(offset, range) {
1093
+ return offset >= range.start && offset <= range.end;
1094
+ }
1095
+ function hover(source, position) {
1096
+ const analysis = analyze(source);
1097
+ const { conv, ast } = analysis;
1098
+ const offset = conv.offset(position);
1099
+ const toRange = (span) => ({
1100
+ start: conv.position(span.start),
1101
+ end: conv.position(span.end)
1102
+ });
1103
+ for (const site of analysis.sites) {
1104
+ const attr = site.attrs.find((item) => within(offset, item.keyRange));
1105
+ if (!attr)
1106
+ continue;
1107
+ const doc = attributeDoc(site.context, attr.key, ast.kind);
1108
+ return doc === undefined ? undefined : { contents: doc, range: toRange(attr.keyRange) };
1109
+ }
1110
+ const found = occurrenceAt(analysis, offset);
1111
+ if (found) {
1112
+ const { item } = found;
1113
+ const type = item.attrs.find((attr) => attr.key === "type");
1114
+ const others = item.attrs.filter((attr) => attr !== type);
1115
+ const parts = [`**${item.kind}** \`${item.id}\``, `Label: ${item.label ?? item.id}`];
1116
+ if (type)
1117
+ parts.push(`Type: \`${show(type.value)}\``);
1118
+ if (others.length > 0) {
1119
+ parts.push(others.map((attr) => `- ${attr.key}: ${show(attr.value)}`).join(`
1120
+ `));
1121
+ }
1122
+ parts.push(`Connections: ${item.incoming} incoming, ${item.outgoing} outgoing`);
1123
+ return { contents: parts.join(`
1124
+
1125
+ `), range: toRange(found.range) };
1126
+ }
1127
+ if (!ast.header.missing && within(offset, ast.header.kindRange)) {
1128
+ return { contents: KIND_DOCS[ast.kind], range: toRange(ast.header.kindRange) };
1129
+ }
1130
+ return;
1131
+ }
1132
+ // src/language/navigation.ts
1133
+ var BARE = new RegExp(`^(?:${IDENT.source})$`, "u");
1134
+ function at(analysis, position) {
1135
+ return occurrenceAt(analysis, analysis.conv.offset(position));
1136
+ }
1137
+ function toRange(analysis, span) {
1138
+ return { start: analysis.conv.position(span.start), end: analysis.conv.position(span.end) };
1139
+ }
1140
+ function definition(source, position) {
1141
+ const analysis = analyze(source);
1142
+ const found = at(analysis, position);
1143
+ if (!found)
1144
+ return;
1145
+ return { range: toRange(analysis, found.item.definition) };
1146
+ }
1147
+ function references2(source, position, includeDeclaration = true) {
1148
+ const analysis = analyze(source);
1149
+ const found = at(analysis, position);
1150
+ if (!found)
1151
+ return [];
1152
+ return analysis.occurrences.filter((occurrence) => occurrence.item === found.item && (includeDeclaration || occurrence.range.start !== found.item.definition.start)).map((occurrence) => ({ range: toRange(analysis, occurrence.range) }));
1153
+ }
1154
+ function prepareRename(source, position) {
1155
+ const analysis = analyze(source);
1156
+ const found = at(analysis, position);
1157
+ if (!found)
1158
+ return;
1159
+ return { range: toRange(analysis, found.range), placeholder: found.item.id };
1160
+ }
1161
+ function rename(source, position, newName) {
1162
+ const analysis = analyze(source);
1163
+ const found = at(analysis, position);
1164
+ if (!found || !BARE.test(newName))
1165
+ return;
1166
+ if (analysis.items.some((item) => item !== found.item && item.id === newName))
1167
+ return;
1168
+ const mine = analysis.occurrences.filter((occurrence) => occurrence.item === found.item);
1169
+ const changes = mine.map((occurrence) => ({
1170
+ range: toRange(analysis, occurrence.range),
1171
+ newText: newName
1172
+ }));
1173
+ let text = analysis.conv.text;
1174
+ for (const occurrence of [...mine].reverse()) {
1175
+ text = text.slice(0, occurrence.range.start) + newName + text.slice(occurrence.range.end);
1176
+ }
1177
+ const before = parseTree(analysis.conv.text).errors;
1178
+ const after = parseTree(text).errors;
1179
+ const known = new Set(before.map((error) => error.code));
1180
+ if (after.length > before.length || after.some((error) => !known.has(error.code)))
1181
+ return;
1182
+ return { changes };
1183
+ }
1184
+ // src/language/symbols.ts
1185
+ function detailOf(id, label) {
1186
+ return label !== undefined && label.value !== id ? label.value : undefined;
1187
+ }
1188
+ function symbols(analysis) {
1189
+ const { ast } = analysis;
1190
+ const make = (kind, id, label, range, children, blocked) => {
1191
+ const block = blocked ? analysis.block(range.end) : undefined;
1192
+ return {
1193
+ name: id.value,
1194
+ detail: detailOf(id.value, label),
1195
+ kind,
1196
+ range: block ? { start: range.start, end: Math.max(range.end, block.end) } : range,
1197
+ selection: id.range,
1198
+ children
1199
+ };
1200
+ };
1201
+ const graph = (statements) => statements.flatMap((statement) => {
1202
+ if (statement.t === "group") {
1203
+ return [make("namespace", statement.id, statement.label, statement.range, graph(statement.body), true)];
1204
+ }
1205
+ if (statement.t === "node")
1206
+ return [make("object", statement.id, statement.label, statement.range, [], false)];
1207
+ return [];
1208
+ });
1209
+ const state = (statements) => statements.flatMap((statement) => statement.t === "state" ? [
1210
+ make("event", statement.id, statement.label, statement.range, statement.body ? state(statement.body) : [], statement.body !== undefined)
1211
+ ] : []);
1212
+ const er = (statements) => statements.flatMap((statement) => {
1213
+ if (statement.t !== "entity")
1214
+ return [];
1215
+ const fields = (statement.attributes ?? []).map((line) => ({
1216
+ name: line.name.value,
1217
+ detail: line.type?.value,
1218
+ kind: "field",
1219
+ range: line.range,
1220
+ selection: line.name.range,
1221
+ children: []
1222
+ }));
1223
+ return [make("struct", statement.id, statement.label, statement.range, fields, statement.attributes !== undefined)];
1224
+ });
1225
+ switch (ast.kind) {
1226
+ case "graph":
1227
+ return graph(ast.body);
1228
+ case "sequence":
1229
+ return ast.body.flatMap((statement) => statement.t === "participant" ? [make("class", statement.id, statement.label, statement.range, [], false)] : []);
1230
+ case "state":
1231
+ return state(ast.body);
1232
+ case "er":
1233
+ return er(ast.body);
1234
+ case "tree": {
1235
+ const nodes = ast.body.map((line) => ({
1236
+ name: line.label.value,
1237
+ kind: "object",
1238
+ range: line.range,
1239
+ selection: line.label.range,
1240
+ children: []
1241
+ }));
1242
+ const roots = [];
1243
+ for (let index = nodes.length - 1;index >= 0; index--) {
1244
+ const parent = ast.body[index].parent;
1245
+ if (parent < 0)
1246
+ continue;
1247
+ const target = nodes[parent];
1248
+ target.range = { start: target.range.start, end: Math.max(target.range.end, nodes[index].range.end) };
1249
+ }
1250
+ ast.body.forEach((line, index) => {
1251
+ if (line.parent < 0)
1252
+ roots.push(nodes[index]);
1253
+ else
1254
+ nodes[line.parent].children.push(nodes[index]);
1255
+ });
1256
+ return roots;
1257
+ }
1258
+ }
1259
+ }
1260
+ function end(items, from) {
1261
+ return items.reduce((value, item) => Math.max(value, item.range.end), from);
1262
+ }
1263
+ function documentSymbols(source) {
1264
+ const analysis = analyze(source);
1265
+ const { ast, conv } = analysis;
1266
+ const range = (span) => ({ start: conv.position(span.start), end: conv.position(span.end) });
1267
+ const convert = (item) => {
1268
+ const symbol = {
1269
+ name: item.name,
1270
+ kind: item.kind,
1271
+ range: range(item.range),
1272
+ selectionRange: range(item.selection)
1273
+ };
1274
+ if (item.detail !== undefined)
1275
+ symbol.detail = item.detail;
1276
+ if (item.children.length > 0)
1277
+ symbol.children = item.children.map(convert);
1278
+ return symbol;
1279
+ };
1280
+ const children = symbols(analysis);
1281
+ if (ast.header.missing)
1282
+ return children.map(convert);
1283
+ const title = ast.header.title;
1284
+ return [
1285
+ convert({
1286
+ name: title?.value ?? ast.kind,
1287
+ detail: title ? ast.kind : undefined,
1288
+ kind: "module",
1289
+ range: { start: ast.header.range.start, end: end(children, ast.header.range.end) },
1290
+ selection: ast.header.kindRange,
1291
+ children
1292
+ })
1293
+ ];
1294
+ }
1295
+ function foldingRanges(source) {
1296
+ const analysis = analyze(source);
1297
+ const { ast, conv } = analysis;
1298
+ const result = [];
1299
+ const region = (from) => {
1300
+ const block = analysis.block(from);
1301
+ if (!block)
1302
+ return;
1303
+ const startLine = conv.position(block.open).line;
1304
+ const endLine = block.close !== undefined ? conv.position(block.close).line - 1 : conv.position(block.end).line;
1305
+ if (endLine > startLine)
1306
+ result.push({ startLine, endLine, kind: "region" });
1307
+ };
1308
+ const graph = (statements) => {
1309
+ for (const statement of statements) {
1310
+ if (statement.t !== "group")
1311
+ continue;
1312
+ region(statement.range.end);
1313
+ graph(statement.body);
1314
+ }
1315
+ };
1316
+ const state = (statements) => {
1317
+ for (const statement of statements) {
1318
+ if (statement.t !== "state" || statement.body === undefined)
1319
+ continue;
1320
+ region(statement.range.end);
1321
+ state(statement.body);
1322
+ }
1323
+ };
1324
+ switch (ast.kind) {
1325
+ case "graph":
1326
+ graph(ast.body);
1327
+ break;
1328
+ case "state":
1329
+ state(ast.body);
1330
+ break;
1331
+ case "er":
1332
+ for (const statement of ast.body) {
1333
+ if (statement.t === "entity" && statement.attributes !== undefined)
1334
+ region(statement.range.end);
1335
+ }
1336
+ break;
1337
+ case "tree": {
1338
+ const levels = [];
1339
+ for (const line of ast.body)
1340
+ levels.push(line.parent < 0 ? 0 : levels[line.parent] + 1);
1341
+ ast.body.forEach((line, index) => {
1342
+ let last = index;
1343
+ while (last + 1 < ast.body.length && levels[last + 1] > levels[index])
1344
+ last++;
1345
+ if (last === index)
1346
+ return;
1347
+ const startLine = conv.position(line.range.start).line;
1348
+ const endLine = conv.position(ast.body[last].range.end).line;
1349
+ if (endLine > startLine)
1350
+ result.push({ startLine, endLine, kind: "region" });
1351
+ });
1352
+ break;
1353
+ }
1354
+ case "sequence":
1355
+ break;
1356
+ }
1357
+ const lines = conv.text.split(`
1358
+ `);
1359
+ let run;
1360
+ const close = (endLine) => {
1361
+ if (run !== undefined && endLine > run)
1362
+ result.push({ startLine: run, endLine, kind: "comment" });
1363
+ run = undefined;
1364
+ };
1365
+ lines.forEach((text, line) => {
1366
+ if (text.trimStart().startsWith("#"))
1367
+ run ??= line;
1368
+ else
1369
+ close(line - 1);
1370
+ });
1371
+ close(lines.length - 1);
1372
+ return result.sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine);
1373
+ }
1374
+ export {
1375
+ complete,
1376
+ definition,
1377
+ documentSymbols,
1378
+ foldingRanges,
1379
+ format,
1380
+ formatText,
1381
+ hover,
1382
+ prepareRename,
1383
+ references2 as references,
1384
+ rename
1385
+ };