transport.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * Normalizes HeadersInit to a plain Record<string, string> for manipulation.
  3. * Handles Headers objects, arrays of tuples, and plain objects.
  4. */
  5. export function normalizeHeaders(headers) {
  6. if (!headers)
  7. return {};
  8. if (headers instanceof Headers) {
  9. return Object.fromEntries(headers.entries());
  10. }
  11. if (Array.isArray(headers)) {
  12. return Object.fromEntries(headers);
  13. }
  14. return { ...headers };
  15. }
  16. /**
  17. * Creates a fetch function that includes base RequestInit options.
  18. * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init.
  19. *
  20. * @param baseFetch - The base fetch function to wrap (defaults to global fetch)
  21. * @param baseInit - The base RequestInit to merge with each request
  22. * @returns A wrapped fetch function that merges base options with call-specific options
  23. */
  24. export function createFetchWithInit(baseFetch = fetch, baseInit) {
  25. if (!baseInit) {
  26. return baseFetch;
  27. }
  28. // Return a wrapped fetch that merges base RequestInit with call-specific init
  29. return async (url, init) => {
  30. const mergedInit = {
  31. ...baseInit,
  32. ...init,
  33. // Headers need special handling - merge instead of replace
  34. headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
  35. };
  36. return baseFetch(url, mergedInit);
  37. };
  38. }
  39. //# sourceMappingURL=transport.js.map