@frondruntime/devtools 0.5.0 → 0.6.0-rc.1

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/src/cause.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import { Diagnostics } from "@frondruntime/core";
2
- import type { ErrorDescriptor } from "./descriptors.ts";
2
+ import {
3
+ describeNonFiniteNumber,
4
+ type ErrorDescriptor,
5
+ setField,
6
+ UNREADABLE,
7
+ } from "./descriptors.ts";
3
8
  import type { EncodePolicy } from "./policy.ts";
4
9
 
5
10
  /**
@@ -124,21 +129,10 @@ export function describeError(
124
129
  });
125
130
 
126
131
  if (full === undefined) {
127
- // `path` and `valueKind` are the two frame fields that describe the app's
128
- // data rather than the runtime's: a path is a list of the app's own key
129
- // names, and a value kind says whether what failed was an array or an
130
- // object. Both are shape by any definition, so `"none"` — whose whole
131
- // contract is that no shape crosses — drops them. The message still
132
- // crosses at every policy; that is deliberate, and it is the one thing a
133
- // reader cannot diagnose without.
134
- const shed = policy === "none" ? { path: undefined, valueKind: undefined } : {};
135
-
136
132
  return {
137
133
  _: "error",
138
134
  message: rootMessage(frames),
139
- causes: frames.map((frame) =>
140
- compact({ ...frame, ...shed, stack: undefined, preview: undefined })
141
- ),
135
+ causes: reduceChain(frames, policy),
142
136
  };
143
137
  }
144
138
 
@@ -151,35 +145,156 @@ export function describeError(
151
145
  // app object whose payload points back at that object is the ordinary shape of
152
146
  // a wrapped failure, and un-marking it there would let the walk descend into
153
147
  // the ancestor instead of naming the cycle.
148
+ //
149
+ // Which links this call inserted is a bit per link, in place of an array of
150
+ // them: there are at most `CAUSE_MAX_DEPTH` links, well under 31.
154
151
  const links = causeValues(value, frames.length);
155
- const marked = links.filter(
156
- (link): link is object => typeof link === "object" && link !== null && !full.seen.has(link)
157
- );
152
+ let marked = 0;
158
153
 
159
- for (const link of marked) {
160
- full.seen.add(link);
154
+ for (let index = 0; index < links.length; index++) {
155
+ const link = links[index];
156
+
157
+ if (typeof link === "object" && link !== null && !full.seen.has(link)) {
158
+ full.seen.add(link);
159
+ marked |= 1 << index;
160
+ }
161
161
  }
162
162
 
163
163
  try {
164
- return {
165
- _: "error",
166
- message: rootMessage(frames),
167
- causes: frames.map((frame, index) =>
168
- compact({
169
- ...frame,
170
- preview: undefined,
171
- stack: frame.stack === undefined ? undefined : abridgeStack(frame.stack),
172
- fields: errorFields(links[index], full.encodeValue),
173
- })
174
- ),
175
- };
164
+ const causes = reduceChain(frames, policy);
165
+
166
+ for (let index = 0; index < causes.length; index++) {
167
+ const fields = errorFields(links[index], full.encodeValue);
168
+
169
+ if (fields !== undefined) {
170
+ // Index-aligned: `reduceChain` keeps one frame per frame it is given.
171
+ (causes[index] as Record<string, unknown>)["fields"] = fields;
172
+ }
173
+ }
174
+
175
+ return { _: "error", message: rootMessage(frames), causes };
176
176
  } finally {
177
- for (const link of marked) {
178
- full.seen.delete(link);
177
+ for (let index = 0; index < links.length; index++) {
178
+ if ((marked & (1 << index)) !== 0) {
179
+ full.seen.delete(links[index] as object);
180
+ }
179
181
  }
180
182
  }
181
183
  }
182
184
 
185
+ /**
186
+ * A chain of frames, each cut down by {@link reduceFrame}.
187
+ *
188
+ * Indexed loops rather than `map`, here and in `reduceFrame`: this runs once
189
+ * per failure in every record, nested once per member of an aggregate, and on
190
+ * Hermes a callback and an entry array per frame are a cost worth not paying.
191
+ */
192
+ function reduceChain(
193
+ chain: ReadonlyArray<Diagnostics.SerializedCauseFrame>,
194
+ policy: EncodePolicy
195
+ ): Array<Record<string, unknown>> {
196
+ const reduced: Array<Record<string, unknown>> = [];
197
+
198
+ for (let index = 0; index < chain.length; index++) {
199
+ reduced.push(reduceFrame(chain[index] as Diagnostics.SerializedCauseFrame, policy));
200
+ }
201
+
202
+ return reduced;
203
+ }
204
+
205
+ /**
206
+ * One frame, cut down to what its policy lets cross.
207
+ *
208
+ * The one place a frame is reduced, so the frames of an aggregate's member
209
+ * chains, which core nests under `failures`, get exactly what the chain that
210
+ * holds them gets. A member frame comes from the same walk as any other and
211
+ * carries the same `preview`, `stack` and absent keys.
212
+ *
213
+ * `path` and `valueKind` are the two frame fields that describe the app's data
214
+ * rather than the runtime's: a path is a list of the app's own key names, and a
215
+ * value kind says whether what failed was an array or an object. Both are shape
216
+ * by any definition, so `"none"` — whose whole contract is that no shape
217
+ * crosses — drops them. The message still crosses at every policy; that is
218
+ * deliberate, and it is the one thing a reader cannot diagnose without.
219
+ *
220
+ * `fields` is not added here: it needs the value behind the frame, which only
221
+ * the outermost chain keeps (see {@link causeValues}).
222
+ */
223
+ function reduceFrame(
224
+ frame: Diagnostics.SerializedCauseFrame,
225
+ policy: EncodePolicy
226
+ ): Record<string, unknown> {
227
+ const out: Record<string, unknown> = {};
228
+
229
+ // `Object.prototype.hasOwnProperty.call` rather than `Object.hasOwn`, which
230
+ // Hermes does not ship.
231
+ for (const key in frame) {
232
+ if (!Object.prototype.hasOwnProperty.call(frame, key)) {
233
+ continue;
234
+ }
235
+
236
+ const value = (frame as Record<string, unknown>)[key];
237
+
238
+ if (value === undefined || key === "preview") {
239
+ continue;
240
+ }
241
+
242
+ if (key === "stack") {
243
+ if (policy === "full" && typeof value === "string") {
244
+ out[key] = abridgeStack(value);
245
+ }
246
+ } else if (key === "path") {
247
+ if (policy !== "none") {
248
+ out[key] = Array.isArray(value) ? pathOf(value) : value;
249
+ }
250
+ } else if (key === "valueKind") {
251
+ if (policy !== "none") {
252
+ out[key] = value;
253
+ }
254
+ } else if (key === "failures" && Array.isArray(value)) {
255
+ const chains: ReadonlyArray<ReadonlyArray<Diagnostics.SerializedCauseFrame>> = value;
256
+ const reduced: Array<Array<Record<string, unknown>>> = [];
257
+
258
+ for (let index = 0; index < chains.length; index++) {
259
+ reduced.push(
260
+ reduceChain(chains[index] as ReadonlyArray<Diagnostics.SerializedCauseFrame>, policy)
261
+ );
262
+ }
263
+
264
+ out[key] = reduced;
265
+ } else if (key === "cancellation" && typeof value === "object" && value !== null) {
266
+ // Core fills both of its keys whether the failure had them or not.
267
+ out[key] = compact(value as Record<string, unknown>);
268
+ } else if (typeof value === "number") {
269
+ out[key] = value - value === 0 ? value : describeNonFiniteNumber(value);
270
+ } else {
271
+ out[key] = value;
272
+ }
273
+ }
274
+
275
+ return out;
276
+ }
277
+
278
+ /**
279
+ * A frame's `path`, with no holes.
280
+ *
281
+ * Core writes each key name as a string and an `undefined` one as
282
+ * `"undefined"`, but keeps a hole where the failure's own list had one. A hole
283
+ * reads as `undefined`, so it goes out as core writes that: the codec rejects a
284
+ * hole as it rejects `undefined`, and one would fail the whole batch.
285
+ */
286
+ function pathOf(path: ReadonlyArray<unknown>): Array<unknown> {
287
+ const out: Array<unknown> = [];
288
+
289
+ for (let index = 0; index < path.length; index++) {
290
+ const entry = path[index];
291
+
292
+ out.push(entry === undefined ? "undefined" : entry);
293
+ }
294
+
295
+ return out;
296
+ }
297
+
183
298
  /**
184
299
  * A stack, selected by frame instead of cut by character.
185
300
  *
@@ -203,7 +318,14 @@ export function describeError(
203
318
  */
204
319
  function abridgeStack(stack: string): string {
205
320
  const lines = stack.split("\n");
206
- const first = lines.findIndex(isStackFrame);
321
+ let first = -1;
322
+
323
+ for (let index = 0; index < lines.length; index++) {
324
+ if (isStackFrame(lines[index] as string)) {
325
+ first = index;
326
+ break;
327
+ }
328
+ }
207
329
 
208
330
  if (first === -1) {
209
331
  return stack.length <= FULL_CAUSE_STACK_LENGTH
@@ -211,31 +333,59 @@ function abridgeStack(stack: string): string {
211
333
  : `${stack.slice(0, FULL_CAUSE_STACK_LENGTH)}…`;
212
334
  }
213
335
 
214
- // Everything above the first frame is the error's own header, kept whole: it
215
- // is the name and message, which is the part a reader reads first.
216
- const header = lines.slice(0, first);
336
+ // One pass over everything below the header, in loops rather than callbacks
337
+ // and spreads, for the reason `reduceChain` gives.
338
+ //
217
339
  // Counted against everything below the header, not just the lines the two
218
340
  // patterns recognize. JSC writes frames this cannot parse — `promiseReactionJob@[native code]`
219
341
  // has no `:line:col` — and dropping those out of the denominator would let the
220
342
  // trace claim it accounted for what it removed while quietly removing more.
221
- const body = lines.slice(first).filter((line) => line.trim() !== "");
222
- const frames = body.filter(isStackFrame);
223
- const own = frames.filter((line) => !LIBRARY_STACK_FRAME.test(line));
224
- const kept = (own.length === 0 ? frames.slice(0, LIBRARY_ONLY_STACK_FRAMES) : own).slice(
225
- 0,
226
- KEPT_STACK_FRAMES
227
- );
228
- const dropped = body.length - kept.length;
229
-
230
- if (dropped === 0) {
231
- return [...header, ...kept].join("\n");
343
+ let body = 0;
344
+ // Only as many of each as can be kept: the top library frames for a trace
345
+ // with no app frames, and the first app frames otherwise.
346
+ const leading: Array<string> = [];
347
+ const own: Array<string> = [];
348
+
349
+ for (let index = first; index < lines.length; index++) {
350
+ const line = lines[index] as string;
351
+
352
+ if (line.trim() === "") {
353
+ continue;
354
+ }
355
+
356
+ body++;
357
+
358
+ if (!isStackFrame(line)) {
359
+ continue;
360
+ }
361
+
362
+ if (leading.length < LIBRARY_ONLY_STACK_FRAMES) {
363
+ leading.push(line);
364
+ }
365
+
366
+ if (own.length < KEPT_STACK_FRAMES && !LIBRARY_STACK_FRAME.test(line)) {
367
+ own.push(line);
368
+ }
232
369
  }
233
370
 
234
- return [
235
- ...header,
236
- ...kept,
237
- ` … ${dropped} frame${dropped === 1 ? "" : "s"} dropped: library internals, unrecognized lines, and any past the first ${KEPT_STACK_FRAMES}`,
238
- ].join("\n");
371
+ const kept = own.length === 0 ? leading : own;
372
+ // Everything above the first frame is the error's own header, kept whole: it
373
+ // is the name and message, which is the part a reader reads first.
374
+ const out = lines.slice(0, first);
375
+
376
+ for (let index = 0; index < kept.length; index++) {
377
+ out.push(kept[index] as string);
378
+ }
379
+
380
+ const dropped = body - kept.length;
381
+
382
+ if (dropped !== 0) {
383
+ out.push(
384
+ ` … ${dropped} frame${dropped === 1 ? "" : "s"} dropped: library internals, unrecognized lines, and any past the first ${KEPT_STACK_FRAMES}`
385
+ );
386
+ }
387
+
388
+ return out.join("\n");
239
389
  }
240
390
 
241
391
  function isStackFrame(line: string): boolean {
@@ -311,19 +461,39 @@ function errorFields(value: unknown, encodeValue: (value: unknown) => unknown):
311
461
  return encodeValue(value);
312
462
  }
313
463
 
314
- const own: Record<string, unknown> = {};
464
+ let keys: ReadonlyArray<string>;
315
465
 
316
466
  try {
317
- for (const key of Object.keys(value)) {
318
- if (!NAMED_ERROR_KEYS.has(key)) {
319
- own[key] = (value as Record<string, unknown>)[key];
320
- }
321
- }
467
+ keys = Object.keys(value);
322
468
  } catch {
323
469
  return undefined;
324
470
  }
325
471
 
326
- return Object.keys(own).length === 0 ? undefined : encodeValue(own);
472
+ const own: Record<string, unknown> = {};
473
+ let copied = 0;
474
+
475
+ // Each read guarded on its own, like the payload walk this hands off to: a
476
+ // getter that throws costs its own field rather than every readable one.
477
+ for (let index = 0; index < keys.length; index++) {
478
+ const key = keys[index] as string;
479
+
480
+ if (NAMED_ERROR_KEYS.has(key)) {
481
+ continue;
482
+ }
483
+
484
+ let field: unknown;
485
+
486
+ try {
487
+ field = (value as Record<string, unknown>)[key];
488
+ } catch {
489
+ field = UNREADABLE;
490
+ }
491
+
492
+ setField(own, key, field);
493
+ copied++;
494
+ }
495
+
496
+ return copied === 0 ? undefined : encodeValue(own);
327
497
  }
328
498
 
329
499
  /**
@@ -352,14 +522,21 @@ function rootMessage(frames: ReadonlyArray<Diagnostics.SerializedCauseFrame>): s
352
522
  /**
353
523
  * Drops absent keys.
354
524
  *
355
- * A cause frame declares every field any failure might carry, so most of them
356
- * are `undefined` on any given one. JSON would drop those anyway; doing it here
357
- * means the in-memory record the hub retains and renders matches the wire.
525
+ * A cancellation declares both of its fields whether the failure had them or
526
+ * not, so either can be `undefined`, and the transport's JSON check rejects an
527
+ * `undefined` value rather than dropping it.
358
528
  */
359
- function compact(frame: Record<string, unknown>): Record<string, unknown> {
529
+ export function compact(record: Record<string, unknown>): Record<string, unknown> {
360
530
  const out: Record<string, unknown> = {};
361
531
 
362
- for (const [key, value] of Object.entries(frame)) {
532
+ for (const key in record) {
533
+ if (!Object.prototype.hasOwnProperty.call(record, key)) {
534
+ continue;
535
+ }
536
+
537
+ // Read once: a getter read twice can answer differently the second time.
538
+ const value = record[key];
539
+
363
540
  if (value !== undefined) {
364
541
  out[key] = value;
365
542
  }
@@ -41,8 +41,8 @@ export type ErrorDescriptor = {
41
41
  * A marker that survived where a value did not.
42
42
  *
43
43
  * Only ever emitted alongside real data — at `"full"`, and at `"shape"` for a
44
- * string long enough to be cut — which is why these stay objects while the
45
- * `"shape"` vocabulary is strings. A reader looking at real values has to be
44
+ * string long enough to be cut or a number with no JSON form — which is why
45
+ * these stay objects while the `"shape"` vocabulary is strings. A reader looking at real values has to be
46
46
  * able to tell a marker from one of them, and `{_: …}` is that tell.
47
47
  *
48
48
  * `_` rather than `_tag` so a descriptor is never mistaken for a domain tagged
@@ -65,7 +65,8 @@ export type ShapeDescriptor =
65
65
  /**
66
66
  * Collections, at `"full"` only — `"shape"` names them `Map(3)` and `Set(3)`.
67
67
  * `size` is the collection's real size; `entries` and `values` are what
68
- * survived the entry bound, so the two disagree when one was hit.
68
+ * survived the entry bound, and end in an `"elided"` marker when it cut them
69
+ * — in a map, as both halves of a last pair.
69
70
  */
70
71
  | {
71
72
  readonly _: "map";
@@ -105,3 +106,69 @@ export const WITHHELD = "withheld";
105
106
  * hole in the policy rather than a diagnostic.
106
107
  */
107
108
  export const UNREADABLE = { _: "opaque", type: "unreadable" } satisfies ShapeDescriptor;
109
+
110
+ const NOT_A_NUMBER = { _: "opaque", type: "number:NaN" } satisfies ShapeDescriptor;
111
+ const POSITIVE_INFINITY = { _: "opaque", type: "number:Infinity" } satisfies ShapeDescriptor;
112
+ const NEGATIVE_INFINITY = { _: "opaque", type: "number:-Infinity" } satisfies ShapeDescriptor;
113
+
114
+ /**
115
+ * A number JSON cannot carry, said by name.
116
+ *
117
+ * Passing `NaN` or an infinity through as a number fails the transport, not
118
+ * just the reader: the RPC codec validates every value as JSON and rejects the
119
+ * whole event batch or snapshot reply that holds one. And `JSON.stringify`
120
+ * alone would write `null`, which a reader cannot tell from a field that really
121
+ * was `null`. Both encoders emit the same three markers so a value reads the
122
+ * same at either policy.
123
+ *
124
+ * Callers test finiteness themselves and reach this only for the non-finite
125
+ * case, so a finite number pays no call. Shared constants, like
126
+ * {@link UNREADABLE}, so marking one allocates nothing.
127
+ */
128
+ export function describeNonFiniteNumber(value: number): ShapeDescriptor {
129
+ return value > 0 ? POSITIVE_INFINITY : value < 0 ? NEGATIVE_INFINITY : NOT_A_NUMBER;
130
+ }
131
+
132
+ /**
133
+ * A class instance's name, or `"object"` when it has none it will give up.
134
+ *
135
+ * Guarded on its own, because both encoders read it after deciding what else
136
+ * to send: a `constructor` or `name` getter that throws would otherwise reach
137
+ * the catch around the whole value and trade its readable fields, or its
138
+ * label, for one marker.
139
+ *
140
+ * Checked for being a string, because nothing else makes it one: the name is
141
+ * read off the app's own prototype, and a `name` of `Infinity` there would
142
+ * otherwise fail the transport for the whole batch.
143
+ */
144
+ export function typeName(value: object): string {
145
+ try {
146
+ const name = (value.constructor as { readonly name?: unknown } | undefined)?.name;
147
+
148
+ return typeof name === "string" ? name : "object";
149
+ } catch {
150
+ return "object";
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Writes `key` onto an encoded record as an own data property.
156
+ *
157
+ * Assignment is not that for one key: `out["__proto__"] = x` sets the record's
158
+ * prototype, which drops the field and leaves an object the transport's JSON
159
+ * check rejects, failing the whole batch. `JSON.parse` makes `__proto__` an
160
+ * ordinary own key, so an app holding a parsed payload can hold one. Only that
161
+ * key takes the slow path; every other key is a plain assignment.
162
+ */
163
+ export function setField(record: Record<string, unknown>, key: string, value: unknown): void {
164
+ if (key === "__proto__") {
165
+ Object.defineProperty(record, key, {
166
+ value,
167
+ enumerable: true,
168
+ writable: true,
169
+ configurable: true,
170
+ });
171
+ } else {
172
+ record[key] = value;
173
+ }
174
+ }