@ahoo-wang/fetcher-eventstream 2.6.13 → 2.6.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.es.js CHANGED
@@ -1,5 +1,5 @@
1
- import { FetcherError as f, CONTENT_TYPE_HEADER as h, ContentTypeValues as l } from "@ahoo-wang/fetcher";
2
- class p {
1
+ import { FetcherError as l, CONTENT_TYPE_HEADER as y, ContentTypeValues as h } from "@ahoo-wang/fetcher";
2
+ class m {
3
3
  constructor() {
4
4
  this.buffer = "";
5
5
  }
@@ -15,8 +15,8 @@ class p {
15
15
  const n = this.buffer.split(`
16
16
  `);
17
17
  this.buffer = n.pop() || "";
18
- for (const s of n)
19
- r.enqueue(s);
18
+ for (const o of n)
19
+ r.enqueue(o);
20
20
  } catch (n) {
21
21
  r.error(n);
22
22
  }
@@ -34,16 +34,16 @@ class p {
34
34
  }
35
35
  }
36
36
  }
37
- class y extends TransformStream {
37
+ class E extends TransformStream {
38
38
  constructor() {
39
- super(new p());
39
+ super(new m());
40
40
  }
41
41
  }
42
42
  const c = class c {
43
43
  };
44
44
  c.ID = "id", c.RETRY = "retry", c.EVENT = "event", c.DATA = "data";
45
45
  let i = c;
46
- function m(t, e, r) {
46
+ function v(t, e, r) {
47
47
  switch (t) {
48
48
  case i.EVENT:
49
49
  r.event = e;
@@ -62,7 +62,7 @@ function m(t, e, r) {
62
62
  }
63
63
  }
64
64
  const a = "message";
65
- class v {
65
+ class S {
66
66
  constructor() {
67
67
  this.currentEvent = {
68
68
  event: a,
@@ -92,12 +92,12 @@ class v {
92
92
  }
93
93
  if (e.startsWith(":"))
94
94
  return;
95
- const s = e.indexOf(":");
96
- let u, o;
97
- s === -1 ? (u = e.toLowerCase(), o = "") : (u = e.substring(0, s).toLowerCase(), o = e.substring(s + 1), o.startsWith(" ") && (o = o.substring(1))), u = u.trim(), o = o.trim(), m(u, o, n);
98
- } catch (s) {
95
+ const o = e.indexOf(":");
96
+ let p, s;
97
+ o === -1 ? (p = e.toLowerCase(), s = "") : (p = e.substring(0, o).toLowerCase(), s = e.substring(o + 1), s.startsWith(" ") && (s = s.substring(1))), p = p.trim(), s = s.trim(), v(p, s, n);
98
+ } catch (o) {
99
99
  r.error(
100
- s instanceof Error ? s : new Error(String(s))
100
+ o instanceof Error ? o : new Error(String(o))
101
101
  ), n.event = a, n.id = void 0, n.retry = void 0, n.data = [];
102
102
  }
103
103
  }
@@ -125,12 +125,12 @@ class v {
125
125
  }
126
126
  }
127
127
  }
128
- class E extends TransformStream {
128
+ class T extends TransformStream {
129
129
  constructor() {
130
- super(new v());
130
+ super(new S());
131
131
  }
132
132
  }
133
- class d extends f {
133
+ class u extends l {
134
134
  /**
135
135
  * Creates a new EventStreamConvertError instance.
136
136
  * @param response - The Response object associated with the error
@@ -138,15 +138,15 @@ class d extends f {
138
138
  * @param cause - Optional underlying error that caused this error
139
139
  */
140
140
  constructor(e, r, n) {
141
- super(r, n), this.response = e, this.name = "EventStreamConvertError", Object.setPrototypeOf(this, d.prototype);
141
+ super(r, n), this.response = e, this.name = "EventStreamConvertError", Object.setPrototypeOf(this, u.prototype);
142
142
  }
143
143
  }
144
- function S(t) {
144
+ function b(t) {
145
145
  if (!t.body)
146
- throw new d(t, "Response body is null");
147
- return t.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new y()).pipeThrough(new E());
146
+ throw new u(t, "Response body is null");
147
+ return t.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new E()).pipeThrough(new T());
148
148
  }
149
- class T {
149
+ class R {
150
150
  transform(e, r) {
151
151
  const n = JSON.parse(e.data);
152
152
  r.enqueue({
@@ -157,54 +157,69 @@ class T {
157
157
  });
158
158
  }
159
159
  }
160
- class b extends TransformStream {
160
+ class w extends TransformStream {
161
161
  constructor() {
162
- super(new T());
162
+ super(new R());
163
163
  }
164
164
  }
165
- function w(t) {
165
+ function g(t) {
166
166
  return t.pipeThrough(
167
- new b()
167
+ new w()
168
168
  );
169
169
  }
170
- const q = (t) => t.requiredResponse.requiredEventStream(), L = (t) => t.requiredResponse.requiredJsonEventStream();
171
- Object.defineProperty(Response.prototype, "contentType", {
170
+ const N = (t) => t.requiredResponse.requiredEventStream(), q = (t) => t.requiredResponse.requiredJsonEventStream(), d = "contentType";
171
+ Object.prototype.hasOwnProperty.call(
172
+ Response.prototype,
173
+ d
174
+ ) || Object.defineProperty(Response.prototype, d, {
172
175
  get() {
173
- return this.headers.get(h);
174
- }
176
+ return this.headers.get(y);
177
+ },
178
+ configurable: !0
175
179
  });
176
- Object.defineProperty(Response.prototype, "isEventStream", {
180
+ const f = "isEventStream";
181
+ Object.prototype.hasOwnProperty.call(
182
+ Response.prototype,
183
+ f
184
+ ) || Object.defineProperty(Response.prototype, f, {
177
185
  get() {
178
186
  const t = this.contentType;
179
- return t ? t.includes(l.TEXT_EVENT_STREAM) : !1;
180
- }
187
+ return t ? t.includes(h.TEXT_EVENT_STREAM) : !1;
188
+ },
189
+ configurable: !0
181
190
  });
182
- Response.prototype.eventStream = function() {
183
- return this.isEventStream ? S(this) : null;
184
- };
185
- Response.prototype.requiredEventStream = function() {
191
+ Object.prototype.hasOwnProperty.call(Response.prototype, "eventStream") || (Response.prototype.eventStream = function() {
192
+ return this.isEventStream ? b(this) : null;
193
+ });
194
+ Object.prototype.hasOwnProperty.call(
195
+ Response.prototype,
196
+ "requiredEventStream"
197
+ ) || (Response.prototype.requiredEventStream = function() {
186
198
  const t = this.eventStream();
187
199
  if (!t)
188
- throw new d(
200
+ throw new u(
189
201
  this,
190
202
  `Event stream is not available. Response content-type: [${this.contentType}]`
191
203
  );
192
204
  return t;
193
- };
194
- Response.prototype.jsonEventStream = function() {
205
+ });
206
+ Object.prototype.hasOwnProperty.call(Response.prototype, "jsonEventStream") || (Response.prototype.jsonEventStream = function() {
195
207
  const t = this.eventStream();
196
- return t ? w(t) : null;
197
- };
198
- Response.prototype.requiredJsonEventStream = function() {
208
+ return t ? g(t) : null;
209
+ });
210
+ Object.prototype.hasOwnProperty.call(
211
+ Response.prototype,
212
+ "requiredJsonEventStream"
213
+ ) || (Response.prototype.requiredJsonEventStream = function() {
199
214
  const t = this.jsonEventStream();
200
215
  if (!t)
201
- throw new d(
216
+ throw new u(
202
217
  this,
203
218
  `Event stream is not available. Response content-type: [${this.contentType}]`
204
219
  );
205
220
  return t;
206
- };
207
- class R {
221
+ });
222
+ class O {
208
223
  /**
209
224
  * Creates a new ReadableStreamAsyncIterable instance.
210
225
  * @param stream - The ReadableStream to wrap.
@@ -279,24 +294,24 @@ class R {
279
294
  return console.debug("Throwing error:", e), this.releaseLock(), { done: !0, value: void 0 };
280
295
  }
281
296
  }
282
- const g = typeof ReadableStream.prototype[Symbol.asyncIterator] == "function";
283
- g || (ReadableStream.prototype[Symbol.asyncIterator] = function() {
284
- return new R(this);
297
+ const P = typeof ReadableStream.prototype[Symbol.asyncIterator] == "function";
298
+ P || (ReadableStream.prototype[Symbol.asyncIterator] = function() {
299
+ return new O(this);
285
300
  });
286
301
  export {
287
- d as EventStreamConvertError,
288
- q as EventStreamResultExtractor,
289
- L as JsonEventStreamResultExtractor,
290
- T as JsonServerSentEventTransform,
291
- b as JsonServerSentEventTransformStream,
292
- R as ReadableStreamAsyncIterable,
302
+ u as EventStreamConvertError,
303
+ N as EventStreamResultExtractor,
304
+ q as JsonEventStreamResultExtractor,
305
+ R as JsonServerSentEventTransform,
306
+ w as JsonServerSentEventTransformStream,
307
+ O as ReadableStreamAsyncIterable,
293
308
  i as ServerSentEventFields,
294
- E as ServerSentEventTransformStream,
295
- v as ServerSentEventTransformer,
296
- y as TextLineTransformStream,
297
- p as TextLineTransformer,
298
- g as isReadableStreamAsyncIterableSupported,
299
- w as toJsonServerSentEventStream,
300
- S as toServerSentEventStream
309
+ T as ServerSentEventTransformStream,
310
+ S as ServerSentEventTransformer,
311
+ E as TextLineTransformStream,
312
+ m as TextLineTransformer,
313
+ P as isReadableStreamAsyncIterableSupported,
314
+ g as toJsonServerSentEventStream,
315
+ b as toServerSentEventStream
301
316
  };
302
317
  //# sourceMappingURL=index.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.es.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamResultExtractor.ts","../src/responses.ts","../src/readableStreamAsyncIterable.ts","../src/readableStreams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport class ServerSentEventFields {\n static readonly ID = 'id';\n static readonly RETRY = 'retry';\n static readonly EVENT = 'event';\n static readonly DATA = 'data';\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventFields.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventFields.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventFields.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventFields.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent> {\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new EventStreamConvertError(response, 'Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, ResultExtractor } from '@ahoo-wang/fetcher';\nimport { ServerSentEventStream } from './eventStreamConverter';\nimport { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * ServerSentEventStream result extractor, used to extract server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of server-sent event stream\n * @throws ExchangeError exception when server does not support ServerSentEventStream\n */\nexport const EventStreamResultExtractor: ResultExtractor<\n ServerSentEventStream\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredEventStream();\n};\n\n/**\n * JsonServerSentEventStream result extractor, used to extract JSON server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of JSON server-sent event stream\n * @throws ExchangeError exception when server does not support JsonServerSentEventStream\n */\nexport const JsonEventStreamResultExtractor: ResultExtractor<\n JsonServerSentEventStream<any>\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredJsonEventStream();\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n}\n\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nObject.defineProperty(Response.prototype, 'contentType', {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n});\n\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nObject.defineProperty(Response.prototype, 'isEventStream', {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n});\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n};\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n};\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A wrapper class that converts a ReadableStream into an AsyncIterable.\n * This allows consuming a ReadableStream using for-await...of loops.\n */\nexport class ReadableStreamAsyncIterable<T> implements AsyncIterable<T> {\n private readonly reader: ReadableStreamDefaultReader<T>;\n private _locked: boolean = true;\n\n /**\n * Creates a new ReadableStreamAsyncIterable instance.\n * @param stream - The ReadableStream to wrap.\n */\n constructor(private readonly stream: ReadableStream<T>) {\n this.reader = stream.getReader();\n }\n\n /**\n * Gets the lock status of the reader.\n * @returns True if the reader is currently locked, false otherwise.\n */\n get locked(): boolean {\n return this._locked;\n }\n\n /**\n * Releases the reader lock if currently locked.\n * This method safely releases the reader lock by catching any potential errors.\n */\n releaseLock() {\n if (!this._locked) return false;\n this._locked = false;\n try {\n this.reader.releaseLock();\n return true;\n } catch (error) {\n console.debug('Failed to release reader lock:', error);\n return false;\n }\n }\n\n /**\n * Implements the AsyncIterable interface by returning this iterator.\n * @returns The async iterator for this instance.\n */\n [Symbol.asyncIterator]() {\n return this;\n }\n\n /**\n * Gets the next value from the stream.\n * Reads the next chunk from the stream and returns it as an IteratorResult.\n * If the stream is done, releases the lock and returns a done result.\n * @returns A promise that resolves to an IteratorResult containing the next value or done status.\n * @throws If an error occurs while reading from the stream.\n */\n async next(): Promise<IteratorResult<T>> {\n try {\n const { done, value } = await this.reader.read();\n if (done) {\n this.releaseLock();\n return { done: true, value: undefined };\n }\n\n return { done: false, value };\n } catch (error) {\n this.releaseLock();\n throw error;\n }\n }\n\n /**\n * Implements the return method of the async iterator.\n * Cancels the stream reader and releases the lock.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async return(): Promise<IteratorResult<T>> {\n try {\n await this.reader.cancel();\n } catch (error) {\n console.debug('Failed to cancel stream reader:', error);\n } finally {\n this.releaseLock();\n }\n return { done: true, value: undefined };\n }\n\n /**\n * Implements the throw method of the async iterator.\n * Releases the lock and returns a done result.\n * @param error - The error to be thrown.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async throw(error: any): Promise<IteratorResult<T>> {\n // Ensure the reader lock is released before throwing\n console.debug('Throwing error:', error);\n this.releaseLock();\n return { done: true, value: undefined };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ReadableStreamAsyncIterable } from './readableStreamAsyncIterable';\n\ndeclare global {\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n// Check if ReadableStream already has [Symbol.asyncIterator] implemented\nexport const isReadableStreamAsyncIterableSupported =\n typeof ReadableStream.prototype[Symbol.asyncIterator] === 'function';\n\n// Add [Symbol.asyncIterator] to ReadableStream if not already implemented\nif (!isReadableStreamAsyncIterableSupported) {\n ReadableStream.prototype[Symbol.asyncIterator] = function <R = any>() {\n return new ReadableStreamAsyncIterable<R>(this as ReadableStream<R>);\n };\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EventStreamResultExtractor","exchange","JsonEventStreamResultExtractor","CONTENT_TYPE_HEADER","contentType","ContentTypeValues","eventStream","ReadableStreamAsyncIterable","stream","done","isReadableStreamAsyncIterableSupported"],"mappings":";AAoBO,MAAMA,EAA2D;AAAA,EAAjE,cAAA;AACL,SAAQ,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQjB,UACEC,GACAC,GACA;AACA,QAAI;AACF,WAAK,UAAUD;AACf,YAAME,IAAQ,KAAK,OAAO,MAAM;AAAA,CAAI;AACpC,WAAK,SAASA,EAAM,IAAA,KAAS;AAE7B,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,QAAO;AAC1B,SAAK,UAAU;AACf,QAAI;AACF,kBAAK,OAAO,YAAA,GACL;AAAA,IACT,SAAShC,GAAO;AACd,qBAAQ,MAAM,kCAAkCA,CAAK,GAC9C;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,CAAC,OAAO,aAAa,IAAI;AACvB,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,MAAM,OAAmC;AACvC,QAAI;AACF,YAAM,EAAE,MAAAiC,GAAM,OAAA3B,EAAA,IAAU,MAAM,KAAK,OAAO,KAAA;AAC1C,aAAI2B,KACF,KAAK,YAAA,GACE,EAAE,MAAM,IAAM,OAAO,OAAA,KAGvB,EAAE,MAAM,IAAO,OAAA3B,EAAA;AAAA,IACxB,SAASN,GAAO;AACd,iBAAK,YAAA,GACCA;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,SAAqC;AACzC,QAAI;AACF,YAAM,KAAK,OAAO,OAAA;AAAA,IACpB,SAASA,GAAO;AACd,cAAQ,MAAM,mCAAmCA,CAAK;AAAA,IACxD,UAAA;AACE,WAAK,YAAA;AAAA,IACP;AACA,WAAO,EAAE,MAAM,IAAM,OAAO,OAAA;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,MAAMA,GAAwC;AAElD,mBAAQ,MAAM,mBAAmBA,CAAK,GACtC,KAAK,YAAA,GACE,EAAE,MAAM,IAAM,OAAO,OAAA;AAAA,EAC9B;AACF;AClFO,MAAMkC,IACX,OAAO,eAAe,UAAU,OAAO,aAAa,KAAM;AAGvDA,MACH,eAAe,UAAU,OAAO,aAAa,IAAI,WAAqB;AACpE,SAAO,IAAIH,EAA+B,IAAyB;AACrE;"}
1
+ {"version":3,"file":"index.es.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamResultExtractor.ts","../src/responses.ts","../src/readableStreamAsyncIterable.ts","../src/readableStreams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport class ServerSentEventFields {\n static readonly ID = 'id';\n static readonly RETRY = 'retry';\n static readonly EVENT = 'event';\n static readonly DATA = 'data';\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventFields.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventFields.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventFields.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventFields.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent> {\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new EventStreamConvertError(response, 'Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, ResultExtractor } from '@ahoo-wang/fetcher';\nimport { ServerSentEventStream } from './eventStreamConverter';\nimport { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * ServerSentEventStream result extractor, used to extract server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of server-sent event stream\n * @throws ExchangeError exception when server does not support ServerSentEventStream\n */\nexport const EventStreamResultExtractor: ResultExtractor<\n ServerSentEventStream\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredEventStream();\n};\n\n/**\n * JsonServerSentEventStream result extractor, used to extract JSON server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of JSON server-sent event stream\n * @throws ExchangeError exception when server does not support JsonServerSentEventStream\n */\nexport const JsonEventStreamResultExtractor: ResultExtractor<\n JsonServerSentEventStream<any>\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredJsonEventStream();\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n}\n\nconst CONTENT_TYPE_PROPERTY_NAME = 'contentType';\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n CONTENT_TYPE_PROPERTY_NAME,\n )\n) {\n Object.defineProperty(Response.prototype, CONTENT_TYPE_PROPERTY_NAME, {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n configurable: true,\n });\n}\n\nconst IS_EVENT_STREAM_PROPERTY_NAME = 'isEventStream';\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n IS_EVENT_STREAM_PROPERTY_NAME,\n )\n) {\n Object.defineProperty(Response.prototype, IS_EVENT_STREAM_PROPERTY_NAME, {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n configurable: true,\n });\n}\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nif (!Object.prototype.hasOwnProperty.call(Response.prototype, 'eventStream')) {\n Response.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n };\n}\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n 'requiredEventStream',\n )\n) {\n Response.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n };\n}\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nif (\n !Object.prototype.hasOwnProperty.call(Response.prototype, 'jsonEventStream')\n) {\n Response.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n };\n}\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n 'requiredJsonEventStream',\n )\n) {\n Response.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A wrapper class that converts a ReadableStream into an AsyncIterable.\n * This allows consuming a ReadableStream using for-await...of loops.\n */\nexport class ReadableStreamAsyncIterable<T> implements AsyncIterable<T> {\n private readonly reader: ReadableStreamDefaultReader<T>;\n private _locked: boolean = true;\n\n /**\n * Creates a new ReadableStreamAsyncIterable instance.\n * @param stream - The ReadableStream to wrap.\n */\n constructor(private readonly stream: ReadableStream<T>) {\n this.reader = stream.getReader();\n }\n\n /**\n * Gets the lock status of the reader.\n * @returns True if the reader is currently locked, false otherwise.\n */\n get locked(): boolean {\n return this._locked;\n }\n\n /**\n * Releases the reader lock if currently locked.\n * This method safely releases the reader lock by catching any potential errors.\n */\n releaseLock() {\n if (!this._locked) return false;\n this._locked = false;\n try {\n this.reader.releaseLock();\n return true;\n } catch (error) {\n console.debug('Failed to release reader lock:', error);\n return false;\n }\n }\n\n /**\n * Implements the AsyncIterable interface by returning this iterator.\n * @returns The async iterator for this instance.\n */\n [Symbol.asyncIterator]() {\n return this;\n }\n\n /**\n * Gets the next value from the stream.\n * Reads the next chunk from the stream and returns it as an IteratorResult.\n * If the stream is done, releases the lock and returns a done result.\n * @returns A promise that resolves to an IteratorResult containing the next value or done status.\n * @throws If an error occurs while reading from the stream.\n */\n async next(): Promise<IteratorResult<T>> {\n try {\n const { done, value } = await this.reader.read();\n if (done) {\n this.releaseLock();\n return { done: true, value: undefined };\n }\n\n return { done: false, value };\n } catch (error) {\n this.releaseLock();\n throw error;\n }\n }\n\n /**\n * Implements the return method of the async iterator.\n * Cancels the stream reader and releases the lock.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async return(): Promise<IteratorResult<T>> {\n try {\n await this.reader.cancel();\n } catch (error) {\n console.debug('Failed to cancel stream reader:', error);\n } finally {\n this.releaseLock();\n }\n return { done: true, value: undefined };\n }\n\n /**\n * Implements the throw method of the async iterator.\n * Releases the lock and returns a done result.\n * @param error - The error to be thrown.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async throw(error: any): Promise<IteratorResult<T>> {\n // Ensure the reader lock is released before throwing\n console.debug('Throwing error:', error);\n this.releaseLock();\n return { done: true, value: undefined };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ReadableStreamAsyncIterable } from './readableStreamAsyncIterable';\n\ndeclare global {\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n// Check if ReadableStream already has [Symbol.asyncIterator] implemented\nexport const isReadableStreamAsyncIterableSupported =\n typeof ReadableStream.prototype[Symbol.asyncIterator] === 'function';\n\n// Add [Symbol.asyncIterator] to ReadableStream if not already implemented\nif (!isReadableStreamAsyncIterableSupported) {\n ReadableStream.prototype[Symbol.asyncIterator] = function <R = any>() {\n return new ReadableStreamAsyncIterable<R>(this as ReadableStream<R>);\n };\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EventStreamResultExtractor","exchange","JsonEventStreamResultExtractor","CONTENT_TYPE_PROPERTY_NAME","CONTENT_TYPE_HEADER","IS_EVENT_STREAM_PROPERTY_NAME","contentType","ContentTypeValues","eventStream","ReadableStreamAsyncIterable","stream","done","isReadableStreamAsyncIterableSupported"],"mappings":";AAoBO,MAAMA,EAA2D;AAAA,EAAjE,cAAA;AACL,SAAQ,SAAS;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQjB,UACEC,GACAC,GACA;AACA,QAAI;AACF,WAAK,UAAUD;AACf,YAAME,IAAQ,KAAK,OAAO,MAAM;AAAA,CAAI;AACpC,WAAK,SAASA,EAAM,IAAA,KAAS;AAE7B,iBAAWC,KAAQD;AACjB,QAAAD,EAAW,QAAQE,CAAI;AAAA,IAE3B,SAASC,GAAO;AACd,MAAAH,EAAW,MAAMG,CAAK;AAAA,IACxB;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAMH,GAAsD;AAC1D,QAAI;AAEF,MAAI,KAAK,UACPA,EAAW,QAAQ,KAAK,MAAM;AAAA,IAElC,SAASG,GAAO;AACd,MAAAH,EAAW,MAAMG,CAAK;AAAA,IACxB;AAAA,EACF;AACF;AAKO,MAAMC,UAAgC,gBAAgC;AAAA,EAC3E,cAAc;AACZ,UAAM,IAAIN,GAAqB;AAAA,EACjC;AACF;ACzCO,MAAMO,IAAN,MAAMA,EAAsB;AAKnC;AAJEA,EAAgB,KAAK,MACrBA,EAAgB,QAAQ,SACxBA,EAAgB,QAAQ,SACxBA,EAAgB,OAAO;AAJlB,IAAMC,IAAND;AAaP,SAASE,EACPC,GACAC,GACAC,GACA;AACA,UAAQF,GAAA;AAAA,IACN,KAAKF,EAAsB;AACzB,MAAAI,EAAa,QAAQD;AACrB;AAAA,IACF,KAAKH,EAAsB;AACzB,MAAAI,EAAa,KAAK,KAAKD,CAAK;AAC5B;AAAA,IACF,KAAKH,EAAsB;AACzB,MAAAI,EA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AO,KAAA;AAC1C,aAAI6B,KACF,KAAK,YAAA,GACE,EAAE,MAAM,IAAM,OAAO,OAAA,KAGvB,EAAE,MAAM,IAAO,OAAA7B,EAAA;AAAA,IACxB,SAASN,GAAO;AACd,iBAAK,YAAA,GACCA;AAAA,IACR;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAM,SAAqC;AACzC,QAAI;AACF,YAAM,KAAK,OAAO,OAAA;AAAA,IACpB,SAASA,GAAO;AACd,cAAQ,MAAM,mCAAmCA,CAAK;AAAA,IACxD,UAAA;AACE,WAAK,YAAA;AAAA,IACP;AACA,WAAO,EAAE,MAAM,IAAM,OAAO,OAAA;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAM,MAAMA,GAAwC;AAElD,mBAAQ,MAAM,mBAAmBA,CAAK,GACtC,KAAK,YAAA,GACE,EAAE,MAAM,IAAM,OAAO,OAAA;AAAA,EAC9B;AACF;AClFO,MAAMoC,IACX,OAAO,eAAe,UAAU,OAAO,aAAa,KAAM;AAGvDA,MACH,eAAe,UAAU,OAAO,aAAa,IAAI,WAAqB;AACpE,SAAO,IAAIH,EAA+B,IAAyB;AACrE;"}
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- (function(s,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],i):(s=typeof globalThis<"u"?globalThis:s||self,i(s.FetcherEventStream={},s.Fetcher))})(this,(function(s,i){"use strict";class m{constructor(){this.buffer=""}transform(e,r){try{this.buffer+=e;const n=this.buffer.split(`
2
- `);this.buffer=n.pop()||"";for(const o of n)r.enqueue(o)}catch(n){r.error(n)}}flush(e){try{this.buffer&&e.enqueue(this.buffer)}catch(r){e.error(r)}}}class h extends TransformStream{constructor(){super(new m)}}const f=class f{};f.ID="id",f.RETRY="retry",f.EVENT="event",f.DATA="data";let c=f;function w(t,e,r){switch(t){case c.EVENT:r.event=e;break;case c.DATA:r.data.push(e);break;case c.ID:r.id=e;break;case c.RETRY:{const n=parseInt(e,10);isNaN(n)||(r.retry=n);break}}}const u="message";class v{constructor(){this.currentEvent={event:u,id:void 0,retry:void 0,data:[]}}transform(e,r){const n=this.currentEvent;try{if(e.trim()===""){n.data.length>0&&(r.enqueue({event:n.event||u,data:n.data.join(`
3
- `),id:n.id||"",retry:n.retry}),n.event=u,n.data=[]);return}if(e.startsWith(":"))return;const o=e.indexOf(":");let l,a;o===-1?(l=e.toLowerCase(),a=""):(l=e.substring(0,o).toLowerCase(),a=e.substring(o+1),a.startsWith(" ")&&(a=a.substring(1))),l=l.trim(),a=a.trim(),w(l,a,n)}catch(o){r.error(o instanceof Error?o:new Error(String(o))),n.event=u,n.id=void 0,n.retry=void 0,n.data=[]}}flush(e){const r=this.currentEvent;try{r.data.length>0&&e.enqueue({event:r.event||u,data:r.data.join(`
4
- `),id:r.id||"",retry:r.retry})}catch(n){e.error(n instanceof Error?n:new Error(String(n)))}finally{r.event=u,r.id=void 0,r.retry=void 0,r.data=[]}}}class S extends TransformStream{constructor(){super(new v)}}class d extends i.FetcherError{constructor(e,r,n){super(r,n),this.response=e,this.name="EventStreamConvertError",Object.setPrototypeOf(this,d.prototype)}}function y(t){if(!t.body)throw new d(t,"Response body is null");return t.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new h).pipeThrough(new S)}class p{transform(e,r){const n=JSON.parse(e.data);r.enqueue({data:n,event:e.event,id:e.id,retry:e.retry})}}class E extends TransformStream{constructor(){super(new p)}}function T(t){return t.pipeThrough(new E)}const g=t=>t.requiredResponse.requiredEventStream(),L=t=>t.requiredResponse.requiredJsonEventStream();Object.defineProperty(Response.prototype,"contentType",{get(){return this.headers.get(i.CONTENT_TYPE_HEADER)}}),Object.defineProperty(Response.prototype,"isEventStream",{get(){const t=this.contentType;return t?t.includes(i.ContentTypeValues.TEXT_EVENT_STREAM):!1}}),Response.prototype.eventStream=function(){return this.isEventStream?y(this):null},Response.prototype.requiredEventStream=function(){const t=this.eventStream();if(!t)throw new d(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return t},Response.prototype.jsonEventStream=function(){const t=this.eventStream();return t?T(t):null},Response.prototype.requiredJsonEventStream=function(){const t=this.jsonEventStream();if(!t)throw new d(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return t};class b{constructor(e){this.stream=e,this._locked=!0,this.reader=e.getReader()}get locked(){return this._locked}releaseLock(){if(!this._locked)return!1;this._locked=!1;try{return this.reader.releaseLock(),!0}catch(e){return console.debug("Failed to release reader lock:",e),!1}}[Symbol.asyncIterator](){return this}async next(){try{const{done:e,value:r}=await this.reader.read();return e?(this.releaseLock(),{done:!0,value:void 0}):{done:!1,value:r}}catch(e){throw this.releaseLock(),e}}async return(){try{await this.reader.cancel()}catch(e){console.debug("Failed to cancel stream reader:",e)}finally{this.releaseLock()}return{done:!0,value:void 0}}async throw(e){return console.debug("Throwing error:",e),this.releaseLock(),{done:!0,value:void 0}}}const R=typeof ReadableStream.prototype[Symbol.asyncIterator]=="function";R||(ReadableStream.prototype[Symbol.asyncIterator]=function(){return new b(this)}),s.EventStreamConvertError=d,s.EventStreamResultExtractor=g,s.JsonEventStreamResultExtractor=L,s.JsonServerSentEventTransform=p,s.JsonServerSentEventTransformStream=E,s.ReadableStreamAsyncIterable=b,s.ServerSentEventFields=c,s.ServerSentEventTransformStream=S,s.ServerSentEventTransformer=v,s.TextLineTransformStream=h,s.TextLineTransformer=m,s.isReadableStreamAsyncIterableSupported=R,s.toJsonServerSentEventStream=T,s.toServerSentEventStream=y,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(o,i){typeof exports=="object"&&typeof module<"u"?i(exports,require("@ahoo-wang/fetcher")):typeof define=="function"&&define.amd?define(["exports","@ahoo-wang/fetcher"],i):(o=typeof globalThis<"u"?globalThis:o||self,i(o.FetcherEventStream={},o.Fetcher))})(this,(function(o,i){"use strict";class l{constructor(){this.buffer=""}transform(e,r){try{this.buffer+=e;const n=this.buffer.split(`
2
+ `);this.buffer=n.pop()||"";for(const s of n)r.enqueue(s)}catch(n){r.error(n)}}flush(e){try{this.buffer&&e.enqueue(this.buffer)}catch(r){e.error(r)}}}class y extends TransformStream{constructor(){super(new l)}}const f=class f{};f.ID="id",f.RETRY="retry",f.EVENT="event",f.DATA="data";let c=f;function O(t,e,r){switch(t){case c.EVENT:r.event=e;break;case c.DATA:r.data.push(e);break;case c.ID:r.id=e;break;case c.RETRY:{const n=parseInt(e,10);isNaN(n)||(r.retry=n);break}}}const u="message";class h{constructor(){this.currentEvent={event:u,id:void 0,retry:void 0,data:[]}}transform(e,r){const n=this.currentEvent;try{if(e.trim()===""){n.data.length>0&&(r.enqueue({event:n.event||u,data:n.data.join(`
3
+ `),id:n.id||"",retry:n.retry}),n.event=u,n.data=[]);return}if(e.startsWith(":"))return;const s=e.indexOf(":");let p,a;s===-1?(p=e.toLowerCase(),a=""):(p=e.substring(0,s).toLowerCase(),a=e.substring(s+1),a.startsWith(" ")&&(a=a.substring(1))),p=p.trim(),a=a.trim(),O(p,a,n)}catch(s){r.error(s instanceof Error?s:new Error(String(s))),n.event=u,n.id=void 0,n.retry=void 0,n.data=[]}}flush(e){const r=this.currentEvent;try{r.data.length>0&&e.enqueue({event:r.event||u,data:r.data.join(`
4
+ `),id:r.id||"",retry:r.retry})}catch(n){e.error(n instanceof Error?n:new Error(String(n)))}finally{r.event=u,r.id=void 0,r.retry=void 0,r.data=[]}}}class m extends TransformStream{constructor(){super(new h)}}class d extends i.FetcherError{constructor(e,r,n){super(r,n),this.response=e,this.name="EventStreamConvertError",Object.setPrototypeOf(this,d.prototype)}}function S(t){if(!t.body)throw new d(t,"Response body is null");return t.body.pipeThrough(new TextDecoderStream("utf-8")).pipeThrough(new y).pipeThrough(new m)}class v{transform(e,r){const n=JSON.parse(e.data);r.enqueue({data:n,event:e.event,id:e.id,retry:e.retry})}}class E extends TransformStream{constructor(){super(new v)}}function T(t){return t.pipeThrough(new E)}const j=t=>t.requiredResponse.requiredEventStream(),P=t=>t.requiredResponse.requiredJsonEventStream(),b="contentType";Object.prototype.hasOwnProperty.call(Response.prototype,b)||Object.defineProperty(Response.prototype,b,{get(){return this.headers.get(i.CONTENT_TYPE_HEADER)},configurable:!0});const R="isEventStream";Object.prototype.hasOwnProperty.call(Response.prototype,R)||Object.defineProperty(Response.prototype,R,{get(){const t=this.contentType;return t?t.includes(i.ContentTypeValues.TEXT_EVENT_STREAM):!1},configurable:!0}),Object.prototype.hasOwnProperty.call(Response.prototype,"eventStream")||(Response.prototype.eventStream=function(){return this.isEventStream?S(this):null}),Object.prototype.hasOwnProperty.call(Response.prototype,"requiredEventStream")||(Response.prototype.requiredEventStream=function(){const t=this.eventStream();if(!t)throw new d(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return t}),Object.prototype.hasOwnProperty.call(Response.prototype,"jsonEventStream")||(Response.prototype.jsonEventStream=function(){const t=this.eventStream();return t?T(t):null}),Object.prototype.hasOwnProperty.call(Response.prototype,"requiredJsonEventStream")||(Response.prototype.requiredJsonEventStream=function(){const t=this.jsonEventStream();if(!t)throw new d(this,`Event stream is not available. Response content-type: [${this.contentType}]`);return t});class w{constructor(e){this.stream=e,this._locked=!0,this.reader=e.getReader()}get locked(){return this._locked}releaseLock(){if(!this._locked)return!1;this._locked=!1;try{return this.reader.releaseLock(),!0}catch(e){return console.debug("Failed to release reader lock:",e),!1}}[Symbol.asyncIterator](){return this}async next(){try{const{done:e,value:r}=await this.reader.read();return e?(this.releaseLock(),{done:!0,value:void 0}):{done:!1,value:r}}catch(e){throw this.releaseLock(),e}}async return(){try{await this.reader.cancel()}catch(e){console.debug("Failed to cancel stream reader:",e)}finally{this.releaseLock()}return{done:!0,value:void 0}}async throw(e){return console.debug("Throwing error:",e),this.releaseLock(),{done:!0,value:void 0}}}const g=typeof ReadableStream.prototype[Symbol.asyncIterator]=="function";g||(ReadableStream.prototype[Symbol.asyncIterator]=function(){return new w(this)}),o.EventStreamConvertError=d,o.EventStreamResultExtractor=j,o.JsonEventStreamResultExtractor=P,o.JsonServerSentEventTransform=v,o.JsonServerSentEventTransformStream=E,o.ReadableStreamAsyncIterable=w,o.ServerSentEventFields=c,o.ServerSentEventTransformStream=m,o.ServerSentEventTransformer=h,o.TextLineTransformStream=y,o.TextLineTransformer=l,o.isReadableStreamAsyncIterableSupported=g,o.toJsonServerSentEventStream=T,o.toServerSentEventStream=S,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"})}));
5
5
  //# sourceMappingURL=index.umd.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamResultExtractor.ts","../src/responses.ts","../src/readableStreamAsyncIterable.ts","../src/readableStreams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport class ServerSentEventFields {\n static readonly ID = 'id';\n static readonly RETRY = 'retry';\n static readonly EVENT = 'event';\n static readonly DATA = 'data';\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventFields.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventFields.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventFields.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventFields.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent> {\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new EventStreamConvertError(response, 'Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, ResultExtractor } from '@ahoo-wang/fetcher';\nimport { ServerSentEventStream } from './eventStreamConverter';\nimport { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * ServerSentEventStream result extractor, used to extract server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of server-sent event stream\n * @throws ExchangeError exception when server does not support ServerSentEventStream\n */\nexport const EventStreamResultExtractor: ResultExtractor<\n ServerSentEventStream\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredEventStream();\n};\n\n/**\n * JsonServerSentEventStream result extractor, used to extract JSON server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of JSON server-sent event stream\n * @throws ExchangeError exception when server does not support JsonServerSentEventStream\n */\nexport const JsonEventStreamResultExtractor: ResultExtractor<\n JsonServerSentEventStream<any>\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredJsonEventStream();\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n}\n\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nObject.defineProperty(Response.prototype, 'contentType', {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n});\n\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nObject.defineProperty(Response.prototype, 'isEventStream', {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n});\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n};\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nResponse.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n};\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nResponse.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A wrapper class that converts a ReadableStream into an AsyncIterable.\n * This allows consuming a ReadableStream using for-await...of loops.\n */\nexport class ReadableStreamAsyncIterable<T> implements AsyncIterable<T> {\n private readonly reader: ReadableStreamDefaultReader<T>;\n private _locked: boolean = true;\n\n /**\n * Creates a new ReadableStreamAsyncIterable instance.\n * @param stream - The ReadableStream to wrap.\n */\n constructor(private readonly stream: ReadableStream<T>) {\n this.reader = stream.getReader();\n }\n\n /**\n * Gets the lock status of the reader.\n * @returns True if the reader is currently locked, false otherwise.\n */\n get locked(): boolean {\n return this._locked;\n }\n\n /**\n * Releases the reader lock if currently locked.\n * This method safely releases the reader lock by catching any potential errors.\n */\n releaseLock() {\n if (!this._locked) return false;\n this._locked = false;\n try {\n this.reader.releaseLock();\n return true;\n } catch (error) {\n console.debug('Failed to release reader lock:', error);\n return false;\n }\n }\n\n /**\n * Implements the AsyncIterable interface by returning this iterator.\n * @returns The async iterator for this instance.\n */\n [Symbol.asyncIterator]() {\n return this;\n }\n\n /**\n * Gets the next value from the stream.\n * Reads the next chunk from the stream and returns it as an IteratorResult.\n * If the stream is done, releases the lock and returns a done result.\n * @returns A promise that resolves to an IteratorResult containing the next value or done status.\n * @throws If an error occurs while reading from the stream.\n */\n async next(): Promise<IteratorResult<T>> {\n try {\n const { done, value } = await this.reader.read();\n if (done) {\n this.releaseLock();\n return { done: true, value: undefined };\n }\n\n return { done: false, value };\n } catch (error) {\n this.releaseLock();\n throw error;\n }\n }\n\n /**\n * Implements the return method of the async iterator.\n * Cancels the stream reader and releases the lock.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async return(): Promise<IteratorResult<T>> {\n try {\n await this.reader.cancel();\n } catch (error) {\n console.debug('Failed to cancel stream reader:', error);\n } finally {\n this.releaseLock();\n }\n return { done: true, value: undefined };\n }\n\n /**\n * Implements the throw method of the async iterator.\n * Releases the lock and returns a done result.\n * @param error - The error to be thrown.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async throw(error: any): Promise<IteratorResult<T>> {\n // Ensure the reader lock is released before throwing\n console.debug('Throwing error:', error);\n this.releaseLock();\n return { done: true, value: undefined };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ReadableStreamAsyncIterable } from './readableStreamAsyncIterable';\n\ndeclare global {\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n// Check if ReadableStream already has [Symbol.asyncIterator] implemented\nexport const isReadableStreamAsyncIterableSupported =\n typeof ReadableStream.prototype[Symbol.asyncIterator] === 'function';\n\n// Add [Symbol.asyncIterator] to ReadableStream if not already implemented\nif (!isReadableStreamAsyncIterableSupported) {\n ReadableStream.prototype[Symbol.asyncIterator] = function <R = any>() {\n return new ReadableStreamAsyncIterable<R>(this as ReadableStream<R>);\n };\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EventStreamResultExtractor","exchange","JsonEventStreamResultExtractor","CONTENT_TYPE_HEADER","contentType","ContentTypeValues","eventStream","ReadableStreamAsyncIterable","stream","done","isReadableStreamAsyncIterableSupported"],"mappings":"0SAoBO,MAAMA,CAA2D,CAAjE,aAAA,CACL,KAAQ,OAAS,EAAA,CAQjB,UACEC,EACAC,EACA,CACA,GAAI,CACF,KAAK,QAAUD,EACf,MAAME,EAAQ,KAAK,OAAO,MAAM;AAAA,CAAI,EACpC,KAAK,OAASA,EAAM,IAAA,GAAS,GAE7B,UAAWC,KAAQD,EACjBD,EAAW,QAAQE,CAAI,CAE3B,OAASC,EAAO,CACdH,EAAW,MAAMG,CAAK,CACxB,CACF,CAOA,MAAMH,EAAsD,CAC1D,GAAI,CAEE,KAAK,QACPA,EAAW,QAAQ,KAAK,MAAM,CAElC,OAASG,EAAO,CACdH,EAAW,MAAMG,CAAK,CACxB,CACF,CACF,CAKO,MAAMC,UAAgC,eAAgC,CAC3E,aAAc,CACZ,MAAM,IAAIN,CAAqB,CACjC,CACF,CCzCO,MAAMO,EAAN,MAAMA,CAAsB,CAKnC,EAJEA,EAAgB,GAAK,KACrBA,EAAgB,MAAQ,QACxBA,EAAgB,MAAQ,QACxBA,EAAgB,KAAO,OAJlB,IAAMC,EAAND,EAaP,SAASE,EACPC,EACAC,EACAC,EACA,CACA,OAAQF,EAAA,CACN,KAAKF,EAAsB,MACzBI,EAAa,MAAQD,EACrB,MACF,KAAKH,EAAsB,KACzBI,EAAa,KAAK,KAAKD,CAAK,EAC5B,MACF,KAAKH,EAAsB,GACzBI,EAAa,GAAKD,EAClB,MACF,KAAKH,EAAsB,MAAO,CAChC,MAAMK,EAAa,SAASF,EAAO,EAAE,EAChC,MAAME,CAAU,IACnBD,EAAa,MAAQC,GAEvB,KACF,CAGE,CAEN,CASA,MAAMC,EAAqB,UAOpB,MAAMC,CACqC,CAD3C,aAAA,CAGL,KAAQ,aAA2B,CACjC,MAAOD,EACP,GAAI,OACJ,MAAO,OACP,KAAM,CAAA,CAAC,CACT,CAQA,UACEb,EACAC,EACA,CACA,MAAMU,EAAe,KAAK,aAC1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AA,CACpB,OAASA,EAAO,CACd,QAAQ,MAAM,kCAAmCA,CAAK,CACxD,QAAA,CACE,KAAK,YAAA,CACP,CACA,MAAO,CAAE,KAAM,GAAM,MAAO,MAAA,CAC9B,CAQA,MAAM,MAAMA,EAAwC,CAElD,eAAQ,MAAM,kBAAmBA,CAAK,EACtC,KAAK,YAAA,EACE,CAAE,KAAM,GAAM,MAAO,MAAA,CAC9B,CACF,CClFO,MAAMkC,EACX,OAAO,eAAe,UAAU,OAAO,aAAa,GAAM,WAGvDA,IACH,eAAe,UAAU,OAAO,aAAa,EAAI,UAAqB,CACpE,OAAO,IAAIH,EAA+B,IAAyB,CACrE"}
1
+ {"version":3,"file":"index.umd.js","sources":["../src/textLineTransformStream.ts","../src/serverSentEventTransformStream.ts","../src/eventStreamConverter.ts","../src/jsonServerSentEventTransformStream.ts","../src/eventStreamResultExtractor.ts","../src/responses.ts","../src/readableStreamAsyncIterable.ts","../src/readableStreams.ts"],"sourcesContent":["/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Transformer that splits text into lines.\n *\n * This transformer accumulates chunks of text and splits them by newline characters,\n * emitting each line as a separate chunk while preserving the remaining buffer\n * for the next chunk.\n */\nexport class TextLineTransformer implements Transformer<string, string> {\n private buffer = '';\n\n /**\n * Transform input string chunk by splitting it into lines.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<string>,\n ) {\n try {\n this.buffer += chunk;\n const lines = this.buffer.split('\\n');\n this.buffer = lines.pop() || '';\n\n for (const line of lines) {\n controller.enqueue(line);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n\n /**\n * Flush remaining buffer when the stream ends.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<string>) {\n try {\n // Only send when buffer is not empty, avoid sending meaningless empty lines\n if (this.buffer) {\n controller.enqueue(this.buffer);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n}\n\n/**\n * A TransformStream that splits text into lines.\n */\nexport class TextLineTransformStream extends TransformStream<string, string> {\n constructor() {\n super(new TextLineTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Represents a message sent in an event stream.\n *\n * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format}\n */\nexport interface ServerSentEvent {\n /** The event ID to set the EventSource object's last event ID value. */\n id?: string;\n /** A string identifying the type of event described. */\n event: string;\n /** The event data */\n data: string;\n /** The reconnection interval (in milliseconds) to wait before retrying the connection */\n retry?: number;\n}\n\nexport class ServerSentEventFields {\n static readonly ID = 'id';\n static readonly RETRY = 'retry';\n static readonly EVENT = 'event';\n static readonly DATA = 'data';\n}\n\n/**\n * Process field value\n * @param field Field name\n * @param value Field value\n * @param currentEvent Current event state\n */\nfunction processFieldInternal(\n field: string,\n value: string,\n currentEvent: EventState,\n) {\n switch (field) {\n case ServerSentEventFields.EVENT:\n currentEvent.event = value;\n break;\n case ServerSentEventFields.DATA:\n currentEvent.data.push(value);\n break;\n case ServerSentEventFields.ID:\n currentEvent.id = value;\n break;\n case ServerSentEventFields.RETRY: {\n const retryValue = parseInt(value, 10);\n if (!isNaN(retryValue)) {\n currentEvent.retry = retryValue;\n }\n break;\n }\n default:\n // Ignore unknown fields\n break;\n }\n}\n\ninterface EventState {\n event?: string;\n id?: string;\n retry?: number;\n data: string[];\n}\n\nconst DEFAULT_EVENT_TYPE = 'message';\n\n/**\n * Transformer responsible for converting a string stream into a ServerSentEvent object stream.\n *\n * Implements the Transformer interface for processing data transformation in TransformStream.\n */\nexport class ServerSentEventTransformer\n implements Transformer<string, ServerSentEvent> {\n // Initialize currentEvent with default values in a closure\n private currentEvent: EventState = {\n event: DEFAULT_EVENT_TYPE,\n id: undefined,\n retry: undefined,\n data: [],\n };\n\n /**\n * Transform input string chunk into ServerSentEvent object.\n *\n * @param chunk Input string chunk\n * @param controller Controller for controlling the transform stream\n */\n transform(\n chunk: string,\n controller: TransformStreamDefaultController<ServerSentEvent>,\n ) {\n const currentEvent = this.currentEvent;\n try {\n // Skip empty lines (event separator)\n if (chunk.trim() === '') {\n // If there is accumulated event data, send event\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n\n // Reset current event (preserve id and retry for subsequent events)\n currentEvent.event = DEFAULT_EVENT_TYPE;\n // Preserve id and retry for subsequent events (no need to reassign to themselves)\n currentEvent.data = [];\n }\n return;\n }\n\n // Ignore comment lines (starting with colon)\n if (chunk.startsWith(':')) {\n return;\n }\n\n // Parse fields\n const colonIndex = chunk.indexOf(':');\n let field: string;\n let value: string;\n\n if (colonIndex === -1) {\n // No colon, entire line as field name, value is empty\n field = chunk.toLowerCase();\n value = '';\n } else {\n // Extract field name and value\n field = chunk.substring(0, colonIndex).toLowerCase();\n value = chunk.substring(colonIndex + 1);\n\n // If value starts with space, remove leading space\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n }\n\n // Remove trailing newlines from field and value\n field = field.trim();\n value = value.trim();\n\n processFieldInternal(field, value, currentEvent);\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n\n /**\n * Called when the stream ends, used to process remaining data.\n *\n * @param controller Controller for controlling the transform stream\n */\n flush(controller: TransformStreamDefaultController<ServerSentEvent>) {\n const currentEvent = this.currentEvent;\n try {\n // Send the last event (if any)\n if (currentEvent.data.length > 0) {\n controller.enqueue({\n event: currentEvent.event || DEFAULT_EVENT_TYPE,\n data: currentEvent.data.join('\\n'),\n id: currentEvent.id || '',\n retry: currentEvent.retry,\n } as ServerSentEvent);\n }\n } catch (error) {\n controller.error(\n error instanceof Error ? error : new Error(String(error)),\n );\n } finally {\n // Reset state\n currentEvent.event = DEFAULT_EVENT_TYPE;\n currentEvent.id = undefined;\n currentEvent.retry = undefined;\n currentEvent.data = [];\n }\n }\n}\n\n/**\n * A TransformStream that converts a stream of strings into a stream of ServerSentEvent objects.\n */\nexport class ServerSentEventTransformStream extends TransformStream<\n string,\n ServerSentEvent\n> {\n constructor() {\n super(new ServerSentEventTransformer());\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TextLineTransformStream } from './textLineTransformStream';\nimport {\n type ServerSentEvent,\n ServerSentEventTransformStream,\n} from './serverSentEventTransformStream';\nimport { FetcherError } from '@ahoo-wang/fetcher';\n\n/**\n * A ReadableStream of ServerSentEvent objects.\n */\nexport type ServerSentEventStream = ReadableStream<ServerSentEvent>;\n\n/**\n * Custom error class for event stream conversion errors.\n * Thrown when there are issues converting a Response to a ServerSentEventStream.\n */\nexport class EventStreamConvertError extends FetcherError {\n /**\n * Creates a new EventStreamConvertError instance.\n * @param response - The Response object associated with the error\n * @param errorMsg - Optional error message describing what went wrong during conversion\n * @param cause - Optional underlying error that caused this error\n */\n constructor(\n public readonly response: Response,\n errorMsg?: string,\n cause?: Error | any,\n ) {\n super(errorMsg, cause);\n this.name = 'EventStreamConvertError';\n // Restore prototype chain for proper inheritance\n Object.setPrototypeOf(this, EventStreamConvertError.prototype);\n }\n}\n\n/**\n * Converts a Response object to a ServerSentEventStream.\n *\n * Processes the response body through a series of transform streams:\n * 1. TextDecoderStream: Decode Uint8Array data to UTF-8 strings\n * 2. TextLineStream: Split text by lines\n * 3. ServerSentEventStream: Parse line data into server-sent events\n *\n * @param response - The Response object to convert\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws Error if the response body is null\n */\nexport function toServerSentEventStream(\n response: Response,\n): ServerSentEventStream {\n if (!response.body) {\n throw new EventStreamConvertError(response, 'Response body is null');\n }\n\n return response.body\n .pipeThrough(new TextDecoderStream('utf-8'))\n .pipeThrough(new TextLineTransformStream())\n .pipeThrough(new ServerSentEventTransformStream());\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { type ServerSentEvent } from './serverSentEventTransformStream';\nimport { ServerSentEventStream } from './eventStreamConverter';\n\nexport interface JsonServerSentEvent<DATA>\n extends Omit<ServerSentEvent, 'data'> {\n data: DATA;\n}\n\nexport class JsonServerSentEventTransform<DATA>\n implements Transformer<ServerSentEvent, JsonServerSentEvent<DATA>> {\n transform(\n chunk: ServerSentEvent,\n controller: TransformStreamDefaultController<JsonServerSentEvent<DATA>>,\n ) {\n const json = JSON.parse(chunk.data) as DATA;\n controller.enqueue({\n data: json,\n event: chunk.event,\n id: chunk.id,\n retry: chunk.retry,\n });\n }\n}\n\nexport class JsonServerSentEventTransformStream<DATA> extends TransformStream<\n ServerSentEvent,\n JsonServerSentEvent<DATA>\n> {\n constructor() {\n super(new JsonServerSentEventTransform());\n }\n}\n\nexport type JsonServerSentEventStream<DATA> = ReadableStream<\n JsonServerSentEvent<DATA>\n>;\n\nexport function toJsonServerSentEventStream<DATA>(\n serverSentEventStream: ServerSentEventStream,\n): JsonServerSentEventStream<DATA> {\n return serverSentEventStream.pipeThrough(\n new JsonServerSentEventTransformStream<DATA>(),\n );\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FetchExchange, ResultExtractor } from '@ahoo-wang/fetcher';\nimport { ServerSentEventStream } from './eventStreamConverter';\nimport { JsonServerSentEventStream } from './jsonServerSentEventTransformStream';\n\n/**\n * ServerSentEventStream result extractor, used to extract server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of server-sent event stream\n * @throws ExchangeError exception when server does not support ServerSentEventStream\n */\nexport const EventStreamResultExtractor: ResultExtractor<\n ServerSentEventStream\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredEventStream();\n};\n\n/**\n * JsonServerSentEventStream result extractor, used to extract JSON server-sent event stream from FetchExchange\n *\n * @param exchange - FetchExchange object containing request and response information\n * @returns Readable stream object of JSON server-sent event stream\n * @throws ExchangeError exception when server does not support JsonServerSentEventStream\n */\nexport const JsonEventStreamResultExtractor: ResultExtractor<\n JsonServerSentEventStream<any>\n> = (exchange: FetchExchange) => {\n return exchange.requiredResponse.requiredJsonEventStream();\n};\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n EventStreamConvertError,\n type ServerSentEventStream,\n toServerSentEventStream,\n} from './eventStreamConverter';\nimport {\n type JsonServerSentEventStream,\n toJsonServerSentEventStream,\n} from './jsonServerSentEventTransformStream';\nimport { CONTENT_TYPE_HEADER, ContentTypeValues } from '@ahoo-wang/fetcher';\n\ndeclare global {\n interface Response {\n /**\n * Gets the content type of the response.\n *\n * This property provides access to the Content-Type header of the response,\n * which indicates the media type of the resource transmitted in the response.\n *\n * @returns The content type header value as a string, or null if the header is not set\n */\n get contentType(): string | null;\n\n /**\n * Checks if the response is an event stream.\n *\n * This property examines the Content-Type header to determine if the response\n * contains server-sent events data (text/event-stream).\n *\n * @returns true if the response is an event stream, false otherwise\n */\n get isEventStream(): boolean;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects, or null if not an event stream\n */\n eventStream(): ServerSentEventStream | null;\n\n /**\n * Returns a ServerSentEventStream for consuming server-sent events.\n *\n * This method is similar to eventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream.\n *\n * @returns A ReadableStream of ServerSentEvent objects\n * @throws {Error} if the event stream is not available\n */\n requiredEventStream(): ServerSentEventStream;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is added to Response objects by the EventStreamInterceptor\n * when the response content type indicates a server-sent event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data, or null if not an event stream\n */\n jsonEventStream<DATA>(): JsonServerSentEventStream<DATA> | null;\n\n /**\n * Returns a JsonServerSentEventStream for consuming server-sent events with JSON data.\n *\n * This method is similar to jsonEventStream() but will throw an error if the event stream is not available.\n * It is added to Response objects by the EventStreamInterceptor when the response content type\n * indicates a server-sent event stream with JSON data.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A ReadableStream of ServerSentEvent objects with JSON data\n * @throws {Error} if the event stream is not available\n */\n requiredJsonEventStream<DATA>(): JsonServerSentEventStream<DATA>;\n }\n}\n\nconst CONTENT_TYPE_PROPERTY_NAME = 'contentType';\n/**\n * Defines the contentType property on Response prototype.\n * This property provides a convenient way to access the Content-Type header value.\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n CONTENT_TYPE_PROPERTY_NAME,\n )\n) {\n Object.defineProperty(Response.prototype, CONTENT_TYPE_PROPERTY_NAME, {\n get() {\n return this.headers.get(CONTENT_TYPE_HEADER);\n },\n configurable: true,\n });\n}\n\nconst IS_EVENT_STREAM_PROPERTY_NAME = 'isEventStream';\n/**\n * Defines the isEventStream property on Response prototype.\n * This property checks if the response has a Content-Type header indicating it's an event stream.\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n IS_EVENT_STREAM_PROPERTY_NAME,\n )\n) {\n Object.defineProperty(Response.prototype, IS_EVENT_STREAM_PROPERTY_NAME, {\n get() {\n const contentType = this.contentType;\n if (!contentType) {\n return false;\n }\n return contentType.includes(ContentTypeValues.TEXT_EVENT_STREAM);\n },\n configurable: true,\n });\n}\n\n/**\n * Implementation of the eventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream.\n *\n * @returns A ServerSentEventStream if the response is an event stream, null otherwise\n */\nif (!Object.prototype.hasOwnProperty.call(Response.prototype, 'eventStream')) {\n Response.prototype.eventStream = function() {\n if (!this.isEventStream) {\n return null;\n }\n return toServerSentEventStream(this);\n };\n}\n\n/**\n * Implementation of the requiredEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a ServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @returns A ServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n 'requiredEventStream',\n )\n) {\n Response.prototype.requiredEventStream = function() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n };\n}\n\n/**\n * Implementation of the jsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream, null otherwise\n */\nif (\n !Object.prototype.hasOwnProperty.call(Response.prototype, 'jsonEventStream')\n) {\n Response.prototype.jsonEventStream = function <DATA>() {\n const eventStream = this.eventStream();\n if (!eventStream) {\n return null;\n }\n return toJsonServerSentEventStream<DATA>(eventStream);\n };\n}\n\n/**\n * Implementation of the requiredJsonEventStream method for Response objects.\n * Converts a Response with text/event-stream content type to a JsonServerSentEventStream,\n * throwing an error if the response is not an event stream.\n *\n * @template DATA - The type of the JSON data in the server-sent events\n * @returns A JsonServerSentEventStream if the response is an event stream\n * @throws {Error} if the response is not an event stream\n */\nif (\n !Object.prototype.hasOwnProperty.call(\n Response.prototype,\n 'requiredJsonEventStream',\n )\n) {\n Response.prototype.requiredJsonEventStream = function <DATA>() {\n const eventStream = this.jsonEventStream<DATA>();\n if (!eventStream) {\n throw new EventStreamConvertError(\n this,\n `Event stream is not available. Response content-type: [${this.contentType}]`,\n );\n }\n return eventStream;\n };\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * A wrapper class that converts a ReadableStream into an AsyncIterable.\n * This allows consuming a ReadableStream using for-await...of loops.\n */\nexport class ReadableStreamAsyncIterable<T> implements AsyncIterable<T> {\n private readonly reader: ReadableStreamDefaultReader<T>;\n private _locked: boolean = true;\n\n /**\n * Creates a new ReadableStreamAsyncIterable instance.\n * @param stream - The ReadableStream to wrap.\n */\n constructor(private readonly stream: ReadableStream<T>) {\n this.reader = stream.getReader();\n }\n\n /**\n * Gets the lock status of the reader.\n * @returns True if the reader is currently locked, false otherwise.\n */\n get locked(): boolean {\n return this._locked;\n }\n\n /**\n * Releases the reader lock if currently locked.\n * This method safely releases the reader lock by catching any potential errors.\n */\n releaseLock() {\n if (!this._locked) return false;\n this._locked = false;\n try {\n this.reader.releaseLock();\n return true;\n } catch (error) {\n console.debug('Failed to release reader lock:', error);\n return false;\n }\n }\n\n /**\n * Implements the AsyncIterable interface by returning this iterator.\n * @returns The async iterator for this instance.\n */\n [Symbol.asyncIterator]() {\n return this;\n }\n\n /**\n * Gets the next value from the stream.\n * Reads the next chunk from the stream and returns it as an IteratorResult.\n * If the stream is done, releases the lock and returns a done result.\n * @returns A promise that resolves to an IteratorResult containing the next value or done status.\n * @throws If an error occurs while reading from the stream.\n */\n async next(): Promise<IteratorResult<T>> {\n try {\n const { done, value } = await this.reader.read();\n if (done) {\n this.releaseLock();\n return { done: true, value: undefined };\n }\n\n return { done: false, value };\n } catch (error) {\n this.releaseLock();\n throw error;\n }\n }\n\n /**\n * Implements the return method of the async iterator.\n * Cancels the stream reader and releases the lock.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async return(): Promise<IteratorResult<T>> {\n try {\n await this.reader.cancel();\n } catch (error) {\n console.debug('Failed to cancel stream reader:', error);\n } finally {\n this.releaseLock();\n }\n return { done: true, value: undefined };\n }\n\n /**\n * Implements the throw method of the async iterator.\n * Releases the lock and returns a done result.\n * @param error - The error to be thrown.\n * @returns A promise that resolves to a done IteratorResult.\n */\n async throw(error: any): Promise<IteratorResult<T>> {\n // Ensure the reader lock is released before throwing\n console.debug('Throwing error:', error);\n this.releaseLock();\n return { done: true, value: undefined };\n }\n}\n","/*\n * Copyright [2021-present] [ahoo wang <ahoowang@qq.com> (https://github.com/Ahoo-Wang)].\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * http://www.apache.org/licenses/LICENSE-2.0\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ReadableStreamAsyncIterable } from './readableStreamAsyncIterable';\n\ndeclare global {\n interface ReadableStream<R = any> {\n /**\n * Makes ReadableStream async iterable for use with for-await loops.\n *\n * This allows the stream to be consumed using `for await (const chunk of stream)` syntax.\n *\n * @returns An async iterator for the stream\n */\n [Symbol.asyncIterator](): AsyncIterator<R>;\n }\n}\n\n// Check if ReadableStream already has [Symbol.asyncIterator] implemented\nexport const isReadableStreamAsyncIterableSupported =\n typeof ReadableStream.prototype[Symbol.asyncIterator] === 'function';\n\n// Add [Symbol.asyncIterator] to ReadableStream if not already implemented\nif (!isReadableStreamAsyncIterableSupported) {\n ReadableStream.prototype[Symbol.asyncIterator] = function <R = any>() {\n return new ReadableStreamAsyncIterable<R>(this as ReadableStream<R>);\n };\n}\n"],"names":["TextLineTransformer","chunk","controller","lines","line","error","TextLineTransformStream","_ServerSentEventFields","ServerSentEventFields","processFieldInternal","field","value","currentEvent","retryValue","DEFAULT_EVENT_TYPE","ServerSentEventTransformer","colonIndex","ServerSentEventTransformStream","EventStreamConvertError","FetcherError","response","errorMsg","cause","toServerSentEventStream","JsonServerSentEventTransform","json","JsonServerSentEventTransformStream","toJsonServerSentEventStream","serverSentEventStream","EventStreamResultExtractor","exchange","JsonEventStreamResultExtractor","CONTENT_TYPE_PROPERTY_NAME","CONTENT_TYPE_HEADER","IS_EVENT_STREAM_PROPERTY_NAME","contentType","ContentTypeValues","eventStream","ReadableStreamAsyncIterable","stream","done","isReadableStreamAsyncIterableSupported"],"mappings":"0SAoBO,MAAMA,CAA2D,CAAjE,aAAA,CACL,KAAQ,OAAS,EAAA,CAQjB,UACEC,EACAC,EACA,CACA,GAAI,CACF,KAAK,QAAUD,EACf,MAAME,EAAQ,KAAK,OAAO,MAAM;AAAA,CAAI,EACpC,KAAK,OAASA,EAAM,IAAA,GAAS,GAE7B,UAAWC,KAAQD,EACjBD,EAAW,QAAQE,CAAI,CAE3B,OAASC,EAAO,CACdH,EAAW,MAAMG,CAAK,CACxB,CACF,CAOA,MAAMH,EAAsD,CAC1D,GAAI,CAEE,KAAK,QACPA,EAAW,QAAQ,KAAK,MAAM,CAElC,OAASG,EAAO,CACdH,EAAW,MAAMG,CAAK,CACxB,CACF,CACF,CAKO,MAAMC,UAAgC,eAAgC,CAC3E,aAAc,CACZ,MAAM,IAAIN,CAAqB,CACjC,CACF,CCzCO,MAAMO,EAAN,MAAMA,CAAsB,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,CAC9B,CACF,CClFO,MAAMoC,EACX,OAAO,eAAe,UAAU,OAAO,aAAa,GAAM,WAGvDA,IACH,eAAe,UAAU,OAAO,aAAa,EAAI,UAAqB,CACpE,OAAO,IAAIH,EAA+B,IAAyB,CACrE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ahoo-wang/fetcher-eventstream",
3
- "version": "2.6.13",
3
+ "version": "2.6.16",
4
4
  "description": "Server-Sent Events (SSE) support for Fetcher HTTP client with native LLM streaming API support. Enables real-time data streaming and token-by-token LLM response handling.",
5
5
  "keywords": [
6
6
  "fetch",
@@ -49,7 +49,7 @@
49
49
  "globals": "^16.4.0",
50
50
  "prettier": "^3.6.2",
51
51
  "typescript": "^5.9.3",
52
- "typescript-eslint": "^8.45.0",
52
+ "typescript-eslint": "^8.46.0",
53
53
  "unplugin-dts": "1.0.0-beta.6",
54
54
  "vite": "^7.1.9",
55
55
  "vite-bundle-analyzer": "^1.2.3",