fetch-text-by-line.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import type { BunFile } from 'bun';
  2. import { fetchWithRetry, defaultRequestInit } from './fetch-retry';
  3. import { TextLineStream } from './text-line-transform-stream';
  4. import { PolyfillTextDecoderStream } from './text-decoder-stream';
  5. import { processLine } from './process-line';
  6. const enableTextLineStream = !!process.env.ENABLE_TEXT_LINE_STREAM;
  7. const decoder = new TextDecoder('utf-8');
  8. async function *createTextLineAsyncIterableFromStreamSource(stream: ReadableStream<Uint8Array>): AsyncIterable<string> {
  9. let buf = '';
  10. const reader = stream.getReader();
  11. while (true) {
  12. const res = await reader.read();
  13. if (res.done) {
  14. break;
  15. }
  16. const chunkStr = decoder.decode(res.value).replaceAll('\r\n', '\n');
  17. for (let i = 0, len = chunkStr.length; i < len; i++) {
  18. const char = chunkStr[i];
  19. if (char === '\n') {
  20. yield buf;
  21. buf = '';
  22. } else {
  23. buf += char;
  24. }
  25. }
  26. }
  27. if (buf) {
  28. yield buf;
  29. }
  30. }
  31. const getBunBlob = (file: string | URL | BunFile) => {
  32. if (typeof file === 'string') {
  33. return Bun.file(file);
  34. } if (!('writer' in file)) {
  35. return Bun.file(file);
  36. }
  37. return file;
  38. };
  39. export const readFileByLine: ((file: string | URL | BunFile) => AsyncIterable<string>) = enableTextLineStream
  40. ? (file: string | URL | BunFile) => getBunBlob(file).stream().pipeThrough(new PolyfillTextDecoderStream()).pipeThrough(new TextLineStream())
  41. : (file: string | URL | BunFile) => createTextLineAsyncIterableFromStreamSource(getBunBlob(file).stream());
  42. const ensureResponseBody = (resp: Response) => {
  43. if (!resp.body) {
  44. throw new Error('Failed to fetch remote text');
  45. }
  46. if (resp.bodyUsed) {
  47. throw new Error('Body has already been consumed.');
  48. }
  49. return resp.body;
  50. };
  51. export const createReadlineInterfaceFromResponse: ((resp: Response) => AsyncIterable<string>) = enableTextLineStream
  52. ? (resp) => ensureResponseBody(resp).pipeThrough(new PolyfillTextDecoderStream()).pipeThrough(new TextLineStream())
  53. : (resp) => createTextLineAsyncIterableFromStreamSource(ensureResponseBody(resp));
  54. export function fetchRemoteTextByLine(url: string | URL) {
  55. return fetchWithRetry(url, defaultRequestInit).then(createReadlineInterfaceFromResponse);
  56. }
  57. export async function readFileIntoProcessedArray(file: string | URL | BunFile) {
  58. if (typeof file === 'string') {
  59. file = Bun.file(file);
  60. } else if (!('writer' in file)) {
  61. file = Bun.file(file);
  62. }
  63. const content = await file.text();
  64. return content.split('\n').filter(processLine);
  65. }