@krate/runtime 0.5.0-rc.2 → 0.5.0-rc.3

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 (152) hide show
  1. package/dist/actions.d.ts +7 -0
  2. package/dist/actions.js +21 -3
  3. package/dist/actions.test.js +8 -410
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/after.test.js +58 -0
  7. package/dist/assets-static.d.ts +10 -1
  8. package/dist/assets-static.js +10 -2
  9. package/dist/base-path.js +4 -3
  10. package/dist/builtin-tags.d.ts +12 -0
  11. package/dist/builtin-tags.js +42 -0
  12. package/dist/builtin-tags.test.js +12 -0
  13. package/dist/cache-adapter.test.js +4 -203
  14. package/dist/cache-scope.d.ts +2 -0
  15. package/dist/cache.test.js +1 -197
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/dev-overlay.d.ts +54 -3
  19. package/dist/dev-overlay.js +469 -76
  20. package/dist/dom.js +3 -1
  21. package/dist/events.test.js +2 -407
  22. package/dist/handler-html.test.js +1 -202
  23. package/dist/handler-routing.js +3 -0
  24. package/dist/handler-segments.d.ts +6 -0
  25. package/dist/handler-segments.js +16 -2
  26. package/dist/handler-segments.test.js +8 -200
  27. package/dist/head-tags.d.ts +9 -0
  28. package/dist/head-tags.js +85 -1
  29. package/dist/head-tags.test.js +18 -125
  30. package/dist/index.d.ts +1 -5
  31. package/dist/index.js +3 -0
  32. package/dist/inline-action-token.test.js +31 -0
  33. package/dist/jsx-svg-types.test.js +58 -0
  34. package/dist/jsx-types.d.ts +92 -1
  35. package/dist/krate-core.js +1 -1
  36. package/dist/krate-dev.js +384 -65
  37. package/dist/krate-f-actions.js +1 -1
  38. package/dist/krate-f-navigation.js +1 -1
  39. package/dist/krate-f-router-lite.js +1 -1
  40. package/dist/krate-f-router.js +1 -1
  41. package/dist/krate-features.json +2 -0
  42. package/dist/krate-hydrate-lite.js +5 -5
  43. package/dist/krate-hydrate.js +5 -5
  44. package/dist/krate-runtime.js +5 -5
  45. package/dist/link-base-path.test.js +28 -0
  46. package/dist/node-server.test.js +1 -355
  47. package/dist/platform.d.ts +52 -0
  48. package/dist/platform.js +57 -0
  49. package/dist/platform.test.js +44 -0
  50. package/dist/router-nav.test.js +15 -444
  51. package/dist/router.js +39 -1
  52. package/dist/server-handler.d.ts +48 -0
  53. package/dist/server-handler.js +272 -16
  54. package/dist/server-handler.test.js +54 -388
  55. package/dist/server-renderer.test.js +0 -104
  56. package/dist/server.d.ts +15 -5
  57. package/dist/server.js +149 -22
  58. package/dist/server.test.js +52 -60
  59. package/dist/site-config.d.ts +13 -0
  60. package/dist/site-config.js +28 -0
  61. package/dist/site-config.test.js +30 -0
  62. package/dist/ssr-core-behavior.test.js +3 -515
  63. package/dist/testing.d.ts +59 -0
  64. package/dist/testing.js +88 -0
  65. package/dist/testing.test.js +73 -0
  66. package/package.json +9 -1
  67. package/dist/action-context.test.js +0 -72
  68. package/dist/base-path.test.js +0 -88
  69. package/dist/class-component.test.js +0 -462
  70. package/dist/class-helpers.test.js +0 -169
  71. package/dist/context.test.js +0 -57
  72. package/dist/derived.test.js +0 -140
  73. package/dist/dev-overlay.test.js +0 -165
  74. package/dist/discrete.test.js +0 -100
  75. package/dist/dom.test.d.ts +0 -1
  76. package/dist/dom.test.js +0 -39
  77. package/dist/effect-errors.test.d.ts +0 -1
  78. package/dist/effect-errors.test.js +0 -199
  79. package/dist/effects.test.d.ts +0 -1
  80. package/dist/effects.test.js +0 -485
  81. package/dist/handler-routing.test.d.ts +0 -1
  82. package/dist/handler-routing.test.js +0 -99
  83. package/dist/highlight-bind.test.d.ts +0 -1
  84. package/dist/highlight-bind.test.js +0 -124
  85. package/dist/highlight.test.d.ts +0 -1
  86. package/dist/highlight.test.js +0 -56
  87. package/dist/lanes.test.d.ts +0 -1
  88. package/dist/lanes.test.js +0 -59
  89. package/dist/list.test.d.ts +0 -1
  90. package/dist/list.test.js +0 -435
  91. package/dist/metadata.test.d.ts +0 -1
  92. package/dist/metadata.test.js +0 -167
  93. package/dist/navigation.test.d.ts +0 -1
  94. package/dist/navigation.test.js +0 -130
  95. package/dist/optimistic-lanes.test.d.ts +0 -1
  96. package/dist/optimistic-lanes.test.js +0 -45
  97. package/dist/patterns.test.d.ts +0 -1
  98. package/dist/patterns.test.js +0 -125
  99. package/dist/portal.test.d.ts +0 -1
  100. package/dist/portal.test.js +0 -99
  101. package/dist/react-effects.test.d.ts +0 -1
  102. package/dist/react-effects.test.js +0 -133
  103. package/dist/react-suspense.test.d.ts +0 -1
  104. package/dist/react-suspense.test.js +0 -194
  105. package/dist/react.test.d.ts +0 -1
  106. package/dist/react.test.js +0 -60
  107. package/dist/react19.test.d.ts +0 -1
  108. package/dist/react19.test.js +0 -176
  109. package/dist/reactivity-core.test.d.ts +0 -1
  110. package/dist/reactivity-core.test.js +0 -152
  111. package/dist/reconcile.test.d.ts +0 -1
  112. package/dist/reconcile.test.js +0 -110
  113. package/dist/refs.test.d.ts +0 -1
  114. package/dist/refs.test.js +0 -257
  115. package/dist/router-layout.test.d.ts +0 -1
  116. package/dist/router-layout.test.js +0 -249
  117. package/dist/router-slots.test.d.ts +0 -1
  118. package/dist/router-slots.test.js +0 -144
  119. package/dist/router-speculation.test.d.ts +0 -1
  120. package/dist/router-speculation.test.js +0 -25
  121. package/dist/router-styles.test.d.ts +0 -1
  122. package/dist/router-styles.test.js +0 -98
  123. package/dist/router.test.d.ts +0 -1
  124. package/dist/router.test.js +0 -36
  125. package/dist/server-async.test.d.ts +0 -1
  126. package/dist/server-async.test.js +0 -216
  127. package/dist/server-highlight.test.d.ts +0 -1
  128. package/dist/server-highlight.test.js +0 -32
  129. package/dist/signal-lanes.test.d.ts +0 -1
  130. package/dist/signal-lanes.test.js +0 -32
  131. package/dist/slots.test.d.ts +0 -1
  132. package/dist/slots.test.js +0 -187
  133. package/dist/snapshots.test.d.ts +0 -1
  134. package/dist/snapshots.test.js +0 -208
  135. package/dist/ssr-core.test.d.ts +0 -1
  136. package/dist/ssr-core.test.js +0 -324
  137. package/dist/static-memory.test.d.ts +0 -1
  138. package/dist/static-memory.test.js +0 -26
  139. package/dist/storage.test.d.ts +0 -1
  140. package/dist/storage.test.js +0 -46
  141. package/dist/suspense-actions.test.d.ts +0 -1
  142. package/dist/suspense-actions.test.js +0 -72
  143. package/dist/suspense.test.d.ts +0 -1
  144. package/dist/suspense.test.js +0 -556
  145. /package/dist/{action-context.test.d.ts → after.test.d.ts} +0 -0
  146. /package/dist/{base-path.test.d.ts → builtin-tags.test.d.ts} +0 -0
  147. /package/dist/{class-component.test.d.ts → inline-action-token.test.d.ts} +0 -0
  148. /package/dist/{class-helpers.test.d.ts → jsx-svg-types.test.d.ts} +0 -0
  149. /package/dist/{context.test.d.ts → link-base-path.test.d.ts} +0 -0
  150. /package/dist/{derived.test.d.ts → platform.test.d.ts} +0 -0
  151. /package/dist/{dev-overlay.test.d.ts → site-config.test.d.ts} +0 -0
  152. /package/dist/{discrete.test.d.ts → testing.test.d.ts} +0 -0
@@ -6,12 +6,26 @@
6
6
  * diagnostics (file:line:col + source + caret + hint) and client runtime errors,
7
7
  * forwards runtime errors back to the dev server, and offers open-in-editor.
8
8
  */
9
+ import { siteConfig } from './site-config.js';
10
+ /** True inside a Krate Native window (`krate://app`, or `https://app.localhost` on Windows). */
11
+ export function isNativeOrigin() {
12
+ try {
13
+ return location.protocol === 'krate:' || location.origin === 'https://app.localhost';
14
+ }
15
+ catch {
16
+ return false;
17
+ }
18
+ }
9
19
  function devConfig() {
10
20
  const raw = window.__KRATE_DEV__;
11
- const runtime = window.__KRATE_CFG__;
21
+ const runtime = siteConfig();
22
+ const native = isNativeOrigin();
12
23
  return {
13
24
  sse: raw?.sse ?? '/__krate/hotreload',
14
- errors: raw?.errors ?? '/__krate/client-error',
25
+ frames: raw?.frames ?? (native ? '/__krate/hmr' : ''),
26
+ events: raw?.events ?? (native ? '/__krate/dev/events' : ''),
27
+ memory: raw?.memory ?? (native ? '/__krate/dev/memory' : ''),
28
+ errors: raw?.errors ?? (native ? '/__krate/dev/client-error' : '/__krate/client-error'),
15
29
  open: raw?.open ?? '/__krate/open',
16
30
  overlay: raw?.overlay ?? true,
17
31
  toolbar: raw?.toolbar ?? true,
@@ -76,7 +90,11 @@ export function decodeMappings(mappings) {
76
90
  continue;
77
91
  const nums = decodeVLQ(part);
78
92
  genCol += nums[0] || 0;
79
- if (nums.length >= 4) {
93
+ if (nums.length === 1) {
94
+ // An end marker: no original position from here on.
95
+ segs.push({ genCol, src: -1, srcLine: 0, srcCol: 0 });
96
+ }
97
+ else if (nums.length >= 4) {
80
98
  src += nums[1];
81
99
  srcLine += nums[2];
82
100
  srcCol += nums[3];
@@ -95,7 +113,8 @@ async function loadSourceMap(url) {
95
113
  return cached;
96
114
  const p = (async () => {
97
115
  try {
98
- if (/^[a-z]+:\/\//i.test(url) && !url.startsWith(location.origin))
116
+ const u = new URL(url, location.href);
117
+ if (u.protocol !== location.protocol || u.host !== location.host)
99
118
  return null;
100
119
  const res = await fetch(url + '.map');
101
120
  if (!res.ok)
@@ -115,7 +134,7 @@ async function loadSourceMap(url) {
115
134
  /** Parses a V8/Firefox stack line into its script location, if present. */
116
135
  export function parseStackFrame(line) {
117
136
  const patterns = [
118
- /^(.*?)((?:https?:)?\/\/[^\s)]+|\/[^\s):]+):(\d+):(\d+)(.*)$/,
137
+ /^(.*?)((?:[a-z][a-z0-9+.-]*:)?\/\/[^\s)]+|\/[^\s):]+):(\d+):(\d+)(.*)$/,
119
138
  ];
120
139
  for (const re of patterns) {
121
140
  const m = re.exec(line);
@@ -126,18 +145,32 @@ export function parseStackFrame(line) {
126
145
  return null;
127
146
  }
128
147
  function remapLocation(map, line, col) {
129
- const segs = map.lines[line - 1];
130
- if (!segs || segs.length === 0)
131
- return null;
132
148
  let best = null;
133
- for (const s of segs) {
134
- if (s.genCol <= col - 1)
135
- best = s;
136
- else
137
- break;
149
+ const segs = map.lines[line - 1];
150
+ if (segs && segs.length > 0) {
151
+ for (const s of segs) {
152
+ if (s.genCol <= col - 1)
153
+ best = s;
154
+ else
155
+ break;
156
+ }
157
+ if (!best)
158
+ best = segs[0];
159
+ }
160
+ else {
161
+ // An unminified hydration map has a mapping only where a marker starts;
162
+ // it holds until the next one, so a line without any takes the last
163
+ // mapping before it.
164
+ for (let i = Math.min(line - 1, map.lines.length) - 1; i >= 0 && !best; i--) {
165
+ const prev = map.lines[i];
166
+ if (prev && prev.length > 0)
167
+ best = prev[prev.length - 1];
168
+ }
169
+ if (!best)
170
+ return null;
138
171
  }
139
- if (!best)
140
- best = segs[0];
172
+ if (best.src < 0)
173
+ return null;
141
174
  const source = map.sources[best.src] || '';
142
175
  return { source, line: best.srcLine + 1, col: best.srcCol + 1 };
143
176
  }
@@ -154,7 +187,9 @@ export async function symbolicateStack(stack) {
154
187
  if (!map)
155
188
  return line;
156
189
  const loc = remapLocation(map, frame.line, frame.col);
157
- if (!loc)
190
+ // The generic label of a compiler-generated bundle says nothing more
191
+ // than the frame's own file and line.
192
+ if (!loc || !loc.source || loc.source === 'krate-hydration.js')
158
193
  return line;
159
194
  return frame.prefix + loc.source + ':' + loc.line + ':' + loc.col + frame.suffix;
160
195
  }));
@@ -164,6 +199,18 @@ export async function symbolicateStack(stack) {
164
199
  * Route matcher: a segment starting with `[` matches anything; `[...x]` matches
165
200
  * the rest. Exported (pure) for testing.
166
201
  */
202
+ function formatArg(a) {
203
+ if (a instanceof Error)
204
+ return a.message || String(a);
205
+ if (typeof a === 'string')
206
+ return a;
207
+ try {
208
+ return JSON.stringify(a) ?? String(a);
209
+ }
210
+ catch {
211
+ return String(a);
212
+ }
213
+ }
167
214
  export function routeMatches(pattern, pathname, basePath = '') {
168
215
  const a = norm(stripBase(pathname, basePath)).split('/');
169
216
  const b = norm(pattern).split('/');
@@ -179,6 +226,103 @@ export function routeMatches(pattern, pathname, basePath = '') {
179
226
  }
180
227
  return a.length === b.length;
181
228
  }
229
+ /**
230
+ * Splits a buffer of Krate frames (u32 length, JSON, u16 blob count, blobs)
231
+ * into its complete JSON values. `rest` is the incomplete tail to prepend to
232
+ * the next chunk. Exported (pure) for testing.
233
+ */
234
+ export function parseFrames(buf) {
235
+ const values = [];
236
+ const view = new DataView(buf.buffer, buf.byteOffset, buf.byteLength);
237
+ const td = new TextDecoder();
238
+ let pos = 0;
239
+ while (buf.length - pos >= 4) {
240
+ const n = view.getUint32(pos);
241
+ let end = pos + 4 + n;
242
+ if (buf.length < end + 2)
243
+ break;
244
+ const json = td.decode(buf.subarray(pos + 4, end));
245
+ const blobs = view.getUint16(end);
246
+ end += 2;
247
+ let complete = true;
248
+ for (let i = 0; i < blobs; i++) {
249
+ if (buf.length < end + 4) {
250
+ complete = false;
251
+ break;
252
+ }
253
+ end += 4 + view.getUint32(end);
254
+ if (buf.length < end) {
255
+ complete = false;
256
+ break;
257
+ }
258
+ }
259
+ if (!complete)
260
+ break;
261
+ try {
262
+ values.push(JSON.parse(json));
263
+ }
264
+ catch {
265
+ /* skip a malformed frame */
266
+ }
267
+ pos = end;
268
+ }
269
+ return { values, rest: buf.subarray(pos) };
270
+ }
271
+ /** The host-side stack a KrateError carries in dev (`data.stack`), or "". */
272
+ export function hostStackOf(reason) {
273
+ const data = reason?.data;
274
+ const stack = data && typeof data === 'object' ? data.stack : undefined;
275
+ return typeof stack === 'string' ? stack : '';
276
+ }
277
+ /** One line of the Host panel. Exported (pure) for testing. */
278
+ export function hostEventLine(ev) {
279
+ const t = ev.time ? new Date(ev.time).toLocaleTimeString() : '';
280
+ const dur = ev.durNs ? (ev.durNs / 1e6 >= 10 ? Math.round(ev.durNs / 1e6) : Math.round(ev.durNs / 1e5) / 10) + 'ms' : '';
281
+ const err = ev.code ? ' ' + ev.code + (ev.message ? ': ' + ev.message : '') : '';
282
+ return [t, ev.kind, ev.fn, dur].filter(Boolean).join(' ') + err;
283
+ }
284
+ /** Format a byte count for the Memory panel. Exported (pure) for testing. */
285
+ export function formatBytes(n) {
286
+ if (!Number.isFinite(n) || n < 0)
287
+ return 'n/a';
288
+ if (n >= 1 << 30)
289
+ return (n / (1 << 30)).toFixed(2) + ' GiB';
290
+ if (n >= 1 << 20)
291
+ return (n / (1 << 20)).toFixed(1) + ' MiB';
292
+ if (n >= 1 << 10)
293
+ return Math.round(n / (1 << 10)) + ' KiB';
294
+ return Math.round(n) + ' B';
295
+ }
296
+ /**
297
+ * The JS heap of this page, or null where the engine does not expose it.
298
+ * Chromium has performance.memory; WebKit (the engine of the Linux and macOS
299
+ * webviews) has no heap size API, so the panel shows the web process row
300
+ * (PSS and private dirty, which include the JS heap) instead.
301
+ */
302
+ export function jsHeapBytes() {
303
+ const m = (typeof performance !== 'undefined' ? performance.memory : undefined);
304
+ return m && typeof m.usedJSHeapSize === 'number' ? m.usedJSHeapSize : null;
305
+ }
306
+ /** The rows of the Memory panel as [label, value] pairs. Exported (pure) for testing. */
307
+ export function memoryRows(rep, domNodes, heap) {
308
+ const rows = [];
309
+ if (rep && rep.procs) {
310
+ for (const p of rep.procs) {
311
+ rows.push([p.role + ' (' + p.pid + ')', 'PSS ' + formatBytes(p.pss) + ' / private dirty ' + formatBytes(p.privateDirty)]);
312
+ }
313
+ if (rep.total)
314
+ rows.push(['total', 'PSS ' + formatBytes(rep.total.pss) + ' / private dirty ' + formatBytes(rep.total.privateDirty)]);
315
+ }
316
+ else {
317
+ rows.push(['processes', 'unavailable']);
318
+ }
319
+ rows.push(['DOM nodes', String(domNodes)]);
320
+ rows.push(['JS heap', heap === null ? 'unavailable in this engine (see the web process row)' : formatBytes(heap)]);
321
+ return rows;
322
+ }
323
+ const ICON_MEM = '<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
324
+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
325
+ '<rect x="4" y="6" width="16" height="12" rx="1"/><path d="M8 10v4M12 10v4M16 10v4"/><path d="M7 18v2M12 18v2M17 18v2"/></svg>';
182
326
  const ICON_RELOAD = '<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
183
327
  'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
184
328
  '<path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>';
@@ -186,6 +330,9 @@ const ICON_ALERT = '<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="curr
186
330
  'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
187
331
  '<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/>' +
188
332
  '<path d="M12 9v4"/><path d="M12 17h.01"/></svg>';
333
+ const ICON_HOST = '<svg class="ic" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" ' +
334
+ 'stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">' +
335
+ '<rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8"/><path d="M12 16v4"/></svg>';
189
336
  const STYLE = `
190
337
  :host { all: initial; }
191
338
  * { box-sizing: border-box; }
@@ -288,6 +435,31 @@ const STYLE = `
288
435
  .frame .src { color: #d4d4d4; }
289
436
  .frame .caret { color: var(--red); }
290
437
  .hint { margin-top: 8px; color: #a3e635; }
438
+ .hostpanel {
439
+ position: fixed; right: 12px; bottom: 12px; z-index: 2147483002;
440
+ width: min(560px, calc(100vw - 24px)); max-height: 50vh; display: flex; flex-direction: column;
441
+ background: var(--bg); border: 1px solid var(--line); border-radius: 12px;
442
+ box-shadow: 0 16px 48px rgba(0,0,0,.5); overflow: hidden;
443
+ font: 12px/1.45 "SF Mono", Menlo, Monaco, Consolas, "Courier New", monospace; color: var(--fg);
444
+ }
445
+ .hostpanel[hidden] { display: none; }
446
+ .hostpanel .card-head { padding: 8px 12px; }
447
+ .hostrows { overflow: auto; padding: 4px 0; }
448
+ .hostrow { padding: 2px 12px; white-space: pre-wrap; word-break: break-word; }
449
+ .hostrow.err { color: var(--red); }
450
+ .hostrow.sig { color: var(--muted); }
451
+ .mempanel {
452
+ position: fixed; right: 12px; bottom: 12px; z-index: 2147483002;
453
+ width: min(460px, calc(100vw - 24px));
454
+ background: var(--bg); border: 1px solid var(--line); border-radius: 12px;
455
+ box-shadow: 0 16px 48px rgba(0,0,0,.5); overflow: hidden;
456
+ font: 12px/1.45 "SF Mono", Menlo, Monaco, Consolas, "Courier New", monospace; color: var(--fg);
457
+ }
458
+ .mempanel[hidden] { display: none; }
459
+ .mempanel .card-head { padding: 8px 12px; }
460
+ .memrow { display: flex; gap: 12px; justify-content: space-between; padding: 2px 12px; }
461
+ .memrow .k { color: var(--muted); }
462
+ .memrow .v { text-align: right; }
291
463
  .stack {
292
464
  margin-top: 10px; color: var(--muted); white-space: pre-wrap; word-break: break-word;
293
465
  max-height: 320px; overflow: auto;
@@ -298,6 +470,7 @@ class KrateDev {
298
470
  this.cfg = devConfig();
299
471
  this.buildDiags = [];
300
472
  this.runtimeErrors = [];
473
+ this.hostSeq = 0;
301
474
  this.seen = new Set();
302
475
  }
303
476
  init() {
@@ -327,8 +500,14 @@ class KrateDev {
327
500
  '<button class="tb-btn errors" type="button" title="Show errors">' +
328
501
  ICON_ALERT +
329
502
  '<span class="tb-label">Errors</span></button>' +
503
+ (this.cfg.events
504
+ ? '<button class="tb-btn host" type="button" title="Host calls">' + ICON_HOST + '<span class="tb-label">Host</span></button>'
505
+ : '') +
330
506
  '<div class="tb-center"><span class="brand">krate</span>' +
331
507
  '<span class="route"></span></div>' +
508
+ (this.cfg.memory
509
+ ? '<button class="tb-btn mem" type="button" title="Memory">' + ICON_MEM + '<span class="tb-label">Memory</span></button>'
510
+ : '') +
332
511
  '<button class="tb-btn reload" type="button" title="Reload">' +
333
512
  ICON_RELOAD +
334
513
  '<span class="tb-label">Reload</span></button>';
@@ -342,7 +521,10 @@ class KrateDev {
342
521
  if (e.key === 'Escape')
343
522
  this.hide();
344
523
  });
345
- this.connectSSE();
524
+ if (this.cfg.frames)
525
+ this.connectFrames();
526
+ else
527
+ this.connectSSE();
346
528
  this.captureRuntimeErrors();
347
529
  }
348
530
  onClick(e) {
@@ -365,6 +547,22 @@ class KrateDev {
365
547
  this.hide();
366
548
  return;
367
549
  }
550
+ if (t.classList.contains('host')) {
551
+ this.toggleHost();
552
+ return;
553
+ }
554
+ if (t.classList.contains('mem')) {
555
+ this.toggleMemory();
556
+ return;
557
+ }
558
+ if (t.classList.contains('memclose')) {
559
+ this.toggleMemory(false);
560
+ return;
561
+ }
562
+ if (t.classList.contains('hostclose')) {
563
+ this.toggleHost(false);
564
+ return;
565
+ }
368
566
  if (t.classList.contains('reload')) {
369
567
  location.reload();
370
568
  return;
@@ -418,59 +616,193 @@ class KrateDev {
418
616
  location.reload();
419
617
  connectedOnce = true;
420
618
  });
421
- sse.addEventListener('reload', (e) => {
422
- // A rebuild without diagnostics supersedes any compile error on screen,
423
- // whichever route it touched.
424
- if (this.buildDiags.length > 0) {
425
- this.buildDiags = [];
426
- this.setStatus(true);
427
- this.render();
428
- }
429
- let cssOnly = false;
619
+ const parse = (e) => {
430
620
  try {
431
- const d = JSON.parse(e.data);
432
- cssOnly = d.cssOnly === true;
433
- if (d.pages &&
434
- Array.isArray(d.pages) &&
435
- !d.pages.some((p) => p === '/404' || p === '/500' || routeMatches(p, location.pathname, this.cfg.basePath))) {
436
- return;
437
- }
621
+ return JSON.parse(e.data);
438
622
  }
439
623
  catch {
440
- /* full reload */
441
- }
442
- if (cssOnly) {
443
- this.swapStylesheets().catch(() => location.reload());
444
- return;
445
- }
446
- location.reload();
447
- });
448
- sse.addEventListener('build-error', (e) => {
449
- try {
450
- const d = JSON.parse(e.data);
451
- this.buildDiags = Array.isArray(d.diagnostics) ? d.diagnostics : [];
624
+ return null;
452
625
  }
453
- catch {
454
- this.buildDiags = [];
626
+ };
627
+ sse.addEventListener('reload', (e) => this.onReload(parse(e)));
628
+ sse.addEventListener('build-error', (e) => this.onBuildError(parse(e)));
629
+ sse.addEventListener('client-error', (e) => this.onClientError(parse(e)));
630
+ }
631
+ /**
632
+ * Krate Native: the same events as SSE, as `{hmr: {type, ...}}` frames on a
633
+ * streaming fetch. Reconnects after the stream ends; a second "connected"
634
+ * means the shell restarted, so the page is stale.
635
+ */
636
+ connectFrames() {
637
+ let connectedOnce = false;
638
+ const run = async () => {
639
+ const res = await fetch(this.cfg.frames, { cache: 'no-store' });
640
+ if (!res.ok || !res.body)
641
+ throw new Error('hmr stream unavailable');
642
+ const reader = res.body.getReader();
643
+ let buf = new Uint8Array(0);
644
+ for (;;) {
645
+ const { done, value } = await reader.read();
646
+ if (done)
647
+ return;
648
+ const joined = new Uint8Array(buf.length + value.length);
649
+ joined.set(buf);
650
+ joined.set(value, buf.length);
651
+ const parsed = parseFrames(joined);
652
+ buf = parsed.rest;
653
+ for (const v of parsed.values) {
654
+ const m = v?.hmr;
655
+ if (!m || typeof m !== 'object')
656
+ continue;
657
+ if (m.type === 'connected') {
658
+ if (connectedOnce)
659
+ location.reload();
660
+ connectedOnce = true;
661
+ }
662
+ else if (m.type === 'reload')
663
+ this.onReload(m);
664
+ else if (m.type === 'build-error')
665
+ this.onBuildError(m);
666
+ else if (m.type === 'client-error')
667
+ this.onClientError(m);
668
+ }
455
669
  }
456
- this.setStatus(this.buildDiags.length === 0);
670
+ };
671
+ const loop = () => {
672
+ run().then(() => setTimeout(loop, 1000), () => setTimeout(loop, 1000));
673
+ };
674
+ loop();
675
+ }
676
+ onReload(d) {
677
+ // A rebuild without diagnostics supersedes any compile error on screen,
678
+ // whichever route it touched.
679
+ if (this.buildDiags.length > 0) {
680
+ this.buildDiags = [];
681
+ this.setStatus(true);
457
682
  this.render();
458
- });
459
- sse.addEventListener('client-error', (e) => {
460
- try {
461
- const d = JSON.parse(e.data);
462
- if (!d.clientError)
463
- return;
464
- const err = d.clientError;
465
- // This tab reported the error itself and already shows it.
466
- if (this.seen.has(err.message + '|' + (err.stack || '')))
467
- return;
468
- this.addRuntime('Runtime Error', err.message, err.stack);
683
+ }
684
+ let cssOnly = false;
685
+ if (d) {
686
+ cssOnly = d.cssOnly === true;
687
+ const pages = d.pages;
688
+ if (pages &&
689
+ Array.isArray(pages) &&
690
+ !pages.some((p) => p === '/404' || p === '/500' || routeMatches(p, location.pathname, this.cfg.basePath))) {
691
+ return;
469
692
  }
470
- catch {
471
- /* ignore */
693
+ }
694
+ if (cssOnly) {
695
+ this.swapStylesheets().catch(() => location.reload());
696
+ return;
697
+ }
698
+ location.reload();
699
+ }
700
+ onBuildError(d) {
701
+ this.buildDiags = d && Array.isArray(d.diagnostics) ? d.diagnostics : [];
702
+ this.setStatus(this.buildDiags.length === 0);
703
+ this.render();
704
+ }
705
+ onClientError(d) {
706
+ if (!d || !d.clientError)
707
+ return;
708
+ const err = d.clientError;
709
+ // This tab reported the error itself and already shows it.
710
+ if (this.seen.has(err.message + '|' + (err.stack || '')))
711
+ return;
712
+ this.addRuntime('Runtime Error', err.message, err.stack);
713
+ }
714
+ toggleHost(force) {
715
+ if (!this.cfg.events)
716
+ return;
717
+ if (!this.hostPanel) {
718
+ const el = document.createElement('div');
719
+ el.className = 'hostpanel';
720
+ el.hidden = true;
721
+ el.innerHTML =
722
+ '<div class="card-head"><span class="title" style="color:inherit">Host calls</span>' +
723
+ '<span class="spacer"></span><button class="btn hostclose" type="button">Close</button></div>' +
724
+ '<div class="hostrows"></div>';
725
+ this.shadow.appendChild(el);
726
+ this.hostPanel = el;
727
+ this.hostRows = el.querySelector('.hostrows');
728
+ }
729
+ const open = force ?? this.hostPanel.hidden;
730
+ this.hostPanel.hidden = !open;
731
+ if (this.hostTimer)
732
+ clearInterval(this.hostTimer);
733
+ this.hostTimer = undefined;
734
+ if (open) {
735
+ void this.pollHost();
736
+ this.hostTimer = setInterval(() => void this.pollHost(), 1000);
737
+ }
738
+ }
739
+ /** The Memory panel samples only while it is open (every 2 seconds). */
740
+ toggleMemory(force) {
741
+ if (!this.cfg.memory)
742
+ return;
743
+ if (!this.memPanel) {
744
+ const el = document.createElement('div');
745
+ el.className = 'mempanel';
746
+ el.hidden = true;
747
+ el.innerHTML =
748
+ '<div class="card-head"><span class="title" style="color:inherit">Memory</span>' +
749
+ '<span class="spacer"></span><button class="btn memclose" type="button">Close</button></div>' +
750
+ '<div class="memrows"></div>';
751
+ this.shadow.appendChild(el);
752
+ this.memPanel = el;
753
+ this.memRows = el.querySelector('.memrows');
754
+ }
755
+ const open = force ?? this.memPanel.hidden;
756
+ this.memPanel.hidden = !open;
757
+ if (this.memTimer)
758
+ clearInterval(this.memTimer);
759
+ this.memTimer = undefined;
760
+ if (open) {
761
+ void this.pollMemory();
762
+ this.memTimer = setInterval(() => void this.pollMemory(), 2000);
763
+ }
764
+ }
765
+ async pollMemory() {
766
+ let rep = null;
767
+ try {
768
+ const res = await fetch(this.cfg.memory, { cache: 'no-store' });
769
+ if (res.ok)
770
+ rep = (await res.json());
771
+ }
772
+ catch {
773
+ /* the panel is best-effort */
774
+ }
775
+ const rows = memoryRows(rep, document.getElementsByTagName('*').length, jsHeapBytes());
776
+ this.memRows.innerHTML = rows
777
+ .map(([k, v]) => '<div class="memrow"><span class="k">' + esc(k) + '</span><span class="v">' + esc(v) + '</span></div>')
778
+ .join('');
779
+ }
780
+ async pollHost() {
781
+ try {
782
+ const res = await fetch(this.cfg.events + '?since=' + this.hostSeq, { cache: 'no-store' });
783
+ if (!res.ok)
784
+ return;
785
+ const parsed = parseFrames(new Uint8Array(await res.arrayBuffer()));
786
+ const rows = this.hostRows;
787
+ const pinned = rows.scrollTop + rows.clientHeight >= rows.scrollHeight - 8;
788
+ for (const v of parsed.values) {
789
+ const ev = v?.ev;
790
+ if (!ev)
791
+ continue;
792
+ this.hostSeq = Math.max(this.hostSeq, ev.seq);
793
+ const row = document.createElement('div');
794
+ row.className = 'hostrow' + (ev.code ? ' err' : ev.kind === 'signal' ? ' sig' : '');
795
+ row.textContent = hostEventLine(ev);
796
+ rows.appendChild(row);
472
797
  }
473
- });
798
+ while (rows.childElementCount > 200)
799
+ rows.firstElementChild.remove();
800
+ if (pinned)
801
+ rows.scrollTop = rows.scrollHeight;
802
+ }
803
+ catch {
804
+ /* the panel is best-effort */
805
+ }
474
806
  }
475
807
  /**
476
808
  * Apply a CSS-only rebuild without a full reload: fetch the freshly built
@@ -524,57 +856,117 @@ class KrateDev {
524
856
  captureRuntimeErrors() {
525
857
  window.addEventListener('error', (e) => this.onError(e));
526
858
  window.addEventListener('unhandledrejection', (e) => this.onRejection(e));
859
+ // A script or stylesheet that fails to load fires on its element and does
860
+ // not bubble, so only the capture phase sees it.
861
+ window.addEventListener('error', (e) => this.onResourceError(e), true);
862
+ this.captureConsole();
527
863
  // This bundle loads after the page script, so the page's first render ran
528
864
  // before these listeners existed. The head buffers what happened until now.
529
865
  const early = window.__KRATE_EARLY_ERRORS__;
530
866
  window.__KRATE_EARLY_ERRORS__ = undefined;
531
867
  for (const e of early ?? []) {
532
- if (e.type === 'error')
868
+ if (e.type === 'console')
869
+ this.onConsole(e.message, e.stack);
870
+ else if (e.type === 'error' && e.target && e.target !== window)
871
+ this.onResourceError(e);
872
+ else if (e.type === 'error')
533
873
  this.onError(e);
534
874
  else
535
875
  this.onRejection(e);
536
876
  }
537
877
  }
878
+ captureConsole() {
879
+ const c = console;
880
+ const orig = c.error;
881
+ c.error = (...args) => {
882
+ try {
883
+ const first = args.find((a) => a instanceof Error);
884
+ this.onConsole(args.map(formatArg).join(' '), first?.stack);
885
+ }
886
+ catch {
887
+ /* never break the page's own logging */
888
+ }
889
+ return orig.apply(c, args);
890
+ };
891
+ }
892
+ onConsole(message, stack) {
893
+ this.report({ message, stack, url: location.href, kind: 'console' });
894
+ this.addRuntime('console.error', message, stack);
895
+ }
896
+ onResourceError(e) {
897
+ const t = e.target;
898
+ if (!t || t === window || !t.tagName)
899
+ return;
900
+ const src = t.src || t.href || '';
901
+ if (!src)
902
+ return;
903
+ const message = 'failed to load <' + t.tagName.toLowerCase() + '> ' + src;
904
+ this.report({ message, url: src, kind: 'resource' });
905
+ this.addRuntime('Resource Error', message);
906
+ }
538
907
  onError(e) {
539
908
  const stack = e.error?.stack || '';
540
909
  const message = e.message || 'Unknown error';
910
+ const hostStack = hostStackOf(e.error);
541
911
  this.report({
542
912
  message,
543
- stack,
913
+ stack: hostStack ? stack + '\nHost stack:\n' + hostStack : stack,
544
914
  url: e.filename,
545
915
  line: e.lineno,
546
916
  col: e.colno,
547
917
  kind: 'error',
548
918
  });
549
- this.addRuntime('Runtime Error', message, stack);
919
+ this.addRuntime('Runtime Error', message, stack, hostStack);
550
920
  }
551
921
  onRejection(e) {
552
922
  const reason = e.reason;
553
923
  const message = reason instanceof Error ? reason.message : String(reason);
554
924
  const stack = reason instanceof Error ? reason.stack : '';
555
- this.report({ message, stack, url: location.href, kind: 'unhandledrejection' });
556
- this.addRuntime('Unhandled Promise Rejection', message, stack);
925
+ const hostStack = hostStackOf(reason);
926
+ this.report({ message, stack: hostStack ? (stack || '') + '\nHost stack:\n' + hostStack : stack, url: location.href, kind: 'unhandledrejection' });
927
+ this.addRuntime('Unhandled Promise Rejection', message, stack, hostStack);
557
928
  }
558
929
  report(payload) {
559
930
  const key = payload.message + '|' + (payload.stack || '');
560
931
  if (this.seen.has(key))
561
932
  return;
562
933
  this.seen.add(key);
934
+ const win = globalThis.__KRATE_WINDOW__;
935
+ if (typeof win === 'string' && win)
936
+ payload.window = win;
937
+ if (!payload.stack || payload.stack.indexOf('.js') === -1) {
938
+ this.send(payload);
939
+ return;
940
+ }
941
+ // Map the stack to the sources before it reaches the terminal, but never
942
+ // hold the report back for long: the source maps are best-effort.
943
+ const raw = payload.stack;
944
+ Promise.race([symbolicateStack(raw), new Promise((r) => setTimeout(() => r(raw), 1500))])
945
+ .catch(() => raw)
946
+ .then((stack) => this.send({ ...payload, stack }));
947
+ }
948
+ send(payload) {
949
+ const body = JSON.stringify(payload);
950
+ // sendBeacon throws on the custom scheme of a native webview (WebKitGTK),
951
+ // so a failed or absent beacon falls back to fetch.
563
952
  try {
564
- const body = JSON.stringify(payload);
565
- if (navigator.sendBeacon) {
566
- navigator.sendBeacon(this.cfg.errors, new Blob([body], { type: 'application/json' }));
567
- }
568
- else {
569
- fetch(this.cfg.errors, { method: 'POST', body, headers: { 'Content-Type': 'application/json' }, keepalive: true }).catch(() => { });
953
+ if (!this.cfg.frames && navigator.sendBeacon) {
954
+ if (navigator.sendBeacon(this.cfg.errors, new Blob([body], { type: 'application/json' })))
955
+ return;
570
956
  }
571
957
  }
958
+ catch {
959
+ /* fall through to fetch */
960
+ }
961
+ try {
962
+ fetch(this.cfg.errors, { method: 'POST', body, headers: { 'Content-Type': 'application/json' }, keepalive: true }).catch(() => { });
963
+ }
572
964
  catch {
573
965
  /* reporting is best-effort */
574
966
  }
575
967
  }
576
- addRuntime(title, message, stack) {
577
- const entry = { title, message, stack };
968
+ addRuntime(title, message, stack, hostStack) {
969
+ const entry = { title, message, stack, hostStack };
578
970
  this.runtimeErrors.push(entry);
579
971
  this.setStatus(false);
580
972
  this.render();
@@ -615,7 +1007,8 @@ class KrateDev {
615
1007
  return '<div class="diag">' + actions + '<div class="msg">' + esc(d.message) + '</div>' + this.frameHTML(d) + hint + '</div>';
616
1008
  }
617
1009
  runtimeHTML(r) {
618
- const stack = r.stack ? '<div class="stack">' + esc(r.stack) + '</div>' : '';
1010
+ const host = r.hostStack ? '<div class="stack">Host stack:\n' + esc(r.hostStack) + '</div>' : '';
1011
+ const stack = host + (r.stack ? '<div class="stack">' + esc(r.stack) + '</div>' : '');
619
1012
  return '<div class="diag"><div class="msg">' + esc(r.message) + '</div>' + stack + '</div>';
620
1013
  }
621
1014
  render() {