import type {RollupBuild, OutputOptions, OutputAsset, OutputChunk, SourceMap} from "rollup";

export interface TestOutput{
  code: string,
  fileName: string,
  source: any,
  map: any
}

export const getCode = async (bundle: RollupBuild, outputOptions: OutputOptions): Promise<TestOutput[]> => {
  const { output } = await bundle.generate(outputOptions || { format: 'cjs', exports: 'auto' });

  return output.sort((a,b)=> {
    if(a.fileName === b.fileName && (<OutputAsset>a).source !== (<OutputAsset>b).source){ return (<OutputAsset>a).source<(<OutputAsset>b).source?-1:1}
    return a.fileName < b.fileName ? -1 : (a.fileName > b.fileName? 1 : 0);
  }).map(chunk=> {
    const { code, map } = (<OutputChunk>chunk);
    const { fileName, source } = (<OutputAsset>chunk);
    return {
      code,
      fileName,
      source,
      map
    };
  });
};
