function loadAndSubFixture()

in src/fixtures.ts [77:128]


function loadAndSubFixture(
  directory: string,
  location: ApiLocation,
  fixtureName: string,
  source: string,
  mustExist: boolean,
) {
  const candidates = fixtureCandidates(directory, fixtureName, location);
  const fixtureFileName = candidates.find((n) => fs.existsSync(n));

  if (!fixtureFileName) {
    if (mustExist) {
      throw new Error(`Sample uses fixture ${fixtureName}, but not found: ${JSON.stringify(candidates)}`);
    }
    return source;
  }

  const fixtureContents = fs.readFileSync(fixtureFileName, {
    encoding: 'utf-8',
  });

  const subRegex = /[/]{3}[ \t]*here[ \t]*$/im;
  if (!subRegex.test(fixtureContents)) {
    throw new Error(`Fixture does not contain '/// here': ${fixtureFileName}`);
  }

  const { imports, statements } = sidelineImports(source);
  const show = '/// !show';
  const hide = '/// !hide';

  const result = fixtureContents.replace(
    subRegex,
    [
      '// Code snippet begins after !show marker below',
      show,
      statements,
      hide,
      '// Code snippet ended before !hide marker above',
    ].join('\n'),
  );

  return imports
    ? [
        '// Hoisted imports begin after !show marker below',
        show,
        imports,
        hide,
        '// Hoisted imports ended before !hide marker above',
        result,
      ].join('\n')
    : result;
}