@laravel/stream-react 0.2.1 → 0.3.1
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/README.md +169 -3
- package/dist/index.d.ts +38 -3
- package/dist/index.es.js +193 -39
- package/dist/index.umd.js +1 -1
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
<a href="https://www.npmjs.com/package/@laravel/stream-react"><img src="https://img.shields.io/npm/l/@laravel/stream-react" alt="License"></a>
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
|
-
Easily consume
|
|
10
|
+
Easily consume streams in your React application.
|
|
11
11
|
|
|
12
12
|
## Installation
|
|
13
13
|
|
|
@@ -15,9 +15,175 @@ Easily consume [Server-Sent Events (SSE)](https://laravel.com/docs/responses#eve
|
|
|
15
15
|
npm install @laravel/stream-react
|
|
16
16
|
```
|
|
17
17
|
|
|
18
|
-
##
|
|
18
|
+
## Streaming Responses
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
> [!IMPORTANT]
|
|
21
|
+
> The `useStream` hook is currently in Beta, the API is subject to change prior to the v1.0.0 release. All notable changes will be documented in the [changelog](./../../CHANGELOG.md).
|
|
22
|
+
|
|
23
|
+
The `useStream` hook allows you to seamlessly consume [streamed responses](https://laravel.com/docs/responses#streamed-responses) in your React application.
|
|
24
|
+
|
|
25
|
+
Provide your stream URL and the hook will automatically update `data` with the concatenated response as data is returned from your server:
|
|
26
|
+
|
|
27
|
+
```tsx
|
|
28
|
+
import { useStream } from "@laravel/stream-react";
|
|
29
|
+
|
|
30
|
+
function App() {
|
|
31
|
+
const { data, isFetching, isStreaming, send } = useStream("chat");
|
|
32
|
+
|
|
33
|
+
const sendMessage = () => {
|
|
34
|
+
send({
|
|
35
|
+
message: `Current timestamp: ${Date.now()}`,
|
|
36
|
+
});
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
return (
|
|
40
|
+
<div>
|
|
41
|
+
<div>{data}</div>
|
|
42
|
+
{isFetching && <div>Connecting...</div>}
|
|
43
|
+
{isStreaming && <div>Generating...</div>}
|
|
44
|
+
<button onClick={sendMessage}>Send Message</button>
|
|
45
|
+
</div>
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
When sending data back to the stream, the active connection to the stream is canceled before sending the new data. All requests are sent as JSON `POST` requests.
|
|
51
|
+
|
|
52
|
+
The second argument given to `useStream` is an options object that you may use to customize the stream consumption behavior. The default values for this object are shown below:
|
|
53
|
+
|
|
54
|
+
```tsx
|
|
55
|
+
import { useStream } from "@laravel/stream-react";
|
|
56
|
+
|
|
57
|
+
function App() {
|
|
58
|
+
const { data } = useStream("chat", {
|
|
59
|
+
id: undefined,
|
|
60
|
+
initialInput: undefined,
|
|
61
|
+
headers: undefined,
|
|
62
|
+
csrfToken: undefined,
|
|
63
|
+
onResponse: (response: Response) => void,
|
|
64
|
+
onData: (data: string) => void,
|
|
65
|
+
onCancel: () => void,
|
|
66
|
+
onFinish: () => void,
|
|
67
|
+
onError: (error: Error) => void,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
return <div>{data}</div>;
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
`onResponse` is triggered after a successful initial response from the stream and the raw [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) is passed to the callback.
|
|
75
|
+
|
|
76
|
+
`onData` is called as each chunk is received, the current chunk is passed to the callback.
|
|
77
|
+
|
|
78
|
+
`onFinish` is called when a stream has finished and when an error is thrown during the fetch/read cycle.
|
|
79
|
+
|
|
80
|
+
By default, a request is not made the to stream on initialization. You may pass an initial payload to the stream by using the `initialInput` option:
|
|
81
|
+
|
|
82
|
+
```tsx
|
|
83
|
+
import { useStream } from "@laravel/stream-react";
|
|
84
|
+
|
|
85
|
+
function App() {
|
|
86
|
+
const { data } = useStream("chat", {
|
|
87
|
+
initialInput: {
|
|
88
|
+
message: "Introduce yourself.",
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
return <div>{data}</div>;
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
To cancel a stream manually, you may use the `cancel` method returned from the hook:
|
|
97
|
+
|
|
98
|
+
```tsx
|
|
99
|
+
import { useStream } from "@laravel/stream-react";
|
|
100
|
+
|
|
101
|
+
function App() {
|
|
102
|
+
const { data, cancel } = useStream("chat");
|
|
103
|
+
|
|
104
|
+
return (
|
|
105
|
+
<div>
|
|
106
|
+
<div>{data}</div>
|
|
107
|
+
<button onClick={cancel}>Cancel</button>
|
|
108
|
+
</div>
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Each time the `useStream` hook is used, a random `id` is generated to identify the stream. This is sent back to the server with each request in the `X-STREAM-ID` header.
|
|
114
|
+
|
|
115
|
+
When consuming the same stream from multiple components, you can read and write to the stream by providing your own `id`:
|
|
116
|
+
|
|
117
|
+
```tsx
|
|
118
|
+
// App.tsx
|
|
119
|
+
import { useStream } from "@laravel/stream-react";
|
|
120
|
+
|
|
121
|
+
function App() {
|
|
122
|
+
const { data, id } = useStream("chat");
|
|
123
|
+
|
|
124
|
+
return (
|
|
125
|
+
<div>
|
|
126
|
+
<div>{data}</div>
|
|
127
|
+
<StreamStatus id={id} />
|
|
128
|
+
</div>
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// StreamStatus.tsx
|
|
133
|
+
import { useStream } from "@laravel/stream-react";
|
|
134
|
+
|
|
135
|
+
function StreamStatus({ id }) {
|
|
136
|
+
const { isFetching, isStreaming } = useStream("chat", { id });
|
|
137
|
+
|
|
138
|
+
return (
|
|
139
|
+
<div>
|
|
140
|
+
{isFetching && <div>Connecting...</div>}
|
|
141
|
+
{isStreaming && <div>Generating...</div>}
|
|
142
|
+
</div>
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
The `useJsonStream` hook is identical to the `useStream` hook except that it will attempt to parse the data as JSON once it has finished streaming:
|
|
148
|
+
|
|
149
|
+
```tsx
|
|
150
|
+
import { useJsonStream } from "@laravel/stream-react";
|
|
151
|
+
|
|
152
|
+
type User = {
|
|
153
|
+
id: number;
|
|
154
|
+
name: string;
|
|
155
|
+
email: string;
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
function App() {
|
|
159
|
+
const { data, send } = useJsonStream<{ users: User[] }>("users");
|
|
160
|
+
|
|
161
|
+
const loadUsers = () => {
|
|
162
|
+
send({
|
|
163
|
+
query: "taylor",
|
|
164
|
+
});
|
|
165
|
+
};
|
|
166
|
+
|
|
167
|
+
return (
|
|
168
|
+
<div>
|
|
169
|
+
<ul>
|
|
170
|
+
{data?.users.map((user) => (
|
|
171
|
+
<li>
|
|
172
|
+
{user.id}: {user.name}
|
|
173
|
+
</li>
|
|
174
|
+
))}
|
|
175
|
+
</ul>
|
|
176
|
+
<button onClick={loadUsers}>Load Users</button>
|
|
177
|
+
</div>
|
|
178
|
+
);
|
|
179
|
+
}
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
## Event Streams (SSE)
|
|
183
|
+
|
|
184
|
+
The `useEventStream` hook allows you to seamlessly consume [Server-Sent Events (SSE)](https://laravel.com/docs/responses#event-streams) in your React application.
|
|
185
|
+
|
|
186
|
+
Provide your stream URL and the hook will automatically update `message` with the concatenated response as messages are returned from your server:
|
|
21
187
|
|
|
22
188
|
```tsx
|
|
23
189
|
import { useEventStream } from "@laravel/stream-react";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
declare type
|
|
1
|
+
declare type EventStreamOptions = {
|
|
2
2
|
eventName?: string | string[];
|
|
3
3
|
endSignal?: string;
|
|
4
4
|
glue?: string;
|
|
@@ -8,13 +8,26 @@ declare type Options = {
|
|
|
8
8
|
onError?: (error: Event) => void;
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
-
declare type
|
|
11
|
+
declare type EventStreamResult = {
|
|
12
12
|
message: string;
|
|
13
13
|
messageParts: string[];
|
|
14
14
|
close: (resetMessage?: boolean) => void;
|
|
15
15
|
clearMessage: () => void;
|
|
16
16
|
};
|
|
17
17
|
|
|
18
|
+
declare type StreamOptions = {
|
|
19
|
+
id?: string;
|
|
20
|
+
initialInput?: Record<string, any>;
|
|
21
|
+
headers?: Record<string, string>;
|
|
22
|
+
csrfToken?: string;
|
|
23
|
+
json?: boolean;
|
|
24
|
+
onResponse?: (response: Response) => void;
|
|
25
|
+
onData?: (data: string) => void;
|
|
26
|
+
onCancel?: () => void;
|
|
27
|
+
onFinish?: () => void;
|
|
28
|
+
onError?: (error: Error) => void;
|
|
29
|
+
};
|
|
30
|
+
|
|
18
31
|
/**
|
|
19
32
|
* Hook for handling server-sent event (SSE) streams
|
|
20
33
|
*
|
|
@@ -25,6 +38,28 @@ declare type StreamResult = {
|
|
|
25
38
|
*
|
|
26
39
|
* @returns StreamResult object containing the accumulated response, close, and reset functions
|
|
27
40
|
*/
|
|
28
|
-
export declare const useEventStream: (url: string, { eventName, endSignal, glue, replace, onMessage, onComplete, onError, }?:
|
|
41
|
+
export declare const useEventStream: (url: string, { eventName, endSignal, glue, replace, onMessage, onComplete, onError, }?: EventStreamOptions) => EventStreamResult;
|
|
42
|
+
|
|
43
|
+
export declare const useJsonStream: <TJsonData = null>(url: string, options?: Omit<StreamOptions, "json">) => {
|
|
44
|
+
isFetching: boolean;
|
|
45
|
+
isStreaming: boolean;
|
|
46
|
+
id: string;
|
|
47
|
+
send: (body: Record<string, any>) => void;
|
|
48
|
+
cancel: () => void;
|
|
49
|
+
clearData: () => void;
|
|
50
|
+
data: TJsonData | null;
|
|
51
|
+
rawData: string;
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export declare const useStream: <TJsonData = null>(url: string, options?: StreamOptions) => {
|
|
55
|
+
data: string;
|
|
56
|
+
jsonData: TJsonData | null;
|
|
57
|
+
isFetching: boolean;
|
|
58
|
+
isStreaming: boolean;
|
|
59
|
+
id: string;
|
|
60
|
+
send: (body: Record<string, any>) => void;
|
|
61
|
+
cancel: () => void;
|
|
62
|
+
clearData: () => void;
|
|
63
|
+
};
|
|
29
64
|
|
|
30
65
|
export { }
|
package/dist/index.es.js
CHANGED
|
@@ -1,48 +1,202 @@
|
|
|
1
|
-
import { useRef as
|
|
2
|
-
const
|
|
3
|
-
eventName:
|
|
4
|
-
endSignal:
|
|
5
|
-
glue:
|
|
6
|
-
replace:
|
|
7
|
-
onMessage:
|
|
8
|
-
onComplete:
|
|
9
|
-
onError:
|
|
1
|
+
import { useRef as j, useMemo as V, useState as y, useCallback as o, useEffect as M } from "react";
|
|
2
|
+
const I = "data: ", Q = (r, {
|
|
3
|
+
eventName: e = "update",
|
|
4
|
+
endSignal: n = "</stream>",
|
|
5
|
+
glue: c = " ",
|
|
6
|
+
replace: b = !1,
|
|
7
|
+
onMessage: T = () => null,
|
|
8
|
+
onComplete: k = () => null,
|
|
9
|
+
onError: P = () => null
|
|
10
10
|
} = {}) => {
|
|
11
|
-
const
|
|
12
|
-
() => Array.isArray(
|
|
13
|
-
Array.isArray(
|
|
14
|
-
), [
|
|
15
|
-
|
|
16
|
-
}, []),
|
|
17
|
-
(
|
|
18
|
-
if ([
|
|
19
|
-
|
|
11
|
+
const i = j(null), g = j([]), w = V(
|
|
12
|
+
() => Array.isArray(e) ? e : [e],
|
|
13
|
+
Array.isArray(e) ? e : [e]
|
|
14
|
+
), [D, A] = y(""), [d, f] = y([]), h = o(() => {
|
|
15
|
+
g.current = [], A(""), f([]);
|
|
16
|
+
}, []), E = o(
|
|
17
|
+
(t) => {
|
|
18
|
+
if ([n, `${I}${n}`].includes(t.data)) {
|
|
19
|
+
S(), k();
|
|
20
20
|
return;
|
|
21
21
|
}
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
),
|
|
22
|
+
b && h(), g.current.push(
|
|
23
|
+
t.data.startsWith(I) ? t.data.substring(I.length) : t.data
|
|
24
|
+
), A(g.current.join(c)), f(g.current), T(t);
|
|
25
25
|
},
|
|
26
|
-
[
|
|
27
|
-
),
|
|
28
|
-
|
|
29
|
-
}, []),
|
|
30
|
-
var
|
|
31
|
-
|
|
32
|
-
var
|
|
33
|
-
(
|
|
34
|
-
}), (
|
|
26
|
+
[w, c]
|
|
27
|
+
), F = o((t) => {
|
|
28
|
+
P(t), S();
|
|
29
|
+
}, []), S = o((t = !1) => {
|
|
30
|
+
var a, s;
|
|
31
|
+
w.forEach((u) => {
|
|
32
|
+
var l;
|
|
33
|
+
(l = i.current) == null || l.removeEventListener(u, E);
|
|
34
|
+
}), (a = i.current) == null || a.removeEventListener("error", F), (s = i.current) == null || s.close(), i.current = null, t && h();
|
|
35
35
|
}, []);
|
|
36
|
-
return
|
|
37
|
-
var
|
|
38
|
-
(
|
|
39
|
-
}),
|
|
40
|
-
message:
|
|
41
|
-
messageParts:
|
|
42
|
-
close:
|
|
43
|
-
clearMessage:
|
|
36
|
+
return M(() => (h(), i.current = new EventSource(r), w.forEach((t) => {
|
|
37
|
+
var a;
|
|
38
|
+
(a = i.current) == null || a.addEventListener(t, E);
|
|
39
|
+
}), i.current.addEventListener("error", F), S), [r, w, E, F, h]), {
|
|
40
|
+
message: D,
|
|
41
|
+
messageParts: d,
|
|
42
|
+
close: S,
|
|
43
|
+
clearMessage: h
|
|
44
44
|
};
|
|
45
|
+
}, W = "useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";
|
|
46
|
+
let $ = (r = 21) => {
|
|
47
|
+
let e = "", n = crypto.getRandomValues(new Uint8Array(r |= 0));
|
|
48
|
+
for (; r--; )
|
|
49
|
+
e += W[n[r] & 63];
|
|
50
|
+
return e;
|
|
51
|
+
};
|
|
52
|
+
const C = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Map(), R = (r) => {
|
|
53
|
+
const e = C.get(r);
|
|
54
|
+
if (e)
|
|
55
|
+
return e;
|
|
56
|
+
const n = {
|
|
57
|
+
controller: new AbortController(),
|
|
58
|
+
data: "",
|
|
59
|
+
isFetching: !1,
|
|
60
|
+
isStreaming: !1,
|
|
61
|
+
jsonData: null
|
|
62
|
+
};
|
|
63
|
+
return C.set(r, n), n;
|
|
64
|
+
}, q = (r) => (m.has(r) || m.set(r, []), m.get(r)), X = (r) => {
|
|
65
|
+
var e;
|
|
66
|
+
return m.has(r) && ((e = m.get(r)) == null ? void 0 : e.length);
|
|
67
|
+
}, B = (r, e) => (q(r).push(e), () => {
|
|
68
|
+
m.set(
|
|
69
|
+
r,
|
|
70
|
+
q(r).filter((n) => n !== e)
|
|
71
|
+
), X(r) || (C.delete(r), m.delete(r));
|
|
72
|
+
}), G = (r, e = {}) => {
|
|
73
|
+
const n = j(e.id ?? $()), c = j(R(n.current)), b = j(
|
|
74
|
+
(() => {
|
|
75
|
+
var s;
|
|
76
|
+
const t = {
|
|
77
|
+
"Content-Type": "application/json",
|
|
78
|
+
"X-STREAM-ID": n.current
|
|
79
|
+
}, a = e.csrfToken ?? ((s = document.querySelector('meta[name="csrf-token"]')) == null ? void 0 : s.getAttribute("content"));
|
|
80
|
+
return a && (t["X-CSRF-TOKEN"] = a), t;
|
|
81
|
+
})()
|
|
82
|
+
), [T, k] = y(c.current.data), [P, i] = y(
|
|
83
|
+
c.current.jsonData
|
|
84
|
+
), [g, w] = y(c.current.isFetching), [D, A] = y(c.current.isStreaming), d = o(
|
|
85
|
+
(t) => {
|
|
86
|
+
var s;
|
|
87
|
+
C.set(n.current, {
|
|
88
|
+
...R(n.current),
|
|
89
|
+
...t
|
|
90
|
+
});
|
|
91
|
+
const a = R(n.current);
|
|
92
|
+
(s = m.get(n.current)) == null || s.forEach((u) => u(a));
|
|
93
|
+
},
|
|
94
|
+
[]
|
|
95
|
+
), f = o(() => {
|
|
96
|
+
var t;
|
|
97
|
+
c.current.controller.abort(), (g || D) && ((t = e.onCancel) == null || t.call(e)), d({
|
|
98
|
+
isFetching: !1,
|
|
99
|
+
isStreaming: !1
|
|
100
|
+
});
|
|
101
|
+
}, [g, D]), h = o(() => {
|
|
102
|
+
d({
|
|
103
|
+
data: "",
|
|
104
|
+
jsonData: null
|
|
105
|
+
});
|
|
106
|
+
}, []), E = o(
|
|
107
|
+
(t = {}) => {
|
|
108
|
+
const a = new AbortController();
|
|
109
|
+
d({
|
|
110
|
+
isFetching: !0,
|
|
111
|
+
controller: a
|
|
112
|
+
}), fetch(r, {
|
|
113
|
+
method: "POST",
|
|
114
|
+
signal: a.signal,
|
|
115
|
+
headers: {
|
|
116
|
+
...b.current,
|
|
117
|
+
...e.headers ?? {}
|
|
118
|
+
},
|
|
119
|
+
body: JSON.stringify(t)
|
|
120
|
+
}).then(async (s) => {
|
|
121
|
+
var u;
|
|
122
|
+
if (!s.ok) {
|
|
123
|
+
const l = await s.text();
|
|
124
|
+
throw new Error(l);
|
|
125
|
+
}
|
|
126
|
+
if (!s.body)
|
|
127
|
+
throw new Error(
|
|
128
|
+
"ReadableStream not yet supported in this browser."
|
|
129
|
+
);
|
|
130
|
+
return (u = e.onResponse) == null || u.call(e, s), d({
|
|
131
|
+
isFetching: !1,
|
|
132
|
+
isStreaming: !0
|
|
133
|
+
}), S(s.body.getReader());
|
|
134
|
+
}).catch((s) => {
|
|
135
|
+
var u, l;
|
|
136
|
+
d({
|
|
137
|
+
isFetching: !1,
|
|
138
|
+
isStreaming: !1
|
|
139
|
+
}), (u = e.onError) == null || u.call(e, s), (l = e.onFinish) == null || l.call(e);
|
|
140
|
+
});
|
|
141
|
+
},
|
|
142
|
+
[r]
|
|
143
|
+
), F = o((t) => {
|
|
144
|
+
f(), E(t), h();
|
|
145
|
+
}, []), S = o(
|
|
146
|
+
(t, a = "") => t.read().then(({ done: s, value: u }) => {
|
|
147
|
+
var x, J, O;
|
|
148
|
+
const l = new TextDecoder("utf-8").decode(u), v = a + l;
|
|
149
|
+
(x = e.onData) == null || x.call(e, l);
|
|
150
|
+
const L = {
|
|
151
|
+
data: v
|
|
152
|
+
};
|
|
153
|
+
if (!s)
|
|
154
|
+
return d(L), S(t, v);
|
|
155
|
+
if (L.isStreaming = !1, e.json)
|
|
156
|
+
try {
|
|
157
|
+
L.jsonData = JSON.parse(
|
|
158
|
+
v
|
|
159
|
+
);
|
|
160
|
+
} catch (K) {
|
|
161
|
+
(J = e.onError) == null || J.call(e, K);
|
|
162
|
+
}
|
|
163
|
+
return d(L), (O = e.onFinish) == null || O.call(e), "";
|
|
164
|
+
}),
|
|
165
|
+
[]
|
|
166
|
+
);
|
|
167
|
+
return M(() => {
|
|
168
|
+
const t = B(
|
|
169
|
+
n.current,
|
|
170
|
+
(a) => {
|
|
171
|
+
c.current = R(n.current), w(a.isFetching), A(a.isStreaming), k(a.data), i(a.jsonData);
|
|
172
|
+
}
|
|
173
|
+
);
|
|
174
|
+
return () => {
|
|
175
|
+
t(), X(n.current) || f();
|
|
176
|
+
};
|
|
177
|
+
}, []), M(() => (window.addEventListener("beforeunload", f), () => {
|
|
178
|
+
window.removeEventListener("beforeunload", f);
|
|
179
|
+
}), [f]), M(() => {
|
|
180
|
+
e.initialInput && E(e.initialInput);
|
|
181
|
+
}, []), {
|
|
182
|
+
data: T,
|
|
183
|
+
jsonData: P,
|
|
184
|
+
isFetching: g,
|
|
185
|
+
isStreaming: D,
|
|
186
|
+
id: n.current,
|
|
187
|
+
send: F,
|
|
188
|
+
cancel: f,
|
|
189
|
+
clearData: h
|
|
190
|
+
};
|
|
191
|
+
}, Y = (r, e = {}) => {
|
|
192
|
+
const { jsonData: n, data: c, ...b } = G(r, {
|
|
193
|
+
...e,
|
|
194
|
+
json: !0
|
|
195
|
+
});
|
|
196
|
+
return { data: n, rawData: c, ...b };
|
|
45
197
|
};
|
|
46
198
|
export {
|
|
47
|
-
|
|
199
|
+
Q as useEventStream,
|
|
200
|
+
Y as useJsonStream,
|
|
201
|
+
G as useStream
|
|
48
202
|
};
|
package/dist/index.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(t
|
|
1
|
+
(function(i,t){typeof exports=="object"&&typeof module<"u"?t(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],t):(i=typeof globalThis<"u"?globalThis:i||self,t(i.LaravelStreamReact={},i.React))})(this,function(i,t){"use strict";const L="data: ",X=(r,{eventName:e="update",endSignal:s="</stream>",glue:c=" ",replace:y=!1,onMessage:A=()=>null,onComplete:M=()=>null,onError:T=()=>null}={})=>{const o=t.useRef(null),m=t.useRef([]),E=t.useMemo(()=>Array.isArray(e)?e:[e],Array.isArray(e)?e:[e]),[C,j]=t.useState(""),[d,h]=t.useState([]),S=t.useCallback(()=>{m.current=[],j(""),h([])},[]),w=t.useCallback(n=>{if([s,`${L}${s}`].includes(n.data)){b(),M();return}y&&S(),m.current.push(n.data.startsWith(L)?n.data.substring(L.length):n.data),j(m.current.join(c)),h(m.current),A(n)},[E,c]),R=t.useCallback(n=>{T(n),b()},[]),b=t.useCallback((n=!1)=>{var a,u;E.forEach(l=>{var f;(f=o.current)==null||f.removeEventListener(l,w)}),(a=o.current)==null||a.removeEventListener("error",R),(u=o.current)==null||u.close(),o.current=null,n&&S()},[]);return t.useEffect(()=>(S(),o.current=new EventSource(r),E.forEach(n=>{var a;(a=o.current)==null||a.addEventListener(n,w)}),o.current.addEventListener("error",R),b),[r,E,w,R,S]),{message:C,messageParts:d,close:b,clearMessage:S}},K="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";let V=(r=21)=>{let e="",s=crypto.getRandomValues(new Uint8Array(r|=0));for(;r--;)e+=K[s[r]&63];return e};const k=new Map,g=new Map,D=r=>{const e=k.get(r);if(e)return e;const s={controller:new AbortController,data:"",isFetching:!1,isStreaming:!1,jsonData:null};return k.set(r,s),s},P=r=>(g.has(r)||g.set(r,[]),g.get(r)),I=r=>{var e;return g.has(r)&&((e=g.get(r))==null?void 0:e.length)},W=(r,e)=>(P(r).push(e),()=>{g.set(r,P(r).filter(s=>s!==e)),I(r)||(k.delete(r),g.delete(r))}),J=(r,e={})=>{const s=t.useRef(e.id??V()),c=t.useRef(D(s.current)),y=t.useRef((()=>{var u;const n={"Content-Type":"application/json","X-STREAM-ID":s.current},a=e.csrfToken??((u=document.querySelector('meta[name="csrf-token"]'))==null?void 0:u.getAttribute("content"));return a&&(n["X-CSRF-TOKEN"]=a),n})()),[A,M]=t.useState(c.current.data),[T,o]=t.useState(c.current.jsonData),[m,E]=t.useState(c.current.isFetching),[C,j]=t.useState(c.current.isStreaming),d=t.useCallback(n=>{var u;k.set(s.current,{...D(s.current),...n});const a=D(s.current);(u=g.get(s.current))==null||u.forEach(l=>l(a))},[]),h=t.useCallback(()=>{var n;c.current.controller.abort(),(m||C)&&((n=e.onCancel)==null||n.call(e)),d({isFetching:!1,isStreaming:!1})},[m,C]),S=t.useCallback(()=>{d({data:"",jsonData:null})},[]),w=t.useCallback((n={})=>{const a=new AbortController;d({isFetching:!0,controller:a}),fetch(r,{method:"POST",signal:a.signal,headers:{...y.current,...e.headers??{}},body:JSON.stringify(n)}).then(async u=>{var l;if(!u.ok){const f=await u.text();throw new Error(f)}if(!u.body)throw new Error("ReadableStream not yet supported in this browser.");return(l=e.onResponse)==null||l.call(e,u),d({isFetching:!1,isStreaming:!0}),b(u.body.getReader())}).catch(u=>{var l,f;d({isFetching:!1,isStreaming:!1}),(l=e.onError)==null||l.call(e,u),(f=e.onFinish)==null||f.call(e)})},[r]),R=t.useCallback(n=>{h(),w(n),S()},[]),b=t.useCallback((n,a="")=>n.read().then(({done:u,value:l})=>{var O,q,x;const f=new TextDecoder("utf-8").decode(l),v=a+f;(O=e.onData)==null||O.call(e,f);const F={data:v};if(!u)return d(F),b(n,v);if(F.isStreaming=!1,e.json)try{F.jsonData=JSON.parse(v)}catch(B){(q=e.onError)==null||q.call(e,B)}return d(F),(x=e.onFinish)==null||x.call(e),""}),[]);return t.useEffect(()=>{const n=W(s.current,a=>{c.current=D(s.current),E(a.isFetching),j(a.isStreaming),M(a.data),o(a.jsonData)});return()=>{n(),I(s.current)||h()}},[]),t.useEffect(()=>(window.addEventListener("beforeunload",h),()=>{window.removeEventListener("beforeunload",h)}),[h]),t.useEffect(()=>{e.initialInput&&w(e.initialInput)},[]),{data:A,jsonData:T,isFetching:m,isStreaming:C,id:s.current,send:R,cancel:h,clearData:S}},$=(r,e={})=>{const{jsonData:s,data:c,...y}=J(r,{...e,json:!0});return{data:s,rawData:c,...y}};i.useEventStream=X,i.useJsonStream=$,i.useStream=J,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@laravel/stream-react",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Laravel streaming hooks for React",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"laravel",
|
|
@@ -47,10 +47,11 @@
|
|
|
47
47
|
"@vitejs/plugin-vue": "^5.0.0",
|
|
48
48
|
"eslint": "^9.0.0",
|
|
49
49
|
"jsdom": "^26.0.0",
|
|
50
|
+
"msw": "^2.8.2",
|
|
50
51
|
"prettier": "^3.5.3",
|
|
51
52
|
"typescript": "^5.3.0",
|
|
52
|
-
"vite-plugin-dts": "^4.5.3",
|
|
53
53
|
"vite": "^5.1.0",
|
|
54
|
+
"vite-plugin-dts": "^4.5.3",
|
|
54
55
|
"vitest": "^3.1.1"
|
|
55
56
|
},
|
|
56
57
|
"peerDependencies": {
|