@solidjs/web 2.0.0-rc.2 → 2.0.0-rc.21

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 (124) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +5165 -0
  3. package/dist/server.js +1876 -374
  4. package/dist/{server.cjs → server.observe.js} +2070 -577
  5. package/dist/{dev.cjs → web.dev.js} +955 -567
  6. package/dist/web.js +646 -350
  7. package/dist/{dev.js → web.observe.js} +699 -421
  8. package/frames/dist/assets.js +92 -0
  9. package/frames/dist/client.dev.js +1296 -1198
  10. package/frames/dist/client.js +1128 -1191
  11. package/frames/dist/client.observe.js +2041 -0
  12. package/frames/dist/regions.js +171 -0
  13. package/frames/dist/server.dev.js +2545 -0
  14. package/frames/dist/server.js +1683 -3004
  15. package/frames/dist/server.observe.js +2544 -0
  16. package/frames/dist/trace.js +45 -0
  17. package/frames/dist/wire.js +594 -0
  18. package/frames/package.json +2 -25
  19. package/package.json +244 -256
  20. package/performance-tracks/dist/performance-tracks.dev.js +679 -0
  21. package/performance-tracks/dist/performance-tracks.js +6 -0
  22. package/performance-tracks/dist/performance-tracks.observe.js +667 -0
  23. package/performance-tracks/package.json +7 -0
  24. package/performance-tracks/types/index.d.ts +69 -0
  25. package/serialization/decode/package.json +2 -15
  26. package/serialization/dist/decode.js +121 -25
  27. package/serialization/dist/serialization.js +282 -88
  28. package/serialization/package.json +2 -15
  29. package/serialization/types/index.d.ts +115 -153
  30. package/serialization/types/serializer-decode.d.ts +173 -114
  31. package/serialization/types/serializer.d.ts +144 -0
  32. package/server-functions/dist/client.dev.js +1462 -0
  33. package/server-functions/dist/client.js +667 -165
  34. package/server-functions/dist/client.observe.js +1441 -0
  35. package/server-functions/dist/rich-args.js +102 -1
  36. package/server-functions/dist/server.dev.js +2802 -299
  37. package/server-functions/dist/server.js +2724 -314
  38. package/server-functions/dist/server.observe.js +3680 -0
  39. package/server-functions/package.json +2 -35
  40. package/server-functions/rich-args/package.json +2 -15
  41. package/skills/server-components/SKILL.md +117 -0
  42. package/storage/package.json +2 -15
  43. package/types/client.d.ts +342 -288
  44. package/types/constants.d.ts +22 -0
  45. package/types/cookies.d.ts +32 -84
  46. package/types/diagnostics.d.ts +80 -0
  47. package/types/frames/assets-tier.d.ts +78 -0
  48. package/types/frames/client.d.ts +40 -1
  49. package/types/frames/frame-client.d.ts +443 -280
  50. package/types/frames/frame-container-plugin.d.ts +64 -0
  51. package/types/frames/frame-morph.d.ts +29 -0
  52. package/types/frames/frame-sink.d.ts +141 -161
  53. package/types/frames/frame-transport.d.ts +263 -184
  54. package/types/frames/regions-tier.d.ts +60 -0
  55. package/types/frames/serializer-decode.d.ts +241 -0
  56. package/types/frames/serializer.d.ts +115 -153
  57. package/types/frames/server.d.ts +2 -2
  58. package/types/frames/trace-tier.d.ts +2 -0
  59. package/types/frames/tree-rewrite.d.ts +39 -0
  60. package/types/frames/wire-tier.d.ts +169 -0
  61. package/types/head.d.ts +20 -0
  62. package/types/index.d.ts +98 -81
  63. package/types/index.server.d.ts +159 -0
  64. package/types/jsx.d.ts +49 -44
  65. package/types/observe.d.ts +535 -0
  66. package/types/reconcile.d.ts +1 -0
  67. package/types/render.d.ts +11 -0
  68. package/types/request-error-hook.d.ts +5 -0
  69. package/types/response.d.ts +95 -147
  70. package/types/serializer-decode.d.ts +173 -114
  71. package/types/serializer.d.ts +115 -153
  72. package/types/server-functions/argument-codec.d.ts +30 -0
  73. package/types/server-functions/client.d.ts +237 -223
  74. package/types/server-functions/flash.d.ts +28 -30
  75. package/types/server-functions/registry.d.ts +105 -0
  76. package/types/server-functions/rich-args.d.ts +1 -10
  77. package/types/server-functions/server.d.ts +538 -531
  78. package/types/server-functions/shared.d.ts +398 -425
  79. package/types/server-functions/uploads.d.ts +53 -0
  80. package/types/server-mock.d.ts +154 -20
  81. package/types/server-observe.d.ts +86 -0
  82. package/types/server.d.ts +601 -422
  83. package/types/trace.d.ts +127 -0
  84. package/LICENSE +0 -21
  85. package/dist/web.cjs +0 -2033
  86. package/frames/dist/client.cjs +0 -2002
  87. package/frames/dist/client.dev.cjs +0 -2022
  88. package/frames/dist/server.cjs +0 -3877
  89. package/serialization/dist/decode.cjs +0 -139
  90. package/serialization/dist/serialization.cjs +0 -261
  91. package/serialization/types-cjs/index.d.cts +0 -182
  92. package/serialization/types-cjs/package.json +0 -3
  93. package/serialization/types-cjs/serializer-decode.d.cts +0 -182
  94. package/server-functions/dist/client.cjs +0 -834
  95. package/server-functions/dist/rich-args.cjs +0 -11
  96. package/server-functions/dist/server.cjs +0 -1242
  97. package/server-functions/dist/server.dev.cjs +0 -1242
  98. package/storage/dist/storage.cjs +0 -12
  99. package/storage/types-cjs/index.d.cts +0 -28
  100. package/storage/types-cjs/package.json +0 -3
  101. package/types/core.d.ts +0 -9
  102. package/types-cjs/client.d.cts +0 -337
  103. package/types-cjs/cookies.d.cts +0 -93
  104. package/types-cjs/core.d.cts +0 -9
  105. package/types-cjs/frames/client.d.cts +0 -36
  106. package/types-cjs/frames/frame-client.d.cts +0 -356
  107. package/types-cjs/frames/frame-sink.d.cts +0 -194
  108. package/types-cjs/frames/frame-transport.d.cts +0 -222
  109. package/types-cjs/frames/serializer.d.cts +0 -182
  110. package/types-cjs/frames/server.d.cts +0 -52
  111. package/types-cjs/index.d.cts +0 -244
  112. package/types-cjs/jsx-properties.d.cts +0 -93
  113. package/types-cjs/jsx.d.cts +0 -4159
  114. package/types-cjs/package.json +0 -3
  115. package/types-cjs/response.d.cts +0 -174
  116. package/types-cjs/serializer-decode.d.cts +0 -182
  117. package/types-cjs/serializer.d.cts +0 -182
  118. package/types-cjs/server-functions/client.d.cts +0 -262
  119. package/types-cjs/server-functions/flash.d.cts +0 -38
  120. package/types-cjs/server-functions/rich-args.d.cts +0 -10
  121. package/types-cjs/server-functions/server.d.cts +0 -681
  122. package/types-cjs/server-functions/shared.d.cts +0 -523
  123. package/types-cjs/server-mock.d.cts +0 -286
  124. package/types-cjs/server.d.cts +0 -544
@@ -16,14 +16,42 @@ function withMeta(fn, meta) {
16
16
  Object.assign(metadata, meta);
17
17
  return fn;
18
18
  }
19
+ const SERVER_FUNCTION_INVOKE = Symbol.for("solid.ServerFunctionInvoke");
20
+ const INVOKE_OPTION_REDIRECTS = {
21
+ 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.",
22
+ method: "The method is declaration-scoped: declare the function with GET(fn).",
23
+ body: "The arguments are the body: pass them in the args array.",
24
+ timeout: "Compose timeouts through `signal` with AbortSignal.timeout(ms) (and AbortSignal.any to " + "combine it with a caller signal)."
25
+ };
26
+ function invoke(fn, options, ...args) {
27
+ const channel = typeof fn === "function" && fn[SERVER_FUNCTION_INVOKE];
28
+ if (!channel) {
29
+ 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.");
30
+ }
31
+ if (options === null || typeof options !== "object") {
32
+ throw new Error("invoke's second argument is the invocation options bag: invoke(fn, { signal }, ...args)");
33
+ }
34
+ const picked = {};
35
+ for (const key in options) {
36
+ if (key !== "signal" && key !== "keepalive" && key !== "priority") {
37
+ 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."));
38
+ }
39
+ }
40
+ if (options.signal !== undefined) picked.signal = options.signal;
41
+ if (options.keepalive !== undefined) picked.keepalive = options.keepalive;
42
+ if (options.priority !== undefined) picked.priority = options.priority;
43
+ return channel(args, picked);
44
+ }
19
45
  const LIVE_SOURCE = Symbol.for("solid.LiveSource");
46
+ const LIVE_RESUME_FROM = Symbol.for("solid.LiveResumeFrom");
47
+ const LIVE_LOCAL = Symbol.for("solid.LiveLocal");
20
48
  const SERVER_FUNCTION_RPC = Symbol.for("solid.ServerFunctionRPC");
21
49
  function provideServerFunctionRPC(rpc) {
22
50
  globalThis[SERVER_FUNCTION_RPC] || (globalThis[SERVER_FUNCTION_RPC] = rpc);
23
51
  }
24
52
 
25
53
  const FLASH_COOKIE = "flash";
26
- const FLASH_MATCHER = new RegExp(`(?:^|;\\s*)${FLASH_COOKIE}=([^;]+)`);
54
+ const FLASH_MATCHER = /(?:^|;\s*)flash=([^;]+)/;
27
55
  function hasFlashCookie(cookieHeader) {
28
56
  return !!cookieHeader && FLASH_MATCHER.test(cookieHeader);
29
57
  }
@@ -40,17 +68,45 @@ function configureServerFunctionsCodec(codec) {
40
68
  function getServerFunctionsCodec() {
41
69
  return codecConfig.codec;
42
70
  }
71
+ const UNNAMED_FLIGHT_SOURCE = "true";
43
72
  const flightConfig = {
44
- consumer: undefined
73
+ consumers: new Map()
45
74
  };
46
- function subscribeFlightData(consumer) {
47
- flightConfig.consumer = consumer;
75
+ function assertFlightSource(source) {
76
+ if (source === UNNAMED_FLIGHT_SOURCE || source === "" || source.includes(",")) {
77
+ 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).`);
78
+ }
79
+ }
80
+ function subscribeFlightData(sourceOrConsumer, maybeConsumer) {
81
+ const named = typeof sourceOrConsumer === "string";
82
+ if (named) assertFlightSource(sourceOrConsumer);
83
+ const source = named ? sourceOrConsumer : UNNAMED_FLIGHT_SOURCE;
84
+ const consumer = named ? maybeConsumer : sourceOrConsumer;
85
+ flightConfig.consumers.set(source, consumer);
48
86
  return () => {
49
- if (flightConfig.consumer === consumer) flightConfig.consumer = undefined;
87
+ if (flightConfig.consumers.get(source) === consumer) flightConfig.consumers.delete(source);
50
88
  };
51
89
  }
52
- function getFlightDataConsumer() {
53
- return flightConfig.consumer;
90
+ function getFlightDataConsumer(source) {
91
+ return flightConfig.consumers.get(source === undefined ? UNNAMED_FLIGHT_SOURCE : source);
92
+ }
93
+ function getFlightDataSourceIds() {
94
+ return [...flightConfig.consumers.keys()];
95
+ }
96
+ function hasFlightMetadata(response) {
97
+ return response.headers.has(REDIRECT_HEADER) || response.headers.has(REVALIDATE_HEADER);
98
+ }
99
+ async function deliverFlightData(response, data) {
100
+ if (data) await Promise.allSettled(Object.values(data).flatMap(s => s && typeof s == "object" ? Object.values(s) : []));
101
+ const folded = (response.headers.get(SINGLE_FLIGHT_HEADER) || "").split(",");
102
+ const metadata = hasFlightMetadata(response);
103
+ for (const source of getFlightDataSourceIds()) {
104
+ if (!metadata && !folded.includes(source)) continue;
105
+ const consumer = getFlightDataConsumer(source);
106
+ if (consumer) await consumer(data ? data[source] : undefined, {
107
+ response
108
+ });
109
+ }
54
110
  }
55
111
  function frameAddress(id, args) {
56
112
  return args && args.length ? id + ":" + hashArguments(args) : id;
@@ -96,7 +152,78 @@ function stableString(value, seen) {
96
152
  }
97
153
  return out + "}";
98
154
  }
99
- const FUNCTION_HEADER = "X-Server-Function-Id";
155
+ function serverFunctionAddress(endpoint, id) {
156
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
157
+ return `${mount}/${encodeURIComponent(id)}`;
158
+ }
159
+ function serverFunctionDataAddress(endpoint, id) {
160
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
161
+ return `${mount}/data/${encodeURIComponent(id)}`;
162
+ }
163
+ function serverFunctionLiveAddress(endpoint, id) {
164
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
165
+ return `${mount}/live/${encodeURIComponent(id)}`;
166
+ }
167
+ function parseServerFunctionAddress(pathname, endpoint) {
168
+ const mount = endpoint.endsWith("/") ? endpoint.slice(0, -1) : endpoint;
169
+ if (!pathname.startsWith(mount)) return null;
170
+ const rest = pathname.slice(mount.length);
171
+ if (!rest.startsWith("/")) return null;
172
+ let segment = rest.slice(1);
173
+ let data = false;
174
+ let live = false;
175
+ if (segment.startsWith("data/")) {
176
+ segment = segment.slice(5);
177
+ data = true;
178
+ } else if (segment.startsWith("live/")) {
179
+ segment = segment.slice(5);
180
+ live = true;
181
+ }
182
+ if (!segment || segment.includes("/")) return null;
183
+ try {
184
+ return {
185
+ id: decodeURIComponent(segment),
186
+ data,
187
+ live
188
+ };
189
+ } catch {
190
+ return null;
191
+ }
192
+ }
193
+ const MAX_GET_URL_LENGTH = 2000;
194
+ function urlTargetId(target, helper) {
195
+ if (typeof target === "string") return target;
196
+ if (isServerFunction(target) && typeof target.id === "string") return target.id;
197
+ throw new Error(`${helper} expects a server function reference (or its id).`);
198
+ }
199
+ function serverFunctionActionUrlFor(endpoint, target, boundArgs) {
200
+ const address = serverFunctionAddress(endpoint, urlTargetId(target, "serverFunctionActionUrl"));
201
+ if (!boundArgs.length) return address;
202
+ if (!isJSONSafe(boundArgs)) {
203
+ 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.");
204
+ }
205
+ return `${address}?args=${encodeURIComponent(JSON.stringify(boundArgs))}`;
206
+ }
207
+ function serverFunctionUrlFor(endpoint, fn, args) {
208
+ if (!isServerFunction(fn) || typeof fn.id !== "string") {
209
+ throw new Error("serverFunctionUrl expects a server function reference.");
210
+ }
211
+ const metadata = getServerFunctionMetadata(fn);
212
+ if (!metadata || metadata.method !== "GET") {
213
+ 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).');
214
+ }
215
+ const address = metadata.live ? serverFunctionLiveAddress(endpoint, fn.id) : serverFunctionDataAddress(endpoint, fn.id);
216
+ if (!args.length) return address;
217
+ if (!isJSONSafe(args)) {
218
+ 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.");
219
+ }
220
+ const url = `${address}?args=${encodeURIComponent(JSON.stringify(args))}`;
221
+ const length = new URL(url, globalThis.location?.href || "http://localhost").href.length;
222
+ if (length > MAX_GET_URL_LENGTH) {
223
+ 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.");
224
+ }
225
+ return url;
226
+ }
100
227
  const ERROR_HEADER = "X-Server-Function-Error";
101
228
  const ERROR_HEADER_MARKER = "=?1?";
102
229
  const NEEDS_ENCODING = /[^\x20-\x7e\xa0-\xff]/;
@@ -122,8 +249,31 @@ function decodeErrorHeaderValue(value) {
122
249
  return value;
123
250
  }
124
251
  }
125
- const INSTANCE_HEADER = "X-Server-Function-Instance";
126
252
  const BODY_FORMAT_HEADER = "X-Server-Function-Format";
253
+ const LAST_EVENT_ID_HEADER = "Last-Event-ID";
254
+ const LIVE_WIRE = Symbol("solid.LiveWire");
255
+ const UNKNOWN_HEADER = "X-Server-Function-Unknown";
256
+ const REDIRECT_HEADER = "X-Server-Function-Redirect";
257
+ function decodeRedirectHeaderValue(value) {
258
+ if (typeof value !== "string") return undefined;
259
+ const at = value.indexOf(" ");
260
+ if (at < 0) return undefined;
261
+ const status = Number(value.slice(0, at));
262
+ const url = value.slice(at + 1);
263
+ if (!Number.isInteger(status) || !url) return undefined;
264
+ if (status !== 301 && status !== 302 && status !== 303 && status !== 307 && status !== 308) return undefined;
265
+ let parsed;
266
+ try {
267
+ parsed = new URL(url);
268
+ } catch {
269
+ return undefined;
270
+ }
271
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return undefined;
272
+ return {
273
+ status,
274
+ url
275
+ };
276
+ }
127
277
  const SINGLE_FLIGHT_HEADER = "X-Single-Flight";
128
278
  const FILE_FORM_KEY = "__server_function_file__";
129
279
  const BodyFormat = {
@@ -135,7 +285,8 @@ const BodyFormat = {
135
285
  File: "5",
136
286
  ArrayBuffer: "6",
137
287
  Uint8Array: "7",
138
- Json: "8"
288
+ Json: "8",
289
+ Void: "9"
139
290
  };
140
291
  const JSON_SAFE_DEPTH_LIMIT = 4096;
141
292
  const EXIT = {};
@@ -152,7 +303,7 @@ function isJSONSafe(value) {
152
303
  const t = typeof v;
153
304
  if (t === "string" || t === "boolean") continue;
154
305
  if (t === "number") {
155
- if (!Number.isFinite(v)) return false;
306
+ if (!Number.isFinite(v) || Object.is(v, -0)) return false;
156
307
  continue;
157
308
  }
158
309
  if (t !== "object") return false;
@@ -165,7 +316,11 @@ function isJSONSafe(value) {
165
316
  const proto = Object.getPrototypeOf(v);
166
317
  if (proto !== Object.prototype && proto !== null) return false;
167
318
  if (Symbol.asyncIterator in v || Symbol.iterator in v) return false;
168
- for (const k in v) stack.push(v[k]);
319
+ for (const k in v) {
320
+ const descriptor = Object.getOwnPropertyDescriptor(v, k);
321
+ if (descriptor === undefined || !("value" in descriptor)) return false;
322
+ stack.push(descriptor.value);
323
+ }
169
324
  }
170
325
  }
171
326
  return true;
@@ -231,92 +386,224 @@ function getHeadersAndBody(body) {
231
386
  return undefined;
232
387
  }
233
388
  }
234
- async function extractBody(source, codecOptions) {
389
+ async function extractBody(source, codecOptions, wire) {
235
390
  const contentType = source.headers.get("content-type");
236
391
  const format = source.headers.get(BODY_FORMAT_HEADER);
237
- const clone = source.clone();
238
392
  switch (true) {
239
393
  case format === BodyFormat.Serialized:
240
- return await deserializeStream(clone, codecOptions);
394
+ return await deserializeStream(source, codecOptions, wire);
241
395
  case format === BodyFormat.Json:
242
- return JSON.parse(await clone.text());
396
+ return JSON.parse(await source.text());
243
397
  case format === BodyFormat.String:
244
- return await clone.text();
398
+ return await source.text();
245
399
  case format === BodyFormat.File:
246
400
  {
247
- const formData = await clone.formData();
401
+ const formData = await source.formData();
248
402
  return formData.get(FILE_FORM_KEY);
249
403
  }
250
404
  case format === BodyFormat.FormData:
251
405
  case contentType && contentType.startsWith("multipart/form-data"):
252
- return await clone.formData();
406
+ return await source.formData();
253
407
  case format === BodyFormat.URLSearchParams:
254
408
  case contentType && contentType.startsWith("application/x-www-form-urlencoded"):
255
- return new URLSearchParams(await clone.text());
409
+ return new URLSearchParams(await source.text());
256
410
  case format === BodyFormat.Blob:
257
- return await clone.blob();
411
+ return await source.blob();
258
412
  case format === BodyFormat.ArrayBuffer:
259
- return await clone.arrayBuffer();
413
+ return await source.arrayBuffer();
260
414
  case format === BodyFormat.Uint8Array:
261
- return new Uint8Array(await clone.arrayBuffer());
415
+ return new Uint8Array(await source.arrayBuffer());
262
416
  }
263
417
  return undefined;
264
418
  }
265
419
  function createChunk(data) {
266
- const encoder = new TextEncoder();
267
- const encodeData = encoder.encode(data);
420
+ const encodeData = CHUNK_ENCODER.encode(data);
268
421
  const bytes = encodeData.length;
422
+ if (bytes > MAX_CHUNK_BYTES) {
423
+ throw new RangeError("Server function chunk is too large to frame.");
424
+ }
269
425
  const chunk = new Uint8Array(12 + bytes);
270
- chunk.set(encoder.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
426
+ chunk.set(CHUNK_ENCODER.encode(`;0x${bytes.toString(16).padStart(8, "0")};`));
271
427
  chunk.set(encodeData, 12);
272
428
  return chunk;
273
429
  }
430
+ const CHUNK_ENCODER = /* @__PURE__ */new TextEncoder();
431
+ const CHUNK_DECODER = /* @__PURE__ */new TextDecoder("utf-8", {
432
+ fatal: true
433
+ });
434
+ const MAX_CHUNK_BYTES = 0xffffffff;
435
+ const RETAINED_STORE_BYTES = 64 * 1024;
436
+ const DONE = {
437
+ done: true,
438
+ value: undefined
439
+ };
440
+ function malformedStream() {
441
+ return new Error("Malformed server function stream.");
442
+ }
274
443
  class ChunkReader {
275
444
  constructor(stream) {
276
445
  this.reader = stream.getReader();
277
- this.buffer = new Uint8Array(0);
446
+ this.store = new Uint8Array(0);
447
+ this.buffer = this.store;
278
448
  this.done = false;
449
+ this.cancelled = false;
279
450
  }
280
451
  async readChunk() {
281
452
  const chunk = await this.reader.read();
282
- if (!chunk.done) {
283
- const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
284
- newBuffer.set(this.buffer);
285
- newBuffer.set(chunk.value, this.buffer.length);
286
- this.buffer = newBuffer;
287
- } else {
453
+ if (chunk.done) {
288
454
  this.done = true;
455
+ return this.cancelled;
456
+ }
457
+ const incoming = chunk.value;
458
+ const store = this.store;
459
+ const start = this.buffer.byteOffset;
460
+ const end = start + this.buffer.length;
461
+ const needed = this.buffer.length + incoming.length;
462
+ if (end + incoming.length <= store.length) {
463
+ store.set(incoming, end);
464
+ this.buffer = store.subarray(start, end + incoming.length);
465
+ } else if (needed <= store.length) {
466
+ store.copyWithin(0, start, end);
467
+ store.set(incoming, this.buffer.length);
468
+ this.buffer = store.subarray(0, needed);
469
+ } else {
470
+ const grown = new Uint8Array(Math.max(needed, store.length * 2));
471
+ grown.set(this.buffer);
472
+ grown.set(incoming, this.buffer.length);
473
+ this.store = grown;
474
+ this.buffer = grown.subarray(0, needed);
289
475
  }
476
+ return this.cancelled;
290
477
  }
291
478
  async next() {
479
+ if (this.cancelled) return DONE;
292
480
  while (this.buffer.length < 12) {
293
481
  if (this.done) {
294
- if (this.buffer.length === 0) return {
295
- done: true,
296
- value: undefined
297
- };
298
- throw new Error("Malformed server function stream.");
482
+ if (this.buffer.length === 0) return DONE;
483
+ throw malformedStream();
299
484
  }
300
- await this.readChunk();
301
- }
302
- const decoder = new TextDecoder();
303
- const bytes = Number.parseInt(decoder.decode(this.buffer.subarray(1, 11)), 16);
304
- if (Number.isNaN(bytes)) {
305
- throw new Error("Malformed server function stream.");
485
+ if (await this.readChunk()) return DONE;
306
486
  }
487
+ const header = String.fromCharCode(...this.buffer.subarray(0, 12));
488
+ if (!/^;0x[\dA-Fa-f]{8};$/.test(header)) throw malformedStream();
489
+ const bytes = parseInt(header.slice(3, 11), 16);
307
490
  while (bytes > this.buffer.length - 12) {
308
491
  if (this.done) {
309
- throw new Error("Malformed server function stream.");
492
+ throw malformedStream();
310
493
  }
311
- await this.readChunk();
494
+ if (await this.readChunk()) return DONE;
495
+ }
496
+ let partial;
497
+ try {
498
+ partial = CHUNK_DECODER.decode(this.buffer.subarray(12, 12 + bytes));
499
+ } catch {
500
+ throw malformedStream();
312
501
  }
313
- const partial = decoder.decode(this.buffer.subarray(12, 12 + bytes));
314
502
  this.buffer = this.buffer.subarray(12 + bytes);
503
+ if (this.store.length > RETAINED_STORE_BYTES && this.buffer.length <= RETAINED_STORE_BYTES) {
504
+ this.store = this.buffer = this.buffer.slice();
505
+ }
315
506
  return {
316
507
  done: false,
317
508
  value: partial
318
509
  };
319
510
  }
511
+ async drain(interpret) {
512
+ try {
513
+ while (true) {
514
+ const result = await this.next();
515
+ if (result.done) {
516
+ break;
517
+ }
518
+ interpret(result.value);
519
+ }
520
+ } catch (error) {
521
+ this.cancel(error).catch(() => {});
522
+ throw error;
523
+ }
524
+ }
525
+ cancel(reason) {
526
+ this.cancelled = true;
527
+ return this.reader.cancel(reason);
528
+ }
529
+ }
530
+ function createEventChunk(data, id) {
531
+ let event = id !== undefined && !id.includes("\0") ? `id: ${id}\n` : "";
532
+ for (const line of data.split(/\r\n|\r|\n/)) event += `data: ${line}\n`;
533
+ return CHUNK_ENCODER.encode(event + "\n");
534
+ }
535
+ const EVENT_STREAM_HEARTBEAT = /* @__PURE__ */new TextEncoder().encode(":\n\n");
536
+ function isEventStream(source) {
537
+ const contentType = source.headers.get("content-type");
538
+ return !!contentType && contentType.startsWith("text/event-stream");
539
+ }
540
+ class EventStreamReader {
541
+ constructor(stream, wire) {
542
+ this.reader = stream.getReader();
543
+ this.decoder = new TextDecoder();
544
+ this.wire = wire;
545
+ this.buffer = "";
546
+ this.done = false;
547
+ this.data = null;
548
+ this.id = undefined;
549
+ }
550
+ async read() {
551
+ const chunk = await this.reader.read();
552
+ if (chunk.done) {
553
+ this.done = true;
554
+ this.buffer += this.decoder.decode();
555
+ } else {
556
+ this.buffer += this.decoder.decode(chunk.value, {
557
+ stream: true
558
+ });
559
+ }
560
+ }
561
+ takeLine() {
562
+ const buffer = this.buffer;
563
+ const cr = buffer.indexOf("\r");
564
+ const lf = buffer.indexOf("\n");
565
+ const end = cr < 0 ? lf : lf < 0 ? cr : Math.min(cr, lf);
566
+ if (end < 0) return null;
567
+ let skip = 1;
568
+ if (buffer[end] === "\r") {
569
+ if (end + 1 === buffer.length) {
570
+ if (!this.done) return null;
571
+ } else if (buffer[end + 1] === "\n") skip = 2;
572
+ }
573
+ this.buffer = buffer.slice(end + skip);
574
+ return buffer.slice(0, end);
575
+ }
576
+ async next() {
577
+ while (true) {
578
+ const line = this.takeLine();
579
+ if (line === null) {
580
+ if (this.done) return {
581
+ done: true,
582
+ value: undefined
583
+ };
584
+ await this.read();
585
+ continue;
586
+ }
587
+ if (line === "") {
588
+ const data = this.data;
589
+ const id = this.id;
590
+ this.data = null;
591
+ this.id = undefined;
592
+ if (data === null) continue;
593
+ if (id !== undefined && this.wire) this.wire.position = id;
594
+ return {
595
+ done: false,
596
+ value: data.join("\n")
597
+ };
598
+ }
599
+ if (line[0] === ":") continue;
600
+ const colon = line.indexOf(":");
601
+ const field = colon < 0 ? line : line.slice(0, colon);
602
+ let value = colon < 0 ? "" : line.slice(colon + 1);
603
+ if (value[0] === " ") value = value.slice(1);
604
+ if (field === "data") (this.data ??= []).push(value);else if (field === "id" && !value.includes("\0")) this.id = value;
605
+ }
606
+ }
320
607
  async drain(interpret) {
321
608
  while (true) {
322
609
  const result = await this.next();
@@ -326,6 +613,37 @@ class ChunkReader {
326
613
  interpret(result.value);
327
614
  }
328
615
  }
616
+ cancel(reason) {
617
+ return this.reader.cancel(reason);
618
+ }
619
+ }
620
+ function positionDigest(value) {
621
+ if (value === undefined || !isJSONSafe(value)) return undefined;
622
+ const text = JSON.stringify(value);
623
+ if (typeof text !== "string") return undefined;
624
+ return textDigest(text);
625
+ }
626
+ function textDigest(text) {
627
+ let a = 0x811c9dc5;
628
+ let b = 0x050c5d1f;
629
+ for (let i = 0; i < text.length; i++) {
630
+ const code = text.charCodeAt(i);
631
+ a = Math.imul(a ^ code, 0x01000193);
632
+ b = Math.imul(b ^ code, 0x01000193);
633
+ }
634
+ return (a >>> 0).toString(16).padStart(8, "0") + (b >>> 0).toString(16).padStart(8, "0");
635
+ }
636
+ const ERROR_TRAILER_PREFIX = "!";
637
+ function errorFromTrailer(payload) {
638
+ let shape;
639
+ try {
640
+ shape = JSON.parse(payload.slice(1));
641
+ } catch {
642
+ shape = null;
643
+ }
644
+ const error = new Error(shape && typeof shape.message === "string" ? shape.message : "Server function result could not be delivered.");
645
+ if (shape && typeof shape.name === "string") error.name = shape.name;
646
+ return error;
329
647
  }
330
648
  function serializeStream(value, codecOptions) {
331
649
  return new ReadableStream({
@@ -352,28 +670,53 @@ async function serializeString(value, codecOptions) {
352
670
  const response = new Response(serializeStream(value, codecOptions));
353
671
  return await response.text();
354
672
  }
355
- async function deserializeStream(source, codecOptions) {
673
+ async function deserializeStream(source, codecOptions, wire) {
356
674
  if (!source.body) {
357
675
  throw new Error("missing body");
358
676
  }
359
- const reader = new ChunkReader(source.body);
360
- const result = await reader.next();
361
- if (!result.done) {
362
- const {
363
- createJSONDeserializer
364
- } = await import('@solidjs/web/serialization/decode');
365
- const deserializeChunk = createJSONDeserializer(codecOptions);
366
- function interpretChunk(chunk) {
367
- return deserializeChunk(JSON.parse(chunk));
677
+ const reader = wire && isEventStream(source) ? wire.open(source.body) : new ChunkReader(source.body);
678
+ try {
679
+ const result = await reader.next();
680
+ if (!result.done) {
681
+ if (result.value.startsWith(ERROR_TRAILER_PREFIX)) {
682
+ throw errorFromTrailer(result.value);
683
+ }
684
+ const {
685
+ createJSONDeserializer
686
+ } = await import('@solidjs/web/serialization/decode');
687
+ const deserializeChunk = createJSONDeserializer(codecOptions);
688
+ function interpretChunk(chunk) {
689
+ if (chunk.startsWith(ERROR_TRAILER_PREFIX)) {
690
+ throw errorFromTrailer(chunk);
691
+ }
692
+ return deserializeChunk(JSON.parse(chunk));
693
+ }
694
+ const connection = wire && wire.connection;
695
+ let endConnection;
696
+ if (connection) connection.ended = new Promise(resolve => endConnection = resolve);
697
+ const end = error => {
698
+ const sweep = () => deserializeChunk.abort(error);
699
+ if (connection) {
700
+ const close = () => deserializeChunk.close();
701
+ endConnection({
702
+ open: deserializeChunk.open(),
703
+ error,
704
+ sweep,
705
+ close
706
+ });
707
+ } else sweep();
708
+ };
709
+ reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
710
+ return interpretChunk(result.value);
368
711
  }
369
- reader.drain(interpretChunk).then(() => deserializeChunk.abort(new Error("Server function stream ended unexpectedly.")), error => deserializeChunk.abort(error));
370
- return interpretChunk(result.value);
712
+ } catch (error) {
713
+ reader.cancel(error).catch(() => {});
714
+ throw error;
371
715
  }
372
- return undefined;
373
716
  }
374
717
  async function decodeResponse(response, codecOptions) {
375
718
  if (!response.body) return undefined;
376
- return await extractBody(response, codecOptions === undefined ? codecConfig.codec : codecOptions);
719
+ return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
377
720
  }
378
721
  async function decodeResponsePayload(response, codecOptions) {
379
722
  const decoded = await decodeResponse(response, codecOptions);
@@ -390,76 +733,97 @@ async function decodeResponsePayload(response, codecOptions) {
390
733
 
391
734
  const config = {
392
735
  endpoint: "/_server",
736
+ fetch: undefined,
393
737
  prepareRequest: undefined,
394
738
  responseHandler: undefined,
395
739
  serializeArgs: undefined
396
740
  };
397
- const CALL_OBSERVERS = new Set();
398
- function notifyCallObservers(type, id, instance, value, meta) {
399
- if (CALL_OBSERVERS.size === 0) return;
400
- const field = type === "request" ? "request" : "response";
401
- const time = performance.now();
402
- for (const observer of new Set(CALL_OBSERVERS)) {
403
- try {
404
- observer({
405
- type,
406
- id,
407
- instance,
408
- [field]: value.clone(),
409
- meta,
410
- time
411
- });
412
- } catch (error) {
413
- console.error(error);
414
- }
415
- }
741
+ function serverFunctionUrl(fn, ...args) {
742
+ return serverFunctionUrlFor(config.endpoint, fn, args);
743
+ }
744
+ function serverFunctionActionUrl(fn, ...boundArgs) {
745
+ return serverFunctionActionUrlFor(config.endpoint, fn, boundArgs);
416
746
  }
417
- function observeServerFunctionCalls(observer) {
418
- CALL_OBSERVERS.add(observer);
419
- return () => CALL_OBSERVERS.delete(observer);
747
+ function parseServerFunctionActionUrl(url) {
748
+ const parsed = parseServerFunctionAddress(new URL(url, globalThis.location?.href || "http://localhost").pathname, config.endpoint);
749
+ return parsed && parsed.id;
420
750
  }
421
751
  function serializeArguments(args) {
422
752
  if (!config.serializeArgs) {
423
- 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.");
753
+ 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, files, etc. through the codec — " + "or pass a single Blob/FormData/File argument, which has a native " + "HTTP encoding.");
424
754
  }
425
755
  return config.serializeArgs(args);
426
756
  }
427
757
  function configureServerFunctionsClient({
428
758
  endpoint,
429
759
  codec,
760
+ fetch,
430
761
  prepareRequest,
431
762
  responseHandler,
432
763
  serializeArgs
433
764
  } = {}) {
434
765
  if (endpoint !== undefined) config.endpoint = endpoint;
435
766
  if (codec !== undefined) configureServerFunctionsCodec(codec);
767
+ if (fetch !== undefined) config.fetch = fetch;
436
768
  if (prepareRequest !== undefined) config.prepareRequest = prepareRequest;
437
769
  if (responseHandler !== undefined) config.responseHandler = responseHandler;
438
770
  if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
439
771
  }
440
- let INSTANCE = 0;
441
- let rpcProvided = false;
772
+ let rpc;
442
773
  function provideRPC() {
443
- if (rpcProvided) return;
444
- rpcProvided = true;
445
- provideServerFunctionRPC({
774
+ if (rpc) return;
775
+ provideServerFunctionRPC(rpc = {
446
776
  GET,
447
777
  decodeResponse
448
778
  });
449
779
  }
780
+ function siblingAddressFor(base, kind) {
781
+ const splitAt = base.search(/[?#]/);
782
+ const path = splitAt < 0 ? base : base.slice(0, splitAt);
783
+ const rest = splitAt < 0 ? "" : base.slice(splitAt);
784
+ const slash = path.lastIndexOf("/");
785
+ if (path.endsWith(`/${kind}/`, slash + 1)) return base;
786
+ return `${path.slice(0, slash + 1)}${kind}/${path.slice(slash + 1)}${rest}`;
787
+ }
788
+ const dataAddressFor = base => siblingAddressFor(base, "data");
450
789
  function serverFunctionFailure(response, value) {
451
- const error = value ?? new Error(`Server function call failed with status ${response.status}`);
452
- if (error instanceof Error && !("status" in error)) error.status = response.status;
790
+ const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
791
+ 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}`);
792
+ if (error instanceof Error && !("status" in error)) {
793
+ error.status = response.status;
794
+ const retryAfter = parseRetryAfter(response.headers.get("Retry-After"));
795
+ if (retryAfter !== undefined) error.retryAfter = retryAfter;
796
+ }
797
+ if (unknown && error instanceof Error) error.unknownFunction = true;
453
798
  return error;
454
799
  }
455
- async function createRequest(base, id, instance, options, meta) {
800
+ function parseRetryAfter(header) {
801
+ if (!header) return undefined;
802
+ const trimmed = header.trim();
803
+ if (/^\d+$/.test(trimmed)) return Number(trimmed);
804
+ const date = Date.parse(trimmed);
805
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - Date.now()) / 1000));
806
+ return undefined;
807
+ }
808
+ function isReadCall(options) {
809
+ return !!options.read || !!options.method && options.method.toUpperCase() === "GET";
810
+ }
811
+ async function createRequest(base, id, options, meta) {
456
812
  const headers = {
457
- ...options.headers,
458
- [FUNCTION_HEADER]: id,
459
- [INSTANCE_HEADER]: instance
813
+ ...options.headers
460
814
  };
461
- if (getFlightDataConsumer() && !options.read && (!options.method || options.method.toUpperCase() !== "GET")) {
462
- headers[SINGLE_FLIGHT_HEADER] = "true";
815
+ const wire = options[LIVE_WIRE];
816
+ if (wire) {
817
+ options = {
818
+ ...options
819
+ };
820
+ delete options[LIVE_WIRE];
821
+ if (wire.position !== undefined) headers[LAST_EVENT_ID_HEADER] = wire.position;
822
+ if (wire.headers) Object.assign(headers, wire.headers);
823
+ }
824
+ const flightSources = getFlightDataSourceIds();
825
+ if (flightSources.length > 0 && !isReadCall(options)) {
826
+ headers[SINGLE_FLIGHT_HEADER] = flightSources.join(",");
463
827
  }
464
828
  let init = {
465
829
  method: "POST",
@@ -467,26 +831,32 @@ async function createRequest(base, id, instance, options, meta) {
467
831
  headers
468
832
  };
469
833
  if (config.prepareRequest) {
470
- init = (await config.prepareRequest(init, {
834
+ let prepared = config.prepareRequest(init, {
471
835
  id,
472
836
  meta
473
- })) || init;
837
+ });
838
+ if (prepared && typeof prepared.then === "function") prepared = await prepared;
839
+ if (prepared && prepared !== init) {
840
+ if (typeof prepared !== "object") {
841
+ 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, ... } })");
842
+ }
843
+ if (typeof prepared.method !== "string" || prepared.method.toUpperCase() !== init.method.toUpperCase()) {
844
+ 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, ... } })");
845
+ }
846
+ }
847
+ init = prepared || init;
474
848
  }
475
- if (CALL_OBSERVERS.size === 0) return fetch(base, init);
476
- const request = new Request(new URL(base, globalThis.location?.href || "http://localhost"), init);
477
- notifyCallObservers("request", id, instance, request, meta);
478
- const response = await fetch(request);
479
- notifyCallObservers("response", id, instance, response, meta);
480
- return response;
849
+ const send = config.fetch || fetch;
850
+ return (meta.fetch || send)(base, init, send);
481
851
  }
482
- async function initializeResponse(base, id, instance, options, args, meta) {
852
+ async function initializeResponse(base, id, options, args, meta) {
483
853
  if (args.length === 0) {
484
- return createRequest(base, id, instance, options, meta);
854
+ return createRequest(base, id, options, meta);
485
855
  }
486
856
  if (args.length === 1) {
487
857
  const result = getHeadersAndBody(args[0]);
488
858
  if (result) {
489
- return createRequest(base, id, instance, {
859
+ return createRequest(base, id, {
490
860
  ...options,
491
861
  body: result.body,
492
862
  headers: {
@@ -498,7 +868,7 @@ async function initializeResponse(base, id, instance, options, args, meta) {
498
868
  }
499
869
  try {
500
870
  if (isJSONSafe(args)) {
501
- return createRequest(base, id, instance, {
871
+ return createRequest(base, id, {
502
872
  ...options,
503
873
  body: JSON.stringify(args),
504
874
  headers: {
@@ -512,11 +882,12 @@ async function initializeResponse(base, id, instance, options, args, meta) {
512
882
  }
513
883
  if (args.length > 1) {
514
884
  try {
515
- const trailing = getHeadersAndBody(args[args.length - 1]);
885
+ const last = args[args.length - 1];
886
+ const trailing = typeof last !== "string" && getHeadersAndBody(last);
516
887
  const leading = args.slice(0, -1).map(arg => arg === undefined ? null : arg);
517
888
  if (trailing && isJSONSafe(leading)) {
518
889
  const target = base + (base.includes("?") ? "&" : "?") + "args=" + encodeURIComponent(JSON.stringify(leading));
519
- return createRequest(target, id, instance, {
890
+ return createRequest(target, id, {
520
891
  ...options,
521
892
  body: trailing.body,
522
893
  headers: {
@@ -528,56 +899,66 @@ async function initializeResponse(base, id, instance, options, args, meta) {
528
899
  } catch {
529
900
  }
530
901
  }
531
- return createRequest(base, id, instance, {
902
+ return createRequest(base, id, {
532
903
  ...options,
533
904
  body: await serializeArguments(args),
534
905
  headers: {
535
906
  ...options.headers,
536
- "Content-Type": "text/plain",
537
907
  [BODY_FORMAT_HEADER]: BodyFormat.Serialized
538
908
  }
539
909
  }, meta);
540
910
  }
541
- async function fetchServerFunction(base, id, options, args, meta, callArgs = args) {
542
- const instance = `server-function:${INSTANCE++}`;
911
+ const fetchServerFunction = dispatchServerFunction;
912
+ async function dispatchServerFunction(base, id, options, args, meta, callArgs = args, observation) {
543
913
  const handler = config.responseHandler;
544
914
  const context = handler && handler.capture ? handler.capture({
545
915
  id,
546
916
  meta
547
917
  }) : undefined;
918
+ const sent = options;
548
919
  const controller = options.signal ? undefined : new AbortController();
549
920
  if (controller) options = {
550
921
  ...options,
551
922
  signal: controller.signal
552
923
  };
553
- const response = await initializeResponse(base, id, instance, options, args, meta);
924
+ const response = await initializeResponse(base, id, options, args, meta);
554
925
  if (handler) {
555
- const handled = handler.handle(response, {
926
+ const ctx = {
556
927
  id,
557
928
  meta,
558
929
  args: callArgs,
559
- context
560
- });
930
+ context,
931
+ retry: () => fetchServerFunction(base, id, sent, args, meta, callArgs)
932
+ };
933
+ if (options[LIVE_WIRE]) ctx[LIVE_WIRE] = options[LIVE_WIRE];
934
+ const handled = handler.handle(response, ctx);
561
935
  if (handled !== undefined) return handled;
562
936
  }
563
- const failed = response.headers.has(ERROR_HEADER) || response.status >= 500;
564
- if (response.headers.has(SINGLE_FLIGHT_HEADER)) {
565
- const consumer = getFlightDataConsumer();
566
- if (consumer) {
567
- const payload = await decodeResponse(response);
568
- await consumer(payload.data, {
569
- response
570
- });
571
- if (failed && !response.headers.has("Location") && !response.headers.has(REVALIDATE_HEADER)) {
572
- throw serverFunctionFailure(response, payload.value);
937
+ if (response.status >= 400 && !response.headers.has(BODY_FORMAT_HEADER)) {
938
+ throw serverFunctionFailure(response, undefined);
939
+ }
940
+ const failed = response.headers.has(ERROR_HEADER);
941
+ if (!isReadCall(options) && getFlightDataSourceIds().length > 0) {
942
+ const folded = response.headers.has(SINGLE_FLIGHT_HEADER);
943
+ const metadata = hasFlightMetadata(response);
944
+ if (metadata || folded) {
945
+ const decoded = response.body ? await extractBody(response, getServerFunctionsCodec()) : undefined;
946
+ const enveloped = folded && decoded !== undefined;
947
+ const value = enveloped ? decoded.value : decoded;
948
+ await deliverFlightData(response, enveloped ? decoded.data : undefined);
949
+ if (failed && !metadata) {
950
+ throw serverFunctionFailure(response, value);
573
951
  }
574
- return payload.value;
952
+ return value;
575
953
  }
576
954
  }
577
- if (response.headers.has("Location") || response.headers.has(REVALIDATE_HEADER) || response.headers.has(SINGLE_FLIGHT_HEADER)) {
955
+ 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) {
578
956
  return response;
579
957
  }
580
- const result = await decodeResponse(response.clone());
958
+ if (response.status < 300 && !response.headers.has(BODY_FORMAT_HEADER) && !response.headers.has("X-Content-Raw")) {
959
+ 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`));
960
+ }
961
+ const result = response.body ? await extractBody(response, getServerFunctionsCodec(), options[LIVE_WIRE]) : undefined;
581
962
  if (failed) {
582
963
  throw serverFunctionFailure(response, result);
583
964
  }
@@ -602,24 +983,30 @@ function createServerReference(id, name, base) {
602
983
  const metadata = name === undefined ? {} : {
603
984
  name
604
985
  };
605
- const fn = (...args) => {
986
+ const run = (args, invokeOptions) => {
987
+ const send = () => fetchServerFunction(base ? dataAddressFor(base) : serverFunctionDataAddress(config.endpoint, id), id, invokeOptions ? {
988
+ ...invokeOptions
989
+ } : {}, args, metadata);
606
990
  const handler = config.responseHandler;
607
- if (handler && handler.intercept) {
991
+ if (handler && handler.intercept && !adoptedCall(invokeOptions)) {
608
992
  const hit = handler.intercept({
609
993
  id,
610
994
  meta: metadata,
611
- args
995
+ args,
996
+ retry: send
612
997
  });
613
- if (hit !== undefined) return hit;
998
+ if (hit !== undefined) return localOrSend(hit, send);
614
999
  }
615
- return fetchServerFunction(base || config.endpoint, id, {}, args, metadata);
1000
+ return send();
616
1001
  };
1002
+ const fn = (...args) => run(args);
617
1003
  fn[SERVER_FUNCTION_METADATA] = metadata;
1004
+ fn[SERVER_FUNCTION_INVOKE] = run;
618
1005
  return new Proxy(fn, {
619
1006
  get(target, prop) {
620
1007
  if (prop === "id") return id;
621
1008
  if (prop === "url") {
622
- return base || `${config.endpoint}?id=${encodeURIComponent(id)}`;
1009
+ return base || serverFunctionAddress(config.endpoint, id);
623
1010
  }
624
1011
  return target[prop];
625
1012
  }
@@ -634,45 +1021,84 @@ function GET(fn) {
634
1021
  const metadata = {
635
1022
  ...getServerFunctionMetadata(fn)
636
1023
  };
637
- const wrapped = async (...args) => {
1024
+ const run = async (args, invokeOptions) => {
638
1025
  const handler = config.responseHandler;
639
- if (handler && handler.intercept) {
1026
+ if (handler && handler.intercept && !adoptedCall(invokeOptions)) {
1027
+ const retry = () => send(args, invokeOptions);
640
1028
  const hit = handler.intercept({
641
1029
  id,
642
1030
  meta: metadata,
643
- args
1031
+ args,
1032
+ retry
644
1033
  });
645
- if (hit !== undefined) return hit;
1034
+ if (hit !== undefined) return localOrSend(hit, retry);
646
1035
  }
647
- let base = `${config.endpoint}?id=${encodeURIComponent(id)}`;
648
- if (args.length) {
649
- const encoded = isJSONSafe(args) ? JSON.stringify(args) : await serializeArguments(args);
650
- base += `&args=${encodeURIComponent(encoded)}`;
1036
+ return send(args, invokeOptions);
1037
+ };
1038
+ const send = async (args, invokeOptions) => {
1039
+ const opts = invokeOptions || {};
1040
+ const address = opts[LIVE_WIRE] ? serverFunctionLiveAddress(config.endpoint, id) : serverFunctionDataAddress(config.endpoint, id);
1041
+ if (!args.length) {
1042
+ return fetchServerFunction(address, id, {
1043
+ ...opts,
1044
+ method: "GET"
1045
+ }, [], metadata, args);
651
1046
  }
652
- return fetchServerFunction(base, id, {
1047
+ const encoded = isJSONSafe(args) ? JSON.stringify(args) : await serializeArguments(args);
1048
+ const url = `${address}?args=${encodeURIComponent(encoded)}`;
1049
+ const absolute = new URL(url, globalThis.location?.href || "http://localhost").href;
1050
+ if (absolute.length > MAX_GET_URL_LENGTH) {
1051
+ return fetchServerFunction(address, id, {
1052
+ ...opts,
1053
+ read: true
1054
+ }, args, metadata);
1055
+ }
1056
+ return fetchServerFunction(url, id, {
1057
+ ...opts,
653
1058
  method: "GET"
654
1059
  }, [], metadata, args);
655
1060
  };
1061
+ const wrapped = (...args) => run(args);
656
1062
  wrapped[SERVER_FUNCTION_METADATA] = metadata;
1063
+ wrapped[SERVER_FUNCTION_INVOKE] = run;
657
1064
  wrapped.id = id;
658
1065
  Object.defineProperty(wrapped, "url", {
659
- get: () => `${config.endpoint}?id=${encodeURIComponent(id)}`,
1066
+ get: () => serverFunctionAddress(config.endpoint, id),
660
1067
  configurable: true
661
1068
  });
662
1069
  return withMeta(wrapped, {
663
1070
  method: "GET"
664
1071
  });
665
1072
  }
1073
+ function broadcast(fn) {
1074
+ return live(fn);
1075
+ }
1076
+ function localOrSend(hit, send) {
1077
+ if (hit === null || typeof hit.then !== "function") return hit;
1078
+ return hit.then(answer => answer === undefined ? send() : answer);
1079
+ }
1080
+ function adoptedCall(options) {
1081
+ const wire = options && options[LIVE_WIRE];
1082
+ return !!(wire && wire.adopted);
1083
+ }
666
1084
  function live(fn) {
667
1085
  if (!isServerFunction(fn)) {
668
1086
  throw new Error("live expects a server function reference");
669
1087
  }
1088
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = rpc.GET(fn);
670
1089
  const id = fn.id;
671
1090
  const metadata = {
672
1091
  ...getServerFunctionMetadata(fn),
673
1092
  live: true
674
1093
  };
675
- const wrapped = (...args) => {
1094
+ const makeIterable = (args, invokeOptions) => {
1095
+ const handler = config.responseHandler;
1096
+ handler && handler.onLive && handler.onLive();
1097
+ const local = handler && handler.intercept ? handler.intercept({
1098
+ id,
1099
+ meta: metadata,
1100
+ args
1101
+ }) : undefined;
676
1102
  const iterable = {
677
1103
  [LIVE_SOURCE]: true,
678
1104
  [Symbol.asyncIterator]() {
@@ -680,20 +1106,50 @@ function live(fn) {
680
1106
  let connected = false;
681
1107
  let attempts = 0;
682
1108
  let stopped = false;
683
- let ended = false;
1109
+ let closed = false;
1110
+ let ended;
684
1111
  let timer, wake;
685
1112
  const DONE = {
686
1113
  done: true,
687
1114
  value: undefined
688
1115
  };
1116
+ const invokeSignal = invokeOptions && invokeOptions.signal;
1117
+ const controller = new AbortController();
1118
+ let resume = iterable[LIVE_RESUME_FROM];
1119
+ let seed = iterable[LIVE_LOCAL];
1120
+ const wire = {
1121
+ position: resume !== undefined ? positionDigest(resume) : undefined,
1122
+ connection: undefined,
1123
+ adopted: resume !== undefined,
1124
+ open: body => new EventStreamReader(body, wire)
1125
+ };
1126
+ const ends = [];
1127
+ const settle = (end, error) => {
1128
+ try {
1129
+ error !== undefined ? end.sweep() : end.close();
1130
+ } catch {}
1131
+ };
1132
+ const settleAll = error => {
1133
+ while (ends.length) settle(ends.pop(), error);
1134
+ };
1135
+ const wireOptions = {
1136
+ ...invokeOptions,
1137
+ [LIVE_WIRE]: wire,
1138
+ signal: invokeSignal ? AbortSignal.any([invokeSignal, controller.signal]) : controller.signal
1139
+ };
689
1140
  const emit = (state, error) => {
690
1141
  try {
691
1142
  iterable.onstatus && iterable.onstatus(state, error);
692
1143
  } catch {}
693
1144
  };
1145
+ const track = open => {
1146
+ return;
1147
+ };
694
1148
  const emitClosed = error => {
695
- if (ended) return;
696
- ended = true;
1149
+ settleAll(error);
1150
+ if (ended) ended.then(end => settle(end, error));
1151
+ if (closed) return;
1152
+ closed = true;
697
1153
  emit("closed", error);
698
1154
  };
699
1155
  const closeIt = value => {
@@ -707,37 +1163,68 @@ function live(fn) {
707
1163
  }
708
1164
  };
709
1165
  const callOnce = () => {
710
- if (metadata.method === "GET") return fn(...args);
711
1166
  const handler = config.responseHandler;
712
- if (handler && handler.intercept) {
713
- const hit = handler.intercept({
1167
+ if (handler && handler.resume) {
1168
+ const from = handler.resume({
714
1169
  id,
715
1170
  meta: metadata,
716
1171
  args
717
1172
  });
718
- if (hit !== undefined) return hit;
1173
+ wire.headers = from ? from.headers : undefined;
1174
+ if (from && from.position !== undefined) wire.position = from.position;
719
1175
  }
720
- return fetchServerFunction(fn.url, id, {
721
- read: true
722
- }, args, metadata, args);
1176
+ return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
723
1177
  };
724
1178
  const pull = async () => {
1179
+ if (resume !== undefined) {
1180
+ const value = resume;
1181
+ resume = undefined;
1182
+ if (!stopped) return {
1183
+ done: false,
1184
+ value
1185
+ };
1186
+ }
1187
+ if (seed !== undefined) {
1188
+ const value = typeof seed.then === "function" ? await seed : seed;
1189
+ seed = undefined;
1190
+ if (value !== undefined) {
1191
+ wire.adopted = true;
1192
+ if (!stopped) return {
1193
+ done: false,
1194
+ value
1195
+ };
1196
+ }
1197
+ }
725
1198
  while (!stopped) {
726
1199
  try {
727
1200
  if (!it) {
1201
+ const connection = wire.connection = {
1202
+ ended: undefined
1203
+ };
728
1204
  const result = await callOnce();
729
1205
  connected = true;
1206
+ ended = connection.ended;
730
1207
  it = result !== null && typeof result === "object" && result[Symbol.asyncIterator] ? result[Symbol.asyncIterator]() : async function* () {
731
1208
  yield result;
732
1209
  }();
733
1210
  if (stopped) {
734
1211
  closeIt();
1212
+ controller.abort();
735
1213
  return DONE;
736
1214
  }
1215
+ track(true);
737
1216
  emit("connected");
738
1217
  }
739
- const r = await it.next();
740
- if (r.done) {
1218
+ const r = await (ended ? Promise.race([it.next(), ended.then(end => ({
1219
+ end
1220
+ }))]) : it.next());
1221
+ if (r.end || r.done) {
1222
+ const end = r.end || ended && (await ended);
1223
+ if (end && end.open > 0) {
1224
+ ends.push(end);
1225
+ throw end.error;
1226
+ }
1227
+ if (end) settle(end);
741
1228
  emitClosed();
742
1229
  return DONE;
743
1230
  }
@@ -745,23 +1232,34 @@ function live(fn) {
745
1232
  attempts = 0;
746
1233
  return r;
747
1234
  } catch (error) {
1235
+ if (stopped) return DONE;
748
1236
  if (!connected) throw error;
749
- if (error !== null && typeof error === "object" && typeof error.status === "number" && error.status >= 400 && error.status < 500) {
1237
+ if (invokeSignal && invokeSignal.aborted) {
750
1238
  stopped = true;
751
1239
  emitClosed(error);
752
1240
  throw error;
753
1241
  }
754
- it = undefined;
1242
+ 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") {
1243
+ stopped = true;
1244
+ emitClosed(error);
1245
+ throw error;
1246
+ }
1247
+ closeIt();
755
1248
  emit("reconnecting", error);
756
1249
  await new Promise(resolve => {
757
1250
  wake = resolve;
758
- timer = setTimeout(resolve, Math.min(500 * 2 ** attempts++, 10000));
1251
+ const named = error !== null && typeof error === "object" && typeof error.retryAfter === "number" ? Math.min(error.retryAfter * 1000, 60000) : undefined;
1252
+ timer = setTimeout(resolve, named ?? Math.min(500 * 2 ** attempts++, 10000));
759
1253
  if (typeof addEventListener === "function") addEventListener("online", resolve, {
760
1254
  once: true
761
1255
  });
1256
+ if (invokeSignal) invokeSignal.addEventListener("abort", resolve, {
1257
+ once: true
1258
+ });
762
1259
  });
763
1260
  clearTimeout(timer);
764
1261
  if (typeof removeEventListener === "function") removeEventListener("online", wake);
1262
+ if (invokeSignal) invokeSignal.removeEventListener("abort", wake);
765
1263
  timer = wake = undefined;
766
1264
  }
767
1265
  }
@@ -774,6 +1272,7 @@ function live(fn) {
774
1272
  if (timer !== undefined) clearTimeout(timer);
775
1273
  if (wake) wake();
776
1274
  closeIt(value);
1275
+ controller.abort();
777
1276
  emitClosed();
778
1277
  return Promise.resolve({
779
1278
  done: true,
@@ -783,9 +1282,12 @@ function live(fn) {
783
1282
  };
784
1283
  }
785
1284
  };
1285
+ if (local !== undefined) iterable[LIVE_LOCAL] = local;
786
1286
  return iterable;
787
1287
  };
1288
+ const wrapped = (...args) => makeIterable(args);
788
1289
  wrapped[SERVER_FUNCTION_METADATA] = metadata;
1290
+ wrapped[SERVER_FUNCTION_INVOKE] = makeIterable;
789
1291
  wrapped.id = id;
790
1292
  Object.defineProperty(wrapped, "url", {
791
1293
  get: () => fn.url,
@@ -800,4 +1302,4 @@ function getServerFunctionInvocation() {
800
1302
  return undefined;
801
1303
  }
802
1304
 
803
- export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, FUNCTION_HEADER, GET, INSTANCE_HEADER, REVALIDATE_HEADER, SINGLE_FLIGHT_HEADER, clearFlashCookie, configureServerFunctionsClient, createChunk, createServerReference, decodeErrorHeaderValue, decodeResponse, decodeResponsePayload, deserializeStream, encodeErrorHeaderValue, frameAddress, getFlightDataConsumer, getServerFunctionInvocation, getServerFunctionMetadata, getServerFunctionsCodec, hasFlashCookie, isServerFunction, live, observeServerFunctionCalls, registerServerReference, serializeString, subscribeFlightData, withMeta };
1305
+ export { ChunkReader, ERROR_HEADER, EVENT_STREAM_HEARTBEAT, EventStreamReader, FLASH_COOKIE, GET, LAST_EVENT_ID_HEADER, LIVE_WIRE, REDIRECT_HEADER, REVALIDATE_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, broadcast, clearFlashCookie, configureServerFunctionsClient, createChunk, createEventChunk, createServerReference, decodeErrorHeaderValue, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, deliverFlightData, deserializeStream, encodeErrorHeaderValue, frameAddress, getFlightDataConsumer, getFlightDataSourceIds, getServerFunctionInvocation, getServerFunctionMetadata, getServerFunctionsCodec, hasFlashCookie, hasFlightMetadata, invoke, isEventStream, isServerFunction, live, parseServerFunctionActionUrl, positionDigest, registerServerReference, serializeString, serverFunctionActionUrl, serverFunctionUrl, subscribeFlightData, withMeta };