MCPcopy
hub / github.com/codeaashu/claude-code / withVCR

Function withVCR

src/services/vcr.ts:88–161  ·  view source on GitHub ↗
(
  messages: Message[],
  f: () => Promise<(AssistantMessage | StreamEvent | SystemAPIErrorMessage)[]>,
)

Source from the content-addressed store, hash-verified

86}
87
88export 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 })

Callers 3

withStreamingVCRFunction · 0.85
queryHaikuFunction · 0.85
queryWithModelFunction · 0.85

Calls 14

shouldUseVCRFunction · 0.85
normalizeMessagesForAPIFunction · 0.85
mapMessagesFunction · 0.85
getCwdFunction · 0.85
jsonStringifyFunction · 0.85
jsonParseFunction · 0.85
readFileFunction · 0.85
mapMessageFunction · 0.85
getErrnoCodeFunction · 0.85
isEnvTruthyFunction · 0.85
mkdirFunction · 0.85
forEachMethod · 0.80

Tested by

no test coverage detected