parse.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2. import type { FinalRequestOptions } from './request-options';
  3. import { Stream } from '../core/streaming';
  4. import { type Opencode } from '../client';
  5. import { formatRequestDetails, loggerFor } from './utils/log';
  6. export type APIResponseProps = {
  7. response: Response;
  8. options: FinalRequestOptions;
  9. controller: AbortController;
  10. requestLogID: string;
  11. retryOfRequestLogID: string | undefined;
  12. startTime: number;
  13. };
  14. export async function defaultParseResponse<T>(client: Opencode, props: APIResponseProps): Promise<T> {
  15. const { response, requestLogID, retryOfRequestLogID, startTime } = props;
  16. const body = await (async () => {
  17. if (props.options.stream) {
  18. loggerFor(client).debug('response', response.status, response.url, response.headers, response.body);
  19. // Note: there is an invariant here that isn't represented in the type system
  20. // that if you set `stream: true` the response type must also be `Stream<T>`
  21. if (props.options.__streamClass) {
  22. return props.options.__streamClass.fromSSEResponse(response, props.controller, client) as any;
  23. }
  24. return Stream.fromSSEResponse(response, props.controller, client) as any;
  25. }
  26. // fetch refuses to read the body when the status code is 204.
  27. if (response.status === 204) {
  28. return null as T;
  29. }
  30. if (props.options.__binaryResponse) {
  31. return response as unknown as T;
  32. }
  33. const contentType = response.headers.get('content-type');
  34. const mediaType = contentType?.split(';')[0]?.trim();
  35. const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json');
  36. if (isJSON) {
  37. const json = await response.json();
  38. return json as T;
  39. }
  40. const text = await response.text();
  41. return text as unknown as T;
  42. })();
  43. loggerFor(client).debug(
  44. `[${requestLogID}] response parsed`,
  45. formatRequestDetails({
  46. retryOfRequestLogID,
  47. url: response.url,
  48. status: response.status,
  49. body,
  50. durationMs: Date.now() - startTime,
  51. }),
  52. );
  53. return body;
  54. }