@solidjs/web 2.0.0-rc.7 → 2.0.0-rc.9

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 (88) hide show
  1. package/dist/server.dev.js +638 -124
  2. package/dist/server.js +445 -94
  3. package/dist/{server.dev.cjs → server.observe.js} +602 -416
  4. package/dist/web.dev.js +229 -49
  5. package/dist/web.js +194 -46
  6. package/dist/{web.cjs → web.observe.js} +290 -275
  7. package/frames/dist/client.dev.js +103 -4
  8. package/frames/dist/client.js +5 -2
  9. package/frames/dist/{client.dev.cjs → client.observe.js} +139 -79
  10. package/frames/dist/server.dev.js +540 -79
  11. package/frames/dist/server.js +371 -52
  12. package/frames/dist/{server.cjs → server.observe.js} +544 -140
  13. package/frames/package.json +15 -21
  14. package/package.json +145 -294
  15. package/serialization/decode/package.json +3 -9
  16. package/serialization/package.json +3 -9
  17. package/serialization/types/serializer-decode.d.ts +49 -2
  18. package/server-functions/dist/{client.cjs → client.dev.js} +140 -107
  19. package/server-functions/dist/client.js +74 -69
  20. package/server-functions/dist/client.observe.js +1102 -0
  21. package/server-functions/dist/server.dev.js +430 -41
  22. package/server-functions/dist/server.js +367 -40
  23. package/server-functions/dist/{server.cjs → server.observe.js} +430 -85
  24. package/server-functions/package.json +15 -21
  25. package/server-functions/rich-args/package.json +3 -9
  26. package/storage/package.json +3 -9
  27. package/types/client.d.ts +39 -1
  28. package/types/diagnostics.d.ts +24 -0
  29. package/types/frames/frame-transport.d.ts +1 -1
  30. package/types/frames/serializer-decode.d.ts +49 -2
  31. package/types/index.d.ts +25 -15
  32. package/types/index.server.d.ts +35 -8
  33. package/types/jsx.d.ts +15 -4
  34. package/types/observe.d.ts +294 -0
  35. package/types/response.d.ts +18 -0
  36. package/types/serializer-decode.d.ts +49 -2
  37. package/types/server-functions/client.d.ts +32 -22
  38. package/types/server-functions/server.d.ts +55 -41
  39. package/types/server-functions/shared.d.ts +39 -9
  40. package/types/server-mock.d.ts +26 -4
  41. package/types/server-observe.d.ts +39 -0
  42. package/types/server.d.ts +105 -6
  43. package/types/trace.d.ts +79 -0
  44. package/dist/server.cjs +0 -3708
  45. package/dist/web.dev.cjs +0 -2285
  46. package/frames/dist/client.cjs +0 -2043
  47. package/frames/dist/server.dev.cjs +0 -4584
  48. package/serialization/dist/decode.cjs +0 -155
  49. package/serialization/dist/serialization.cjs +0 -275
  50. package/serialization/types-cjs/index.d.cts +0 -101
  51. package/serialization/types-cjs/package.json +0 -3
  52. package/serialization/types-cjs/serializer-decode.d.cts +0 -172
  53. package/serialization/types-cjs/serializer.d.cts +0 -101
  54. package/server-functions/dist/rich-args.cjs +0 -11
  55. package/server-functions/dist/server.dev.cjs +0 -2409
  56. package/storage/dist/storage.cjs +0 -12
  57. package/storage/types-cjs/index.d.cts +0 -28
  58. package/storage/types-cjs/package.json +0 -3
  59. package/types-cjs/client.d.cts +0 -197
  60. package/types-cjs/constants.d.cts +0 -20
  61. package/types-cjs/cookies.d.cts +0 -41
  62. package/types-cjs/frames/client.d.cts +0 -36
  63. package/types-cjs/frames/frame-client.d.cts +0 -370
  64. package/types-cjs/frames/frame-container-plugin.d.cts +0 -71
  65. package/types-cjs/frames/frame-sink.d.cts +0 -92
  66. package/types-cjs/frames/frame-transport.d.cts +0 -189
  67. package/types-cjs/frames/serializer-decode.d.cts +0 -172
  68. package/types-cjs/frames/serializer.d.cts +0 -101
  69. package/types-cjs/frames/server.d.cts +0 -52
  70. package/types-cjs/head.d.cts +0 -19
  71. package/types-cjs/index.d.cts +0 -191
  72. package/types-cjs/index.server.d.cts +0 -147
  73. package/types-cjs/jsx-properties.d.cts +0 -93
  74. package/types-cjs/jsx.d.cts +0 -4146
  75. package/types-cjs/package.json +0 -3
  76. package/types-cjs/reconcile.d.cts +0 -1
  77. package/types-cjs/render.d.cts +0 -6
  78. package/types-cjs/response.d.cts +0 -81
  79. package/types-cjs/serializer-decode.d.cts +0 -172
  80. package/types-cjs/serializer.d.cts +0 -101
  81. package/types-cjs/server-functions/client.d.cts +0 -184
  82. package/types-cjs/server-functions/flash.d.cts +0 -36
  83. package/types-cjs/server-functions/registry.d.cts +0 -100
  84. package/types-cjs/server-functions/rich-args.d.cts +0 -1
  85. package/types-cjs/server-functions/server.d.cts +0 -546
  86. package/types-cjs/server-functions/shared.d.cts +0 -283
  87. package/types-cjs/server-mock.d.cts +0 -337
  88. package/types-cjs/server.d.cts +0 -408
@@ -0,0 +1,1102 @@
1
+ const REVALIDATE_HEADER = "X-Revalidate";
2
+
3
+ const RECORDS = Symbol.for("@solidjs/signals/observe/records");
4
+ const ATTRIBUTION = Symbol.for("@solidjs/signals/observe/attribution");
5
+ function records() {
6
+ return globalThis[RECORDS];
7
+ }
8
+ function currentOrigin() {
9
+ const hooks = globalThis[ATTRIBUTION];
10
+ return hooks === undefined ? undefined : hooks.currentOrigin();
11
+ }
12
+ function isDeferredBody(value) {
13
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
14
+ if (typeof ReadableStream !== "undefined" && value instanceof ReadableStream) return true;
15
+ const v = value;
16
+ if (typeof v[Symbol.asyncIterator] === "function") return true;
17
+ return typeof v[Symbol.iterator] === "function" && !Array.isArray(value) && !(value instanceof Map) && !(value instanceof Set) && !ArrayBuffer.isView(value);
18
+ }
19
+ function observeCall(id, method, args) {
20
+ const channel = records();
21
+ if (channel === undefined || !channel.observed("call")) return undefined;
22
+ const at = performance.now();
23
+ const origin = currentOrigin();
24
+ let response;
25
+ let settled = false;
26
+ return {
27
+ response(r) {
28
+ response = r;
29
+ },
30
+ settle(outcome, value) {
31
+ if (settled) return;
32
+ settled = true;
33
+ const event = {
34
+ id,
35
+ at,
36
+ durationMs: performance.now() - at,
37
+ method,
38
+ outcome
39
+ };
40
+ if (response !== undefined) event.status = response.status;
41
+ if (origin !== undefined) event.origin = origin;
42
+ const live = {
43
+ args
44
+ };
45
+ if (response !== undefined) live.response = response;
46
+ if (outcome === "ok") {
47
+ live.result = value;
48
+ if (isDeferredBody(value)) event.deferred = true;
49
+ } else live.error = value;
50
+ channel.emit("call", event, live);
51
+ }
52
+ };
53
+ }
54
+
55
+ const SERVER_FUNCTION_METADATA = Symbol.for("solid.ServerFunctionMetadata");
56
+ function getServerFunctionMetadata(fn) {
57
+ if (typeof fn !== "function") return undefined;
58
+ return fn[SERVER_FUNCTION_METADATA] || undefined;
59
+ }
60
+ function isServerFunction(fn) {
61
+ return typeof fn === "function" && !!fn[SERVER_FUNCTION_METADATA];
62
+ }
63
+ function withMeta(fn, meta) {
64
+ const metadata = getServerFunctionMetadata(fn);
65
+ if (!metadata) {
66
+ throw new Error("withMeta expects a server function reference");
67
+ }
68
+ Object.assign(metadata, meta);
69
+ return fn;
70
+ }
71
+ const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
72
+ const INVOKE_OPTION_REDIRECTS = {
73
+ headers: "Session-dynamic headers belong to the prepareRequest hook, declaration metadata to " + "withMeta(fn, meta), and data belongs in the arguments, where it is serialized, typed, " + "and part of the cache key.",
74
+ method: "The method is declaration-scoped: declare the function with GET(fn).",
75
+ body: "The arguments are the body: pass them in the args array.",
76
+ timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
77
+ };
78
+ function invoke(fn, options, ...args) {
79
+ const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
80
+ if (!channel) {
81
+ throw new Error(isServerFunction(fn) ? "invoke: this wrapper does not forward the invocation channel " + "(SERVER_FUNCTION_INVOKE). Wrappers that share calls (caches, channels) opt in " + "deliberately — a caller's signal cannot own a wire other callers share. Invoke " + "the underlying reference directly, or use the wrapper's own per-call idioms." : "invoke expects a server function reference (or a wrapper that forwards its " + "invocation channel). Per-call options apply at the transport; for a data " + "layer's calls, use its per-call options instead.");
82
+ }
83
+ if (options === null || typeof options !== "object") {
84
+ throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
85
+ }
86
+ const picked = {};
87
+ for (const key in options) {
88
+ if (key !== "signal" && key !== "keepalive" && key !== "priority") {
89
+ throw new Error(`\`${key}\` is not an invocation option. ` + (INVOKE_OPTION_REDIRECTS[key] || "Options here are strictly invocation-scoped (they vary between calls of the " + "same function): signal, keepalive, priority."));
90
+ }
91
+ }
92
+ if (options.signal !== undefined) picked.signal = options.signal;
93
+ if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
94
+ if (options.priority !== undefined) picked.priority = options.priority;
95
+ return channel(args, picked);
96
+ }
97
+ const LIVE_SOURCE = Symbol.for("solid.LiveSource");
98
+ const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
99
+ function provideServerFunctionRPC(rpc) {
100
+ globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
101
+ }
102
+
103
+ const FLASH_COOKIE = "flash";
104
+ const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
105
+ function hasFlashCookie(cookieHeader) {
106
+ return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
107
+ }
108
+ function clearFlashCookie() {
109
+ return `${FLASH_COOKIE}=; Max-Age=0; Path=/`;
110
+ }
111
+
112
+ const codecConfig = {
113
+ codec: undefined
114
+ };
115
+ function configureServerFunctionsCodec(codec) {
116
+ codecConfig.codec = codec;
117
+ }
118
+ function getServerFunctionsCodec() {
119
+ return codecConfig.codec;
120
+ }
121
+ const UNNAMED_FLIGHT_SOURCE = "true";
122
+ const flightConfig = {
123
+ consumers: new Map()
124
+ };
125
+ function assertFlightSource(source) {
126
+ if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
127
+ throw new TypeError(`Invalid flight data source id "${source}": ids ride the ` + `${SINGLE_FLIGHT_HEADER} header as a comma-separated list, and "true" is ` + `reserved for the unnamed registration (the bare consumer/hook signatures).`);
128
+ }
129
+ }
130
+ function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
131
+ const named = typeof sourceOrConsumer === "string";
132
+ if (named) assertFlightSource(sourceOrConsumer);
133
+ const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
134
+ const consumer = named ? maybeConsumer : sourceOrConsumer;
135
+ flightConfig.consumers.set(source, consumer);
136
+ return () => {
137
+ if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
138
+ };
139
+ }
140
+ function getFlightDataConsumer(source) {
141
+ return flightConfig.consumers.get(source === undefined ? UNNAMED_FLIGHT_SOURCE : source);
142
+ }
143
+ function getFlightDataSourceIds() {
144
+ return [...flightConfig.consumers.keys()];
145
+ }
146
+ function frameAddress(id, args) {
147
+ return args && args.length ? id + ":" + hashArguments(args) : id;
148
+ }
149
+ function hashArguments(args) {
150
+ let hash = 0;
151
+ const text = stableString(args);
152
+ for (let i = 0; i < text.length; i++) {
153
+ hash = (hash << 5) - hash + text.charCodeAt(i);
154
+ hash |= 0;
155
+ }
156
+ return (hash >>> 0).toString(36);
157
+ }
158
+ function stableString(value, seen) {
159
+ if (value === null || typeof value !== "object") {
160
+ return typeof value === "bigint" ? value + "n" : String(value);
161
+ }
162
+ if (value instanceof Date) return "Date:" + value.getTime();
163
+ seen || (seen = new Set());
164
+ if (seen.has(value)) return "~";
165
+ seen.add(value);
166
+ if (value instanceof Map) {
167
+ const entries = [];
168
+ for (const [k, v] of value) {
169
+ entries.push(stableString(k, seen) + "=>" + stableString(v, seen));
170
+ }
171
+ return "Map{" + entries.sort().join(",") + "}";
172
+ }
173
+ if (value instanceof Set) {
174
+ const members = [];
175
+ for (const v of value) members.push(stableString(v, seen));
176
+ return "Set{" + members.sort().join(",") + "}";
177
+ }
178
+ if (Array.isArray(value)) {
179
+ let out = "[";
180
+ for (let i = 0; i < value.length; i++) out += (i ? "," : "") + stableString(value[i], seen);
181
+ return out + "]";
182
+ }
183
+ const keys = Object.keys(value).sort();
184
+ let out = "{";
185
+ for (let i = 0; i < keys.length; i++) {
186
+ out += (i ? "," : "") + keys[i] + ":" + stableString(value[keys[i]], seen);
187
+ }
188
+ return out + "}";
189
+ }
190
+ function serverFunctionAddress(endpoint, id) {
191
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
192
+ return `${mount}/${encodeURIComponent(id)}`;
193
+ }
194
+ function serverFunctionDataAddress(endpoint, id) {
195
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
196
+ return `${mount}/data/${encodeURIComponent(id)}`;
197
+ }
198
+ function parseServerFunctionAddress(pathname, endpoint) {
199
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
200
+ if (!pathname.startsWith(mount)) return null;
201
+ const rest = pathname.slice(mount.length);
202
+ if (!rest.startsWith("/")) return null;
203
+ let segment = rest.slice(1);
204
+ let data = false;
205
+ if (segment.startsWith("data/")) {
206
+ segment = segment.slice(5);
207
+ data = true;
208
+ }
209
+ if (!segment || segment.includes("/")) return null;
210
+ try {
211
+ return {
212
+ id: decodeURIComponent(segment),
213
+ data
214
+ };
215
+ } catch {
216
+ return null;
217
+ }
218
+ }
219
+ const MAX_GET_URL_LENGTH = 2000;
220
+ function urlTargetId(target, helper) {
221
+ if (typeof target === "string") return target;
222
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
223
+ throw new Error(`${helper} expects a server function reference (or its id).`);
224
+ }
225
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
226
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
227
+ if (!boundArgs.length) return address;
228
+ if (!isJSONSafe(boundArgs)) {
229
+ throw new Error("Bound arguments in an action url must be JSON-safe: the server reads them the way it " + "reads a form post's, and that convention has no codec. Pass the value through the " + "function's body, or call the reference instead of rendering a url for it.");
230
+ }
231
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
232
+ }
233
+ function serverFunctionUrlFor(endpoint, fn, args) {
234
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
235
+ throw new Error("serverFunctionUrl expects a server function reference.");
236
+ }
237
+ const metadata = getServerFunctionMetadata(fn);
238
+ if (!metadata || metadata.method !== "GET") {
239
+ throw new Error(`serverFunctionUrl: "${fn.id}" is not a declared read. A call over the default ` + "transport is a POST — its arguments travel in the body, so no url describes it. " + "Declare the function with GET(fn) for a cacheable read that has a url, or start " + 'the call itself: invoke(fn, { priority: "low" }, ...args).');
240
+ }
241
+ const address = serverFunctionDataAddress(endpoint, fn.id);
242
+ if (!args.length) return address;
243
+ if (!isJSONSafe(args)) {
244
+ throw new Error("Arguments in a server function url must be JSON-safe: the transport encodes anything " + "else through the codec asynchronously, and a url rendered as a value cannot wait for " + "it. Pass JSON-safe arguments, or call the reference instead of rendering a url for it.");
245
+ }
246
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
247
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
248
+ if (length > MAX_GET_URL_LENGTH) {
249
+ throw new Error(`serverFunctionUrl: the url for "${fn.id}" with these arguments is ${length} characters; ` + `past ${MAX_GET_URL_LENGTH} the call dispatches over POST (a cache miss rather than a ` + "414), so no url describes it. Shorten the arguments, or call the reference instead.");
250
+ }
251
+ return url;
252
+ }
253
+ const ERROR_HEADER = "X-Server-Function-Error";
254
+ const ERROR_HEADER_MARKER = "=?1?";
255
+ const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
256
+ function encodeErrorHeaderValue(value) {
257
+ let stripped = String(value).replace(/[\r\n]+/g, "");
258
+ if (!NEEDS_ENCODING.test(stripped) && !stripped.startsWith(ERROR_HEADER_MARKER) && stripped === stripped.trim()) {
259
+ return stripped;
260
+ }
261
+ if (typeof stripped.toWellFormed === "function") {
262
+ stripped = stripped.toWellFormed();
263
+ } else {
264
+ stripped = stripped.replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, "\uFFFD");
265
+ }
266
+ return ERROR_HEADER_MARKER + encodeURIComponent(stripped);
267
+ }
268
+ function decodeErrorHeaderValue(value) {
269
+ if (typeof value !== "string" || !value.startsWith(ERROR_HEADER_MARKER)) {
270
+ return value;
271
+ }
272
+ try {
273
+ return decodeURIComponent(value.slice(ERROR_HEADER_MARKER.length));
274
+ } catch {
275
+ return value;
276
+ }
277
+ }
278
+ const BODY_FORMAT_HEADER = "X-Server-Function-Format";
279
+ const UNKNOWN_HEADER = "X-Server-Function-Unknown";
280
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
281
+ function decodeRedirectHeaderValue(value) {
282
+ if (typeof value !== "string") return undefined;
283
+ const at = value.indexOf(" ");
284
+ if (at < 0) return undefined;
285
+ const status = Number(value.slice(0, at));
286
+ const url = value.slice(at + 1);
287
+ if (!Number.isInteger(status) || !url) return undefined;
288
+ if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
289
+ let parsed;
290
+ try {
291
+ parsed = new URL(url);
292
+ } catch {
293
+ return undefined;
294
+ }
295
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
296
+ return {
297
+ status,
298
+ url
299
+ };
300
+ }
301
+ const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
302
+ const FILE_FORM_KEY = "__server_function_file__";
303
+ const BodyFormat = {
304
+ Serialized: "0",
305
+ String: "1",
306
+ FormData: "2",
307
+ URLSearchParams: "3",
308
+ Blob: "4",
309
+ File: "5",
310
+ ArrayBuffer: "6",
311
+ Uint8Array: "7",
312
+ Json: "8",
313
+ Void: "9"
314
+ };
315
+ const JSON_SAFE_DEPTH_LIMIT = 4096;
316
+ const EXIT = {};
317
+ function isJSONSafe(value) {
318
+ const stack = [value];
319
+ const ancestors = new Set();
320
+ while (stack.length) {
321
+ const v = stack.pop();
322
+ if (v === EXIT) {
323
+ ancestors.delete(stack.pop());
324
+ continue;
325
+ }
326
+ if (v === null) continue;
327
+ const t = typeof v;
328
+ if (t === "string" || t === "boolean") continue;
329
+ if (t === "number") {
330
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
331
+ continue;
332
+ }
333
+ if (t !== "object") return false;
334
+ if (ancestors.has(v) || ancestors.size >= JSON_SAFE_DEPTH_LIMIT) return false;
335
+ ancestors.add(v);
336
+ stack.push(v, EXIT);
337
+ if (Array.isArray(v)) {
338
+ for (let i = 0; i < v.length; i++) stack.push(v[i]);
339
+ } else {
340
+ const proto = Object.getPrototypeOf(v);
341
+ if (proto !== Object.prototype && proto !== null) return false;
342
+ if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
343
+ for (const k in v) {
344
+ const descriptor = Object.getOwnPropertyDescriptor(v, k);
345
+ if (descriptor === undefined || !("value" in descriptor)) return false;
346
+ stack.push(descriptor.value);
347
+ }
348
+ }
349
+ }
350
+ return true;
351
+ }
352
+ function getHeadersAndBody(body) {
353
+ switch (true) {
354
+ case typeof body === "string":
355
+ return {
356
+ headers: {
357
+ "Content-Type": "text/plain",
358
+ [BODY_FORMAT_HEADER]: BodyFormat.String
359
+ },
360
+ body
361
+ };
362
+ case body instanceof FormData:
363
+ return {
364
+ headers: {
365
+ [BODY_FORMAT_HEADER]: BodyFormat.FormData
366
+ },
367
+ body
368
+ };
369
+ case body instanceof URLSearchParams:
370
+ return {
371
+ headers: {
372
+ "Content-Type": "application/x-www-form-urlencoded",
373
+ [BODY_FORMAT_HEADER]: BodyFormat.URLSearchParams
374
+ },
375
+ body
376
+ };
377
+ case typeof File !== "undefined" && body instanceof File:
378
+ {
379
+ const formData = new FormData();
380
+ formData.append(FILE_FORM_KEY, body, body.name);
381
+ return {
382
+ headers: {
383
+ [BODY_FORMAT_HEADER]: BodyFormat.File
384
+ },
385
+ body: formData
386
+ };
387
+ }
388
+ case body instanceof Blob:
389
+ return {
390
+ headers: {
391
+ [BODY_FORMAT_HEADER]: BodyFormat.Blob
392
+ },
393
+ body
394
+ };
395
+ case body instanceof ArrayBuffer:
396
+ return {
397
+ headers: {
398
+ [BODY_FORMAT_HEADER]: BodyFormat.ArrayBuffer
399
+ },
400
+ body
401
+ };
402
+ case body instanceof Uint8Array:
403
+ return {
404
+ headers: {
405
+ [BODY_FORMAT_HEADER]: BodyFormat.Uint8Array
406
+ },
407
+ body: new Uint8Array(body)
408
+ };
409
+ default:
410
+ return undefined;
411
+ }
412
+ }
413
+ async function extractBody(source, codecOptions) {
414
+ const contentType = source.headers.get("content-type");
415
+ const format = source.headers.get(BODY_FORMAT_HEADER);
416
+ switch (true) {
417
+ case format === BodyFormat.Serialized:
418
+ return await deserializeStream(source, codecOptions);
419
+ case format === BodyFormat.Json:
420
+ return JSON.parse(await source.text());
421
+ case format === BodyFormat.String:
422
+ return await source.text();
423
+ case format === BodyFormat.File:
424
+ {
425
+ const formData = await source.formData();
426
+ return formData.get(FILE_FORM_KEY);
427
+ }
428
+ case format === BodyFormat.FormData:
429
+ case contentType && contentType.startsWith("multipart/form-data"):
430
+ return await source.formData();
431
+ case format === BodyFormat.URLSearchParams:
432
+ case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
433
+ return new URLSearchParams(await source.text());
434
+ case format === BodyFormat.Blob:
435
+ return await source.blob();
436
+ case format === BodyFormat.ArrayBuffer:
437
+ return await source.arrayBuffer();
438
+ case format === BodyFormat.Uint8Array:
439
+ return new Uint8Array(await source.arrayBuffer());
440
+ }
441
+ return undefined;
442
+ }
443
+ function createChunk(data) {
444
+ const encoder = new TextEncoder();
445
+ const encodeData = encoder.encode(data);
446
+ const bytes = encodeData.length;
447
+ const chunk = new Uint8Array(12 + bytes);
448
+ chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
449
+ chunk.set(encodeData, 12);
450
+ return chunk;
451
+ }
452
+ class ChunkReader {
453
+ constructor(stream) {
454
+ this.reader = stream.getReader();
455
+ this.store = new Uint8Array(0);
456
+ this.buffer = this.store;
457
+ this.done = false;
458
+ }
459
+ async readChunk() {
460
+ const chunk = await this.reader.read();
461
+ if (chunk.done) {
462
+ this.done = true;
463
+ return;
464
+ }
465
+ const incoming = chunk.value;
466
+ const store = this.store;
467
+ const start = this.buffer.byteOffset;
468
+ const end = start + this.buffer.length;
469
+ const needed = this.buffer.length + incoming.length;
470
+ if (end + incoming.length <= store.length) {
471
+ store.set(incoming, end);
472
+ this.buffer = store.subarray(start, end + incoming.length);
473
+ } else if (needed <= store.length) {
474
+ store.copyWithin(0, start, end);
475
+ store.set(incoming, this.buffer.length);
476
+ this.buffer = store.subarray(0, needed);
477
+ } else {
478
+ const grown = new Uint8Array(Math.max(needed, store.length * 2));
479
+ grown.set(this.buffer);
480
+ grown.set(incoming, this.buffer.length);
481
+ this.store = grown;
482
+ this.buffer = grown.subarray(0, needed);
483
+ }
484
+ }
485
+ async next() {
486
+ while (this.buffer.length < 12) {
487
+ if (this.done) {
488
+ if (this.buffer.length === 0) return {
489
+ done: true,
490
+ value: undefined
491
+ };
492
+ throw new Error("Malformed server function stream.");
493
+ }
494
+ await this.readChunk();
495
+ }
496
+ const decoder = new TextDecoder();
497
+ const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
498
+ if (Number.isNaN(bytes)) {
499
+ throw new Error("Malformed server function stream.");
500
+ }
501
+ while (bytes > this.buffer.length - 12) {
502
+ if (this.done) {
503
+ throw new Error("Malformed server function stream.");
504
+ }
505
+ await this.readChunk();
506
+ }
507
+ const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
508
+ this.buffer = this.buffer.subarray(12 + bytes);
509
+ return {
510
+ done: false,
511
+ value: partial
512
+ };
513
+ }
514
+ async drain(interpret) {
515
+ while (true) {
516
+ const result = await this.next();
517
+ if (result.done) {
518
+ break;
519
+ }
520
+ interpret(result.value);
521
+ }
522
+ }
523
+ }
524
+ const ERROR_TRAILER_PREFIX = "!";
525
+ function errorFromTrailer(payload) {
526
+ let shape;
527
+ try {
528
+ shape = JSON.parse(payload.slice(1));
529
+ } catch {
530
+ shape = null;
531
+ }
532
+ const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
533
+ if (shape && typeof shape.name === "string") error.name = shape.name;
534
+ return error;
535
+ }
536
+ function serializeStream(value, codecOptions) {
537
+ return new ReadableStream({
538
+ async start(controller) {
539
+ const {
540
+ serializeJSON
541
+ } = await import('@solidjs/web/serialization');
542
+ serializeJSON(value, {
543
+ ...codecOptions,
544
+ onParse(node) {
545
+ controller.enqueue(createChunk(JSON.stringify(node)));
546
+ },
547
+ onDone() {
548
+ controller.close();
549
+ },
550
+ onError(error) {
551
+ controller.error(error);
552
+ }
553
+ });
554
+ }
555
+ });
556
+ }
557
+ async function serializeString(value, codecOptions) {
558
+ const response = new Response(serializeStream(value, codecOptions));
559
+ return await response.text();
560
+ }
561
+ async function deserializeStream(source, codecOptions) {
562
+ if (!source.body) {
563
+ throw new Error("missing body");
564
+ }
565
+ const reader = new ChunkReader(source.body);
566
+ const result = await reader.next();
567
+ if (!result.done) {
568
+ if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
569
+ throw errorFromTrailer(result.value);
570
+ }
571
+ const {
572
+ createJSONDeserializer
573
+ } = await import('@solidjs/web/serialization/decode');
574
+ const deserializeChunk = createJSONDeserializer(codecOptions);
575
+ function interpretChunk(chunk) {
576
+ if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
577
+ throw errorFromTrailer(chunk);
578
+ }
579
+ return deserializeChunk(JSON.parse(chunk));
580
+ }
581
+ reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
582
+ return interpretChunk(result.value);
583
+ }
584
+ return undefined;
585
+ }
586
+ async function decodeResponse(response, codecOptions) {
587
+ if (!response.body) return undefined;
588
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
589
+ }
590
+ async function decodeResponsePayload(response, codecOptions) {
591
+ const decoded = await decodeResponse(response, codecOptions);
592
+ if (decoded !== undefined && response.headers.has(SINGLE_FLIGHT_HEADER)) {
593
+ return {
594
+ value: decoded.value,
595
+ flightData: decoded.data
596
+ };
597
+ }
598
+ return {
599
+ value: decoded
600
+ };
601
+ }
602
+
603
+ const config = {
604
+ endpoint: "/_server",
605
+ fetch: undefined,
606
+ prepareRequest: undefined,
607
+ responseHandler: undefined,
608
+ serializeArgs: undefined
609
+ };
610
+ function serverFunctionUrl(fn, ...args) {
611
+ return serverFunctionUrlFor(config.endpoint, fn, args);
612
+ }
613
+ function serverFunctionActionUrl(fn, ...boundArgs) {
614
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
615
+ }
616
+ function parseServerFunctionActionUrl(url) {
617
+ const parsed = parseServerFunctionAddress(new URL(url, globalThis.location?.href || "http://localhost").pathname, config.endpoint);
618
+ return parsed && parsed.id;
619
+ }
620
+ function serializeArguments(args) {
621
+ if (!config.serializeArgs) {
622
+ throw new Error("Server function arguments are sent as JSON by default and these " + "arguments are not JSON-serializable. Call enableRichArguments() " + '(from "@solidjs/web/server-functions/rich-args") once at startup ' + "to send Dates, Maps, Sets, typed arrays, etc. through the codec — " + "or pass a single Blob/FormData/File argument, which has a native " + "HTTP encoding.");
623
+ }
624
+ return config.serializeArgs(args);
625
+ }
626
+ function configureServerFunctionsClient({
627
+ endpoint,
628
+ codec,
629
+ fetch,
630
+ prepareRequest,
631
+ responseHandler,
632
+ serializeArgs
633
+ } = {}) {
634
+ if (endpoint !== undefined) config.endpoint = endpoint;
635
+ if (codec !== undefined) configureServerFunctionsCodec(codec);
636
+ if (fetch !== undefined) config.fetch = fetch;
637
+ if (prepareRequest !== undefined) config.prepareRequest = prepareRequest;
638
+ if (responseHandler !== undefined) config.responseHandler = responseHandler;
639
+ if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
640
+ }
641
+ let rpcProvided = false;
642
+ function provideRPC() {
643
+ if (rpcProvided) return;
644
+ rpcProvided = true;
645
+ provideServerFunctionRPC({
646
+ GET,
647
+ decodeResponse
648
+ });
649
+ }
650
+ function dataAddressFor(base) {
651
+ const splitAt = base.search(/[?#]/);
652
+ const path = splitAt < 0 ? base : base.slice(0, splitAt);
653
+ const rest = splitAt < 0 ? "" : base.slice(splitAt);
654
+ const slash = path.lastIndexOf("/");
655
+ if (path.endsWith("/data/", slash + 1)) return base;
656
+ return `${path.slice(0, slash + 1)}data/${path.slice(slash + 1)}${rest}`;
657
+ }
658
+ function serverFunctionFailure(response, value) {
659
+ const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
660
+ const error = value ?? new Error(unknown ? "Server function is not part of the deployment that answered (version skew or removed function)" : `Server function call failed with status ${response.status}`);
661
+ if (error instanceof Error && !("status" in error)) {
662
+ error.status = response.status;
663
+ const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
664
+ if (retryAfter !== undefined) error.retryAfter = retryAfter;
665
+ }
666
+ if (unknown && error instanceof Error) error.unknownFunction = true;
667
+ return error;
668
+ }
669
+ function parseRetryAfter(header) {
670
+ if (!header) return undefined;
671
+ const trimmed = header.trim();
672
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
673
+ const date = Date.parse(trimmed);
674
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));
675
+ return undefined;
676
+ }
677
+ function isReadCall(options) {
678
+ return !!options.read || !!options.method && options.method.toUpperCase() === "GET";
679
+ }
680
+ async function createRequest(base, id, options, meta) {
681
+ const headers = {
682
+ ...options.headers
683
+ };
684
+ const flightSources = getFlightDataSourceIds();
685
+ if (flightSources.length > 0 && !isReadCall(options)) {
686
+ headers[SINGLE_FLIGHT_HEADER] = flightSources.join(",");
687
+ }
688
+ let init = {
689
+ method: "POST",
690
+ ...options,
691
+ headers
692
+ };
693
+ if (config.prepareRequest) {
694
+ const prepared = await config.prepareRequest(init, {
695
+ id,
696
+ meta
697
+ });
698
+ if (prepared && prepared !== init) {
699
+ if (typeof prepared !== "object") {
700
+ throw new Error("prepareRequest must return (or mutate and return) the RequestInit it received; " + `it returned a ${typeof prepared}. Spread the init: ` + "init => ({ ...init, headers: { ...init.headers, ... } })");
701
+ }
702
+ if (typeof prepared.method !== "string" || prepared.method.toUpperCase() !== init.method.toUpperCase()) {
703
+ throw new Error(`prepareRequest returned an init without the transport's ${init.method} method, ` + "which would send the call without its payload or protocol. Spread the init it " + "received: init => ({ ...init, headers: { ...init.headers, ... } })");
704
+ }
705
+ }
706
+ init = prepared || init;
707
+ }
708
+ const send = config.fetch || fetch;
709
+ return send(base, init);
710
+ }
711
+ async function initializeResponse(base, id, options, args, meta) {
712
+ if (args.length === 0) {
713
+ return createRequest(base, id, options, meta);
714
+ }
715
+ if (args.length === 1) {
716
+ const result = getHeadersAndBody(args[0]);
717
+ if (result) {
718
+ return createRequest(base, id, {
719
+ ...options,
720
+ body: result.body,
721
+ headers: {
722
+ ...options.headers,
723
+ ...result.headers
724
+ }
725
+ }, meta);
726
+ }
727
+ }
728
+ try {
729
+ if (isJSONSafe(args)) {
730
+ return createRequest(base, id, {
731
+ ...options,
732
+ body: JSON.stringify(args),
733
+ headers: {
734
+ ...options.headers,
735
+ "Content-Type": "application/json",
736
+ [BODY_FORMAT_HEADER]: BodyFormat.Json
737
+ }
738
+ }, meta);
739
+ }
740
+ } catch {
741
+ }
742
+ if (args.length > 1) {
743
+ try {
744
+ const trailing = getHeadersAndBody(args[args.length - 1]);
745
+ const leading = args.slice(0, -1).map(arg => arg === undefined ? null : arg);
746
+ if (trailing && isJSONSafe(leading)) {
747
+ const target = base + (base.includes("?") ? "&" : "?") + "args=" + encodeURIComponent(JSON.stringify(leading));
748
+ return createRequest(target, id, {
749
+ ...options,
750
+ body: trailing.body,
751
+ headers: {
752
+ ...options.headers,
753
+ ...trailing.headers
754
+ }
755
+ }, meta);
756
+ }
757
+ } catch {
758
+ }
759
+ }
760
+ return createRequest(base, id, {
761
+ ...options,
762
+ body: await serializeArguments(args),
763
+ headers: {
764
+ ...options.headers,
765
+ "Content-Type": "text/plain",
766
+ [BODY_FORMAT_HEADER]: BodyFormat.Serialized
767
+ }
768
+ }, meta);
769
+ }
770
+ async function observedFetch(base, id, options, args, meta, callArgs = args) {
771
+ const observation = observeCall(id, options.method && options.method.toUpperCase() === "GET" ? "GET" : "POST", callArgs);
772
+ if (!observation) return dispatchServerFunction(base, id, options, args, meta, callArgs);
773
+ let result;
774
+ try {
775
+ result = await dispatchServerFunction(base, id, options, args, meta, callArgs, observation);
776
+ } catch (error) {
777
+ observation.settle("error", error);
778
+ throw error;
779
+ }
780
+ observation.settle("ok", result);
781
+ return result;
782
+ }
783
+ const fetchServerFunction = observedFetch ;
784
+ async function dispatchServerFunction(base, id, options, args, meta, callArgs = args, observation) {
785
+ const handler = config.responseHandler;
786
+ const context = handler && handler.capture ? handler.capture({
787
+ id,
788
+ meta
789
+ }) : undefined;
790
+ const controller = options.signal ? undefined : new AbortController();
791
+ if (controller) options = {
792
+ ...options,
793
+ signal: controller.signal
794
+ };
795
+ const response = await initializeResponse(base, id, options, args, meta);
796
+ if (observation) observation.response(response);
797
+ if (handler) {
798
+ const handled = handler.handle(response, {
799
+ id,
800
+ meta,
801
+ args: callArgs,
802
+ context
803
+ });
804
+ if (handled !== undefined) return handled;
805
+ }
806
+ if (response.status >= 400 && !response.headers.has(BODY_FORMAT_HEADER)) {
807
+ throw serverFunctionFailure(response, undefined);
808
+ }
809
+ const failed = response.headers.has(ERROR_HEADER);
810
+ const registered = isReadCall(options) ? [] : getFlightDataSourceIds();
811
+ if (registered.length > 0) {
812
+ const folded = response.headers.has(SINGLE_FLIGHT_HEADER) ? response.headers.get(SINGLE_FLIGHT_HEADER).split(",") : [];
813
+ const metadata = response.headers.has(REDIRECT_HEADER) || response.headers.has(REVALIDATE_HEADER);
814
+ if (metadata || folded.length > 0) {
815
+ const decoded = response.body ? await extractBody(response, getServerFunctionsCodec()) : undefined;
816
+ const enveloped = folded.length > 0 && decoded !== undefined;
817
+ const value = enveloped ? decoded.value : decoded;
818
+ const data = enveloped ? decoded.data : undefined;
819
+ for (const source of registered) {
820
+ if (!metadata && !folded.includes(source)) continue;
821
+ const consumer = getFlightDataConsumer(source);
822
+ if (consumer) await consumer(data ? data[source] : undefined, {
823
+ response
824
+ });
825
+ }
826
+ if (failed && !metadata) {
827
+ throw serverFunctionFailure(response, value);
828
+ }
829
+ return value;
830
+ }
831
+ }
832
+ if (response.headers.has(REDIRECT_HEADER) || response.headers.has(REVALIDATE_HEADER) || response.headers.has(SINGLE_FLIGHT_HEADER) || response.status >= 300 && response.status < 400 && response.status !== 304) {
833
+ return response;
834
+ }
835
+ if (response.status < 300 && !response.headers.has(BODY_FORMAT_HEADER) && !response.headers.has("X-Content-Raw")) {
836
+ throw serverFunctionFailure(response, new Error(`Server function response carries no recognized encoding (status ${response.status}` + `${response.headers.get("Content-Type") ? `, content-type ${response.headers.get("Content-Type")}` : ""}): answered by something other than the server function runtime`));
837
+ }
838
+ const result = response.body ? await extractBody(response, getServerFunctionsCodec()) : undefined;
839
+ if (failed) {
840
+ throw serverFunctionFailure(response, result);
841
+ }
842
+ if (controller && result?.[Symbol.asyncIterator]) {
843
+ return {
844
+ [Symbol.asyncIterator]() {
845
+ const it = result[Symbol.asyncIterator]();
846
+ return {
847
+ next: () => it.next(),
848
+ return: value => (controller.abort(), Promise.resolve({
849
+ done: true,
850
+ value
851
+ }))
852
+ };
853
+ }
854
+ };
855
+ }
856
+ return result;
857
+ }
858
+ function createServerReference(id, name, base) {
859
+ provideRPC();
860
+ const metadata = name === undefined ? {} : {
861
+ name
862
+ };
863
+ const run = (args, invokeOptions) => {
864
+ const handler = config.responseHandler;
865
+ if (handler && handler.intercept) {
866
+ const hit = handler.intercept({
867
+ id,
868
+ meta: metadata,
869
+ args
870
+ });
871
+ if (hit !== undefined) return hit;
872
+ }
873
+ return fetchServerFunction(base ? dataAddressFor(base) : serverFunctionDataAddress(config.endpoint, id), id, invokeOptions ? {
874
+ ...invokeOptions
875
+ } : {}, args, metadata);
876
+ };
877
+ const fn = (...args) => run(args);
878
+ fn[SERVER_FUNCTION_METADATA] = metadata;
879
+ fn[SERVER_FUNCTION_INVOKE] = run;
880
+ return new Proxy(fn, {
881
+ get(target, prop) {
882
+ if (prop === "id") return id;
883
+ if (prop === "url") {
884
+ return base || serverFunctionAddress(config.endpoint, id);
885
+ }
886
+ return target[prop];
887
+ }
888
+ });
889
+ }
890
+ function GET(fn) {
891
+ if (!isServerFunction(fn)) {
892
+ throw new Error("GET expects a server function reference");
893
+ }
894
+ provideRPC();
895
+ const id = fn.id;
896
+ const metadata = {
897
+ ...getServerFunctionMetadata(fn)
898
+ };
899
+ const run = async (args, invokeOptions) => {
900
+ const handler = config.responseHandler;
901
+ if (handler && handler.intercept) {
902
+ const hit = handler.intercept({
903
+ id,
904
+ meta: metadata,
905
+ args
906
+ });
907
+ if (hit !== undefined) return hit;
908
+ }
909
+ const opts = invokeOptions || {};
910
+ const address = serverFunctionDataAddress(config.endpoint, id);
911
+ if (!args.length) {
912
+ return fetchServerFunction(address, id, {
913
+ ...opts,
914
+ method: "GET"
915
+ }, [], metadata, args);
916
+ }
917
+ const encoded = isJSONSafe(args) ? JSON.stringify(args) : await serializeArguments(args);
918
+ const url = `${address}?args=${encodeURIComponent(encoded)}`;
919
+ const absolute = new URL(url, globalThis.location?.href || "http://localhost").href;
920
+ if (absolute.length > MAX_GET_URL_LENGTH) {
921
+ return fetchServerFunction(address, id, {
922
+ ...opts,
923
+ read: true
924
+ }, args, metadata);
925
+ }
926
+ return fetchServerFunction(url, id, {
927
+ ...opts,
928
+ method: "GET"
929
+ }, [], metadata, args);
930
+ };
931
+ const wrapped = (...args) => run(args);
932
+ wrapped[SERVER_FUNCTION_METADATA] = metadata;
933
+ wrapped[SERVER_FUNCTION_INVOKE] = run;
934
+ wrapped.id = id;
935
+ Object.defineProperty(wrapped, "url", {
936
+ get: () => serverFunctionAddress(config.endpoint, id),
937
+ configurable: true
938
+ });
939
+ return withMeta(wrapped, {
940
+ method: "GET"
941
+ });
942
+ }
943
+ function live(fn) {
944
+ if (!isServerFunction(fn)) {
945
+ throw new Error("live expects a server function reference");
946
+ }
947
+ const id = fn.id;
948
+ const metadata = {
949
+ ...getServerFunctionMetadata(fn),
950
+ live: true
951
+ };
952
+ const makeIterable = (args, invokeOptions) => {
953
+ const iterable = {
954
+ [LIVE_SOURCE]: true,
955
+ [Symbol.asyncIterator]() {
956
+ let it;
957
+ let connected = false;
958
+ let attempts = 0;
959
+ let stopped = false;
960
+ let ended = false;
961
+ let timer, wake;
962
+ const DONE = {
963
+ done: true,
964
+ value: undefined
965
+ };
966
+ const invokeSignal = invokeOptions && invokeOptions.signal;
967
+ const controller = new AbortController();
968
+ const wireOptions = {
969
+ ...invokeOptions,
970
+ signal: invokeSignal ? AbortSignal.any([invokeSignal, controller.signal]) : controller.signal
971
+ };
972
+ const emit = (state, error) => {
973
+ try {
974
+ iterable.onstatus && iterable.onstatus(state, error);
975
+ } catch {}
976
+ };
977
+ const emitClosed = error => {
978
+ if (ended) return;
979
+ ended = true;
980
+ emit("closed", error);
981
+ };
982
+ const closeIt = value => {
983
+ const current = it;
984
+ it = undefined;
985
+ if (current) {
986
+ try {
987
+ const r = current.return && current.return(value);
988
+ if (r && typeof r.then === "function") r.then(undefined, () => {});
989
+ } catch {}
990
+ }
991
+ };
992
+ const callOnce = () => {
993
+ if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
994
+ const handler = config.responseHandler;
995
+ if (handler && handler.intercept) {
996
+ const hit = handler.intercept({
997
+ id,
998
+ meta: metadata,
999
+ args
1000
+ });
1001
+ if (hit !== undefined) return hit;
1002
+ }
1003
+ return fetchServerFunction(fn.url, id, {
1004
+ ...wireOptions,
1005
+ read: true
1006
+ }, args, metadata, args);
1007
+ };
1008
+ const pull = async () => {
1009
+ while (!stopped) {
1010
+ try {
1011
+ if (!it) {
1012
+ const result = await callOnce();
1013
+ connected = true;
1014
+ it = result !== null && typeof result === "object" && result[Symbol.asyncIterator] ? result[Symbol.asyncIterator]() : async function* () {
1015
+ yield result;
1016
+ }();
1017
+ if (stopped) {
1018
+ closeIt();
1019
+ controller.abort();
1020
+ return DONE;
1021
+ }
1022
+ emit("connected");
1023
+ }
1024
+ const r = await it.next();
1025
+ if (r.done) {
1026
+ emitClosed();
1027
+ return DONE;
1028
+ }
1029
+ if (stopped) return DONE;
1030
+ attempts = 0;
1031
+ return r;
1032
+ } catch (error) {
1033
+ if (stopped) return DONE;
1034
+ if (!connected) throw error;
1035
+ if (invokeSignal && invokeSignal.aborted) {
1036
+ stopped = true;
1037
+ emitClosed(error);
1038
+ throw error;
1039
+ }
1040
+ if (error !== null && typeof error === "object" && typeof error.status === "number" && error.status >= 400 && error.status < 500 && error.status !== 408 && error.status !== 425 && error.status !== 429 && typeof error.retryAfter !== "number") {
1041
+ stopped = true;
1042
+ emitClosed(error);
1043
+ throw error;
1044
+ }
1045
+ it = undefined;
1046
+ emit("reconnecting", error);
1047
+ await new Promise(resolve => {
1048
+ wake = resolve;
1049
+ const named = error !== null && typeof error === "object" && typeof error.retryAfter === "number" ? Math.min(error.retryAfter * 1000, 60000) : undefined;
1050
+ timer = setTimeout(resolve, named ?? Math.min(500 * 2 ** attempts++, 10000));
1051
+ if (typeof addEventListener === "function") addEventListener("online", resolve, {
1052
+ once: true
1053
+ });
1054
+ if (invokeSignal) invokeSignal.addEventListener("abort", resolve, {
1055
+ once: true
1056
+ });
1057
+ });
1058
+ clearTimeout(timer);
1059
+ if (typeof removeEventListener === "function") removeEventListener("online", wake);
1060
+ if (invokeSignal) invokeSignal.removeEventListener("abort", wake);
1061
+ timer = wake = undefined;
1062
+ }
1063
+ }
1064
+ return DONE;
1065
+ };
1066
+ return {
1067
+ next: () => pull(),
1068
+ return(value) {
1069
+ stopped = true;
1070
+ if (timer !== undefined) clearTimeout(timer);
1071
+ if (wake) wake();
1072
+ closeIt(value);
1073
+ controller.abort();
1074
+ emitClosed();
1075
+ return Promise.resolve({
1076
+ done: true,
1077
+ value
1078
+ });
1079
+ }
1080
+ };
1081
+ }
1082
+ };
1083
+ return iterable;
1084
+ };
1085
+ const wrapped = (...args) => makeIterable(args);
1086
+ wrapped[SERVER_FUNCTION_METADATA] = metadata;
1087
+ wrapped[SERVER_FUNCTION_INVOKE] = makeIterable;
1088
+ wrapped.id = id;
1089
+ Object.defineProperty(wrapped, "url", {
1090
+ get: () => fn.url,
1091
+ configurable: true
1092
+ });
1093
+ return wrapped;
1094
+ }
1095
+ function registerServerReference() {
1096
+ throw new Error("registerServerReference must not be called in the client build");
1097
+ }
1098
+ function getServerFunctionInvocation() {
1099
+ return undefined;
1100
+ }
1101
+
1102
+ export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GET, REDIRECT_HEADER, REVALIDATE_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, clearFlashCookie, configureServerFunctionsClient, createChunk, createServerReference, decodeErrorHeaderValue, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, deserializeStream, encodeErrorHeaderValue, frameAddress, getFlightDataConsumer, getFlightDataSourceIds, getServerFunctionInvocation, getServerFunctionMetadata, getServerFunctionsCodec, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerServerReference, serializeString, serverFunctionActionUrl, serverFunctionUrl, subscribeFlightData, withMeta };