@krate/runtime 0.5.0-rc.13 → 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 (83) hide show
  1. package/dist/action-context.d.ts +2 -0
  2. package/dist/action-context.js +12 -1
  3. package/dist/action-seal.d.ts +5 -0
  4. package/dist/action-seal.js +105 -0
  5. package/dist/actions.js +7 -1
  6. package/dist/cache-scope.d.ts +2 -0
  7. package/dist/dev/api.d.ts +93 -0
  8. package/dist/dev/api.js +2 -0
  9. package/dist/dev/app.d.ts +165 -0
  10. package/dist/dev/app.js +1204 -0
  11. package/dist/dev/commands.d.ts +49 -0
  12. package/dist/dev/commands.js +114 -0
  13. package/dist/dev/highlight.d.ts +4 -0
  14. package/dist/dev/highlight.js +126 -0
  15. package/dist/dev/icons.d.ts +4 -0
  16. package/dist/dev/icons.js +57 -0
  17. package/dist/dev/inspect.d.ts +55 -0
  18. package/dist/dev/inspect.js +256 -0
  19. package/dist/dev/inspector.d.ts +39 -0
  20. package/dist/dev/inspector.js +348 -0
  21. package/dist/dev/issues.d.ts +83 -0
  22. package/dist/dev/issues.js +166 -0
  23. package/dist/dev/modal.d.ts +16 -0
  24. package/dist/dev/modal.js +836 -0
  25. package/dist/dev/native.d.ts +53 -0
  26. package/dist/dev/native.js +95 -0
  27. package/dist/dev/palette.d.ts +9 -0
  28. package/dist/dev/palette.js +250 -0
  29. package/dist/dev/panel.d.ts +31 -0
  30. package/dist/dev/panel.js +848 -0
  31. package/dist/dev/requests.d.ts +36 -0
  32. package/dist/dev/requests.js +150 -0
  33. package/dist/dev/settings.d.ts +32 -0
  34. package/dist/dev/settings.js +78 -0
  35. package/dist/dev/sourcemap.d.ts +22 -0
  36. package/dist/dev/sourcemap.js +148 -0
  37. package/dist/dev/stack.d.ts +38 -0
  38. package/dist/dev/stack.js +115 -0
  39. package/dist/dev/styles.d.ts +1 -0
  40. package/dist/dev/styles.js +424 -0
  41. package/dist/dev/util.d.ts +63 -0
  42. package/dist/dev/util.js +190 -0
  43. package/dist/dev-overlay.d.ts +9 -83
  44. package/dist/dev-overlay.js +17 -1038
  45. package/dist/flight-props.d.ts +2 -0
  46. package/dist/flight-props.js +12 -1
  47. package/dist/handler-routing.js +7 -1
  48. package/dist/island-swap.js +10 -1
  49. package/dist/krate-core.js +1 -1
  50. package/dist/krate-dev.js +441 -871
  51. package/dist/krate-f-actions.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.js +1 -1
  55. package/dist/krate-hydrate-lite.js +5 -5
  56. package/dist/krate-hydrate.js +5 -5
  57. package/dist/krate-island-swap.js +1 -1
  58. package/dist/krate-runtime.js +5 -5
  59. package/dist/list.js +23 -1
  60. package/dist/metadata.js +23 -12
  61. package/dist/navigation-server.d.ts +1 -2
  62. package/dist/navigation-server.js +1 -2
  63. package/dist/navigation.d.ts +1 -1
  64. package/dist/navigation.js +7 -2
  65. package/dist/process-guard.d.ts +23 -0
  66. package/dist/process-guard.js +45 -0
  67. package/dist/react-types.d.ts +29 -0
  68. package/dist/react-types.js +1 -0
  69. package/dist/react.d.ts +2 -0
  70. package/dist/react.js +3 -0
  71. package/dist/request-context.d.ts +15 -0
  72. package/dist/request-context.js +41 -0
  73. package/dist/router.js +17 -0
  74. package/dist/server-handler.d.ts +4 -0
  75. package/dist/server-handler.js +43 -8
  76. package/dist/server-renderer.js +94 -2
  77. package/dist/server.d.ts +1 -1
  78. package/dist/server.js +57 -11
  79. package/dist/signal.d.ts +8 -0
  80. package/dist/signal.js +4 -0
  81. package/dist/ssr-core.d.ts +5 -0
  82. package/dist/ssr-core.js +49 -7
  83. package/package.json +5 -1
@@ -0,0 +1,36 @@
1
+ export interface FailedRequest {
2
+ method: string;
3
+ url: string;
4
+ /** HTTP status, 0 for a network error. */
5
+ status: number;
6
+ /** The network error's message, when the request did not complete. */
7
+ error?: string;
8
+ /** Duration in ms. */
9
+ ms: number;
10
+ /** When the request ended (Date.now()). */
11
+ t: number;
12
+ }
13
+ export declare const REQUEST_RING = 50;
14
+ /**
15
+ * fetch without the capture: the overlay's own requests (source maps, code
16
+ * frames, a stylesheet swap) are not the page's and must not be recorded.
17
+ */
18
+ export declare function rawFetch(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
19
+ /** How far before an error a failed request still counts as near it. */
20
+ export declare const NEAR_BEFORE_MS = 15000;
21
+ export declare class RequestLog {
22
+ list: FailedRequest[];
23
+ onChange?: () => void;
24
+ add(r: FailedRequest): void;
25
+ /** The failed requests that ended shortly before (or just after) time t, newest last. */
26
+ near(t: number): FailedRequest[];
27
+ }
28
+ /** True for the overlay's own requests and other dev server internals. */
29
+ export declare function isInternalURL(url: string): boolean;
30
+ /** A request URL shown relative to the page origin when it is same-origin. */
31
+ export declare function displayURL(url: string): string;
32
+ /**
33
+ * Wraps fetch and XMLHttpRequest so failed requests (a status of 400 or more,
34
+ * or a network error) land in log. Returns the function that undoes it.
35
+ */
36
+ export declare function captureRequests(log: RequestLog, g?: any): () => void;
@@ -0,0 +1,150 @@
1
+ // Failed network requests of the page (fetch and XMLHttpRequest), kept in a
2
+ // small ring so a runtime error can show the requests around it.
3
+ export const REQUEST_RING = 50;
4
+ let unwrapped;
5
+ /**
6
+ * fetch without the capture: the overlay's own requests (source maps, code
7
+ * frames, a stylesheet swap) are not the page's and must not be recorded.
8
+ */
9
+ export function rawFetch(input, init) {
10
+ return (unwrapped || fetch)(input, init);
11
+ }
12
+ /** How far before an error a failed request still counts as near it. */
13
+ export const NEAR_BEFORE_MS = 15000;
14
+ const NEAR_AFTER_MS = 2000;
15
+ export class RequestLog {
16
+ constructor() {
17
+ this.list = [];
18
+ }
19
+ add(r) {
20
+ this.list.push(r);
21
+ if (this.list.length > REQUEST_RING)
22
+ this.list.shift();
23
+ this.onChange?.();
24
+ }
25
+ /** The failed requests that ended shortly before (or just after) time t, newest last. */
26
+ near(t) {
27
+ return this.list.filter((r) => r.t >= t - NEAR_BEFORE_MS && r.t <= t + NEAR_AFTER_MS);
28
+ }
29
+ }
30
+ /** True for the overlay's own requests and other dev server internals. */
31
+ export function isInternalURL(url) {
32
+ try {
33
+ const u = new URL(url, typeof location !== 'undefined' ? location.href : 'http://localhost/');
34
+ return /^\/__krate\//.test(u.pathname);
35
+ }
36
+ catch {
37
+ return false;
38
+ }
39
+ }
40
+ function urlOf(input) {
41
+ if (typeof input === 'string')
42
+ return input;
43
+ if (input && typeof input === 'object') {
44
+ const o = input;
45
+ if (typeof o.url === 'string')
46
+ return o.url;
47
+ if (typeof o.href === 'string')
48
+ return o.href;
49
+ }
50
+ return String(input);
51
+ }
52
+ /** A request URL shown relative to the page origin when it is same-origin. */
53
+ export function displayURL(url) {
54
+ try {
55
+ const u = new URL(url, location.href);
56
+ return u.origin === location.origin ? u.pathname + u.search : u.href;
57
+ }
58
+ catch {
59
+ return url;
60
+ }
61
+ }
62
+ /**
63
+ * Wraps fetch and XMLHttpRequest so failed requests (a status of 400 or more,
64
+ * or a network error) land in log. Returns the function that undoes it.
65
+ */
66
+ export function captureRequests(log, g = globalThis) {
67
+ const undo = [];
68
+ const now = () => (typeof performance !== 'undefined' ? performance.now() : Date.now());
69
+ const origFetch = g.fetch;
70
+ if (typeof origFetch === 'function') {
71
+ unwrapped = origFetch.bind(g);
72
+ const wrapped = function (input, init) {
73
+ const url = urlOf(input);
74
+ const method = String(init?.method || (input && typeof input === 'object' && input.method) || 'GET').toUpperCase();
75
+ const start = now();
76
+ const p = origFetch.apply(this, arguments);
77
+ if (isInternalURL(url))
78
+ return p;
79
+ return p.then((res) => {
80
+ try {
81
+ if (res && res.status >= 400)
82
+ log.add({ method, url, status: res.status, ms: Math.round(now() - start), t: Date.now() });
83
+ }
84
+ catch {
85
+ /* never break the page's request */
86
+ }
87
+ return res;
88
+ }, (err) => {
89
+ try {
90
+ const aborted = err && typeof err === 'object' && err.name === 'AbortError';
91
+ if (!aborted)
92
+ log.add({ method, url, status: 0, error: err instanceof Error ? err.message : String(err), ms: Math.round(now() - start), t: Date.now() });
93
+ }
94
+ catch {
95
+ /* never break the page's request */
96
+ }
97
+ throw err;
98
+ });
99
+ };
100
+ g.fetch = wrapped;
101
+ undo.push(() => {
102
+ if (g.fetch === wrapped)
103
+ g.fetch = origFetch;
104
+ unwrapped = undefined;
105
+ });
106
+ }
107
+ const XHR = g.XMLHttpRequest;
108
+ if (typeof XHR === 'function' && XHR.prototype) {
109
+ const proto = XHR.prototype;
110
+ const open = proto.open;
111
+ const send = proto.send;
112
+ proto.open = function (method, url) {
113
+ this.__kdReq = { method: String(method || 'GET').toUpperCase(), url: urlOf(url) };
114
+ return open.apply(this, arguments);
115
+ };
116
+ proto.send = function () {
117
+ const req = this.__kdReq;
118
+ if (req && !isInternalURL(req.url)) {
119
+ const start = now();
120
+ let done = false;
121
+ const finish = (error) => {
122
+ if (done)
123
+ return;
124
+ done = true;
125
+ try {
126
+ const status = error ? 0 : Number(this.status) || 0;
127
+ if (error || status >= 400 || status === 0) {
128
+ log.add({ method: req.method, url: req.url, status, error: error || (status === 0 ? 'network error' : undefined), ms: Math.round(now() - start), t: Date.now() });
129
+ }
130
+ }
131
+ catch {
132
+ /* never break the page's request */
133
+ }
134
+ };
135
+ this.addEventListener('load', () => finish());
136
+ this.addEventListener('error', () => finish('network error'));
137
+ this.addEventListener('timeout', () => finish('timed out'));
138
+ }
139
+ return send.apply(this, arguments);
140
+ };
141
+ undo.push(() => {
142
+ proto.open = open;
143
+ proto.send = send;
144
+ });
145
+ }
146
+ return () => {
147
+ for (const u of undo.splice(0))
148
+ u();
149
+ };
150
+ }
@@ -0,0 +1,32 @@
1
+ export type Corner = 'bl' | 'br' | 'tl' | 'tr';
2
+ export type Theme = 'system' | 'dark' | 'light';
3
+ export interface Settings {
4
+ corner: Corner;
5
+ theme: Theme;
6
+ /** Allowlisted editor id passed to /__krate/open; "" uses devServer.editor. */
7
+ editor: string;
8
+ openOnRuntime: boolean;
9
+ consoleIssues: boolean;
10
+ /** List build warnings (KR5002, ...) with the issues. */
11
+ showWarnings: boolean;
12
+ collapsed: boolean;
13
+ }
14
+ export declare const SETTINGS_KEY = "krate:dev-overlay";
15
+ export declare const DEFAULT_SETTINGS: Settings;
16
+ export declare function loadSettings(): Settings;
17
+ export declare function saveSettings(s: Settings): void;
18
+ /** The nearest corner of the viewport to a point. */
19
+ export declare function nearestCorner(x: number, y: number, w: number, h: number): Corner;
20
+ export type Shortcut = 'menu' | 'inspect' | 'issues' | 'hide';
21
+ /**
22
+ * The overlay shortcut of a key event: Alt with K, I, E or the period key,
23
+ * matched by physical key (`code`) so it works on every layout and with
24
+ * macOS Option producing other characters.
25
+ */
26
+ export declare function shortcutOf(e: KeyboardEvent): Shortcut | null;
27
+ /** The label of one key: an icon for macOS modifiers, text elsewhere. */
28
+ export declare function keyLabel(k: string, mac?: boolean): string;
29
+ /** A key combination in one kbd chip ("Alt K" / option icon + K). */
30
+ export declare function kbd(keys: string[], mac?: boolean): string;
31
+ /** A key combination as separate kbd chips, for the shortcuts list. */
32
+ export declare function kbds(keys: string[], mac?: boolean): string;
@@ -0,0 +1,78 @@
1
+ // Per-browser overlay preferences, kept in localStorage.
2
+ import { esc, isMac, store } from './util.js';
3
+ import { icon } from './icons.js';
4
+ export const SETTINGS_KEY = 'krate:dev-overlay';
5
+ export const DEFAULT_SETTINGS = {
6
+ corner: 'bl',
7
+ theme: 'system',
8
+ editor: '',
9
+ openOnRuntime: true,
10
+ consoleIssues: true,
11
+ showWarnings: true,
12
+ collapsed: false,
13
+ };
14
+ const CORNERS = ['bl', 'br', 'tl', 'tr'];
15
+ const THEMES = ['system', 'dark', 'light'];
16
+ export function loadSettings() {
17
+ const s = { ...DEFAULT_SETTINGS };
18
+ try {
19
+ const raw = JSON.parse(store.get(SETTINGS_KEY) || '{}');
20
+ if (CORNERS.includes(raw.corner))
21
+ s.corner = raw.corner;
22
+ if (THEMES.includes(raw.theme))
23
+ s.theme = raw.theme;
24
+ if (typeof raw.editor === 'string' && /^[\w.-]{0,40}$/.test(raw.editor))
25
+ s.editor = raw.editor;
26
+ for (const k of ['openOnRuntime', 'consoleIssues', 'showWarnings', 'collapsed']) {
27
+ if (typeof raw[k] === 'boolean')
28
+ s[k] = raw[k];
29
+ }
30
+ }
31
+ catch {
32
+ /* a corrupt entry falls back to the defaults */
33
+ }
34
+ return s;
35
+ }
36
+ export function saveSettings(s) {
37
+ store.set(SETTINGS_KEY, JSON.stringify(s));
38
+ }
39
+ /** The nearest corner of the viewport to a point. */
40
+ export function nearestCorner(x, y, w, h) {
41
+ return ((y < h / 2 ? 't' : 'b') + (x < w / 2 ? 'l' : 'r'));
42
+ }
43
+ /**
44
+ * The overlay shortcut of a key event: Alt with K, I, E or the period key,
45
+ * matched by physical key (`code`) so it works on every layout and with
46
+ * macOS Option producing other characters.
47
+ */
48
+ export function shortcutOf(e) {
49
+ if (!e.altKey || e.ctrlKey || e.metaKey || e.shiftKey)
50
+ return null;
51
+ switch (e.code) {
52
+ case 'KeyK':
53
+ return 'menu';
54
+ case 'KeyI':
55
+ return 'inspect';
56
+ case 'KeyE':
57
+ return 'issues';
58
+ case 'Period':
59
+ return 'hide';
60
+ }
61
+ return null;
62
+ }
63
+ const MAC_KEYS = { Alt: 'option', Mod: 'command', Shift: 'arrow-big-up', Enter: 'corner-down-left' };
64
+ const PC_KEYS = { Alt: 'Alt', Mod: 'Ctrl', Shift: 'Shift', Enter: 'Enter' };
65
+ /** The label of one key: an icon for macOS modifiers, text elsewhere. */
66
+ export function keyLabel(k, mac = isMac()) {
67
+ if (mac && MAC_KEYS[k])
68
+ return icon(MAC_KEYS[k]);
69
+ return esc(PC_KEYS[k] || k);
70
+ }
71
+ /** A key combination in one kbd chip ("Alt K" / option icon + K). */
72
+ export function kbd(keys, mac = isMac()) {
73
+ return '<span class="kbd">' + keys.map((k) => keyLabel(k, mac)).join(mac ? '' : ' ') + '</span>';
74
+ }
75
+ /** A key combination as separate kbd chips, for the shortcuts list. */
76
+ export function kbds(keys, mac = isMac()) {
77
+ return keys.map((k) => '<span class="kbd">' + keyLabel(k, mac) + '</span>').join('');
78
+ }
@@ -0,0 +1,22 @@
1
+ interface MapSegment {
2
+ genCol: number;
3
+ src: number;
4
+ srcLine: number;
5
+ srcCol: number;
6
+ }
7
+ /** Decodes a Base64 VLQ mapping segment into a delta array. */
8
+ export declare function decodeVLQ(str: string): number[];
9
+ /** Decodes a v3 `mappings` string into per-generated-line segments. */
10
+ export declare function decodeMappings(mappings: string): MapSegment[][];
11
+ interface StackFrame {
12
+ prefix: string;
13
+ url: string;
14
+ line: number;
15
+ col: number;
16
+ suffix: string;
17
+ }
18
+ /** Parses a V8/Firefox stack line into its script location, if present. */
19
+ export declare function parseStackFrame(line: string): StackFrame | null;
20
+ /** Rewrites each mappable frame of a stack trace to its original location. */
21
+ export declare function symbolicateStack(stack: string): Promise<string>;
22
+ export {};
@@ -0,0 +1,148 @@
1
+ // Source-map symbolication. When the build enables source maps the overlay
2
+ // decodes them so runtime stack traces point at real source locations instead
3
+ // of bundle offsets. Fetches fail silently when maps are absent.
4
+ import { rawFetch } from './requests.js';
5
+ const B64_VLQ = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
6
+ /** Decodes a Base64 VLQ mapping segment into a delta array. */
7
+ export function decodeVLQ(str) {
8
+ const out = [];
9
+ let shift = 0;
10
+ let value = 0;
11
+ for (let i = 0; i < str.length; i++) {
12
+ const digit = B64_VLQ.indexOf(str[i]);
13
+ if (digit === -1)
14
+ continue;
15
+ const cont = (digit & 32) !== 0;
16
+ value += (digit & 31) << shift;
17
+ if (cont) {
18
+ shift += 5;
19
+ continue;
20
+ }
21
+ const neg = (value & 1) === 1;
22
+ value >>= 1;
23
+ out.push(neg ? -value : value);
24
+ value = 0;
25
+ shift = 0;
26
+ }
27
+ return out;
28
+ }
29
+ /** Decodes a v3 `mappings` string into per-generated-line segments. */
30
+ export function decodeMappings(mappings) {
31
+ const lines = [];
32
+ let src = 0;
33
+ let srcLine = 0;
34
+ let srcCol = 0;
35
+ for (const line of mappings.split(';')) {
36
+ const segs = [];
37
+ let genCol = 0;
38
+ if (line) {
39
+ for (const part of line.split(',')) {
40
+ if (!part)
41
+ continue;
42
+ const nums = decodeVLQ(part);
43
+ genCol += nums[0] || 0;
44
+ if (nums.length === 1) {
45
+ // An end marker: no original position from here on.
46
+ segs.push({ genCol, src: -1, srcLine: 0, srcCol: 0 });
47
+ }
48
+ else if (nums.length >= 4) {
49
+ src += nums[1];
50
+ srcLine += nums[2];
51
+ srcCol += nums[3];
52
+ segs.push({ genCol, src, srcLine, srcCol });
53
+ }
54
+ }
55
+ }
56
+ lines.push(segs);
57
+ }
58
+ return lines;
59
+ }
60
+ const mapCache = new Map();
61
+ async function loadSourceMap(url) {
62
+ const cached = mapCache.get(url);
63
+ if (cached)
64
+ return cached;
65
+ const p = (async () => {
66
+ try {
67
+ const u = new URL(url, location.href);
68
+ if (u.protocol !== location.protocol || u.host !== location.host)
69
+ return null;
70
+ const res = await rawFetch(url + '.map');
71
+ if (!res.ok)
72
+ return null;
73
+ const json = await res.json();
74
+ if (!json || typeof json.mappings !== 'string')
75
+ return null;
76
+ return { sources: json.sources || [], lines: decodeMappings(json.mappings) };
77
+ }
78
+ catch {
79
+ return null;
80
+ }
81
+ })();
82
+ mapCache.set(url, p);
83
+ return p;
84
+ }
85
+ /** Parses a V8/Firefox stack line into its script location, if present. */
86
+ export function parseStackFrame(line) {
87
+ const patterns = [
88
+ /^(.*?)((?:[a-z][a-z0-9+.-]*:)?\/\/[^\s)]+|\/[^\s):]+):(\d+):(\d+)(.*)$/,
89
+ ];
90
+ for (const re of patterns) {
91
+ const m = re.exec(line);
92
+ if (!m)
93
+ continue;
94
+ return { prefix: m[1], url: m[2], line: Number(m[3]), col: Number(m[4]), suffix: m[5] };
95
+ }
96
+ return null;
97
+ }
98
+ function remapLocation(map, line, col) {
99
+ let best = null;
100
+ const segs = map.lines[line - 1];
101
+ if (segs && segs.length > 0) {
102
+ for (const s of segs) {
103
+ if (s.genCol <= col - 1)
104
+ best = s;
105
+ else
106
+ break;
107
+ }
108
+ if (!best)
109
+ best = segs[0];
110
+ }
111
+ else {
112
+ // An unminified hydration map has a mapping only where a marker starts;
113
+ // it holds until the next one, so a line without any takes the last
114
+ // mapping before it.
115
+ for (let i = Math.min(line - 1, map.lines.length) - 1; i >= 0 && !best; i--) {
116
+ const prev = map.lines[i];
117
+ if (prev && prev.length > 0)
118
+ best = prev[prev.length - 1];
119
+ }
120
+ if (!best)
121
+ return null;
122
+ }
123
+ if (best.src < 0)
124
+ return null;
125
+ const source = map.sources[best.src] || '';
126
+ return { source, line: best.srcLine + 1, col: best.srcCol + 1 };
127
+ }
128
+ /** Rewrites each mappable frame of a stack trace to its original location. */
129
+ export async function symbolicateStack(stack) {
130
+ if (!stack || !stack.includes('.js'))
131
+ return stack;
132
+ const lines = stack.split('\n');
133
+ const out = await Promise.all(lines.map(async (line) => {
134
+ const frame = parseStackFrame(line);
135
+ if (!frame)
136
+ return line;
137
+ const map = await loadSourceMap(frame.url);
138
+ if (!map)
139
+ return line;
140
+ const loc = remapLocation(map, frame.line, frame.col);
141
+ // The generic label of a compiler-generated bundle says nothing more
142
+ // than the frame's own file and line.
143
+ if (!loc || !loc.source || loc.source === 'krate-hydration.js')
144
+ return line;
145
+ return frame.prefix + loc.source + ':' + loc.line + ':' + loc.col + frame.suffix;
146
+ }));
147
+ return out.join('\n');
148
+ }
@@ -0,0 +1,38 @@
1
+ export interface Frame {
2
+ fn: string;
3
+ file: string;
4
+ line: number;
5
+ col: number;
6
+ raw: string;
7
+ app: boolean;
8
+ /** The location is a URL the page loaded (no source map), not a project file. */
9
+ served: boolean;
10
+ }
11
+ export type StackItem = {
12
+ type: 'app';
13
+ frame: Frame;
14
+ } | {
15
+ type: 'fold';
16
+ frames: Frame[];
17
+ };
18
+ /** True for frames of the runtime, generated chunks, the overlay or dependencies. */
19
+ export declare function isFrameworkFile(file: string): boolean;
20
+ /** A file shown relative to the page origin. */
21
+ export declare function displayFile(file: string): string;
22
+ export declare function parseFrame(line: string): Frame | null;
23
+ export declare function parseStack(stack: string | undefined): Frame[];
24
+ /** App frames stay as they are; each run of framework frames folds into one item. */
25
+ export declare function splitStack(frames: Frame[]): StackItem[];
26
+ /** The first frame in the app's own code, or null. */
27
+ export declare function firstAppFrame(frames: Frame[]): Frame | null;
28
+ /** The error class named on the first line of a stack ("TypeError"), else "". */
29
+ export declare function errorName(stack: string | undefined, message?: string): string;
30
+ /**
31
+ * The first project location in a server stack or log: `src/x.ts:3:15`, or
32
+ * an absolute path outside node_modules. Returns null when there is none.
33
+ */
34
+ export declare function projectLocation(text: string | undefined): {
35
+ file: string;
36
+ line: number;
37
+ col: number;
38
+ } | null;
@@ -0,0 +1,115 @@
1
+ // Stack trace parsing for the runtime error view: frames, and the split into
2
+ // the app's own frames and folded framework frames.
3
+ const V8_NAMED = /^\s*at (?:async )?(.*?) \((.*?):(\d+):(\d+)\)\s*$/;
4
+ const V8_ANON = /^\s*at (?:async )?(.*?):(\d+):(\d+)\s*$/;
5
+ const GECKO = /^\s*(.*?)@(.*?):(\d+):(\d+)\s*$/;
6
+ /** True for frames of the runtime, generated chunks, the overlay or dependencies. */
7
+ export function isFrameworkFile(file) {
8
+ return (!file ||
9
+ /node_modules|@krate\/|\/chunks\/|^chunks\/|krate-[a-z-]+\.js|__krate\/|<anonymous>|native code|packages\/runtime\/|krate-hydration\.js|^(?:node|internal):/.test(file));
10
+ }
11
+ /** A file shown relative to the page origin. */
12
+ export function displayFile(file) {
13
+ try {
14
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(file)) {
15
+ const u = new URL(file);
16
+ if (typeof location !== 'undefined' && u.origin === location.origin)
17
+ return u.pathname.replace(/^\//, '');
18
+ return u.host + u.pathname;
19
+ }
20
+ }
21
+ catch {
22
+ /* keep it as is */
23
+ }
24
+ return file.replace(/^\.\//, '');
25
+ }
26
+ export function parseFrame(line) {
27
+ let m = V8_NAMED.exec(line);
28
+ let fn = '';
29
+ let file = '';
30
+ let ln = 0;
31
+ let col = 0;
32
+ if (m) {
33
+ [, fn, file] = m;
34
+ ln = Number(m[3]);
35
+ col = Number(m[4]);
36
+ }
37
+ else if ((m = V8_ANON.exec(line))) {
38
+ file = m[1];
39
+ ln = Number(m[2]);
40
+ col = Number(m[3]);
41
+ }
42
+ else if ((m = GECKO.exec(line))) {
43
+ [, fn, file] = m;
44
+ ln = Number(m[3]);
45
+ col = Number(m[4]);
46
+ }
47
+ else {
48
+ return null;
49
+ }
50
+ const served = /^[a-z][a-z0-9+.-]*:\/\//i.test(file.trim());
51
+ file = displayFile(file.trim());
52
+ return { fn: fn.trim() || '<anonymous>', file, line: ln, col, raw: line.trim(), app: !isFrameworkFile(file), served };
53
+ }
54
+ export function parseStack(stack) {
55
+ if (!stack)
56
+ return [];
57
+ const out = [];
58
+ for (const line of stack.split('\n')) {
59
+ if (/^\s*Host stack:/.test(line))
60
+ break;
61
+ const f = parseFrame(line);
62
+ if (f)
63
+ out.push(f);
64
+ }
65
+ return out;
66
+ }
67
+ /** App frames stay as they are; each run of framework frames folds into one item. */
68
+ export function splitStack(frames) {
69
+ const items = [];
70
+ for (const f of frames) {
71
+ if (f.app) {
72
+ items.push({ type: 'app', frame: f });
73
+ continue;
74
+ }
75
+ const last = items[items.length - 1];
76
+ if (last && last.type === 'fold')
77
+ last.frames.push(f);
78
+ else
79
+ items.push({ type: 'fold', frames: [f] });
80
+ }
81
+ return items;
82
+ }
83
+ /** The first frame in the app's own code, or null. */
84
+ export function firstAppFrame(frames) {
85
+ return frames.find((f) => f.app) || null;
86
+ }
87
+ /** The error class named on the first line of a stack ("TypeError"), else "". */
88
+ export function errorName(stack, message = '') {
89
+ const first = (stack || '').split('\n')[0] || '';
90
+ const m = /^\s*([A-Z][A-Za-z0-9_$]*(?:Error|Exception))\b/.exec(first) || /^\s*([A-Z][A-Za-z0-9_$]*(?:Error|Exception)):/.exec(message);
91
+ return m ? m[1] : '';
92
+ }
93
+ /**
94
+ * The first project location in a server stack or log: `src/x.ts:3:15`, or
95
+ * an absolute path outside node_modules. Returns null when there is none.
96
+ */
97
+ export function projectLocation(text) {
98
+ if (!text)
99
+ return null;
100
+ // Page URLs in the log tail (browser reports) are not server locations.
101
+ text = text
102
+ .split('\n')
103
+ .filter((l) => !/^\s*\[browser\]/.test(l))
104
+ .join('\n')
105
+ .replace(/[a-z][a-z0-9+.-]*:\/\/\S+/gi, '');
106
+ const re = /((?:\/|[A-Za-z]:\\|\.\/)?(?:[\w@.-]+[\\/])*[\w@.[\]-]+\.(?:tsx|ts|jsx|js|mjs|cjs|mts|mdx|go)):(\d+)(?::(\d+))?/g;
107
+ let m;
108
+ while ((m = re.exec(text))) {
109
+ const file = m[1];
110
+ if (/node_modules|\.krate[\\/]|^node:|chunks[\\/]|[\\/]dist[\\/]/.test(file))
111
+ continue;
112
+ return { file, line: Number(m[2]), col: Number(m[3] || 1) };
113
+ }
114
+ return null;
115
+ }