{"version":3,"file":"transcription.cjs","names":["getTestId","matchFixture","applyChaos","flattenHeaders","proxyAndRecord","isErrorResponse","isTranscriptionResponse"],"sources":["../src/transcription.ts"],"sourcesContent":["import type * as http from \"node:http\";\nimport type { ChatCompletionRequest, Fixture, HandlerDefaults } from \"./types.js\";\nimport { isTranscriptionResponse, isErrorResponse, flattenHeaders, getTestId } from \"./helpers.js\";\nimport { matchFixture } from \"./router.js\";\nimport { writeErrorResponse } from \"./sse-writer.js\";\nimport type { Journal } from \"./journal.js\";\nimport { applyChaos } from \"./chaos.js\";\nimport { proxyAndRecord } from \"./recorder.js\";\n\n/**\n * Extract a text field from multipart form data using regex.\n * NOTE: This runs against the full body including binary audio data.\n * It works because text metadata fields (model, response_format, etc.)\n * appear before the binary audio part in standard multipart encoding.\n * A proper multipart parser would be more robust but is overkill for\n * the small set of fields we extract.\n */\nfunction extractFormField(raw: string, fieldName: string): string | undefined {\n  const pattern = new RegExp(\n    `Content-Disposition:\\\\s*form-data;[^\\\\r\\\\n]*name=\"${fieldName}\"[^\\\\r\\\\n]*\\\\r\\\\n\\\\r\\\\n([^\\\\r\\\\n]*)`,\n    \"i\",\n  );\n  const match = raw.match(pattern);\n  return match?.[1];\n}\n\nexport async function handleTranscription(\n  req: http.IncomingMessage,\n  res: http.ServerResponse,\n  raw: string,\n  fixtures: Fixture[],\n  journal: Journal,\n  defaults: HandlerDefaults,\n  setCorsHeaders: (res: http.ServerResponse) => void,\n): Promise<void> {\n  setCorsHeaders(res);\n  const path = req.url ?? \"/v1/audio/transcriptions\";\n  const method = req.method ?? \"POST\";\n\n  const model = extractFormField(raw, \"model\") ?? \"whisper-1\";\n  const responseFormat = extractFormField(raw, \"response_format\") ?? \"json\";\n\n  const syntheticReq: ChatCompletionRequest = {\n    model,\n    messages: [],\n    _endpointType: \"transcription\",\n  };\n\n  const testId = getTestId(req);\n  const fixture = matchFixture(\n    fixtures,\n    syntheticReq,\n    journal.getFixtureMatchCountsForTest(testId),\n    defaults.requestTransform,\n  );\n\n  if (fixture) {\n    journal.incrementFixtureMatchCount(fixture, fixtures, testId);\n    defaults.logger.debug(`Fixture matched: ${JSON.stringify(fixture.match).slice(0, 120)}`);\n  } else {\n    defaults.logger.debug(`No fixture matched for request`);\n  }\n\n  if (\n    applyChaos(\n      res,\n      fixture,\n      defaults.chaos,\n      req.headers,\n      journal,\n      { method, path, headers: flattenHeaders(req.headers), body: syntheticReq },\n      defaults.registry,\n      defaults.logger,\n    )\n  )\n    return;\n\n  if (!fixture) {\n    if (defaults.record) {\n      const proxied = await proxyAndRecord(\n        req,\n        res,\n        syntheticReq,\n        \"openai\",\n        req.url ?? \"/v1/audio/transcriptions\",\n        fixtures,\n        defaults,\n        raw,\n      );\n      if (proxied) {\n        journal.add({\n          method,\n          path,\n          headers: flattenHeaders(req.headers),\n          body: syntheticReq,\n          response: { status: res.statusCode ?? 200, fixture: null, source: \"proxy\" },\n        });\n        return;\n      }\n    }\n\n    const strictStatus = defaults.strict ? 503 : 404;\n    const strictMessage = defaults.strict\n      ? \"Strict mode: no fixture matched\"\n      : \"No fixture matched\";\n    journal.add({\n      method,\n      path,\n      headers: flattenHeaders(req.headers),\n      body: syntheticReq,\n      response: { status: strictStatus, fixture: null },\n    });\n    writeErrorResponse(\n      res,\n      strictStatus,\n      JSON.stringify({\n        error: {\n          message: strictMessage,\n          type: \"invalid_request_error\",\n          code: \"no_fixture_match\",\n        },\n      }),\n    );\n    return;\n  }\n\n  const response = fixture.response;\n\n  if (isErrorResponse(response)) {\n    const status = response.status ?? 500;\n    journal.add({\n      method,\n      path,\n      headers: flattenHeaders(req.headers),\n      body: syntheticReq,\n      response: { status, fixture },\n    });\n    writeErrorResponse(res, status, JSON.stringify(response));\n    return;\n  }\n\n  if (!isTranscriptionResponse(response)) {\n    journal.add({\n      method,\n      path,\n      headers: flattenHeaders(req.headers),\n      body: syntheticReq,\n      response: { status: 500, fixture },\n    });\n    writeErrorResponse(\n      res,\n      500,\n      JSON.stringify({\n        error: {\n          message: \"Fixture response is not a transcription type\",\n          type: \"server_error\",\n        },\n      }),\n    );\n    return;\n  }\n\n  journal.add({\n    method,\n    path,\n    headers: flattenHeaders(req.headers),\n    body: syntheticReq,\n    response: { status: 200, fixture },\n  });\n\n  const t = response.transcription;\n  const useVerbose = responseFormat === \"verbose_json\" || t.words != null || t.segments != null;\n\n  if (useVerbose) {\n    res.writeHead(200, { \"Content-Type\": \"application/json\" });\n    res.end(\n      JSON.stringify({\n        task: \"transcribe\",\n        language: t.language ?? \"english\",\n        duration: t.duration ?? 0,\n        text: t.text,\n        words: t.words ?? [],\n        segments: t.segments ?? [],\n      }),\n    );\n  } else {\n    res.writeHead(200, { \"Content-Type\": \"application/json\" });\n    res.end(JSON.stringify({ text: t.text }));\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAiBA,SAAS,iBAAiB,KAAa,WAAuC;CAC5E,MAAM,UAAU,IAAI,OAClB,qDAAqD,UAAU,sCAC/D,IACD;AAED,QADc,IAAI,MAAM,QAAQ,GACjB;;AAGjB,eAAsB,oBACpB,KACA,KACA,KACA,UACA,SACA,UACA,gBACe;AACf,gBAAe,IAAI;CACnB,MAAM,OAAO,IAAI,OAAO;CACxB,MAAM,SAAS,IAAI,UAAU;CAE7B,MAAM,QAAQ,iBAAiB,KAAK,QAAQ,IAAI;CAChD,MAAM,iBAAiB,iBAAiB,KAAK,kBAAkB,IAAI;CAEnE,MAAM,eAAsC;EAC1C;EACA,UAAU,EAAE;EACZ,eAAe;EAChB;CAED,MAAM,SAASA,0BAAU,IAAI;CAC7B,MAAM,UAAUC,4BACd,UACA,cACA,QAAQ,6BAA6B,OAAO,EAC5C,SAAS,iBACV;AAED,KAAI,SAAS;AACX,UAAQ,2BAA2B,SAAS,UAAU,OAAO;AAC7D,WAAS,OAAO,MAAM,oBAAoB,KAAK,UAAU,QAAQ,MAAM,CAAC,MAAM,GAAG,IAAI,GAAG;OAExF,UAAS,OAAO,MAAM,iCAAiC;AAGzD,KACEC,yBACE,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