All files / kernel-platforms/src/capabilities/fetch nodejs.ts

100% Statements 15/15
100% Branches 6/6
100% Functions 3/3
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                          2x 8x   5x 5x   5x 4x   4x     1x       2x           10x 2x   8x 8x 8x 8x      
import { readFile } from 'node:fs/promises';
 
import { makeFetchCaveat, makeCaveatedFetch } from './shared.ts';
import { fetchConfigStruct } from './types.ts';
import type { FetchCapability, FetchConfig } from './types.ts';
import { makeCapabilitySpecification } from '../../specification.ts';
 
/**
 * Extends the fetch capability with file:// URL support for Node.js
 *
 * @param fromFetch - The underlying fetch capability to wrap
 * @returns A fetch capability with file:// URL support
 */
const makeExtendedFetch = (fromFetch: FetchCapability): FetchCapability => {
  return async (...[input, ...args]: Parameters<FetchCapability>) => {
    // eslint-disable-next-line n/no-unsupported-features/node-builtins
    const url = input instanceof Request ? input.url : input;
    const { protocol, pathname } = new URL(url);
 
    if (protocol === 'file:') {
      const contents = await readFile(pathname, 'utf8');
      // eslint-disable-next-line n/no-unsupported-features/node-builtins
      return new Response(contents);
    }
 
    return await fromFetch(input, ...args);
  };
};
 
export const { configStruct, capabilityFactory } = makeCapabilitySpecification(
  fetchConfigStruct,
  (
    config: FetchConfig,
    options?: { fromFetch: FetchCapability },
  ): FetchCapability => {
    if (!options?.fromFetch) {
      throw new Error('Must provide explicit fromFetch capability');
    }
    const { fromFetch } = options;
    const caveat = makeFetchCaveat(config);
    const extendedFetch = makeExtendedFetch(fromFetch);
    return makeCaveatedFetch(extendedFetch, caveat);
  },
);