( messages: Message[], f: () => Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]>, )
| 86 | } |
| 87 | |
| 88 | export async function withVCR( |
| 89 | messages: Message[], |
| 90 | f: () => Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]>, |
| 91 | ): Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]> { |
| 92 | if (!shouldUseVCR()) { |
| 93 | return await f() |
| 94 | } |
| 95 | |
| 96 | const messagesForAPI = normalizeMessagesForAPI( |
| 97 | messages.filter(_ => { |
| 98 | if (_.type !== 'user') { |
| 99 | return true |
| 100 | } |
| 101 | if (_.isMeta) { |
| 102 | return false |
| 103 | } |
| 104 | return true |
| 105 | }), |
| 106 | ) |
| 107 | |
| 108 | const dehydratedInput = mapMessages( |
| 109 | messagesForAPI.map(_ => _.message.content), |
| 110 | dehydrateValue, |
| 111 | ) |
| 112 | const filename = join( |
| 113 | process.env.CLAUDE_CODE_TEST_FIXTURES_ROOT ?? getCwd(), |
| 114 | `fixtures/${dehydratedInput.map(_ => createHash('sha1').update(jsonStringify(_)).digest('hex').slice(0, 6)).join('-')}.json`, |
| 115 | ) |
| 116 | |
| 117 | // Fetch cached fixture |
| 118 | try { |
| 119 | const cached = jsonParse( |
| 120 | await readFile(filename, { encoding: 'utf8' }), |
| 121 | ) as { output: (AssistantMessage | StreamEvent)[] } |
| 122 | cached.output.forEach(addCachedCostToTotalSessionCost) |
| 123 | return cached.output.map((message, index) => |
| 124 | mapMessage(message, hydrateValue, index, randomUUID()), |
| 125 | ) |
| 126 | } catch (e: unknown) { |
| 127 | const code = getErrnoCode(e) |
| 128 | if (code !== 'ENOENT') { |
| 129 | throw e |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | if (env.isCI && !isEnvTruthy(process.env.VCR_RECORD)) { |
| 134 | throw new Error( |
| 135 | `Anthropic API fixture missing: ${filename}. Re-run tests with VCR_RECORD=1, then commit the result. Input messages:\n${jsonStringify(dehydratedInput, null, 2)}`, |
| 136 | ) |
| 137 | } |
| 138 | |
| 139 | // Create & write new fixture |
| 140 | const results = await f() |
| 141 | if (env.isCI && !isEnvTruthy(process.env.VCR_RECORD)) { |
| 142 | return results |
| 143 | } |
| 144 | |
| 145 | await mkdir(dirname(filename), { recursive: true }) |
no test coverage detected