supabase-edge-function-continuous-stream 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Huy Pham
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,54 @@
1
+ # supabase-edge-function-continuous-stream
2
+
3
+ Continuous WebSocket streaming for Supabase edge functions. Keeps a persistent connection alive across cold starts, supports warmup/context loading, and streams AI responses with automatic retry and worker TTL rotation.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install supabase-edge-function-continuous-stream
9
+ ```
10
+
11
+ ## Entries
12
+
13
+ | Import | React required? | Use for |
14
+ |---|---|---|
15
+ | `supabase-edge-function-continuous-stream` | No | `connectEdgeSocket`, `createStandardAiMessageHandler`, types |
16
+ | `supabase-edge-function-continuous-stream/react` | Yes | `createUseEdgeStream` hook factory |
17
+
18
+ ## React usage
19
+
20
+ Prefer the main entry (works with Next.js webpack and published npm installs):
21
+
22
+ ```ts
23
+ import { createUseEdgeStream } from "supabase-edge-function-continuous-stream";
24
+ ```
25
+
26
+ For explicit React-only imports:
27
+
28
+ ```ts
29
+ import { createUseEdgeStream } from "supabase-edge-function-continuous-stream/react";
30
+ ```
31
+
32
+ ```ts
33
+ import { DEFAULT_EDGE_WORKER_LIMITS } from "supabase-edge-function-continuous-stream";
34
+
35
+ export const useEdgeStream = createUseEdgeStream({
36
+ getAccessToken: async () => {
37
+ const { data } = await supabase.auth.getSession();
38
+ if (!data.session?.access_token) throw new Error("Not authenticated");
39
+ return data.session.access_token;
40
+ },
41
+ getSupabaseUrl: () => process.env.NEXT_PUBLIC_SUPABASE_URL!,
42
+ workerLimits: DEFAULT_EDGE_WORKER_LIMITS,
43
+ });
44
+ ```
45
+
46
+ ## Wire protocol
47
+
48
+ 1. Client opens WebSocket with JWT query param
49
+ 2. `client_warmup` → server responds `status: ready`
50
+ 3. `client_message` → streamed events → `complete`
51
+
52
+ ## License
53
+
54
+ MIT
@@ -0,0 +1,462 @@
1
+ // src/constants.ts
2
+ var MAX_RETRIES = 200;
3
+ var INITIAL_RETRY_DELAY_MS = 1e3;
4
+ var CONNECTION_TIMEOUT_MS = 1e4;
5
+
6
+ // src/connection.ts
7
+ async function connectEdgeSocket(deps) {
8
+ const {
9
+ functionPath,
10
+ getAccessToken,
11
+ getSupabaseUrl,
12
+ wsRef,
13
+ isExplicitDisconnectRef,
14
+ isConnectingRef,
15
+ retryCountRef,
16
+ socketOpenedAtRef,
17
+ isWarmupReadyRef,
18
+ warmupWaitersRef,
19
+ passiveOnServerActionRef,
20
+ activeRequestRef,
21
+ lastWarmupPayloadRef,
22
+ setIsConnected,
23
+ closeSocket,
24
+ sendWarmupPayload,
25
+ settleWarmupWaiters
26
+ } = deps;
27
+ if (wsRef.current?.readyState === WebSocket.OPEN) return Promise.resolve();
28
+ if (isConnectingRef.current) {
29
+ return new Promise((resolve, reject) => {
30
+ const checkInterval = setInterval(() => {
31
+ if (wsRef.current?.readyState === WebSocket.OPEN) {
32
+ clearInterval(checkInterval);
33
+ resolve();
34
+ } else if (wsRef.current?.readyState === WebSocket.CLOSED) {
35
+ clearInterval(checkInterval);
36
+ reject(new Error("Connection closed during check"));
37
+ }
38
+ }, 100);
39
+ });
40
+ }
41
+ isConnectingRef.current = true;
42
+ isExplicitDisconnectRef.current = false;
43
+ try {
44
+ const accessToken = await getAccessToken();
45
+ const supabaseUrl = getSupabaseUrl();
46
+ if (!supabaseUrl) throw new Error("Missing Supabase URL");
47
+ const wsUrl = supabaseUrl.replace(
48
+ /^https?:\/\//,
49
+ (m) => m === "https://" ? "wss://" : "ws://"
50
+ );
51
+ const functionUrl = `${wsUrl}/functions/v1/${functionPath}`;
52
+ return await new Promise((resolveConnection, rejectConnection) => {
53
+ let connectionTimeout = null;
54
+ if (wsRef.current) {
55
+ try {
56
+ wsRef.current.onopen = null;
57
+ wsRef.current.onmessage = null;
58
+ wsRef.current.onerror = null;
59
+ wsRef.current.onclose = null;
60
+ if (wsRef.current.readyState === WebSocket.OPEN || wsRef.current.readyState === WebSocket.CONNECTING) {
61
+ wsRef.current.close();
62
+ }
63
+ } catch {
64
+ }
65
+ }
66
+ const urlWithToken = new URL(functionUrl);
67
+ urlWithToken.searchParams.set("jwt", accessToken);
68
+ wsRef.current = new WebSocket(urlWithToken.toString());
69
+ if (retryCountRef.current === 0) {
70
+ connectionTimeout = setTimeout(() => {
71
+ if (wsRef.current && wsRef.current.readyState !== WebSocket.OPEN) {
72
+ isExplicitDisconnectRef.current = false;
73
+ closeSocket();
74
+ }
75
+ }, CONNECTION_TIMEOUT_MS);
76
+ }
77
+ wsRef.current.onopen = () => {
78
+ if (connectionTimeout) clearTimeout(connectionTimeout);
79
+ retryCountRef.current = 0;
80
+ isConnectingRef.current = false;
81
+ setIsConnected(true);
82
+ socketOpenedAtRef.current = Date.now();
83
+ if (lastWarmupPayloadRef.current) {
84
+ sendWarmupPayload();
85
+ }
86
+ resolveConnection();
87
+ };
88
+ wsRef.current.onerror = () => {
89
+ };
90
+ const retryConnect = () => {
91
+ connectEdgeSocket(deps).then(resolveConnection).catch(rejectConnection);
92
+ };
93
+ wsRef.current.onclose = () => {
94
+ if (connectionTimeout) clearTimeout(connectionTimeout);
95
+ isConnectingRef.current = false;
96
+ setIsConnected(false);
97
+ isWarmupReadyRef.current = false;
98
+ const willRetry = !isExplicitDisconnectRef.current && retryCountRef.current < MAX_RETRIES;
99
+ if (!willRetry) {
100
+ settleWarmupWaiters(new Error("WebSocket closed"));
101
+ }
102
+ if (isExplicitDisconnectRef.current) {
103
+ rejectConnection(
104
+ new Error("WebSocket closed by server or aborted")
105
+ );
106
+ } else if (retryCountRef.current < MAX_RETRIES) {
107
+ retryCountRef.current++;
108
+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, retryCountRef.current - 1);
109
+ setTimeout(retryConnect, delay);
110
+ } else {
111
+ rejectConnection(
112
+ new Error(
113
+ `WebSocket connection failed after ${retryCountRef.current} retries`
114
+ )
115
+ );
116
+ }
117
+ };
118
+ wsRef.current.onmessage = (event) => {
119
+ try {
120
+ const message = JSON.parse(event.data);
121
+ if (message.type === "status" && message.data === "ready") {
122
+ isWarmupReadyRef.current = true;
123
+ settleWarmupWaiters();
124
+ }
125
+ if (message.type === "error" && warmupWaitersRef.current.length > 0 && !isWarmupReadyRef.current) {
126
+ isWarmupReadyRef.current = false;
127
+ settleWarmupWaiters(
128
+ new Error(String(message.data ?? "Warmup failed"))
129
+ );
130
+ }
131
+ const passive = passiveOnServerActionRef.current;
132
+ if (passive && !activeRequestRef.current) {
133
+ const isWarmupControl = message.type === "status" && (message.data === "ready" || message.data === "context");
134
+ if (!isWarmupControl) {
135
+ passive(message.type, message.data);
136
+ }
137
+ }
138
+ if (!activeRequestRef.current) return;
139
+ const { ctx, handler } = activeRequestRef.current;
140
+ handler(message, ctx);
141
+ } catch (error) {
142
+ if (!activeRequestRef.current) return;
143
+ const ctx = activeRequestRef.current.ctx;
144
+ ctx.reject(
145
+ new Error(
146
+ `Failed to parse WebSocket message: ${error instanceof Error ? error.message : String(error)}`
147
+ )
148
+ );
149
+ }
150
+ };
151
+ });
152
+ } catch (err) {
153
+ isConnectingRef.current = false;
154
+ throw err;
155
+ }
156
+ }
157
+
158
+ // src/handler.ts
159
+ function createStandardAiMessageHandler(defaults = {}, callbacks) {
160
+ const state = {};
161
+ const buildResponse = (overrides) => ({
162
+ ...defaults,
163
+ ...state,
164
+ ...overrides
165
+ });
166
+ return (message, ctx) => {
167
+ if (message.type === "response_text" && typeof message.data === "string") {
168
+ state.reply = message.data;
169
+ }
170
+ if (typeof message.data === "object" && message.data !== null && message.type !== "error") {
171
+ Object.assign(state, message.data);
172
+ }
173
+ if (message.type === "error") {
174
+ const raw = message.data ?? "Server error";
175
+ const userMsg = callbacks?.toUserMessage?.(raw);
176
+ if (userMsg) callbacks?.onServerAction?.("error", userMsg);
177
+ ctx.reject(new Error(raw));
178
+ return;
179
+ }
180
+ if (message.type === "complete") {
181
+ ctx.clearOverallTimeout();
182
+ callbacks?.onServerAction?.("complete", message.data);
183
+ if (!ctx.isResolved()) {
184
+ ctx.resolve(buildResponse(message.data));
185
+ }
186
+ return;
187
+ }
188
+ callbacks?.onServerAction?.(message.type, message.data);
189
+ };
190
+ }
191
+
192
+ // src/createUseEdgeStream.ts
193
+ import { useCallback, useEffect, useRef, useState } from "react";
194
+ function createUseEdgeStream(deps) {
195
+ const {
196
+ getAccessToken,
197
+ getSupabaseUrl,
198
+ workerLimits,
199
+ toUserMessage,
200
+ invalidateTags
201
+ } = deps;
202
+ const { edgeWorkerTtlMs, edgeRotateThresholdMs, overallTimeoutMs } = workerLimits;
203
+ return function useEdgeStream(config) {
204
+ const [isLoading, setIsLoading] = useState(false);
205
+ const [error, setError] = useState(null);
206
+ const [data, setData] = useState(void 0);
207
+ const wsRef = useRef(null);
208
+ const isExplicitDisconnectRef = useRef(false);
209
+ const [isConnected, setIsConnected] = useState(false);
210
+ const isConnectingRef = useRef(false);
211
+ const lastWarmupPayloadRef = useRef(null);
212
+ const isWarmupReadyRef = useRef(false);
213
+ const warmupWaitersRef = useRef([]);
214
+ const retryCountRef = useRef(0);
215
+ const passiveOnServerActionRef = useRef(null);
216
+ const socketOpenedAtRef = useRef(null);
217
+ const settleWarmupWaiters = useCallback((warmupError) => {
218
+ const waiters = warmupWaitersRef.current;
219
+ warmupWaitersRef.current = [];
220
+ if (warmupError) {
221
+ waiters.forEach((w) => w.reject(warmupError));
222
+ return;
223
+ }
224
+ waiters.forEach((w) => w.resolve());
225
+ }, []);
226
+ const waitForWarmupReady = useCallback(() => {
227
+ if (isWarmupReadyRef.current) return Promise.resolve();
228
+ return new Promise((resolve, reject) => {
229
+ warmupWaitersRef.current.push({ resolve, reject });
230
+ });
231
+ }, []);
232
+ const sendWarmupPayload = useCallback(() => {
233
+ if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) {
234
+ return;
235
+ }
236
+ if (!lastWarmupPayloadRef.current) return;
237
+ isWarmupReadyRef.current = false;
238
+ wsRef.current.send(
239
+ JSON.stringify({
240
+ type: "client_warmup",
241
+ data: lastWarmupPayloadRef.current
242
+ })
243
+ );
244
+ }, []);
245
+ const activeRequestRef = useRef(null);
246
+ useEffect(() => {
247
+ return () => {
248
+ isExplicitDisconnectRef.current = true;
249
+ if (wsRef.current) {
250
+ try {
251
+ wsRef.current.close();
252
+ } catch {
253
+ }
254
+ }
255
+ };
256
+ }, []);
257
+ const closeSocket = useCallback(() => {
258
+ if (!wsRef.current) return;
259
+ try {
260
+ wsRef.current.close();
261
+ } catch {
262
+ }
263
+ socketOpenedAtRef.current = null;
264
+ }, []);
265
+ const abort = useCallback(() => {
266
+ isExplicitDisconnectRef.current = true;
267
+ closeSocket();
268
+ setIsLoading(false);
269
+ if (activeRequestRef.current) {
270
+ activeRequestRef.current.reject(new Error("Request aborted"));
271
+ if (activeRequestRef.current.overallTimeout) {
272
+ clearTimeout(activeRequestRef.current.overallTimeout);
273
+ }
274
+ activeRequestRef.current = null;
275
+ }
276
+ }, [closeSocket]);
277
+ const connectWebSocket = useCallback(
278
+ () => connectEdgeSocket({
279
+ functionPath: config.functionPath,
280
+ getAccessToken,
281
+ getSupabaseUrl,
282
+ wsRef,
283
+ isExplicitDisconnectRef,
284
+ isConnectingRef,
285
+ retryCountRef,
286
+ socketOpenedAtRef,
287
+ isWarmupReadyRef,
288
+ warmupWaitersRef,
289
+ passiveOnServerActionRef,
290
+ activeRequestRef,
291
+ lastWarmupPayloadRef,
292
+ setIsConnected,
293
+ closeSocket,
294
+ sendWarmupPayload,
295
+ settleWarmupWaiters
296
+ }),
297
+ [
298
+ config.functionPath,
299
+ closeSocket,
300
+ sendWarmupPayload,
301
+ settleWarmupWaiters
302
+ ]
303
+ );
304
+ const rotateConnectionIfNeeded = useCallback(
305
+ async (getExpiresAt) => {
306
+ const fallbackExpires = socketOpenedAtRef.current ? socketOpenedAtRef.current + edgeWorkerTtlMs : null;
307
+ const expiresAt = getExpiresAt?.() ?? fallbackExpires;
308
+ if (!expiresAt) return;
309
+ if (expiresAt - Date.now() >= edgeRotateThresholdMs) return;
310
+ isExplicitDisconnectRef.current = false;
311
+ closeSocket();
312
+ isWarmupReadyRef.current = false;
313
+ await connectWebSocket();
314
+ },
315
+ [closeSocket, connectWebSocket, edgeRotateThresholdMs, edgeWorkerTtlMs]
316
+ );
317
+ const warmup = useCallback(
318
+ async (payload, options) => {
319
+ if (options?.onServerAction) {
320
+ passiveOnServerActionRef.current = options.onServerAction;
321
+ }
322
+ lastWarmupPayloadRef.current = payload;
323
+ isWarmupReadyRef.current = false;
324
+ const wasOpen = wsRef.current?.readyState === WebSocket.OPEN;
325
+ await connectWebSocket();
326
+ if (!isWarmupReadyRef.current) {
327
+ if (wasOpen) sendWarmupPayload();
328
+ await waitForWarmupReady();
329
+ }
330
+ },
331
+ [connectWebSocket, sendWarmupPayload, waitForWarmupReady]
332
+ );
333
+ const send = useCallback(
334
+ async (payload, options) => {
335
+ if (!isLoading) {
336
+ await rotateConnectionIfNeeded(options.getWorkerExpiresAt);
337
+ }
338
+ setIsLoading(true);
339
+ setError(null);
340
+ setData(void 0);
341
+ isExplicitDisconnectRef.current = false;
342
+ let resolved = false;
343
+ const ctx = {
344
+ resolve: (value) => {
345
+ resolved = true;
346
+ setData(value);
347
+ setIsLoading(false);
348
+ if (options.invalidateTags && invalidateTags) {
349
+ const shouldInvalidate = options.invalidateTags.condition ? options.invalidateTags.condition(value) : true;
350
+ if (shouldInvalidate) {
351
+ invalidateTags(options.invalidateTags.tags);
352
+ }
353
+ }
354
+ if (activeRequestRef.current?.overallTimeout) {
355
+ clearTimeout(activeRequestRef.current.overallTimeout);
356
+ }
357
+ if (activeRequestRef.current?.resolve) {
358
+ activeRequestRef.current.resolve(value);
359
+ }
360
+ activeRequestRef.current = null;
361
+ },
362
+ reject: (err) => {
363
+ resolved = true;
364
+ setError(err);
365
+ setIsLoading(false);
366
+ if (activeRequestRef.current?.overallTimeout) {
367
+ clearTimeout(activeRequestRef.current.overallTimeout);
368
+ }
369
+ if (activeRequestRef.current?.reject) {
370
+ activeRequestRef.current.reject(err);
371
+ }
372
+ activeRequestRef.current = null;
373
+ },
374
+ closeSocket,
375
+ clearOverallTimeout: () => {
376
+ if (activeRequestRef.current?.overallTimeout) {
377
+ clearTimeout(activeRequestRef.current.overallTimeout);
378
+ }
379
+ },
380
+ isResolved: () => resolved
381
+ };
382
+ return new Promise((resolvePromise, rejectPromise) => {
383
+ const overallTimeout = setTimeout(() => {
384
+ if (!resolved) {
385
+ const err = new Error("WebSocket request timeout");
386
+ setError(err);
387
+ setIsLoading(false);
388
+ rejectPromise(err);
389
+ activeRequestRef.current = null;
390
+ }
391
+ }, overallTimeoutMs);
392
+ const handler = options.onMessage || createStandardAiMessageHandler(options.defaults || {}, {
393
+ onServerAction: options.onServerAction,
394
+ toUserMessage
395
+ });
396
+ activeRequestRef.current = {
397
+ payload,
398
+ options,
399
+ ctx,
400
+ resolve: resolvePromise,
401
+ reject: rejectPromise,
402
+ overallTimeout,
403
+ handler
404
+ };
405
+ connectWebSocket().then(async () => {
406
+ if (!activeRequestRef.current || activeRequestRef.current.sent) {
407
+ return;
408
+ }
409
+ if (!lastWarmupPayloadRef.current) {
410
+ throw new Error("Warmup required");
411
+ }
412
+ if (!isWarmupReadyRef.current) {
413
+ sendWarmupPayload();
414
+ await waitForWarmupReady();
415
+ }
416
+ if (wsRef.current?.readyState === WebSocket.OPEN && activeRequestRef.current && !activeRequestRef.current.sent) {
417
+ activeRequestRef.current.sent = true;
418
+ wsRef.current.send(
419
+ JSON.stringify({ type: "client_message", data: payload })
420
+ );
421
+ }
422
+ }).catch((err) => {
423
+ clearTimeout(overallTimeout);
424
+ setError(err);
425
+ setIsLoading(false);
426
+ rejectPromise(err);
427
+ activeRequestRef.current = null;
428
+ });
429
+ });
430
+ },
431
+ [
432
+ connectWebSocket,
433
+ closeSocket,
434
+ sendWarmupPayload,
435
+ waitForWarmupReady,
436
+ rotateConnectionIfNeeded,
437
+ isLoading,
438
+ overallTimeoutMs,
439
+ toUserMessage,
440
+ invalidateTags
441
+ ]
442
+ );
443
+ return {
444
+ warmup,
445
+ send,
446
+ abort,
447
+ isLoading,
448
+ error,
449
+ data,
450
+ isConnected
451
+ };
452
+ };
453
+ }
454
+
455
+ export {
456
+ MAX_RETRIES,
457
+ INITIAL_RETRY_DELAY_MS,
458
+ CONNECTION_TIMEOUT_MS,
459
+ connectEdgeSocket,
460
+ createStandardAiMessageHandler,
461
+ createUseEdgeStream
462
+ };