@solidjs/web 2.0.0-rc.1 → 2.0.0-rc.11

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