@ds-lang/monaco-editor 0.0.0-stage → 1.1.1

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/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@ds-lang/monaco-editor",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.1.1",
4
+ "description": "The DS editor kit for Monaco: Desert Sage (DS) rulesets in the host's Monaco editor, with the DS compiler in the browser for live diagnostics, ds lsp, and recordings with their replay and inspect views",
5
+ "license": "BSD-4-Clause OR AGPL-3.0-or-later",
6
+ "homepage": "https://ds-lang.org",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/desert-sage/ds-monaco-editor.git"
10
+ },
11
+ "bugs": {
12
+ "url": "https://github.com/desert-sage/ds-monaco-editor/issues"
13
+ },
14
+ "type": "module",
15
+ "exports": {
16
+ ".": "./src/index.mjs",
17
+ "./compiler-worker": "./src/compiler-worker.mjs",
18
+ "./lsp-worker": "./src/lsp-worker.mjs",
19
+ "./lsp-server": "./src/node/ds-lsp.mjs"
20
+ },
21
+ "files": [
22
+ "src/",
23
+ "dist/",
24
+ "LICENSE",
25
+ "README.md"
26
+ ],
27
+ "publishConfig": {
28
+ "access": "public"
29
+ },
30
+ "engines": {
31
+ "node": ">=22"
32
+ },
33
+ "scripts": {
34
+ "test": "node --test test/*.test.mjs",
35
+ "test:browser": "playwright test",
36
+ "build": "node build.mjs"
37
+ },
38
+ "peerDependencies": {
39
+ "@ds-lang/ds": "1.1.1",
40
+ "@ds-lang/tools": "1.1.1",
41
+ "monaco-editor": ">=0.45.0"
42
+ },
43
+ "peerDependenciesMeta": {
44
+ "@ds-lang/tools": {
45
+ "optional": true
46
+ }
47
+ },
48
+ "dependencies": {
49
+ "@ds-lang/editor-core": "1.1.1"
50
+ },
51
+ "devDependencies": {
52
+ "@ds-lang/ds": "1.1.1",
53
+ "@ds-lang/tools": "1.1.1",
54
+ "@playwright/test": "1.65.1",
55
+ "esbuild": "0.25.12",
56
+ "monaco-editor": "0.52.2"
57
+ }
58
+ }
@@ -0,0 +1,5 @@
1
+ // SPDX-FileCopyrightText: 2026 Dan Finster and the Desert Sage Contributors
2
+ // SPDX-License-Identifier: BSD-4-Clause OR AGPL-3.0-or-later
3
+ // The compiler's thread, ds-editor-core's: built into dist/compiler-worker.js
4
+ // for a host page, and exported as ./compiler-worker.
5
+ import '@ds-lang/editor-core/compiler-worker';
@@ -0,0 +1,472 @@
1
+ // SPDX-FileCopyrightText: 2026 Dan Finster and the Desert Sage Contributors
2
+ // SPDX-License-Identifier: BSD-4-Clause OR AGPL-3.0-or-later
3
+ // The debugger in the host's Monaco, on a debugging session (ds-editor-core's
4
+ // dapSession) on the host's `ds dap`. ds-codemirror-editor's
5
+ // debugger (debugger.mjs there) gives the same, on the same keys:
6
+ //
7
+ // the glyph margin a click on a line sets or clears its breakpoint; an Alt-
8
+ // or Shift-click opens it to edit, with its condition, hit
9
+ // count and log message. ds dap says whether each is
10
+ // verified; an unverified one is greyed, with ds dap's
11
+ // message on hover
12
+ // the stop the line ds dap stopped at, marked and kept in view
13
+ // F5 continue, Shift-F5 reverse continue, F10 next, Shift-F10 step back,
14
+ // F11 step in, Shift-F11 step out, F6 pause, Ctrl-Shift-F5 restart (the
15
+ // breakpoints kept)
16
+ // the panel below the editor: the same controls as buttons, the stop,
17
+ // the step granularity, go to a target from the cursor's
18
+ // line, step in to one of the firings the action caused
19
+ // (Into…), the function, fact, cache and exception
20
+ // breakpoints, and ds dap's output
21
+ // the hover while stopped, the value of the name under the pointer
22
+ // at the top frame, with its parts (ds-editor-core's
23
+ // hoverText)
24
+ //
25
+ // The call stack, Variables, Watch, the console and the event log are
26
+ // ds-editor-core's (createDebugInspector), which a host puts beside the
27
+ // editor.
28
+ //
29
+ // Breakpoints are decorations, which Monaco keeps on their lines as the text
30
+ // changes, and are sent to ds dap as lines.
31
+ import { expressionAt, hoverText } from '@ds-lang/editor-core';
32
+
33
+ const STYLE = `
34
+ .ds-bp::before { content: '●'; color: var(--ds-code-bad, #cf222e); }
35
+ .ds-bp.unverified::before { color: var(--ds-code-soft, #8c959f); }
36
+ .ds-bp.logpoint::before { content: '◆'; }
37
+ .ds-bp.conditional { font-weight: 700; }
38
+ .ds-stop { background: var(--ds-code-stop, rgba(255, 213, 0, 0.35)); }
39
+ .ds-debug-panel { padding: 4px 8px; font-family: var(--ds-code-font, monospace); max-height: 16em; overflow: auto; border-top: 1px solid var(--ds-view-border, #d0d7de); }
40
+ .ds-debug-panel button, .ds-debug-panel input, .ds-debug-panel select { font: inherit; }
41
+ .ds-debug-panel button { margin-right: 4px; }
42
+ .ds-debug-panel .ds-row { margin: 2px 0; }
43
+ .ds-debug-panel .ds-stopline { font-weight: 600; }
44
+ .ds-debug-panel .bad { color: var(--ds-code-bad, #cf222e); }
45
+ .ds-debug-panel ul, .ds-debug-panel ol { margin: 2px 0; padding-left: 1.5em; }
46
+ `;
47
+
48
+ function addStyle(doc) {
49
+ if (!doc.getElementById('ds-monaco-debug')) {
50
+ const style = doc.createElement('style');
51
+ style.id = 'ds-monaco-debug';
52
+ style.textContent = STYLE;
53
+ doc.head.appendChild(style);
54
+ }
55
+ }
56
+
57
+ const STEPS = [
58
+ ['F5', 'continue', 'Continue'],
59
+ ['Shift+F5', 'reverseContinue', 'Reverse'],
60
+ ['F10', 'next', 'Step'],
61
+ ['Shift+F10', 'stepBack', 'Back'],
62
+ ['F11', 'stepIn', 'In'],
63
+ ['Shift+F11', 'stepOut', 'Out'],
64
+ ['F6', 'pause', 'Pause'],
65
+ ['Ctrl+Shift+F5', 'restart', 'Restart'],
66
+ ];
67
+
68
+ const FILTERS = [
69
+ ['unanswered_call', 'Unanswered call'],
70
+ ['fault', 'Fault'],
71
+ ['engine_error', 'Engine error'],
72
+ ];
73
+
74
+ /**
75
+ * The debugger on a session, for a Monaco editor showing the session's source.
76
+ *
77
+ * @param {any} monaco the host's monaco
78
+ * @param {any} editor the editor (createEditor's, or the host's own)
79
+ * @param {ReturnType<typeof import('@ds-lang/editor-core').dapSession>} session the session, which the host has launched
80
+ * @param {{panelParent?: HTMLElement}} [options] where the panel goes; just after the editor's element unless given
81
+ * @returns {{toggle: (line: number, options?: object) => Promise<void>, sync: () => Promise<any[]>, step: (command: string) => Promise<any>, refresh: () => Promise<void>, hoverAt: (line: number, column: number) => Promise<{line: number, from: number, to: number, text: string} | null>, breakpoints: () => any[], dispose: () => void}} what the tests and a host's own controls use
82
+ */
83
+ export function dsDebugger(monaco, editor, session, { panelParent } = {}) {
84
+ const doc = editor.getContainerDomNode().ownerDocument;
85
+ addStyle(doc);
86
+ editor.updateOptions({ glyphMargin: true });
87
+ const model = editor.getModel();
88
+
89
+ /** Each breakpoint: its line, its decoration's id, what it asks, and what ds dap answered. */
90
+ let breakpoints = [];
91
+ /** The breakpoints' decorations, which Monaco keeps on their lines as the text changes. */
92
+ let ids = [];
93
+ const stopDecoration = editor.createDecorationsCollection([]);
94
+
95
+ const lineOf = b => {
96
+ const r = model.getDecorationRange(b.id);
97
+ return r ? r.startLineNumber : null;
98
+ };
99
+
100
+ function draw() {
101
+ ids = model.deltaDecorations(
102
+ ids,
103
+ breakpoints.map(b => ({
104
+ range: new monaco.Range(b.line, 1, b.line, 1),
105
+ options: {
106
+ stickiness: monaco.editor.TrackedRangeStickiness.NeverGrowsWhenTypingAtEdges,
107
+ glyphMarginClassName: `ds-bp${b.verified === false ? ' unverified' : ''}${b.logMessage ? ' logpoint' : ''}${b.condition || b.hitCondition || b.logMessage ? ' conditional' : ''}`,
108
+ glyphMarginHoverMessage: {
109
+ value:
110
+ b.verified === false
111
+ ? b.message || 'not verified'
112
+ : [b.condition && `when ${b.condition}`, b.hitCondition && `hit ${b.hitCondition}`, b.logMessage && `log ${b.logMessage}`].filter(Boolean).join('; ') || 'breakpoint',
113
+ },
114
+ },
115
+ })),
116
+ );
117
+ breakpoints = breakpoints.map((b, i) => ({ ...b, id: ids[i] }));
118
+ }
119
+
120
+ /** Sends the line breakpoints, and keeps ds dap's answer to each. */
121
+ async function sync() {
122
+ breakpoints = breakpoints.map(b => ({ ...b, line: lineOf(b) || b.line }));
123
+ const answered = await session.setLineBreakpoints(
124
+ breakpoints.map(b => ({
125
+ line: b.line,
126
+ ...(b.condition ? { condition: b.condition } : {}),
127
+ ...(b.hitCondition ? { hitCondition: b.hitCondition } : {}),
128
+ ...(b.logMessage ? { logMessage: b.logMessage } : {}),
129
+ })),
130
+ );
131
+ breakpoints = breakpoints.map((b, i) => (answered[i] ? { ...b, dapId: answered[i].id, verified: !!answered[i].verified, message: answered[i].message } : b));
132
+ draw();
133
+ return answered;
134
+ }
135
+
136
+ /** Sets or clears the breakpoint on a line (1-based), or sets it with these options. */
137
+ async function toggle(line, options = null) {
138
+ breakpoints = breakpoints.map(b => ({ ...b, line: lineOf(b) || b.line }));
139
+ const there = breakpoints.find(b => b.line === line);
140
+ if (options) {
141
+ breakpoints = [...breakpoints.filter(b => b.line !== line), { line, ...options }];
142
+ } else {
143
+ breakpoints = there ? breakpoints.filter(b => b.line !== line) : [...breakpoints, { line }];
144
+ }
145
+ breakpoints.sort((a, b) => a.line - b.line);
146
+ draw();
147
+ await sync();
148
+ }
149
+
150
+ const step = command => session.request(command);
151
+
152
+ // ---- the panel ----
153
+
154
+ const el = (name, attrs = {}, parent = null, text = null) => {
155
+ const e = doc.createElement(name);
156
+ for (const [k, v] of Object.entries(attrs)) {
157
+ e.setAttribute(k, String(v));
158
+ }
159
+ if (text !== null) {
160
+ e.textContent = text;
161
+ }
162
+ if (parent) {
163
+ parent.append(e);
164
+ }
165
+ return e;
166
+ };
167
+
168
+ // Its own class: ds-editor-core's debug inspector, which a host puts
169
+ // beside it, is `ds-debug`, and the panel's styles are not the inspector's.
170
+ const panel = el('div', { class: 'ds-debug-panel', 'aria-label': 'debugger' });
171
+ if (panelParent) {
172
+ panelParent.append(panel);
173
+ } else {
174
+ editor.getContainerDomNode().after(panel);
175
+ }
176
+ const stopLine = el('div', { class: 'ds-stopline' }, panel, 'Not stopped yet.');
177
+ const note = el('div', { class: 'ds-debugnote' }, panel);
178
+ const say = (text, bad = false) => {
179
+ note.textContent = text;
180
+ note.className = bad ? 'ds-debugnote bad' : 'ds-debugnote';
181
+ };
182
+ const answered = (r, what) => {
183
+ if (!r.success) {
184
+ say(`${what}: ${r.message || 'refused'}`, true);
185
+ }
186
+ return r;
187
+ };
188
+
189
+ // The line breakpoint editor, opened by Alt- or Shift-click in the margin.
190
+ const edit = el('form', { class: 'ds-row ds-bpedit', hidden: '' }, panel);
191
+ const editLine = el('span', {}, edit);
192
+ const condition = el('input', { name: 'condition', placeholder: 'when (DS expression)', size: 22 }, edit);
193
+ const hit = el('input', { name: 'hitCondition', placeholder: 'hit (5, >= 3)', size: 8 }, edit);
194
+ const log = el('input', { name: 'logMessage', placeholder: 'log message (level={r.level})', size: 22 }, edit);
195
+ el('button', { type: 'submit' }, edit, 'Set');
196
+ let editing = null;
197
+ const openEdit = line => {
198
+ const b = breakpoints.find(x => x.line === line) || {};
199
+ editing = line;
200
+ editLine.textContent = `Line ${line}: `;
201
+ condition.value = b.condition || '';
202
+ hit.value = b.hitCondition || '';
203
+ log.value = b.logMessage || '';
204
+ edit.hidden = false;
205
+ condition.focus();
206
+ };
207
+ edit.addEventListener('submit', async e => {
208
+ e.preventDefault();
209
+ const line = editing;
210
+ edit.hidden = true;
211
+ await toggle(line, {
212
+ ...(condition.value ? { condition: condition.value } : {}),
213
+ ...(hit.value ? { hitCondition: hit.value } : {}),
214
+ ...(log.value ? { logMessage: log.value } : {}),
215
+ });
216
+ });
217
+ edit.addEventListener('keydown', e => {
218
+ if (e.key === 'Escape') {
219
+ e.preventDefault();
220
+ edit.hidden = true;
221
+ editor.focus();
222
+ }
223
+ });
224
+
225
+ const controls = el('div', { class: 'ds-row ds-controls' }, panel);
226
+ for (const [key, command, label] of STEPS) {
227
+ el('button', { type: 'button', 'data-command': command, title: key }, controls, label).addEventListener('click', async () => {
228
+ answered(await step(command), label);
229
+ });
230
+ }
231
+ const granularity = el('select', { 'aria-label': 'step granularity' }, controls);
232
+ for (const g of ['action', 'rule', 'pump', 'input']) {
233
+ el('option', { value: g }, granularity, g);
234
+ }
235
+ granularity.addEventListener('change', async () => {
236
+ const r = answered(await session.request('ds/stepGranularity', { granularity: granularity.value }), 'Granularity');
237
+ if (r.success && r.body) {
238
+ granularity.value = r.body.granularity;
239
+ }
240
+ });
241
+ const gotoButton = el('button', { type: 'button', class: 'ds-goto' }, controls, 'Go to…');
242
+ const intoButton = el('button', { type: 'button', class: 'ds-into', title: 'step in to a firing the action caused' }, controls, 'Into…');
243
+ const targets = el('ul', { class: 'ds-targets' }, panel);
244
+ intoButton.addEventListener('click', async () => {
245
+ targets.textContent = '';
246
+ const list = await session.stepInTargets();
247
+ if (!list.length) {
248
+ say('The action here caused no firing.');
249
+ return;
250
+ }
251
+ for (const t of list) {
252
+ el('li', { 'data-step-target': t.id }, targets, t.label).addEventListener('click', async () => {
253
+ targets.textContent = '';
254
+ answered(await session.stepInto(t.id), 'Into');
255
+ });
256
+ }
257
+ });
258
+ gotoButton.addEventListener('click', async () => {
259
+ targets.textContent = '';
260
+ const line = editor.getPosition().lineNumber;
261
+ const r = answered(await session.request('gotoTargets', { source: { path: 'rules.ds' }, line }), 'Go to');
262
+ if (!r.success) {
263
+ return;
264
+ }
265
+ if (!r.body.targets.length) {
266
+ say(`No recorded instant of line ${line}.`);
267
+ }
268
+ for (const t of r.body.targets) {
269
+ el('li', { 'data-target': t.id }, targets, t.label).addEventListener('click', async () => {
270
+ targets.textContent = '';
271
+ answered(await session.request('goto', { threadId: (session.state.stopped && session.state.stopped.threadId) || 1, targetId: t.id }), 'Go to');
272
+ });
273
+ }
274
+ });
275
+
276
+ const fn = el('form', { class: 'ds-row ds-functions' }, panel);
277
+ el('span', {}, fn, 'Rules ');
278
+ const fnNames = el('input', { name: 'functions', placeholder: 'rule, rule', size: 24 }, fn);
279
+ el('button', { type: 'submit' }, fn, 'Break on');
280
+ fn.addEventListener('submit', async e => {
281
+ e.preventDefault();
282
+ const names = fnNames.value.split(',').map(s => s.trim()).filter(Boolean);
283
+ const r = answered(await session.request('setFunctionBreakpoints', { breakpoints: names.map(name => ({ name })) }), 'Rule breakpoints');
284
+ if (r.success) {
285
+ const bad = r.body.breakpoints.filter(b => !b.verified);
286
+ say(bad.length ? bad.map(b => b.message).join('; ') : `Breaking on ${names.length} rule(s).`, !!bad.length);
287
+ }
288
+ });
289
+
290
+ const fact = el('form', { class: 'ds-row ds-facts' }, panel);
291
+ el('span', {}, fact, 'Facts ');
292
+ const factSchema = el('input', { name: 'schema', placeholder: 'schema', size: 10 }, fact);
293
+ const onAssert = el('input', { type: 'checkbox', name: 'assert', checked: '' }, fact);
294
+ el('span', {}, fact, 'assert ');
295
+ const onRetract = el('input', { type: 'checkbox', name: 'retract' }, fact);
296
+ el('span', {}, fact, 'retract ');
297
+ const factWhere = el('input', { name: 'where', placeholder: 'where (optional)', size: 18 }, fact);
298
+ el('button', { type: 'submit' }, fact, 'Break on');
299
+ fact.addEventListener('submit', async e => {
300
+ e.preventDefault();
301
+ const on = [onAssert.checked && 'assert', onRetract.checked && 'retract'].filter(Boolean);
302
+ const bp = { schema: factSchema.value, on, ...(factWhere.value ? { where: factWhere.value } : {}) };
303
+ const r = answered(await session.request('ds/setFactBreakpoints', { breakpoints: factSchema.value ? [bp] : [] }), 'Fact breakpoint');
304
+ if (r.success) {
305
+ const [b] = r.body.breakpoints;
306
+ say(b ? (b.verified ? `Breaking on ${bp.schema} ${on.join(' and ')}.` : b.message) : 'No fact breakpoint.', !!(b && !b.verified));
307
+ }
308
+ });
309
+
310
+ const cache = el('form', { class: 'ds-row ds-cache' }, panel);
311
+ el('span', {}, cache, 'Cache ');
312
+ const cacheKey = el('input', { name: 'key', placeholder: 'key (empty: any)', size: 14 }, cache);
313
+ const cacheOn = {};
314
+ for (const op of ['get', 'set', 'delete']) {
315
+ cacheOn[op] = el('input', { type: 'checkbox', name: op, ...(op === 'get' ? {} : { checked: '' }) }, cache);
316
+ el('span', {}, cache, `${op} `);
317
+ }
318
+ el('button', { type: 'submit' }, cache, 'Break on');
319
+ cache.addEventListener('submit', async e => {
320
+ e.preventDefault();
321
+ const on = Object.keys(cacheOn).filter(op => cacheOn[op].checked);
322
+ const r = answered(await session.request('ds/setCacheBreakpoints', { breakpoints: [{ key: cacheKey.value, on }] }), 'Cache breakpoint');
323
+ if (r.success) {
324
+ const [b] = r.body.breakpoints;
325
+ say(b && !b.verified ? b.message : `Breaking on cache ${on.join(', ')}.`, !!(b && !b.verified));
326
+ }
327
+ });
328
+
329
+ const ex = el('div', { class: 'ds-row ds-exceptions' }, panel);
330
+ el('span', {}, ex, 'Stop on ');
331
+ for (const [filter, label] of FILTERS) {
332
+ const box = el('input', { type: 'checkbox', name: filter, ...(filter === 'engine_error' ? { checked: '' } : {}) }, ex);
333
+ el('span', {}, ex, `${label} `);
334
+ box.addEventListener('change', async () => {
335
+ const filters = FILTERS.map(([f]) => f).filter(f => ex.querySelector(`input[name="${f}"]`).checked);
336
+ answered(await session.request('setExceptionBreakpoints', { filters }), 'Exception breakpoints');
337
+ });
338
+ }
339
+ const output = el('ol', { class: 'ds-output', 'aria-label': 'output' }, panel);
340
+
341
+ /** Marks the stop's line, and brings the panel up to the session. */
342
+ async function refresh() {
343
+ const s = session.state.stopped;
344
+ let line = null;
345
+ let where = '';
346
+ if (s && s.threadId !== undefined) {
347
+ const stack = await session.request('stackTrace', { threadId: s.threadId, levels: 1 });
348
+ const frame = stack.success && stack.body.stackFrames.length ? stack.body.stackFrames[0] : null;
349
+ if (frame && frame.line) {
350
+ line = frame.line;
351
+ where = ` at line ${frame.line} (${frame.name})`;
352
+ }
353
+ }
354
+ stopDecoration.set(line ? [{ range: new monaco.Range(line, 1, line, 1), options: { isWholeLine: true, className: 'ds-stop' } }] : []);
355
+ if (line) {
356
+ editor.setPosition({ lineNumber: line, column: 1 });
357
+ editor.revealLineInCenterIfOutsideViewport(line);
358
+ }
359
+ stopLine.textContent = session.state.ended
360
+ ? session.state.ended
361
+ : s
362
+ ? `Stopped: ${s.reason}${s.description ? `, ${s.description}` : ''}${where}.`
363
+ : 'Not stopped yet.';
364
+ output.textContent = '';
365
+ for (const o of session.state.output.slice(-20)) {
366
+ el('li', { class: o.category }, output, o.output.replace(/\n$/, ''));
367
+ }
368
+ }
369
+
370
+ // A click in the glyph margin sets or clears; Alt- or Shift-click edits.
371
+ const mouse = editor.onMouseDown(e => {
372
+ if (e.target.type !== monaco.editor.MouseTargetType.GUTTER_GLYPH_MARGIN || !e.target.position) {
373
+ return;
374
+ }
375
+ const line = e.target.position.lineNumber;
376
+ if (e.event.altKey || e.event.shiftKey) {
377
+ openEdit(line);
378
+ } else {
379
+ toggle(line);
380
+ }
381
+ });
382
+
383
+ const K = monaco.KeyCode;
384
+ const M = monaco.KeyMod;
385
+ const keys = { F5: K.F5, F6: K.F6, F10: K.F10, F11: K.F11 };
386
+ // Ctrl is Ctrl, or Cmd on a Mac, as VS Code binds restart.
387
+ const mods = { Shift: M.Shift, Ctrl: M.CtrlCmd };
388
+ for (const [key, command] of STEPS) {
389
+ const parts = key.split('+');
390
+ const code = keys[parts.pop()];
391
+ editor.addCommand(parts.reduce((m, p) => m | mods[p], 0) | code, () => {
392
+ step(command);
393
+ });
394
+ }
395
+
396
+ /**
397
+ * What the debug hover shows at a line and column (1-based): the
398
+ * expression there and its value where the session has stopped, or null.
399
+ *
400
+ * @param {number} line
401
+ * @param {number} column
402
+ * @returns {Promise<{line: number, from: number, to: number, text: string} | null>} the name's columns, 1-based, end exclusive
403
+ */
404
+ async function hoverAt(line, column) {
405
+ const st = session.state;
406
+ if (!st.stopped || st.ended) {
407
+ return null;
408
+ }
409
+ const at = expressionAt(model.getLineContent(line), column - 1);
410
+ if (!at) {
411
+ return null;
412
+ }
413
+ const text = await hoverText(session, at.expression);
414
+ return text === null ? null : { line, from: at.from + 1, to: at.to + 1, text };
415
+ }
416
+
417
+ // The hover, for this editor's model alone, in whatever language the host gave it.
418
+ const hover = monaco.languages.registerHoverProvider(model.getLanguageId(), {
419
+ async provideHover(m, position) {
420
+ if (m !== model) {
421
+ return null;
422
+ }
423
+ const v = await hoverAt(position.lineNumber, position.column);
424
+ if (!v) {
425
+ return null;
426
+ }
427
+ return {
428
+ range: new monaco.Range(v.line, v.from, v.line, v.to),
429
+ contents: [{ value: `\`\`\`\n${v.text}\n\`\`\`` }],
430
+ };
431
+ },
432
+ });
433
+
434
+ // Each answer that moved the session marks its stop. A `breakpoint` event
435
+ // (a restart sends one for each) says again whether ds dap verified it.
436
+ let moved = false;
437
+ const unlisten = session.listen((kind, v) => {
438
+ if (kind === 'event' && v.event === 'breakpoint' && v.body && v.body.breakpoint) {
439
+ const bp = v.body.breakpoint;
440
+ if (breakpoints.some(b => b.dapId === bp.id)) {
441
+ breakpoints = v.body.reason === 'removed'
442
+ ? breakpoints.filter(b => b.dapId !== bp.id)
443
+ : breakpoints.map(b => (b.dapId === bp.id ? { ...b, line: lineOf(b) || b.line, verified: !!bp.verified, message: bp.message } : b));
444
+ draw();
445
+ }
446
+ }
447
+ if (kind === 'event' && (v.event === 'stopped' || v.event === 'terminated' || v.event === 'output')) {
448
+ moved = true;
449
+ }
450
+ if (kind === 'answer' && moved) {
451
+ moved = false;
452
+ refresh();
453
+ }
454
+ });
455
+
456
+ return {
457
+ toggle,
458
+ sync,
459
+ step,
460
+ refresh,
461
+ hoverAt,
462
+ breakpoints: () => breakpoints.map(b => ({ ...b, line: lineOf(b) || b.line })),
463
+ dispose() {
464
+ unlisten();
465
+ hover.dispose();
466
+ mouse.dispose();
467
+ ids = model.deltaDecorations(ids, []);
468
+ stopDecoration.clear();
469
+ panel.remove();
470
+ },
471
+ };
472
+ }
@@ -0,0 +1,65 @@
1
+ // SPDX-FileCopyrightText: 2026 Dan Finster and the Desert Sage Contributors
2
+ // SPDX-License-Identifier: BSD-4-Clause OR AGPL-3.0-or-later
3
+ // The compiler's diagnostics as Monaco markers: ds-editor-core's
4
+ // dsDiagnostics (dsc's 1-based lines and columns, columns in characters)
5
+ // placed in the model, whose columns are 1-based UTF-16 units. A diagnostic
6
+ // with no place in the document (a library's, a failed analysis) goes on the
7
+ // first character, as ds-codemirror-editor puts it.
8
+ import { dsDiagnostics } from '@ds-lang/editor-core';
9
+
10
+ /** The owner Monaco files the kit's markers under. */
11
+ export const MARKER_OWNER = 'ds';
12
+
13
+ /**
14
+ * A 1-based line and character column as a Monaco position, clamped to the
15
+ * model: the column walked by code point, so a line holding `°F` or an
16
+ * astral character lands where dsc means.
17
+ *
18
+ * @param {{getLineCount: () => number, getLineContent: (line: number) => string}} model the model
19
+ * @param {{line?: number, column?: number} | null} pos dsc's position
20
+ * @returns {{lineNumber: number, column: number}} the position
21
+ */
22
+ export function positionOf(model, pos) {
23
+ const lineNumber = Math.max(1, Math.min((pos && pos.line) | 0 || 1, model.getLineCount()));
24
+ const text = model.getLineContent(lineNumber);
25
+ const chars = Array.from(text).slice(0, Math.max(0, ((pos && pos.column) | 0) - 1));
26
+ return { lineNumber, column: chars.join('').length + 1 };
27
+ }
28
+
29
+ /**
30
+ * The compiler's answer as marker data for monaco.editor.setModelMarkers.
31
+ *
32
+ * @param {any} model the model
33
+ * @param {{diagnostics?: any[], failure?: string}} result the compiler's answer
34
+ * @param {string} file the document's file name, as the compiler names it
35
+ * @param {{Error: number, Warning: number}} severities monaco.MarkerSeverity
36
+ * @returns {object[]} the markers
37
+ */
38
+ export function toMonacoMarkers(model, result, file, severities) {
39
+ return dsDiagnostics(result, file).map(d => {
40
+ const start = positionOf(model, d.start || { line: 1, column: 1 });
41
+ let end = d.start ? positionOf(model, d.end) : start;
42
+ if (end.lineNumber < start.lineNumber || (end.lineNumber === start.lineNumber && end.column <= start.column)) {
43
+ // A zero-width range shows nothing: mark the next character, or
44
+ // the one before at the end of a line.
45
+ const max = model.getLineContent(start.lineNumber).length + 1;
46
+ end = { lineNumber: start.lineNumber, column: Math.min(start.column + 1, max) };
47
+ if (end.column === start.column && start.column > 1) {
48
+ start.column -= 1;
49
+ }
50
+ }
51
+ const marker = {
52
+ severity: d.severity === 'warning' ? severities.Warning : severities.Error,
53
+ message: d.message,
54
+ startLineNumber: start.lineNumber,
55
+ startColumn: start.column,
56
+ endLineNumber: end.lineNumber,
57
+ endColumn: end.column,
58
+ };
59
+ if (d.code) {
60
+ marker.code = d.code;
61
+ marker.source = 'dsc';
62
+ }
63
+ return marker;
64
+ });
65
+ }