@krate/runtime 0.5.0-beta.3 → 0.5.0-rc.10

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 (219) hide show
  1. package/dist/action-context.js +1 -1
  2. package/dist/actions.d.ts +7 -0
  3. package/dist/actions.js +34 -10
  4. package/dist/after.d.ts +28 -0
  5. package/dist/after.js +48 -0
  6. package/dist/assets-static.d.ts +10 -1
  7. package/dist/assets-static.js +10 -2
  8. package/dist/base-path.d.ts +7 -0
  9. package/dist/base-path.js +20 -0
  10. package/dist/boundary.js +1 -1
  11. package/dist/builtin-tags.d.ts +12 -0
  12. package/dist/builtin-tags.js +42 -0
  13. package/dist/cache-adapter.js +1 -1
  14. package/dist/cache-scope.d.ts +8 -0
  15. package/dist/cache-scope.js +14 -1
  16. package/dist/cloudflare-workers.d.ts +2 -0
  17. package/dist/cloudflare-workers.js +27 -0
  18. package/dist/context.d.ts +5 -0
  19. package/dist/context.js +28 -17
  20. package/dist/dev-overlay.d.ts +54 -3
  21. package/dist/dev-overlay.js +496 -91
  22. package/dist/dom.d.ts +4 -0
  23. package/dist/dom.js +62 -16
  24. package/dist/effects.js +43 -10
  25. package/dist/events.d.ts +2 -0
  26. package/dist/events.js +18 -0
  27. package/dist/flight-props.d.ts +7 -0
  28. package/dist/flight-props.js +105 -0
  29. package/dist/handler-html.js +4 -4
  30. package/dist/handler-routing.d.ts +2 -23
  31. package/dist/handler-routing.js +9 -190
  32. package/dist/handler-segments.d.ts +6 -0
  33. package/dist/handler-segments.js +18 -4
  34. package/dist/head-tags.d.ts +9 -0
  35. package/dist/head-tags.js +93 -6
  36. package/dist/highlight-bind.js +1 -1
  37. package/dist/highlight.d.ts +3 -2
  38. package/dist/highlight.js +17 -12
  39. package/dist/hints.d.ts +25 -2
  40. package/dist/hints.js +147 -74
  41. package/dist/index.d.ts +2 -0
  42. package/dist/index.js +3 -0
  43. package/dist/island-swap.d.ts +47 -0
  44. package/dist/island-swap.js +635 -0
  45. package/dist/jsx-dev-runtime.d.ts +1 -1
  46. package/dist/jsx-types.d.ts +99 -3
  47. package/dist/krate-core.js +1 -1
  48. package/dist/krate-dev.js +407 -80
  49. package/dist/krate-f-actions.js +1 -1
  50. package/dist/krate-f-classes.js +1 -1
  51. package/dist/krate-f-highlight.js +1 -1
  52. package/dist/krate-f-list.js +1 -1
  53. package/dist/krate-f-navigation.js +1 -1
  54. package/dist/krate-f-router-lite.js +1 -1
  55. package/dist/krate-f-router.js +1 -1
  56. package/dist/krate-features.json +455 -0
  57. package/dist/krate-hydrate-lite.js +5 -5
  58. package/dist/krate-hydrate.js +5 -5
  59. package/dist/krate-island-swap.js +1 -0
  60. package/dist/krate-runtime.js +5 -5
  61. package/dist/krate-suspense.js +1 -1
  62. package/dist/list.d.ts +14 -4
  63. package/dist/list.js +30 -23
  64. package/dist/metadata.js +5 -2
  65. package/dist/navigation-react.d.ts +13 -0
  66. package/dist/navigation-react.js +86 -0
  67. package/dist/navigation.d.ts +19 -0
  68. package/dist/navigation.js +35 -0
  69. package/dist/node-server.js +3 -3
  70. package/dist/og.js +1 -1
  71. package/dist/platform.d.ts +52 -0
  72. package/dist/platform.js +57 -0
  73. package/dist/react-compat.d.ts +39 -0
  74. package/dist/react-compat.js +359 -0
  75. package/dist/react-server.d.ts +63 -0
  76. package/dist/react-server.js +125 -0
  77. package/dist/region-wire.d.ts +10 -0
  78. package/dist/region-wire.js +154 -0
  79. package/dist/request-context.js +1 -1
  80. package/dist/request-extras.d.ts +4 -0
  81. package/dist/request-extras.js +51 -0
  82. package/dist/resp.js +1 -1
  83. package/dist/route-source.d.ts +39 -0
  84. package/dist/route-source.js +532 -0
  85. package/dist/router-lite.js +3 -9
  86. package/dist/router.d.ts +1 -1
  87. package/dist/router.js +675 -100
  88. package/dist/server-handler.d.ts +69 -1
  89. package/dist/server-handler.js +515 -96
  90. package/dist/server-renderer.js +16 -7
  91. package/dist/server.d.ts +73 -16
  92. package/dist/server.js +619 -102
  93. package/dist/sha256.js +9 -9
  94. package/dist/signal.js +47 -20
  95. package/dist/site-config.d.ts +15 -0
  96. package/dist/site-config.js +28 -0
  97. package/dist/slot.d.ts +12 -0
  98. package/dist/slot.js +23 -0
  99. package/dist/ssr-core.d.ts +2 -0
  100. package/dist/ssr-core.js +12 -4
  101. package/dist/suspense.js +34 -2
  102. package/dist/testing.d.ts +62 -0
  103. package/dist/testing.js +90 -0
  104. package/dist/use-id.js +1 -1
  105. package/package.json +28 -3
  106. package/dist/action-context.test.d.ts +0 -1
  107. package/dist/action-context.test.js +0 -72
  108. package/dist/actions.test.d.ts +0 -1
  109. package/dist/actions.test.js +0 -477
  110. package/dist/cache-adapter.test.d.ts +0 -1
  111. package/dist/cache-adapter.test.js +0 -244
  112. package/dist/cache.test.d.ts +0 -1
  113. package/dist/cache.test.js +0 -233
  114. package/dist/class-component.test.d.ts +0 -1
  115. package/dist/class-component.test.js +0 -462
  116. package/dist/class-helpers.test.d.ts +0 -1
  117. package/dist/class-helpers.test.js +0 -169
  118. package/dist/context.test.d.ts +0 -1
  119. package/dist/context.test.js +0 -57
  120. package/dist/derived.test.d.ts +0 -1
  121. package/dist/derived.test.js +0 -140
  122. package/dist/dev-overlay.test.d.ts +0 -1
  123. package/dist/dev-overlay.test.js +0 -152
  124. package/dist/discrete.test.d.ts +0 -1
  125. package/dist/discrete.test.js +0 -100
  126. package/dist/dom.test.d.ts +0 -1
  127. package/dist/dom.test.js +0 -31
  128. package/dist/effect-errors.test.d.ts +0 -1
  129. package/dist/effect-errors.test.js +0 -163
  130. package/dist/effects.test.d.ts +0 -1
  131. package/dist/effects.test.js +0 -485
  132. package/dist/events.test.d.ts +0 -1
  133. package/dist/events.test.js +0 -447
  134. package/dist/handler-html.test.d.ts +0 -1
  135. package/dist/handler-html.test.js +0 -256
  136. package/dist/handler-routing.test.d.ts +0 -1
  137. package/dist/handler-routing.test.js +0 -99
  138. package/dist/handler-segments.test.d.ts +0 -1
  139. package/dist/handler-segments.test.js +0 -217
  140. package/dist/head-tags.test.d.ts +0 -1
  141. package/dist/head-tags.test.js +0 -131
  142. package/dist/highlight-bind.test.d.ts +0 -1
  143. package/dist/highlight-bind.test.js +0 -124
  144. package/dist/highlight.test.d.ts +0 -1
  145. package/dist/highlight.test.js +0 -56
  146. package/dist/lanes.test.d.ts +0 -1
  147. package/dist/lanes.test.js +0 -59
  148. package/dist/list.test.d.ts +0 -1
  149. package/dist/list.test.js +0 -344
  150. package/dist/metadata.test.d.ts +0 -1
  151. package/dist/metadata.test.js +0 -167
  152. package/dist/navigation.test.d.ts +0 -1
  153. package/dist/navigation.test.js +0 -130
  154. package/dist/node-server.test.d.ts +0 -1
  155. package/dist/node-server.test.js +0 -492
  156. package/dist/optimistic-lanes.test.d.ts +0 -1
  157. package/dist/optimistic-lanes.test.js +0 -45
  158. package/dist/patterns.test.d.ts +0 -1
  159. package/dist/patterns.test.js +0 -98
  160. package/dist/portal.test.d.ts +0 -1
  161. package/dist/portal.test.js +0 -99
  162. package/dist/react-effects.test.d.ts +0 -1
  163. package/dist/react-effects.test.js +0 -96
  164. package/dist/react-suspense.test.d.ts +0 -1
  165. package/dist/react-suspense.test.js +0 -194
  166. package/dist/react.test.d.ts +0 -1
  167. package/dist/react.test.js +0 -60
  168. package/dist/react19.test.d.ts +0 -1
  169. package/dist/react19.test.js +0 -176
  170. package/dist/reactivity-core.test.d.ts +0 -1
  171. package/dist/reactivity-core.test.js +0 -152
  172. package/dist/reconcile.test.d.ts +0 -1
  173. package/dist/reconcile.test.js +0 -110
  174. package/dist/refs.test.d.ts +0 -1
  175. package/dist/refs.test.js +0 -257
  176. package/dist/router-layout.test.d.ts +0 -1
  177. package/dist/router-layout.test.js +0 -249
  178. package/dist/router-nav.test.d.ts +0 -1
  179. package/dist/router-nav.test.js +0 -464
  180. package/dist/router-slots.test.d.ts +0 -1
  181. package/dist/router-slots.test.js +0 -144
  182. package/dist/router-speculation.test.d.ts +0 -1
  183. package/dist/router-speculation.test.js +0 -25
  184. package/dist/router-styles.test.d.ts +0 -1
  185. package/dist/router-styles.test.js +0 -98
  186. package/dist/router.test.d.ts +0 -1
  187. package/dist/router.test.js +0 -36
  188. package/dist/server-async.test.d.ts +0 -1
  189. package/dist/server-async.test.js +0 -216
  190. package/dist/server-handler.test.d.ts +0 -1
  191. package/dist/server-handler.test.js +0 -535
  192. package/dist/server-highlight.test.d.ts +0 -1
  193. package/dist/server-highlight.test.js +0 -32
  194. package/dist/server-renderer.test.d.ts +0 -1
  195. package/dist/server-renderer.test.js +0 -266
  196. package/dist/server.test.d.ts +0 -1
  197. package/dist/server.test.js +0 -88
  198. package/dist/sha256.test.d.ts +0 -1
  199. package/dist/sha256.test.js +0 -13
  200. package/dist/signal-lanes.test.d.ts +0 -1
  201. package/dist/signal-lanes.test.js +0 -32
  202. package/dist/signal.test.d.ts +0 -1
  203. package/dist/signal.test.js +0 -68
  204. package/dist/slots.test.d.ts +0 -1
  205. package/dist/slots.test.js +0 -169
  206. package/dist/snapshots.test.d.ts +0 -1
  207. package/dist/snapshots.test.js +0 -208
  208. package/dist/ssr-core-behavior.test.d.ts +0 -1
  209. package/dist/ssr-core-behavior.test.js +0 -620
  210. package/dist/ssr-core.test.d.ts +0 -1
  211. package/dist/ssr-core.test.js +0 -324
  212. package/dist/static-memory.test.d.ts +0 -1
  213. package/dist/static-memory.test.js +0 -26
  214. package/dist/storage.test.d.ts +0 -1
  215. package/dist/storage.test.js +0 -46
  216. package/dist/suspense-actions.test.d.ts +0 -1
  217. package/dist/suspense-actions.test.js +0 -72
  218. package/dist/suspense.test.d.ts +0 -1
  219. package/dist/suspense.test.js +0 -518
@@ -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,24 +145,38 @@ 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];
138
159
  }
139
- if (!best)
140
- best = segs[0];
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;
171
+ }
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
  }
144
177
  /** Rewrites each mappable frame of a stack trace to its original location. */
145
178
  export async function symbolicateStack(stack) {
146
- if (!stack || stack.indexOf('.js') === -1)
179
+ if (!stack || !stack.includes('.js'))
147
180
  return stack;
148
181
  const lines = stack.split('\n');
149
182
  const out = await Promise.all(lines.map(async (line) => {
@@ -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
@@ -522,47 +854,119 @@ class KrateDev {
522
854
  }
523
855
  }
524
856
  captureRuntimeErrors() {
525
- window.addEventListener('error', (e) => {
526
- const stack = e.error?.stack || '';
527
- const message = e.message || 'Unknown error';
528
- this.report({
529
- message,
530
- stack,
531
- url: e.filename,
532
- line: e.lineno,
533
- col: e.colno,
534
- kind: 'error',
535
- });
536
- this.addRuntime('Runtime Error', message, stack);
537
- });
538
- window.addEventListener('unhandledrejection', (e) => {
539
- const reason = e.reason;
540
- const message = reason instanceof Error ? reason.message : String(reason);
541
- const stack = reason instanceof Error ? reason.stack : '';
542
- this.report({ message, stack, url: location.href, kind: 'unhandledrejection' });
543
- this.addRuntime('Unhandled Promise Rejection', message, stack);
857
+ window.addEventListener('error', (e) => this.onError(e));
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();
863
+ // This bundle loads after the page script, so the page's first render ran
864
+ // before these listeners existed. The head buffers what happened until now.
865
+ const early = window.__KRATE_EARLY_ERRORS__;
866
+ window.__KRATE_EARLY_ERRORS__ = undefined;
867
+ for (const e of early ?? []) {
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')
873
+ this.onError(e);
874
+ else
875
+ this.onRejection(e);
876
+ }
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
+ }
907
+ onError(e) {
908
+ const stack = e.error?.stack || '';
909
+ const message = e.message || 'Unknown error';
910
+ const hostStack = hostStackOf(e.error);
911
+ this.report({
912
+ message,
913
+ stack: hostStack ? stack + '\nHost stack:\n' + hostStack : stack,
914
+ url: e.filename,
915
+ line: e.lineno,
916
+ col: e.colno,
917
+ kind: 'error',
544
918
  });
919
+ this.addRuntime('Runtime Error', message, stack, hostStack);
920
+ }
921
+ onRejection(e) {
922
+ const reason = e.reason;
923
+ const message = reason instanceof Error ? reason.message : String(reason);
924
+ const stack = reason instanceof Error ? reason.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);
545
928
  }
546
929
  report(payload) {
547
930
  const key = payload.message + '|' + (payload.stack || '');
548
931
  if (this.seen.has(key))
549
932
  return;
550
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.includes('.js')) {
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.
551
952
  try {
552
- const body = JSON.stringify(payload);
553
- if (navigator.sendBeacon) {
554
- navigator.sendBeacon(this.cfg.errors, new Blob([body], { type: 'application/json' }));
555
- }
556
- else {
557
- 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;
558
956
  }
559
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
+ }
560
964
  catch {
561
965
  /* reporting is best-effort */
562
966
  }
563
967
  }
564
- addRuntime(title, message, stack) {
565
- const entry = { title, message, stack };
968
+ addRuntime(title, message, stack, hostStack) {
969
+ const entry = { title, message, stack, hostStack };
566
970
  this.runtimeErrors.push(entry);
567
971
  this.setStatus(false);
568
972
  this.render();
@@ -603,7 +1007,8 @@ class KrateDev {
603
1007
  return '<div class="diag">' + actions + '<div class="msg">' + esc(d.message) + '</div>' + this.frameHTML(d) + hint + '</div>';
604
1008
  }
605
1009
  runtimeHTML(r) {
606
- 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>' : '');
607
1012
  return '<div class="diag"><div class="msg">' + esc(r.message) + '</div>' + stack + '</div>';
608
1013
  }
609
1014
  render() {