From 047d328cb0968fb1926e41326d35b595ba3fb3bc Mon Sep 17 00:00:00 2001
From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com>
Date: Mon, 10 Jul 2023 16:45:09 +0100
Subject: [PATCH] refactor(streaming): make response body streaming polyfill
 more spec-compliant (#44)

---
 .release-please-manifest.json |  2 +-
 src/streaming.ts              | 16 ++++++++++++----
 2 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/.release-please-manifest.json b/.release-please-manifest.json
index 258342d8..d9d5699b 100644
--- a/.release-please-manifest.json
+++ b/.release-please-manifest.json
@@ -1,3 +1,3 @@
 {
-  ".": "0.5.2"
+  ".": "0.5.3"
 }
diff --git a/src/streaming.ts b/src/streaming.ts
index 15651545..fd629c8a 100644
--- a/src/streaming.ts
+++ b/src/streaming.ts
@@ -259,19 +259,27 @@ function partition(str: string, delimiter: string): [string, string, string] {
  * Most browsers don't yet have async iterable support for ReadableStream,
  * and Node has a very different way of reading bytes from its "ReadableStream".
  *
- * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1624185965
+ * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490
  */
 function readableStreamAsyncIterable<T>(stream: any): AsyncIterableIterator<T> {
   if (stream[Symbol.asyncIterator]) return stream;
 
   const reader = stream.getReader();
   return {
-    next() {
-      return reader.read();
+    async next() {
+      try {
+        const result = await reader.read();
+        if (result?.done) reader.releaseLock(); // release lock when stream becomes closed
+        return result;
+      } catch (e) {
+        reader.releaseLock(); // release lock when stream becomes errored
+        throw e;
+      }
     },
     async return() {
-      reader.cancel();
+      const cancelPromise = reader.cancel();
       reader.releaseLock();
+      await cancelPromise;
       return { done: true, value: undefined };
     },
     [Symbol.asyncIterator]() {