@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/full.ts CHANGED
@@ -1,5 +1,11 @@
1
1
  import { describeError } from "./cause.ts";
2
- import { type ShapeDescriptor, UNREADABLE } from "./descriptors.ts";
2
+ import {
3
+ describeNonFiniteNumber,
4
+ type ShapeDescriptor,
5
+ setField,
6
+ typeName,
7
+ UNREADABLE,
8
+ } from "./descriptors.ts";
3
9
 
4
10
  /**
5
11
  * Bounds for `"full"`. Termination guards, not a byte budget.
@@ -63,10 +69,14 @@ export function describeFull(
63
69
  }
64
70
 
65
71
  switch (typeof value) {
66
- case "boolean":
67
- case "number": {
72
+ case "boolean": {
68
73
  return value;
69
74
  }
75
+ // See `describeShape` for the finiteness test: one subtraction, so a finite
76
+ // number takes the same path it always did.
77
+ case "number": {
78
+ return value - value === 0 ? value : describeNonFiniteNumber(value);
79
+ }
70
80
  // Not JSON-safe, and no rendering of them is more useful than saying what
71
81
  // they were.
72
82
  case "bigint": {
@@ -75,7 +85,7 @@ export function describeFull(
75
85
  case "function": {
76
86
  return {
77
87
  _: "opaque",
78
- type: `function:${(value as { readonly name?: string }).name || "anonymous"}`,
88
+ type: `function:${functionName(value)}`,
79
89
  } satisfies ShapeDescriptor;
80
90
  }
81
91
  case "symbol": {
@@ -135,7 +145,12 @@ function describeFullStructureUnguarded(
135
145
  }
136
146
 
137
147
  if (value instanceof Date) {
138
- return value.toISOString();
148
+ // An invalid date throws here and reaches the guard around this walk as
149
+ // unreadable. An override can instead return anything, and a non-string
150
+ // fails the transport for the whole batch, so it reads the same way.
151
+ const iso: unknown = value.toISOString();
152
+
153
+ return typeof iso === "string" ? iso : UNREADABLE;
139
154
  }
140
155
 
141
156
  if (depth >= FULL_MAX_DEPTH) {
@@ -146,46 +161,110 @@ function describeFullStructureUnguarded(
146
161
 
147
162
  try {
148
163
  if (Array.isArray(value)) {
149
- const kept = value.slice(0, FULL_MAX_ENTRIES);
150
- const encoded: Array<unknown> = kept.map((entry) =>
151
- describeFull(entry, depth + 1, seen, budget)
152
- );
153
-
154
- if (value.length > FULL_MAX_ENTRIES) {
155
- encoded.push({
156
- _: "elided",
157
- by: "entries",
158
- length: value.length,
159
- } satisfies ShapeDescriptor);
164
+ const length = arrayLength(value);
165
+ // `length` is read through the array's own getter, which a proxy can
166
+ // answer with anything: a non-number or `NaN` reads as empty, and an
167
+ // infinity as past the bound.
168
+ const count =
169
+ typeof length === "number" && length > 0
170
+ ? Math.min(Math.floor(length), FULL_MAX_ENTRIES)
171
+ : 0;
172
+ const encoded: Array<unknown> = [];
173
+
174
+ // Indexed, with each read guarded on its own: a hole reads as `undefined`
175
+ // and goes out as `null`, where a hole left in place fails the transport
176
+ // for the whole batch, and an entry whose read throws costs that entry
177
+ // rather than every readable one beside it.
178
+ for (let index = 0; index < count; index++) {
179
+ let entry: unknown;
180
+
181
+ try {
182
+ entry = value[index];
183
+ } catch {
184
+ encoded.push(UNREADABLE);
185
+ continue;
186
+ }
187
+
188
+ encoded.push(describeFull(entry, depth + 1, seen, budget));
189
+ }
190
+
191
+ if (typeof length === "number" && length > FULL_MAX_ENTRIES) {
192
+ encoded.push(entriesCut(finiteNumber(length)));
160
193
  }
161
194
 
162
195
  return encoded;
163
196
  }
164
197
 
198
+ // Read through the iterator protocol, as a spread reads them, with every
199
+ // read that can run the app's code guarded on its own: `size`, each step,
200
+ // its `done` and its `value`, and each half of a map's pair. A subclass can
201
+ // override any of them, and a throw in one should not cost what the others
202
+ // read. The walk of what a step held has guards of its own. The iterator is
203
+ // taken outside the guards, because a value that cannot even give one up
204
+ // has nothing readable at all.
165
205
  if (value instanceof Map) {
166
- return {
167
- _: "map",
168
- entries: [...value.entries()]
169
- .slice(0, FULL_MAX_ENTRIES)
170
- .map(
171
- ([key, entry]) =>
172
- [
173
- describeFull(key, depth + 1, seen, budget),
174
- describeFull(entry, depth + 1, seen, budget),
175
- ] as const
176
- ),
177
- size: value.size,
178
- } satisfies ShapeDescriptor;
206
+ const walk = readSteps(value.entries());
207
+ const entries: Array<readonly [unknown, unknown]> = [];
208
+
209
+ for (let index = 0; index < walk.values.length; index++) {
210
+ const pair = walk.values[index];
211
+
212
+ entries.push([
213
+ describeStepValue(halfOf(pair, 0), depth, seen, budget),
214
+ describeStepValue(halfOf(pair, 1), depth, seen, budget),
215
+ ]);
216
+ }
217
+
218
+ const reported = collectionSize(value);
219
+ const size = reported ?? entries.length;
220
+
221
+ // Each marker is a pair, like every other entry, so a reader walking
222
+ // pairs meets it where the entries stopped.
223
+ switch (walk.end) {
224
+ case "broken": {
225
+ entries.push([UNREADABLE, UNREADABLE]);
226
+ break;
227
+ }
228
+ case "cut": {
229
+ const marker = entriesCut(reported);
230
+
231
+ entries.push([marker, marker]);
232
+ break;
233
+ }
234
+ case "done": {
235
+ break;
236
+ }
237
+ }
238
+
239
+ return { _: "map", entries, size } satisfies ShapeDescriptor;
179
240
  }
180
241
 
181
242
  if (value instanceof Set) {
182
- return {
183
- _: "set",
184
- values: [...value.values()]
185
- .slice(0, FULL_MAX_ENTRIES)
186
- .map((entry) => describeFull(entry, depth + 1, seen, budget)),
187
- size: value.size,
188
- } satisfies ShapeDescriptor;
243
+ const walk = readSteps(value.values());
244
+ const values: Array<unknown> = [];
245
+
246
+ for (let index = 0; index < walk.values.length; index++) {
247
+ values.push(describeStepValue(walk.values[index], depth, seen, budget));
248
+ }
249
+
250
+ const reported = collectionSize(value);
251
+ const size = reported ?? values.length;
252
+
253
+ switch (walk.end) {
254
+ case "broken": {
255
+ values.push(UNREADABLE);
256
+ break;
257
+ }
258
+ case "cut": {
259
+ values.push(entriesCut(reported));
260
+ break;
261
+ }
262
+ case "done": {
263
+ break;
264
+ }
265
+ }
266
+
267
+ return { _: "set", values, size } satisfies ShapeDescriptor;
189
268
  }
190
269
 
191
270
  const out: Record<string, unknown> = {};
@@ -195,8 +274,20 @@ function describeFullStructureUnguarded(
195
274
  const allKeys = Object.keys(value);
196
275
  const keys = allKeys.slice(0, FULL_MAX_ENTRIES);
197
276
 
277
+ // Guarded per key, around the read as well as the walk below it: the read
278
+ // is where a getter runs, and a throw there would otherwise reach the catch
279
+ // around this whole walk and trade every readable sibling for one marker.
280
+ // The nested walk restores `seen` itself, so nothing needs undoing here.
198
281
  for (const key of keys) {
199
- out[key] = describeFull((value as Record<string, unknown>)[key], depth + 1, seen, budget);
282
+ let encoded: unknown;
283
+
284
+ try {
285
+ encoded = describeFull((value as Record<string, unknown>)[key], depth + 1, seen, budget);
286
+ } catch {
287
+ encoded = UNREADABLE;
288
+ }
289
+
290
+ setField(out, key, encoded);
200
291
  }
201
292
 
202
293
  // An array that gets truncated pushes a marker; an object has to carry one
@@ -221,8 +312,7 @@ function describeFullStructureUnguarded(
221
312
  // value is a `HubServerResult` and not a bag of keys is most of what makes
222
313
  // a graph result readable.
223
314
  if (prototype !== null && prototype !== Object.prototype) {
224
- out["_type"] =
225
- (value.constructor as { readonly name?: string } | undefined)?.name ?? "object";
315
+ out["_type"] = typeName(value);
226
316
  }
227
317
 
228
318
  return out;
@@ -230,3 +320,201 @@ function describeFullStructureUnguarded(
230
320
  seen.delete(value);
231
321
  }
232
322
  }
323
+
324
+ /**
325
+ * Stands in for a step's `value`, or a half of a map's pair, whose read threw.
326
+ * Private to this module, so no app value can be it.
327
+ */
328
+ const UNREADABLE_STEP: unique symbol = Symbol("unreadable step");
329
+
330
+ const NO_ARGUMENTS: ReadonlyArray<never> = [];
331
+
332
+ /** What one walk of a collection's iterator read, and how it ended. */
333
+ type CollectionWalk = {
334
+ /** Each step's `value`, read once, or {@link UNREADABLE_STEP}. */
335
+ readonly values: Array<unknown>;
336
+ /**
337
+ * `"done"` when the iterator finished, `"cut"` when the entry bound stopped
338
+ * the reads, and `"broken"` when a step could not be read: `next` threw, its
339
+ * result was not an object, or its `done` threw. Without a readable `done`
340
+ * there is no telling whether the walk is over, so it stops there.
341
+ */
342
+ readonly end: "done" | "cut" | "broken";
343
+ };
344
+
345
+ /**
346
+ * Reads a collection's steps by the iterator protocol, as a spread does.
347
+ *
348
+ * The iterator comes from the iterable `entries()` or `values()` returned,
349
+ * because an override may hand back any iterable, and a built-in iterator
350
+ * returns itself. One that is not iterable is used as the iterator itself.
351
+ * `next` is read once and `done` is taken by truthiness, both as the protocol
352
+ * has it.
353
+ *
354
+ * Each step's `value` is read once, so a map's key and value come from the same
355
+ * read. A step whose `value` read throws is still a step: the iterator said it
356
+ * was not done, so the walk goes on past it.
357
+ *
358
+ * The bound stops the reads, not just the output: an iterator runs the app's
359
+ * code and need never finish. One step past the bound says whether anything was
360
+ * cut, so a collection exactly at it reads as whole.
361
+ */
362
+ function readSteps(source: object): CollectionWalk {
363
+ const method = (source as { readonly [Symbol.iterator]?: unknown })[Symbol.iterator];
364
+ const iterator: unknown =
365
+ typeof method === "function" ? Reflect.apply(method, source, NO_ARGUMENTS) : source;
366
+ const next = (iterator as { readonly next?: unknown }).next as (this: unknown) => unknown;
367
+ const values: Array<unknown> = [];
368
+
369
+ for (;;) {
370
+ let step: unknown;
371
+ let done: unknown;
372
+
373
+ try {
374
+ step = Reflect.apply(next, iterator, NO_ARGUMENTS);
375
+
376
+ if (step === null || (typeof step !== "object" && typeof step !== "function")) {
377
+ return { values, end: "broken" };
378
+ }
379
+
380
+ done = (step as { readonly done?: unknown }).done;
381
+ } catch {
382
+ return { values, end: "broken" };
383
+ }
384
+
385
+ if (done) {
386
+ return { values, end: "done" };
387
+ }
388
+
389
+ if (values.length === FULL_MAX_ENTRIES) {
390
+ return { values, end: "cut" };
391
+ }
392
+
393
+ let entry: unknown;
394
+
395
+ try {
396
+ entry = (step as { readonly value?: unknown }).value;
397
+ } catch {
398
+ entry = UNREADABLE_STEP;
399
+ }
400
+
401
+ values.push(entry);
402
+ }
403
+ }
404
+
405
+ /** One half of a map step's pair, read on its own guard. */
406
+ function halfOf(pair: unknown, index: 0 | 1): unknown {
407
+ if (pair === UNREADABLE_STEP) {
408
+ return UNREADABLE_STEP;
409
+ }
410
+
411
+ try {
412
+ return (pair as { readonly [index: number]: unknown })[index];
413
+ } catch {
414
+ return UNREADABLE_STEP;
415
+ }
416
+ }
417
+
418
+ /** A read from {@link readSteps} or {@link halfOf}, walked unless it threw. */
419
+ function describeStepValue(
420
+ read: unknown,
421
+ depth: number,
422
+ seen: Set<object>,
423
+ budget: Budget
424
+ ): unknown {
425
+ return read === UNREADABLE_STEP ? UNREADABLE : describeFull(read, depth + 1, seen, budget);
426
+ }
427
+
428
+ /** The largest array index. `2 ** 32 - 1` is an ordinary key on an array. */
429
+ const MAX_ARRAY_INDEX = 2 ** 32 - 2;
430
+
431
+ /**
432
+ * An array's length, read once.
433
+ *
434
+ * A proxy can make the read throw, and its entries may still be readable. Then
435
+ * the length is one past the highest own index key, enumerable or not, so the
436
+ * entries survive and a hole among them still reads as one. The keys are
437
+ * listed by name alone, which asks the proxy for no descriptors. If they
438
+ * cannot be listed either, nothing about the array is readable and the throw
439
+ * reaches the caller's guard.
440
+ */
441
+ function arrayLength(value: ReadonlyArray<unknown>): unknown {
442
+ try {
443
+ return value.length;
444
+ } catch {
445
+ const keys = Object.getOwnPropertyNames(value);
446
+ let length = 0;
447
+
448
+ for (let index = 0; index < keys.length; index++) {
449
+ const key = keys[index] as string;
450
+ const position = Number(key);
451
+
452
+ // A canonical array index only: `"01"` and `"1.5"` are ordinary keys,
453
+ // and so is anything past the largest index.
454
+ if (
455
+ position >= length &&
456
+ position <= MAX_ARRAY_INDEX &&
457
+ String(position) === key &&
458
+ Number.isInteger(position)
459
+ ) {
460
+ length = position + 1;
461
+ }
462
+ }
463
+
464
+ return length;
465
+ }
466
+ }
467
+
468
+ /**
469
+ * A function's name, or `"anonymous"` when it has none it will give up.
470
+ *
471
+ * Guarded and checked for the reason {@link typeName} is: the read can run a
472
+ * getter, and a name that is not a string — a symbol, say — would throw when
473
+ * written into the marker.
474
+ */
475
+ function functionName(value: unknown): string {
476
+ try {
477
+ const name = (value as { readonly name?: unknown }).name;
478
+
479
+ return typeof name === "string" && name !== "" ? name : "anonymous";
480
+ } catch {
481
+ return "anonymous";
482
+ }
483
+ }
484
+
485
+ /**
486
+ * A collection's `size`, when reading it neither throws nor gives a number JSON
487
+ * cannot carry. The caller falls back to the entries it counted.
488
+ */
489
+ function collectionSize(
490
+ value: ReadonlyMap<unknown, unknown> | ReadonlySet<unknown>
491
+ ): number | undefined {
492
+ try {
493
+ return finiteNumber(value.size);
494
+ } catch {
495
+ return undefined;
496
+ }
497
+ }
498
+
499
+ /**
500
+ * The marker for a list the entry bound cut, with the full count when the value
501
+ * gave one JSON can carry. Without it the marker still says entries were cut;
502
+ * it just cannot say how many.
503
+ */
504
+ function entriesCut(length: number | undefined): ShapeDescriptor {
505
+ return length === undefined
506
+ ? { _: "elided", by: "entries" }
507
+ : { _: "elided", by: "entries", length };
508
+ }
509
+
510
+ /**
511
+ * A length or size as the value reports it, when that is a finite number.
512
+ *
513
+ * Both are read through the app's own getters: a `Map` or `Set` subclass can
514
+ * override `size`, and a proxy over an array can answer anything for `length`.
515
+ * A non-finite number there would fail the transport for the whole batch, so a
516
+ * caller falls back to what it counted, or leaves the count out.
517
+ */
518
+ function finiteNumber(reported: unknown): number | undefined {
519
+ return typeof reported === "number" && reported - reported === 0 ? reported : undefined;
520
+ }
package/src/shape.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  import { describeError } from "./cause.ts";
2
- import { type ShapeDescriptor, UNREADABLE } from "./descriptors.ts";
2
+ import {
3
+ describeNonFiniteNumber,
4
+ type ShapeDescriptor,
5
+ typeName,
6
+ UNREADABLE,
7
+ } from "./descriptors.ts";
3
8
 
4
9
  const MAX_STRING_LENGTH = 256;
5
10
  const MAX_KEYS = 32;
@@ -26,6 +31,8 @@ const MAX_DEPTH = 3;
26
31
  * string[42] an array of 42, named by its first element
27
32
  * {id,name}[3] the same, where that element is an object
28
33
  * unknown[0] an empty array: nothing to name it by
34
+ * unreadable[2] the first element could not be read
35
+ * string[?] the length could not be read
29
36
  * Map(3) / Set(3) collections, by size
30
37
  * function / symbol / bigint values with no JSON form
31
38
  * {…} / […] the depth bound stopped the walk here
@@ -53,19 +60,23 @@ export function describeShape(value: unknown, depth: number): unknown {
53
60
  }
54
61
 
55
62
  switch (typeof value) {
56
- case "boolean":
57
- case "number": {
63
+ case "boolean": {
58
64
  return value;
59
65
  }
66
+ case "number": {
67
+ // `value - value` is zero for every finite number and `NaN` for the rest:
68
+ // one subtraction, so a finite number stays as cheap as a boolean.
69
+ return value - value === 0 ? value : describeNonFiniteNumber(value);
70
+ }
60
71
  case "bigint":
61
72
  case "function":
62
73
  case "symbol": {
63
74
  return typeof value;
64
75
  }
65
76
  case "string": {
66
- // The one descriptor that stays an object at this policy, because it is
67
- // the one carrying content: `head` is app data, and a reader has to be
68
- // able to tell it from a string that crossed whole.
77
+ // An object at this policy, like a non-finite number's marker, because it
78
+ // carries content: `head` is app data, and a reader has to be able to
79
+ // tell it from a string that crossed whole.
69
80
  return value.length <= MAX_STRING_LENGTH
70
81
  ? value
71
82
  : ({
@@ -101,12 +112,10 @@ function describeStructureUnguarded(value: object, depth: number): unknown {
101
112
  }
102
113
 
103
114
  if (Array.isArray(value)) {
104
- const first = value[0];
105
-
106
115
  // Named by its first element rather than by every one of them: a
107
116
  // homogeneous array is the common case and the first entry settles it, and
108
117
  // a heterogeneous one is not summarizable at any length worth spending.
109
- return `${first === undefined ? "unknown" : shapeName(first, depth + 1)}[${value.length}]`;
118
+ return `${firstElementName(value, depth + 1)}[${lengthLabel(value)}]`;
110
119
  }
111
120
 
112
121
  if (value instanceof Map) {
@@ -123,17 +132,58 @@ function describeStructureUnguarded(value: object, depth: number): unknown {
123
132
  // far as this encoder is willing to go, and `{?}` says the fields exist rather
124
133
  // than letting a bare type name read as "it has none".
125
134
  if (prototype !== null && prototype !== Object.prototype) {
126
- return `${(value.constructor as { readonly name?: string } | undefined)?.name ?? "object"}{?}`;
135
+ return `${typeName(value)}{?}`;
127
136
  }
128
137
 
138
+ // A fresh array, so cut in place rather than copied.
129
139
  const keys = Object.keys(value);
130
- const shown = keys.length > MAX_KEYS ? [...keys.slice(0, MAX_KEYS), "…"] : keys;
140
+ if (keys.length > MAX_KEYS) {
141
+ keys.length = MAX_KEYS;
142
+ keys.push("…");
143
+ }
131
144
  // `_tag` is the one nested field that survives verbatim. A discriminant is
132
145
  // structure, not data — and a failure feed that says "an object with these
133
146
  // keys" instead of "GraphNodeAcquireFailed" is not worth reading.
134
- const tag = (value as { readonly _tag?: unknown })._tag;
147
+ //
148
+ // Read on its own guard: a getter that throws here costs the tag, not the
149
+ // key list already read.
150
+ let tag: unknown;
151
+
152
+ try {
153
+ tag = (value as { readonly _tag?: unknown })._tag;
154
+ } catch {
155
+ tag = undefined;
156
+ }
135
157
 
136
- return `${typeof tag === "string" ? tag : ""}{${shown.join(",")}}`;
158
+ return `${typeof tag === "string" ? tag : ""}{${keys.join(",")}}`;
159
+ }
160
+
161
+ /**
162
+ * What an array's first element is, read on its own guard so a throw costs the
163
+ * name and not the length beside it.
164
+ */
165
+ function firstElementName(value: ReadonlyArray<unknown>, depth: number): string {
166
+ let first: unknown;
167
+
168
+ try {
169
+ first = value[0];
170
+ } catch {
171
+ return "unreadable";
172
+ }
173
+
174
+ return first === undefined ? "unknown" : shapeName(first, depth);
175
+ }
176
+
177
+ /**
178
+ * An array's length as the label writes it, or `?` when it cannot be read or
179
+ * written: a proxy can make the read throw, or answer with a symbol.
180
+ */
181
+ function lengthLabel(value: ReadonlyArray<unknown>): string {
182
+ try {
183
+ return `${value.length}`;
184
+ } catch {
185
+ return "?";
186
+ }
137
187
  }
138
188
 
139
189
  /**
@@ -156,6 +206,12 @@ function shapeName(value: unknown, depth: number): string {
156
206
  const described = describeStructure(value, depth);
157
207
 
158
208
  // An `Error` element describes as a cause chain, which is an object. Its
159
- // descriptor names it `error`, so the array says the same.
160
- return typeof described === "string" ? described : "error";
209
+ // descriptor names it `error`, so the array says the same. An element that
210
+ // could not be read describes as the unreadable marker, also an object, and
211
+ // is named for that instead: it is not a failure.
212
+ if (typeof described === "string") {
213
+ return described;
214
+ }
215
+
216
+ return described === UNREADABLE ? "unreadable" : "error";
161
217
  }