@solidjs/web 2.0.0-rc.16 → 2.0.0-rc.18

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.
@@ -1,4 +1,4 @@
1
- import { isStream, fromCrossJSON, Feature, createStream, OpaqueReference as OpaqueReference$1, createPlugin as createPlugin$1, toCrossJSONStream, Serializer, getCrossReferenceHeader } from 'seroval';
1
+ import { isStream, fromCrossJSON, Feature, createStream, OpaqueReference as OpaqueReference$1, createPlugin as createPlugin$1, Serializer, getCrossReferenceHeader, toCrossJSONStream, crossSerializeStream } from 'seroval';
2
2
  import { AbortSignalPlugin, CustomEventPlugin, DOMExceptionPlugin, EventPlugin, FormDataPlugin, HeadersPlugin, ReadableStreamPlugin, RequestPlugin, ResponsePlugin, URLSearchParamsPlugin, URLPlugin } from 'seroval-plugins/web';
3
3
 
4
4
  const STATE = Symbol.for("solid.container-trace-state");
@@ -132,11 +132,16 @@ function createJSONDeserializer(options) {
132
132
  const close = () => {
133
133
  alive = false;
134
134
  };
135
- const off = stream.on({
136
- next() {},
137
- throw: close,
138
- return: close
139
- });
135
+ let off;
136
+ try {
137
+ off = stream.on({
138
+ next() {},
139
+ throw: close,
140
+ return: close
141
+ });
142
+ } catch {
143
+ return stream.alive !== false;
144
+ }
140
145
  if (typeof off === "function") off();
141
146
  return alive;
142
147
  }
@@ -233,6 +238,90 @@ function createSerializer(options) {
233
238
  disabledFeatures: (options.disabledFeatures === undefined ? defaultDisabledFeatures() : options.disabledFeatures) | serializeOnlyDisabledFeatures(options.serializeErrorStacks)
234
239
  });
235
240
  }
241
+ function createKeyedSerializer(serialize, onError, onDone) {
242
+ const cancels = new Set();
243
+ let pendingWrites = 0;
244
+ let flushed = false;
245
+ let done = false;
246
+ let closed = false;
247
+ const maybeDone = () => {
248
+ if (flushed && pendingWrites === 0 && !done) {
249
+ done = true;
250
+ onDone && onDone();
251
+ }
252
+ };
253
+ return {
254
+ write(key, value) {
255
+ if (flushed) return;
256
+ pendingWrites++;
257
+ let settled = false;
258
+ let failed = false;
259
+ let started = false;
260
+ let cancel = null;
261
+ const settle = () => {
262
+ if (settled) return;
263
+ settled = true;
264
+ if (cancel) cancels.delete(cancel);
265
+ pendingWrites--;
266
+ maybeDone();
267
+ };
268
+ let stream;
269
+ try {
270
+ stream = serialize(key, value, {
271
+ onError: onError && (err => {
272
+ failed = true;
273
+ onError(err);
274
+ if (cancel) {
275
+ cancel();
276
+ settle();
277
+ }
278
+ }),
279
+ onDone: settle
280
+ }, initial => {
281
+ if (initial) started = true;
282
+ return !closed;
283
+ });
284
+ } catch (err) {
285
+ settle();
286
+ throw err;
287
+ }
288
+ if (settled) return;
289
+ if (closed || failed) {
290
+ stream();
291
+ settle();
292
+ return;
293
+ }
294
+ cancel = stream;
295
+ cancels.add(cancel);
296
+ },
297
+ flush() {
298
+ flushed = true;
299
+ maybeDone();
300
+ },
301
+ close() {
302
+ closed = flushed = true;
303
+ for (const cancel of cancels) cancel();
304
+ cancels.clear();
305
+ if (!done) {
306
+ done = true;
307
+ onDone && onDone();
308
+ }
309
+ }
310
+ };
311
+ }
312
+ const KEY_ESCAPES = {
313
+ '"': '\\"',
314
+ "\\": "\\\\",
315
+ "\n": "\\n",
316
+ "\r": "\\r",
317
+ "\b": "\\b",
318
+ "\t": "\\t",
319
+ "\f": "\\f",
320
+ "<": "\\x3C",
321
+ "\u2028": "\\u2028",
322
+ "\u2029": "\\u2029"
323
+ };
324
+ const serializeKey = key => ("" + key).replace(/["\\\n\r\b\t\f<\u2028\u2029]/g, c => KEY_ESCAPES[c]);
236
325
  function createHydrationSerializer({
237
326
  onData,
238
327
  onDone,
@@ -240,14 +329,20 @@ function createHydrationSerializer({
240
329
  onError,
241
330
  plugins
242
331
  }) {
243
- return createSerializer({
332
+ const resolvedPlugins = resolveSerializerPlugins(plugins);
333
+ const disabledFeatures = defaultDisabledFeatures() | serializeOnlyDisabledFeatures();
334
+ const refs = new Map();
335
+ return createKeyedSerializer((key, value, callbacks, live) => crossSerializeStream(value, {
244
336
  scopeId,
245
- plugins,
246
- globalIdentifier: HYDRATION_GLOBAL,
247
- onData,
248
- onDone,
249
- onError
250
- });
337
+ refs,
338
+ plugins: resolvedPlugins,
339
+ disabledFeatures,
340
+ onSerialize(data, initial) {
341
+ if (!live(initial)) return;
342
+ onData(initial ? HYDRATION_GLOBAL + '["' + serializeKey(key) + '"]=' + data : data);
343
+ },
344
+ ...callbacks
345
+ }), onError, onDone);
251
346
  }
252
347
  function getLocalHeaderScript(id) {
253
348
  return getCrossReferenceHeader(id) + ";";
@@ -256,6 +351,7 @@ function serializeJSON(value, {
256
351
  onParse,
257
352
  onDone,
258
353
  onError,
354
+ refs,
259
355
  ...codecOptions
260
356
  }) {
261
357
  const resolved = resolveCodecOptions(codecOptions);
@@ -263,6 +359,7 @@ function serializeJSON(value, {
263
359
  onParse,
264
360
  onDone,
265
361
  onError,
362
+ refs,
266
363
  ...resolved,
267
364
  disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(resolved.serializeErrorStacks)
268
365
  });
@@ -283,56 +380,19 @@ function createJSONSerializer({
283
380
  serializeErrorStacks
284
381
  });
285
382
  const refs = new Map();
286
- const cancels = new Set();
287
- let pendingWrites = 0;
288
- let flushed = false;
289
- let done = false;
290
- const maybeDone = () => {
291
- if (flushed && pendingWrites === 0 && !done) {
292
- done = true;
293
- onDone && onDone();
294
- }
295
- };
296
- return {
297
- write(key, value) {
298
- if (flushed) return;
299
- pendingWrites++;
300
- let settled = false;
301
- let cancel = null;
302
- const stream = toCrossJSONStream(value, {
303
- refs,
304
- plugins: resolved.plugins,
305
- disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(resolved.serializeErrorStacks),
306
- onParse(node, initial) {
307
- onData({
308
- key,
309
- node,
310
- initial
311
- });
312
- },
313
- onError,
314
- onDone() {
315
- settled = true;
316
- if (cancel) cancels.delete(cancel);
317
- pendingWrites--;
318
- maybeDone();
319
- }
383
+ return createKeyedSerializer((key, value, callbacks, live) => toCrossJSONStream(value, {
384
+ refs,
385
+ plugins: resolved.plugins,
386
+ disabledFeatures: resolved.disabledFeatures | serializeOnlyDisabledFeatures(resolved.serializeErrorStacks),
387
+ onParse(node, initial) {
388
+ if (live(initial)) onData({
389
+ key,
390
+ node,
391
+ initial
320
392
  });
321
- if (!settled) {
322
- cancel = stream;
323
- cancels.add(cancel);
324
- }
325
393
  },
326
- flush() {
327
- flushed = true;
328
- maybeDone();
329
- },
330
- close() {
331
- flushed = true;
332
- for (const cancel of cancels) cancel();
333
- cancels.clear();
334
- }
335
- };
394
+ ...callbacks
395
+ }), onError, onDone);
336
396
  }
337
397
 
338
398
  export { DEFAULT_WEB_PLUGINS, OpaqueReference, createHydrationSerializer, createJSONDataTable, createJSONDeserializer, createJSONSerializer, createPlugin, createSerializer, getLocalHeaderScript, resolveSerializerPlugins, serializeJSON };
@@ -36,10 +36,11 @@ export interface WebSerializerOptions {
36
36
  }
37
37
  /**
38
38
  * Options for `createHydrationSerializer` — `WebSerializerOptions` minus
39
- * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`).
39
+ * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`,
40
+ * `serializeErrorStacks`: its stacks follow `NODE_ENV`).
40
41
  * @internal
41
42
  */
42
- export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures">;
43
+ export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures" | "serializeErrorStacks">;
43
44
  /**
44
45
  * Options for `serializeJSON`.
45
46
  *
@@ -69,7 +70,10 @@ export interface JSONSerializerOptions extends JSONCodecOptions {
69
70
  initial: boolean;
70
71
  }) => void;
71
72
  onError?: (error: unknown) => void;
72
- /** Fires once `flush()` has been called and every pending value settled. */
73
+ /**
74
+ * Fires once `flush()` has been called and every pending value settled, or
75
+ * once `close()` runs.
76
+ */
73
77
  onDone?: () => void;
74
78
  }
75
79
  export declare const createPlugin: <Value, Info extends PluginInfo>(plugin: SerializerPlugin<Value, Info>) => SerializerPlugin<Value, Info>;
@@ -91,7 +95,11 @@ export declare const OpaqueReference: {
91
95
  * Integration-facing; may change (see the entry banner).
92
96
  */
93
97
  export declare function createSerializer(options: WebSerializerOptions): Serializer;
94
- export declare function createHydrationSerializer(options: HydrationSerializerOptions): Serializer;
98
+ export declare function createHydrationSerializer(options: HydrationSerializerOptions): {
99
+ write(key: string, value: unknown): void;
100
+ flush(): void;
101
+ close(): void;
102
+ };
95
103
  export declare function getLocalHeaderScript(id?: string): string;
96
104
  export declare function serializeJSON(value: unknown, options: JSONSerializeOptions): () => void;
97
105
  export declare function createJSONSerializer(options: JSONSerializerOptions): {
@@ -36,10 +36,11 @@ export interface WebSerializerOptions {
36
36
  }
37
37
  /**
38
38
  * Options for `createHydrationSerializer` — `WebSerializerOptions` minus
39
- * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`).
39
+ * the knobs hydration pins (`globalIdentifier`, `disabledFeatures`,
40
+ * `serializeErrorStacks`: its stacks follow `NODE_ENV`).
40
41
  * @internal
41
42
  */
42
- export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures">;
43
+ export type HydrationSerializerOptions = Omit<WebSerializerOptions, "globalIdentifier" | "disabledFeatures" | "serializeErrorStacks">;
43
44
  /**
44
45
  * Options for `serializeJSON`.
45
46
  *
@@ -69,7 +70,10 @@ export interface JSONSerializerOptions extends JSONCodecOptions {
69
70
  initial: boolean;
70
71
  }) => void;
71
72
  onError?: (error: unknown) => void;
72
- /** Fires once `flush()` has been called and every pending value settled. */
73
+ /**
74
+ * Fires once `flush()` has been called and every pending value settled, or
75
+ * once `close()` runs.
76
+ */
73
77
  onDone?: () => void;
74
78
  }
75
79
  export declare const createPlugin: <Value, Info extends PluginInfo>(plugin: SerializerPlugin<Value, Info>) => SerializerPlugin<Value, Info>;
@@ -91,7 +95,11 @@ export declare const OpaqueReference: {
91
95
  * Integration-facing; may change (see the entry banner).
92
96
  */
93
97
  export declare function createSerializer(options: WebSerializerOptions): Serializer;
94
- export declare function createHydrationSerializer(options: HydrationSerializerOptions): Serializer;
98
+ export declare function createHydrationSerializer(options: HydrationSerializerOptions): {
99
+ write(key: string, value: unknown): void;
100
+ flush(): void;
101
+ close(): void;
102
+ };
95
103
  export declare function getLocalHeaderScript(id?: string): string;
96
104
  export declare function serializeJSON(value: unknown, options: JSONSerializeOptions): () => void;
97
105
  export declare function createJSONSerializer(options: JSONSerializerOptions): {
@@ -858,7 +858,7 @@ function parseServerFunctionActionUrl(url) {
858
858
  }
859
859
  function serializeArguments(args) {
860
860
  if (!config.serializeArgs) {
861
- 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.");
861
+ 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.");
862
862
  }
863
863
  return config.serializeArgs(args);
864
864
  }
@@ -877,11 +877,10 @@ function configureServerFunctionsClient({
877
877
  if (responseHandler !== undefined) config.responseHandler = responseHandler;
878
878
  if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
879
879
  }
880
- let rpcProvided = false;
880
+ let rpc;
881
881
  function provideRPC() {
882
- if (rpcProvided) return;
883
- rpcProvided = true;
884
- provideServerFunctionRPC({
882
+ if (rpc) return;
883
+ provideServerFunctionRPC(rpc = {
885
884
  GET,
886
885
  decodeResponse
887
886
  });
@@ -895,7 +894,6 @@ function siblingAddressFor(base, kind) {
895
894
  return `${path.slice(0, slash + 1)}${kind}/${path.slice(slash + 1)}${rest}`;
896
895
  }
897
896
  const dataAddressFor = base => siblingAddressFor(base, "data");
898
- const liveAddressFor = base => siblingAddressFor(base, "live");
899
897
  function serverFunctionFailure(response, value) {
900
898
  const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
901
899
  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}`);
@@ -1022,7 +1020,6 @@ async function initializeResponse(base, id, options, args, meta) {
1022
1020
  body: await serializeArguments(args),
1023
1021
  headers: {
1024
1022
  ...options.headers,
1025
- "Content-Type": "text/plain",
1026
1023
  [BODY_FORMAT_HEADER]: BodyFormat.Serialized
1027
1024
  }
1028
1025
  }, meta);
@@ -1225,6 +1222,9 @@ function trackLiveConnection(id, open) {
1225
1222
  const names = [...openLiveConnections].map(([fnId, n]) => n > 1 ? `${fnId} ×${n}` : fnId);
1226
1223
  console.warn(`live: ${total} live connections are open (${names.join(", ")}) and this page was served ` + `over ${protocol}. Browsers allow six connections per origin under HTTP/1.1, so the next ` + `request to this origin — a navigation, a fetch, an image — waits behind them. live ` + `requires HTTP/2: the dev server speaks it with \`server.https\`; production hosts do by default.`);
1227
1224
  }
1225
+ function broadcast(fn) {
1226
+ return live(fn);
1227
+ }
1228
1228
  function localOrSend(hit, send) {
1229
1229
  if (hit === null || typeof hit.then !== "function") return hit;
1230
1230
  return hit.then(answer => answer === undefined ? send() : answer);
@@ -1237,6 +1237,7 @@ function live(fn) {
1237
1237
  if (!isServerFunction(fn)) {
1238
1238
  throw new Error("live expects a server function reference");
1239
1239
  }
1240
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = rpc.GET(fn);
1240
1241
  const id = fn.id;
1241
1242
  const metadata = {
1242
1243
  ...getServerFunctionMetadata(fn),
@@ -1329,19 +1330,7 @@ function live(fn) {
1329
1330
  wire.headers = from ? from.headers : undefined;
1330
1331
  if (from && from.position !== undefined) wire.position = from.position;
1331
1332
  }
1332
- if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1333
- if (handler && handler.intercept && !wire.adopted) {
1334
- const hit = handler.intercept({
1335
- id,
1336
- meta: metadata,
1337
- args
1338
- });
1339
- if (hit !== undefined) return hit;
1340
- }
1341
- return fetchServerFunction(liveAddressFor(fn.url), id, {
1342
- ...wireOptions,
1343
- read: true
1344
- }, args, metadata, args);
1333
+ return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1345
1334
  };
1346
1335
  const pull = async () => {
1347
1336
  if (resume !== undefined) {
@@ -1470,4 +1459,4 @@ function getServerFunctionInvocation() {
1470
1459
  return undefined;
1471
1460
  }
1472
1461
 
1473
- 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 };
1462
+ 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 };
@@ -750,7 +750,7 @@ function parseServerFunctionActionUrl(url) {
750
750
  }
751
751
  function serializeArguments(args) {
752
752
  if (!config.serializeArgs) {
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, 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.");
754
754
  }
755
755
  return config.serializeArgs(args);
756
756
  }
@@ -769,11 +769,10 @@ function configureServerFunctionsClient({
769
769
  if (responseHandler !== undefined) config.responseHandler = responseHandler;
770
770
  if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
771
771
  }
772
- let rpcProvided = false;
772
+ let rpc;
773
773
  function provideRPC() {
774
- if (rpcProvided) return;
775
- rpcProvided = true;
776
- provideServerFunctionRPC({
774
+ if (rpc) return;
775
+ provideServerFunctionRPC(rpc = {
777
776
  GET,
778
777
  decodeResponse
779
778
  });
@@ -787,7 +786,6 @@ function siblingAddressFor(base, kind) {
787
786
  return `${path.slice(0, slash + 1)}${kind}/${path.slice(slash + 1)}${rest}`;
788
787
  }
789
788
  const dataAddressFor = base => siblingAddressFor(base, "data");
790
- const liveAddressFor = base => siblingAddressFor(base, "live");
791
789
  function serverFunctionFailure(response, value) {
792
790
  const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
793
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}`);
@@ -906,7 +904,6 @@ async function initializeResponse(base, id, options, args, meta) {
906
904
  body: await serializeArguments(args),
907
905
  headers: {
908
906
  ...options.headers,
909
- "Content-Type": "text/plain",
910
907
  [BODY_FORMAT_HEADER]: BodyFormat.Serialized
911
908
  }
912
909
  }, meta);
@@ -1073,6 +1070,9 @@ function GET(fn) {
1073
1070
  method: "GET"
1074
1071
  });
1075
1072
  }
1073
+ function broadcast(fn) {
1074
+ return live(fn);
1075
+ }
1076
1076
  function localOrSend(hit, send) {
1077
1077
  if (hit === null || typeof hit.then !== "function") return hit;
1078
1078
  return hit.then(answer => answer === undefined ? send() : answer);
@@ -1085,6 +1085,7 @@ function live(fn) {
1085
1085
  if (!isServerFunction(fn)) {
1086
1086
  throw new Error("live expects a server function reference");
1087
1087
  }
1088
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = rpc.GET(fn);
1088
1089
  const id = fn.id;
1089
1090
  const metadata = {
1090
1091
  ...getServerFunctionMetadata(fn),
@@ -1172,19 +1173,7 @@ function live(fn) {
1172
1173
  wire.headers = from ? from.headers : undefined;
1173
1174
  if (from && from.position !== undefined) wire.position = from.position;
1174
1175
  }
1175
- if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1176
- if (handler && handler.intercept && !wire.adopted) {
1177
- const hit = handler.intercept({
1178
- id,
1179
- meta: metadata,
1180
- args
1181
- });
1182
- if (hit !== undefined) return hit;
1183
- }
1184
- return fetchServerFunction(liveAddressFor(fn.url), id, {
1185
- ...wireOptions,
1186
- read: true
1187
- }, args, metadata, args);
1176
+ return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1188
1177
  };
1189
1178
  const pull = async () => {
1190
1179
  if (resume !== undefined) {
@@ -1313,4 +1302,4 @@ function getServerFunctionInvocation() {
1313
1302
  return undefined;
1314
1303
  }
1315
1304
 
1316
- 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 };
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 };
@@ -858,7 +858,7 @@ function parseServerFunctionActionUrl(url) {
858
858
  }
859
859
  function serializeArguments(args) {
860
860
  if (!config.serializeArgs) {
861
- 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.");
861
+ 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.");
862
862
  }
863
863
  return config.serializeArgs(args);
864
864
  }
@@ -877,11 +877,10 @@ function configureServerFunctionsClient({
877
877
  if (responseHandler !== undefined) config.responseHandler = responseHandler;
878
878
  if (serializeArgs !== undefined) config.serializeArgs = serializeArgs;
879
879
  }
880
- let rpcProvided = false;
880
+ let rpc;
881
881
  function provideRPC() {
882
- if (rpcProvided) return;
883
- rpcProvided = true;
884
- provideServerFunctionRPC({
882
+ if (rpc) return;
883
+ provideServerFunctionRPC(rpc = {
885
884
  GET,
886
885
  decodeResponse
887
886
  });
@@ -895,7 +894,6 @@ function siblingAddressFor(base, kind) {
895
894
  return `${path.slice(0, slash + 1)}${kind}/${path.slice(slash + 1)}${rest}`;
896
895
  }
897
896
  const dataAddressFor = base => siblingAddressFor(base, "data");
898
- const liveAddressFor = base => siblingAddressFor(base, "live");
899
897
  function serverFunctionFailure(response, value) {
900
898
  const unknown = response.headers.get(UNKNOWN_HEADER) !== null;
901
899
  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}`);
@@ -1022,7 +1020,6 @@ async function initializeResponse(base, id, options, args, meta) {
1022
1020
  body: await serializeArguments(args),
1023
1021
  headers: {
1024
1022
  ...options.headers,
1025
- "Content-Type": "text/plain",
1026
1023
  [BODY_FORMAT_HEADER]: BodyFormat.Serialized
1027
1024
  }
1028
1025
  }, meta);
@@ -1209,6 +1206,9 @@ function GET(fn) {
1209
1206
  method: "GET"
1210
1207
  });
1211
1208
  }
1209
+ function broadcast(fn) {
1210
+ return live(fn);
1211
+ }
1212
1212
  function localOrSend(hit, send) {
1213
1213
  if (hit === null || typeof hit.then !== "function") return hit;
1214
1214
  return hit.then(answer => answer === undefined ? send() : answer);
@@ -1221,6 +1221,7 @@ function live(fn) {
1221
1221
  if (!isServerFunction(fn)) {
1222
1222
  throw new Error("live expects a server function reference");
1223
1223
  }
1224
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = rpc.GET(fn);
1224
1225
  const id = fn.id;
1225
1226
  const metadata = {
1226
1227
  ...getServerFunctionMetadata(fn),
@@ -1308,19 +1309,7 @@ function live(fn) {
1308
1309
  wire.headers = from ? from.headers : undefined;
1309
1310
  if (from && from.position !== undefined) wire.position = from.position;
1310
1311
  }
1311
- if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1312
- if (handler && handler.intercept && !wire.adopted) {
1313
- const hit = handler.intercept({
1314
- id,
1315
- meta: metadata,
1316
- args
1317
- });
1318
- if (hit !== undefined) return hit;
1319
- }
1320
- return fetchServerFunction(liveAddressFor(fn.url), id, {
1321
- ...wireOptions,
1322
- read: true
1323
- }, args, metadata, args);
1312
+ return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1324
1313
  };
1325
1314
  const pull = async () => {
1326
1315
  if (resume !== undefined) {
@@ -1449,4 +1438,4 @@ function getServerFunctionInvocation() {
1449
1438
  return undefined;
1450
1439
  }
1451
1440
 
1452
- 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 };
1441
+ 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 };
@@ -23,18 +23,69 @@ function encodeRefusal(name) {
23
23
  };
24
24
  }
25
25
  let encodeRefusals;
26
- function argumentEncodeCodec(codec) {
26
+ function argumentEncodeCodec(codec, extra = []) {
27
27
  if (!encodeRefusals) encodeRefusals = [encodeRefusal("Response"), encodeRefusal("Request")];
28
- const refusals = encodeRefusals;
28
+ const refusals = extra.length ? [...extra, ...encodeRefusals] : encodeRefusals;
29
29
  return {
30
30
  ...codec,
31
31
  plugins: codec && codec.plugins ? [...refusals, ...codec.plugins] : refusals
32
32
  };
33
33
  }
34
34
 
35
+ const UPLOAD_ARGS_PART = "args";
36
+ const UPLOAD_FILE_PART = "file";
37
+ const UPLOAD_TAG = "solid/server-function-upload";
38
+ function isBlob(value) {
39
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
40
+ return typeof value === "object" && value !== null && typeof value.size === "number" && typeof value.type === "string" && typeof value.arrayBuffer === "function" && typeof value.slice === "function";
41
+ }
42
+ function malformed() {
43
+ return new TypeError("Malformed server function upload");
44
+ }
45
+ function createUploadSerializer(files) {
46
+ const indexOf = value => {
47
+ const index = files.indexOf(value);
48
+ return index === -1 ? files.push(value) - 1 : index;
49
+ };
50
+ return {
51
+ tag: UPLOAD_TAG,
52
+ test: isBlob,
53
+ parse: {
54
+ sync: (value, ctx) => ({
55
+ i: ctx.parse(indexOf(value))
56
+ }),
57
+ async: async (value, ctx) => ({
58
+ i: await ctx.parse(indexOf(value))
59
+ }),
60
+ stream: (value, ctx) => ({
61
+ i: ctx.parse(indexOf(value))
62
+ })
63
+ },
64
+ serialize: (node, ctx) => ctx.serialize(node.i),
65
+ deserialize: () => {
66
+ throw malformed();
67
+ }
68
+ };
69
+ }
70
+ async function createUploadBody(serialized, files) {
71
+ const form = new FormData();
72
+ form.set(UPLOAD_ARGS_PART, serialized);
73
+ const blobs = await Promise.all(files.map(async file => file instanceof Blob ? file : new Blob([await file.arrayBuffer()], {
74
+ type: file.type
75
+ })));
76
+ for (let i = 0; i < blobs.length; i++) {
77
+ form.set(UPLOAD_FILE_PART + i, blobs[i], files[i].name ?? "blob");
78
+ }
79
+ return form;
80
+ }
81
+
35
82
  function enableRichArguments() {
36
83
  configureServerFunctionsClient({
37
- serializeArgs: args => serializeString(args, argumentEncodeCodec(getServerFunctionsCodec()))
84
+ serializeArgs: async args => {
85
+ const files = [];
86
+ const serialized = await serializeString(args, argumentEncodeCodec(getServerFunctionsCodec(), [createUploadSerializer(files)]));
87
+ return files.length ? await createUploadBody(serialized, files) : serialized;
88
+ }
38
89
  });
39
90
  }
40
91