@reliantlabs/forge-web-runtime 0.3.1 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -3
- package/dist/devlog.d.ts +10 -1
- package/dist/devlog.js +334 -23
- package/dist/devlog.js.map +1 -1
- package/dist/error-boundary.d.ts +1 -1
- package/dist/error-boundary.js +9 -2
- package/dist/error-boundary.js.map +1 -1
- package/dist/error-reporter.d.ts +27 -0
- package/dist/error-reporter.js +55 -0
- package/dist/error-reporter.js.map +1 -0
- package/dist/index.d.ts +15 -2
- package/dist/index.js +15 -2
- package/dist/index.js.map +1 -1
- package/dist/mock-transport.d.ts +8 -1
- package/dist/mock-transport.js +198 -6
- package/dist/mock-transport.js.map +1 -1
- package/dist/money.d.ts +69 -0
- package/dist/money.js +335 -0
- package/dist/money.js.map +1 -0
- package/dist/resource.js +7 -2
- package/dist/resource.js.map +1 -1
- package/dist/service-hooks.js +9 -0
- package/dist/service-hooks.js.map +1 -1
- package/dist/telemetry.d.ts +61 -21
- package/dist/telemetry.js +254 -111
- package/dist/telemetry.js.map +1 -1
- package/package.json +13 -46
- package/dist/otel.d.ts +0 -31
- package/dist/otel.js +0 -94
- package/dist/otel.js.map +0 -1
package/README.md
CHANGED
|
@@ -12,7 +12,8 @@ import {
|
|
|
12
12
|
useSession, // the signed-in user
|
|
13
13
|
RouteGuard, // signed-in render gate
|
|
14
14
|
Resource, // the list tristate + cursor pagination
|
|
15
|
-
|
|
15
|
+
reportException, // record a caught error with the browser telemetry SDK
|
|
16
|
+
formatMinorUnits, // exact money display; parseMinorUnits for input
|
|
16
17
|
} from "@reliantlabs/forge-web-runtime";
|
|
17
18
|
```
|
|
18
19
|
|
|
@@ -21,8 +22,8 @@ import {
|
|
|
21
22
|
**In:** mechanism. The interceptor stack (auth, brand headers, W3C
|
|
22
23
|
traceparent, error normalization, idempotency-gated retry), the session
|
|
23
24
|
derived from JWT claims, the error boundary, the toast queue, the
|
|
24
|
-
`<Resource>` tristate/pagination container, trace-context propagation,
|
|
25
|
-
|
|
25
|
+
`<Resource>` tristate/pagination container, trace-context propagation,
|
|
26
|
+
the HyperDX browser SDK wiring (`/telemetry` subpath), and integer money / basis-point formatting and parsing.
|
|
26
27
|
|
|
27
28
|
**Out:** presentation a project is meant to own. The component library under
|
|
28
29
|
`src/components/ui`, `globals.css`, the nav and the app layout all stay in the
|
|
@@ -125,6 +126,28 @@ Metro with `unstable_enablePackageExports` off, and `expo/tsconfig.base` sets
|
|
|
125
126
|
build output, reached the old way. Delete it and mobile breaks while web keeps
|
|
126
127
|
working.
|
|
127
128
|
|
|
129
|
+
## Money and basis points
|
|
130
|
+
|
|
131
|
+
The web counterpart of `forge/pkg/money`. An amount is an integer count of
|
|
132
|
+
its currency's minor unit (protobuf-es hands an `int64` over as a `bigint`)
|
|
133
|
+
plus an ISO 4217 code, and no float sits anywhere between the wire and the
|
|
134
|
+
screen.
|
|
135
|
+
|
|
136
|
+
```ts
|
|
137
|
+
formatMinorUnits(123456n); // "$1,234.56"
|
|
138
|
+
formatMinorUnits(1234n, { currency: "JPY" }); // "¥1,234"
|
|
139
|
+
formatMinorUnits(123456n, { currency: "EUR", locale: "de-DE" }); // "1.234,56 €"
|
|
140
|
+
parseMinorUnits("$1,234.5"); // 123450n
|
|
141
|
+
parseMinorUnits("1.234"); // null: USD has two minor digits, so no rounding
|
|
142
|
+
minorUnitsToInput(123450n); // "1234.50", parses back exactly
|
|
143
|
+
formatBasisPoints(825); // "8.25%"
|
|
144
|
+
parseBasisPoints("8.25%"); // 825
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
Minor digits come from Intl (JPY 0, KWD 3). Formatting stays exact past 2^53.
|
|
148
|
+
The parsers return `null` rather than guessing, so a form validates on that.
|
|
149
|
+
`src/money.ts`'s header lists the full rules.
|
|
150
|
+
|
|
128
151
|
## The `--color-*` contract
|
|
129
152
|
|
|
130
153
|
Several components render semantic Tailwind utilities. They are part of this
|
package/dist/devlog.d.ts
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
1
|
/** Console methods this module mirrors. */
|
|
2
2
|
declare const LEVELS: readonly ["log", "info", "warn", "error", "debug"];
|
|
3
3
|
type Level = (typeof LEVELS)[number];
|
|
4
|
-
/**
|
|
4
|
+
/**
|
|
5
|
+
* One log line on the wire.
|
|
6
|
+
*
|
|
7
|
+
* Also the whole v1 body: a legacy endpoint receives exactly this object, which
|
|
8
|
+
* is why the shape is unchanged and still exported.
|
|
9
|
+
*/
|
|
5
10
|
export interface DevLogPayload {
|
|
6
11
|
level: Level | "error";
|
|
7
12
|
msg: string;
|
|
8
13
|
}
|
|
14
|
+
/** The v2 body: many lines, one request. */
|
|
15
|
+
export interface DevLogBatch {
|
|
16
|
+
entries: DevLogPayload[];
|
|
17
|
+
}
|
|
9
18
|
export interface DevLoggingOptions {
|
|
10
19
|
/**
|
|
11
20
|
* Whether to install at all. Pass `import.meta.env.DEV` (Vite) or
|
package/dist/devlog.js
CHANGED
|
@@ -8,6 +8,47 @@
|
|
|
8
8
|
// browser console output to a dev-server endpoint that prints it, so it lands
|
|
9
9
|
// in .forge/logs/<env>/frontend_<name>.log next to the server logs.
|
|
10
10
|
//
|
|
11
|
+
// ── Why this batches (protocol v2) ───────────────────────────────────────
|
|
12
|
+
//
|
|
13
|
+
// The first version sent one fetch POST per console call. Measured in a real
|
|
14
|
+
// app that logs freely, that is ~80 requests/s at light load and 200+/s in a
|
|
15
|
+
// burst, and those requests are not free bystanders: they share the browser's
|
|
16
|
+
// six-connections-per-origin pool and the dev server's single event loop with
|
|
17
|
+
// the app's own RPCs. In the same session, RPC latency averaged 37ms in quiet
|
|
18
|
+
// seconds and 127ms in seconds carrying 200+ log lines. Worse, `keepalive`
|
|
19
|
+
// requests draw on a 64 KiB in-flight browser quota shared across the page, so
|
|
20
|
+
// a burst does not just slow things down — some of it gets rejected, and the
|
|
21
|
+
// original `.catch(() => {})` made that indistinguishable from silence.
|
|
22
|
+
//
|
|
23
|
+
// So entries are buffered and flushed as a batch:
|
|
24
|
+
//
|
|
25
|
+
// - every FLUSH_INTERVAL_MS, timer armed when an entry lands in an empty
|
|
26
|
+
// buffer (the common case: a few lines coalesce into one request),
|
|
27
|
+
// - immediately once buffered output reaches MAX_BATCH_BYTES,
|
|
28
|
+
// - on a microtask for anything error-level, so a crash never waits 250ms
|
|
29
|
+
// while a same-tick burst still coalesces,
|
|
30
|
+
// - synchronously via sendBeacon on pagehide / visibilitychange→hidden,
|
|
31
|
+
// which is the only way output survives a navigation or a crash-reload.
|
|
32
|
+
//
|
|
33
|
+
// At most ONE request is in flight. Entries logged during it keep buffering and
|
|
34
|
+
// go out when it settles, which is what makes the printed order the log order —
|
|
35
|
+
// six parallel POSTs would interleave on the server.
|
|
36
|
+
//
|
|
37
|
+
// Nothing is ever dropped silently. A full buffer, a rejected request and an
|
|
38
|
+
// over-quota request all increment a counter, and the next batch to leave
|
|
39
|
+
// carries a synthetic warn line saying how many lines were lost and why. The
|
|
40
|
+
// failure this replaces was a dead sink that looked exactly like working code.
|
|
41
|
+
//
|
|
42
|
+
// ── Legacy endpoints ─────────────────────────────────────────────────────
|
|
43
|
+
//
|
|
44
|
+
// The receiving endpoint is a scaffold-once file the PROJECT owns (a Vite
|
|
45
|
+
// plugin / a Next.js route handler), so upgrading this package through npm will
|
|
46
|
+
// routinely meet an endpoint that predates batching. Such an endpoint answers
|
|
47
|
+
// 204 and prints one empty line for the whole batch — total, silent loss. A v2
|
|
48
|
+
// endpoint therefore returns `X-Forge-Devlog: 2`, and a 2xx without it makes
|
|
49
|
+
// this client fall back permanently to one v1 POST per line (plus one warn
|
|
50
|
+
// line telling the developer to update the endpoint).
|
|
51
|
+
//
|
|
11
52
|
// DEV ONLY, and structurally so. The receiving endpoint is a Vite plugin
|
|
12
53
|
// gated `apply: "serve"` / a Next.js route behind a NODE_ENV check, so it does
|
|
13
54
|
// not exist in a production build; installDevLogging() additionally no-ops
|
|
@@ -20,61 +61,303 @@
|
|
|
20
61
|
/** Console methods this module mirrors. */
|
|
21
62
|
const LEVELS = ["log", "info", "warn", "error", "debug"];
|
|
22
63
|
export const DEV_LOG_ENDPOINT = "/__forge/log";
|
|
64
|
+
/** Response header a batching endpoint sets. Its ABSENCE selects v1 fallback. */
|
|
65
|
+
const PROTOCOL_HEADER = "X-Forge-Devlog";
|
|
66
|
+
/** Cap a single line so a runaway loop cannot fill the disk. Matches the endpoints. */
|
|
67
|
+
const MAX_LINE = 8_000;
|
|
68
|
+
/** How long a line may wait for company before it is sent. */
|
|
69
|
+
const FLUSH_INTERVAL_MS = 250;
|
|
70
|
+
/**
|
|
71
|
+
* Per-request ceiling. Deliberately half of the browser's 64 KiB shared
|
|
72
|
+
* `keepalive` in-flight quota: with one request in flight, a batch cannot be
|
|
73
|
+
* the thing that pushes the page over it.
|
|
74
|
+
*/
|
|
75
|
+
const MAX_BATCH_BYTES = 32 * 1024;
|
|
76
|
+
/** Buffer ceiling. Past it entries are dropped and counted, never queued forever. */
|
|
77
|
+
const MAX_BUFFER_ENTRIES = 5_000;
|
|
23
78
|
const original = {};
|
|
24
79
|
let installed = false;
|
|
25
80
|
// Guards against infinite recursion. The forwarder calls fetch(), and anything
|
|
26
81
|
// that logs inside fetch (an interceptor, a polyfill, a devtools extension)
|
|
27
|
-
// would otherwise re-enter the override forever.
|
|
82
|
+
// would otherwise re-enter the override forever. Such a line is still mirrored
|
|
83
|
+
// to the real console — it is only forwarding that is suppressed.
|
|
28
84
|
let forwarding = false;
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
85
|
+
let endpointUrl = DEV_LOG_ENDPOINT;
|
|
86
|
+
let buffer = [];
|
|
87
|
+
let bufferedBytes = 0;
|
|
88
|
+
let flushTimer;
|
|
89
|
+
let requestInFlight = false;
|
|
90
|
+
let errorFlushQueued = false;
|
|
91
|
+
let droppedCount = 0;
|
|
92
|
+
let droppedReason = "";
|
|
93
|
+
/** Set for good once an endpoint is known not to understand batches. */
|
|
94
|
+
let legacyEndpoint = false;
|
|
95
|
+
/**
|
|
96
|
+
* Render one console argument as a string.
|
|
97
|
+
*
|
|
98
|
+
* Circular structures and BigInt are the two cases a plain JSON.stringify
|
|
99
|
+
* throws on, and the old fallback to String(value) turned both into
|
|
100
|
+
* "[object Object]" — deleting exactly the shape you were trying to read. The
|
|
101
|
+
* replacer keeps the object and names the cycle instead.
|
|
102
|
+
*/
|
|
103
|
+
function render(value) {
|
|
104
|
+
if (typeof value === "string")
|
|
105
|
+
return value;
|
|
106
|
+
if (value instanceof Error) {
|
|
107
|
+
return `${value.name}: ${value.message}${value.stack ? `\n${value.stack}` : ""}`;
|
|
33
108
|
}
|
|
34
|
-
if (typeof arg === "string")
|
|
35
|
-
return arg;
|
|
36
109
|
try {
|
|
37
|
-
|
|
110
|
+
const seen = new WeakSet();
|
|
111
|
+
return (JSON.stringify(value, (_key, val) => {
|
|
112
|
+
if (typeof val === "bigint")
|
|
113
|
+
return `${val}n`;
|
|
114
|
+
if (typeof val === "object" && val !== null) {
|
|
115
|
+
if (seen.has(val))
|
|
116
|
+
return "[Circular]";
|
|
117
|
+
seen.add(val);
|
|
118
|
+
}
|
|
119
|
+
return val;
|
|
120
|
+
}) ?? String(value));
|
|
38
121
|
}
|
|
39
122
|
catch {
|
|
40
|
-
//
|
|
41
|
-
return String(
|
|
123
|
+
// DOM nodes, getters that throw — never let logging throw.
|
|
124
|
+
return String(value);
|
|
42
125
|
}
|
|
43
126
|
}
|
|
44
|
-
function
|
|
127
|
+
function truncate(msg) {
|
|
128
|
+
return msg.length > MAX_LINE ? `${msg.slice(0, MAX_LINE)}… (truncated)` : msg;
|
|
129
|
+
}
|
|
130
|
+
function entryBytes(entry) {
|
|
131
|
+
return JSON.stringify(entry).length;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Buffer one line and decide whether it can wait.
|
|
135
|
+
*
|
|
136
|
+
* Arguments are rendered HERE rather than at flush time: a console argument is
|
|
137
|
+
* a live object, and by the time a batch leaves 250ms later the array it logged
|
|
138
|
+
* may have been mutated or emptied. The snapshot is the value at the call.
|
|
139
|
+
*/
|
|
140
|
+
function capture(level, args) {
|
|
45
141
|
if (forwarding)
|
|
46
142
|
return;
|
|
143
|
+
if (buffer.length >= MAX_BUFFER_ENTRIES) {
|
|
144
|
+
droppedCount += 1;
|
|
145
|
+
droppedReason = "buffer full";
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const entry = {
|
|
149
|
+
level,
|
|
150
|
+
msg: truncate(args.map(render).join(" ")),
|
|
151
|
+
};
|
|
152
|
+
const wasEmpty = buffer.length === 0;
|
|
153
|
+
buffer.push(entry);
|
|
154
|
+
bufferedBytes += entryBytes(entry);
|
|
155
|
+
if (bufferedBytes >= MAX_BATCH_BYTES) {
|
|
156
|
+
flush();
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (level === "error") {
|
|
160
|
+
// An error is what someone is waiting for; it must not sit in a timer. The
|
|
161
|
+
// microtask (rather than a direct flush) lets a same-tick burst — a failing
|
|
162
|
+
// render logging three times — still leave as one request.
|
|
163
|
+
if (!errorFlushQueued) {
|
|
164
|
+
errorFlushQueued = true;
|
|
165
|
+
queueMicrotask(() => {
|
|
166
|
+
errorFlushQueued = false;
|
|
167
|
+
flush();
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (wasEmpty)
|
|
173
|
+
armTimer();
|
|
174
|
+
}
|
|
175
|
+
function armTimer() {
|
|
176
|
+
if (flushTimer !== undefined)
|
|
177
|
+
return;
|
|
178
|
+
flushTimer = setTimeout(() => {
|
|
179
|
+
flushTimer = undefined;
|
|
180
|
+
flush();
|
|
181
|
+
}, FLUSH_INTERVAL_MS);
|
|
182
|
+
}
|
|
183
|
+
function clearFlushTimer() {
|
|
184
|
+
if (flushTimer === undefined)
|
|
185
|
+
return;
|
|
186
|
+
clearTimeout(flushTimer);
|
|
187
|
+
flushTimer = undefined;
|
|
188
|
+
}
|
|
189
|
+
/** Pull entries off the front of the buffer without exceeding MAX_BATCH_BYTES. */
|
|
190
|
+
function takeBatch(limit = MAX_BATCH_BYTES) {
|
|
191
|
+
const batch = [];
|
|
192
|
+
let size = '{"entries":[]}'.length;
|
|
193
|
+
while (buffer.length > 0) {
|
|
194
|
+
const entry = buffer[0];
|
|
195
|
+
const cost = entryBytes(entry) + (batch.length > 0 ? 1 : 0);
|
|
196
|
+
// Always take at least one entry: a single line that somehow exceeds the
|
|
197
|
+
// limit must still leave, or it stalls every line behind it forever.
|
|
198
|
+
if (batch.length > 0 && size + cost > limit)
|
|
199
|
+
break;
|
|
200
|
+
buffer.shift();
|
|
201
|
+
bufferedBytes -= entryBytes(entry);
|
|
202
|
+
batch.push(entry);
|
|
203
|
+
size += cost;
|
|
204
|
+
}
|
|
205
|
+
if (buffer.length === 0)
|
|
206
|
+
bufferedBytes = 0;
|
|
207
|
+
return batch;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Prepend the "we lost lines" notice, if any, so it travels with the next batch
|
|
211
|
+
* rather than needing a request of its own.
|
|
212
|
+
*/
|
|
213
|
+
function drainDroppedNotice() {
|
|
214
|
+
if (droppedCount === 0)
|
|
215
|
+
return;
|
|
216
|
+
const notice = {
|
|
217
|
+
level: "warn",
|
|
218
|
+
msg: `[forge-devlog] dropped ${droppedCount} lines (${droppedReason})`,
|
|
219
|
+
};
|
|
220
|
+
buffer.unshift(notice);
|
|
221
|
+
bufferedBytes += entryBytes(notice);
|
|
222
|
+
droppedCount = 0;
|
|
223
|
+
droppedReason = "";
|
|
224
|
+
}
|
|
225
|
+
function post(body) {
|
|
226
|
+
// The recursion guard must wrap the CALL, not the promise: a fetch polyfill
|
|
227
|
+
// that logs does so synchronously from inside fetch().
|
|
47
228
|
forwarding = true;
|
|
48
229
|
try {
|
|
49
|
-
|
|
50
|
-
void fetch(endpoint, {
|
|
230
|
+
return fetch(endpointUrl, {
|
|
51
231
|
method: "POST",
|
|
52
232
|
headers: { "Content-Type": "application/json" },
|
|
53
|
-
body
|
|
233
|
+
body,
|
|
54
234
|
// A log emitted during unload (the interesting case for a crash on
|
|
55
235
|
// navigation) is cancelled without this.
|
|
56
236
|
keepalive: true,
|
|
57
237
|
// Never let log forwarding trip a credentials or CORS policy.
|
|
58
238
|
credentials: "omit",
|
|
59
|
-
}).catch(() => {
|
|
60
|
-
// The dev server going away must not surface as an app error.
|
|
61
239
|
});
|
|
62
240
|
}
|
|
63
241
|
finally {
|
|
64
242
|
forwarding = false;
|
|
65
243
|
}
|
|
66
244
|
}
|
|
67
|
-
|
|
68
|
-
|
|
245
|
+
/**
|
|
246
|
+
* Send one request's worth of buffered output, if nothing is in flight.
|
|
247
|
+
*
|
|
248
|
+
* The single-flight rule is what guarantees the dev server prints lines in the
|
|
249
|
+
* order they were logged, and it doubles as backpressure: a slow endpoint makes
|
|
250
|
+
* batches bigger rather than making requests pile up.
|
|
251
|
+
*/
|
|
252
|
+
function flush() {
|
|
253
|
+
if (requestInFlight)
|
|
254
|
+
return;
|
|
255
|
+
drainDroppedNotice();
|
|
256
|
+
if (buffer.length === 0)
|
|
257
|
+
return;
|
|
258
|
+
clearFlushTimer();
|
|
259
|
+
const batch = legacyEndpoint ? takeBatch(0) : takeBatch();
|
|
260
|
+
if (batch.length === 0)
|
|
261
|
+
return;
|
|
262
|
+
const body = legacyEndpoint
|
|
263
|
+
? JSON.stringify(batch[0])
|
|
264
|
+
: JSON.stringify({ entries: batch });
|
|
265
|
+
requestInFlight = true;
|
|
266
|
+
post(body).then((response) => {
|
|
267
|
+
requestInFlight = false;
|
|
268
|
+
if (!response.ok) {
|
|
269
|
+
countDropped(batch.length, `endpoint returned ${response.status}`);
|
|
270
|
+
}
|
|
271
|
+
else if (!legacyEndpoint && !response.headers.get(PROTOCOL_HEADER)) {
|
|
272
|
+
adoptLegacyMode(batch);
|
|
273
|
+
}
|
|
274
|
+
if (buffer.length > 0 || droppedCount > 0)
|
|
275
|
+
flush();
|
|
276
|
+
}, () => {
|
|
277
|
+
requestInFlight = false;
|
|
278
|
+
countDropped(batch.length, "request failed");
|
|
279
|
+
if (buffer.length > 0)
|
|
280
|
+
flush();
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
function countDropped(count, reason) {
|
|
284
|
+
droppedCount += count;
|
|
285
|
+
droppedReason = reason;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* A 2xx with no protocol header came from an endpoint written before batching.
|
|
289
|
+
* It parsed `{entries:[...]}` as a v1 body, found no `msg`, and printed one
|
|
290
|
+
* empty line — so this batch is lost unless it is re-sent one line at a time,
|
|
291
|
+
* and so is everything after it.
|
|
292
|
+
*/
|
|
293
|
+
function adoptLegacyMode(lost) {
|
|
294
|
+
legacyEndpoint = true;
|
|
295
|
+
const notice = {
|
|
296
|
+
level: "warn",
|
|
297
|
+
msg: "[forge-devlog] this dev server's /__forge/log endpoint predates batched " +
|
|
298
|
+
"posts; update it (forge skill: debug) — falling back to one request per line",
|
|
299
|
+
};
|
|
300
|
+
buffer.unshift(notice, ...lost);
|
|
301
|
+
bufferedBytes += [notice, ...lost].reduce((n, e) => n + entryBytes(e), 0);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Last-chance flush on page teardown.
|
|
305
|
+
*
|
|
306
|
+
* fetch — even with keepalive — is not reliable here, and an async flush is
|
|
307
|
+
* hopeless: the event loop may not run again. sendBeacon hands the bytes to the
|
|
308
|
+
* browser to deliver after the document is gone, which is precisely the case
|
|
309
|
+
* where the last few log lines explain what happened.
|
|
310
|
+
*/
|
|
311
|
+
function flushOnUnload() {
|
|
312
|
+
drainDroppedNotice();
|
|
313
|
+
if (buffer.length === 0)
|
|
314
|
+
return;
|
|
315
|
+
const canBeacon = typeof navigator !== "undefined" &&
|
|
316
|
+
typeof navigator.sendBeacon === "function";
|
|
317
|
+
if (!canBeacon) {
|
|
318
|
+
// No beacon: keepalive fetch is the only remaining option, and one request
|
|
319
|
+
// has a better chance of leaving than a queue of them.
|
|
320
|
+
flush();
|
|
321
|
+
return;
|
|
322
|
+
}
|
|
323
|
+
forwarding = true;
|
|
324
|
+
try {
|
|
325
|
+
while (buffer.length > 0) {
|
|
326
|
+
const batch = legacyEndpoint ? takeBatch(0) : takeBatch();
|
|
327
|
+
const body = legacyEndpoint
|
|
328
|
+
? JSON.stringify(batch[0])
|
|
329
|
+
: JSON.stringify({ entries: batch });
|
|
330
|
+
// text/plain is not a decoration: sendBeacon with application/json is a
|
|
331
|
+
// non-simple request and would need a CORS preflight it cannot make. The
|
|
332
|
+
// endpoints parse the body regardless of Content-Type for this reason.
|
|
333
|
+
const blob = new Blob([body], { type: "text/plain;charset=UTF-8" });
|
|
334
|
+
if (!navigator.sendBeacon(endpointUrl, blob)) {
|
|
335
|
+
// The beacon queue is full (64 KiB per origin). Nothing later will fit
|
|
336
|
+
// either, so stop and account for what is left.
|
|
337
|
+
countDropped(batch.length + buffer.length, "beacon queue full");
|
|
338
|
+
buffer = [];
|
|
339
|
+
bufferedBytes = 0;
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
finally {
|
|
345
|
+
forwarding = false;
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
function onWindowError(event) {
|
|
349
|
+
capture("error", [
|
|
69
350
|
event.error ??
|
|
70
351
|
`${event.message} @ ${event.filename}:${event.lineno}:${event.colno}`,
|
|
71
352
|
]);
|
|
72
353
|
}
|
|
73
|
-
function onRejection(
|
|
74
|
-
|
|
354
|
+
function onRejection(event) {
|
|
355
|
+
capture("error", ["unhandled rejection:", event.reason]);
|
|
75
356
|
}
|
|
76
357
|
let errorHandler;
|
|
77
358
|
let rejectionHandler;
|
|
359
|
+
let pageHideHandler;
|
|
360
|
+
let visibilityHandler;
|
|
78
361
|
/**
|
|
79
362
|
* Mirror console output and uncaught errors to the dev server, which prints
|
|
80
363
|
* them into .forge/logs/<env>/frontend_<name>.log.
|
|
@@ -100,6 +383,13 @@ export function installDevLogging(options) {
|
|
|
100
383
|
return; // SSR / prerender pass
|
|
101
384
|
const { endpoint = DEV_LOG_ENDPOINT, mirrorToConsole = true } = options;
|
|
102
385
|
installed = true;
|
|
386
|
+
endpointUrl = endpoint;
|
|
387
|
+
buffer = [];
|
|
388
|
+
bufferedBytes = 0;
|
|
389
|
+
droppedCount = 0;
|
|
390
|
+
droppedReason = "";
|
|
391
|
+
legacyEndpoint = false;
|
|
392
|
+
requestInFlight = false;
|
|
103
393
|
for (const level of LEVELS) {
|
|
104
394
|
// Keep the ORIGINAL reference, not a bound copy: uninstall must restore
|
|
105
395
|
// console.log to the identical function it replaced, so a second consumer
|
|
@@ -109,18 +399,33 @@ export function installDevLogging(options) {
|
|
|
109
399
|
console[level] = (...args) => {
|
|
110
400
|
if (mirrorToConsole)
|
|
111
401
|
previous.apply(console, args);
|
|
112
|
-
|
|
402
|
+
capture(level, args);
|
|
113
403
|
};
|
|
114
404
|
}
|
|
115
|
-
errorHandler = (e) => onWindowError(
|
|
116
|
-
rejectionHandler = (e) => onRejection(
|
|
405
|
+
errorHandler = (e) => onWindowError(e);
|
|
406
|
+
rejectionHandler = (e) => onRejection(e);
|
|
407
|
+
pageHideHandler = () => flushOnUnload();
|
|
117
408
|
window.addEventListener("error", errorHandler);
|
|
118
409
|
window.addEventListener("unhandledrejection", rejectionHandler);
|
|
410
|
+
window.addEventListener("pagehide", pageHideHandler);
|
|
411
|
+
if (typeof document !== "undefined") {
|
|
412
|
+
// visibilitychange→hidden is the only teardown signal mobile Safari
|
|
413
|
+
// reliably fires; pagehide alone loses the whole buffer there.
|
|
414
|
+
visibilityHandler = () => {
|
|
415
|
+
if (document.visibilityState === "hidden")
|
|
416
|
+
flushOnUnload();
|
|
417
|
+
};
|
|
418
|
+
document.addEventListener("visibilitychange", visibilityHandler);
|
|
419
|
+
}
|
|
119
420
|
}
|
|
120
421
|
/** Restore the original console methods and remove the window listeners. */
|
|
121
422
|
export function uninstallDevLogging() {
|
|
122
423
|
if (!installed)
|
|
123
424
|
return;
|
|
425
|
+
// Flush before restoring: whatever is buffered was logged while this was
|
|
426
|
+
// installed, and a teardown is no reason to lose it.
|
|
427
|
+
clearFlushTimer();
|
|
428
|
+
flush();
|
|
124
429
|
for (const level of LEVELS) {
|
|
125
430
|
const previous = original[level];
|
|
126
431
|
if (previous)
|
|
@@ -131,8 +436,14 @@ export function uninstallDevLogging() {
|
|
|
131
436
|
window.removeEventListener("error", errorHandler);
|
|
132
437
|
if (rejectionHandler)
|
|
133
438
|
window.removeEventListener("unhandledrejection", rejectionHandler);
|
|
439
|
+
if (pageHideHandler)
|
|
440
|
+
window.removeEventListener("pagehide", pageHideHandler);
|
|
441
|
+
if (visibilityHandler && typeof document !== "undefined")
|
|
442
|
+
document.removeEventListener("visibilitychange", visibilityHandler);
|
|
134
443
|
errorHandler = undefined;
|
|
135
444
|
rejectionHandler = undefined;
|
|
445
|
+
pageHideHandler = undefined;
|
|
446
|
+
visibilityHandler = undefined;
|
|
136
447
|
installed = false;
|
|
137
448
|
}
|
|
138
449
|
/** Whether the console override is currently installed. Exposed for tests. */
|
package/dist/devlog.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devlog.js","sourceRoot":"","sources":["../src/devlog.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,2EAA2E;AAC3E,0EAA0E;AAC1E,8EAA8E;AAC9E,oEAAoE;AACpE,EAAE;AACF,yEAAyE;AACzE,+EAA+E;AAC/E,2EAA2E;AAC3E,sEAAsE;AACtE,mDAAmD;AACnD,EAAE;AACF,6EAA6E;AAC7E,0EAA0E;AAC1E,oDAAoD;AAEpD,2CAA2C;AAC3C,MAAM,MAAM,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAU,CAAC;AA2BlE,MAAM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":["// Dev-only browser log forwarding.\n//\n// A browser's console is a dead end: an agent debugging a scaffolded frontend\n// cannot open devtools, so every console line and — worse — every uncaught\n// error is invisible to it. The backend has no such gap (structured slog, the\n// observe ComponentChain, and forge's dev loop already tees each process's\n// stdout to .forge/logs/<env>/). This closes the frontend half by POSTing\n// browser console output to a dev-server endpoint that prints it, so it lands\n// in .forge/logs/<env>/frontend_<name>.log next to the server logs.\n//\n// DEV ONLY, and structurally so. The receiving endpoint is a Vite plugin\n// gated `apply: \"serve\"` / a Next.js route behind a NODE_ENV check, so it does\n// not exist in a production build; installDevLogging() additionally no-ops\n// unless it is handed dev: true. A production bundle therefore has no\n// endpoint to post to AND no code that would post.\n//\n// It is also reversible: uninstallDevLogging() restores the original console\n// methods, and the scaffolded call site is an ordinary line in main.tsx /\n// providers.tsx that a project can delete outright.\n\n/** Console methods this module mirrors. */\nconst LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n\ntype Level = (typeof LEVELS)[number];\n\n/** The wire shape the dev-server endpoint expects. */\nexport interface DevLogPayload {\n level: Level | \"error\";\n msg: string;\n}\n\nexport interface DevLoggingOptions {\n /**\n * Whether to install at all. Pass `import.meta.env.DEV` (Vite) or\n * `process.env.NODE_ENV !== \"production\"` (Next.js). When false this is a\n * no-op, so the call site needs no conditional of its own.\n */\n dev: boolean;\n /** Endpoint the dev server serves. Defaults to the forge convention. */\n endpoint?: string;\n /**\n * Also keep writing to the real console. Default true — the browser devtools\n * experience should be unchanged; this feature ADDS a sink, it does not move\n * one.\n */\n mirrorToConsole?: boolean;\n}\n\nexport const DEV_LOG_ENDPOINT = \"/__forge/log\";\n\nconst original: Partial<Record<Level, (...args: unknown[]) => void>> = {};\nlet installed = false;\n\n// Guards against infinite recursion. The forwarder calls fetch(), and anything\n// that logs inside fetch (an interceptor, a polyfill, a devtools extension)\n// would otherwise re-enter the override forever.\nlet forwarding = false;\n\n/** Render one console argument as a string, keeping Error stacks intact. */\nfunction render(arg: unknown): string {\n if (arg instanceof Error) {\n return `${arg.name}: ${arg.message}${arg.stack ? `\\n${arg.stack}` : \"\"}`;\n }\n if (typeof arg === \"string\") return arg;\n try {\n return JSON.stringify(arg);\n } catch {\n // Circular structures, BigInt, DOM nodes — never let logging throw.\n return String(arg);\n }\n}\n\nfunction forward(\n endpoint: string,\n level: DevLogPayload[\"level\"],\n args: unknown[],\n): void {\n if (forwarding) return;\n forwarding = true;\n try {\n const body: DevLogPayload = { level, msg: args.map(render).join(\" \") };\n void fetch(endpoint, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(body),\n // A log emitted during unload (the interesting case for a crash on\n // navigation) is cancelled without this.\n keepalive: true,\n // Never let log forwarding trip a credentials or CORS policy.\n credentials: \"omit\",\n }).catch(() => {\n // The dev server going away must not surface as an app error.\n });\n } finally {\n forwarding = false;\n }\n}\n\nfunction onWindowError(endpoint: string, event: ErrorEvent): void {\n forward(endpoint, \"error\", [\n event.error ??\n `${event.message} @ ${event.filename}:${event.lineno}:${event.colno}`,\n ]);\n}\n\nfunction onRejection(endpoint: string, event: PromiseRejectionEvent): void {\n forward(endpoint, \"error\", [\"unhandled rejection:\", event.reason]);\n}\n\nlet errorHandler: ((e: ErrorEvent) => void) | undefined;\nlet rejectionHandler: ((e: PromiseRejectionEvent) => void) | undefined;\n\n/**\n * Mirror console output and uncaught errors to the dev server, which prints\n * them into .forge/logs/<env>/frontend_<name>.log.\n *\n * The window listeners are the point of the feature as much as the console\n * override is: an uncaught TypeError or a rejected promise produces no console\n * call of its own, and those are exactly the failures worth seeing.\n *\n * Safe to call more than once; the second call is a no-op.\n */\nexport function installDevLogging(options: DevLoggingOptions): void {\n // `dev` is read off `options` rather than destructured with a default, and\n // checked FIRST. A bundler constant-folds `import.meta.env.DEV` to false at\n // the CALL SITE and can then drop the argument entirely, leaving a bare\n // `installDevLogging({})` — with a defaulted `dev` that call would install\n // the override in a production bundle. `options?.dev !== true` is therefore\n // fail-closed: absent, undefined, or anything non-true means do nothing.\n if (options?.dev !== true) return;\n if (installed) return;\n if (typeof window === \"undefined\") return; // SSR / prerender pass\n\n const { endpoint = DEV_LOG_ENDPOINT, mirrorToConsole = true } = options;\n installed = true;\n\n for (const level of LEVELS) {\n // Keep the ORIGINAL reference, not a bound copy: uninstall must restore\n // console.log to the identical function it replaced, so a second consumer\n // holding that reference (or a test asserting on it) sees no difference.\n const previous = console[level] as (...args: unknown[]) => void;\n original[level] = previous;\n console[level] = (...args: unknown[]) => {\n if (mirrorToConsole) previous.apply(console, args);\n forward(endpoint, level, args);\n };\n }\n\n errorHandler = (e) => onWindowError(endpoint, e);\n rejectionHandler = (e) => onRejection(endpoint, e);\n window.addEventListener(\"error\", errorHandler);\n window.addEventListener(\"unhandledrejection\", rejectionHandler);\n}\n\n/** Restore the original console methods and remove the window listeners. */\nexport function uninstallDevLogging(): void {\n if (!installed) return;\n for (const level of LEVELS) {\n const previous = original[level];\n if (previous) console[level] = previous;\n delete original[level];\n }\n if (errorHandler) window.removeEventListener(\"error\", errorHandler);\n if (rejectionHandler)\n window.removeEventListener(\"unhandledrejection\", rejectionHandler);\n errorHandler = undefined;\n rejectionHandler = undefined;\n installed = false;\n}\n\n/** Whether the console override is currently installed. Exposed for tests. */\nexport function devLoggingInstalled(): boolean {\n return installed;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"devlog.js","sourceRoot":"","sources":["../src/devlog.ts"],"names":[],"mappings":"AAAA,mCAAmC;AACnC,EAAE;AACF,8EAA8E;AAC9E,2EAA2E;AAC3E,8EAA8E;AAC9E,2EAA2E;AAC3E,0EAA0E;AAC1E,8EAA8E;AAC9E,oEAAoE;AACpE,EAAE;AACF,4EAA4E;AAC5E,EAAE;AACF,6EAA6E;AAC7E,6EAA6E;AAC7E,8EAA8E;AAC9E,8EAA8E;AAC9E,8EAA8E;AAC9E,2EAA2E;AAC3E,+EAA+E;AAC/E,6EAA6E;AAC7E,wEAAwE;AACxE,EAAE;AACF,kDAAkD;AAClD,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K,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,QAAQ,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;QACjC,IAAI,QAAQ;YAAE,OAAO,CAAC,KAAK,CAAC,GAAG,QAAQ,CAAC;QACxC,OAAO,QAAQ,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;IACD,IAAI,YAAY;QAAE,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,YAAY,CAAC,CAAC;IACpE,IAAI,gBAAgB;QAClB,MAAM,CAAC,mBAAmB,CAAC,oBAAoB,EAAE,gBAAgB,CAAC,CAAC;IACrE,IAAI,eAAe;QAAE,MAAM,CAAC,mBAAmB,CAAC,UAAU,EAAE,eAAe,CAAC,CAAC;IAC7E,IAAI,iBAAiB,IAAI,OAAO,QAAQ,KAAK,WAAW;QACtD,QAAQ,CAAC,mBAAmB,CAAC,kBAAkB,EAAE,iBAAiB,CAAC,CAAC;IACtE,YAAY,GAAG,SAAS,CAAC;IACzB,gBAAgB,GAAG,SAAS,CAAC;IAC7B,eAAe,GAAG,SAAS,CAAC;IAC5B,iBAAiB,GAAG,SAAS,CAAC;IAC9B,SAAS,GAAG,KAAK,CAAC;AACpB,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,mBAAmB;IACjC,OAAO,SAAS,CAAC;AACnB,CAAC","sourcesContent":["// Dev-only browser log forwarding.\n//\n// A browser's console is a dead end: an agent debugging a scaffolded frontend\n// cannot open devtools, so every console line and — worse — every uncaught\n// error is invisible to it. The backend has no such gap (structured slog, the\n// observe ComponentChain, and forge's dev loop already tees each process's\n// stdout to .forge/logs/<env>/). This closes the frontend half by POSTing\n// browser console output to a dev-server endpoint that prints it, so it lands\n// in .forge/logs/<env>/frontend_<name>.log next to the server logs.\n//\n// ── Why this batches (protocol v2) ───────────────────────────────────────\n//\n// The first version sent one fetch POST per console call. Measured in a real\n// app that logs freely, that is ~80 requests/s at light load and 200+/s in a\n// burst, and those requests are not free bystanders: they share the browser's\n// six-connections-per-origin pool and the dev server's single event loop with\n// the app's own RPCs. In the same session, RPC latency averaged 37ms in quiet\n// seconds and 127ms in seconds carrying 200+ log lines. Worse, `keepalive`\n// requests draw on a 64 KiB in-flight browser quota shared across the page, so\n// a burst does not just slow things down — some of it gets rejected, and the\n// original `.catch(() => {})` made that indistinguishable from silence.\n//\n// So entries are buffered and flushed as a batch:\n//\n// - every FLUSH_INTERVAL_MS, timer armed when an entry lands in an empty\n// buffer (the common case: a few lines coalesce into one request),\n// - immediately once buffered output reaches MAX_BATCH_BYTES,\n// - on a microtask for anything error-level, so a crash never waits 250ms\n// while a same-tick burst still coalesces,\n// - synchronously via sendBeacon on pagehide / visibilitychange→hidden,\n// which is the only way output survives a navigation or a crash-reload.\n//\n// At most ONE request is in flight. Entries logged during it keep buffering and\n// go out when it settles, which is what makes the printed order the log order —\n// six parallel POSTs would interleave on the server.\n//\n// Nothing is ever dropped silently. A full buffer, a rejected request and an\n// over-quota request all increment a counter, and the next batch to leave\n// carries a synthetic warn line saying how many lines were lost and why. The\n// failure this replaces was a dead sink that looked exactly like working code.\n//\n// ── Legacy endpoints ─────────────────────────────────────────────────────\n//\n// The receiving endpoint is a scaffold-once file the PROJECT owns (a Vite\n// plugin / a Next.js route handler), so upgrading this package through npm will\n// routinely meet an endpoint that predates batching. Such an endpoint answers\n// 204 and prints one empty line for the whole batch — total, silent loss. A v2\n// endpoint therefore returns `X-Forge-Devlog: 2`, and a 2xx without it makes\n// this client fall back permanently to one v1 POST per line (plus one warn\n// line telling the developer to update the endpoint).\n//\n// DEV ONLY, and structurally so. The receiving endpoint is a Vite plugin\n// gated `apply: \"serve\"` / a Next.js route behind a NODE_ENV check, so it does\n// not exist in a production build; installDevLogging() additionally no-ops\n// unless it is handed dev: true. A production bundle therefore has no\n// endpoint to post to AND no code that would post.\n//\n// It is also reversible: uninstallDevLogging() restores the original console\n// methods, and the scaffolded call site is an ordinary line in main.tsx /\n// providers.tsx that a project can delete outright.\n\n/** Console methods this module mirrors. */\nconst LEVELS = [\"log\", \"info\", \"warn\", \"error\", \"debug\"] as const;\n\ntype Level = (typeof LEVELS)[number];\n\n/**\n * One log line on the wire.\n *\n * Also the whole v1 body: a legacy endpoint receives exactly this object, which\n * is why the shape is unchanged and still exported.\n */\nexport interface DevLogPayload {\n level: Level | \"error\";\n msg: string;\n}\n\n/** The v2 body: many lines, one request. */\nexport interface DevLogBatch {\n entries: DevLogPayload[];\n}\n\nexport interface DevLoggingOptions {\n /**\n * Whether to install at all. Pass `import.meta.env.DEV` (Vite) or\n * `process.env.NODE_ENV !== \"production\"` (Next.js). When false this is a\n * no-op, so the call site needs no conditional of its own.\n */\n dev: boolean;\n /** Endpoint the dev server serves. Defaults to the forge convention. */\n endpoint?: string;\n /**\n * Also keep writing to the real console. Default true — the browser devtools\n * experience should be unchanged; this feature ADDS a sink, it does not move\n * one.\n */\n mirrorToConsole?: boolean;\n}\n\nexport const DEV_LOG_ENDPOINT = \"/__forge/log\";\n\n/** Response header a batching endpoint sets. Its ABSENCE selects v1 fallback. */\nconst PROTOCOL_HEADER = \"X-Forge-Devlog\";\n\n/** Cap a single line so a runaway loop cannot fill the disk. Matches the endpoints. */\nconst MAX_LINE = 8_000;\n\n/** How long a line may wait for company before it is sent. */\nconst FLUSH_INTERVAL_MS = 250;\n\n/**\n * Per-request ceiling. Deliberately half of the browser's 64 KiB shared\n * `keepalive` in-flight quota: with one request in flight, a batch cannot be\n * the thing that pushes the page over it.\n */\nconst MAX_BATCH_BYTES = 32 * 1024;\n\n/** Buffer ceiling. Past it entries are dropped and counted, never queued forever. */\nconst MAX_BUFFER_ENTRIES = 5_000;\n\nconst original: Partial<Record<Level, (...args: unknown[]) => void>> = {};\nlet installed = false;\n\n// Guards against infinite recursion. The forwarder calls fetch(), and anything\n// that logs inside fetch (an interceptor, a polyfill, a devtools extension)\n// would otherwise re-enter the override forever. Such a line is still mirrored\n// to the real console — it is only forwarding that is suppressed.\nlet forwarding = false;\n\nlet endpointUrl = DEV_LOG_ENDPOINT;\nlet buffer: DevLogPayload[] = [];\nlet bufferedBytes = 0;\nlet flushTimer: ReturnType<typeof setTimeout> | undefined;\nlet requestInFlight = false;\nlet errorFlushQueued = false;\nlet droppedCount = 0;\nlet droppedReason = \"\";\n/** Set for good once an endpoint is known not to understand batches. */\nlet legacyEndpoint = false;\n\n/**\n * Render one console argument as a string.\n *\n * Circular structures and BigInt are the two cases a plain JSON.stringify\n * throws on, and the old fallback to String(value) turned both into\n * \"[object Object]\" — deleting exactly the shape you were trying to read. The\n * replacer keeps the object and names the cycle instead.\n */\nfunction render(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value instanceof Error) {\n return `${value.name}: ${value.message}${\n value.stack ? `\\n${value.stack}` : \"\"\n }`;\n }\n try {\n const seen = new WeakSet<object>();\n return (\n JSON.stringify(value, (_key, val: unknown) => {\n if (typeof val === \"bigint\") return `${val}n`;\n if (typeof val === \"object\" && val !== null) {\n if (seen.has(val)) return \"[Circular]\";\n seen.add(val);\n }\n return val;\n }) ?? String(value)\n );\n } catch {\n // DOM nodes, getters that throw — never let logging throw.\n return String(value);\n }\n}\n\nfunction truncate(msg: string): string {\n return msg.length > MAX_LINE ? `${msg.slice(0, MAX_LINE)}… (truncated)` : msg;\n}\n\nfunction entryBytes(entry: DevLogPayload): number {\n return JSON.stringify(entry).length;\n}\n\n/**\n * Buffer one line and decide whether it can wait.\n *\n * Arguments are rendered HERE rather than at flush time: a console argument is\n * a live object, and by the time a batch leaves 250ms later the array it logged\n * may have been mutated or emptied. The snapshot is the value at the call.\n */\nfunction capture(level: DevLogPayload[\"level\"], args: unknown[]): void {\n if (forwarding) return;\n\n if (buffer.length >= MAX_BUFFER_ENTRIES) {\n droppedCount += 1;\n droppedReason = \"buffer full\";\n return;\n }\n\n const entry: DevLogPayload = {\n level,\n msg: truncate(args.map(render).join(\" \")),\n };\n const wasEmpty = buffer.length === 0;\n buffer.push(entry);\n bufferedBytes += entryBytes(entry);\n\n if (bufferedBytes >= MAX_BATCH_BYTES) {\n flush();\n return;\n }\n\n if (level === \"error\") {\n // An error is what someone is waiting for; it must not sit in a timer. The\n // microtask (rather than a direct flush) lets a same-tick burst — a failing\n // render logging three times — still leave as one request.\n if (!errorFlushQueued) {\n errorFlushQueued = true;\n queueMicrotask(() => {\n errorFlushQueued = false;\n flush();\n });\n }\n return;\n }\n\n if (wasEmpty) armTimer();\n}\n\nfunction armTimer(): void {\n if (flushTimer !== undefined) return;\n flushTimer = setTimeout(() => {\n flushTimer = undefined;\n flush();\n }, FLUSH_INTERVAL_MS);\n}\n\nfunction clearFlushTimer(): void {\n if (flushTimer === undefined) return;\n clearTimeout(flushTimer);\n flushTimer = undefined;\n}\n\n/** Pull entries off the front of the buffer without exceeding MAX_BATCH_BYTES. */\nfunction takeBatch(limit = MAX_BATCH_BYTES): DevLogPayload[] {\n const batch: DevLogPayload[] = [];\n let size = '{\"entries\":[]}'.length;\n while (buffer.length > 0) {\n const entry = buffer[0] as DevLogPayload;\n const cost = entryBytes(entry) + (batch.length > 0 ? 1 : 0);\n // Always take at least one entry: a single line that somehow exceeds the\n // limit must still leave, or it stalls every line behind it forever.\n if (batch.length > 0 && size + cost > limit) break;\n buffer.shift();\n bufferedBytes -= entryBytes(entry);\n batch.push(entry);\n size += cost;\n }\n if (buffer.length === 0) bufferedBytes = 0;\n return batch;\n}\n\n/**\n * Prepend the \"we lost lines\" notice, if any, so it travels with the next batch\n * rather than needing a request of its own.\n */\nfunction drainDroppedNotice(): void {\n if (droppedCount === 0) return;\n const notice: DevLogPayload = {\n level: \"warn\",\n msg: `[forge-devlog] dropped ${droppedCount} lines (${droppedReason})`,\n };\n buffer.unshift(notice);\n bufferedBytes += entryBytes(notice);\n droppedCount = 0;\n droppedReason = \"\";\n}\n\nfunction post(body: string): Promise<Response> {\n // The recursion guard must wrap the CALL, not the promise: a fetch polyfill\n // that logs does so synchronously from inside fetch().\n forwarding = true;\n try {\n return fetch(endpointUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body,\n // A log emitted during unload (the interesting case for a crash on\n // navigation) is cancelled without this.\n keepalive: true,\n // Never let log forwarding trip a credentials or CORS policy.\n credentials: \"omit\",\n });\n } finally {\n forwarding = false;\n }\n}\n\n/**\n * Send one request's worth of buffered output, if nothing is in flight.\n *\n * The single-flight rule is what guarantees the dev server prints lines in the\n * order they were logged, and it doubles as backpressure: a slow endpoint makes\n * batches bigger rather than making requests pile up.\n */\nfunction flush(): void {\n if (requestInFlight) return;\n drainDroppedNotice();\n if (buffer.length === 0) return;\n clearFlushTimer();\n\n const batch = legacyEndpoint ? takeBatch(0) : takeBatch();\n if (batch.length === 0) return;\n\n const body = legacyEndpoint\n ? JSON.stringify(batch[0])\n : JSON.stringify({ entries: batch } satisfies DevLogBatch);\n\n requestInFlight = true;\n post(body).then(\n (response) => {\n requestInFlight = false;\n if (!response.ok) {\n countDropped(batch.length, `endpoint returned ${response.status}`);\n } else if (!legacyEndpoint && !response.headers.get(PROTOCOL_HEADER)) {\n adoptLegacyMode(batch);\n }\n if (buffer.length > 0 || droppedCount > 0) flush();\n },\n () => {\n requestInFlight = false;\n countDropped(batch.length, \"request failed\");\n if (buffer.length > 0) flush();\n },\n );\n}\n\nfunction countDropped(count: number, reason: string): void {\n droppedCount += count;\n droppedReason = reason;\n}\n\n/**\n * A 2xx with no protocol header came from an endpoint written before batching.\n * It parsed `{entries:[...]}` as a v1 body, found no `msg`, and printed one\n * empty line — so this batch is lost unless it is re-sent one line at a time,\n * and so is everything after it.\n */\nfunction adoptLegacyMode(lost: DevLogPayload[]): void {\n legacyEndpoint = true;\n const notice: DevLogPayload = {\n level: \"warn\",\n msg:\n \"[forge-devlog] this dev server's /__forge/log endpoint predates batched \" +\n \"posts; update it (forge skill: debug) — falling back to one request per line\",\n };\n buffer.unshift(notice, ...lost);\n bufferedBytes += [notice, ...lost].reduce((n, e) => n + entryBytes(e), 0);\n}\n\n/**\n * Last-chance flush on page teardown.\n *\n * fetch — even with keepalive — is not reliable here, and an async flush is\n * hopeless: the event loop may not run again. sendBeacon hands the bytes to the\n * browser to deliver after the document is gone, which is precisely the case\n * where the last few log lines explain what happened.\n */\nfunction flushOnUnload(): void {\n drainDroppedNotice();\n if (buffer.length === 0) return;\n\n const canBeacon =\n typeof navigator !== \"undefined\" &&\n typeof navigator.sendBeacon === \"function\";\n if (!canBeacon) {\n // No beacon: keepalive fetch is the only remaining option, and one request\n // has a better chance of leaving than a queue of them.\n flush();\n return;\n }\n\n forwarding = true;\n try {\n while (buffer.length > 0) {\n const batch = legacyEndpoint ? takeBatch(0) : takeBatch();\n const body = legacyEndpoint\n ? JSON.stringify(batch[0])\n : JSON.stringify({ entries: batch } satisfies DevLogBatch);\n // text/plain is not a decoration: sendBeacon with application/json is a\n // non-simple request and would need a CORS preflight it cannot make. The\n // endpoints parse the body regardless of Content-Type for this reason.\n const blob = new Blob([body], { type: \"text/plain;charset=UTF-8\" });\n if (!navigator.sendBeacon(endpointUrl, blob)) {\n // The beacon queue is full (64 KiB per origin). Nothing later will fit\n // either, so stop and account for what is left.\n countDropped(batch.length + buffer.length, \"beacon queue full\");\n buffer = [];\n bufferedBytes = 0;\n return;\n }\n }\n } finally {\n forwarding = false;\n }\n}\n\nfunction onWindowError(event: ErrorEvent): void {\n capture(\"error\", [\n event.error ??\n `${event.message} @ ${event.filename}:${event.lineno}:${event.colno}`,\n ]);\n}\n\nfunction onRejection(event: PromiseRejectionEvent): void {\n capture(\"error\", [\"unhandled rejection:\", event.reason]);\n}\n\nlet errorHandler: ((e: ErrorEvent) => void) | undefined;\nlet rejectionHandler: ((e: PromiseRejectionEvent) => void) | undefined;\nlet pageHideHandler: (() => void) | undefined;\nlet visibilityHandler: (() => void) | undefined;\n\n/**\n * Mirror console output and uncaught errors to the dev server, which prints\n * them into .forge/logs/<env>/frontend_<name>.log.\n *\n * The window listeners are the point of the feature as much as the console\n * override is: an uncaught TypeError or a rejected promise produces no console\n * call of its own, and those are exactly the failures worth seeing.\n *\n * Safe to call more than once; the second call is a no-op.\n */\nexport function installDevLogging(options: DevLoggingOptions): void {\n // `dev` is read off `options` rather than destructured with a default, and\n // checked FIRST. A bundler constant-folds `import.meta.env.DEV` to false at\n // the CALL SITE and can then drop the argument entirely, leaving a bare\n // `installDevLogging({})` — with a defaulted `dev` that call would install\n // the override in a production bundle. `options?.dev !== true` is therefore\n // fail-closed: absent, undefined, or anything non-true means do nothing.\n if (options?.dev !== true) return;\n if (installed) return;\n if (typeof window === \"undefined\") return; // SSR / prerender pass\n\n const { endpoint = DEV_LOG_ENDPOINT, mirrorToConsole = true } = options;\n installed = true;\n endpointUrl = endpoint;\n buffer = [];\n bufferedBytes = 0;\n droppedCount = 0;\n droppedReason = \"\";\n legacyEndpoint = false;\n requestInFlight = false;\n\n for (const level of LEVELS) {\n // Keep the ORIGINAL reference, not a bound copy: uninstall must restore\n // console.log to the identical function it replaced, so a second consumer\n // holding that reference (or a test asserting on it) sees no difference.\n const previous = console[level] as (...args: unknown[]) => void;\n original[level] = previous;\n console[level] = (...args: unknown[]) => {\n if (mirrorToConsole) previous.apply(console, args);\n capture(level, args);\n };\n }\n\n errorHandler = (e) => onWindowError(e);\n rejectionHandler = (e) => onRejection(e);\n pageHideHandler = () => flushOnUnload();\n window.addEventListener(\"error\", errorHandler);\n window.addEventListener(\"unhandledrejection\", rejectionHandler);\n window.addEventListener(\"pagehide\", pageHideHandler);\n\n if (typeof document !== \"undefined\") {\n // visibilitychange→hidden is the only teardown signal mobile Safari\n // reliably fires; pagehide alone loses the whole buffer there.\n visibilityHandler = () => {\n if (document.visibilityState === \"hidden\") flushOnUnload();\n };\n document.addEventListener(\"visibilitychange\", visibilityHandler);\n }\n}\n\n/** Restore the original console methods and remove the window listeners. */\nexport function uninstallDevLogging(): void {\n if (!installed) return;\n\n // Flush before restoring: whatever is buffered was logged while this was\n // installed, and a teardown is no reason to lose it.\n clearFlushTimer();\n flush();\n\n for (const level of LEVELS) {\n const previous = original[level];\n if (previous) console[level] = previous;\n delete original[level];\n }\n if (errorHandler) window.removeEventListener(\"error\", errorHandler);\n if (rejectionHandler)\n window.removeEventListener(\"unhandledrejection\", rejectionHandler);\n if (pageHideHandler) window.removeEventListener(\"pagehide\", pageHideHandler);\n if (visibilityHandler && typeof document !== \"undefined\")\n document.removeEventListener(\"visibilitychange\", visibilityHandler);\n errorHandler = undefined;\n rejectionHandler = undefined;\n pageHideHandler = undefined;\n visibilityHandler = undefined;\n installed = false;\n}\n\n/** Whether the console override is currently installed. Exposed for tests. */\nexport function devLoggingInstalled(): boolean {\n return installed;\n}\n"]}
|
package/dist/error-boundary.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ interface Props {
|
|
|
7
7
|
children: ReactNode;
|
|
8
8
|
/** Custom fallback UI. Defaults to DefaultErrorFallback. */
|
|
9
9
|
fallback?: (props: FallbackProps) => ReactNode;
|
|
10
|
-
/**
|
|
10
|
+
/** Extra reporter hook, called after the error is recorded with the browser telemetry SDK. */
|
|
11
11
|
onError?: (error: Error, info: ErrorInfo) => void;
|
|
12
12
|
/** When any value in this array changes, the boundary resets. */
|
|
13
13
|
resetKeys?: unknown[];
|
package/dist/error-boundary.js
CHANGED
|
@@ -8,6 +8,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
8
8
|
// dashboard widget, a <Resource> table — so one crashing panel degrades to a
|
|
9
9
|
// small fallback instead of taking the whole route (or the app) white.
|
|
10
10
|
import { Component, } from "react";
|
|
11
|
+
import { reportException } from "./error-reporter.js";
|
|
12
|
+
import { userMessage } from "./errors.js";
|
|
11
13
|
export class RuntimeErrorBoundary extends Component {
|
|
12
14
|
constructor(props) {
|
|
13
15
|
super(props);
|
|
@@ -17,8 +19,13 @@ export class RuntimeErrorBoundary extends Component {
|
|
|
17
19
|
return { error };
|
|
18
20
|
}
|
|
19
21
|
componentDidCatch(error, info) {
|
|
20
|
-
// Always log
|
|
22
|
+
// Always log, and record with the browser telemetry SDK (a no-op when
|
|
23
|
+
// none is running); the app can additionally forward to a sink via onError.
|
|
21
24
|
console.error("[runtime] error boundary caught:", error, info);
|
|
25
|
+
reportException(error, {
|
|
26
|
+
"react.component_stack": info.componentStack ?? "",
|
|
27
|
+
"error.handled_by": "RuntimeErrorBoundary",
|
|
28
|
+
});
|
|
22
29
|
this.props.onError?.(error, info);
|
|
23
30
|
}
|
|
24
31
|
componentDidUpdate(prev) {
|
|
@@ -58,6 +65,6 @@ export function DefaultErrorFallback({ error, reset, compact, }) {
|
|
|
58
65
|
if (compact) {
|
|
59
66
|
return (_jsxs("div", { role: "alert", className: "flex items-center justify-between gap-3 rounded-md border border-danger-border bg-danger-surface px-3 py-2 text-sm text-danger-ink", children: [_jsx("span", { className: "truncate", children: "Couldn't load this section." }), _jsx("button", { type: "button", onClick: reset, className: "shrink-0 font-medium text-danger underline hover:text-danger-hover", children: "Retry" })] }));
|
|
60
67
|
}
|
|
61
|
-
return (_jsxs("div", { role: "alert", className: "flex min-h-[12rem] flex-col items-center justify-center gap-3 rounded-lg border border-danger-border bg-danger-surface p-8 text-center", children: [_jsx("h2", { className: "text-lg font-semibold text-danger-ink", children: "Something went wrong" }), _jsx("p", { className: "max-w-md text-sm text-danger-ink", children: "This section ran into an unexpected error. You can try again \u2014 the rest of the app is still working." }), _jsx("p", { className: "max-w-md
|
|
68
|
+
return (_jsxs("div", { role: "alert", className: "flex min-h-[12rem] flex-col items-center justify-center gap-3 rounded-lg border border-danger-border bg-danger-surface p-8 text-center", children: [_jsx("h2", { className: "text-lg font-semibold text-danger-ink", children: "Something went wrong" }), _jsx("p", { className: "max-w-md text-sm text-danger-ink", children: "This section ran into an unexpected error. You can try again \u2014 the rest of the app is still working." }), _jsx("p", { className: "max-w-md text-sm text-danger-ink", children: userMessage(error) }), _jsx("button", { type: "button", onClick: reset, className: "mt-1 rounded-md bg-danger px-4 py-2 text-sm font-medium text-on-danger hover:bg-danger-hover", children: "Try again" })] }));
|
|
62
69
|
}
|
|
63
70
|
//# sourceMappingURL=error-boundary.js.map
|