Skip to content

fix: fix bug with polyfill fetch #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/fetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ export function fetchEventSource(input: RequestInfo, {

await onopen(response);

await getBytes(response.body!, getLines(getMessages(id => {
await getBytes(response, getLines(getMessages(id => {
if (id) {
// store the id and send it back on the next retry:
headers[LastEventId] = id;
Expand Down
19 changes: 12 additions & 7 deletions src/parse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,16 @@ export interface EventSourceMessage {
* @param onChunk A function that will be called on each new byte chunk in the stream.
* @returns {Promise<void>} A promise that will be resolved when the stream closes.
*/
export async function getBytes(stream: ReadableStream<Uint8Array>, onChunk: (arr: Uint8Array) => void) {
const reader = stream.getReader();
let result: ReadableStreamDefaultReadResult<Uint8Array>;
while (!(result = await reader.read()).done) {
onChunk(result.value);
export async function getBytes(response: Response, onChunk: (arr: Uint8Array) => void) {
const reader = response.body?.getReader();
if (reader) {
let result = await reader.read();
while (!result.done) {
onChunk(result.value);
result = await reader.read();
}
} else {
onChunk(new Uint8Array(await response.arrayBuffer()));
}
}

Expand Down Expand Up @@ -64,10 +69,10 @@ export function getLines(onLine: (line: Uint8Array, fieldLength: number) => void
if (buffer[position] === ControlChars.NewLine) {
lineStart = ++position; // skip to next char
}

discardTrailingNewline = false;
}

// start looking forward till the end of line:
let lineEnd = -1; // index of the \r or \n char
for (; position < bufLength && lineEnd === -1; ++position) {
Expand Down