@solidjs/start 2.0.0-alpha.1 → 2.0.0-alpha.3

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 (119) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/config/constants.d.ts +1 -1
  3. package/dist/config/constants.js +1 -1
  4. package/dist/config/dev-server.js +18 -0
  5. package/dist/config/env.d.ts +19 -0
  6. package/dist/config/env.js +81 -0
  7. package/dist/config/fs-routes/fs-watcher.js +14 -20
  8. package/dist/config/fs-routes/index.js +2 -2
  9. package/dist/config/fs-routes/router.js +7 -8
  10. package/dist/config/index.d.ts +16 -1
  11. package/dist/config/index.js +30 -29
  12. package/dist/config/lazy.js +35 -5
  13. package/dist/config/manifest.js +40 -6
  14. package/dist/config/vite-utils.d.ts +6 -1
  15. package/dist/config/vite-utils.js +7 -3
  16. package/dist/directives/bubble-function-declaration.d.ts +3 -0
  17. package/dist/directives/bubble-function-declaration.js +23 -0
  18. package/dist/directives/compile.d.ts +9 -0
  19. package/dist/directives/compile.js +40 -0
  20. package/dist/directives/generate-unique-name.d.ts +3 -0
  21. package/dist/directives/generate-unique-name.js +16 -0
  22. package/dist/directives/get-descriptive-name.d.ts +2 -0
  23. package/dist/directives/get-descriptive-name.js +37 -0
  24. package/dist/directives/get-import-identifier.d.ts +4 -0
  25. package/dist/directives/get-import-identifier.js +19 -0
  26. package/dist/directives/get-root-statement-path.d.ts +2 -0
  27. package/dist/directives/get-root-statement-path.js +12 -0
  28. package/dist/directives/index.d.ts +14 -0
  29. package/dist/directives/index.js +169 -0
  30. package/dist/directives/is-statement-top-level.d.ts +3 -0
  31. package/dist/directives/is-statement-top-level.js +9 -0
  32. package/dist/directives/paths.d.ts +9 -0
  33. package/dist/directives/paths.js +36 -0
  34. package/dist/directives/plugin.d.ts +21 -0
  35. package/dist/directives/plugin.js +302 -0
  36. package/dist/directives/remove-unused-variables.d.ts +3 -0
  37. package/dist/directives/remove-unused-variables.js +53 -0
  38. package/dist/directives/types.d.ts +10 -0
  39. package/dist/directives/xxhash32.d.ts +6 -0
  40. package/dist/directives/xxhash32.js +193 -0
  41. package/dist/{server/server-runtime.d.ts → fns/client.d.ts} +1 -1
  42. package/dist/fns/client.js +106 -0
  43. package/dist/fns/handler.d.ts +5 -0
  44. package/dist/{server/server-functions-handler.js → fns/handler.js} +55 -96
  45. package/dist/fns/registration.d.ts +2 -0
  46. package/dist/fns/registration.js +12 -0
  47. package/dist/fns/serialization.d.ts +6 -0
  48. package/dist/fns/serialization.js +208 -0
  49. package/dist/fns/server.d.ts +7 -0
  50. package/dist/{server/server-fns-runtime.js → fns/server.js} +7 -1
  51. package/dist/fns/shared.d.ts +17 -0
  52. package/dist/fns/shared.js +105 -0
  53. package/dist/http/index.d.ts +1 -1
  54. package/dist/middleware/index.d.ts +20 -0
  55. package/dist/middleware/index.js +21 -1
  56. package/dist/server/StartServer.jsx +2 -0
  57. package/dist/server/assets/PatchVirtualDevStyles.d.ts +4 -0
  58. package/dist/server/assets/PatchVirtualDevStyles.jsx +28 -0
  59. package/dist/server/collect-styles.js +9 -21
  60. package/dist/server/handler.d.ts +61 -3
  61. package/dist/server/handler.js +18 -15
  62. package/dist/server/spa/StartServer.jsx +2 -0
  63. package/dist/server/spa/handler.d.ts +30 -1
  64. package/dist/server/types.d.ts +1 -1
  65. package/dist/shared/dev-overlay/CodeView.jsx +4 -4
  66. package/dist/shared/dev-overlay/DevOverlayDialog.jsx +34 -34
  67. package/dist/shared/dev-overlay/index.jsx +2 -2
  68. package/dist/shared/dev-overlay/styles.css +40 -40
  69. package/package.json +27 -20
  70. package/src/config/constants.ts +1 -1
  71. package/src/config/dev-server.ts +12 -0
  72. package/src/config/env.ts +105 -0
  73. package/src/config/fs-routes/fs-watcher.ts +17 -24
  74. package/src/config/fs-routes/index.ts +2 -2
  75. package/src/config/fs-routes/router.ts +7 -8
  76. package/src/config/index.ts +44 -40
  77. package/src/config/lazy.ts +36 -5
  78. package/src/config/manifest.ts +40 -9
  79. package/src/config/vite-utils.ts +8 -4
  80. package/src/directives/bubble-function-declaration.ts +33 -0
  81. package/src/directives/compile.ts +54 -0
  82. package/src/directives/generate-unique-name.ts +22 -0
  83. package/src/directives/get-descriptive-name.ts +39 -0
  84. package/src/directives/get-import-identifier.ts +34 -0
  85. package/src/directives/get-root-statement-path.ts +14 -0
  86. package/src/directives/index.ts +232 -0
  87. package/src/directives/is-statement-top-level.ts +13 -0
  88. package/src/directives/paths.ts +63 -0
  89. package/src/directives/plugin.ts +389 -0
  90. package/src/directives/remove-unused-variables.ts +55 -0
  91. package/src/directives/types.ts +12 -0
  92. package/src/directives/xxhash32.ts +214 -0
  93. package/src/env.d.ts +1 -1
  94. package/src/fns/client.ts +141 -0
  95. package/src/fns/handler.spec.ts +85 -0
  96. package/src/{server/server-functions-handler.ts → fns/handler.ts} +65 -117
  97. package/src/fns/registration.ts +19 -0
  98. package/src/fns/serialization.ts +250 -0
  99. package/src/{server/server-fns-runtime.ts → fns/server.ts} +17 -2
  100. package/src/fns/shared.ts +116 -0
  101. package/src/middleware/index.ts +21 -1
  102. package/src/server/StartServer.tsx +2 -0
  103. package/src/server/assets/PatchVirtualDevStyles.tsx +31 -0
  104. package/src/server/collect-styles.ts +9 -26
  105. package/src/server/handler.ts +20 -16
  106. package/src/server/spa/StartServer.tsx +2 -0
  107. package/src/server/types.ts +1 -1
  108. package/src/shared/dev-overlay/CodeView.tsx +5 -7
  109. package/src/shared/dev-overlay/DevOverlayDialog.tsx +34 -34
  110. package/src/shared/dev-overlay/get-source-map.ts +1 -1
  111. package/src/shared/dev-overlay/index.tsx +4 -4
  112. package/src/shared/dev-overlay/styles.css +40 -40
  113. package/tsconfig.json +1 -0
  114. package/dist/server/fetchEvent.spec.js +0 -65
  115. package/dist/server/server-fns-runtime.d.ts +0 -1
  116. package/dist/server/server-functions-handler.d.ts +0 -2
  117. package/dist/server/server-runtime.js +0 -194
  118. package/src/server/server-runtime.ts +0 -240
  119. /package/dist/{server/fetchEvent.spec.d.ts → directives/types.js} +0 -0
@@ -1,73 +1,27 @@
1
- import { getServerFnById } from "solidstart:server-fn-manifest";
2
1
  import { parseSetCookie } from "cookie-es";
3
2
  import { type H3Event, parseCookies } from "h3";
4
- import { crossSerializeStream, fromJSON, getCrossReferenceHeader } from "seroval";
5
- import {
6
- CustomEventPlugin,
7
- DOMExceptionPlugin,
8
- EventPlugin,
9
- FormDataPlugin,
10
- HeadersPlugin,
11
- ReadableStreamPlugin,
12
- RequestPlugin,
13
- ResponsePlugin,
14
- URLPlugin,
15
- URLSearchParamsPlugin,
16
- } from "seroval-plugins/web";
17
3
  import { sharedConfig } from "solid-js";
18
4
  import { renderToString } from "solid-js/web";
19
5
  import { provideRequestEvent } from "solid-js/web/storage";
20
6
 
21
- import { getFetchEvent, mergeResponseHeaders } from "./fetchEvent.ts";
22
- import { createPageEvent } from "./handler.ts";
23
- import type { FetchEvent, PageEvent } from "./types.ts";
24
- import { getExpectedRedirectStatus } from "./util.ts";
25
-
26
- function createChunk(data: string) {
27
- const encodeData = new TextEncoder().encode(data);
28
- const bytes = encodeData.length;
29
- const baseHex = bytes.toString(16);
30
- const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex; // 32-bit
31
- const head = new TextEncoder().encode(`;0x${totalHex};`);
7
+ import { getFetchEvent, mergeResponseHeaders } from "../server/fetchEvent.ts";
8
+ import { createPageEvent } from "../server/handler.ts";
9
+ import {
10
+ deserializeFromJSONString,
11
+ serializeToJSONStream,
12
+ serializeToJSStream,
13
+ } from "./serialization.ts";
14
+ import {
15
+ BODY_FORMAT_KEY,
16
+ BodyFormat,
17
+ extractBody,
18
+ getHeadersAndBody,
19
+ } from "./shared.ts";
20
+ import "solid-start:server-fn-manifest";
32
21
 
33
- const chunk = new Uint8Array(12 + bytes);
34
- chunk.set(head);
35
- chunk.set(encodeData, 12);
36
- return chunk;
37
- }
38
-
39
- function serializeToStream(id: string, value: any) {
40
- return new ReadableStream({
41
- start(controller) {
42
- crossSerializeStream(value, {
43
- scopeId: id,
44
- plugins: [
45
- CustomEventPlugin,
46
- DOMExceptionPlugin,
47
- EventPlugin,
48
- FormDataPlugin,
49
- HeadersPlugin,
50
- ReadableStreamPlugin,
51
- RequestPlugin,
52
- ResponsePlugin,
53
- URLSearchParamsPlugin,
54
- URLPlugin,
55
- ],
56
- onSerialize(data: string, initial: boolean) {
57
- controller.enqueue(
58
- createChunk(initial ? `(${getCrossReferenceHeader(id)},${data})` : data),
59
- );
60
- },
61
- onDone() {
62
- controller.close();
63
- },
64
- onError(error: any) {
65
- controller.error(error);
66
- },
67
- });
68
- },
69
- });
70
- }
22
+ import { getServerFunction } from "./registration.ts";
23
+ import type { FetchEvent, PageEvent } from "../server/types.ts";
24
+ import { getExpectedRedirectStatus } from "../server/util.ts";
71
25
 
72
26
  export async function handleServerFunction(h3Event: H3Event) {
73
27
  const event = getFetchEvent(h3Event);
@@ -91,59 +45,27 @@ export async function handleServerFunction(h3Event: H3Event) {
91
45
  }
92
46
  }
93
47
 
94
- const serverFunction = await getServerFnById(functionId!);
48
+ const serverFunction = getServerFunction(functionId!);
95
49
 
96
50
  let parsed: any[] = [];
97
51
 
98
52
  // grab bound arguments from url when no JS
99
- if (!instance || h3Event.method === "GET") {
53
+ if (!instance || request.method === "GET") {
100
54
  const args = url.searchParams.get("args");
101
55
  if (args) {
102
- const json = JSON.parse(args);
103
- (json.t
104
- ? (fromJSON(json, {
105
- plugins: [
106
- CustomEventPlugin,
107
- DOMExceptionPlugin,
108
- EventPlugin,
109
- FormDataPlugin,
110
- HeadersPlugin,
111
- ReadableStreamPlugin,
112
- RequestPlugin,
113
- ResponsePlugin,
114
- URLSearchParamsPlugin,
115
- URLPlugin,
116
- ],
117
- }) as any)
118
- : json
119
- ).forEach((arg: any) => {
56
+ const result = (await deserializeFromJSONString(args)) as any[];
57
+ for (const arg of result) {
120
58
  parsed.push(arg);
121
- });
59
+ }
122
60
  }
123
61
  }
124
- if (h3Event.method === "POST") {
125
- const contentType = request.headers.get("content-type");
126
-
127
- if (
128
- contentType?.startsWith("multipart/form-data") ||
129
- contentType?.startsWith("application/x-www-form-urlencoded")
130
- ) {
131
- parsed.push(await event.request.formData());
132
- } else if (contentType?.startsWith("application/json")) {
133
- parsed = fromJSON(await event.request.json(), {
134
- plugins: [
135
- CustomEventPlugin,
136
- DOMExceptionPlugin,
137
- EventPlugin,
138
- FormDataPlugin,
139
- HeadersPlugin,
140
- ReadableStreamPlugin,
141
- RequestPlugin,
142
- ResponsePlugin,
143
- URLSearchParamsPlugin,
144
- URLPlugin,
145
- ],
146
- });
62
+ if (request.method === "POST" && request.body !== null) {
63
+ const bodyFormat = request.headers.get(BODY_FORMAT_KEY);
64
+ const decoded = await extractBody("", false, request.clone());
65
+ if (bodyFormat === BodyFormat.Seroval) {
66
+ parsed = decoded as any[];
67
+ } else {
68
+ parsed.push(decoded);
147
69
  }
148
70
  }
149
71
  try {
@@ -171,16 +93,26 @@ export async function handleServerFunction(h3Event: H3Event) {
171
93
  h3Event.res.status = result.status;
172
94
  if ((result as any).customBody) {
173
95
  result = await (result as any).customBody();
174
- } else if (result.body == undefined) result = null;
96
+ } else if (result.body == null) result = null;
175
97
  }
176
98
  }
177
99
 
178
100
  // handle no JS success case
179
101
  if (!instance) return handleNoJS(result, request, parsed);
180
102
 
181
- h3Event.res.headers.set("content-type", "text/javascript");
182
-
183
- return serializeToStream(instance, result);
103
+ const body = getHeadersAndBody(result);
104
+ if (body) {
105
+ return new Response(body.body, {
106
+ headers: body.headers,
107
+ });
108
+ }
109
+ h3Event.res.headers.set(BODY_FORMAT_KEY, BodyFormat.Seroval);
110
+ if (import.meta.env.SEROVAL_MODE === "js") {
111
+ h3Event.res.headers.set("content-type", "text/javascript");
112
+ return serializeToJSStream(instance, result);
113
+ }
114
+ h3Event.res.headers.set("content-type", "text/plain");
115
+ return serializeToJSONStream(result);
184
116
  } catch (x) {
185
117
  if (x instanceof Response) {
186
118
  if (singleFlight && instance) {
@@ -192,8 +124,8 @@ export async function handleServerFunction(h3Event: H3Event) {
192
124
  if ((x as any).status && (!instance || (x as any).status < 300 || (x as any).status >= 400))
193
125
  h3Event.res.status = (x as any).status;
194
126
  if ((x as any).customBody) {
195
- x = (x as any).customBody();
196
- } else if ((x as any).body === undefined) x = null;
127
+ x = await (x as any).customBody();
128
+ } else if ((x as any).body == null) x = null;
197
129
  h3Event.res.headers.set("X-Error", "true");
198
130
  } else if (instance) {
199
131
  const error = x instanceof Error ? x.message : typeof x === "string" ? x : "true";
@@ -203,8 +135,24 @@ export async function handleServerFunction(h3Event: H3Event) {
203
135
  x = handleNoJS(x, request, parsed, true);
204
136
  }
205
137
  if (instance) {
206
- h3Event.res.headers.set("content-type", "text/javascript");
207
- return serializeToStream(instance, x);
138
+ const body = getHeadersAndBody(x);
139
+ if (body) {
140
+ const headers = new Headers(body.headers as HeadersInit);
141
+ const errorHeader = h3Event.res.headers.get("X-Error");
142
+ if (errorHeader !== null) {
143
+ headers.set("X-Error", errorHeader);
144
+ }
145
+ return new Response(body.body, {
146
+ headers: body.headers,
147
+ });
148
+ }
149
+ h3Event.res.headers.set(BODY_FORMAT_KEY, BodyFormat.Seroval);
150
+ if (import.meta.env.SEROVAL_MODE === "js") {
151
+ h3Event.res.headers.set("content-type", "text/javascript");
152
+ return serializeToJSStream(instance, x);
153
+ }
154
+ h3Event.res.headers.set("content-type", "text/plain");
155
+ return serializeToJSONStream(x);
208
156
  }
209
157
  return x;
210
158
  }
@@ -249,12 +197,12 @@ function handleNoJS(result: any, request: Request, parsed: any[], thrown?: boole
249
197
  }
250
198
 
251
199
  let App: any;
252
- function createSingleFlightHeaders(sourceEvent: FetchEvent) {
200
+ export function createSingleFlightHeaders(sourceEvent: FetchEvent) {
253
201
  // cookie handling logic is pretty simplistic so this might be imperfect
254
202
  // unclear if h3 internals are available on all platforms but we need a way to
255
203
  // update request headers on the underlying H3 event.
256
204
 
257
- const headers = sourceEvent.request.headers;
205
+ const headers = new Headers(sourceEvent.request.headers);
258
206
  const cookies = parseCookies(sourceEvent.nativeEvent);
259
207
  const SetCookies = sourceEvent.response.headers.getSetCookie();
260
208
  headers.delete("cookie");
@@ -0,0 +1,19 @@
1
+ const REGISTRATIONS = new Map<string, Function>();
2
+
3
+ export function registerServerFunction<T extends any[], R>(
4
+ id: string,
5
+ callback: (...args: T) => Promise<R>,
6
+ ) {
7
+ REGISTRATIONS.set(id, callback);
8
+ return callback;
9
+ }
10
+
11
+ export function getServerFunction<T extends any[], R>(
12
+ id: string,
13
+ ): ((...args: T) => Promise<R>) {
14
+ const fn = REGISTRATIONS.get(id) as ((...args: T) => Promise<R>) | undefined;
15
+ if (fn) {
16
+ return fn;
17
+ }
18
+ throw new Error('invalid server function: ' + id);
19
+ }
@@ -0,0 +1,250 @@
1
+ import {
2
+ crossSerializeStream,
3
+ deserialize,
4
+ Feature,
5
+ fromCrossJSON,
6
+ getCrossReferenceHeader,
7
+ type SerovalNode,
8
+ toCrossJSONStream,
9
+ } from "seroval";
10
+ import {
11
+ AbortSignalPlugin,
12
+ CustomEventPlugin,
13
+ DOMExceptionPlugin,
14
+ EventPlugin,
15
+ FormDataPlugin,
16
+ HeadersPlugin,
17
+ ReadableStreamPlugin,
18
+ RequestPlugin,
19
+ ResponsePlugin,
20
+ URLPlugin,
21
+ URLSearchParamsPlugin,
22
+ } from "seroval-plugins/web";
23
+
24
+ // TODO(Alexis): if we can, allow providing an option to extend these.
25
+ const DEFAULT_PLUGINS = [
26
+ AbortSignalPlugin,
27
+ CustomEventPlugin,
28
+ DOMExceptionPlugin,
29
+ EventPlugin,
30
+ FormDataPlugin,
31
+ HeadersPlugin,
32
+ ReadableStreamPlugin,
33
+ RequestPlugin,
34
+ ResponsePlugin,
35
+ URLSearchParamsPlugin,
36
+ URLPlugin,
37
+ ];
38
+ const MAX_SERIALIZATION_DEPTH_LIMIT = 64;
39
+ const DISABLED_FEATURES = Feature.RegExp;
40
+
41
+ /**
42
+ * Alexis:
43
+ *
44
+ * A "chunk" is a piece of data emitted by the streaming serializer.
45
+ * Each chunk is represented by a 32-bit value (encoded in hexadecimal),
46
+ * followed by the encoded string (8-bit representation). This format
47
+ * is important so we know how much of the chunk being streamed we
48
+ * are expecting before parsing the entire string data.
49
+ *
50
+ * This is sort of a bootleg "multipart/form-data" except it's bad at
51
+ * handling File/Blob LOL
52
+ *
53
+ * The format is as follows:
54
+ * ;0xFFFFFFFF;<string data>
55
+ */
56
+ function createChunk(data: string): Uint8Array {
57
+ const encodeData = new TextEncoder().encode(data);
58
+ const bytes = encodeData.length;
59
+ const baseHex = bytes.toString(16);
60
+ const totalHex = "00000000".substring(0, 8 - baseHex.length) + baseHex; // 32-bit
61
+ const head = new TextEncoder().encode(`;0x${totalHex};`);
62
+
63
+ const chunk = new Uint8Array(12 + bytes);
64
+ chunk.set(head);
65
+ chunk.set(encodeData, 12);
66
+ return chunk;
67
+ }
68
+
69
+ export function serializeToJSStream(id: string, value: any) {
70
+ return new ReadableStream({
71
+ start(controller) {
72
+ crossSerializeStream(value, {
73
+ scopeId: id,
74
+ plugins: DEFAULT_PLUGINS,
75
+ onSerialize(data: string, initial: boolean) {
76
+ controller.enqueue(
77
+ createChunk(initial ? `(${getCrossReferenceHeader(id)},${data})` : data),
78
+ );
79
+ },
80
+ onDone() {
81
+ controller.close();
82
+ },
83
+ onError(error: any) {
84
+ controller.error(error);
85
+ },
86
+ });
87
+ },
88
+ });
89
+ }
90
+
91
+ export function serializeToJSONStream(value: any) {
92
+ return new ReadableStream({
93
+ start(controller) {
94
+ toCrossJSONStream(value, {
95
+ disabledFeatures: DISABLED_FEATURES,
96
+ depthLimit: MAX_SERIALIZATION_DEPTH_LIMIT,
97
+ plugins: DEFAULT_PLUGINS,
98
+ onParse(node) {
99
+ controller.enqueue(createChunk(JSON.stringify(node)));
100
+ },
101
+ onDone() {
102
+ controller.close();
103
+ },
104
+ onError(error) {
105
+ controller.error(error);
106
+ },
107
+ });
108
+ },
109
+ });
110
+ }
111
+
112
+ class SerovalChunkReader {
113
+ reader: ReadableStreamDefaultReader<Uint8Array>;
114
+ buffer: Uint8Array;
115
+ done: boolean;
116
+ constructor(stream: ReadableStream<Uint8Array>) {
117
+ this.reader = stream.getReader();
118
+ this.buffer = new Uint8Array(0);
119
+ this.done = false;
120
+ }
121
+
122
+ async readChunk() {
123
+ // if there's no chunk, read again
124
+ const chunk = await this.reader.read();
125
+ if (!chunk.done) {
126
+ // repopulate the buffer
127
+ const newBuffer = new Uint8Array(this.buffer.length + chunk.value.length);
128
+ newBuffer.set(this.buffer);
129
+ newBuffer.set(chunk.value, this.buffer.length);
130
+ this.buffer = newBuffer;
131
+ } else {
132
+ this.done = true;
133
+ }
134
+ }
135
+
136
+ async next(): Promise<{ done: true; value: undefined } | { done: false; value: string }> {
137
+ // Check if the buffer is empty
138
+ if (this.buffer.length === 0) {
139
+ // if we are already done...
140
+ if (this.done) {
141
+ return {
142
+ done: true,
143
+ value: undefined,
144
+ };
145
+ }
146
+ // Otherwise, read a new chunk
147
+ await this.readChunk();
148
+ return await this.next();
149
+ }
150
+ // Read the "byte header"
151
+ // The byte header tells us how big the expected data is
152
+ // so we know how much data we should wait before we
153
+ // deserialize the data
154
+ const head = new TextDecoder().decode(this.buffer.subarray(1, 11));
155
+ const bytes = Number.parseInt(head, 16); // ;0x00000000;
156
+ if (Number.isNaN(bytes)) {
157
+ throw new Error("Malformed server function stream.");
158
+ }
159
+ // Check if the buffer has enough bytes to be parsed
160
+ while (bytes > this.buffer.length - 12) {
161
+ // If it's not enough, and the reader is done
162
+ // then the chunk is invalid.
163
+ if (this.done) {
164
+ throw new Error("Malformed server function stream.");
165
+ }
166
+ // Otherwise, we read more chunks
167
+ await this.readChunk();
168
+ }
169
+ // Extract the exact chunk as defined by the byte header
170
+ const partial = new TextDecoder().decode(this.buffer.subarray(12, 12 + bytes));
171
+ // The rest goes to the buffer
172
+ this.buffer = this.buffer.subarray(12 + bytes);
173
+
174
+ // Deserialize the chunk
175
+ return {
176
+ done: false,
177
+ value: partial,
178
+ };
179
+ }
180
+
181
+ async drain(interpret: (chunk: string) => void) {
182
+ while (true) {
183
+ const result = await this.next();
184
+ if (result.done) {
185
+ break;
186
+ } else {
187
+ interpret(result.value);
188
+ }
189
+ }
190
+ }
191
+ }
192
+
193
+ export async function serializeToJSONString(value: any) {
194
+ const response = new Response(serializeToJSONStream(value));
195
+ return await response.text();
196
+ }
197
+
198
+ export async function deserializeFromJSONString(json: string) {
199
+ const blob = new Response(json);
200
+ return await deserializeJSONStream(blob);
201
+ }
202
+
203
+ export async function deserializeJSONStream(response: Response | Request) {
204
+ if (!response.body) {
205
+ throw new Error("missing body");
206
+ }
207
+ const reader = new SerovalChunkReader(response.body);
208
+ const result = await reader.next();
209
+ if (!result.done) {
210
+ const refs = new Map();
211
+
212
+ function interpretChunk(chunk: string): unknown {
213
+ const value = fromCrossJSON(JSON.parse(chunk) as SerovalNode, {
214
+ refs,
215
+ disabledFeatures: DISABLED_FEATURES,
216
+ depthLimit: MAX_SERIALIZATION_DEPTH_LIMIT,
217
+ plugins: DEFAULT_PLUGINS,
218
+ });
219
+ return value;
220
+ }
221
+
222
+ void reader.drain(interpretChunk);
223
+
224
+ return interpretChunk(result.value);
225
+ }
226
+ return undefined;
227
+ }
228
+
229
+ export async function deserializeJSStream(id: string, response: Request | Response) {
230
+ if (!response.body) {
231
+ throw new Error("missing body");
232
+ }
233
+ const reader = new SerovalChunkReader(response.body);
234
+
235
+ const result = await reader.next();
236
+
237
+ if (!result.done) {
238
+ reader.drain(deserialize).then(
239
+ () => {
240
+ // @ts-ignore
241
+ delete $R[id];
242
+ },
243
+ () => {
244
+ // no-op
245
+ },
246
+ );
247
+ return deserialize(result.value);
248
+ }
249
+ return undefined;
250
+ }
@@ -1,7 +1,22 @@
1
1
  import { getRequestEvent } from "solid-js/web";
2
2
  import { provideRequestEvent } from "solid-js/web/storage";
3
+ import { registerServerFunction } from "./registration.ts";
3
4
 
4
- export function createServerReference(fn: Function, id: string) {
5
+ interface Registration<T extends any[], R> {
6
+ id: string;
7
+ fn: (...args: T) => Promise<R>;
8
+ }
9
+
10
+ export function createServerReference<T extends any[], R>(
11
+ id: string,
12
+ fn: (...args: T) => Promise<R>,
13
+ ) {
14
+ const registration: Registration<T, R> = { id, fn };
15
+ registerServerFunction(id, fn);
16
+ return registration;
17
+ }
18
+
19
+ export function cloneServerReference<T extends any[], R>({ id, fn }: Registration<T, R>) {
5
20
  if (typeof fn !== "function")
6
21
  throw new Error("Export from a 'use server' module must be a function");
7
22
  let baseURL = import.meta.env.BASE_URL ?? "/";
@@ -24,7 +39,7 @@ export function createServerReference(fn: Function, id: string) {
24
39
  };
25
40
  evt.serverOnly = true;
26
41
  return provideRequestEvent(evt, () => {
27
- return fn.apply(thisArg, args);
42
+ return fn.apply(thisArg, args as T);
28
43
  });
29
44
  },
30
45
  });
@@ -0,0 +1,116 @@
1
+ import { deserializeJSONStream, deserializeJSStream } from "./serialization.ts";
2
+
3
+ export const BODY_FORMAT_KEY = "X-Start-Type";
4
+
5
+ export const BODY_FORMAL_FILE = "__START__";
6
+
7
+ export const enum BodyFormat {
8
+ Seroval = "0",
9
+ String = "1",
10
+ FormData = "2",
11
+ URLSearchParams = "3",
12
+ Blob = "4",
13
+ File = "5",
14
+ ArrayBuffer = "6",
15
+ Uint8Array = "7",
16
+ }
17
+
18
+ export function getHeadersAndBody(body: any):
19
+ | {
20
+ headers?: HeadersInit;
21
+ body: BodyInit;
22
+ }
23
+ | undefined {
24
+ switch (true) {
25
+ case typeof body === "string":
26
+ return {
27
+ headers: {
28
+ "Content-Type": "text/plain",
29
+ [BODY_FORMAT_KEY]: BodyFormat.String,
30
+ },
31
+ body,
32
+ };
33
+ case body instanceof FormData:
34
+ return {
35
+ headers: {
36
+ [BODY_FORMAT_KEY]: BodyFormat.FormData,
37
+ },
38
+ body,
39
+ };
40
+ case body instanceof URLSearchParams:
41
+ return {
42
+ headers: {
43
+ "Content-Type": "application/x-www-form-urlencoded",
44
+ [BODY_FORMAT_KEY]: BodyFormat.URLSearchParams,
45
+ },
46
+ body,
47
+ };
48
+ case body instanceof File: {
49
+ const formData = new FormData();
50
+ formData.append(BODY_FORMAL_FILE, body, body.name);
51
+ return {
52
+ headers: {
53
+ [BODY_FORMAT_KEY]: BodyFormat.File,
54
+ },
55
+ body: formData,
56
+ };
57
+ }
58
+ case body instanceof Blob:
59
+ return {
60
+ headers: {
61
+ [BODY_FORMAT_KEY]: BodyFormat.Blob,
62
+ },
63
+ body,
64
+ };
65
+ case body instanceof ArrayBuffer:
66
+ return {
67
+ headers: {
68
+ [BODY_FORMAT_KEY]: BodyFormat.ArrayBuffer,
69
+ },
70
+ body,
71
+ };
72
+ case body instanceof Uint8Array:
73
+ return {
74
+ headers: {
75
+ [BODY_FORMAT_KEY]: BodyFormat.Uint8Array,
76
+ },
77
+ body: new Uint8Array(body),
78
+ };
79
+ default:
80
+ return undefined;
81
+ }
82
+ }
83
+
84
+ export async function extractBody(instance: string, client: boolean, source: Request | Response) {
85
+ const contentType = source.headers.get("content-type");
86
+ const startType = source.headers.get(BODY_FORMAT_KEY);
87
+ const clone = source.clone();
88
+
89
+ switch (true) {
90
+ case startType === BodyFormat.Seroval:
91
+ if (client && import.meta.env.SEROVAL_MODE === "js") {
92
+ return await deserializeJSStream(instance, clone);
93
+ }
94
+ return await deserializeJSONStream(clone);
95
+ case startType === BodyFormat.String:
96
+ return await clone.text();
97
+ case startType === BodyFormat.File: {
98
+ const formData = await clone.formData();
99
+ return formData.get(BODY_FORMAL_FILE);
100
+ }
101
+ case startType === BodyFormat.FormData:
102
+ case contentType?.startsWith("multipart/form-data"):
103
+ return await clone.formData();
104
+ case startType === BodyFormat.URLSearchParams:
105
+ case contentType?.startsWith("application/x-www-form-urlencoded"):
106
+ return new URLSearchParams(await clone.text());
107
+ case startType === BodyFormat.Blob:
108
+ return await clone.blob();
109
+ case startType === BodyFormat.ArrayBuffer:
110
+ return await clone.arrayBuffer();
111
+ case startType === BodyFormat.Uint8Array:
112
+ return new Uint8Array(await clone.arrayBuffer());
113
+ }
114
+
115
+ return undefined;
116
+ }
@@ -36,12 +36,32 @@ function wrapResponseMiddleware(onBeforeResponse: ResponseMiddleware): Middlewar
36
36
 
37
37
  const fetchEvent = getFetchEvent(h3Event);
38
38
  const mwResponse = await onBeforeResponse(fetchEvent, {
39
- body: (resp as any)?.body,
39
+ body: resp,
40
40
  });
41
41
  if (mwResponse) return mwResponse;
42
42
  };
43
43
  }
44
44
 
45
+ /**
46
+ * Creates middleware for handling requests and responses.
47
+ *
48
+ * @see https://docs.solidjs.com/solid-start/reference/server/create-middleware
49
+ /**
50
+ * Creates request/response middlewares via H3.
51
+ *
52
+ * Accepts an array of H3 {@link Middleware}
53
+ *
54
+ * @tip To run your middleware before response, `await next()` in your function block.
55
+ *@example
56
+ * const middleware = createMiddleware([
57
+ * async (event, next) => {
58
+ * const resp = await next();
59
+ * if (resp instanceof Response) return resp;
60
+ * return new Response("Not found", { status: 404 });
61
+ * },
62
+ * ]);
63
+ *
64
+ */
45
65
  export function createMiddleware(
46
66
  args:
47
67
  | {