devflare 0.0.0 → 1.0.0-next.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.
Files changed (199) hide show
  1. package/LLM.md +976 -0
  2. package/README.md +737 -1
  3. package/bin/devflare.js +14 -0
  4. package/dist/account-rvrj687w.js +397 -0
  5. package/dist/ai-dx4fr9jh.js +107 -0
  6. package/dist/bridge/client.d.ts +82 -0
  7. package/dist/bridge/client.d.ts.map +1 -0
  8. package/dist/bridge/index.d.ts +7 -0
  9. package/dist/bridge/index.d.ts.map +1 -0
  10. package/dist/bridge/miniflare.d.ts +70 -0
  11. package/dist/bridge/miniflare.d.ts.map +1 -0
  12. package/dist/bridge/protocol.d.ts +146 -0
  13. package/dist/bridge/protocol.d.ts.map +1 -0
  14. package/dist/bridge/proxy.d.ts +49 -0
  15. package/dist/bridge/proxy.d.ts.map +1 -0
  16. package/dist/bridge/serialization.d.ts +83 -0
  17. package/dist/bridge/serialization.d.ts.map +1 -0
  18. package/dist/bridge/server.d.ts +8 -0
  19. package/dist/bridge/server.d.ts.map +1 -0
  20. package/dist/browser-shim/binding-worker.d.ts +7 -0
  21. package/dist/browser-shim/binding-worker.d.ts.map +1 -0
  22. package/dist/browser-shim/handler.d.ts +21 -0
  23. package/dist/browser-shim/handler.d.ts.map +1 -0
  24. package/dist/browser-shim/index.d.ts +3 -0
  25. package/dist/browser-shim/index.d.ts.map +1 -0
  26. package/dist/browser-shim/server.d.ts +25 -0
  27. package/dist/browser-shim/server.d.ts.map +1 -0
  28. package/dist/browser-shim/worker.d.ts +14 -0
  29. package/dist/browser-shim/worker.d.ts.map +1 -0
  30. package/dist/build-mnf6v8gd.js +53 -0
  31. package/dist/bundler/do-bundler.d.ts +42 -0
  32. package/dist/bundler/do-bundler.d.ts.map +1 -0
  33. package/dist/bundler/index.d.ts +2 -0
  34. package/dist/bundler/index.d.ts.map +1 -0
  35. package/dist/cli/bin.d.ts +3 -0
  36. package/dist/cli/bin.d.ts.map +1 -0
  37. package/dist/cli/colors.d.ts +11 -0
  38. package/dist/cli/colors.d.ts.map +1 -0
  39. package/dist/cli/commands/account.d.ts +4 -0
  40. package/dist/cli/commands/account.d.ts.map +1 -0
  41. package/dist/cli/commands/ai.d.ts +3 -0
  42. package/dist/cli/commands/ai.d.ts.map +1 -0
  43. package/dist/cli/commands/build.d.ts +4 -0
  44. package/dist/cli/commands/build.d.ts.map +1 -0
  45. package/dist/cli/commands/deploy.d.ts +4 -0
  46. package/dist/cli/commands/deploy.d.ts.map +1 -0
  47. package/dist/cli/commands/dev.d.ts +4 -0
  48. package/dist/cli/commands/dev.d.ts.map +1 -0
  49. package/dist/cli/commands/doctor.d.ts +4 -0
  50. package/dist/cli/commands/doctor.d.ts.map +1 -0
  51. package/dist/cli/commands/init.d.ts +4 -0
  52. package/dist/cli/commands/init.d.ts.map +1 -0
  53. package/dist/cli/commands/remote.d.ts +4 -0
  54. package/dist/cli/commands/remote.d.ts.map +1 -0
  55. package/dist/cli/commands/types.d.ts +4 -0
  56. package/dist/cli/commands/types.d.ts.map +1 -0
  57. package/dist/cli/dependencies.d.ts +90 -0
  58. package/dist/cli/dependencies.d.ts.map +1 -0
  59. package/dist/cli/index.d.ts +23 -0
  60. package/dist/cli/index.d.ts.map +1 -0
  61. package/dist/cli/wrangler-auth.d.ts +36 -0
  62. package/dist/cli/wrangler-auth.d.ts.map +1 -0
  63. package/dist/cloudflare/account.d.ts +65 -0
  64. package/dist/cloudflare/account.d.ts.map +1 -0
  65. package/dist/cloudflare/api.d.ts +51 -0
  66. package/dist/cloudflare/api.d.ts.map +1 -0
  67. package/dist/cloudflare/auth.d.ts +35 -0
  68. package/dist/cloudflare/auth.d.ts.map +1 -0
  69. package/dist/cloudflare/index.d.ts +107 -0
  70. package/dist/cloudflare/index.d.ts.map +1 -0
  71. package/dist/cloudflare/index.js +13 -0
  72. package/dist/cloudflare/preferences.d.ts +46 -0
  73. package/dist/cloudflare/preferences.d.ts.map +1 -0
  74. package/dist/cloudflare/pricing.d.ts +15 -0
  75. package/dist/cloudflare/pricing.d.ts.map +1 -0
  76. package/dist/cloudflare/remote-config.d.ts +37 -0
  77. package/dist/cloudflare/remote-config.d.ts.map +1 -0
  78. package/dist/cloudflare/types.d.ts +161 -0
  79. package/dist/cloudflare/types.d.ts.map +1 -0
  80. package/dist/cloudflare/usage.d.ts +77 -0
  81. package/dist/cloudflare/usage.d.ts.map +1 -0
  82. package/dist/config/compiler.d.ts +146 -0
  83. package/dist/config/compiler.d.ts.map +1 -0
  84. package/dist/config/define.d.ts +44 -0
  85. package/dist/config/define.d.ts.map +1 -0
  86. package/dist/config/index.d.ts +6 -0
  87. package/dist/config/index.d.ts.map +1 -0
  88. package/dist/config/loader.d.ts +52 -0
  89. package/dist/config/loader.d.ts.map +1 -0
  90. package/dist/config/ref.d.ts +160 -0
  91. package/dist/config/ref.d.ts.map +1 -0
  92. package/dist/config/schema.d.ts +3318 -0
  93. package/dist/config/schema.d.ts.map +1 -0
  94. package/dist/decorators/durable-object.d.ts +59 -0
  95. package/dist/decorators/durable-object.d.ts.map +1 -0
  96. package/dist/decorators/index.d.ts +3 -0
  97. package/dist/decorators/index.d.ts.map +1 -0
  98. package/dist/decorators/index.js +9 -0
  99. package/dist/deploy-nhceck39.js +70 -0
  100. package/dist/dev-qnxet3j9.js +2096 -0
  101. package/dist/dev-server/index.d.ts +2 -0
  102. package/dist/dev-server/index.d.ts.map +1 -0
  103. package/dist/dev-server/server.d.ts +30 -0
  104. package/dist/dev-server/server.d.ts.map +1 -0
  105. package/dist/doctor-e8fy6fj5.js +186 -0
  106. package/dist/durable-object-t4kbb0yt.js +13 -0
  107. package/dist/env.d.ts +48 -0
  108. package/dist/env.d.ts.map +1 -0
  109. package/dist/index-07q6yxyc.js +168 -0
  110. package/dist/index-1xpj0m4r.js +57 -0
  111. package/dist/index-37x76zdn.js +4 -0
  112. package/dist/index-3t6rypgc.js +13 -0
  113. package/dist/index-67qcae0f.js +183 -0
  114. package/dist/index-a855bdsx.js +18 -0
  115. package/dist/index-d8bdkx2h.js +109 -0
  116. package/dist/index-ep3445yc.js +2225 -0
  117. package/dist/index-gz1gndna.js +307 -0
  118. package/dist/index-hcex3rgh.js +266 -0
  119. package/dist/index-m2q41jwa.js +462 -0
  120. package/dist/index-n7rs26ft.js +77 -0
  121. package/dist/index-pf5s73n9.js +1413 -0
  122. package/dist/index-rbht7m9r.js +36 -0
  123. package/dist/index-tfyxa77h.js +850 -0
  124. package/dist/index-tk6ej9dj.js +94 -0
  125. package/dist/index-z14anrqp.js +226 -0
  126. package/dist/index.d.ts +13 -0
  127. package/dist/index.d.ts.map +1 -0
  128. package/dist/index.js +298 -0
  129. package/dist/init-f9mgmew3.js +186 -0
  130. package/dist/remote-q59qk463.js +97 -0
  131. package/dist/runtime/context.d.ts +46 -0
  132. package/dist/runtime/context.d.ts.map +1 -0
  133. package/dist/runtime/exports.d.ts +118 -0
  134. package/dist/runtime/exports.d.ts.map +1 -0
  135. package/dist/runtime/index.d.ts +4 -0
  136. package/dist/runtime/index.d.ts.map +1 -0
  137. package/dist/runtime/index.js +111 -0
  138. package/dist/runtime/middleware.d.ts +82 -0
  139. package/dist/runtime/middleware.d.ts.map +1 -0
  140. package/dist/runtime/validation.d.ts +37 -0
  141. package/dist/runtime/validation.d.ts.map +1 -0
  142. package/dist/sveltekit/index.d.ts +2 -0
  143. package/dist/sveltekit/index.d.ts.map +1 -0
  144. package/dist/sveltekit/index.js +182 -0
  145. package/dist/sveltekit/platform.d.ts +141 -0
  146. package/dist/sveltekit/platform.d.ts.map +1 -0
  147. package/dist/test/bridge-context.d.ts +73 -0
  148. package/dist/test/bridge-context.d.ts.map +1 -0
  149. package/dist/test/cf.d.ts +130 -0
  150. package/dist/test/cf.d.ts.map +1 -0
  151. package/dist/test/email.d.ts +75 -0
  152. package/dist/test/email.d.ts.map +1 -0
  153. package/dist/test/index.d.ts +22 -0
  154. package/dist/test/index.d.ts.map +1 -0
  155. package/dist/test/index.js +71 -0
  156. package/dist/test/multi-worker-context.d.ts +114 -0
  157. package/dist/test/multi-worker-context.d.ts.map +1 -0
  158. package/dist/test/queue.d.ts +74 -0
  159. package/dist/test/queue.d.ts.map +1 -0
  160. package/dist/test/remote-ai.d.ts +6 -0
  161. package/dist/test/remote-ai.d.ts.map +1 -0
  162. package/dist/test/remote-vectorize.d.ts +6 -0
  163. package/dist/test/remote-vectorize.d.ts.map +1 -0
  164. package/dist/test/resolve-service-bindings.d.ts +68 -0
  165. package/dist/test/resolve-service-bindings.d.ts.map +1 -0
  166. package/dist/test/scheduled.d.ts +58 -0
  167. package/dist/test/scheduled.d.ts.map +1 -0
  168. package/dist/test/should-skip.d.ts +50 -0
  169. package/dist/test/should-skip.d.ts.map +1 -0
  170. package/dist/test/simple-context.d.ts +43 -0
  171. package/dist/test/simple-context.d.ts.map +1 -0
  172. package/dist/test/tail.d.ts +86 -0
  173. package/dist/test/tail.d.ts.map +1 -0
  174. package/dist/test/utilities.d.ts +99 -0
  175. package/dist/test/utilities.d.ts.map +1 -0
  176. package/dist/test/worker.d.ts +76 -0
  177. package/dist/test/worker.d.ts.map +1 -0
  178. package/dist/transform/durable-object.d.ts +46 -0
  179. package/dist/transform/durable-object.d.ts.map +1 -0
  180. package/dist/transform/index.d.ts +3 -0
  181. package/dist/transform/index.d.ts.map +1 -0
  182. package/dist/transform/worker-entrypoint.d.ts +66 -0
  183. package/dist/transform/worker-entrypoint.d.ts.map +1 -0
  184. package/dist/types-5nyrz1sz.js +454 -0
  185. package/dist/utils/entrypoint-discovery.d.ts +29 -0
  186. package/dist/utils/entrypoint-discovery.d.ts.map +1 -0
  187. package/dist/utils/glob.d.ts +33 -0
  188. package/dist/utils/glob.d.ts.map +1 -0
  189. package/dist/utils/resolve-package.d.ts +10 -0
  190. package/dist/utils/resolve-package.d.ts.map +1 -0
  191. package/dist/vite/index.d.ts +3 -0
  192. package/dist/vite/index.d.ts.map +1 -0
  193. package/dist/vite/index.js +339 -0
  194. package/dist/vite/plugin.d.ts +138 -0
  195. package/dist/vite/plugin.d.ts.map +1 -0
  196. package/dist/worker-entrypoint-m9th0rg0.js +13 -0
  197. package/dist/workerName.d.ts +17 -0
  198. package/dist/workerName.d.ts.map +1 -0
  199. package/package.json +112 -1
@@ -0,0 +1,1413 @@
1
+ import {
2
+ normalizeDOBinding
3
+ } from "./index-hcex3rgh.js";
4
+ import {
5
+ __require
6
+ } from "./index-37x76zdn.js";
7
+
8
+ // src/bridge/protocol.ts
9
+ var BinaryKind = {
10
+ StreamChunk: 1,
11
+ WsData: 2
12
+ };
13
+ var BinaryFlags = {
14
+ FIN: 1,
15
+ TEXT: 2
16
+ };
17
+ var BINARY_HEADER_SIZE = 10;
18
+ function encodeBinaryFrame(kind, id, seq, flags, payload) {
19
+ const frame = new Uint8Array(BINARY_HEADER_SIZE + payload.byteLength);
20
+ const view = new DataView(frame.buffer);
21
+ view.setUint8(0, kind);
22
+ view.setUint32(1, id, true);
23
+ view.setUint32(5, seq, true);
24
+ view.setUint8(9, flags);
25
+ frame.set(payload, BINARY_HEADER_SIZE);
26
+ return frame;
27
+ }
28
+ function decodeBinaryFrame(frame) {
29
+ if (frame.byteLength < BINARY_HEADER_SIZE) {
30
+ throw new Error(`Invalid binary frame: too short (${frame.byteLength} bytes)`);
31
+ }
32
+ const view = new DataView(frame.buffer, frame.byteOffset, frame.byteLength);
33
+ return {
34
+ kind: view.getUint8(0),
35
+ id: view.getUint32(1, true),
36
+ seq: view.getUint32(5, true),
37
+ flags: view.getUint8(9),
38
+ payload: frame.subarray(BINARY_HEADER_SIZE)
39
+ };
40
+ }
41
+ function parseJsonMsg(data) {
42
+ const msg = JSON.parse(data);
43
+ if (typeof msg !== "object" || msg === null || !("t" in msg)) {
44
+ throw new Error("Invalid message: missing type field");
45
+ }
46
+ return msg;
47
+ }
48
+ function stringifyJsonMsg(msg) {
49
+ return JSON.stringify(msg);
50
+ }
51
+ var rpcIdCounter = 0;
52
+ var streamIdCounter = 0;
53
+ var wsIdCounter = 0;
54
+ function nextRpcId() {
55
+ return `rpc_${++rpcIdCounter}`;
56
+ }
57
+ function nextStreamId() {
58
+ return ++streamIdCounter;
59
+ }
60
+ function nextWsId() {
61
+ return ++wsIdCounter;
62
+ }
63
+ var DEFAULT_CHUNK_SIZE = 256 * 1024;
64
+ var HTTP_TRANSFER_THRESHOLD = 512 * 1024;
65
+ var DEFAULT_BRIDGE_PORT = 8686;
66
+
67
+ // src/bridge/serialization.ts
68
+ async function serializeRequest(request, options) {
69
+ const streams = [];
70
+ const threshold = options?.httpThreshold ?? 10 * 1024 * 1024;
71
+ const headers = [];
72
+ request.headers.forEach((value, key) => {
73
+ headers.push([key, value]);
74
+ });
75
+ let body = null;
76
+ if (request.body) {
77
+ const bytes = await request.arrayBuffer();
78
+ if (bytes.byteLength > threshold) {
79
+ body = { type: "http", transferId: crypto.randomUUID() };
80
+ } else if (bytes.byteLength > 0) {
81
+ body = { type: "bytes", data: base64Encode(new Uint8Array(bytes)) };
82
+ }
83
+ }
84
+ return {
85
+ serialized: {
86
+ url: request.url,
87
+ method: request.method,
88
+ headers,
89
+ body,
90
+ redirect: request.redirect
91
+ },
92
+ streams
93
+ };
94
+ }
95
+ function deserializeRequest(serialized, getStream) {
96
+ let body = null;
97
+ if (serialized.body) {
98
+ switch (serialized.body.type) {
99
+ case "bytes":
100
+ body = base64Decode(serialized.body.data);
101
+ break;
102
+ case "stream":
103
+ if (getStream) {
104
+ body = getStream(serialized.body.sid) ?? null;
105
+ }
106
+ break;
107
+ case "http":
108
+ throw new Error("HTTP transfer body must be handled externally");
109
+ }
110
+ }
111
+ return new Request(serialized.url, {
112
+ method: serialized.method,
113
+ headers: serialized.headers,
114
+ body,
115
+ redirect: serialized.redirect
116
+ });
117
+ }
118
+ async function serializeResponse(response, options) {
119
+ const streams = [];
120
+ const threshold = options?.httpThreshold ?? 10 * 1024 * 1024;
121
+ const headers = [];
122
+ response.headers.forEach((value, key) => {
123
+ headers.push([key, value]);
124
+ });
125
+ let body = null;
126
+ if (response.body) {
127
+ const bytes = await response.arrayBuffer();
128
+ if (bytes.byteLength > threshold) {
129
+ body = { type: "http", transferId: crypto.randomUUID() };
130
+ } else if (bytes.byteLength > 0) {
131
+ body = { type: "bytes", data: base64Encode(new Uint8Array(bytes)) };
132
+ }
133
+ }
134
+ return {
135
+ serialized: {
136
+ status: response.status,
137
+ statusText: response.statusText,
138
+ headers,
139
+ body
140
+ },
141
+ streams
142
+ };
143
+ }
144
+ function deserializeResponse(serialized, getStream) {
145
+ let body = null;
146
+ if (serialized.body) {
147
+ switch (serialized.body.type) {
148
+ case "bytes":
149
+ body = base64Decode(serialized.body.data);
150
+ break;
151
+ case "stream":
152
+ if (getStream) {
153
+ body = getStream(serialized.body.sid) ?? null;
154
+ }
155
+ break;
156
+ case "http":
157
+ throw new Error("HTTP transfer body must be handled externally");
158
+ }
159
+ }
160
+ return new Response(body, {
161
+ status: serialized.status,
162
+ statusText: serialized.statusText,
163
+ headers: serialized.headers
164
+ });
165
+ }
166
+ async function serializeValue(value) {
167
+ const streams = [];
168
+ const result = await serializeValueInternal(value, streams);
169
+ return { value: result, streams };
170
+ }
171
+ async function serializeValueInternal(value, streams) {
172
+ if (value === null || value === undefined) {
173
+ return value;
174
+ }
175
+ if (value instanceof Request) {
176
+ const { serialized, streams: reqStreams } = await serializeRequest(value);
177
+ streams.push(...reqStreams);
178
+ return { __type: "Request", ...serialized };
179
+ }
180
+ if (value instanceof Response) {
181
+ const { serialized, streams: resStreams } = await serializeResponse(value);
182
+ streams.push(...resStreams);
183
+ return { __type: "Response", ...serialized };
184
+ }
185
+ if (value instanceof ReadableStream) {
186
+ const sid = nextStreamId();
187
+ streams.push({ sid, stream: value });
188
+ return { __type: "ReadableStream", sid };
189
+ }
190
+ if (value instanceof Uint8Array) {
191
+ return { __type: "Uint8Array", data: base64Encode(value) };
192
+ }
193
+ if (value instanceof ArrayBuffer) {
194
+ return { __type: "ArrayBuffer", data: base64Encode(new Uint8Array(value)) };
195
+ }
196
+ if (Array.isArray(value)) {
197
+ return Promise.all(value.map((v) => serializeValueInternal(v, streams)));
198
+ }
199
+ if (typeof value === "object") {
200
+ const result = {};
201
+ for (const [k, v] of Object.entries(value)) {
202
+ result[k] = await serializeValueInternal(v, streams);
203
+ }
204
+ return result;
205
+ }
206
+ return value;
207
+ }
208
+ function deserializeValue(value, getStream) {
209
+ if (value === null || value === undefined) {
210
+ return value;
211
+ }
212
+ if (typeof value === "object" && value !== null) {
213
+ const obj = value;
214
+ if (obj.__type === "Request") {
215
+ return deserializeRequest(obj, getStream);
216
+ }
217
+ if (obj.__type === "Response") {
218
+ return deserializeResponse(obj, getStream);
219
+ }
220
+ if (obj.__type === "ReadableStream") {
221
+ const sid = obj.sid;
222
+ return getStream?.(sid) ?? null;
223
+ }
224
+ if (obj.__type === "Uint8Array") {
225
+ return base64Decode(obj.data);
226
+ }
227
+ if (obj.__type === "ArrayBuffer") {
228
+ return base64Decode(obj.data).buffer;
229
+ }
230
+ if (obj.__type === "R2Object") {
231
+ return deserializeR2Object(obj);
232
+ }
233
+ if (obj.__type === "R2ObjectBody") {
234
+ return deserializeR2ObjectBody(obj);
235
+ }
236
+ if (Array.isArray(value)) {
237
+ return value.map((v) => deserializeValue(v, getStream));
238
+ }
239
+ const result = {};
240
+ for (const [k, v] of Object.entries(obj)) {
241
+ result[k] = deserializeValue(v, getStream);
242
+ }
243
+ return result;
244
+ }
245
+ return value;
246
+ }
247
+ function deserializeR2Object(obj) {
248
+ const serialized = obj;
249
+ return {
250
+ key: serialized.key,
251
+ version: serialized.version,
252
+ size: serialized.size,
253
+ etag: serialized.etag,
254
+ httpEtag: serialized.httpEtag,
255
+ checksums: serialized.checksums,
256
+ uploaded: serialized.uploaded ? new Date(serialized.uploaded) : new Date,
257
+ httpMetadata: serialized.httpMetadata,
258
+ customMetadata: serialized.customMetadata,
259
+ range: serialized.range,
260
+ storageClass: serialized.storageClass,
261
+ writeHttpMetadata(headers) {
262
+ if (serialized.httpMetadata?.contentType) {
263
+ headers.set("Content-Type", serialized.httpMetadata.contentType);
264
+ }
265
+ if (serialized.httpMetadata?.contentLanguage) {
266
+ headers.set("Content-Language", serialized.httpMetadata.contentLanguage);
267
+ }
268
+ if (serialized.httpMetadata?.contentDisposition) {
269
+ headers.set("Content-Disposition", serialized.httpMetadata.contentDisposition);
270
+ }
271
+ if (serialized.httpMetadata?.contentEncoding) {
272
+ headers.set("Content-Encoding", serialized.httpMetadata.contentEncoding);
273
+ }
274
+ if (serialized.httpMetadata?.cacheControl) {
275
+ headers.set("Cache-Control", serialized.httpMetadata.cacheControl);
276
+ }
277
+ if (serialized.httpMetadata?.cacheExpiry) {
278
+ headers.set("Expires", new Date(serialized.httpMetadata.cacheExpiry).toUTCString());
279
+ }
280
+ }
281
+ };
282
+ }
283
+ function deserializeR2ObjectBody(obj) {
284
+ const serialized = obj;
285
+ const bodyBytes = serialized.bodyData ? base64Decode(serialized.bodyData) : new Uint8Array(0);
286
+ const r2ObjectBody = {
287
+ key: serialized.key,
288
+ version: serialized.version,
289
+ size: serialized.size,
290
+ etag: serialized.etag,
291
+ httpEtag: serialized.httpEtag,
292
+ checksums: serialized.checksums,
293
+ uploaded: serialized.uploaded ? new Date(serialized.uploaded) : new Date,
294
+ httpMetadata: serialized.httpMetadata,
295
+ customMetadata: serialized.customMetadata,
296
+ range: serialized.range,
297
+ storageClass: serialized.storageClass,
298
+ body: new ReadableStream({
299
+ start(controller) {
300
+ controller.enqueue(bodyBytes);
301
+ controller.close();
302
+ }
303
+ }),
304
+ bodyUsed: false,
305
+ async arrayBuffer() {
306
+ const copy = new Uint8Array(bodyBytes.byteLength);
307
+ copy.set(bodyBytes);
308
+ return copy.buffer;
309
+ },
310
+ async text() {
311
+ return new TextDecoder().decode(bodyBytes);
312
+ },
313
+ async json() {
314
+ const text = new TextDecoder().decode(bodyBytes);
315
+ return JSON.parse(text);
316
+ },
317
+ async blob() {
318
+ const contentType = serialized.httpMetadata?.contentType || "application/octet-stream";
319
+ const buffer = bodyBytes.buffer.slice(bodyBytes.byteOffset, bodyBytes.byteOffset + bodyBytes.byteLength);
320
+ return new Blob([buffer], { type: contentType });
321
+ },
322
+ writeHttpMetadata(headers) {
323
+ if (serialized.httpMetadata?.contentType) {
324
+ headers.set("Content-Type", serialized.httpMetadata.contentType);
325
+ }
326
+ if (serialized.httpMetadata?.contentLanguage) {
327
+ headers.set("Content-Language", serialized.httpMetadata.contentLanguage);
328
+ }
329
+ if (serialized.httpMetadata?.contentDisposition) {
330
+ headers.set("Content-Disposition", serialized.httpMetadata.contentDisposition);
331
+ }
332
+ if (serialized.httpMetadata?.contentEncoding) {
333
+ headers.set("Content-Encoding", serialized.httpMetadata.contentEncoding);
334
+ }
335
+ if (serialized.httpMetadata?.cacheControl) {
336
+ headers.set("Cache-Control", serialized.httpMetadata.cacheControl);
337
+ }
338
+ if (serialized.httpMetadata?.cacheExpiry) {
339
+ headers.set("Expires", new Date(serialized.httpMetadata.cacheExpiry).toUTCString());
340
+ }
341
+ }
342
+ };
343
+ return r2ObjectBody;
344
+ }
345
+ function base64Encode(bytes) {
346
+ if (typeof Buffer !== "undefined") {
347
+ return Buffer.from(bytes).toString("base64");
348
+ }
349
+ let binary = "";
350
+ for (let i = 0;i < bytes.byteLength; i++) {
351
+ binary += String.fromCharCode(bytes[i]);
352
+ }
353
+ return btoa(binary);
354
+ }
355
+ function base64Decode(str) {
356
+ if (typeof Buffer !== "undefined") {
357
+ return new Uint8Array(Buffer.from(str, "base64"));
358
+ }
359
+ const binary = atob(str);
360
+ const bytes = new Uint8Array(binary.length);
361
+ for (let i = 0;i < binary.length; i++) {
362
+ bytes[i] = binary.charCodeAt(i);
363
+ }
364
+ return bytes;
365
+ }
366
+
367
+ // src/bridge/client.ts
368
+ class BridgeClient {
369
+ ws = null;
370
+ url;
371
+ autoReconnect;
372
+ reconnectDelay;
373
+ connectTimeout;
374
+ pendingCalls = new Map;
375
+ activeStreams = new Map;
376
+ wsProxies = new Map;
377
+ outgoingStreams = new Map;
378
+ connectPromise = null;
379
+ isConnected = false;
380
+ constructor(options = {}) {
381
+ this.url = options.url ?? `ws://localhost:${DEFAULT_BRIDGE_PORT}`;
382
+ this.autoReconnect = options.autoReconnect ?? true;
383
+ this.reconnectDelay = options.reconnectDelay ?? 1000;
384
+ this.connectTimeout = options.connectTimeout ?? 5000;
385
+ }
386
+ getUrl() {
387
+ return this.url;
388
+ }
389
+ getHttpUrl() {
390
+ return this.url.replace(/^ws:\/\//, "http://").replace(/^wss:\/\//, "https://");
391
+ }
392
+ async connect() {
393
+ if (this.isConnected)
394
+ return;
395
+ if (this.connectPromise)
396
+ return this.connectPromise;
397
+ this.connectPromise = new Promise((resolve, reject) => {
398
+ const timeout = setTimeout(() => {
399
+ reject(new Error(`Connection timeout: ${this.url}`));
400
+ this.ws?.close();
401
+ }, this.connectTimeout);
402
+ try {
403
+ this.ws = new WebSocket(this.url);
404
+ this.ws.binaryType = "arraybuffer";
405
+ this.ws.onopen = () => {
406
+ clearTimeout(timeout);
407
+ this.isConnected = true;
408
+ this.connectPromise = null;
409
+ resolve();
410
+ };
411
+ this.ws.onerror = () => {
412
+ clearTimeout(timeout);
413
+ this.connectPromise = null;
414
+ reject(new Error("WebSocket connection failed"));
415
+ };
416
+ this.ws.onclose = () => {
417
+ this.handleDisconnect();
418
+ };
419
+ this.ws.onmessage = (event) => {
420
+ this.handleMessage(event.data);
421
+ };
422
+ } catch (error) {
423
+ clearTimeout(timeout);
424
+ this.connectPromise = null;
425
+ reject(error);
426
+ }
427
+ });
428
+ return this.connectPromise;
429
+ }
430
+ disconnect() {
431
+ this.autoReconnect = false;
432
+ this.ws?.close();
433
+ this.ws = null;
434
+ this.isConnected = false;
435
+ for (const [id, pending] of this.pendingCalls) {
436
+ clearTimeout(pending.timeout);
437
+ pending.reject(new Error("Bridge disconnected"));
438
+ }
439
+ this.pendingCalls.clear();
440
+ }
441
+ get connected() {
442
+ return this.isConnected;
443
+ }
444
+ handleDisconnect() {
445
+ this.isConnected = false;
446
+ this.ws = null;
447
+ for (const [_id, pending] of this.pendingCalls) {
448
+ clearTimeout(pending.timeout);
449
+ pending.reject(new Error("Bridge disconnected"));
450
+ }
451
+ this.pendingCalls.clear();
452
+ for (const [_sid, stream] of this.activeStreams) {
453
+ stream.controller.error(new Error("Bridge disconnected"));
454
+ }
455
+ this.activeStreams.clear();
456
+ if (this.autoReconnect) {
457
+ setTimeout(() => {
458
+ this.connect().catch(() => {});
459
+ }, this.reconnectDelay);
460
+ }
461
+ }
462
+ async call(method, params, timeoutMs = 30000) {
463
+ await this.ensureConnected();
464
+ const id = nextRpcId();
465
+ const { value: serializedParams, streams } = await serializeValue(params);
466
+ for (const streamRef of streams) {
467
+ this.outgoingStreams.set(streamRef.sid, streamRef);
468
+ }
469
+ return new Promise((resolve, reject) => {
470
+ const timeout = setTimeout(() => {
471
+ this.pendingCalls.delete(id);
472
+ reject(new Error(`RPC timeout: ${method}`));
473
+ }, timeoutMs);
474
+ this.pendingCalls.set(id, { resolve, reject, timeout });
475
+ const msg = {
476
+ t: "rpc.call",
477
+ id,
478
+ method,
479
+ params: serializedParams
480
+ };
481
+ this.send(msg);
482
+ });
483
+ }
484
+ async createWsProxy(binding, id, url, headers) {
485
+ await this.ensureConnected();
486
+ const wid = nextWsId();
487
+ const proxy = {
488
+ clientWs: null,
489
+ onMessage: () => {},
490
+ onClose: () => {}
491
+ };
492
+ this.wsProxies.set(wid, proxy);
493
+ const msg = {
494
+ t: "ws.open",
495
+ wid,
496
+ target: { binding, id, url, headers }
497
+ };
498
+ this.send(msg);
499
+ return {
500
+ wid,
501
+ send: (data) => {
502
+ const payload = typeof data === "string" ? new TextEncoder().encode(data) : data;
503
+ const flags = typeof data === "string" ? BinaryFlags.TEXT : 0;
504
+ const frame = encodeBinaryFrame(BinaryKind.WsData, wid, 0, flags, payload);
505
+ this.ws?.send(frame);
506
+ },
507
+ close: (code, reason) => {
508
+ const closeMsg = { t: "ws.close", wid, code, reason };
509
+ this.send(closeMsg);
510
+ this.wsProxies.delete(wid);
511
+ },
512
+ onMessage: (handler) => {
513
+ proxy.onMessage = handler;
514
+ },
515
+ onClose: (handler) => {
516
+ proxy.onClose = handler;
517
+ }
518
+ };
519
+ }
520
+ createReadableStream(sid) {
521
+ return new ReadableStream({
522
+ start: (controller) => {
523
+ this.activeStreams.set(sid, {
524
+ controller,
525
+ buffer: [],
526
+ creditRemaining: 0
527
+ });
528
+ },
529
+ pull: async (controller) => {
530
+ const stream = this.activeStreams.get(sid);
531
+ if (!stream)
532
+ return;
533
+ const pullMsg = {
534
+ t: "stream.pull",
535
+ sid,
536
+ creditBytes: DEFAULT_CHUNK_SIZE * 4
537
+ };
538
+ this.send(pullMsg);
539
+ await new Promise((resolve) => {
540
+ const checkBuffer = () => {
541
+ const s = this.activeStreams.get(sid);
542
+ if (!s)
543
+ return resolve();
544
+ if (s.buffer.length > 0) {
545
+ const chunk = s.buffer.shift();
546
+ controller.enqueue(chunk);
547
+ resolve();
548
+ } else {
549
+ setTimeout(checkBuffer, 10);
550
+ }
551
+ };
552
+ checkBuffer();
553
+ });
554
+ },
555
+ cancel: () => {
556
+ this.activeStreams.delete(sid);
557
+ }
558
+ });
559
+ }
560
+ handleMessage(data) {
561
+ if (typeof data === "string") {
562
+ this.handleJsonMessage(data);
563
+ } else {
564
+ this.handleBinaryMessage(new Uint8Array(data));
565
+ }
566
+ }
567
+ handleJsonMessage(data) {
568
+ try {
569
+ const msg = parseJsonMsg(data);
570
+ switch (msg.t) {
571
+ case "rpc.ok":
572
+ this.handleRpcOk(msg);
573
+ break;
574
+ case "rpc.err":
575
+ this.handleRpcErr(msg);
576
+ break;
577
+ case "event":
578
+ this.handleEvent(msg);
579
+ break;
580
+ case "stream.pull":
581
+ this.handleStreamPull(msg);
582
+ break;
583
+ case "stream.end":
584
+ this.handleStreamEnd(msg);
585
+ break;
586
+ case "stream.abort":
587
+ this.handleStreamAbort(msg);
588
+ break;
589
+ case "ws.opened":
590
+ break;
591
+ case "ws.close":
592
+ this.handleWsClose(msg);
593
+ break;
594
+ }
595
+ } catch (error) {}
596
+ }
597
+ handleBinaryMessage(frame) {
598
+ try {
599
+ const decoded = decodeBinaryFrame(frame);
600
+ switch (decoded.kind) {
601
+ case BinaryKind.StreamChunk:
602
+ this.handleStreamChunk(decoded);
603
+ break;
604
+ case BinaryKind.WsData:
605
+ this.handleWsData(decoded);
606
+ break;
607
+ }
608
+ } catch {}
609
+ }
610
+ handleRpcOk(msg) {
611
+ const pending = this.pendingCalls.get(msg.id);
612
+ if (!pending)
613
+ return;
614
+ clearTimeout(pending.timeout);
615
+ this.pendingCalls.delete(msg.id);
616
+ const result = deserializeValue(msg.result, (sid) => this.createReadableStream(sid));
617
+ pending.resolve(result);
618
+ }
619
+ handleRpcErr(msg) {
620
+ const pending = this.pendingCalls.get(msg.id);
621
+ if (!pending)
622
+ return;
623
+ clearTimeout(pending.timeout);
624
+ this.pendingCalls.delete(msg.id);
625
+ const error = new Error(msg.error.message);
626
+ error.code = msg.error.code;
627
+ error.details = msg.error.details;
628
+ pending.reject(error);
629
+ }
630
+ handleEvent(_msg) {}
631
+ handleStreamPull(msg) {
632
+ const streamRef = this.outgoingStreams.get(msg.sid);
633
+ if (!streamRef)
634
+ return;
635
+ this.pumpStream(streamRef, msg.creditBytes);
636
+ }
637
+ async pumpStream(streamRef, creditBytes) {
638
+ const reader = streamRef.stream.getReader();
639
+ let sent = 0;
640
+ let seq = 0;
641
+ try {
642
+ while (sent < creditBytes) {
643
+ const { done, value } = await reader.read();
644
+ if (done) {
645
+ this.send({ t: "stream.end", sid: streamRef.sid });
646
+ this.outgoingStreams.delete(streamRef.sid);
647
+ break;
648
+ }
649
+ if (value) {
650
+ const frame = encodeBinaryFrame(BinaryKind.StreamChunk, streamRef.sid, seq++, 0, value);
651
+ this.ws?.send(frame);
652
+ sent += value.byteLength;
653
+ }
654
+ }
655
+ } catch (error) {
656
+ this.send({
657
+ t: "stream.abort",
658
+ sid: streamRef.sid,
659
+ error: String(error)
660
+ });
661
+ this.outgoingStreams.delete(streamRef.sid);
662
+ } finally {
663
+ reader.releaseLock();
664
+ }
665
+ }
666
+ handleStreamChunk(decoded) {
667
+ const stream = this.activeStreams.get(decoded.id);
668
+ if (!stream)
669
+ return;
670
+ stream.buffer.push(decoded.payload);
671
+ }
672
+ handleStreamEnd(msg) {
673
+ const stream = this.activeStreams.get(msg.sid);
674
+ if (!stream)
675
+ return;
676
+ for (const chunk of stream.buffer) {
677
+ stream.controller.enqueue(chunk);
678
+ }
679
+ stream.controller.close();
680
+ this.activeStreams.delete(msg.sid);
681
+ }
682
+ handleStreamAbort(msg) {
683
+ const stream = this.activeStreams.get(msg.sid);
684
+ if (!stream)
685
+ return;
686
+ stream.controller.error(new Error(msg.error ?? "Stream aborted"));
687
+ this.activeStreams.delete(msg.sid);
688
+ }
689
+ handleWsData(decoded) {
690
+ const proxy = this.wsProxies.get(decoded.id);
691
+ if (!proxy)
692
+ return;
693
+ const isText = (decoded.flags & BinaryFlags.TEXT) !== 0;
694
+ const data = isText ? new TextDecoder().decode(decoded.payload) : decoded.payload;
695
+ proxy.onMessage(data);
696
+ }
697
+ handleWsClose(msg) {
698
+ const proxy = this.wsProxies.get(msg.wid);
699
+ if (!proxy)
700
+ return;
701
+ proxy.onClose(msg.code, msg.reason);
702
+ this.wsProxies.delete(msg.wid);
703
+ }
704
+ async ensureConnected() {
705
+ if (!this.isConnected) {
706
+ await this.connect();
707
+ }
708
+ }
709
+ send(msg) {
710
+ if (!this.ws || !this.isConnected) {
711
+ throw new Error("Not connected to bridge");
712
+ }
713
+ this.ws.send(stringifyJsonMsg(msg));
714
+ }
715
+ }
716
+ var defaultClient = null;
717
+ function getClient(options) {
718
+ if (!defaultClient) {
719
+ defaultClient = new BridgeClient(options);
720
+ }
721
+ return defaultClient;
722
+ }
723
+
724
+ // src/bridge/proxy.ts
725
+ function createKVProxy(client, bindingName) {
726
+ return {
727
+ async get(key, options) {
728
+ return client.call(`${bindingName}.get`, [key, options]);
729
+ },
730
+ async put(key, value, options) {
731
+ await client.call(`${bindingName}.put`, [key, value, options]);
732
+ },
733
+ async delete(key) {
734
+ await client.call(`${bindingName}.delete`, [key]);
735
+ },
736
+ async list(options) {
737
+ return client.call(`${bindingName}.list`, [options]);
738
+ },
739
+ async getWithMetadata(key, options) {
740
+ return client.call(`${bindingName}.getWithMetadata`, [key, options]);
741
+ }
742
+ };
743
+ }
744
+ function createR2Proxy(client, bindingName) {
745
+ return {
746
+ async head(key) {
747
+ return client.call(`${bindingName}.head`, [key]);
748
+ },
749
+ async get(key, options) {
750
+ return client.call(`${bindingName}.r2.get`, [key, options]);
751
+ },
752
+ async put(key, value, options) {
753
+ const size = getValueSize(value);
754
+ if (size > HTTP_TRANSFER_THRESHOLD) {
755
+ const transferId = `${bindingName}:${key}`;
756
+ const httpUrl = client.getHttpUrl();
757
+ const transferUrl = httpUrl.replace(/\/$/, "") + `/_devflare/transfer/${encodeURIComponent(transferId)}`;
758
+ const response = await fetch(transferUrl, {
759
+ method: "PUT",
760
+ body: value,
761
+ headers: {
762
+ ...options?.httpMetadata?.contentType ? { "Content-Type": options.httpMetadata.contentType } : {}
763
+ }
764
+ });
765
+ if (!response.ok) {
766
+ const error = await response.text();
767
+ throw new Error(`HTTP transfer failed: ${error}`);
768
+ }
769
+ return response.json();
770
+ }
771
+ return client.call(`${bindingName}.r2.put`, [key, value, options]);
772
+ },
773
+ async delete(keys) {
774
+ await client.call(`${bindingName}.r2.delete`, [keys]);
775
+ },
776
+ async list(options) {
777
+ return client.call(`${bindingName}.r2.list`, [options]);
778
+ },
779
+ async createMultipartUpload(key, options) {
780
+ return client.call(`${bindingName}.createMultipartUpload`, [key, options]);
781
+ },
782
+ async resumeMultipartUpload(key, uploadId) {
783
+ return client.call(`${bindingName}.resumeMultipartUpload`, [key, uploadId]);
784
+ }
785
+ };
786
+ }
787
+ function getValueSize(value) {
788
+ if (value instanceof Blob)
789
+ return value.size;
790
+ if (value instanceof ArrayBuffer)
791
+ return value.byteLength;
792
+ if (value instanceof Uint8Array)
793
+ return value.byteLength;
794
+ if (typeof value === "string")
795
+ return value.length;
796
+ if (value instanceof ReadableStream)
797
+ return Infinity;
798
+ return 0;
799
+ }
800
+ function createD1Proxy(client, bindingName) {
801
+ return {
802
+ prepare(sql) {
803
+ return createD1StatementProxy(client, bindingName, sql, []);
804
+ },
805
+ async batch(statements) {
806
+ const serialized = statements.map((stmt) => {
807
+ const s = stmt;
808
+ return { sql: s._sql, bindings: s._bindings };
809
+ });
810
+ return client.call(`${bindingName}.batch`, [serialized]);
811
+ },
812
+ async exec(sql) {
813
+ return client.call(`${bindingName}.exec`, [sql]);
814
+ },
815
+ async dump() {
816
+ return client.call(`${bindingName}.dump`, []);
817
+ }
818
+ };
819
+ }
820
+ function createD1StatementProxy(client, bindingName, sql, bindings) {
821
+ const stmt = {
822
+ _sql: sql,
823
+ _bindings: bindings,
824
+ bind(...values) {
825
+ return createD1StatementProxy(client, bindingName, sql, values);
826
+ },
827
+ async first(column) {
828
+ return client.call(`${bindingName}.stmt.first`, [sql, ...bindings, column]);
829
+ },
830
+ async all() {
831
+ return client.call(`${bindingName}.stmt.all`, [sql, ...bindings]);
832
+ },
833
+ async run() {
834
+ return client.call(`${bindingName}.stmt.run`, [sql, ...bindings]);
835
+ },
836
+ async raw(options) {
837
+ return client.call(`${bindingName}.stmt.raw`, [sql, ...bindings, options]);
838
+ }
839
+ };
840
+ return stmt;
841
+ }
842
+ function createDOProxy(client, bindingName, proxyOptions = {}) {
843
+ return {
844
+ idFromName(name) {
845
+ return createDOIdProxy(client, bindingName, { type: "name", value: name });
846
+ },
847
+ idFromString(hexId) {
848
+ return createDOIdProxy(client, bindingName, { type: "hex", value: hexId });
849
+ },
850
+ newUniqueId(options) {
851
+ const tempId = crypto.randomUUID().replace(/-/g, "");
852
+ return createDOIdProxy(client, bindingName, { type: "unique", value: tempId, options });
853
+ },
854
+ get(id) {
855
+ const idProxy = id;
856
+ return createDOStubProxy(client, bindingName, idProxy._idInfo, proxyOptions);
857
+ },
858
+ getByName(name) {
859
+ const id = this.idFromName(name);
860
+ return this.get(id);
861
+ },
862
+ jurisdiction(jurisdiction) {
863
+ return createDOProxy(client, bindingName, proxyOptions);
864
+ }
865
+ };
866
+ }
867
+ function createDOIdProxy(client, bindingName, idInfo) {
868
+ return {
869
+ _idInfo: idInfo,
870
+ toString() {
871
+ if (idInfo.type === "hex")
872
+ return idInfo.value;
873
+ return `${idInfo.type}:${idInfo.value}`;
874
+ },
875
+ equals(other) {
876
+ return this.toString() === other.toString();
877
+ }
878
+ };
879
+ }
880
+ function createDOStubProxy(client, bindingName, idInfo, proxyOptions = {}) {
881
+ const { transformResult } = proxyOptions;
882
+ let resolvedId = null;
883
+ const resolveId = async () => {
884
+ if (resolvedId)
885
+ return resolvedId;
886
+ switch (idInfo.type) {
887
+ case "name":
888
+ resolvedId = await client.call(`${bindingName}.idFromName`, [idInfo.value]);
889
+ break;
890
+ case "hex":
891
+ resolvedId = { __type: "DOId", hex: idInfo.value };
892
+ break;
893
+ case "unique":
894
+ resolvedId = await client.call(`${bindingName}.newUniqueId`, [idInfo.options]);
895
+ break;
896
+ }
897
+ return resolvedId;
898
+ };
899
+ const stubBase = {
900
+ async fetch(input, init) {
901
+ const id = await resolveId();
902
+ const request = input instanceof Request ? input : new Request(input, init);
903
+ const { serialized } = await serializeRequest(request);
904
+ const result = await client.call(`${bindingName}.stub.fetch`, [bindingName, id, serialized]);
905
+ return deserializeResponse(result);
906
+ },
907
+ async connect(url, options) {
908
+ const id = await resolveId();
909
+ const headersList = [];
910
+ if (options?.headers) {
911
+ const headers = new Headers(options.headers);
912
+ headers.forEach((value, key) => {
913
+ headersList.push([key, value]);
914
+ });
915
+ }
916
+ const wsProxy = await client.createWsProxy(bindingName, id.hex, url, headersList);
917
+ let readController = null;
918
+ const readable = new ReadableStream({
919
+ start(controller) {
920
+ readController = controller;
921
+ },
922
+ cancel() {
923
+ wsProxy.close();
924
+ }
925
+ });
926
+ wsProxy.onMessage((data) => {
927
+ if (readController) {
928
+ const chunk = typeof data === "string" ? new TextEncoder().encode(data) : data;
929
+ readController.enqueue(chunk);
930
+ }
931
+ });
932
+ wsProxy.onClose((code, reason) => {
933
+ if (readController) {
934
+ readController.close();
935
+ }
936
+ });
937
+ const writable = new WritableStream({
938
+ write(chunk) {
939
+ wsProxy.send(chunk);
940
+ },
941
+ close() {
942
+ wsProxy.close(1000, "Normal closure");
943
+ },
944
+ abort(reason) {
945
+ wsProxy.close(1001, reason?.toString() ?? "Aborted");
946
+ }
947
+ });
948
+ return {
949
+ readable,
950
+ writable,
951
+ get opened() {
952
+ return Promise.resolve({
953
+ remoteAddress: "127.0.0.1",
954
+ localAddress: "127.0.0.1"
955
+ });
956
+ },
957
+ get closed() {
958
+ return new Promise((resolve) => {
959
+ wsProxy.onClose(() => resolve());
960
+ });
961
+ },
962
+ close() {
963
+ wsProxy.close(1000, "Normal closure");
964
+ return Promise.resolve();
965
+ },
966
+ startTls() {
967
+ throw new Error("startTls not supported on DO WebSocket proxy");
968
+ }
969
+ };
970
+ },
971
+ get id() {
972
+ return createDOIdProxy(client, bindingName, idInfo);
973
+ },
974
+ get name() {
975
+ return idInfo.type === "name" ? idInfo.value : undefined;
976
+ }
977
+ };
978
+ return new Proxy(stubBase, {
979
+ get(target, prop) {
980
+ if (prop in target) {
981
+ return target[prop];
982
+ }
983
+ if (typeof prop === "symbol") {
984
+ return;
985
+ }
986
+ return async (...args) => {
987
+ const id = await resolveId();
988
+ let result = await client.call(`${bindingName}.stub.rpc`, [
989
+ bindingName,
990
+ id,
991
+ prop,
992
+ args
993
+ ]);
994
+ if (transformResult) {
995
+ result = transformResult(result);
996
+ }
997
+ return result;
998
+ };
999
+ }
1000
+ });
1001
+ }
1002
+ function createQueueProxy(client, bindingName) {
1003
+ return {
1004
+ async send(message, options) {
1005
+ await client.call(`${bindingName}.send`, [message, options]);
1006
+ },
1007
+ async sendBatch(messages, options) {
1008
+ await client.call(`${bindingName}.sendBatch`, [messages, options]);
1009
+ }
1010
+ };
1011
+ }
1012
+ function createAIProxy(client, bindingName) {
1013
+ return {
1014
+ async run(model, inputs, options) {
1015
+ return client.call(`${bindingName}.run`, [model, inputs, options]);
1016
+ }
1017
+ };
1018
+ }
1019
+ var globalBindingHints = {};
1020
+ function createEnvProxy(options = {}) {
1021
+ const client = options.client ?? getClient();
1022
+ const bindingProxies = new Map;
1023
+ const doProxyOptions = { transformResult: options.transformResult };
1024
+ const hints = { ...globalBindingHints, ...options.hints };
1025
+ return new Proxy({}, {
1026
+ get(target, prop) {
1027
+ if (typeof prop !== "string")
1028
+ return;
1029
+ if (bindingProxies.has(prop)) {
1030
+ return bindingProxies.get(prop);
1031
+ }
1032
+ const hint = hints[prop];
1033
+ let proxy;
1034
+ switch (hint) {
1035
+ case "kv":
1036
+ proxy = createKVProxy(client, prop);
1037
+ break;
1038
+ case "r2":
1039
+ proxy = createR2Proxy(client, prop);
1040
+ break;
1041
+ case "d1":
1042
+ proxy = createD1Proxy(client, prop);
1043
+ break;
1044
+ case "do":
1045
+ proxy = createDOProxy(client, prop, doProxyOptions);
1046
+ break;
1047
+ case "queue":
1048
+ proxy = createQueueProxy(client, prop);
1049
+ break;
1050
+ case "ai":
1051
+ proxy = createAIProxy(client, prop);
1052
+ break;
1053
+ case "secret":
1054
+ case "var":
1055
+ proxy = createSimpleBindingProxy(client, prop);
1056
+ break;
1057
+ default:
1058
+ proxy = createGenericBindingProxy(client, prop);
1059
+ }
1060
+ bindingProxies.set(prop, proxy);
1061
+ return proxy;
1062
+ },
1063
+ has(target, prop) {
1064
+ return typeof prop === "string";
1065
+ },
1066
+ ownKeys() {
1067
+ return Object.keys(hints);
1068
+ },
1069
+ getOwnPropertyDescriptor(target, prop) {
1070
+ if (typeof prop === "string") {
1071
+ return { configurable: true, enumerable: true, writable: false };
1072
+ }
1073
+ return;
1074
+ }
1075
+ });
1076
+ }
1077
+ function createGenericBindingProxy(client, bindingName) {
1078
+ return new Proxy({}, {
1079
+ get(target, prop) {
1080
+ if (typeof prop !== "string")
1081
+ return;
1082
+ if (["get", "put", "delete", "list", "getWithMetadata"].includes(prop)) {
1083
+ return createKVProxy(client, bindingName)[prop];
1084
+ }
1085
+ if (["idFromName", "idFromString", "newUniqueId", "get"].includes(prop)) {
1086
+ return createDOProxy(client, bindingName)[prop];
1087
+ }
1088
+ if (["prepare", "batch", "exec", "dump"].includes(prop)) {
1089
+ return createD1Proxy(client, bindingName)[prop];
1090
+ }
1091
+ if (["head"].includes(prop)) {
1092
+ return createR2Proxy(client, bindingName)[prop];
1093
+ }
1094
+ return async (...args) => {
1095
+ return client.call(`${bindingName}.${prop}`, args);
1096
+ };
1097
+ }
1098
+ });
1099
+ }
1100
+ function createSimpleBindingProxy(client, bindingName) {
1101
+ let cachedValue;
1102
+ let fetched = false;
1103
+ return {
1104
+ then(resolve, reject) {
1105
+ if (fetched) {
1106
+ resolve(cachedValue);
1107
+ return;
1108
+ }
1109
+ client.call(`${bindingName}.value`, []).then((value) => {
1110
+ cachedValue = value;
1111
+ fetched = true;
1112
+ resolve(value);
1113
+ }).catch(reject);
1114
+ },
1115
+ toString() {
1116
+ if (!fetched)
1117
+ throw new Error(`Binding ${bindingName} not yet fetched. Use await.`);
1118
+ return String(cachedValue);
1119
+ }
1120
+ };
1121
+ }
1122
+ var globalEnvProxy = null;
1123
+ var bridgeEnv = new Proxy({}, {
1124
+ get(target, prop) {
1125
+ if (!globalEnvProxy) {
1126
+ globalEnvProxy = createEnvProxy({ lazy: true });
1127
+ }
1128
+ return globalEnvProxy[prop];
1129
+ }
1130
+ });
1131
+ function initEnv(options = {}) {
1132
+ globalEnvProxy = createEnvProxy(options);
1133
+ return globalEnvProxy;
1134
+ }
1135
+ function setBindingHints(hints) {
1136
+ globalBindingHints = { ...globalBindingHints, ...hints };
1137
+ globalEnvProxy = null;
1138
+ }
1139
+
1140
+ // src/bridge/miniflare.ts
1141
+ function generateGatewayScript() {
1142
+ return `
1143
+ // Gateway Worker — Provides RPC access to all bindings
1144
+ export default {
1145
+ async fetch(request, env, ctx) {
1146
+ const url = new URL(request.url)
1147
+
1148
+ // Health check
1149
+ if (url.pathname === '/_devflare/health') {
1150
+ return new Response(JSON.stringify({ status: 'ok', bindings: Object.keys(env) }), {
1151
+ headers: { 'Content-Type': 'application/json' }
1152
+ })
1153
+ }
1154
+
1155
+ // RPC endpoint
1156
+ if (url.pathname === '/_devflare/rpc' && request.method === 'POST') {
1157
+ try {
1158
+ const { method, params } = await request.json()
1159
+ const result = await executeRpc(env, method, params)
1160
+ return new Response(JSON.stringify({ ok: true, result }), {
1161
+ headers: { 'Content-Type': 'application/json' }
1162
+ })
1163
+ } catch (error) {
1164
+ return new Response(JSON.stringify({
1165
+ ok: false,
1166
+ error: { code: 'RPC_ERROR', message: error.message }
1167
+ }), {
1168
+ status: 500,
1169
+ headers: { 'Content-Type': 'application/json' }
1170
+ })
1171
+ }
1172
+ }
1173
+
1174
+ return new Response('Devflare Gateway', { status: 200 })
1175
+ }
1176
+ }
1177
+
1178
+ async function executeRpc(env, method, params) {
1179
+ const [bindingName, ...methodPath] = method.split('.')
1180
+ const binding = env[bindingName]
1181
+
1182
+ if (!binding) {
1183
+ throw new Error(\`Binding "\${bindingName}" not found\`)
1184
+ }
1185
+
1186
+ const methodName = methodPath.join('.')
1187
+
1188
+ // KV operations
1189
+ if (methodName === 'get') return binding.get(params[0], params[1])
1190
+ if (methodName === 'put') return binding.put(params[0], params[1], params[2])
1191
+ if (methodName === 'delete') return binding.delete(params[0])
1192
+ if (methodName === 'list') return binding.list(params[0])
1193
+ if (methodName === 'getWithMetadata') return binding.getWithMetadata(params[0], params[1])
1194
+
1195
+ // R2 operations
1196
+ if (methodName === 'head') return binding.head(params[0])
1197
+ if (methodName === 'r2.get') return serializeR2Object(await binding.get(params[0], params[1]))
1198
+ if (methodName === 'r2.put') return serializeR2Object(await binding.put(params[0], params[1], params[2]))
1199
+ if (methodName === 'r2.delete') return binding.delete(params[0])
1200
+ if (methodName === 'r2.list') return serializeR2Objects(await binding.list(params[0]))
1201
+
1202
+ // D1 operations
1203
+ if (methodName === 'exec') return binding.exec(params[0])
1204
+ if (methodName === 'batch') {
1205
+ const statements = params[0].map(s => binding.prepare(s.sql).bind(...(s.bindings || [])))
1206
+ return binding.batch(statements)
1207
+ }
1208
+ if (methodName.startsWith('stmt.')) {
1209
+ const [, stmtMethod] = methodName.split('.')
1210
+ const [sql, ...bindings] = params
1211
+ const stmt = binding.prepare(sql).bind(...bindings.slice(0, -1))
1212
+
1213
+ if (stmtMethod === 'first') return stmt.first(bindings[bindings.length - 1])
1214
+ if (stmtMethod === 'all') return stmt.all()
1215
+ if (stmtMethod === 'run') return stmt.run()
1216
+ if (stmtMethod === 'raw') return stmt.raw(bindings[bindings.length - 1])
1217
+ }
1218
+
1219
+ // DO operations
1220
+ if (methodName === 'idFromName') {
1221
+ const id = binding.idFromName(params[0])
1222
+ return { __type: 'DOId', hex: id.toString() }
1223
+ }
1224
+ if (methodName === 'idFromString') {
1225
+ const id = binding.idFromString(params[0])
1226
+ return { __type: 'DOId', hex: id.toString() }
1227
+ }
1228
+ if (methodName === 'newUniqueId') {
1229
+ const id = binding.newUniqueId(params[0])
1230
+ return { __type: 'DOId', hex: id.toString() }
1231
+ }
1232
+ if (methodName === 'stub.fetch') {
1233
+ const [, doId, serializedReq] = params
1234
+ const id = binding.idFromString(doId.hex)
1235
+ const stub = binding.get(id)
1236
+ const response = await stub.fetch(new Request(serializedReq.url, {
1237
+ method: serializedReq.method,
1238
+ headers: serializedReq.headers,
1239
+ body: serializedReq.body?.type === 'bytes' ? atob(serializedReq.body.data) : undefined
1240
+ }))
1241
+ return serializeResponse(response)
1242
+ }
1243
+ if (methodName === 'stub.rpc') {
1244
+ // DO RPC: Call a method on the DO instance
1245
+ const [, doId, rpcMethod, rpcParams] = params
1246
+ const id = binding.idFromString(doId.hex)
1247
+ const stub = binding.get(id)
1248
+
1249
+ // Use fetch to call the RPC endpoint
1250
+ const response = await stub.fetch(new Request('http://do/_rpc', {
1251
+ method: 'POST',
1252
+ headers: { 'Content-Type': 'application/json' },
1253
+ body: JSON.stringify({ method: rpcMethod, params: rpcParams })
1254
+ }))
1255
+
1256
+ const result = await response.json()
1257
+ if (!result.ok) throw new Error(result.error?.message || 'RPC failed')
1258
+ return result.result
1259
+ }
1260
+
1261
+ // Queue operations
1262
+ if (methodName === 'send') return binding.send(params[0], params[1])
1263
+ if (methodName === 'sendBatch') return binding.sendBatch(params[0], params[1])
1264
+
1265
+ // Generic fallback
1266
+ if (typeof binding[methodName] === 'function') {
1267
+ return binding[methodName](...params)
1268
+ }
1269
+
1270
+ throw new Error(\`Unknown method: \${method}\`)
1271
+ }
1272
+
1273
+ function serializeResponse(response) {
1274
+ return {
1275
+ status: response.status,
1276
+ statusText: response.statusText,
1277
+ headers: [...response.headers.entries()],
1278
+ body: null // Will be streamed separately for large bodies
1279
+ }
1280
+ }
1281
+
1282
+ function serializeR2Object(obj) {
1283
+ if (!obj) return null
1284
+ return {
1285
+ key: obj.key,
1286
+ version: obj.version,
1287
+ size: obj.size,
1288
+ etag: obj.etag,
1289
+ httpEtag: obj.httpEtag,
1290
+ uploaded: obj.uploaded?.toISOString(),
1291
+ httpMetadata: obj.httpMetadata,
1292
+ customMetadata: obj.customMetadata
1293
+ }
1294
+ }
1295
+
1296
+ function serializeR2Objects(result) {
1297
+ if (!result) return null
1298
+ return {
1299
+ objects: result.objects.map(serializeR2Object),
1300
+ truncated: result.truncated,
1301
+ cursor: result.cursor,
1302
+ delimitedPrefixes: result.delimitedPrefixes
1303
+ }
1304
+ }
1305
+ `;
1306
+ }
1307
+ async function startMiniflare(options = {}) {
1308
+ const { Miniflare, Log, LogLevel } = await import("miniflare");
1309
+ const port = options.port ?? 8787;
1310
+ const persistPath = options.persistPath ?? ".devflare/data";
1311
+ const mfConfig = {
1312
+ modules: true,
1313
+ script: generateGatewayScript(),
1314
+ port,
1315
+ host: "127.0.0.1",
1316
+ log: options.verbose ? new Log(LogLevel.DEBUG) : new Log(LogLevel.WARN),
1317
+ compatibilityDate: options.compatibilityDate ?? "2024-01-01",
1318
+ compatibilityFlags: options.compatibilityFlags ?? []
1319
+ };
1320
+ const hasBindings = (val) => {
1321
+ if (!val)
1322
+ return false;
1323
+ if (Array.isArray(val))
1324
+ return val.length > 0;
1325
+ return Object.keys(val).length > 0;
1326
+ };
1327
+ if (hasBindings(options.kvNamespaces)) {
1328
+ mfConfig.kvNamespaces = options.kvNamespaces;
1329
+ if (options.persist) {
1330
+ mfConfig.kvPersist = `${persistPath}/kv`;
1331
+ }
1332
+ }
1333
+ if (hasBindings(options.r2Buckets)) {
1334
+ mfConfig.r2Buckets = options.r2Buckets;
1335
+ if (options.persist) {
1336
+ mfConfig.r2Persist = `${persistPath}/r2`;
1337
+ }
1338
+ }
1339
+ if (hasBindings(options.d1Databases)) {
1340
+ mfConfig.d1Databases = options.d1Databases;
1341
+ if (options.persist) {
1342
+ mfConfig.d1Persist = `${persistPath}/d1`;
1343
+ }
1344
+ }
1345
+ if (options.durableObjects) {
1346
+ mfConfig.durableObjects = options.durableObjects;
1347
+ if (options.persist) {
1348
+ mfConfig.durableObjectsPersist = `${persistPath}/do`;
1349
+ }
1350
+ }
1351
+ if (options.bindings) {
1352
+ mfConfig.bindings = options.bindings;
1353
+ }
1354
+ if (options.queues?.length) {
1355
+ mfConfig.queueProducers = Object.fromEntries(options.queues.map((q) => [q, { queueName: q }]));
1356
+ }
1357
+ const mf = new Miniflare(mfConfig);
1358
+ await mf.ready;
1359
+ return {
1360
+ ready: Promise.resolve(),
1361
+ async dispose() {
1362
+ await mf.dispose();
1363
+ },
1364
+ async getBindings() {
1365
+ return mf.getBindings();
1366
+ },
1367
+ getKVNamespace: mf.getKVNamespace.bind(mf),
1368
+ getR2Bucket: mf.getR2Bucket.bind(mf),
1369
+ getD1Database: mf.getD1Database.bind(mf),
1370
+ getDurableObjectNamespace: mf.getDurableObjectNamespace.bind(mf),
1371
+ dispatchFetch: mf.dispatchFetch.bind(mf),
1372
+ _mf: mf
1373
+ };
1374
+ }
1375
+ async function startMiniflareFromConfig(config, options = {}) {
1376
+ const bindings = config.bindings ?? {};
1377
+ const mfOptions = {
1378
+ ...options,
1379
+ compatibilityDate: config.compatibilityDate,
1380
+ compatibilityFlags: config.compatibilityFlags,
1381
+ kvNamespaces: bindings.kv ? bindings.kv : undefined,
1382
+ r2Buckets: bindings.r2 ? bindings.r2 : undefined,
1383
+ d1Databases: bindings.d1 ? bindings.d1 : undefined,
1384
+ queues: bindings.queues?.consumers?.map((c) => c.queue),
1385
+ bindings: config.vars,
1386
+ durableObjects: bindings.durableObjects ? Object.fromEntries(Object.entries(bindings.durableObjects).map(([bindingName, doConfig]) => {
1387
+ const normalized = normalizeDOBinding(doConfig);
1388
+ return [
1389
+ bindingName,
1390
+ {
1391
+ className: normalized.className,
1392
+ scriptPath: normalized.scriptName
1393
+ }
1394
+ ];
1395
+ })) : undefined
1396
+ };
1397
+ return startMiniflare(mfOptions);
1398
+ }
1399
+ var globalMiniflare = null;
1400
+ async function getMiniflare(options) {
1401
+ if (!globalMiniflare) {
1402
+ globalMiniflare = await startMiniflare(options);
1403
+ }
1404
+ return globalMiniflare;
1405
+ }
1406
+ async function stopMiniflare() {
1407
+ if (globalMiniflare) {
1408
+ await globalMiniflare.dispose();
1409
+ globalMiniflare = null;
1410
+ }
1411
+ }
1412
+
1413
+ export { BinaryKind, BinaryFlags, encodeBinaryFrame, decodeBinaryFrame, parseJsonMsg, stringifyJsonMsg, serializeValue, deserializeValue, base64Encode, base64Decode, BridgeClient, getClient, createEnvProxy, bridgeEnv, initEnv, setBindingHints, startMiniflare, startMiniflareFromConfig, getMiniflare, stopMiniflare };