@specific.dev/spectest 0.24.0 → 0.27.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.
Files changed (74) hide show
  1. package/dist/aws-sigv4.d.ts +42 -0
  2. package/dist/aws-sigv4.js +166 -0
  3. package/dist/browser.d.ts +314 -0
  4. package/dist/browser.js +1320 -0
  5. package/dist/components/email.d.ts +135 -0
  6. package/dist/components/email.js +271 -0
  7. package/dist/components/expo.d.ts +69 -0
  8. package/dist/components/expo.js +125 -0
  9. package/dist/components/index.d.ts +8 -0
  10. package/dist/components/index.js +18 -0
  11. package/dist/components/k3s.d.ts +143 -0
  12. package/dist/components/k3s.js +1067 -0
  13. package/dist/components/postgres.d.ts +93 -0
  14. package/dist/components/postgres.js +58 -0
  15. package/dist/components/replayFake.d.ts +169 -0
  16. package/dist/components/replayFake.js +738 -0
  17. package/dist/components/s3.d.ts +99 -0
  18. package/dist/components/s3.js +81 -0
  19. package/dist/components/supabase.d.ts +197 -0
  20. package/dist/components/supabase.js +1003 -0
  21. package/dist/daemon.d.ts +1 -0
  22. package/dist/daemon.js +4223 -0
  23. package/dist/ids.d.ts +2 -0
  24. package/{src/ids.ts → dist/ids.js} +46 -50
  25. package/dist/index.d.ts +1183 -0
  26. package/dist/index.js +769 -0
  27. package/dist/ingress.d.ts +114 -0
  28. package/dist/ingress.js +210 -0
  29. package/dist/inspect.d.ts +228 -0
  30. package/dist/inspect.js +429 -0
  31. package/dist/locator.d.ts +260 -0
  32. package/dist/locator.js +293 -0
  33. package/dist/mobile.d.ts +71 -0
  34. package/dist/mobile.js +65 -0
  35. package/dist/record-secrets.d.ts +9 -0
  36. package/{src/record-secrets.ts → dist/record-secrets.js} +13 -15
  37. package/dist/recorder.d.ts +516 -0
  38. package/dist/recorder.js +219 -0
  39. package/dist/redis.d.ts +54 -0
  40. package/dist/redis.js +126 -0
  41. package/dist/replay-bundle.d.ts +38 -0
  42. package/{src/replay-bundle.ts → dist/replay-bundle.js} +29 -47
  43. package/dist/resolver.d.ts +1 -0
  44. package/dist/resolver.js +309 -0
  45. package/dist/s3.d.ts +89 -0
  46. package/dist/s3.js +198 -0
  47. package/dist/sql.d.ts +74 -0
  48. package/dist/sql.js +151 -0
  49. package/dist/terminal.d.ts +161 -0
  50. package/dist/terminal.js +538 -0
  51. package/package.json +24 -9
  52. package/src/browser.ts +0 -1807
  53. package/src/components/email.ts +0 -398
  54. package/src/components/expo.ts +0 -167
  55. package/src/components/index.ts +0 -63
  56. package/src/components/k3s.ts +0 -1312
  57. package/src/components/postgres.ts +0 -105
  58. package/src/components/replayFake.ts +0 -848
  59. package/src/components/s3.ts +0 -132
  60. package/src/components/supabase.ts +0 -1299
  61. package/src/daemon.ts +0 -4969
  62. package/src/index.ts +0 -2350
  63. package/src/ingress.ts +0 -288
  64. package/src/inspect.ts +0 -673
  65. package/src/locator.ts +0 -594
  66. package/src/mobile.ts +0 -133
  67. package/src/recorder.ts +0 -817
  68. package/src/redis.ts +0 -202
  69. package/src/resolver.ts +0 -351
  70. package/src/s3.ts +0 -333
  71. package/src/sql.ts +0 -243
  72. package/src/terminal.ts +0 -740
  73. package/src/vendor/rrweb-plugin-console-record.umd.js +0 -521
  74. package/src/vendor/rrweb-record.min.js +0 -5061
package/src/inspect.ts DELETED
@@ -1,673 +0,0 @@
1
- // Provenance wrappers for op return values.
2
- //
3
- // When a tracked op (fetch, db query, browser.evaluate) records its
4
- // event, it wraps its return value via `wrap(value, sourceSeq)`. The
5
- // wrapper carries an `OP_TAG` describing which op produced it and the
6
- // access path within that op's payload. When the wrapped value reaches
7
- // `expect()`, the matcher reads the tag and attaches `sourceSeq` + `path`
8
- // to its AssertionEvent so the UI can nest the assertion under its
9
- // originating op.
10
- //
11
- // Two shapes of wrapper:
12
- // - Objects/arrays: lazy `Proxy`. Reading a property returns a fresh
13
- // wrapped child with the path extended. Structural shape stays raw:
14
- // an array's `length` is a real number (provenance belongs on the
15
- // data, not the container's size — `rows.length === 1` must work).
16
- // - Primitives: a small `Carrier` object holding the value and tag.
17
- // Coercion sinks (`valueOf`/`toString`/`toJSON`/`Symbol.toPrimitive`)
18
- // recover the raw primitive, so template interpolation, arithmetic,
19
- // loose equality, and `JSON.stringify` all behave. The one remaining
20
- // sharp edge is strict `===` against a primitive (always false — an
21
- // object can never `===` a number); `.unwrap()` first, and the
22
- // `Carrier<T>` typing makes that a compile-time error in TS.
23
- //
24
- // Cannot tag: `null` / `undefined` (no place to attach a symbol) and
25
- // functions (we don't currently need to). Those pass through as-is — but a
26
- // nullish *leaf read* off a proxy is recorded in the pending-nullish register
27
- // below so `expect()` can still recover its provenance (see `adoptNullishTag`).
28
- //
29
- // Escape: every wrapper exposes `.unwrap()` returning the fully raw value (it
30
- // walks every wrapper layer, so one call always reaches raw). That is the
31
- // public escape hatch; there is no `unwrap(x)` free function — a spectest op
32
- // result is always wrapped (see below), so the value always has `.unwrap()`.
33
- // (`readRaw` is the internal, never-throws primitive `.unwrap()` and `expect()`
34
- // are built on; it isn't part of the public surface.)
35
- //
36
- // Wrapping is UNCONDITIONAL: a spectest op (fetch/exec/terminal/poll/db/
37
- // browser.evaluate) always returns a wrapped value, in every context — a test,
38
- // a `ctx.poll` predicate, `setup`, `eval`, a fake handler. Whether the op also
39
- // recorded a timeline *event* is a separate decision (the recorder may be
40
- // absent, paused, or have truncated the event): when there is no event the
41
- // wrapper simply carries no provenance (`sourceSeq: undefined`), so `expect()`
42
- // can't nest it under an op — but the wrapper SHAPE (`.unwrap()`, coercion
43
- // sinks, the proxy) is always present. That keeps `Wrapped`/`WrappedResponse`/
44
- // `Carrier<T>` honest at runtime everywhere, instead of silently collapsing to
45
- // a raw value wherever recording happened to be off.
46
-
47
- // Registered in the GLOBAL symbol registry (`Symbol.for`), not module-private
48
- // (`Symbol`), so a value tagged by ONE copy of this module unwraps correctly in
49
- // ANOTHER. This matters whenever two copies of the SDK load in the same runtime:
50
- // the in-VM daemon runs the baked SDK at /opt/spectest/sdk and mints the
51
- // provenance carriers (ctx.fetch / ctx.browser / db results), while a user's
52
- // test file resolving `@specific.dev/spectest` to a registry-pinned copy gets
53
- // its `expect`. With module-private symbols the two `UNWRAP`s differed, so
54
- // `expect`'s auto-unwrap silently no-op'd and wrapped assertions failed
55
- // nonsensically (`expect("Hello Spec").toContain("Hello")` -> false). The
56
- // control plane also repoints the dep at the baked copy so normally only one
57
- // copy loads; this is defense-in-depth for the cases where it can't (and only
58
- // takes full effect once both copies ship this `Symbol.for`).
59
- export const OP_TAG = Symbol.for("spectest.opTag");
60
- export const UNWRAP = Symbol.for("spectest.unwrap");
61
-
62
- // The escape hatch from a wrapped value to its raw form is the `.unwrap()`
63
- // method that lives on the `Carrier` / `WrappedObject` / `WrappedArray` /
64
- // `WrappedResponse` types. We deliberately do NOT augment the global
65
- // `Number`/`String`/`Boolean`/`Object` prototypes with a phantom `unwrap()`:
66
- // that made `.unwrap()` typecheck on *every* value, including a genuinely raw
67
- // primitive (a third-party return, or a plain `fetch` the project code calls
68
- // itself), where `.unwrap()` would compile but throw at runtime. Without the
69
- // phantom, `.unwrap()` only typechecks on a value whose static type is one of
70
- // the wrapper types — and because spectest ops now wrap unconditionally (see
71
- // above), those static types are honest at runtime in every context. A value
72
- // that is raw *and* typed raw (it came from outside a spectest op) neither
73
- // needs nor offers `.unwrap()` — use it directly.
74
-
75
- export interface OpTag {
76
- /** Seq of the timeline event this value came from, or `undefined` when the
77
- * value was wrapped without a recorded event (no recorder, paused, or the
78
- * event was truncated). `expect()` only nests under a defined `sourceSeq`. */
79
- sourceSeq: number | undefined;
80
- path: readonly string[];
81
- }
82
-
83
- /** Read the tag if present; returns undefined for raw values. */
84
- export function readTag(x: unknown): OpTag | undefined {
85
- if (x === null || x === undefined) return undefined;
86
- if (typeof x !== "object" && typeof x !== "function") return undefined;
87
- return (x as { [OP_TAG]?: OpTag })[OP_TAG];
88
- }
89
-
90
- // ───────────────────────────────────────────────────────────────────────────
91
- // Pending nullish-leaf register
92
- //
93
- // Reading a `null`/`undefined` leaf off a wrapped object (`dep.status.readyReplicas`
94
- // on a failed deployment) hands back a raw nullish value with no tag — a symbol
95
- // can't ride on `null`/`undefined`, and minting a stand-in object would break
96
- // every `=== null` / `if (!x)` in real code (see `wrap`). So the natural
97
- // `expect(dep.status.readyReplicas).toBeFalsy()` used to lose its provenance and
98
- // render as a disconnected top-level assertion, even though `field(...)` could
99
- // recover it manually.
100
- //
101
- // To make the natural form work too, the proxy *notes* every nullish leaf read
102
- // here (source op + access path). `expect()` consults the register when it
103
- // receives an untagged nullish value via `adoptNullishTag`, matching the most
104
- // recent note. The note is single-consume, freshest-wins, and invalidated by
105
- // any subsequent recorded op (the recorder calls `clearPendingNullish`), so the
106
- // window for misattribution is one untagged nullish read immediately followed by
107
- // an `expect` of an unrelated nullish literal with no op in between — narrow,
108
- // and the worst case points at a contextually-adjacent field rather than losing
109
- // the link entirely. The note never reaches program control flow: it is read
110
- // only inside `expect()`, which `readRaw`s back to the real nullish value.
111
- // ───────────────────────────────────────────────────────────────────────────
112
-
113
- let pendingNullish: { value: null | undefined; tag: OpTag } | undefined;
114
-
115
- function noteNullishLeaf(
116
- value: null | undefined,
117
- sourceSeq: number | undefined,
118
- path: readonly string[],
119
- ): void {
120
- pendingNullish = { value, tag: { sourceSeq, path: [...path] } };
121
- }
122
-
123
- /** Forget any pending nullish-leaf note. Called by the recorder whenever a new
124
- * op is recorded, so a note can't outlive the read that produced it. */
125
- export function clearPendingNullish(): void {
126
- pendingNullish = undefined;
127
- }
128
-
129
- /**
130
- * If `value` is an untagged `null`/`undefined` that matches the most recent
131
- * nullish-leaf read, mint a tagged {@link makeCarrier} holder for it (the same
132
- * stand-in `field`/`retag` use) and clear the note; otherwise return `value`
133
- * unchanged. The holder is safe because it goes straight to `expect()`, which
134
- * `readRaw`s it before matching — it never escapes into control flow.
135
- */
136
- export function adoptNullishTag<T>(value: T): T {
137
- if (value !== null && value !== undefined) return value;
138
- const p = pendingNullish;
139
- if (!p || !Object.is(p.value, value)) return value;
140
- pendingNullish = undefined;
141
- return makeCarrier(value, p.tag.sourceSeq, p.tag.path) as unknown as T;
142
- }
143
-
144
- /** If x is wrapped, return the raw value; otherwise return x. */
145
- export function readRaw<T>(x: T): T {
146
- // Walks the chain — a value can carry more than one wrapper at once
147
- // (e.g. a polled k8s pod is wrapped by the component's `withTagging`
148
- // with the HTTP seq, then by `ctx.poll`'s `wrap(...)` with the wait
149
- // seq). A single-step unwrap would still hand callers a proxy.
150
- let cur: unknown = x;
151
- while (cur !== null && cur !== undefined) {
152
- const t = typeof cur;
153
- if (t !== "object" && t !== "function") return cur as T;
154
- // Presence check, NOT `next === undefined`: a carrier minted by `field`
155
- // may wrap `undefined` itself (`[UNWRAP] = undefined`). Testing the value
156
- // would mistake that for "no wrapper" and hand the carrier object back, so
157
- // a `toBeFalsy()` would see a truthy object.
158
- if (!(UNWRAP in (cur as object))) return cur as T;
159
- const next = (cur as { [UNWRAP]?: unknown })[UNWRAP];
160
- if (next === cur) return cur as T;
161
- cur = next;
162
- }
163
- return cur as T;
164
- }
165
-
166
- /** The raw type behind a wrapper: a `Carrier`/`WrappedObject`/`WrappedArray`/
167
- * `WrappedResponse` resolves to its `unwrap()` return type; anything else is
168
- * already raw and passes through unchanged. */
169
- export type Unwrap<T> = T extends { unwrap(): infer V } ? V : T;
170
-
171
- /**
172
- * Wrap a value so reads through it carry an `OpTag`. Recursion is lazy:
173
- * a property read on an object Proxy wraps its child on demand.
174
- */
175
- export function wrap<T>(
176
- raw: T,
177
- sourceSeq: number | undefined,
178
- path: readonly string[] = [],
179
- ): T {
180
- if (raw === null || raw === undefined) return raw;
181
- const t = typeof raw;
182
- if (t === "object") {
183
- return wrapObject(raw as object, sourceSeq, path) as unknown as T;
184
- }
185
- if (t === "function") return raw;
186
- // primitive
187
- return makeCarrier(raw, sourceSeq, path) as unknown as T;
188
- }
189
-
190
- /**
191
- * Like {@link wrap}, but for values read *through* a wrapped container, where a
192
- * `null`/`undefined` leaf must still leave a provenance trail. `wrap` passes
193
- * nullish through raw (a symbol can't ride on it); here we additionally
194
- * {@link noteNullishLeaf note} the read so `expect()` can adopt the tag via
195
- * {@link adoptNullishTag}. The returned value is identical to `wrap`'s — raw
196
- * nullish or a proxy/carrier — so control flow is unaffected.
197
- */
198
- function wrapChild<T>(value: T, sourceSeq: number | undefined, path: readonly string[]): T {
199
- if (value === null || value === undefined) {
200
- noteNullishLeaf(value as null | undefined, sourceSeq, path);
201
- return value;
202
- }
203
- return wrap(value, sourceSeq, path);
204
- }
205
-
206
- // Array methods whose return value derives from the array's contents.
207
- // We re-wrap their results so assertions on `arr.find(...)` etc. still
208
- // fold under the originating op. Predicates still see raw items (the
209
- // method runs on the raw target), so `===` comparisons keep working.
210
- const ARRAY_TAGGED_METHODS = new Set([
211
- "find",
212
- "findLast",
213
- "at",
214
- "map",
215
- "filter",
216
- "slice",
217
- "flat",
218
- "flatMap",
219
- "concat",
220
- "includes",
221
- "indexOf",
222
- "lastIndexOf",
223
- "findIndex",
224
- "findLastIndex",
225
- "some",
226
- "every",
227
- ]);
228
-
229
- function wrapObject<T extends object>(
230
- raw: T,
231
- sourceSeq: number | undefined,
232
- path: readonly string[],
233
- ): T {
234
- const tag: OpTag = { sourceSeq, path };
235
- const isArray = Array.isArray(raw);
236
- const handler: ProxyHandler<T> = {
237
- get(target, prop, receiver) {
238
- if (prop === OP_TAG) return tag;
239
- if (prop === UNWRAP) return target;
240
- if (prop === "unwrap") {
241
- // Only intercept when the underlying object doesn't already have
242
- // its own `unwrap` — otherwise we'd shadow a legitimate property.
243
- // `readRaw` (not a bare `target`) so a value carrying more than one
244
- // wrapper — e.g. a `ctx.poll` result whose inner value was already
245
- // tagged by a component's `withTagging` — unwraps all the way to raw
246
- // in one call, not just one layer.
247
- if (!(prop in (target as object))) {
248
- return () => readRaw(target);
249
- }
250
- }
251
- // `.transform(label, fn)` — same shape/guard as `unwrap`: only intercept
252
- // when the underlying object has no own `transform`, so a real data field
253
- // named `transform` is never shadowed.
254
- if (prop === "transform" && !(prop in (target as object))) {
255
- return makeTransform(readRaw(target), sourceSeq, path);
256
- }
257
- // Hide thenable-ness from `await`. We must never accidentally
258
- // implement `then`, or `await fetch(...)` would resolve to the
259
- // wrong thing if we ever wrapped a Promise (we don't, but be safe).
260
- if (prop === "then" && !(prop in (target as object))) return undefined;
261
-
262
- const value = Reflect.get(target, prop, receiver);
263
- if (typeof prop === "symbol") {
264
- // Symbols (iterator, toPrimitive, etc.) — pass through bound.
265
- return typeof value === "function"
266
- ? (value as (...a: unknown[]) => unknown).bind(target)
267
- : value;
268
- }
269
- // Container shape stays raw: `rows.length === 1` must be a plain
270
- // number comparison, not carrier-vs-number (silently false).
271
- // Provenance for "how many" assertions still works — `expect`
272
- // accepts raw values, it just won't nest under the op.
273
- if (isArray && prop === "length") return value;
274
- const childPath = path.concat(String(prop));
275
- if (typeof value === "function") {
276
- if (isArray && ARRAY_TAGGED_METHODS.has(prop)) {
277
- const method = value as (...a: unknown[]) => unknown;
278
- const taggedPath = path.concat(`<${prop}>`);
279
- return (...args: unknown[]) => {
280
- const result = method.apply(target, args);
281
- return wrapChild(result, sourceSeq, taggedPath);
282
- };
283
- }
284
- // Other methods stay bound to the raw target; their return
285
- // values aren't wrapped here — call sites that need
286
- // promise-returning methods (e.g. Response.json()) install a
287
- // bespoke wrapper.
288
- return (value as (...a: unknown[]) => unknown).bind(target);
289
- }
290
- return wrapChild(value, sourceSeq, childPath);
291
- },
292
- has(target, prop) {
293
- if (prop === OP_TAG || prop === UNWRAP) return true;
294
- return Reflect.has(target, prop);
295
- },
296
- // Block writes; wrappers are read-only views.
297
- set() {
298
- return false;
299
- },
300
- deleteProperty() {
301
- return false;
302
- },
303
- };
304
- return new Proxy(raw, handler);
305
- }
306
-
307
- // The `.transform(label, fn)` method every wrapper (carrier + object/array
308
- // proxy) carries — the value-level analogue of `.unwrap()`. It runs the raw
309
- // value through `fn` and re-`wrap`s the result with `path` extended by a
310
- // `<label>` derived-step marker, so the decoded value keeps the source op's
311
- // provenance (`sourceSeq`) and stays navigable: a later `expect(...)` on it, or
312
- // on a subfield, still nests under the originating op (`secret.data.config.<json>.tier`).
313
- // `label` is a plain word; the `<…>` brackets are added here so they never leak
314
- // into the call site (the same convention array methods use, `<find>`/`<map>`).
315
- // A throw in `fn` (a non-string value, malformed base64/JSON) is rethrown
316
- // prefixed with `<label>:`, failing the test at the bad value.
317
- function makeTransform(
318
- raw: unknown,
319
- sourceSeq: number | undefined,
320
- path: readonly string[],
321
- ): (label: string, fn: (raw: never) => unknown) => unknown {
322
- return (label, fn) => {
323
- const nextPath = [...path, `<${label}>`];
324
- let result: unknown;
325
- try {
326
- result = (fn as (r: unknown) => unknown)(raw);
327
- } catch (err) {
328
- const detail = err instanceof Error ? err.message : String(err);
329
- throw new Error(`<${label}>: ${detail}`);
330
- }
331
- return wrap(result, sourceSeq, nextPath);
332
- };
333
- }
334
-
335
- // Runtime shape of a primitive carrier: the public `Carrier<T>` surface
336
- // (`unwrap()`) plus the internal provenance symbols. Kept private so the
337
- // exported `Carrier<T>` stays clean.
338
- interface CarrierCell<T> extends Carrier<T> {
339
- [OP_TAG]: OpTag;
340
- [UNWRAP]: T;
341
- }
342
-
343
- function makeCarrier<T>(
344
- raw: T,
345
- sourceSeq: number | undefined,
346
- path: readonly string[],
347
- ): CarrierCell<T> {
348
- const tag: OpTag = { sourceSeq, path };
349
- return {
350
- [OP_TAG]: tag,
351
- [UNWRAP]: raw,
352
- unwrap: () => raw,
353
- transform: makeTransform(raw, sourceSeq, path) as unknown as Carrier<T>["transform"],
354
- // Coercion sinks recover the raw primitive instead of inheriting
355
- // Object.prototype's defaults ("[object Object]" / NaN / {}). A
356
- // carrier interpolated into a string, fed to arithmetic, `==`, or
357
- // `JSON.stringify` now behaves like its value — silent wrongness
358
- // (a bogus "[object Object]" namespace in a kubectl command) was
359
- // the most expensive failure mode this wrapper ever produced.
360
- valueOf: () => raw,
361
- toString: () => String(raw),
362
- toJSON: () => raw,
363
- [Symbol.toPrimitive]: () => raw,
364
- };
365
- }
366
-
367
- // ───────────────────────────────────────────────────────────────────────────
368
- // Provenance-preserving field selection
369
- //
370
- // The proxy/carrier only carries the OpTag across *property reads* (and a
371
- // whitelist of array methods), and it can't carry it across `null`/`undefined`
372
- // at all — those are primitives with nowhere to hang a symbol, and `wrap`
373
- // passes them through raw. So `expect(row.deleted_at).toBe(null)` reaches
374
- // `expect()` as a bare `null` with no tag and renders as a disconnected
375
- // top-level row. `field` recovers the link by tagging from the *container*.
376
- // (A decoded value loses its tag the same way, through the decode; the
377
- // `.transform(label, fn)` method every wrapper carries (see `makeTransform`)
378
- // recovers it — it runs the still-tagged value through `fn` and re-`wrap`s the
379
- // result with the source path extended by a `<label>` marker.)
380
- // ───────────────────────────────────────────────────────────────────────────
381
-
382
- /**
383
- * Re-tag a value against an existing source op. Uses the normal `wrap` for
384
- * non-nullish results (object → proxy, primitive → carrier) but a
385
- * {@link makeCarrier} *holder* for `null`/`undefined` — those can't hold a
386
- * symbol, and `wrap` deliberately passes them through raw. The holder is an
387
- * object masquerading as null/undefined, which is ONLY safe because it never
388
- * escapes into program control flow: it goes straight to `expect()`, which
389
- * `readRaw`s it back to the real value before matching.
390
- */
391
- function retag(raw: unknown, sourceSeq: number | undefined, path: readonly string[]): unknown {
392
- return raw === null || raw === undefined
393
- ? makeCarrier(raw, sourceSeq, path)
394
- : wrap(raw, sourceSeq, path);
395
- }
396
-
397
- /**
398
- * Provenance-preserving, null-safe field selector — for asserting on a leaf
399
- * that is `null`/`undefined`. Reading such a leaf off a wrapped object hands
400
- * back a raw `null`/`undefined` (a symbol tag can't ride on those, and minting
401
- * a stand-in object would break every `=== null` / `if (!x)` in real code), so
402
- * the raw value alone loses its link to the originating op. `field` reads the
403
- * tag from the *container* and navigates the raw value, returning a tagged
404
- * handle even when the leaf is nullish — safe because the handle only ever
405
- * feeds `expect()`. Pass it straight to `expect(...)`; works with every matcher.
406
- *
407
- * Mostly redundant now: the plain `expect(dep.status.readyReplicas).toBeFalsy()`
408
- * form recovers provenance on its own — the proxy notes each nullish leaf read
409
- * and `expect` adopts the note (see {@link adoptNullishTag}). Reach for `field`
410
- * when the nullish read and the `expect` are separated by another recorded op
411
- * (which clears the note), or to make the navigation explicit.
412
- *
413
- * ```ts
414
- * expect(field(created, "branched_from_environment_id")).toBe(null);
415
- * expect(field(dep, "status", "readyReplicas")).toBeFalsy();
416
- * ```
417
- */
418
- export function field(value: unknown, ...path: Array<string | number>): unknown {
419
- const tag = readTag(value);
420
- let cur: unknown = readRaw(value);
421
- for (const key of path) {
422
- if (cur === null || cur === undefined) {
423
- cur = undefined;
424
- break;
425
- }
426
- cur = (cur as Record<string | number, unknown>)[key];
427
- }
428
- if (!tag) return cur;
429
- return retag(cur, tag.sourceSeq, [...tag.path, ...path.map(String)]);
430
- }
431
-
432
- /**
433
- * A provenance-carrying handle to a value produced by a tracked op
434
- * (`ctx.fetch`, a db query, `browser.evaluate`). Pass it straight to
435
- * `expect(...)` — the matcher reads the provenance and nests the
436
- * assertion under the originating op in the timeline.
437
- *
438
- * At runtime, coercion sinks recover the raw value (`` `${carrier}` ``,
439
- * `JSON.stringify(carrier)` behave as if raw). But the *type* is honestly an
440
- * object, not `T`, so arithmetic (`carrier + 1`), `==`/`===`, and handing it
441
- * to a typed API are all compile errors — `carrier.unwrap()` (or `expect(...)`,
442
- * which unwraps for you) first. This is deliberate: a wrapped value is a
443
- * handle, and the type says so rather than masquerading as its raw type.
444
- */
445
- export interface Carrier<T> {
446
- /** Recover the raw underlying value. */
447
- unwrap(): T;
448
- /**
449
- * Run the raw value through `fn` and get back a provenance-carrying handle to
450
- * the result — for asserting on a *decoded* value (base64, JSON, JWT, …) while
451
- * keeping its link to the op that produced it. The op path is extended by a
452
- * `<label>` marker, so a later `expect(...)` on the result still nests under
453
- * the source op. `label` is a plain word (`"base64"`, `"json"`); the UI adds
454
- * the `<…>` brackets, so don't include them yourself. `fn` receives the raw
455
- * value (typed `T`), so no cast is needed. `R` types the result. A throw in
456
- * `fn` is rethrown prefixed with `<label>:`, failing the test at the value.
457
- *
458
- * ```ts
459
- * expect(secret.data.url.transform("base64", (s) => Buffer.from(s, "base64").toString()))
460
- * .toContain("redis://");
461
- * ```
462
- */
463
- transform<R = unknown>(label: string, fn: (raw: T) => R): Wrapped<R>;
464
- /** Coerces to the raw value (arithmetic, `==`). */
465
- valueOf(): T;
466
- /** Renders the raw value (template interpolation). */
467
- toString(): string;
468
- /** Serializes as the raw value under `JSON.stringify`. */
469
- toJSON(): T;
470
- /** Coerces to the raw value. */
471
- [Symbol.toPrimitive](hint?: string): T;
472
- }
473
-
474
- /**
475
- * The values `expect()` accepts: anything carrying provenance from a recorded
476
- * op (fetch / db / exec / browser / fakes / k8s) — every member of the
477
- * {@link wrap} family ({@link Carrier}, {@link WrappedObject},
478
- * {@link WrappedArray}, {@link WrappedResponse}) exposes `.unwrap()`, so this
479
- * structural shape admits them all and rejects a raw primitive / object.
480
- *
481
- * `null`/`undefined` are also admitted: a nullish leaf can't carry the symbol
482
- * tag, but `adoptNullishTag` recovers its provenance at runtime, so
483
- * `expect(rows[0]?.text)` and `expect(dep.status.readyReplicas)` stay on
484
- * `expect`. To assert on a value with no provenance (a computed number, a raw
485
- * WebSocket frame), use `expectRaw(value, message)` instead.
486
- */
487
- export type Provenanced = { unwrap(): unknown } | null | undefined;
488
-
489
- /**
490
- * What a tracked op's value looks like once wrapped — applied *deeply*, so the
491
- * type matches the runtime at every level (the proxy lazily wraps each leaf you
492
- * read). A primitive becomes a {@link Carrier}; an object keeps its keys but
493
- * each property is itself `Wrapped`, plus an `.unwrap()`; an array keeps a raw
494
- * `.length` and indexes to `Wrapped` elements (see {@link WrappedArray}).
495
- *
496
- * Because leaves are `Carrier`s rather than their raw type, using one as raw
497
- * data — arithmetic, string methods, a typed client — is a compile error;
498
- * `x.unwrap()` (or `expect(x)`, which unwraps) recovers the raw value. That's
499
- * the whole point: the type tells you it's a handle instead of pretending to be
500
- * the underlying value and blowing up at runtime.
501
- *
502
- * **Distributes over unions** so the nullish members of an optional property
503
- * survive as `null`/`undefined` rather than collapsing into a `Carrier<undefined>`.
504
- * That's what lets `?.` narrow a wrapped optional leaf: `Wrapped<V1PodStatus |
505
- * undefined>` is `WrappedObject<V1PodStatus> | undefined` (so `pod.status?.phase`
506
- * type-checks), not `Carrier<undefined> | WrappedObject<…>` (where `?.` can't see
507
- * the `Carrier` as nullish). A nullish leaf still reaches `expect` untagged and is
508
- * recovered at runtime by {@link adoptNullishTag}; `Provenanced` admits it because
509
- * it includes `null | undefined`.
510
- */
511
- export type Wrapped<T> = T extends null | undefined
512
- ? T
513
- : T extends readonly (infer U)[]
514
- ? WrappedArray<U>
515
- : // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
516
- T extends (...args: never[]) => unknown
517
- ? T
518
- : T extends object
519
- ? WrappedObject<T>
520
- : Carrier<T>;
521
-
522
- /** A wrapped object: every own property is itself {@link Wrapped}, plus an
523
- * `.unwrap()` that recovers the fully-raw value (all nested leaves raw). */
524
- export type WrappedObject<T> = {
525
- readonly [K in keyof T]: Wrapped<T[K]>;
526
- } & {
527
- /** Recover the fully raw value (nested leaves unwrapped too). */
528
- unwrap(): T;
529
- /** Run the raw object through `fn`, keeping provenance (op path + `<label>`),
530
- * and get back a navigable handle to the result. See {@link Carrier.transform}. */
531
- transform<R = unknown>(label: string, fn: (raw: T) => R): Wrapped<R>;
532
- };
533
-
534
- /**
535
- * A wrapped array. Indexing and the content-deriving methods (`find`, `map`,
536
- * `filter`, `slice`, …) return {@link Wrapped} values so assertions on them
537
- * still fold under the originating op; their *predicates* receive raw elements
538
- * (the method runs on the raw target), so `=== ` comparisons inside a predicate
539
- * keep working. `.length` stays a real `number` — provenance belongs on the
540
- * data, not the container's size, so `rows.length === 1` must be a plain
541
- * comparison. Iteration (`for…of`, spread) yields raw elements.
542
- */
543
- export interface WrappedArray<U> {
544
- readonly length: number;
545
- readonly [index: number]: Wrapped<U>;
546
- /** Recover the raw array (elements unwrapped). */
547
- unwrap(): U[];
548
- /** Run the raw array through `fn`, keeping provenance (op path + `<label>`),
549
- * and get back a navigable handle to the result. See {@link Carrier.transform}. */
550
- transform<R = unknown>(label: string, fn: (raw: U[]) => R): Wrapped<R>;
551
- at(index: number): Wrapped<U> | undefined;
552
- find(
553
- predicate: (value: U, index: number, obj: U[]) => unknown,
554
- ): Wrapped<U> | undefined;
555
- findLast(
556
- predicate: (value: U, index: number, obj: U[]) => unknown,
557
- ): Wrapped<U> | undefined;
558
- findIndex(predicate: (value: U, index: number, obj: U[]) => unknown): number;
559
- findLastIndex(
560
- predicate: (value: U, index: number, obj: U[]) => unknown,
561
- ): number;
562
- filter(
563
- predicate: (value: U, index: number, array: U[]) => unknown,
564
- ): WrappedArray<U>;
565
- map<R>(callback: (value: U, index: number, array: U[]) => R): WrappedArray<R>;
566
- slice(start?: number, end?: number): WrappedArray<U>;
567
- concat(...items: U[][]): WrappedArray<U>;
568
- flat(): WrappedArray<unknown>;
569
- flatMap<R>(callback: (value: U, index: number, array: U[]) => R): WrappedArray<R>;
570
- /** Note: returns a `Carrier<boolean>` at runtime (re-wrapped for provenance),
571
- * so use `arr.includes(x).unwrap()` or `expect(arr.includes(x))` rather than
572
- * a bare `if`. */
573
- includes(value: U, fromIndex?: number): Carrier<boolean>;
574
- indexOf(value: U, fromIndex?: number): Carrier<number>;
575
- lastIndexOf(value: U, fromIndex?: number): Carrier<number>;
576
- some(predicate: (value: U, index: number, array: U[]) => unknown): Carrier<boolean>;
577
- every(predicate: (value: U, index: number, array: U[]) => unknown): Carrier<boolean>;
578
- /** Iteration yields *raw* elements (the runtime forwards the raw iterator). */
579
- [Symbol.iterator](): IterableIterator<U>;
580
- }
581
-
582
- /**
583
- * The view `ctx.fetch` resolves to in every context (a spectest op wraps
584
- * unconditionally): a {@link Response} whose status-line accessors are
585
- * {@link Carrier}s — so a raw `res.status === 200` is a *type error*
586
- * (status is a `Carrier<number>`, not a number), the exact mistake that
587
- * used to silently always be false. Compare `res.status.unwrap() === 200`
588
- * or `res.unwrap().status === 200`, or assert with `expect(res.status)`.
589
- *
590
- * `json<T>()` / `text()` return {@link Wrapped} body values; `.unwrap()`
591
- * (or {@link unwrap the whole response}) recovers the plain `Response`.
592
- */
593
- export interface WrappedResponse {
594
- readonly status: Carrier<number>;
595
- readonly ok: Carrier<boolean>;
596
- readonly statusText: Carrier<string>;
597
- readonly url: Carrier<string>;
598
- readonly redirected: Carrier<boolean>;
599
- readonly type: Carrier<string>;
600
- readonly headers: Headers;
601
- readonly bodyUsed: boolean;
602
- json<T = unknown>(): Promise<Wrapped<T>>;
603
- text(): Promise<Carrier<string>>;
604
- arrayBuffer(): Promise<ArrayBuffer>;
605
- blob(): Promise<Blob>;
606
- formData(): Promise<FormData>;
607
- clone(): WrappedResponse;
608
- /** Recover the underlying raw {@link Response} (a real `number` status,
609
- * an unwrapped body, etc.). */
610
- unwrap(): Response;
611
- }
612
-
613
- /** The signature of `ctx.fetch`: a `fetch` that resolves to a
614
- * {@link WrappedResponse} so reads carry provenance into assertions. */
615
- export type SpectestFetch = (
616
- input: RequestInfo | URL,
617
- init?: RequestInit,
618
- ) => Promise<WrappedResponse>;
619
-
620
- /**
621
- * Bespoke wrapper for `fetch` responses. Reads on `status` / `ok` /
622
- * `statusText` / `url` / `redirected` / `type` return carriers tagged
623
- * to `sourceSeq`. The body-reading methods (`json`, `text`) return the
624
- * resolved value wrapped under `path: ["body"]`. Everything else passes
625
- * through bound to the real Response.
626
- */
627
- export function wrapResponse(res: Response, sourceSeq: number | undefined): WrappedResponse {
628
- const tag: OpTag = { sourceSeq, path: [] };
629
- const carrierProps = new Set([
630
- "status",
631
- "ok",
632
- "statusText",
633
- "url",
634
- "redirected",
635
- "type",
636
- ]);
637
- const bodyMethods = new Set(["json", "text"]);
638
- const handler: ProxyHandler<Response> = {
639
- get(target, prop) {
640
- if (prop === OP_TAG) return tag;
641
- if (prop === UNWRAP) return target;
642
- // Full recursive unwrap (see the note in `wrapObject`).
643
- if (prop === "unwrap") return () => readRaw(target);
644
- if (prop === "then") return undefined;
645
-
646
- if (typeof prop === "string" && carrierProps.has(prop)) {
647
- const value = (target as unknown as Record<string, unknown>)[prop];
648
- return wrap(value, sourceSeq, [prop]);
649
- }
650
- if (typeof prop === "string" && bodyMethods.has(prop)) {
651
- const fn = (target as unknown as Record<string, unknown>)[prop] as
652
- | ((...a: unknown[]) => Promise<unknown>)
653
- | undefined;
654
- if (typeof fn !== "function") return fn;
655
- return async (...args: unknown[]) => {
656
- const value = await fn.apply(target, args);
657
- return wrap(value, sourceSeq, ["body"]);
658
- };
659
- }
660
- const value = (target as unknown as Record<string | symbol, unknown>)[
661
- prop as string | symbol
662
- ];
663
- return typeof value === "function"
664
- ? (value as (...a: unknown[]) => unknown).bind(target)
665
- : value;
666
- },
667
- has(target, prop) {
668
- if (prop === OP_TAG || prop === UNWRAP) return true;
669
- return Reflect.has(target, prop);
670
- },
671
- };
672
- return new Proxy(res, handler) as unknown as WrappedResponse;
673
- }