@krate/runtime 0.5.0-rc.14 → 0.5.0-rc.15

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 (61) hide show
  1. package/dist/action-context.js +5 -1
  2. package/dist/dev/api.d.ts +93 -0
  3. package/dist/dev/api.js +2 -0
  4. package/dist/dev/app.d.ts +165 -0
  5. package/dist/dev/app.js +1204 -0
  6. package/dist/dev/commands.d.ts +49 -0
  7. package/dist/dev/commands.js +114 -0
  8. package/dist/dev/highlight.d.ts +4 -0
  9. package/dist/dev/highlight.js +126 -0
  10. package/dist/dev/icons.d.ts +4 -0
  11. package/dist/dev/icons.js +57 -0
  12. package/dist/dev/inspect.d.ts +55 -0
  13. package/dist/dev/inspect.js +256 -0
  14. package/dist/dev/inspector.d.ts +39 -0
  15. package/dist/dev/inspector.js +348 -0
  16. package/dist/dev/issues.d.ts +83 -0
  17. package/dist/dev/issues.js +166 -0
  18. package/dist/dev/modal.d.ts +16 -0
  19. package/dist/dev/modal.js +836 -0
  20. package/dist/dev/native.d.ts +53 -0
  21. package/dist/dev/native.js +95 -0
  22. package/dist/dev/palette.d.ts +9 -0
  23. package/dist/dev/palette.js +250 -0
  24. package/dist/dev/panel.d.ts +31 -0
  25. package/dist/dev/panel.js +848 -0
  26. package/dist/dev/requests.d.ts +36 -0
  27. package/dist/dev/requests.js +150 -0
  28. package/dist/dev/settings.d.ts +32 -0
  29. package/dist/dev/settings.js +78 -0
  30. package/dist/dev/sourcemap.d.ts +22 -0
  31. package/dist/dev/sourcemap.js +148 -0
  32. package/dist/dev/stack.d.ts +38 -0
  33. package/dist/dev/stack.js +115 -0
  34. package/dist/dev/styles.d.ts +1 -0
  35. package/dist/dev/styles.js +424 -0
  36. package/dist/dev/util.d.ts +63 -0
  37. package/dist/dev/util.js +190 -0
  38. package/dist/dev-overlay.d.ts +9 -83
  39. package/dist/dev-overlay.js +17 -1038
  40. package/dist/island-swap.js +7 -1
  41. package/dist/krate-core.js +1 -1
  42. package/dist/krate-dev.js +441 -871
  43. package/dist/krate-f-list.js +1 -1
  44. package/dist/krate-f-navigation.js +1 -1
  45. package/dist/krate-hydrate-lite.js +5 -5
  46. package/dist/krate-hydrate.js +5 -5
  47. package/dist/krate-island-swap.js +1 -1
  48. package/dist/krate-runtime.js +5 -5
  49. package/dist/list.js +23 -1
  50. package/dist/metadata.js +23 -12
  51. package/dist/request-context.d.ts +10 -0
  52. package/dist/request-context.js +24 -0
  53. package/dist/server-handler.d.ts +2 -0
  54. package/dist/server-handler.js +1 -1
  55. package/dist/server-renderer.js +6 -2
  56. package/dist/server.js +2 -2
  57. package/dist/signal.d.ts +8 -0
  58. package/dist/signal.js +4 -0
  59. package/dist/ssr-core.d.ts +3 -0
  60. package/dist/ssr-core.js +44 -5
  61. package/package.json +1 -1
@@ -0,0 +1,39 @@
1
+ import type { KrateDev } from './app.js';
2
+ import { type Box, type CompRow } from './inspect.js';
3
+ export declare class Inspector {
4
+ private app;
5
+ on: boolean;
6
+ rows: CompRow[];
7
+ private els;
8
+ private ranges;
9
+ private layer?;
10
+ private legend?;
11
+ private tip?;
12
+ private hot;
13
+ private frame;
14
+ private observer?;
15
+ private last;
16
+ constructor(app: KrateDev);
17
+ private onMove;
18
+ private onClick;
19
+ /** Swallow the press that would start the click, so page handlers do not run. */
20
+ private onDown;
21
+ private onViewport;
22
+ toggle(): void;
23
+ enable(): void;
24
+ disable(): void;
25
+ /** Re-reads the table after a client-side navigation. */
26
+ refresh(): void;
27
+ private index;
28
+ private schedule;
29
+ /** The boxes an instance covers on screen. */
30
+ boxesOf(row: CompRow): Box[];
31
+ renderLegend(): void;
32
+ private draw;
33
+ private markHot;
34
+ /** The innermost instance at a point. */
35
+ rowAt(x: number, y: number): number;
36
+ private hover;
37
+ private renderTip;
38
+ private placeTip;
39
+ }
@@ -0,0 +1,348 @@
1
+ // The component inspector: tier outlines with names, a legend, and a hover
2
+ // tooltip. Clicks on the page open the hovered component's source.
3
+ import { icon } from './icons.js';
4
+ import { TIERS, boxContains, commentRanges, elementBox, formatValue, hydrationOf, hydrationStartOf, indexElements, kdNumbers, rangeBox, readTable, signalsOf, tierCounts, } from './inspect.js';
5
+ import { renderPanelBody } from './panel.js';
6
+ import { copyText, esc, kb } from './util.js';
7
+ const TIER_NAME = { static: 'Static', server: 'Server', client: 'Client', runtime: 'Runtime', island: 'Island' };
8
+ const MAX_BOXES = 400;
9
+ export class Inspector {
10
+ constructor(app) {
11
+ this.app = app;
12
+ this.on = false;
13
+ this.rows = [];
14
+ this.els = new Map();
15
+ this.ranges = new Map();
16
+ this.hot = -1;
17
+ this.frame = 0;
18
+ this.last = null;
19
+ this.onMove = (e) => {
20
+ this.last = { x: e.clientX, y: e.clientY };
21
+ this.hover(e.clientX, e.clientY, e.composedPath().includes(this.app.host));
22
+ };
23
+ this.onClick = (e) => {
24
+ if (e.composedPath().includes(this.app.host))
25
+ return;
26
+ const row = this.rows[this.hot];
27
+ if (!row)
28
+ return;
29
+ e.preventDefault();
30
+ e.stopPropagation();
31
+ e.stopImmediatePropagation();
32
+ if (!row.file) {
33
+ this.app.toast('No source location for ' + row.name, '', 'x');
34
+ return;
35
+ }
36
+ const loc = row.file + (row.line ? ':' + row.line : '');
37
+ if (e.shiftKey) {
38
+ void copyText(loc).then((ok) => this.app.toast(ok ? 'Path copied' : 'Could not copy', loc, ok ? 'check' : 'x'));
39
+ }
40
+ else {
41
+ void this.app.openInEditor(row.file, row.line);
42
+ }
43
+ };
44
+ /** Swallow the press that would start the click, so page handlers do not run. */
45
+ this.onDown = (e) => {
46
+ if (e.composedPath().includes(this.app.host) || this.hot < 0)
47
+ return;
48
+ e.preventDefault();
49
+ e.stopPropagation();
50
+ };
51
+ this.onViewport = () => this.schedule();
52
+ }
53
+ toggle() {
54
+ if (this.on)
55
+ this.disable();
56
+ else
57
+ this.enable();
58
+ }
59
+ enable() {
60
+ const rows = readTable();
61
+ if (!rows) {
62
+ this.app.toast('No component data on this page', 'dev builds only', 'x');
63
+ return;
64
+ }
65
+ if (this.app.hiddenAll)
66
+ return;
67
+ this.on = true;
68
+ this.rows = rows;
69
+ this.index();
70
+ const root = this.app.root;
71
+ this.layer = document.createElement('div');
72
+ this.layer.className = 'ins';
73
+ this.layer.setAttribute('aria-hidden', 'true');
74
+ root.insertBefore(this.layer, root.firstChild);
75
+ this.legend = document.createElement('div');
76
+ this.legend.className = 'legend';
77
+ this.legend.setAttribute('role', 'status');
78
+ root.appendChild(this.legend);
79
+ this.tip = document.createElement('div');
80
+ this.tip.className = 'tip';
81
+ this.tip.hidden = true;
82
+ root.appendChild(this.tip);
83
+ this.renderLegend();
84
+ this.draw();
85
+ document.addEventListener('pointermove', this.onMove, true);
86
+ document.addEventListener('click', this.onClick, true);
87
+ document.addEventListener('pointerdown', this.onDown, true);
88
+ document.addEventListener('mousedown', this.onDown, true);
89
+ window.addEventListener('scroll', this.onViewport, true);
90
+ window.addEventListener('resize', this.onViewport);
91
+ try {
92
+ this.observer = new MutationObserver((list) => {
93
+ if (list.some((m) => !this.app.host.contains(m.target))) {
94
+ this.index();
95
+ this.schedule();
96
+ }
97
+ });
98
+ this.observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-kd', 'style', 'class'] });
99
+ }
100
+ catch {
101
+ /* without an observer the outlines follow scroll and resize only */
102
+ }
103
+ this.app.renderDock();
104
+ if (this.app.panelOpen && this.app.tab === 'inspect')
105
+ renderPanelBody(this.app);
106
+ if (this.app.cfg.api && this.app.route === undefined)
107
+ void this.app.loadRoute();
108
+ }
109
+ disable() {
110
+ if (!this.on)
111
+ return;
112
+ this.on = false;
113
+ this.hot = -1;
114
+ document.removeEventListener('pointermove', this.onMove, true);
115
+ document.removeEventListener('click', this.onClick, true);
116
+ document.removeEventListener('pointerdown', this.onDown, true);
117
+ document.removeEventListener('mousedown', this.onDown, true);
118
+ window.removeEventListener('scroll', this.onViewport, true);
119
+ window.removeEventListener('resize', this.onViewport);
120
+ this.observer?.disconnect();
121
+ this.observer = undefined;
122
+ if (this.frame)
123
+ cancelAnimationFrame(this.frame);
124
+ this.frame = 0;
125
+ this.layer?.remove();
126
+ this.legend?.remove();
127
+ this.tip?.remove();
128
+ this.layer = this.legend = this.tip = undefined;
129
+ this.app.renderDock();
130
+ if (this.app.panelOpen && this.app.tab === 'inspect')
131
+ renderPanelBody(this.app);
132
+ }
133
+ /** Re-reads the table after a client-side navigation. */
134
+ refresh() {
135
+ if (!this.on)
136
+ return;
137
+ this.rows = readTable() || [];
138
+ this.index();
139
+ this.renderLegend();
140
+ this.schedule();
141
+ }
142
+ index() {
143
+ this.els = indexElements();
144
+ this.ranges = commentRanges(this.rows);
145
+ }
146
+ schedule() {
147
+ if (this.frame)
148
+ return;
149
+ this.frame = requestAnimationFrame(() => {
150
+ this.frame = 0;
151
+ this.draw();
152
+ if (this.last)
153
+ this.hover(this.last.x, this.last.y, false);
154
+ });
155
+ }
156
+ /** The boxes an instance covers on screen. */
157
+ boxesOf(row) {
158
+ const out = [];
159
+ for (const el of this.els.get(row.n) || []) {
160
+ const b = elementBox(el);
161
+ if (b)
162
+ out.push(b);
163
+ }
164
+ const rg = this.ranges.get(row.n);
165
+ if (rg) {
166
+ const b = rangeBox(rg);
167
+ if (b)
168
+ out.push(b);
169
+ }
170
+ return out;
171
+ }
172
+ renderLegend() {
173
+ if (!this.legend)
174
+ return;
175
+ const c = tierCounts(this.rows);
176
+ const isl = this.app.route?.sizes?.gzipIslands;
177
+ this.legend.innerHTML =
178
+ TIERS.filter((t) => t !== 'island' || c.island)
179
+ .map((t) => '<div class="li tp ' + t + '">' + TIER_NAME[t] + ' <b>' + c[t] + '</b></div>')
180
+ .join('') +
181
+ (isl ? '<span class="sep"></span><span class="js">' + kb(isl) + ' KB of island JS</span>' : '') +
182
+ '<button class="iconbtn" type="button" data-act="inspect" aria-label="Stop inspecting">' +
183
+ icon('x') +
184
+ '</button>';
185
+ }
186
+ draw() {
187
+ if (!this.layer)
188
+ return;
189
+ const vw = innerWidth;
190
+ const vh = innerHeight;
191
+ // Instances that share a root element draw one outline, labeled with the
192
+ // innermost name (rows come outermost first).
193
+ const boxes = [];
194
+ const seen = new Map();
195
+ for (const row of this.rows) {
196
+ if (boxes.length >= MAX_BOXES)
197
+ break;
198
+ this.boxesOf(row).forEach((box, k) => {
199
+ if (box.top > vh || box.left > vw || box.top + box.height < 0 || box.left + box.width < 0)
200
+ return;
201
+ const key = [box.left, box.top, box.width, box.height].map(Math.round).join(',');
202
+ const at = seen.get(key);
203
+ if (at !== undefined) {
204
+ boxes[at].row = row;
205
+ return;
206
+ }
207
+ seen.set(key, boxes.length);
208
+ boxes.push({ row, box, label: k === 0 });
209
+ });
210
+ }
211
+ this.layer.innerHTML = boxes
212
+ .map(({ row, box: b, label }) => {
213
+ const cls = 'ob ' + row.tier + (b.left + 140 > vw ? ' flip' : '') + (b.top < 24 ? ' inside' : '');
214
+ return ('<div class="' +
215
+ cls +
216
+ '" data-n="' +
217
+ row.n +
218
+ '" style="left:' +
219
+ b.left +
220
+ 'px;top:' +
221
+ b.top +
222
+ 'px;width:' +
223
+ b.width +
224
+ 'px;height:' +
225
+ b.height +
226
+ 'px">' +
227
+ (label ? '<span class="nm">' + esc(row.name) + '</span>' : '') +
228
+ '</div>');
229
+ })
230
+ .join('');
231
+ this.markHot();
232
+ }
233
+ markHot() {
234
+ this.layer?.querySelectorAll('.ob').forEach((el) => el.classList.toggle('hot', Number(el.dataset.n) === this.hot));
235
+ }
236
+ /** The innermost instance at a point. */
237
+ rowAt(x, y) {
238
+ let el = document.elementFromPoint(x, y);
239
+ let best = -1;
240
+ let bestArea = Infinity;
241
+ while (el && el !== document.documentElement) {
242
+ if (el === this.app.host)
243
+ return -1;
244
+ const ns = kdNumbers(el);
245
+ if (ns.length) {
246
+ best = ns[ns.length - 1];
247
+ const b = elementBox(el);
248
+ bestArea = b ? b.width * b.height : Infinity;
249
+ break;
250
+ }
251
+ el = el.parentElement;
252
+ }
253
+ // Comment-delimited instances (runtime regions, "use client" islands)
254
+ // have no element; take one when it is smaller than the element found.
255
+ for (const [n] of this.ranges) {
256
+ const row = this.rows[n];
257
+ if (!row)
258
+ continue;
259
+ for (const b of this.boxesOf(row)) {
260
+ if (boxContains(b, x, y) && b.width * b.height < bestArea) {
261
+ best = n;
262
+ bestArea = b.width * b.height;
263
+ }
264
+ }
265
+ }
266
+ return best;
267
+ }
268
+ hover(x, y, overOverlay) {
269
+ const n = overOverlay ? -1 : this.rowAt(x, y);
270
+ if (n !== this.hot) {
271
+ this.hot = n;
272
+ this.markHot();
273
+ this.renderTip();
274
+ }
275
+ this.placeTip(x, y);
276
+ }
277
+ renderTip() {
278
+ const tip = this.tip;
279
+ if (!tip)
280
+ return;
281
+ const row = this.rows[this.hot];
282
+ if (!row) {
283
+ tip.hidden = true;
284
+ return;
285
+ }
286
+ let kv = '';
287
+ if (row.file)
288
+ kv += '<dt>Source</dt><dd><span class="mono link path">' + esc(row.file + (row.line ? ':' + row.line : '')) + '</span></dd>';
289
+ const props = this.ranges.get(row.n)?.data?.props;
290
+ if (props && typeof props === 'object' && Object.keys(props).length)
291
+ kv += '<dt>Props</dt><dd><span class="mono">' + esc(formatValue(props)) + '</span></dd>';
292
+ const sigs = signalsOf(row.key);
293
+ if (sigs.length) {
294
+ kv +=
295
+ '<dt>Signals</dt><dd><span class="mono">' +
296
+ sigs
297
+ .map((s) => {
298
+ const cls = typeof s.value === 'boolean' ? 'sv-b' : typeof s.value === 'string' ? 'sv-s' : 'sv-n';
299
+ return esc(s.name) + ' = <span class="' + cls + '">' + esc(formatValue(s.value)) + '</span>';
300
+ })
301
+ .join(', ') +
302
+ '</span></dd>';
303
+ }
304
+ const gz = row.island ? this.app.route?.islands?.find((i) => i.id === row.island)?.gzip : undefined;
305
+ if (gz !== undefined)
306
+ kv += '<dt>Shipped</dt><dd><span class="mono">' + kb(gz) + ' KB gz</span></dd>';
307
+ else if (row.tier === 'static' || row.tier === 'server')
308
+ kv += '<dt>Shipped</dt><dd><span class="mono">HTML only, no JS</span></dd>';
309
+ const ms = hydrationOf(row);
310
+ if (ms !== undefined) {
311
+ const at = hydrationStartOf(row);
312
+ kv +=
313
+ '<dt>Hydrated</dt><dd><span class="mono">' +
314
+ (ms < 10 ? ms.toFixed(1) : Math.round(ms)) +
315
+ ' ms' +
316
+ (at !== undefined ? ', ' + Math.round(at) + ' ms after load' : '') +
317
+ '</span></dd>';
318
+ }
319
+ if (row.tier === 'runtime')
320
+ kv += '<dt>Renders</dt><dd><span class="mono">per request</span></dd>';
321
+ tip.innerHTML =
322
+ '<div class="tip-h"><span class="name">' +
323
+ esc(row.name) +
324
+ '</span><span class="tp ' +
325
+ row.tier +
326
+ '">' +
327
+ row.tier +
328
+ '</span></div>' +
329
+ (kv ? '<div class="tip-b"><dl class="kv">' + kv + '</dl></div>' : '') +
330
+ '<div class="tip-f"><span>Click: open in editor</span><span>Shift-click: copy path</span></div>';
331
+ tip.hidden = false;
332
+ }
333
+ placeTip(x, y) {
334
+ const tip = this.tip;
335
+ if (!tip || tip.hidden)
336
+ return;
337
+ const w = tip.offsetWidth || 300;
338
+ const h = tip.offsetHeight || 160;
339
+ let left = x + 16;
340
+ let top = y + 18;
341
+ if (left + w > innerWidth - 8)
342
+ left = Math.max(8, x - w - 16);
343
+ if (top + h > innerHeight - 8)
344
+ top = Math.max(8, y - h - 18);
345
+ tip.style.left = left + 'px';
346
+ tip.style.top = top + 'px';
347
+ }
348
+ }
@@ -0,0 +1,83 @@
1
+ export interface DevDiagnostic {
2
+ file?: string;
3
+ line?: number;
4
+ col?: number;
5
+ message: string;
6
+ hint?: string;
7
+ source?: string;
8
+ severity?: string;
9
+ code?: string;
10
+ }
11
+ export interface DevClientError {
12
+ message: string;
13
+ stack?: string;
14
+ url?: string;
15
+ line?: number;
16
+ col?: number;
17
+ kind?: string;
18
+ /** The window or view id the page was told it is in (Krate Native). */
19
+ window?: string;
20
+ source?: string;
21
+ detail?: string;
22
+ exitCode?: number;
23
+ log?: string[];
24
+ restart?: string;
25
+ /** The sidecar's runtime and version ("node 22.11"). */
26
+ runtime?: string;
27
+ /** How often it failed and was restarted within the last minute. */
28
+ restarts?: number;
29
+ }
30
+ export type IssueKind = 'build' | 'runtime' | 'server';
31
+ export interface Issue {
32
+ id: string;
33
+ kind: IssueKind;
34
+ severity: 'error' | 'warning';
35
+ /** The chip: a diagnostic code, an error class, or the failing part. */
36
+ label: string;
37
+ message: string;
38
+ file?: string;
39
+ line?: number;
40
+ col?: number;
41
+ hint?: string;
42
+ /** The offending source line a diagnostic carries. */
43
+ source?: string;
44
+ code?: string;
45
+ stack?: string;
46
+ hostStack?: string;
47
+ /** The location is a bundle the page loaded, not a project file. */
48
+ served?: boolean;
49
+ /** How the runtime error was caught. */
50
+ origin?: 'error' | 'rejection' | 'console' | 'resource' | 'remote';
51
+ count: number;
52
+ time: number;
53
+ server?: DevClientError;
54
+ }
55
+ export interface CodeFrame {
56
+ file: string;
57
+ lang: string;
58
+ start: number;
59
+ lines: string[];
60
+ /** Hydration scope key of the client component around the line (built output only). */
61
+ scope?: string;
62
+ }
63
+ export declare function issueFromDiagnostic(d: DevDiagnostic, i: number, time: number): Issue;
64
+ /** True for a build warning (it never blocks the build or opens the overlay). */
65
+ export declare function isBuildWarning(i: Issue): boolean;
66
+ /**
67
+ * Build issues from a list of diagnostics, one per location: a component
68
+ * used by several pages reports the same diagnostic once per page.
69
+ */
70
+ export declare function issuesFromDiagnostics(diags: DevDiagnostic[], time: number, offset?: number): Issue[];
71
+ export declare function issueFromRuntime(origin: NonNullable<Issue['origin']>, message: string, stack: string | undefined, hostStack: string | undefined, time: number): Issue;
72
+ /** Drops the browser's "Uncaught " prefix and an error class the chip already shows. */
73
+ export declare function cleanMessage(message: string, label: string): string;
74
+ export declare function issueFromServer(ce: DevClientError, time: number): Issue;
75
+ /** "1 issue in 1 file", "3 issues in 2 files". */
76
+ export declare function issueSummary(issues: Issue[]): string;
77
+ /** The code frame as plain text with line numbers and a caret under the column. */
78
+ export declare function frameText(frame: CodeFrame, line?: number, col?: number): string;
79
+ /** Markdown describing an issue, for pasting into an AI assistant or a bug report. */
80
+ export declare function copyForAI(issue: Issue, frame: CodeFrame | null, page?: {
81
+ url: string;
82
+ route?: string;
83
+ }): string;
@@ -0,0 +1,166 @@
1
+ // The issues the error overlay pages through, and their copy-for-AI text.
2
+ import { errorName, firstAppFrame, parseStack, projectLocation } from './stack.js';
3
+ export function issueFromDiagnostic(d, i, time) {
4
+ const warning = d.severity === 'warning';
5
+ return {
6
+ // A warning keeps its id across builds (it can be ignored for the
7
+ // session); errors are numbered as reported.
8
+ id: (warning ? 'w:' + (d.col || 0) + ':' : 'b' + i + ':') + (d.code || '') + ':' + (d.file || '') + ':' + (d.line || 0),
9
+ kind: 'build',
10
+ severity: warning ? 'warning' : 'error',
11
+ label: d.code || (warning ? 'Warning' : 'Build error'),
12
+ message: d.message.replace(/^UI: /, ''),
13
+ file: d.file,
14
+ line: d.line,
15
+ col: d.col,
16
+ hint: d.hint,
17
+ source: d.source,
18
+ code: d.code,
19
+ count: 1,
20
+ time,
21
+ };
22
+ }
23
+ /** True for a build warning (it never blocks the build or opens the overlay). */
24
+ export function isBuildWarning(i) {
25
+ return i.kind === 'build' && i.severity === 'warning';
26
+ }
27
+ /**
28
+ * Build issues from a list of diagnostics, one per location: a component
29
+ * used by several pages reports the same diagnostic once per page.
30
+ */
31
+ export function issuesFromDiagnostics(diags, time, offset = 0) {
32
+ const out = [];
33
+ const byKey = new Map();
34
+ diags.forEach((x, i) => {
35
+ if (!x || typeof x.message !== 'string')
36
+ return;
37
+ const k = [x.code, x.file, x.line, x.col, x.message, x.severity].join('|');
38
+ const dup = byKey.get(k);
39
+ if (dup) {
40
+ dup.count++;
41
+ return;
42
+ }
43
+ const issue = issueFromDiagnostic(x, offset + i, time);
44
+ byKey.set(k, issue);
45
+ out.push(issue);
46
+ });
47
+ return out;
48
+ }
49
+ const ORIGIN_LABEL = {
50
+ console: 'console.error',
51
+ resource: 'Resource error',
52
+ rejection: 'Unhandled rejection',
53
+ };
54
+ export function issueFromRuntime(origin, message, stack, hostStack, time) {
55
+ const frame = firstAppFrame(parseStack(stack));
56
+ const label = ORIGIN_LABEL[origin] || errorName(stack, message) || 'Error';
57
+ return {
58
+ id: 'r:' + message + '|' + (stack || ''),
59
+ kind: 'runtime',
60
+ severity: origin === 'console' ? 'warning' : 'error',
61
+ label,
62
+ message: cleanMessage(message, label),
63
+ file: frame?.file,
64
+ line: frame?.line,
65
+ col: frame?.col,
66
+ served: frame?.served,
67
+ stack,
68
+ hostStack,
69
+ origin,
70
+ count: 1,
71
+ time,
72
+ };
73
+ }
74
+ /** Drops the browser's "Uncaught " prefix and an error class the chip already shows. */
75
+ export function cleanMessage(message, label) {
76
+ let m = message.replace(/^Uncaught (?:\(in promise\) )?/, '');
77
+ if (label && m.startsWith(label + ': '))
78
+ m = m.slice(label.length + 2);
79
+ return m;
80
+ }
81
+ export function issueFromServer(ce, time) {
82
+ // The stack ends with the console tail; an old line there is not this crash.
83
+ const tail = new Set((ce.log || []).map((l) => l.trim()));
84
+ const own = (ce.stack || '')
85
+ .split('\n')
86
+ .filter((l) => !tail.has(l.trim()))
87
+ .join('\n');
88
+ const loc = projectLocation(own);
89
+ const source = ce.source || 'Server';
90
+ return {
91
+ id: 's:' + source,
92
+ kind: 'server',
93
+ severity: 'error',
94
+ label: errorName(ce.stack, ce.detail) || source,
95
+ message: ce.detail || ce.message,
96
+ file: loc?.file,
97
+ line: loc?.line,
98
+ col: loc?.col,
99
+ stack: ce.stack,
100
+ count: 1,
101
+ time,
102
+ server: ce,
103
+ };
104
+ }
105
+ /** "1 issue in 1 file", "3 issues in 2 files". */
106
+ export function issueSummary(issues) {
107
+ const files = new Set(issues.map((i) => i.file).filter(Boolean));
108
+ const n = issues.length;
109
+ const word = n && issues.every((i) => i.severity === 'warning') ? 'warning' : 'issue';
110
+ return n + ' ' + word + (n === 1 ? '' : 's') + (files.size ? ' in ' + files.size + (files.size === 1 ? ' file' : ' files') : '');
111
+ }
112
+ function fence(lang, body) {
113
+ const ticks = body.includes('```') ? '````' : '```';
114
+ return ticks + lang + '\n' + body.replace(/\n+$/, '') + '\n' + ticks;
115
+ }
116
+ /** The code frame as plain text with line numbers and a caret under the column. */
117
+ export function frameText(frame, line, col) {
118
+ const last = frame.start + frame.lines.length - 1;
119
+ const w = String(last).length;
120
+ const out = [];
121
+ frame.lines.forEach((text, i) => {
122
+ const n = frame.start + i;
123
+ const hl = n === line;
124
+ out.push((hl ? '> ' : ' ') + String(n).padStart(w) + ' | ' + text);
125
+ if (hl && col && col > 0)
126
+ out.push(' ' + ' '.repeat(w) + ' | ' + ' '.repeat(col - 1) + '^');
127
+ });
128
+ return out.join('\n');
129
+ }
130
+ /** Markdown describing an issue, for pasting into an AI assistant or a bug report. */
131
+ export function copyForAI(issue, frame, page) {
132
+ const kind = issue.kind === 'build' ? 'Build error' : issue.kind === 'server' ? 'Server error' : 'Runtime error';
133
+ const out = [];
134
+ out.push('## ' + kind + (issue.label ? ' ' + issue.label : '') + ': ' + issue.message.split('\n')[0]);
135
+ out.push('');
136
+ if (issue.message.includes('\n'))
137
+ out.push(issue.message, '');
138
+ const loc = issue.file ? issue.file + (issue.line ? ':' + issue.line + (issue.col ? ':' + issue.col : '') : '') : '';
139
+ if (loc)
140
+ out.push('- Location: `' + loc + '`');
141
+ if (issue.server) {
142
+ out.push('- Failed: ' + (issue.server.source || 'server'));
143
+ if (issue.server.exitCode !== undefined)
144
+ out.push('- Exit code: ' + issue.server.exitCode);
145
+ }
146
+ if (page)
147
+ out.push('- Page: ' + page.url + (page.route && page.route !== page.url ? ' (route `' + page.route + '`)' : ''));
148
+ if (issue.count > 1)
149
+ out.push('- Happened ' + issue.count + ' times');
150
+ out.push('- Reported by: Krate dev server');
151
+ if (frame && frame.lines.length) {
152
+ out.push('', fence(frame.lang || '', frameText(frame, issue.line, issue.col)));
153
+ }
154
+ else if (issue.source) {
155
+ out.push('', fence('', issue.source + (issue.col ? '\n' + ' '.repeat(issue.col - 1) + '^' : '')));
156
+ }
157
+ if (issue.hint)
158
+ out.push('', 'Hint: ' + issue.hint);
159
+ if (issue.stack && issue.kind !== 'build')
160
+ out.push('', 'Stack:', '', fence('', issue.stack));
161
+ if (issue.hostStack)
162
+ out.push('', 'Host stack:', '', fence('', issue.hostStack));
163
+ if (issue.server?.log?.length)
164
+ out.push('', 'Last console lines:', '', fence('', issue.server.log.join('\n')));
165
+ return out.join('\n') + '\n';
166
+ }
@@ -0,0 +1,16 @@
1
+ import type { KrateDev } from './app.js';
2
+ import type { FixChange } from './api.js';
3
+ import { type CodeFrame, type Issue } from './issues.js';
4
+ import { type FailedRequest } from './requests.js';
5
+ /** "node 22.11 · exited with code 1 · 12:44:30 · restarted twice in the last minute". */
6
+ export declare function serverSub(i: Issue, t: string): string;
7
+ /** The changed line of a fix: `from` replaced at its column, or its first occurrence. */
8
+ export declare function applyChange(line: string, c: FixChange): string;
9
+ export declare function codeFrameHTML(frame: CodeFrame | null, i: Issue, note?: string): string;
10
+ /** Failed requests around a runtime error, newest last. */
11
+ export declare function requestsHTML(reqs: FailedRequest[], at: number): string;
12
+ export declare function renderModal(app: KrateDev): void;
13
+ /** Loads the code frame and fix preview of an issue, then re-renders. */
14
+ export declare function prepareIssue(app: KrateDev, i: Issue | undefined): void;
15
+ export declare function modalClick(app: KrateDev, act: string, t: HTMLElement, _e: MouseEvent): boolean;
16
+ export declare function modalKey(app: KrateDev, e: KeyboardEvent, typing: boolean): boolean;