@solidjs/web 2.0.0-rc.15 → 2.0.0-rc.17

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 (55) hide show
  1. package/README.md +1 -1
  2. package/dist/server.dev.js +361 -483
  3. package/dist/server.js +346 -391
  4. package/dist/server.observe.js +346 -391
  5. package/dist/web.dev.js +110 -55
  6. package/dist/web.js +51 -50
  7. package/dist/web.observe.js +61 -55
  8. package/frames/dist/client.dev.js +610 -621
  9. package/frames/dist/client.js +540 -566
  10. package/frames/dist/client.observe.js +571 -573
  11. package/frames/dist/regions.js +43 -2
  12. package/frames/dist/server.dev.js +793 -424
  13. package/frames/dist/server.js +792 -371
  14. package/frames/dist/server.observe.js +792 -371
  15. package/frames/dist/wire.js +371 -6
  16. package/package.json +11 -11
  17. package/serialization/dist/decode.js +9 -7
  18. package/serialization/dist/serialization.js +9 -7
  19. package/serialization/types/serializer-decode.d.ts +2 -2
  20. package/server-functions/dist/client.dev.js +13 -22
  21. package/server-functions/dist/client.js +11 -22
  22. package/server-functions/dist/client.observe.js +13 -22
  23. package/server-functions/dist/rich-args.js +84 -1
  24. package/server-functions/dist/server.dev.js +194 -20
  25. package/server-functions/dist/server.js +194 -20
  26. package/server-functions/dist/server.observe.js +194 -20
  27. package/skills/server-components/SKILL.md +74 -185
  28. package/types/client.d.ts +27 -5
  29. package/types/diagnostics.d.ts +16 -0
  30. package/types/frames/assets-tier.d.ts +2 -2
  31. package/types/frames/client.d.ts +8 -3
  32. package/types/frames/frame-client.d.ts +121 -157
  33. package/types/frames/frame-morph.d.ts +28 -0
  34. package/types/frames/frame-sink.d.ts +13 -9
  35. package/types/frames/frame-transport.d.ts +30 -1
  36. package/types/frames/regions-tier.d.ts +15 -0
  37. package/types/frames/serializer-decode.d.ts +2 -2
  38. package/types/frames/server.d.ts +0 -52
  39. package/types/frames/wire-tier.d.ts +54 -1
  40. package/types/index.d.ts +2 -2
  41. package/types/jsx.d.ts +11 -5
  42. package/types/observe.d.ts +14 -7
  43. package/types/render.d.ts +3 -1
  44. package/types/response.d.ts +5 -4
  45. package/types/serializer-decode.d.ts +2 -2
  46. package/types/server-functions/argument-codec.d.ts +30 -0
  47. package/types/server-functions/client.d.ts +27 -9
  48. package/types/server-functions/server.d.ts +23 -2
  49. package/types/server-functions/shared.d.ts +19 -0
  50. package/types/server-functions/uploads.d.ts +50 -0
  51. package/types/server-observe.d.ts +3 -2
  52. package/types/server.d.ts +58 -77
  53. package/frames/dist/bind.dev.js +0 -326
  54. package/frames/dist/bind.js +0 -295
  55. package/types/frames/bind-tier.d.ts +0 -60
@@ -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}`);
@@ -849,7 +847,7 @@ async function createRequest(base, id, options, meta) {
849
847
  init = prepared || init;
850
848
  }
851
849
  const send = config.fetch || fetch;
852
- return send(base, init);
850
+ return (meta.fetch || send)(base, init, send);
853
851
  }
854
852
  async function initializeResponse(base, id, options, args, meta) {
855
853
  if (args.length === 0) {
@@ -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}`);
@@ -965,7 +963,7 @@ async function createRequest(base, id, options, meta) {
965
963
  }
966
964
  if (observation) observation.request(base, init);
967
965
  const send = config.fetch || fetch;
968
- return send(base, init);
966
+ return (meta.fetch || send)(base, init, send);
969
967
  }
970
968
  async function initializeResponse(base, id, options, args, meta) {
971
969
  if (args.length === 0) {
@@ -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);
@@ -1057,6 +1054,7 @@ async function dispatchServerFunction(base, id, options, args, meta, callArgs =
1057
1054
  ...options,
1058
1055
  [CALL_OBSERVATION]: observation
1059
1056
  };
1057
+ const startedAt = handler ? performance.now() : undefined;
1060
1058
  const response = await initializeResponse(base, id, options, args, meta);
1061
1059
  if (observation) observation.response(response);
1062
1060
  if (handler) {
@@ -1067,6 +1065,7 @@ async function dispatchServerFunction(base, id, options, args, meta, callArgs =
1067
1065
  context,
1068
1066
  retry: () => fetchServerFunction(base, id, sent, args, meta, callArgs)
1069
1067
  };
1068
+ ctx.startedAt = startedAt;
1070
1069
  if (options[LIVE_WIRE]) ctx[LIVE_WIRE] = options[LIVE_WIRE];
1071
1070
  const handled = handler.handle(response, ctx);
1072
1071
  if (handled !== undefined) return handled;
@@ -1207,6 +1206,9 @@ function GET(fn) {
1207
1206
  method: "GET"
1208
1207
  });
1209
1208
  }
1209
+ function broadcast(fn) {
1210
+ return live(fn);
1211
+ }
1210
1212
  function localOrSend(hit, send) {
1211
1213
  if (hit === null || typeof hit.then !== "function") return hit;
1212
1214
  return hit.then(answer => answer === undefined ? send() : answer);
@@ -1219,6 +1221,7 @@ function live(fn) {
1219
1221
  if (!isServerFunction(fn)) {
1220
1222
  throw new Error("live expects a server function reference");
1221
1223
  }
1224
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = rpc.GET(fn);
1222
1225
  const id = fn.id;
1223
1226
  const metadata = {
1224
1227
  ...getServerFunctionMetadata(fn),
@@ -1306,19 +1309,7 @@ function live(fn) {
1306
1309
  wire.headers = from ? from.headers : undefined;
1307
1310
  if (from && from.position !== undefined) wire.position = from.position;
1308
1311
  }
1309
- if (metadata.method === "GET") return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1310
- if (handler && handler.intercept && !wire.adopted) {
1311
- const hit = handler.intercept({
1312
- id,
1313
- meta: metadata,
1314
- args
1315
- });
1316
- if (hit !== undefined) return hit;
1317
- }
1318
- return fetchServerFunction(liveAddressFor(fn.url), id, {
1319
- ...wireOptions,
1320
- read: true
1321
- }, args, metadata, args);
1312
+ return fn[SERVER_FUNCTION_INVOKE](args, wireOptions);
1322
1313
  };
1323
1314
  const pull = async () => {
1324
1315
  if (resume !== undefined) {
@@ -1447,4 +1438,4 @@ function getServerFunctionInvocation() {
1447
1438
  return undefined;
1448
1439
  }
1449
1440
 
1450
- 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 };
@@ -1,8 +1,91 @@
1
1
  import { configureServerFunctionsClient, serializeString, getServerFunctionsCodec } from '@solidjs/web/server-functions/client';
2
2
 
3
+ const REFUSED_ARGUMENT = Symbol("solid.serverFunction.refusedArgument");
4
+ function refusedArgumentError(name = "Response or Request") {
5
+ const error = new TypeError(`Server function arguments cannot carry Response or Request values (got a ${name}). ` + "Pass the data it holds — its body, headers or url — instead.");
6
+ error[REFUSED_ARGUMENT] = true;
7
+ return error;
8
+ }
9
+ function encodeRefusal(name) {
10
+ const refuse = () => {
11
+ throw refusedArgumentError(name);
12
+ };
13
+ return {
14
+ tag: `seroval-plugins/web/${name}`,
15
+ test: value => typeof globalThis[name] === "function" && value instanceof globalThis[name],
16
+ parse: {
17
+ sync: refuse,
18
+ async: refuse,
19
+ stream: refuse
20
+ },
21
+ serialize: refuse,
22
+ deserialize: refuse
23
+ };
24
+ }
25
+ let encodeRefusals;
26
+ function argumentEncodeCodec(codec, extra = []) {
27
+ if (!encodeRefusals) encodeRefusals = [encodeRefusal("Response"), encodeRefusal("Request")];
28
+ const refusals = extra.length ? [...extra, ...encodeRefusals] : encodeRefusals;
29
+ return {
30
+ ...codec,
31
+ plugins: codec && codec.plugins ? [...refusals, ...codec.plugins] : refusals
32
+ };
33
+ }
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
+
3
82
  function enableRichArguments() {
4
83
  configureServerFunctionsClient({
5
- serializeArgs: args => serializeString(args, 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
+ }
6
89
  });
7
90
  }
8
91
 
@@ -56,11 +56,9 @@ function parseTraceparent(value) {
56
56
  };
57
57
  }
58
58
  function randomHex(bytes) {
59
- const buffer = new Uint8Array(bytes);
60
- crypto.getRandomValues(buffer);
61
59
  let out = "";
62
- for (let i = 0; i < buffer.length; i++) out += (buffer[i] < 16 ? "0" : "") + buffer[i].toString(16);
63
- return out;
60
+ for (let i = 0; i < bytes; i += 4) out += (Math.random() * 0x100000000 >>> 0).toString(16).padStart(8, "0");
61
+ return out.length === bytes * 2 ? out : out.slice(0, bytes * 2);
64
62
  }
65
63
  function randomTraceId() {
66
64
  let id = randomHex(16);
@@ -853,6 +851,10 @@ function createEventChunk(data, id) {
853
851
  return CHUNK_ENCODER.encode(event + "\n");
854
852
  }
855
853
  const EVENT_STREAM_HEARTBEAT = /* @__PURE__ */new TextEncoder().encode(":\n\n");
854
+ function isEventStream(source) {
855
+ const contentType = source.headers.get("content-type");
856
+ return !!contentType && contentType.startsWith("text/event-stream");
857
+ }
856
858
  function positionDigest(value) {
857
859
  if (value === undefined || !isJSONSafe(value)) return undefined;
858
860
  const text = JSON.stringify(value);
@@ -915,7 +917,7 @@ async function deserializeStream(source, codecOptions, wire) {
915
917
  if (!source.body) {
916
918
  throw new Error("missing body");
917
919
  }
918
- const reader = new ChunkReader(source.body);
920
+ const reader = wire && isEventStream(source) ? wire.open(source.body) : new ChunkReader(source.body);
919
921
  try {
920
922
  const result = await reader.next();
921
923
  if (!result.done) {
@@ -934,10 +936,18 @@ async function deserializeStream(source, codecOptions, wire) {
934
936
  }
935
937
  const connection = wire && wire.connection;
936
938
  let endConnection;
937
- if (connection) ;
939
+ if (connection) connection.ended = new Promise(resolve => endConnection = resolve);
938
940
  const end = error => {
939
941
  const sweep = () => deserializeChunk.abort(error);
940
- if (connection) ; else sweep();
942
+ if (connection) {
943
+ const close = () => deserializeChunk.close();
944
+ endConnection({
945
+ open: deserializeChunk.open(),
946
+ error,
947
+ sweep,
948
+ close
949
+ });
950
+ } else sweep();
941
951
  };
942
952
  reader.drain(interpretChunk).then(() => end(new Error("Server function stream ended unexpectedly.")), error => end(error));
943
953
  return interpretChunk(result.value);
@@ -947,9 +957,6 @@ async function deserializeStream(source, codecOptions, wire) {
947
957
  throw error;
948
958
  }
949
959
  }
950
- async function deserializeString(text, codecOptions) {
951
- return await deserializeStream(new Response(text), codecOptions);
952
- }
953
960
  async function decodeResponse(response, codecOptions) {
954
961
  if (!response.body) return undefined;
955
962
  return await extractBody(response.clone(), codecOptions === undefined ? codecConfig.codec : codecOptions);
@@ -1268,6 +1275,96 @@ async function decodeFlashCookie(cookieHeader) {
1268
1275
  }
1269
1276
  }
1270
1277
 
1278
+ const RESPONSE_TAG = "seroval-plugins/web/Response";
1279
+ const REQUEST_TAG = "seroval-plugins/web/Request";
1280
+ const REFUSED_TAGS = [RESPONSE_TAG, REQUEST_TAG];
1281
+ const RESOLVED_PLUGINS = Symbol.for("solid.codec.resolvedPlugins");
1282
+ const REFUSED_ARGUMENT = Symbol("solid.serverFunction.refusedArgument");
1283
+ function refusedArgumentError(name = "Response or Request") {
1284
+ const error = new TypeError(`Server function arguments cannot carry Response or Request values (got a ${name}). ` + "Pass the data it holds — its body, headers or url — instead.");
1285
+ error[REFUSED_ARGUMENT] = true;
1286
+ return error;
1287
+ }
1288
+ function refusedArgument(error) {
1289
+ for (let depth = 0; depth < 4 && error !== null && typeof error === "object"; depth++) {
1290
+ if (error[REFUSED_ARGUMENT] === true) return error;
1291
+ error = error.cause;
1292
+ }
1293
+ }
1294
+ const refused = plugin => REFUSED_TAGS.includes(plugin.tag);
1295
+ const reachesRefused = plugin => refused(plugin) || !!plugin.extends && plugin.extends.some(reachesRefused);
1296
+ function filterPlugins(plugins, out, seen) {
1297
+ for (const plugin of plugins) {
1298
+ if (seen.has(plugin)) continue;
1299
+ seen.add(plugin);
1300
+ if (refused(plugin)) continue;
1301
+ const severs = !!plugin.extends && plugin.extends.some(reachesRefused);
1302
+ out.push(severs ? {
1303
+ ...plugin,
1304
+ extends: undefined
1305
+ } : plugin);
1306
+ if (plugin.extends) filterPlugins(plugin.extends, out, seen);
1307
+ }
1308
+ return out;
1309
+ }
1310
+ let defaultArgumentPlugins;
1311
+ const customArgumentPlugins = new WeakMap();
1312
+ function argumentDecodeCodec(codec, defaults) {
1313
+ const custom = codec && codec.plugins;
1314
+ let plugins = custom ? customArgumentPlugins.get(custom) : defaultArgumentPlugins;
1315
+ if (!plugins) {
1316
+ plugins = filterPlugins(custom ? [...custom, ...defaults] : defaults, [], new Set());
1317
+ if (custom) customArgumentPlugins.set(custom, plugins);else defaultArgumentPlugins = plugins;
1318
+ }
1319
+ return {
1320
+ ...codec,
1321
+ [RESOLVED_PLUGINS]: plugins
1322
+ };
1323
+ }
1324
+ function namesRefusedType(payload) {
1325
+ for (const tag of REFUSED_TAGS) if (payload.includes(`"c":"${tag}"`)) return true;
1326
+ return false;
1327
+ }
1328
+ function withArgumentPlugins(argumentCodec, extra) {
1329
+ return {
1330
+ ...argumentCodec,
1331
+ [RESOLVED_PLUGINS]: [...extra, ...argumentCodec[RESOLVED_PLUGINS]]
1332
+ };
1333
+ }
1334
+
1335
+ const UPLOAD_ARGS_PART = "args";
1336
+ const UPLOAD_FILE_PART = "file";
1337
+ const UPLOAD_TAG = "solid/server-function-upload";
1338
+ function isBlob(value) {
1339
+ if (typeof Blob !== "undefined" && value instanceof Blob) return true;
1340
+ return typeof value === "object" && value !== null && typeof value.size === "number" && typeof value.type === "string" && typeof value.arrayBuffer === "function" && typeof value.slice === "function";
1341
+ }
1342
+ function malformed() {
1343
+ return new TypeError("Malformed server function upload");
1344
+ }
1345
+ function createUploadDeserializer(form) {
1346
+ const refuse = () => {
1347
+ throw malformed();
1348
+ };
1349
+ return {
1350
+ tag: UPLOAD_TAG,
1351
+ test: () => false,
1352
+ parse: {
1353
+ sync: refuse,
1354
+ async: refuse,
1355
+ stream: refuse
1356
+ },
1357
+ serialize: refuse,
1358
+ deserialize: (node, ctx) => {
1359
+ const index = ctx.deserialize(node.i);
1360
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) refuse();
1361
+ const part = form.get(UPLOAD_FILE_PART + index);
1362
+ if (!isBlob(part)) refuse();
1363
+ return part;
1364
+ }
1365
+ };
1366
+ }
1367
+
1271
1368
  const config = {
1272
1369
  provideEvent: undefined,
1273
1370
  wrapInvocation: undefined,
@@ -1709,6 +1806,7 @@ function live(fn) {
1709
1806
  if (!isServerFunction(fn) || typeof fn.id !== "string") {
1710
1807
  throw new Error("live expects a server function reference");
1711
1808
  }
1809
+ if (getServerFunctionMetadata(fn)?.method !== "GET") fn = GET(fn);
1712
1810
  const metadata = {
1713
1811
  ...getServerFunctionMetadata(fn),
1714
1812
  live: true
@@ -1723,6 +1821,18 @@ function live(fn) {
1723
1821
  });
1724
1822
  return wrapped;
1725
1823
  }
1824
+ function broadcast(fn) {
1825
+ const ref = live(fn);
1826
+ ref[SERVER_FUNCTION_METADATA].broadcast = true;
1827
+ BROADCASTS.add(fn.id);
1828
+ return ref;
1829
+ }
1830
+ function encodedArguments(request, argsEncoding, argumentBytes) {
1831
+ if (request.method !== "POST") return argsEncoding || "";
1832
+ if (!argumentBytes) return undefined;
1833
+ return (request.headers.get("content-type") || "") + "\0" + (argsEncoding || "") + "\0" + new TextDecoder("latin1").decode(argumentBytes);
1834
+ }
1835
+ const BROADCASTS = new Set();
1726
1836
  function brandLive(answer) {
1727
1837
  if (typeof answer === "function" || answer !== null && typeof answer === "object" && answer[Symbol.asyncIterator]) {
1728
1838
  answer[LIVE_SOURCE] = true;
@@ -1833,14 +1943,49 @@ function unknownFormatError(tag) {
1833
1943
  error[FORMAT_SKEW] = true;
1834
1944
  return error;
1835
1945
  }
1836
- async function parseArguments(request, url, scripted, codec) {
1946
+ async function decodeArguments(decode, payload) {
1947
+ if (payload === null) return await decode(undefined);
1948
+ const refuseNamed = () => {
1949
+ const text = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
1950
+ if (namesRefusedType(text)) throw refusedArgumentError();
1951
+ };
1952
+ const connection = {};
1953
+ let value;
1954
+ try {
1955
+ value = await decode({
1956
+ connection
1957
+ });
1958
+ } catch (error) {
1959
+ if (connection.ended) connection.ended.then(end => end.sweep());
1960
+ refuseNamed();
1961
+ throw error;
1962
+ }
1963
+ if (connection.ended) {
1964
+ const {
1965
+ open,
1966
+ sweep
1967
+ } = await connection.ended;
1968
+ sweep();
1969
+ if (open) refuseNamed();
1970
+ }
1971
+ return value;
1972
+ }
1973
+ let decodeModule;
1974
+ async function loadArgumentCodec(codec) {
1975
+ decodeModule = await import('@solidjs/web/serialization/decode');
1976
+ return argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS);
1977
+ }
1978
+ const argumentCodecFor = codec => decodeModule ? argumentDecodeCodec(codec, decodeModule.DEFAULT_WEB_PLUGINS) : loadArgumentCodec(codec);
1979
+ async function parseArguments(request, url, scripted, codec, buffered) {
1837
1980
  const parsed = [];
1838
1981
  const bodyFormat = request.method === "POST" ? request.headers.get(BODY_FORMAT_HEADER) : null;
1839
1982
  const args = url.searchParams.get("args");
1840
1983
  if (args && (!scripted || request.method === "GET" || bodyFormat !== BodyFormat.Serialized)) {
1841
1984
  let result;
1842
1985
  if (args.startsWith(";0x")) {
1843
- result = await deserializeString(args, codec);
1986
+ let argumentCodec = argumentCodecFor(codec);
1987
+ if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
1988
+ result = await decodeArguments(wire => deserializeStream(new Response(args), argumentCodec, wire), args);
1844
1989
  } else {
1845
1990
  result = JSON.parse(args);
1846
1991
  assertDecodeDepth(result);
@@ -1860,7 +2005,24 @@ async function parseArguments(request, url, scripted, codec) {
1860
2005
  throw unknownFormatError(bodyFormat);
1861
2006
  }
1862
2007
  const body = request.clone();
1863
- const decoded = await extractBody(body, codec);
2008
+ let decoded;
2009
+ if (bodyFormat === BodyFormat.Serialized) {
2010
+ let argumentCodec = argumentCodecFor(codec);
2011
+ if (argumentCodec instanceof Promise) argumentCodec = await argumentCodec;
2012
+ if ((request.headers.get("content-type") || "").startsWith("multipart/form-data")) {
2013
+ const form = await body.formData();
2014
+ const encoded = form.get(UPLOAD_ARGS_PART);
2015
+ if (typeof encoded !== "string") {
2016
+ throw new TypeError("Malformed server function upload");
2017
+ }
2018
+ const uploadCodec = withArgumentPlugins(argumentCodec, [createUploadDeserializer(form)]);
2019
+ decoded = await decodeArguments(wire => deserializeStream(new Response(encoded), uploadCodec, wire), encoded);
2020
+ } else {
2021
+ decoded = await decodeArguments(wire => extractBody(body, argumentCodec, wire), buffered);
2022
+ }
2023
+ } else {
2024
+ decoded = await extractBody(body, codec);
2025
+ }
1864
2026
  if (bodyFormat === BodyFormat.Serialized || bodyFormat === BodyFormat.Json) {
1865
2027
  if (bodyFormat === BodyFormat.Json) assertDecodeDepth(decoded);
1866
2028
  if (!Array.isArray(decoded)) {
@@ -2852,6 +3014,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2852
3014
  });
2853
3015
  return finish(protectsRequest ? withCSRFVary(response) : response);
2854
3016
  }
3017
+ let argumentBytes = null;
2855
3018
  if (method === "POST" && request.body !== null && bodySizeLimit !== Infinity) {
2856
3019
  const raw = request.headers.get("content-length");
2857
3020
  const declared = raw !== null && /^\d+$/.test(raw) ? Number(raw) : NaN;
@@ -2877,6 +3040,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2877
3040
  return finish(protectsRequest ? withCSRFVary(response) : response);
2878
3041
  }
2879
3042
  request = withBufferedBody(request, buffered);
3043
+ argumentBytes = buffered;
2880
3044
  }
2881
3045
  let event;
2882
3046
  try {
@@ -2933,10 +3097,10 @@ async function handleServerFunctionRequest(request, options = {}) {
2933
3097
  const collectsFlight = flightHooks.length > 0;
2934
3098
  let parsed;
2935
3099
  try {
2936
- parsed = await parseArguments(request, url, scripted, codec);
3100
+ parsed = await parseArguments(request, url, scripted, codec, argumentBytes);
2937
3101
  } catch (error) {
2938
- const skewed = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true;
2939
- const response = new Response(DEV ? skewed ? error.message : "Malformed server function arguments" : null, {
3102
+ const named = error !== null && typeof error === "object" && error[FORMAT_SKEW] === true ? error : refusedArgument(error);
3103
+ const response = new Response(DEV ? named ? named.message : "Malformed server function arguments" : null, {
2940
3104
  status: 400
2941
3105
  });
2942
3106
  return refuseCommitted(response);
@@ -2960,9 +3124,12 @@ async function handleServerFunctionRequest(request, options = {}) {
2960
3124
  const dispatch = async () => {
2961
3125
  try {
2962
3126
  const invokeOnce = async () => {
3127
+ const shared = !!live && BROADCASTS.has(functionId);
2963
3128
  INVOCATIONS.set(event, {
2964
3129
  id: functionId,
2965
- live: !!live
3130
+ live: !!live,
3131
+ broadcast: shared || undefined,
3132
+ shareKey: shared ? encodedArguments(request, argsEncoding, argumentBytes) : undefined
2966
3133
  });
2967
3134
  const run = () => serverFunction(...parsed);
2968
3135
  return observeInvocation({
@@ -2990,7 +3157,7 @@ async function handleServerFunctionRequest(request, options = {}) {
2990
3157
  response,
2991
3158
  value
2992
3159
  } = result;
2993
- if (!scripted && !handleNoJS && response && response.body) {
3160
+ if (!scripted && !handleNoJS && response && response.body && isJSONSafe(value)) {
2994
3161
  return response;
2995
3162
  }
2996
3163
  if (response && response.headers) {
@@ -3179,11 +3346,15 @@ function ownResponse(response) {
3179
3346
  function finalizeTransportResponse(response, method) {
3180
3347
  const stripBody = method === "HEAD" && response.body !== null;
3181
3348
  const defaultsCache = !response.headers.has("Cache-Control") && response.status !== 304;
3182
- if (stripBody || defaultsCache) {
3349
+ const defaultsSniff = !response.headers.has("X-Content-Type-Options");
3350
+ if (stripBody || defaultsCache || defaultsSniff) {
3183
3351
  try {
3184
3352
  if (defaultsCache) {
3185
3353
  response.headers.set("Cache-Control", "no-store");
3186
3354
  }
3355
+ if (defaultsSniff) {
3356
+ response.headers.set("X-Content-Type-Options", "nosniff");
3357
+ }
3187
3358
  if (!stripBody) return response;
3188
3359
  response.body.cancel().catch(() => {});
3189
3360
  return new Response(null, {
@@ -3194,6 +3365,9 @@ function finalizeTransportResponse(response, method) {
3194
3365
  } catch {
3195
3366
  const headers = new Headers(response.headers);
3196
3367
  if (defaultsCache && !headers.has("Cache-Control")) headers.set("Cache-Control", "no-store");
3368
+ if (defaultsSniff && !headers.has("X-Content-Type-Options")) {
3369
+ headers.set("X-Content-Type-Options", "nosniff");
3370
+ }
3197
3371
  if (stripBody) response.body.cancel().catch(() => {});
3198
3372
  return new Response(stripBody ? null : response.body, {
3199
3373
  status: response.status,
@@ -3205,4 +3379,4 @@ function finalizeTransportResponse(response, method) {
3205
3379
  return response;
3206
3380
  }
3207
3381
 
3208
- export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, clearFlashCookie, configureServerFunctionsServer, createChunk, createEventChunk, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, frameAddress, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serializeStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, textDigest, withMeta };
3382
+ export { ChunkReader, ERROR_HEADER, FLASH_COOKIE, GENERIC_SERVER_ERROR_MESSAGE, GET, REDIRECT_HEADER, SERVER_FUNCTION_INVOKE, SINGLE_FLIGHT_HEADER, UNKNOWN_HEADER, armLiveBody, broadcast, clearFlashCookie, configureServerFunctionsServer, createChunk, createEventChunk, createNoJSHandler, createServerReference, decodeErrorHeaderValue, decodeFlashCookie, decodeRedirectHeaderValue, decodeResponse, decodeResponsePayload, encodeErrorHeaderValue, encodeFlashCookie, foldSetCookies, frameAddress, getEventServerFunctionInvocation, getServerFunction, getServerFunctionInvocation, getServerFunctionMetadata, guardFailures, handleServerFunctionRequest, hasFlashCookie, invoke, isServerFunction, live, parseServerFunctionActionUrl, registerFlightDataSource, registerServerFunction, registerServerReference, sanitizeServerError, serializeResponseStream, serializeStream, serverFunctionActionUrl, serverFunctionUrl, setServerFunctionsDev, subscribeFlightData, textDigest, withMeta };