@ricsam/isolate-fetch 0.1.1 → 0.1.3

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 ADDED
@@ -0,0 +1,93 @@
1
+ # @ricsam/isolate-fetch
2
+
3
+ Fetch API and HTTP server handler.
4
+
5
+ ```typescript
6
+ import { setupFetch } from "@ricsam/isolate-fetch";
7
+
8
+ const handle = await setupFetch(context, {
9
+ onFetch: async (request) => {
10
+ // Handle outbound fetch() calls from the isolate
11
+ console.log(`Fetching: ${request.url}`);
12
+ return fetch(request);
13
+ },
14
+ });
15
+ ```
16
+
17
+ **Injected Globals:**
18
+ - `fetch`, `Request`, `Response`, `Headers`
19
+ - `FormData`, `AbortController`, `AbortSignal`
20
+ - `serve` (HTTP server handler)
21
+
22
+ **Usage in Isolate:**
23
+
24
+ ```javascript
25
+ // Outbound fetch
26
+ const response = await fetch("https://api.example.com/data");
27
+ const data = await response.json();
28
+
29
+ // Request/Response
30
+ const request = new Request("https://example.com", {
31
+ method: "POST",
32
+ headers: { "Content-Type": "application/json" },
33
+ body: JSON.stringify({ name: "test" }),
34
+ });
35
+
36
+ const response = new Response(JSON.stringify({ ok: true }), {
37
+ status: 200,
38
+ headers: { "Content-Type": "application/json" },
39
+ });
40
+
41
+ // Static methods
42
+ Response.json({ message: "hello" });
43
+ Response.redirect("https://example.com", 302);
44
+
45
+ // AbortController
46
+ const controller = new AbortController();
47
+ setTimeout(() => controller.abort(), 5000);
48
+ await fetch(url, { signal: controller.signal });
49
+
50
+ // FormData
51
+ const formData = new FormData();
52
+ formData.append("name", "John");
53
+ formData.append("file", new File(["content"], "file.txt"));
54
+ ```
55
+
56
+ #### HTTP Server
57
+
58
+ Register a server handler in the isolate and dispatch requests from the host:
59
+
60
+ ```typescript
61
+ // In isolate
62
+ await context.eval(`
63
+ serve({
64
+ fetch(request, server) {
65
+ const url = new URL(request.url);
66
+
67
+ if (url.pathname === "/ws") {
68
+ if (server.upgrade(request, { data: { userId: "123" } })) {
69
+ return new Response(null, { status: 101 });
70
+ }
71
+ }
72
+
73
+ return Response.json({ path: url.pathname });
74
+ },
75
+ websocket: {
76
+ open(ws) {
77
+ console.log("Connected:", ws.data.userId);
78
+ },
79
+ message(ws, message) {
80
+ ws.send("Echo: " + message);
81
+ },
82
+ close(ws, code, reason) {
83
+ console.log("Closed:", code, reason);
84
+ }
85
+ }
86
+ });
87
+ `, { promise: true });
88
+
89
+ // From host - dispatch HTTP request
90
+ const response = await handle.dispatchRequest(
91
+ new Request("http://localhost/api/users")
92
+ );
93
+ ```