@bitfab/sdk 0.26.1 → 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.
- package/dist/{chunk-SJFOTDP3.js → chunk-PFV4MPNS.js} +88 -14
- package/dist/chunk-PFV4MPNS.js.map +1 -0
- package/dist/{replay-KYGI6LJY.js → chunk-RNTDM6WM.js} +286 -10
- package/dist/chunk-RNTDM6WM.js.map +1 -0
- package/dist/index.cjs +180 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -6
- package/dist/index.d.ts +43 -6
- package/dist/index.js +8 -4
- package/dist/node.cjs +180 -52
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +8 -4
- package/dist/node.js.map +1 -1
- package/dist/replay-66KNEAMO.js +11 -0
- package/dist/replay-66KNEAMO.js.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-26MUT4IP.js +0 -242
- package/dist/chunk-26MUT4IP.js.map +0 -1
- package/dist/chunk-SJFOTDP3.js.map +0 -1
- package/dist/replay-KYGI6LJY.js.map +0 -1
|
@@ -1,12 +1,259 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
}
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var BitfabError = class extends Error {
|
|
3
|
+
constructor(message, url) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.url = url;
|
|
6
|
+
this.name = "BitfabError";
|
|
7
|
+
}
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
// src/warnOnce.ts
|
|
11
|
+
var warned = /* @__PURE__ */ new Set();
|
|
12
|
+
function warnOnce(key, message) {
|
|
13
|
+
if (warned.has(key)) {
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
warned.add(key);
|
|
17
|
+
try {
|
|
18
|
+
console.warn(`[bitfab] ${message}`);
|
|
19
|
+
} catch {
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// src/randomUuid.ts
|
|
24
|
+
function randomUuid() {
|
|
25
|
+
const globalCrypto = globalThis.crypto;
|
|
26
|
+
if (typeof globalCrypto?.randomUUID === "function") {
|
|
27
|
+
try {
|
|
28
|
+
return globalCrypto.randomUUID();
|
|
29
|
+
} catch {
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
warnOnce(
|
|
33
|
+
"crypto-unavailable",
|
|
34
|
+
"global crypto.randomUUID is unavailable; using a non-cryptographic fallback for trace/span ids. Tracing works normally (ids are correlation-only, not security-sensitive)."
|
|
35
|
+
);
|
|
36
|
+
return fallbackUuidV4();
|
|
37
|
+
}
|
|
38
|
+
function fallbackUuidV4() {
|
|
39
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => {
|
|
40
|
+
const rand = Math.random() * 16 | 0;
|
|
41
|
+
const value = char === "x" ? rand : rand & 3 | 8;
|
|
42
|
+
return value.toString(16);
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// src/asyncStorage.ts
|
|
47
|
+
var AsyncLocalStorageClass = null;
|
|
48
|
+
var initDone = false;
|
|
49
|
+
function registerAsyncLocalStorageClass(cls) {
|
|
50
|
+
if (!AsyncLocalStorageClass) {
|
|
51
|
+
AsyncLocalStorageClass = cls;
|
|
52
|
+
}
|
|
53
|
+
initDone = true;
|
|
54
|
+
}
|
|
55
|
+
function assertAsyncStorageRegistered() {
|
|
56
|
+
if (!AsyncLocalStorageClass) {
|
|
57
|
+
console.warn(
|
|
58
|
+
"Bitfab: AsyncLocalStorage not available \u2014 nested span context will not propagate."
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
var asyncStorageReady = (typeof process !== "undefined" && process.versions?.node ? (
|
|
63
|
+
// The join trick hides "node:async_hooks" from static analysis so
|
|
64
|
+
// bundlers that ban Node.js built-ins don't fail at build time.
|
|
65
|
+
// webpackIgnore tells webpack/turbopack to emit a native import()
|
|
66
|
+
// so Node.js can resolve the module at runtime.
|
|
67
|
+
import(
|
|
68
|
+
/* webpackIgnore: true */
|
|
69
|
+
["node", "async_hooks"].join(":")
|
|
70
|
+
).then(
|
|
71
|
+
(mod) => {
|
|
72
|
+
registerAsyncLocalStorageClass(mod.AsyncLocalStorage);
|
|
73
|
+
}
|
|
74
|
+
).catch(() => {
|
|
75
|
+
})
|
|
76
|
+
) : Promise.resolve()).then(() => {
|
|
77
|
+
initDone = true;
|
|
78
|
+
});
|
|
79
|
+
function isAsyncStorageInitDone() {
|
|
80
|
+
return initDone;
|
|
81
|
+
}
|
|
82
|
+
function createAsyncLocalStorage() {
|
|
83
|
+
return AsyncLocalStorageClass ? new AsyncLocalStorageClass() : null;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// src/replayContext.ts
|
|
87
|
+
var replayContextStorage = null;
|
|
88
|
+
var replayContextReady = asyncStorageReady.then(() => {
|
|
89
|
+
replayContextStorage = createAsyncLocalStorage();
|
|
90
|
+
});
|
|
91
|
+
function getReplayContext() {
|
|
92
|
+
return replayContextStorage?.getStore() ?? null;
|
|
93
|
+
}
|
|
94
|
+
function runWithReplayContext(ctx, fn) {
|
|
95
|
+
if (replayContextStorage) {
|
|
96
|
+
return replayContextStorage.run(ctx, fn);
|
|
97
|
+
}
|
|
98
|
+
return fn();
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// src/serialize.ts
|
|
102
|
+
import superjson from "superjson";
|
|
103
|
+
var MAX_SERIALIZED_BYTES = 512e3;
|
|
104
|
+
var MAX_FRAMEWORK_SERIALIZED_BYTES = 2e6;
|
|
105
|
+
function describeValue(value) {
|
|
106
|
+
try {
|
|
107
|
+
const ctorName = value?.constructor?.name;
|
|
108
|
+
if (ctorName && ctorName !== "Object") {
|
|
109
|
+
return ctorName;
|
|
110
|
+
}
|
|
111
|
+
} catch {
|
|
112
|
+
}
|
|
113
|
+
return typeof value;
|
|
114
|
+
}
|
|
115
|
+
function unserializableStub(value, reason) {
|
|
116
|
+
warnOnce(
|
|
117
|
+
`serialize:${reason.replace(/\d+/g, "N")}`,
|
|
118
|
+
`a value could not be fully serialized for a span (${reason}); it was replaced with a placeholder. The span still ships, but its captured input/output is incomplete.`
|
|
119
|
+
);
|
|
120
|
+
let summary;
|
|
121
|
+
try {
|
|
122
|
+
summary = `<unserializable: ${describeValue(value)} (${reason})>`;
|
|
123
|
+
} catch {
|
|
124
|
+
summary = `<unserializable (${reason})>`;
|
|
125
|
+
}
|
|
126
|
+
return { json: summary };
|
|
127
|
+
}
|
|
128
|
+
function serializeValue(value) {
|
|
129
|
+
try {
|
|
130
|
+
const { json, meta } = superjson.serialize(value);
|
|
131
|
+
let size;
|
|
132
|
+
try {
|
|
133
|
+
size = JSON.stringify(json).length;
|
|
134
|
+
} catch {
|
|
135
|
+
return unserializableStub(value, "stringify_failed_after_superjson");
|
|
136
|
+
}
|
|
137
|
+
if (size > MAX_SERIALIZED_BYTES) {
|
|
138
|
+
return unserializableStub(value, `too_large_${size}_bytes`);
|
|
139
|
+
}
|
|
140
|
+
return meta ? { json, meta } : { json };
|
|
141
|
+
} catch {
|
|
142
|
+
try {
|
|
143
|
+
return { json: JSON.parse(JSON.stringify(value)) };
|
|
144
|
+
} catch {
|
|
145
|
+
return unserializableStub(value, "json_stringify_failed");
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
function deserializeValue(serialized) {
|
|
150
|
+
if (serialized.meta === void 0) {
|
|
151
|
+
return serialized.json;
|
|
152
|
+
}
|
|
153
|
+
return superjson.deserialize({
|
|
154
|
+
json: serialized.json,
|
|
155
|
+
meta: serialized.meta
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
var MAX_SAFE_DEPTH = 6;
|
|
159
|
+
function toJsonSafe(value) {
|
|
160
|
+
return toJsonSafeReport(value).safe;
|
|
161
|
+
}
|
|
162
|
+
function toJsonSafeReport(value) {
|
|
163
|
+
const dropped = [];
|
|
164
|
+
const safe = toJsonSafeInner(value, 0, /* @__PURE__ */ new WeakSet(), dropped);
|
|
165
|
+
try {
|
|
166
|
+
const size = JSON.stringify(safe)?.length ?? 0;
|
|
167
|
+
if (size > MAX_FRAMEWORK_SERIALIZED_BYTES) {
|
|
168
|
+
warnOnce(
|
|
169
|
+
"toJsonSafe:too_large",
|
|
170
|
+
`a framework payload exceeded ${MAX_FRAMEWORK_SERIALIZED_BYTES} bytes and was replaced with a placeholder so the span still ships. The captured state for this span is incomplete.`
|
|
171
|
+
);
|
|
172
|
+
return {
|
|
173
|
+
safe: `<unserializable: too_large_${size}_bytes>`,
|
|
174
|
+
dropped: [...dropped, `too_large_${size}_bytes`]
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
} catch {
|
|
178
|
+
}
|
|
179
|
+
return { safe, dropped };
|
|
180
|
+
}
|
|
181
|
+
function toJsonSafeInner(value, depth, seen, dropped) {
|
|
182
|
+
if (value === null || value === void 0) {
|
|
183
|
+
return value;
|
|
184
|
+
}
|
|
185
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
186
|
+
return value;
|
|
187
|
+
}
|
|
188
|
+
const className = value?.constructor?.name ?? typeof value;
|
|
189
|
+
if (depth > MAX_SAFE_DEPTH) {
|
|
190
|
+
dropped.push(className);
|
|
191
|
+
return `<${className}>`;
|
|
192
|
+
}
|
|
193
|
+
if (typeof value !== "object") {
|
|
194
|
+
if (typeof value === "function" || typeof value === "symbol") {
|
|
195
|
+
dropped.push(className);
|
|
196
|
+
}
|
|
197
|
+
try {
|
|
198
|
+
return String(value);
|
|
199
|
+
} catch {
|
|
200
|
+
dropped.push(className);
|
|
201
|
+
return `<${className}>`;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
if (seen.has(value)) {
|
|
205
|
+
dropped.push(className);
|
|
206
|
+
return `<cycle ${className}>`;
|
|
207
|
+
}
|
|
208
|
+
seen.add(value);
|
|
209
|
+
let result;
|
|
210
|
+
if (Array.isArray(value)) {
|
|
211
|
+
result = value.map(
|
|
212
|
+
(item) => toJsonSafeInner(item, depth + 1, seen, dropped)
|
|
213
|
+
);
|
|
214
|
+
} else if (typeof value.toJSON === "function") {
|
|
215
|
+
try {
|
|
216
|
+
result = toJsonSafeInner(
|
|
217
|
+
value.toJSON(),
|
|
218
|
+
depth + 1,
|
|
219
|
+
seen,
|
|
220
|
+
dropped
|
|
221
|
+
);
|
|
222
|
+
} catch {
|
|
223
|
+
dropped.push(className);
|
|
224
|
+
result = `<${className}>`;
|
|
225
|
+
}
|
|
226
|
+
} else {
|
|
227
|
+
try {
|
|
228
|
+
const obj = {};
|
|
229
|
+
for (const [k, v] of Object.entries(value)) {
|
|
230
|
+
if (!k.startsWith("_")) {
|
|
231
|
+
obj[k] = toJsonSafeInner(v, depth + 1, seen, dropped);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
result = obj;
|
|
235
|
+
} catch {
|
|
236
|
+
dropped.push(className);
|
|
237
|
+
result = `<${className}>`;
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
seen.delete(value);
|
|
241
|
+
return result;
|
|
242
|
+
}
|
|
8
243
|
|
|
9
244
|
// src/replay.ts
|
|
245
|
+
var BITFAB_PROGRESS_PREFIX = "@@bitfab:progress ";
|
|
246
|
+
function reportReplayProgress(progress) {
|
|
247
|
+
const stderr = typeof process !== "undefined" ? process.stderr : void 0;
|
|
248
|
+
if (!stderr) {
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
try {
|
|
252
|
+
stderr.write(`${BITFAB_PROGRESS_PREFIX}${JSON.stringify(progress)}
|
|
253
|
+
`);
|
|
254
|
+
} catch {
|
|
255
|
+
}
|
|
256
|
+
}
|
|
10
257
|
function deserializeInputs(spanData) {
|
|
11
258
|
const inputMeta = spanData.input_meta;
|
|
12
259
|
const rawInput = spanData.input;
|
|
@@ -204,7 +451,7 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options) {
|
|
|
204
451
|
const resultItems = await mapWithConcurrency(
|
|
205
452
|
tasks,
|
|
206
453
|
maxConcurrency,
|
|
207
|
-
options?.onProgress ? (item) => {
|
|
454
|
+
options?.onProgress ? (item, index) => {
|
|
208
455
|
completed += 1;
|
|
209
456
|
if (item.error === null) {
|
|
210
457
|
succeeded += 1;
|
|
@@ -212,7 +459,20 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options) {
|
|
|
212
459
|
errored += 1;
|
|
213
460
|
}
|
|
214
461
|
try {
|
|
215
|
-
options?.onProgress?.({
|
|
462
|
+
options?.onProgress?.({
|
|
463
|
+
completed,
|
|
464
|
+
total,
|
|
465
|
+
succeeded,
|
|
466
|
+
errored,
|
|
467
|
+
item: {
|
|
468
|
+
// Source (historical) trace id, so a UI can identify the trace
|
|
469
|
+
// that just settled. The item's own traceId is the new replay
|
|
470
|
+
// trace and is assigned later (below), so use the server item.
|
|
471
|
+
traceId: serverItems[index]?.traceId ?? null,
|
|
472
|
+
error: item.error,
|
|
473
|
+
durationMs: item.durationMs
|
|
474
|
+
}
|
|
475
|
+
});
|
|
216
476
|
} catch {
|
|
217
477
|
}
|
|
218
478
|
} : void 0
|
|
@@ -269,7 +529,23 @@ async function replay(httpClient, serviceUrl, traceFunctionKey, fn, options) {
|
|
|
269
529
|
testRunUrl: `${serviceUrl}${testRunUrl}`
|
|
270
530
|
};
|
|
271
531
|
}
|
|
532
|
+
|
|
272
533
|
export {
|
|
534
|
+
BitfabError,
|
|
535
|
+
warnOnce,
|
|
536
|
+
serializeValue,
|
|
537
|
+
deserializeValue,
|
|
538
|
+
toJsonSafe,
|
|
539
|
+
toJsonSafeReport,
|
|
540
|
+
randomUuid,
|
|
541
|
+
registerAsyncLocalStorageClass,
|
|
542
|
+
assertAsyncStorageRegistered,
|
|
543
|
+
asyncStorageReady,
|
|
544
|
+
isAsyncStorageInitDone,
|
|
545
|
+
createAsyncLocalStorage,
|
|
546
|
+
getReplayContext,
|
|
547
|
+
BITFAB_PROGRESS_PREFIX,
|
|
548
|
+
reportReplayProgress,
|
|
273
549
|
replay
|
|
274
550
|
};
|
|
275
|
-
//# sourceMappingURL=
|
|
551
|
+
//# sourceMappingURL=chunk-RNTDM6WM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/warnOnce.ts","../src/randomUuid.ts","../src/asyncStorage.ts","../src/replayContext.ts","../src/serialize.ts","../src/replay.ts"],"sourcesContent":["/**\n * Shared error type for Bitfab SDK runtime errors. Lives in its own\n * module to avoid import cycles between `http.ts` and modules that need\n * to throw structured errors (e.g. `dbSnapshot.ts` validation).\n */\n\nexport class BitfabError extends Error {\n constructor(\n message: string,\n public readonly url?: string,\n ) {\n super(message)\n this.name = \"BitfabError\"\n }\n}\n","/**\n * Emit a `console.warn` at most once per distinct `key` for the life of the\n * process.\n *\n * The SDK must NEVER crash a host app, so every failure on the user's path\n * degrades silently (a span is dropped, a call runs untraced, a payload is\n * stubbed). Silent is safe but undebuggable: a user who suddenly has no traces,\n * or sees `<unserializable>` in a span, has no signal as to why. A one-time\n * warning per distinct issue restores that signal without spamming the console\n * from a hot path.\n *\n * Keys should identify the specific degradation (e.g. include the traced\n * function key) so each distinct issue warns once, not just the first one seen.\n */\nconst warned = new Set<string>()\n\nexport function warnOnce(key: string, message: string): void {\n if (warned.has(key)) {\n return\n }\n warned.add(key)\n try {\n console.warn(`[bitfab] ${message}`)\n } catch {\n // Logging must never crash the host app (e.g. a closed/replaced console).\n }\n}\n\n/** Test-only: clear the dedup set so a warning can fire again. */\nexport function _resetWarnOnce(): void {\n warned.clear()\n}\n","/**\n * Generate a UUID v4 without assuming a global `crypto`.\n *\n * `crypto.randomUUID()` is the fast path and exists in every mainstream modern\n * runtime (Node >= 19, all browsers, Deno, Vercel edge, Cloudflare Workers).\n * But the SDK must NEVER crash a host app, and a few runtimes it can legitimately\n * run in lack a global `crypto` or `crypto.randomUUID` (Node < 19 without a\n * polyfill, older React Native, some sandboxes). There, an unguarded\n * `crypto.randomUUID()` throws on the user's call path. This helper falls back\n * to a `Math.random()`-based v4 string instead.\n *\n * The fallback is NOT cryptographically secure. That is fine: trace and span\n * IDs only need to be unique enough to correlate the spans of one trace; they\n * are never security-sensitive.\n */\nimport { warnOnce } from \"./warnOnce.js\"\n\nexport function randomUuid(): string {\n const globalCrypto = (\n globalThis as { crypto?: { randomUUID?: () => string } }\n ).crypto\n if (typeof globalCrypto?.randomUUID === \"function\") {\n try {\n return globalCrypto.randomUUID()\n } catch {\n // Fall through to the manual generator below.\n }\n }\n warnOnce(\n \"crypto-unavailable\",\n \"global crypto.randomUUID is unavailable; using a non-cryptographic fallback for trace/span ids. Tracing works normally (ids are correlation-only, not security-sensitive).\",\n )\n return fallbackUuidV4()\n}\n\n/**\n * RFC 4122 version 4 layout filled from `Math.random()`. Used only when a usable\n * global `crypto.randomUUID` is unavailable.\n */\nfunction fallbackUuidV4(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (char) => {\n const rand = (Math.random() * 16) | 0\n const value = char === \"x\" ? rand : (rand & 0x3) | 0x8\n return value.toString(16)\n })\n}\n","/**\n * Shared AsyncLocalStorage loader.\n *\n * Provides two ways to initialize AsyncLocalStorage:\n *\n * 1. **Synchronous registration** (preferred for Node.js):\n * `asyncStorageNode.ts` calls `registerAsyncLocalStorageClass()` at module\n * evaluation time, so the class is available immediately — no async gap.\n * The `node.ts` entry point imports it before anything else.\n *\n * 2. **Async dynamic import** (fallback for the default entry point):\n * Loads `node:async_hooks` via a bundler-safe dynamic import. This is used\n * by the default `index.ts` entry point so the SDK works in browsers\n * (where the import silently fails) and in Node.js when imported via the\n * default entry point.\n *\n * ## Why the dynamic import looks like this\n *\n * We need to handle three environments:\n *\n * 1. **Pure Node.js** — `import(\"node:async_hooks\")` works natively.\n * 2. **Webpack/Turbopack (Next.js server)** — The bundler processes\n * `import()` calls at build time. The `webpackIgnore` magic comment tells\n * webpack (and turbopack) to emit a native `import()` call instead of\n * trying to resolve it, so Node.js handles it at runtime.\n * 3. **Browsers / Edge** — The `process.versions?.node` guard prevents\n * execution entirely. If it somehow runs, `.catch(() => {})` swallows\n * the failure.\n */\n\nexport interface AsyncLocalStorageLike<T> {\n getStore(): T | undefined\n run<R>(store: T, fn: () => R): R\n}\n\nlet AsyncLocalStorageClass: (new () => AsyncLocalStorageLike<unknown>) | null =\n null\nlet initDone = false\n\n/**\n * Register the AsyncLocalStorage class synchronously.\n *\n * Called by `asyncStorageNode.ts` at module evaluation time so the class\n * is available before any span is created — no async gap, no race condition.\n *\n * Safe to call multiple times; subsequent calls are no-ops.\n */\nexport function registerAsyncLocalStorageClass(\n cls: new () => AsyncLocalStorageLike<unknown>,\n): void {\n if (!AsyncLocalStorageClass) {\n AsyncLocalStorageClass = cls\n }\n initDone = true\n}\n\n/**\n * Assert that AsyncLocalStorage was registered successfully.\n *\n * Called by `node.ts` after importing `asyncStorageNode.ts` to catch\n * import-order bugs at startup rather than silently degrading to the\n * browser fallback (flat spans with no nesting).\n *\n * This should ONLY be called from the Node.js entry point where we\n * know `node:async_hooks` must be available.\n */\nexport function assertAsyncStorageRegistered(): void {\n if (!AsyncLocalStorageClass) {\n console.warn(\n \"Bitfab: AsyncLocalStorage not available — nested span context will not propagate.\",\n )\n }\n}\n\nexport const asyncStorageReady: Promise<void> = (\n typeof process !== \"undefined\" && process.versions?.node\n ? // The join trick hides \"node:async_hooks\" from static analysis so\n // bundlers that ban Node.js built-ins don't fail at build time.\n // webpackIgnore tells webpack/turbopack to emit a native import()\n // so Node.js can resolve the module at runtime.\n import(\n /* webpackIgnore: true */\n [\"node\", \"async_hooks\"].join(\":\")\n )\n .then(\n (mod: {\n AsyncLocalStorage: new () => AsyncLocalStorageLike<unknown>\n }) => {\n registerAsyncLocalStorageClass(mod.AsyncLocalStorage)\n },\n )\n .catch(() => {})\n : Promise.resolve()\n).then(() => {\n initDone = true\n})\n\nexport function isAsyncStorageInitDone(): boolean {\n return initDone\n}\n\nexport function createAsyncLocalStorage<T>(): AsyncLocalStorageLike<T> | null {\n return AsyncLocalStorageClass\n ? (new AsyncLocalStorageClass() as AsyncLocalStorageLike<T>)\n : null\n}\n","/**\n * Replay context propagation via AsyncLocalStorage.\n *\n * When set, the withSpan wrapper injects testRunId into the span payload\n * so that new spans created during replay are linked to the test run.\n * Optionally carries a mock tree so child spans can return historical\n * outputs instead of executing.\n */\n\nimport {\n type AsyncLocalStorageLike,\n asyncStorageReady,\n createAsyncLocalStorage,\n} from \"./asyncStorage.js\"\n\n/** A single span entry in the mock tree with its historical output. */\nexport interface MockSpan {\n sourceSpanId: string\n output: unknown\n outputMeta?: unknown\n}\n\n/**\n * Per-item DB branch resolved by the Bitfab service from the source\n * trace's `dbSnapshotRef`. Carried on the replay context so that\n * customer code reads `databaseUrl` through `ReplayEnvironment`, and so\n * the process-isolated replay runner can materialize it into a `.env`\n * overlay file before customer code initializes its DB client.\n *\n * `neonBranchId` is the literal Neon branch id; passing it to\n * `releaseDbBranchLease` deletes that branch.\n */\nexport interface DbBranchLease {\n neonBranchId: string\n /** Env var name the customer's app reads, e.g. \"DATABASE_URL\". */\n envKey: string\n databaseUrl: string\n expiresAt: string\n /**\n * The instant the branch was pinned to (the source trace's wall clock).\n * Echoed back in `db_snapshot_usage` on the replayed trace's completion.\n */\n snapshotTimestamp?: string\n providerConsoleUrl?: string\n readOnly?: boolean\n}\n\n/**\n * Pre-built lookup table of historical span outputs.\n * Keys are `${traceFunctionKey}:${spanName}:${callIndex}` so that repeated\n * calls with the same (key, name) are matched by call order, but spans\n * sharing only the traceFunctionKey (different name) do not collide.\n */\nexport interface MockTree {\n spans: Map<string, MockSpan>\n}\n\nexport interface ReplayContext {\n testRunId: string\n traceId?: string\n inputSourceSpanId?: string\n /**\n * External trace ID from `external_traces.id`. Used for span-chain\n * lookup against the source platform's trace tree (Braintrust, etc.).\n * NOT the same as the Bitfab `traceId` — see `sourceBitfabTraceId`.\n */\n inputSourceTraceId?: string\n /**\n * The Bitfab `traces.id` of the historical trace that produced this\n * replay item's input. This is what customer-facing surfaces (e.g.\n * `ReplayEnvironment.traceId`) should expose, since it's the ID the\n * customer sees in the Bitfab dashboard.\n */\n sourceBitfabTraceId?: string\n mockTree?: MockTree\n callCounters?: Map<string, number>\n mockStrategy?: \"none\" | \"all\" | \"marked\"\n dbBranchLease?: DbBranchLease\n /**\n * Set to true by `ReplayEnvironment` the first time customer code\n * actually obtains `databaseUrl` for this item (via the getter or\n * `snapshot()`). Reported on the trace completion inside\n * `db_snapshot_usage` so the server can distinguish \"branch was\n * provisioned and exposed\" from \"branch URL was actually consumed\".\n * Any future consumption path that hands the URL to customer code by\n * other means (e.g. a process-isolated runner writing an env overlay)\n * must also set this.\n */\n dbSnapshotAccessed?: boolean\n /**\n * Collector for the replay item's trace-persistence work. When present,\n * the root span's send path pushes a promise that resolves only after\n * every span upload AND the trace completion have been sent (registered\n * synchronously at send time, so the replay runner can await it after\n * the wrapped fn resolves). This is what lets replay guarantee traces\n * are persisted server-side before `completeReplay` builds the\n * trace-ID mapping. Absent outside replay, where sends stay\n * fire-and-forget.\n */\n pendingPersistence?: Promise<unknown>[]\n}\n\nlet replayContextStorage: AsyncLocalStorageLike<ReplayContext | null> | null =\n null\n\nexport const replayContextReady: Promise<void> = asyncStorageReady.then(() => {\n replayContextStorage = createAsyncLocalStorage<ReplayContext | null>()\n})\n\n/** Get the current replay context, if any. */\nexport function getReplayContext(): ReplayContext | null {\n return replayContextStorage?.getStore() ?? null\n}\n\n/** Run a function within a replay context. */\nexport function runWithReplayContext<T>(ctx: ReplayContext, fn: () => T): T {\n if (replayContextStorage) {\n return replayContextStorage.run(ctx, fn)\n }\n return fn()\n}\n","/**\n * Serialization utilities for Bitfab SDK.\n *\n * This module provides serialization with type metadata preservation,\n * using superjson for handling special JavaScript types like Date, Map,\n * Set, BigInt, undefined, etc.\n */\n\nimport superjson from \"superjson\"\nimport { warnOnce } from \"./warnOnce.js\"\n\n/**\n * Serialized value with JSON data and optional superjson meta for type preservation.\n *\n * The json field contains the JSON-serializable data.\n * The meta field (if present) contains superjson type information for deserializing\n * special types like Date, Map, Set, BigInt, etc.\n */\nexport interface SerializedValue {\n json: unknown\n meta?: unknown\n}\n\n// Cap on serialized payload size. superjson can succeed on values like SDK\n// client instances (OpenAI, etc.) and produce hundreds of KB to MB of useless\n// internal state. Anything beyond this is replaced with a stub so the span\n// still ships and the trace isn't dropped server-side.\nconst MAX_SERIALIZED_BYTES = 512_000\n\n// A higher cap for the framework-capture path (toJsonSafe). Agent/graph states\n// (LangGraph, Claude Agent SDK) are legitimately larger than a single\n// function's args/return, so this ceiling preserves real detail while still\n// bounding the payload so the wire-side JSON.stringify can't blow up or get the\n// span rejected server-side.\nconst MAX_FRAMEWORK_SERIALIZED_BYTES = 2_000_000\n\nfunction describeValue(value: unknown): string {\n try {\n const ctorName = (value as { constructor?: { name?: string } })?.constructor\n ?.name\n if (ctorName && ctorName !== \"Object\") {\n return ctorName\n }\n } catch {\n // Property access on `value` can throw (Proxy, poisoned getter).\n }\n return typeof value\n}\n\nfunction unserializableStub(value: unknown, reason: string): SerializedValue {\n // Normalize the byte count out of the key so a too_large warning dedups\n // across differently-sized payloads instead of warning once per size.\n warnOnce(\n `serialize:${reason.replace(/\\d+/g, \"N\")}`,\n `a value could not be fully serialized for a span (${reason}); it was replaced with a placeholder. The span still ships, but its captured input/output is incomplete.`,\n )\n let summary: string\n try {\n summary = `<unserializable: ${describeValue(value)} (${reason})>`\n } catch {\n summary = `<unserializable (${reason})>`\n }\n return { json: summary }\n}\n\n/**\n * Serialize a value using superjson for trace storage.\n *\n * Handles arbitrary JavaScript values including:\n * - Date, RegExp, Error\n * - Map, Set\n * - BigInt\n * - undefined (in objects/arrays)\n * - Circular references\n *\n * Guarantees:\n * - Never throws. Pathological inputs (SDK clients, proxies, poisoned\n * getters, circular graphs that defeat superjson) return a stub string.\n * - Never returns a payload larger than MAX_SERIALIZED_BYTES; oversized\n * inputs are replaced with a stub. Without this the wire-side\n * `JSON.stringify` in http.ts can produce a request that times out or\n * gets rejected, leaving a trace with zero spans.\n *\n * @param value - Any JavaScript value to serialize\n * @returns SerializedValue with 'json' field containing the data.\n * If type metadata is needed for reconstruction, includes 'meta' field.\n *\n * @example\n * ```typescript\n * const result = serializeValue(new Date('2024-01-15T10:30:00Z'))\n * // result.json contains the ISO string\n * // result.meta contains type info for Date reconstruction\n * ```\n */\nexport function serializeValue(value: unknown): SerializedValue {\n try {\n const { json, meta } = superjson.serialize(value)\n\n let size: number\n try {\n size = JSON.stringify(json).length\n } catch {\n return unserializableStub(value, \"stringify_failed_after_superjson\")\n }\n if (size > MAX_SERIALIZED_BYTES) {\n return unserializableStub(value, `too_large_${size}_bytes`)\n }\n\n return meta ? { json, meta } : { json }\n } catch {\n try {\n return { json: JSON.parse(JSON.stringify(value)) }\n } catch {\n return unserializableStub(value, \"json_stringify_failed\")\n }\n }\n}\n\n/**\n * Deserialize a value that was serialized with serializeValue.\n *\n * @param serialized - A SerializedValue object with 'json' and optional 'meta'\n * @returns The reconstructed JavaScript value\n *\n * @example\n * ```typescript\n * const serialized = serializeValue(new Date('2024-01-15'))\n * const date = deserializeValue(serialized)\n * // date is a Date object\n * ```\n */\nexport function deserializeValue(serialized: SerializedValue): unknown {\n if (serialized.meta === undefined) {\n // No metadata, return as-is\n return serialized.json\n }\n\n // Use superjson to deserialize with type reconstruction\n // Cast json to the expected superjson type\n type SuperJSONResult = Parameters<typeof superjson.deserialize>[0]\n return superjson.deserialize({\n json: serialized.json as SuperJSONResult[\"json\"],\n meta: serialized.meta as SuperJSONResult[\"meta\"],\n })\n}\n\nconst MAX_SAFE_DEPTH = 6\n\n/**\n * Convert any value to JSON-safe primitives, never throwing.\n *\n * Produces plain objects/arrays/scalars, recursing through `toJSON()` and\n * own-enumerable properties so no raw non-serializable value (a class, a\n * BigInt-bearing object) survives into a span payload. Cycles collapse to a\n * `<cycle ...>` marker; depth is capped.\n *\n * This is the single shared \"safe serialize\" used by the framework\n * integrations that capture raw objects (LangGraph, Claude Agent SDK). Keeping\n * the recurse-the-dump logic here, in one place, is what stops a new\n * integration from reintroducing the \"dump without recursing\" bug — see\n * `serializationInvariant.test.ts`.\n */\nexport function toJsonSafe(value: unknown): unknown {\n return toJsonSafeReport(value).safe\n}\n\n/**\n * Like {@link toJsonSafe}, but also reports what could not be faithfully\n * captured.\n *\n * Returns `{ safe, dropped }` where `dropped` lists the type name behind every\n * placeholder the walker had to emit: a cycle, a max-depth cut, an oversized\n * payload, or a value that could only be stringified (a function/symbol) or\n * stubbed after a throw. A non-empty `dropped` means the captured input/output\n * is lossy. Framework handlers carry it to the send boundary so a degraded\n * capture is marked non-replayable (`serialization_degraded`) instead of being\n * shipped as if it round-trips — mirrors the Python SDK's `to_json_safe_report`\n * + `finalize_span_payload`.\n */\nexport function toJsonSafeReport(value: unknown): {\n safe: unknown\n dropped: string[]\n} {\n const dropped: string[] = []\n const safe = toJsonSafeInner(value, 0, new WeakSet(), dropped)\n // Cap output size for parity with serializeValue. A multi-MB framework\n // payload (a large LangGraph state, a long message history) would otherwise\n // be JSON.stringify'd synchronously on the user's thread in http.ts and may\n // be rejected server-side, leaving a trace with zero spans. Stub it instead\n // so the span still ships. toJsonSafeInner produces only plain\n // objects/arrays/scalars/strings, so JSON.stringify here cannot throw; the\n // try is belt-and-suspenders.\n try {\n const size = JSON.stringify(safe)?.length ?? 0\n if (size > MAX_FRAMEWORK_SERIALIZED_BYTES) {\n warnOnce(\n \"toJsonSafe:too_large\",\n `a framework payload exceeded ${MAX_FRAMEWORK_SERIALIZED_BYTES} bytes and was replaced with a placeholder so the span still ships. The captured state for this span is incomplete.`,\n )\n // Keep any drops already accumulated by the walk (cycles, functions,\n // depth cuts); a payload can be both lossy AND oversized, and the\n // non-replayable marking needs the real types, not just the size stub.\n return {\n safe: `<unserializable: too_large_${size}_bytes>`,\n dropped: [...dropped, `too_large_${size}_bytes`],\n }\n }\n } catch {\n // Keep the recursed value; the http-layer sanitizer is the final backstop.\n }\n return { safe, dropped }\n}\n\nfunction toJsonSafeInner(\n value: unknown,\n depth: number,\n seen: WeakSet<object>,\n dropped: string[],\n): unknown {\n if (value === null || value === undefined) {\n return value\n }\n if (\n typeof value === \"string\" ||\n typeof value === \"number\" ||\n typeof value === \"boolean\"\n ) {\n return value\n }\n\n const className =\n (value as { constructor?: { name?: string } })?.constructor?.name ??\n typeof value\n if (depth > MAX_SAFE_DEPTH) {\n dropped.push(className)\n return `<${className}>`\n }\n\n // Non-object composites (bigint, function, symbol) stringify directly. A\n // bigint stringifies faithfully; a function/symbol becomes a lossy summary,\n // so those are reported as dropped.\n if (typeof value !== \"object\") {\n if (typeof value === \"function\" || typeof value === \"symbol\") {\n dropped.push(className)\n }\n try {\n return String(value)\n } catch {\n dropped.push(className)\n return `<${className}>`\n }\n }\n\n if (seen.has(value as object)) {\n dropped.push(className)\n return `<cycle ${className}>`\n }\n seen.add(value as object)\n\n let result: unknown\n if (Array.isArray(value)) {\n result = value.map((item) =>\n toJsonSafeInner(item, depth + 1, seen, dropped),\n )\n } else if (typeof (value as Record<string, unknown>).toJSON === \"function\") {\n // Recurse toJSON() output: it can still hold non-serializable values (e.g.\n // a LangChain tool whose schema is a class) that would otherwise survive\n // into the span payload and crash the wire-side JSON.stringify.\n try {\n result = toJsonSafeInner(\n (value as { toJSON(): unknown }).toJSON(),\n depth + 1,\n seen,\n dropped,\n )\n } catch {\n dropped.push(className)\n result = `<${className}>`\n }\n } else {\n try {\n const obj: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) {\n if (!k.startsWith(\"_\")) {\n obj[k] = toJsonSafeInner(v, depth + 1, seen, dropped)\n }\n }\n result = obj\n } catch {\n dropped.push(className)\n result = `<${className}>`\n }\n }\n\n // Backtrack: keep only ancestors on the current path in `seen`, so a shared\n // (DAG) reference under sibling keys is serialized again rather than stubbed\n // as a false cycle. Real cycles (an ancestor referencing itself) are still\n // caught above.\n seen.delete(value as object)\n return result\n}\n","/**\n * Replay historical traces through a function and create a test run.\n *\n * The replay flow has three phases:\n * 1. Start: fetches historical traces from the server and creates a test run\n * 2. Execute: re-runs each trace's inputs through the provided function locally\n * 3. Complete: marks the test run as completed on the server\n */\n\nimport type { DbSnapshotRef } from \"./dbSnapshot.js\"\nimport { BitfabError } from \"./errors.js\"\nimport type {\n CodeChangeFile,\n HttpClient,\n SpanTreeNode,\n TokenUsage,\n} from \"./http.js\"\nimport { randomUuid } from \"./randomUuid.js\"\nimport type { DbBranchLease, MockTree } from \"./replayContext.js\"\nimport { replayContextReady, runWithReplayContext } from \"./replayContext.js\"\nimport type { ReplayEnvironment } from \"./replayEnvironment.js\"\nimport { deserializeValue } from \"./serialize.js\"\n\nexport type MockStrategy = \"none\" | \"all\" | \"marked\"\n\nexport interface ReplayOptions {\n /**\n * Maximum number of traces to replay (1-100, default 5). Ignored when\n * `traceIds` is passed (with a warning): an explicit ID list already\n * determines how many traces replay.\n */\n limit?: number\n /** Optional list of specific trace IDs to replay (max 100). */\n traceIds?: string[]\n /** Maximum number of items to process in parallel. Set to 1 for sequential. Default 10. */\n maxConcurrency?: number\n /**\n * Description of the code change being tested in this replay. Stored on\n * the resulting experiment so the change can be reviewed alongside results.\n */\n codeChangeDescription?: string\n /**\n * Files edited as part of this code change. Each entry holds the file path\n * and the full `before`/`after` contents. The agent reads each file before\n * and after editing and passes the two strings. Use `\"\"` for newly created\n * files (`before`) or deleted files (`after`).\n */\n codeChangeFiles?: CodeChangeFile[]\n /**\n * Mock strategy for child spans during replay.\n * - \"none\": everything runs real code (default)\n * - \"all\": every child withSpan returns historical output\n * - \"marked\": only spans tagged with { mockOnReplay: true } in SpanOptions are mocked\n */\n mock?: MockStrategy\n /**\n * Per-trace environment. When the source trace carries a DB branching\n * snapshot, the SDK populates `environment.databaseUrl` before invoking\n * `fn` for that item and resets it after. Customer code reads from the\n * environment to pick up the per-trace branch URL.\n */\n environment?: ReplayEnvironment\n /** Group ID to associate this replay with an experiment group for live streaming in Studio. */\n experimentGroupId?: string\n /**\n * Dataset this replay runs against. When set, the resulting experiment is\n * durably attributed to the dataset (stored on the test run), so it appears\n * under the dataset's experiments even if the trace lineage can't be\n * reconstructed. Validated server-side against the org.\n */\n datasetId?: string\n /**\n * Reshape recorded inputs before they are spread into `fn`.\n *\n * Replay pulls each trace's inputs exactly as they were captured against the\n * function's signature AT TRACE TIME. When the function's shape has since\n * changed (params renamed, reordered, collapsed into an options object, etc.),\n * the recorded inputs no longer line up and `fn(...inputs)` throws. This hook\n * lets a caller map the recorded inputs onto the current signature so replay\n * can still run.\n *\n * Receives the deserialized recorded inputs and a per-trace {@link AdaptContext}\n * (so a table-driven adapter can look up the adapted inputs by `traceId`), and\n * returns the array actually spread into `fn`. The returned array is also what\n * `ReplayItem.input` reports, so the experiment shows what was really run.\n *\n * Runs per item, inside the same try/catch as `fn`: if the adapter throws, the\n * failure is surfaced on that item's `error` rather than crashing the run.\n * Omit it to spread the recorded inputs unchanged.\n */\n adaptInputs?: (inputs: unknown[], ctx: AdaptContext) => unknown[]\n /**\n * Called once per item as it finishes, in completion order (not input\n * order), with running totals for the whole run. Use it to render replay\n * progress, for example a terminal progress bar. Replay does not know\n * pass/fail at this point (verdicts are assigned later), so the totals only\n * distinguish items whose function ran (`succeeded`) from items that threw\n * (`errored`).\n *\n * Invoked synchronously right after each item settles, so keep it cheap. A\n * throwing callback never crashes the run: the error is swallowed so progress\n * UI can't break replay.\n */\n onProgress?: (progress: ReplayProgress) => void\n}\n\n/** Running totals reported to {@link ReplayOptions.onProgress} as replay proceeds. */\nexport interface ReplayProgress {\n /** Items that have finished so far, whether they succeeded or errored. */\n completed: number\n /** Total number of items in this replay run. */\n total: number\n /** Of the completed items, how many ran the function without throwing. */\n succeeded: number\n /** Of the completed items, how many threw (their `item.error` is set). */\n errored: number\n /**\n * The single item that just settled to produce this event. `traceId` is the\n * source (historical) trace that was replayed (so a UI can identify or link\n * it); `error` is its replay error, or null when it ran ok; `durationMs` is how\n * long this one trace took to replay. Lets a progress UI show per-trace\n * pass/fail and timing as the run streams, without waiting for the full\n * {@link ReplayResult}.\n */\n item?: {\n traceId: string | null\n error: string | null\n durationMs: number | null\n }\n}\n\n/**\n * Wire prefix the Bitfab plugin scans for. Each line {@link reportReplayProgress}\n * writes is this prefix followed by the JSON of the running totals (plus the\n * settled `item`). The plugin polls these lines to report live progress while a\n * replay runs in the background; keep the SDK emitter and the plugin parser in\n * sync.\n */\nexport const BITFAB_PROGRESS_PREFIX = \"@@bitfab:progress \"\n\n/**\n * A ready-made {@link ReplayOptions.onProgress} callback for replay scripts.\n * Pass it straight in:\n *\n * ```ts\n * await bitfab.replay(\"my-fn\", fn, { limit, onProgress: reportReplayProgress })\n * ```\n *\n * It writes one `@@bitfab:progress` line per trace to stderr, which the Bitfab\n * plugin polls to report live progress while the replay runs in the background,\n * so scripts never hand-format the wire protocol.\n * stdout is left untouched for the ReplayResult JSON. Outside Node (no\n * `process.stderr`, e.g. a browser) it is a no-op, and a write failure is\n * swallowed so progress can never crash a run.\n */\nexport function reportReplayProgress(progress: ReplayProgress): void {\n const stderr = typeof process !== \"undefined\" ? process.stderr : undefined\n if (!stderr) {\n return\n }\n try {\n stderr.write(`${BITFAB_PROGRESS_PREFIX}${JSON.stringify(progress)}\\n`)\n } catch {\n // A progress reporter must never crash the replay run.\n }\n}\n\n/** Per-trace context passed to {@link ReplayOptions.adaptInputs}. */\nexport interface AdaptContext {\n /** Bitfab trace ID of the historical trace being replayed. */\n traceId: string\n /** External span ID the recorded inputs were read from. */\n sourceSpanId: string\n}\n\n/**\n * The shape an adapter module must export as `adaptInputs`.\n *\n * Author an adapter in its own file (e.g. `scripts/replay-adapters/<name>.ts`),\n * import it in your replay script, and pass it to `replay({ adaptInputs })`:\n *\n * ```ts\n * import type { AdaptInputsFn } from \"@bitfab/sdk\"\n * export const adaptInputs: AdaptInputsFn = (inputs, ctx) => [reshape(inputs)]\n * ```\n */\nexport type AdaptInputsFn = (inputs: unknown[], ctx: AdaptContext) => unknown[]\n\nexport interface ReplayItem<T> {\n /** Trace ID of the new trace created during replay. */\n traceId: string | null\n /** Deserialized inputs from the original trace. */\n input: unknown[]\n /** The result returned by the function during replay, or undefined on error. */\n result: T | undefined\n /** The original output from the historical trace. */\n originalOutput: unknown\n /** Error message if the function threw, or null on success. */\n error: string | null\n /** Original trace duration in milliseconds, or null if timestamps are missing. */\n durationMs: number | null\n /**\n * Token usage from the REPLAYED run (this item's new execution), aggregated\n * server-side from the spans it produced, or null if the run captured no\n * token data. This is the \"new\" side of a token delta: compare it against\n * the original trace's recorded usage to see how the code change moved cost.\n * Matches what Studio's experiments view shows.\n */\n tokens: TokenUsage | null\n /** Model name from the original trace, or null if not captured. */\n model: string | null\n /**\n * The DB snapshot ref the SDK captured at trace open. Useful for debugging\n * (\"what state was this trace pinned to?\") and for customers building\n * their own resolvers. Undefined when the source trace was captured\n * without `dbSnapshot` configured.\n */\n dbSnapshotRef: DbSnapshotRef | null\n}\n\nexport type { CodeChangeFile, TokenUsage }\n\nexport interface ReplayResult<T> {\n /** Individual replay items with inputs, results, and comparison data. */\n items: ReplayItem<T>[]\n /** The test run ID created on the server. */\n testRunId: string\n /** Full URL to view the test run in the dashboard. */\n testRunUrl: string\n}\n\n/**\n * Deserialize inputs from a historical span's rawData.\n *\n * Prefers superjson-serialized `input_meta` for type preservation,\n * falls back to the raw `input` field.\n */\nfunction deserializeInputs(spanData: Record<string, unknown>): unknown[] {\n const inputMeta = spanData.input_meta as unknown\n const rawInput = spanData.input\n\n // If superjson meta is available, deserialize with type reconstruction\n if (inputMeta !== undefined && inputMeta !== null) {\n const deserialized = deserializeValue({ json: rawInput, meta: inputMeta })\n if (Array.isArray(deserialized)) {\n return deserialized\n }\n return deserialized !== undefined && deserialized !== null\n ? [deserialized]\n : []\n }\n\n // Fall back to raw input\n if (Array.isArray(rawInput)) {\n return rawInput\n }\n return rawInput !== undefined && rawInput !== null ? [rawInput] : []\n}\n\n/**\n * Deserialize the original output from a historical span's rawData.\n */\nfunction deserializeOutput(spanData: Record<string, unknown>): unknown {\n const outputMeta = spanData.output_meta as unknown\n const rawOutput = spanData.output\n\n if (outputMeta !== undefined && outputMeta !== null) {\n return deserializeValue({ json: rawOutput, meta: outputMeta })\n }\n\n return rawOutput\n}\n\n/**\n * Walk the children of a root span tree node in depth-first order and build\n * a MockTree keyed by `${traceFunctionKey}:${spanName}:${callIndex}`.\n *\n * The historical root itself is NOT walked. At replay time the runtime root\n * span has `isRootSpan === true` and never queries the mockTree (mock\n * interception is skipped for root spans by design), so the root has nothing\n * to look up. Walking it would just leave an unreachable entry in the table.\n *\n * The (key, name) compound match is what disambiguates same-key spans:\n * - A wrapped function's children commonly share its traceFunctionKey via\n * the fluent `getFunction(key).withSpan({ name }, ...)` pattern. They\n * disambiguate by `name`, never colliding with each other.\n * - Recursion: same (key, name) at every depth. callIndex per (key, name)\n * orders them correctly without leaking the historical root into the\n * nested call's slot.\n * - Outer-wrapper replay scripts: the outer wrapper's `name` is distinct\n * from anything in the historical tree (it only exists at replay), so\n * its presence never disturbs counters or lookups for spans that do\n * exist in the historical tree.\n */\nfunction buildMockTree(rootNode: SpanTreeNode): MockTree {\n const spans = new Map<\n string,\n { sourceSpanId: string; output: unknown; outputMeta?: unknown }\n >()\n const counters = new Map<string, number>()\n\n function walk(node: SpanTreeNode): void {\n const key = node.traceFunctionKey\n if (key) {\n const name = node.spanName\n const counterKey = `${key}:${name}`\n const index = counters.get(counterKey) ?? 0\n counters.set(counterKey, index + 1)\n spans.set(`${counterKey}:${index}`, {\n sourceSpanId: node.sourceSpanId,\n output: node.output,\n outputMeta: node.outputMeta,\n })\n }\n for (const child of node.children) {\n walk(child)\n }\n }\n\n for (const child of rootNode.children) {\n walk(child)\n }\n\n return { spans }\n}\n\n/**\n * Execute a single replay item: fetch span data, deserialize inputs, call\n * the function within a replay context that injects testRunId into new spans.\n */\nasync function processItem<TReturn>(\n httpClient: HttpClient,\n serverItem: {\n traceId: string\n externalSpanId: string\n durationMs: number | null\n model: string | null\n dbSnapshotRef?: DbSnapshotRef\n dbBranchLease?: DbBranchLease\n },\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n testRunId: string,\n mockStrategy: MockStrategy,\n environment: ReplayEnvironment | undefined,\n adaptInputs:\n | ((inputs: unknown[], ctx: AdaptContext) => unknown[])\n | undefined,\n): Promise<ReplayItem<TReturn>> {\n // The server-side resolver materializes a Neon preview branch per item\n // during `/api/sdk/replay/start` (when the customer passed `environment`,\n // which triggers `includeDbBranchLease: true`). The lease arrives on the\n // server item; we just attach it to the replay context and release the\n // branch in `finally` so any throw (in fetch, mock-tree build, or the\n // customer fn) frees the Neon resource. Items whose source trace had\n // no snapshot ref, or whose resolve failed server-side, arrive without\n // a lease; `env.active` will be `false` for those.\n const lease = environment ? serverItem.dbBranchLease : undefined\n\n let inputs: unknown[] = []\n let originalOutput: unknown\n let result: TReturn | undefined\n let error: string | null = null\n const replayedTraceId = randomUuid()\n // Collects the root span's full persistence chain (span uploads + trace\n // completion). Awaited below so this item's trace is on the server before\n // replay() calls completeReplay. Otherwise the server's trace-ID mapping\n // races the uploads and item.traceId nulls out.\n const pendingPersistence: Promise<unknown>[] = []\n\n try {\n const span = await httpClient.getExternalSpan(serverItem.externalSpanId)\n const spanData = (span.rawData?.span_data ?? {}) as Record<string, unknown>\n\n inputs = deserializeInputs(spanData)\n originalOutput = deserializeOutput(spanData)\n\n // Reshape the recorded inputs onto the current signature when an adapter\n // is supplied. Runs before the mock tree / fn call so the adapted array is\n // what fn receives and what `item.input` reports.\n if (adaptInputs) {\n inputs = adaptInputs(inputs, {\n traceId: serverItem.traceId,\n sourceSpanId: serverItem.externalSpanId,\n })\n }\n\n // Build mock tree when mocking is active\n let mockTree: MockTree | undefined\n if (mockStrategy === \"all\" || mockStrategy === \"marked\") {\n const treeResponse = await httpClient.getSpanTree(\n serverItem.externalSpanId,\n )\n mockTree = buildMockTree(treeResponse.root)\n }\n\n const maybePromise = runWithReplayContext(\n {\n testRunId,\n traceId: replayedTraceId,\n inputSourceSpanId: span.id,\n inputSourceTraceId: span.externalTraceId,\n sourceBitfabTraceId: serverItem.traceId,\n mockTree,\n callCounters: mockTree ? new Map() : undefined,\n mockStrategy,\n dbBranchLease: lease,\n pendingPersistence,\n },\n () => fn(...inputs),\n )\n result = maybePromise instanceof Promise ? await maybePromise : maybePromise\n } catch (e) {\n error = e instanceof Error ? e.message : String(e)\n } finally {\n // Wait for this item's trace (spans + completion) to be fully persisted\n // before the item resolves. Runs on the error path too. A throwing fn\n // still emits a root span whose trace must land before completeReplay.\n await Promise.allSettled(pendingPersistence)\n if (lease) {\n try {\n await httpClient.releaseDbBranchLease(lease.neonBranchId)\n } catch (e) {\n try {\n console.warn(\n `Bitfab: failed to release DB branch ${lease.neonBranchId} (TTL janitor will catch it): ${\n e instanceof Error ? e.message : String(e)\n }`,\n )\n } catch {\n // Never crash the host\n }\n }\n }\n }\n\n return {\n traceId: replayedTraceId,\n input: inputs,\n result,\n originalOutput,\n error,\n durationMs: serverItem.durationMs ?? null,\n // Filled in by replay() from the complete-replay response once the\n // replay traces are persisted and their spans aggregated server-side.\n // Null here (and on older servers) means \"replay tokens not known\".\n tokens: null,\n model: serverItem.model ?? null,\n dbSnapshotRef: serverItem.dbSnapshotRef ?? null,\n }\n}\n\n/**\n * Run async tasks with a concurrency limit.\n * Each task factory is called when a slot opens; results preserve input order.\n */\nasync function mapWithConcurrency<T>(\n tasks: Array<() => Promise<T>>,\n maxConcurrency: number,\n onSettled?: (result: T, index: number) => void,\n): Promise<T[]> {\n const results: T[] = new Array(tasks.length)\n let nextIndex = 0\n\n async function worker(): Promise<void> {\n while (nextIndex < tasks.length) {\n const index = nextIndex++\n const result = await tasks[index]()\n results[index] = result\n onSettled?.(result, index)\n }\n }\n\n const workers = Array.from(\n { length: Math.min(maxConcurrency, tasks.length) },\n () => worker(),\n )\n await Promise.all(workers)\n return results\n}\n\n/**\n * Replay historical traces through a function and create a test run.\n *\n * @internal Called by Bitfab.replay, not part of the public API.\n */\nexport async function replay<TReturn>(\n httpClient: HttpClient,\n serviceUrl: string,\n traceFunctionKey: string,\n // biome-ignore lint/suspicious/noExplicitAny: replay deserializes inputs from historical data\n fn: (...args: any[]) => TReturn | Promise<TReturn>,\n options?: ReplayOptions,\n): Promise<ReplayResult<TReturn>> {\n if (options?.traceIds !== undefined) {\n if (options.traceIds.length === 0) {\n throw new BitfabError(\"traceIds must contain at least one trace ID.\")\n }\n if (options.traceIds.length > 100) {\n throw new BitfabError(\n `traceIds supports at most 100 trace IDs per replay (got ${options.traceIds.length}).`,\n )\n }\n }\n if (options?.limit !== undefined && options?.traceIds !== undefined) {\n try {\n console.warn(\n \"Bitfab: limit is ignored when traceIds is passed: the explicit trace ID list already determines how many traces replay.\",\n )\n } catch {\n // Never crash the host app\n }\n }\n\n await replayContextReady\n\n const {\n testRunId,\n testRunUrl,\n items: serverItems,\n } = await httpClient.startReplay(\n traceFunctionKey,\n // limit is meaningless with explicit traceIds (the ID list determines\n // the count), so it's omitted from the request entirely.\n options?.traceIds ? undefined : (options?.limit ?? 5),\n options?.traceIds,\n options?.codeChangeDescription,\n options?.codeChangeFiles,\n options?.environment !== undefined, // includeDbBranchLease\n options?.experimentGroupId,\n options?.datasetId,\n )\n\n const mockStrategy: MockStrategy = options?.mock ?? \"none\"\n const maxConcurrency = options?.maxConcurrency ?? 10\n\n const tasks = serverItems.map(\n (serverItem) => () =>\n processItem(\n httpClient,\n serverItem,\n fn,\n testRunId,\n mockStrategy,\n options?.environment,\n options?.adaptInputs,\n ),\n )\n const total = tasks.length\n let completed = 0\n let succeeded = 0\n let errored = 0\n const resultItems = await mapWithConcurrency(\n tasks,\n maxConcurrency,\n options?.onProgress\n ? (item, index) => {\n completed += 1\n if (item.error === null) {\n succeeded += 1\n } else {\n errored += 1\n }\n try {\n options?.onProgress?.({\n completed,\n total,\n succeeded,\n errored,\n item: {\n // Source (historical) trace id, so a UI can identify the trace\n // that just settled. The item's own traceId is the new replay\n // trace and is assigned later (below), so use the server item.\n traceId: serverItems[index]?.traceId ?? null,\n error: item.error,\n durationMs: item.durationMs,\n },\n })\n } catch {\n // Progress UI must never crash the replay run.\n }\n }\n : undefined,\n )\n\n // Every item awaited its own trace persistence (spans + completion) in\n // processItem, so all replay traces are on the server by now. No flush\n // needed, and completeReplay's trace-ID mapping is deterministic.\n // completeReplay failures propagate: a missing mapping means verdicts\n // can't be persisted, which callers must hear about loudly.\n const completeResult = await httpClient.completeReplay(testRunId)\n const serverTraceIds = completeResult.traceIds\n // Per-replay-trace token usage, keyed by server trace id. The REPLAYED run's\n // tokens (span-aggregated server-side), used below to fill each item.tokens.\n const replayTokens = completeResult.tokens\n\n if (serverTraceIds === undefined) {\n // Older servers don't return the mapping. Preserve the legacy\n // null-traceId behavior but say why.\n try {\n console.warn(\n \"Bitfab: server did not return replay trace IDs; item.traceId will be null (server upgrade required for verdict persistence)\",\n )\n } catch {\n // Never crash the host app\n }\n for (const item of resultItems) {\n item.traceId = null\n }\n } else {\n // Map each item's locally-generated trace ID to the server's trace row\n // ID. A completed item with no mapping means its trace was sent but the\n // server has no record. A null traceId blocks verdict persistence and\n // the Studio experiments view downstream, so this must never be silent.\n //\n // Severity splits on scope:\n // - ALL completed items missing → systemic (the replayed function isn't\n // wrapped with withSpan, or uploads are wholesale broken). Throw; the\n // run's results are unusable for persistence and silence here is the\n // exact bug this guarantee exists to prevent.\n // - SOME completed items missing → per-item upload failure (transient\n // network blip, one oversized payload). Null those items and log an\n // unmissable error, but return the run; callers can persist verdicts\n // for the items that landed instead of losing all the compute.\n const missing: string[] = []\n let completedCount = 0\n for (const item of resultItems) {\n if (item.traceId) {\n const mapped = serverTraceIds[item.traceId]\n if (item.error === null) {\n completedCount += 1\n if (mapped === undefined) {\n missing.push(item.traceId)\n }\n }\n // Pull this item's replayed-run tokens by its server trace id, before\n // item.traceId is overwritten with that id below.\n if (mapped !== undefined) {\n item.tokens = replayTokens?.[mapped] ?? null\n }\n item.traceId = mapped ?? null\n }\n }\n if (missing.length > 0) {\n const serverCount =\n completeResult.traceCount !== undefined\n ? ` The server persisted ${completeResult.traceCount} trace(s) for this run.`\n : \"\"\n if (missing.length === completedCount) {\n throw new BitfabError(\n `Replay completed but the server has no persisted trace for any of the ${completedCount} completed item(s) (testRunId ${testRunId}).${serverCount} ` +\n `Trace uploads were awaited, so either the uploads failed (check for \"Bitfab: Failed to create\" errors above) or the replayed function is not wrapped with withSpan.`,\n )\n }\n try {\n console.error(\n `Bitfab: server has no persisted trace for ${missing.length} of ${completedCount} completed replay item(s) (testRunId ${testRunId}).${serverCount} ` +\n `Their traceId is null and verdicts cannot be persisted for them. Missing: ${missing.join(\", \")}`,\n )\n } catch {\n // Never crash the host app\n }\n }\n }\n\n return {\n items: resultItems,\n testRunId,\n testRunUrl: `${serviceUrl}${testRunUrl}`,\n }\n}\n"],"mappings":";AAMO,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACE,SACgB,KAChB;AACA,UAAM,OAAO;AAFG;AAGhB,SAAK,OAAO;AAAA,EACd;AACF;;;ACAA,IAAM,SAAS,oBAAI,IAAY;AAExB,SAAS,SAAS,KAAa,SAAuB;AAC3D,MAAI,OAAO,IAAI,GAAG,GAAG;AACnB;AAAA,EACF;AACA,SAAO,IAAI,GAAG;AACd,MAAI;AACF,YAAQ,KAAK,YAAY,OAAO,EAAE;AAAA,EACpC,QAAQ;AAAA,EAER;AACF;;;ACTO,SAAS,aAAqB;AACnC,QAAM,eACJ,WACA;AACF,MAAI,OAAO,cAAc,eAAe,YAAY;AAClD,QAAI;AACF,aAAO,aAAa,WAAW;AAAA,IACjC,QAAQ;AAAA,IAER;AAAA,EACF;AACA;AAAA,IACE;AAAA,IACA;AAAA,EACF;AACA,SAAO,eAAe;AACxB;AAMA,SAAS,iBAAyB;AAChC,SAAO,uCAAuC,QAAQ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