@sveltejs/kit 3.0.0-next.2 → 3.0.0-next.20

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 (192) hide show
  1. package/package.json +58 -36
  2. package/src/cli.js +14 -11
  3. package/src/constants.js +6 -1
  4. package/src/core/adapt/builder.js +54 -60
  5. package/src/core/adapt/index.js +2 -5
  6. package/src/core/config/index.js +141 -76
  7. package/src/core/config/options.js +260 -260
  8. package/src/core/config/types.d.ts +1 -1
  9. package/src/core/env.js +143 -13
  10. package/src/core/generate_manifest/index.js +18 -15
  11. package/src/core/postbuild/analyse.js +7 -19
  12. package/src/core/postbuild/crawl.js +22 -6
  13. package/src/core/postbuild/entities.js +8 -2
  14. package/src/core/postbuild/fallback.js +4 -2
  15. package/src/core/postbuild/prerender.js +193 -69
  16. package/src/core/postbuild/queue.js +2 -1
  17. package/src/core/sync/create_manifest_data/conflict.js +1 -1
  18. package/src/core/sync/create_manifest_data/index.js +72 -52
  19. package/src/core/sync/sync.js +35 -26
  20. package/src/core/sync/ts.js +1 -1
  21. package/src/core/sync/utils.js +22 -2
  22. package/src/core/sync/{write_non_ambient.js → write_app_types.js} +105 -56
  23. package/src/core/sync/write_client_manifest.js +13 -28
  24. package/src/core/sync/write_env.js +7 -5
  25. package/src/core/sync/write_server.js +25 -33
  26. package/src/core/sync/write_tsconfig/index.js +274 -0
  27. package/src/core/sync/write_tsconfig/test-app/package.json +7 -0
  28. package/src/core/sync/write_tsconfig/utils.js +77 -0
  29. package/src/core/sync/write_tsconfig/validate.js +128 -0
  30. package/src/core/sync/write_types/index.js +119 -116
  31. package/src/core/utils.js +30 -5
  32. package/src/exports/env/index.js +77 -0
  33. package/src/exports/env/public.d.ts +55 -0
  34. package/src/exports/hooks/index.js +3 -9
  35. package/src/exports/hooks/public.d.ts +194 -0
  36. package/src/exports/hooks/sequence.js +9 -6
  37. package/src/exports/index.js +53 -20
  38. package/src/exports/internal/client.js +5 -0
  39. package/src/exports/internal/env.js +8 -5
  40. package/src/exports/internal/index.js +1 -90
  41. package/src/exports/internal/{event.js → server/event.js} +1 -2
  42. package/src/exports/internal/server/index.js +37 -0
  43. package/src/exports/internal/server/telemetry.js +95 -0
  44. package/src/exports/internal/shared.js +90 -0
  45. package/src/exports/node/index.js +64 -22
  46. package/src/exports/params/index.js +70 -0
  47. package/src/exports/params/public.d.ts +63 -0
  48. package/src/exports/public.d.ts +219 -1118
  49. package/src/exports/url.js +86 -0
  50. package/src/exports/vite/build/build_server.js +53 -64
  51. package/src/exports/vite/build/remote.js +24 -19
  52. package/src/exports/vite/build/utils.js +0 -8
  53. package/src/exports/vite/dev/index.js +199 -125
  54. package/src/exports/vite/index.js +1514 -833
  55. package/src/exports/vite/module_ids.js +2 -2
  56. package/src/exports/vite/preview/index.js +32 -24
  57. package/src/exports/vite/utils.js +83 -45
  58. package/src/pathname.js +55 -0
  59. package/src/runner.js +15 -0
  60. package/src/runtime/app/env/internal.js +4 -4
  61. package/src/runtime/app/env/types.d.ts +1 -1
  62. package/src/runtime/app/environment/index.js +3 -3
  63. package/src/runtime/app/{forms.js → forms/index.js} +73 -42
  64. package/src/runtime/app/forms/public.d.ts +2 -0
  65. package/src/runtime/app/forms/types.d.ts +56 -0
  66. package/src/runtime/app/internal/transport.js +53 -0
  67. package/src/runtime/app/manifest/index.js +1 -0
  68. package/src/runtime/app/{navigation.js → navigation/index.js} +2 -1
  69. package/src/runtime/app/navigation/public.d.ts +237 -0
  70. package/src/runtime/app/paths/client.js +37 -37
  71. package/src/runtime/app/paths/index.js +1 -1
  72. package/src/runtime/app/paths/internal/client.js +34 -2
  73. package/src/runtime/app/paths/internal/server.js +6 -23
  74. package/src/runtime/app/paths/internal.d.ts +3 -0
  75. package/src/runtime/app/paths/public.d.ts +1 -29
  76. package/src/runtime/app/paths/server.js +36 -17
  77. package/src/runtime/app/paths/types.d.ts +11 -19
  78. package/src/runtime/app/server/index.js +2 -2
  79. package/src/runtime/app/server/public.d.ts +519 -0
  80. package/src/runtime/app/server/remote/command.js +13 -11
  81. package/src/runtime/app/server/remote/form.js +61 -39
  82. package/src/runtime/app/server/remote/prerender.js +45 -45
  83. package/src/runtime/app/server/remote/query.js +106 -108
  84. package/src/runtime/app/server/remote/requested.js +27 -19
  85. package/src/runtime/app/server/remote/shared.js +75 -75
  86. package/src/runtime/app/service-worker/index.js +24 -0
  87. package/src/runtime/app/state/client.js +4 -2
  88. package/src/runtime/app/state/index.js +7 -5
  89. package/src/runtime/app/state/public.d.ts +72 -0
  90. package/src/runtime/app/state/server.js +3 -0
  91. package/src/runtime/app/stores.js +15 -78
  92. package/src/runtime/client/bundle.js +1 -1
  93. package/src/runtime/client/client-entry.js +3 -0
  94. package/src/runtime/client/client.js +1336 -648
  95. package/src/runtime/client/constants.js +3 -6
  96. package/src/runtime/client/entry.js +24 -3
  97. package/src/runtime/client/fetcher.js +25 -25
  98. package/src/runtime/client/ndjson.js +1 -1
  99. package/src/runtime/client/parse.js +1 -1
  100. package/src/runtime/client/payload.js +17 -0
  101. package/src/runtime/client/remote-functions/cache.svelte.js +3 -1
  102. package/src/runtime/client/remote-functions/command.svelte.js +37 -61
  103. package/src/runtime/client/remote-functions/form.svelte.js +267 -178
  104. package/src/runtime/client/remote-functions/prerender.svelte.js +32 -11
  105. package/src/runtime/client/remote-functions/query/index.js +10 -17
  106. package/src/runtime/client/remote-functions/query/instance.svelte.js +64 -18
  107. package/src/runtime/client/remote-functions/query/proxy.js +5 -5
  108. package/src/runtime/client/remote-functions/query-batch.svelte.js +61 -70
  109. package/src/runtime/client/remote-functions/query-live/index.js +1 -1
  110. package/src/runtime/client/remote-functions/query-live/instance.svelte.js +63 -21
  111. package/src/runtime/client/remote-functions/query-live/iterator.js +15 -12
  112. package/src/runtime/client/remote-functions/query-live/proxy.js +2 -12
  113. package/src/runtime/client/remote-functions/shared.svelte.js +90 -65
  114. package/src/runtime/client/snapshots.js +147 -0
  115. package/src/runtime/client/state.svelte.js +94 -55
  116. package/src/runtime/client/stream.js +3 -2
  117. package/src/runtime/client/types.d.ts +13 -9
  118. package/src/runtime/client/utils.js +22 -110
  119. package/src/runtime/components/root.svelte +56 -0
  120. package/src/runtime/env/dynamic/private.js +7 -0
  121. package/src/runtime/env/dynamic/public.js +7 -0
  122. package/src/runtime/env/static/private.js +6 -0
  123. package/src/runtime/env/static/public.js +6 -0
  124. package/src/runtime/form-utils.js +172 -61
  125. package/src/runtime/pathname.js +20 -32
  126. package/src/runtime/props.svelte.js +72 -0
  127. package/src/runtime/server/constants.js +0 -3
  128. package/src/runtime/server/cookie.js +70 -53
  129. package/src/runtime/server/csrf.js +65 -0
  130. package/src/runtime/server/data/index.js +48 -52
  131. package/src/runtime/server/dev.js +22 -0
  132. package/src/runtime/server/endpoint.js +3 -4
  133. package/src/runtime/server/env_module.js +0 -5
  134. package/src/runtime/server/errors.js +160 -0
  135. package/src/runtime/server/fetch.js +31 -38
  136. package/src/runtime/server/index.js +90 -64
  137. package/src/runtime/server/internal.js +71 -0
  138. package/src/runtime/server/page/actions.js +84 -64
  139. package/src/runtime/server/page/crypto.js +2 -2
  140. package/src/runtime/server/page/csp.js +88 -104
  141. package/src/runtime/server/page/data_serializer.js +22 -23
  142. package/src/runtime/server/page/index.js +35 -53
  143. package/src/runtime/server/page/load_data.js +47 -54
  144. package/src/runtime/server/page/render.js +172 -238
  145. package/src/runtime/server/page/respond_with_error.js +16 -30
  146. package/src/runtime/server/page/serialize_data.js +2 -13
  147. package/src/runtime/server/page/server_routing.js +85 -26
  148. package/src/runtime/server/remote-functions.js +639 -0
  149. package/src/runtime/server/respond.js +188 -129
  150. package/src/runtime/server/sourcemaps.js +183 -0
  151. package/src/runtime/server/state.js +53 -0
  152. package/src/runtime/server/utils.js +12 -154
  153. package/src/runtime/shared.js +20 -40
  154. package/src/runtime/utils.js +3 -0
  155. package/src/types/ambient-private.d.ts +11 -1
  156. package/src/types/ambient.d.ts +87 -36
  157. package/src/types/global-private.d.ts +25 -25
  158. package/src/types/internal.d.ts +160 -150
  159. package/src/types/private.d.ts +41 -1
  160. package/src/utils/error.js +28 -4
  161. package/src/utils/escape.js +9 -25
  162. package/src/utils/features.js +1 -1
  163. package/src/utils/filesystem.js +1 -23
  164. package/src/utils/fork.js +7 -2
  165. package/src/utils/hash.js +21 -0
  166. package/src/utils/http.js +8 -7
  167. package/src/utils/import.js +9 -2
  168. package/src/utils/imports.js +83 -0
  169. package/src/utils/mime.js +9 -0
  170. package/src/utils/page_nodes.js +6 -7
  171. package/src/utils/params.js +67 -0
  172. package/src/utils/regex.js +9 -0
  173. package/src/utils/routing.js +145 -73
  174. package/src/utils/shared-iterator.js +5 -0
  175. package/src/utils/streaming.js +14 -4
  176. package/src/utils/url.js +33 -2
  177. package/src/version.js +1 -1
  178. package/types/index.d.ts +2291 -2135
  179. package/types/index.d.ts.map +116 -108
  180. package/src/core/sync/write_ambient.js +0 -18
  181. package/src/core/sync/write_root.js +0 -148
  182. package/src/core/sync/write_tsconfig.js +0 -250
  183. package/src/exports/internal/server.js +0 -22
  184. package/src/exports/node/polyfills.js +0 -30
  185. package/src/runtime/server/app.js +0 -9
  186. package/src/runtime/server/remote.js +0 -457
  187. package/src/runtime/shared-server.js +0 -7
  188. package/src/runtime/telemetry/otel.js +0 -21
  189. package/src/runtime/telemetry/record_span.js +0 -65
  190. package/src/types/synthetic/$lib.md +0 -5
  191. /package/src/exports/internal/{remote-functions.js → server/remote-functions.js} +0 -0
  192. /package/src/{runtime/telemetry/noop.js → telemetry.js} +0 -0
@@ -0,0 +1,639 @@
1
+ /** @import { RequestEvent, SSRManifest } from '@sveltejs/kit' */
2
+ /** @import { RemoteForm } from '$app/server' */
3
+ /** @import { ActionResult } from '$app/forms' */
4
+ /** @import { RemoteFormInternals, RemoteFunctionData, RemoteFunctionResponse, RemoteInternals, RequestState, SSROptions } from 'types' */
5
+
6
+ import { json, error } from '@sveltejs/kit';
7
+ import { Redirect, SvelteKitError } from '@sveltejs/kit/internal';
8
+ import { with_request_store, merge_tracing, record_span } from '@sveltejs/kit/internal/server';
9
+ import { app_dir, base } from '#app/paths';
10
+ import { is_form_content_type } from '../../utils/http.js';
11
+ import { create_remote_key, parse_remote_arg, split_remote_key } from '../shared.js';
12
+ import { stringify } from '#app/internal/transport';
13
+ import { handle_error_and_jsonify } from './errors.js';
14
+ import { normalize_error } from '../../utils/error.js';
15
+ import { check_incorrect_fail_use, get_action_location } from './page/actions.js';
16
+ import { DEV } from 'esm-env';
17
+ import { deserialize_binary_form } from '../form-utils.js';
18
+ import { with_version_header } from './utils.js';
19
+
20
+ /**
21
+ * How long (in milliseconds) to wait after the last message was sent before
22
+ * sending a `: keep-alive` SSE comment, to prevent proxies/load balancers with
23
+ * an idle timeout from closing an otherwise-quiet `query.live` connection.
24
+ */
25
+ const KEEP_ALIVE_INTERVAL = 30_000;
26
+
27
+ /** @type {typeof handle_remote_call_internal} */
28
+ export async function handle_remote_call(event, state, options, manifest, id) {
29
+ return record_span({
30
+ name: 'sveltekit.remote.call',
31
+ attributes: {
32
+ 'sveltekit.remote.call.id': id
33
+ },
34
+ fn: async (current) => {
35
+ const traced_event = merge_tracing(event, current);
36
+ const response = await with_request_store({ event: traced_event, state }, () =>
37
+ handle_remote_call_internal(traced_event, state, options, manifest, id)
38
+ );
39
+ return with_version_header(response);
40
+ }
41
+ });
42
+ }
43
+
44
+ /**
45
+ * @param {RequestEvent} event
46
+ * @param {RequestState} state
47
+ * @param {SSROptions} options
48
+ * @param {SSRManifest} manifest
49
+ * @param {string} id
50
+ */
51
+ async function handle_remote_call_internal(event, state, options, manifest, id) {
52
+ const [hash, name, additional_args] = id.split('/');
53
+ const remotes = manifest._.remotes;
54
+
55
+ if (!Object.hasOwn(remotes, hash)) error(404);
56
+
57
+ const module = await remotes[hash]();
58
+ const fn = Object.hasOwn(module.default, name) ? module.default[name] : undefined;
59
+
60
+ if (!fn) error(404);
61
+
62
+ /** @type {RemoteInternals} */
63
+ const internals = fn.__;
64
+
65
+ event.tracing.current.setAttributes({
66
+ 'sveltekit.remote.call.type': internals.type,
67
+ 'sveltekit.remote.call.name': internals.name
68
+ });
69
+
70
+ /** @type {HeadersInit | undefined} */
71
+ const headers = state.prerendering ? undefined : { 'cache-control': 'private, no-store' };
72
+
73
+ try {
74
+ /** @type {RemoteFunctionData} */
75
+ const data = {};
76
+
77
+ switch (internals.type) {
78
+ case 'query_live': {
79
+ if (event.request.method !== 'GET') {
80
+ throw new SvelteKitError(
81
+ 405,
82
+ 'Method Not Allowed',
83
+ `\`query.live\` functions must be invoked via GET request, not ${event.request.method}`
84
+ );
85
+ }
86
+
87
+ const payload = /** @type {string} */ (
88
+ new URL(event.request.url).searchParams.get('payload')
89
+ );
90
+
91
+ const generator = internals.run(event, state, parse_remote_arg(payload));
92
+
93
+ const encoder = new TextEncoder();
94
+
95
+ let closed = false;
96
+
97
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
98
+ let keep_alive;
99
+
100
+ /**
101
+ * (Re)schedule the keep-alive comment. Called whenever a message is sent, so
102
+ * that a keep-alive is only emitted once `KEEP_ALIVE_INTERVAL` has elapsed
103
+ * without any other activity.
104
+ * @param {ReadableStreamDefaultController} controller
105
+ */
106
+ function schedule_keep_alive(controller) {
107
+ clearTimeout(keep_alive);
108
+ keep_alive = setTimeout(() => {
109
+ if (closed || event.request.signal.aborted) return;
110
+ // SSE comments (lines starting with `:`) are ignored by the client
111
+ controller.enqueue(encoder.encode(': keep-alive\n\n'));
112
+ schedule_keep_alive(controller);
113
+ }, KEEP_ALIVE_INTERVAL);
114
+ }
115
+
116
+ /**
117
+ * @param {ReadableStreamDefaultController} controller
118
+ * @param {any} payload
119
+ */
120
+ function send(controller, payload) {
121
+ controller.enqueue(encoder.encode('data: ' + JSON.stringify(payload) + '\n\n'));
122
+ schedule_keep_alive(controller);
123
+ }
124
+
125
+ /** @type {string | undefined} */
126
+ let result = undefined;
127
+
128
+ async function cancel() {
129
+ if (closed) return;
130
+ closed = true;
131
+ clearTimeout(keep_alive);
132
+ await generator.return(undefined);
133
+ }
134
+
135
+ event.request.signal.addEventListener('abort', cancel, { once: true });
136
+
137
+ return new Response(
138
+ new ReadableStream({
139
+ start(controller) {
140
+ schedule_keep_alive(controller);
141
+ },
142
+ async pull(controller) {
143
+ if (event.request.signal.aborted) {
144
+ await cancel();
145
+ controller.close();
146
+ return;
147
+ }
148
+
149
+ try {
150
+ while (true) {
151
+ const { value, done } = await generator.next();
152
+
153
+ if (done) {
154
+ await cancel();
155
+ controller.close();
156
+ return;
157
+ }
158
+
159
+ // only send changed data
160
+ if (result !== (result = stringify(value))) {
161
+ send(controller, {
162
+ type: 'result',
163
+ result
164
+ });
165
+
166
+ return;
167
+ }
168
+ }
169
+ } catch (error) {
170
+ if (!event.request.signal.aborted) {
171
+ if (error instanceof Redirect) {
172
+ send(controller, {
173
+ type: 'redirect',
174
+ location: error.location
175
+ });
176
+ } else {
177
+ const transformed = await handle_error_and_jsonify(
178
+ event,
179
+ state,
180
+ options,
181
+ error
182
+ );
183
+
184
+ send(controller, {
185
+ type: 'error',
186
+ error: transformed
187
+ });
188
+ }
189
+ }
190
+
191
+ await cancel();
192
+ controller.close();
193
+ }
194
+ },
195
+ cancel
196
+ }),
197
+ {
198
+ headers: {
199
+ 'cache-control': 'private, no-store',
200
+ 'content-type': 'text/event-stream'
201
+ }
202
+ }
203
+ );
204
+ }
205
+
206
+ case 'query_batch': {
207
+ if (event.request.method !== 'POST') {
208
+ throw new SvelteKitError(
209
+ 405,
210
+ 'Method Not Allowed',
211
+ `\`query.batch\` functions must be invoked via POST request, not ${event.request.method}`
212
+ );
213
+ }
214
+
215
+ /** @type {{ payloads: string[] }} */
216
+ const { payloads } = await event.request.json();
217
+
218
+ const args = await Promise.all(payloads.map((payload) => parse_remote_arg(payload)));
219
+
220
+ data._ = await with_request_store({ event, state }, () => internals.run(args, options));
221
+
222
+ break;
223
+ }
224
+
225
+ case 'form': {
226
+ if (event.request.method !== 'POST') {
227
+ throw new SvelteKitError(
228
+ 405,
229
+ 'Method Not Allowed',
230
+ `\`form\` functions must be invoked via POST request, not ${event.request.method}`
231
+ );
232
+ }
233
+
234
+ if (!is_form_content_type(event.request)) {
235
+ throw new SvelteKitError(
236
+ 415,
237
+ 'Unsupported Media Type',
238
+ `\`form\` functions expect form-encoded data — received ${event.request.headers.get(
239
+ 'content-type'
240
+ )}`
241
+ );
242
+ }
243
+
244
+ const {
245
+ data: input,
246
+ meta,
247
+ form_data
248
+ } = await deserialize_binary_form(event.request, internals.id);
249
+ state.remote.requested = create_requested_map(meta.remote_refreshes);
250
+
251
+ // If this is a keyed form instance (created via form.for(key)), add the key to the form data (unless already set)
252
+ // Note that additional_args will only be set if the form is not enhanced, as enhanced forms transfer the key inside `data`.
253
+ if (additional_args && !('id' in input)) {
254
+ input.id = JSON.parse(decodeURIComponent(additional_args));
255
+ }
256
+
257
+ const fn = internals.fn;
258
+ data._ = await with_request_store(
259
+ { event, state: { ...state, is_in_remote_form_or_command: true } },
260
+ () => fn(input, meta, form_data)
261
+ );
262
+
263
+ if (data._.issues) {
264
+ // special case — don't serialize refreshes/reconnects
265
+ return json(
266
+ /** @type {RemoteFunctionResponse} */ ({
267
+ type: 'result',
268
+ data: stringify(data)
269
+ }),
270
+ { headers }
271
+ );
272
+ }
273
+
274
+ break;
275
+ }
276
+
277
+ case 'command': {
278
+ /** @type {{ payload: string, refreshes?: string[] }} */
279
+ const { payload, refreshes } = await event.request.json();
280
+ state.remote.requested = create_requested_map(refreshes);
281
+ const arg = parse_remote_arg(payload);
282
+
283
+ data._ = await with_request_store(
284
+ { event, state: { ...state, is_in_remote_form_or_command: true } },
285
+ () => fn(arg)
286
+ );
287
+
288
+ break;
289
+ }
290
+
291
+ case 'prerender': {
292
+ data._ = await with_request_store({ event, state }, () =>
293
+ fn(parse_remote_arg(additional_args))
294
+ );
295
+
296
+ break;
297
+ }
298
+
299
+ case 'query': {
300
+ const payload = /** @type {string} */ (
301
+ // new URL(...) necessary because we're hiding the URL from the user in the event object
302
+ new URL(event.request.url).searchParams.get('payload')
303
+ );
304
+
305
+ data._ = await with_request_store({ event, state }, () => fn(parse_remote_arg(payload)));
306
+
307
+ break;
308
+ }
309
+ }
310
+
311
+ await collect_remote_data(data, event, state, options);
312
+
313
+ return json(
314
+ /** @type {RemoteFunctionResponse} */ ({
315
+ type: 'result',
316
+ data: stringify(data)
317
+ }),
318
+ { headers }
319
+ );
320
+ } catch (error) {
321
+ if (error instanceof Redirect) {
322
+ const data = await collect_remote_data({ redirect: error.location }, event, state, options);
323
+
324
+ return json(
325
+ /** @type {RemoteFunctionResponse} */ ({
326
+ type: 'result',
327
+ data: stringify(data)
328
+ }),
329
+ { headers }
330
+ );
331
+ }
332
+
333
+ const transformed = await handle_error_and_jsonify(event, state, options, error);
334
+
335
+ return json(
336
+ /** @type {RemoteFunctionResponse} */ ({
337
+ type: 'error',
338
+ error: transformed
339
+ }),
340
+ {
341
+ // By setting a non-200 during prerendering we fail the prerender process (unless handleHttpError handles it).
342
+ // Errors at runtime will be passed to the client and are handled there
343
+ status: state.prerendering ? transformed.status : undefined,
344
+ headers: {
345
+ 'cache-control': 'private, no-store'
346
+ }
347
+ }
348
+ );
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Collects all the query/prerender data that was retrieved
354
+ * during the request and adds it to `data`
355
+ * @param {RemoteFunctionData} data
356
+ * @param {RequestEvent} event
357
+ * @param {RequestState} state
358
+ * @param {SSROptions} options
359
+ */
360
+ export async function collect_remote_data(data, event, state, options) {
361
+ /**
362
+ *
363
+ * @param {unknown} error
364
+ * @returns {Promise<App.Error>}
365
+ */
366
+ function convert_error(error) {
367
+ // TODO 4.0 remove the `Promise.resolve(...)`
368
+ return Promise.resolve(handle_error_and_jsonify(event, state, options, error));
369
+ }
370
+
371
+ /** @type {Promise<any>[]} */
372
+ const promises = [];
373
+
374
+ // Keys the explicit pass has serialized. Invoking a query's `fn` there can, as a
375
+ // side effect, register the same query in `state.remote.implicit` (via
376
+ // `get_response`), so we skip those keys in the implicit pass below to avoid
377
+ // processing them twice.
378
+ /** @type {Set<string>} */
379
+ const processed = new Set();
380
+
381
+ if (state.remote.explicit) {
382
+ const { explicit } = state.remote;
383
+
384
+ /** @type {Promise<void>[]} */
385
+ const inflight = [];
386
+
387
+ const drain = () => {
388
+ for (const [remote_key, { internals, fn }] of explicit) {
389
+ explicit.delete(remote_key);
390
+ if (processed.has(remote_key)) continue;
391
+ processed.add(remote_key);
392
+
393
+ // there were explicit refreshes/reconnects (via `refresh()`/`set()`/`reconnect()`),
394
+ // so the client should apply these single-flight updates instead of calling `invalidateAll()`
395
+ data.r = true;
396
+
397
+ const type = /** @type {'p' | 'q' | 'l'} */ (
398
+ internals.type === 'query_live' ? 'l' : internals.type[0]
399
+ );
400
+
401
+ // `fn` is deferred until now so the query runs after any state mutations
402
+ // in the command/form body. If the query was re-awaited in the meantime,
403
+ // `fn` returns the existing (fresh) cache entry rather than re-running.
404
+ inflight.push(
405
+ fn().then(
406
+ (v) => {
407
+ // a fresh value replaces the node entirely, so a re-run can't leave
408
+ // a stale error from a previous run alongside the new value
409
+ (data[type] ??= {})[remote_key] = { v };
410
+ drain();
411
+ },
412
+ async (e) => {
413
+ if (!(e instanceof Redirect)) {
414
+ // (a Redirect is already handled elsewhere)
415
+ (data[type] ??= {})[remote_key] = { e: await convert_error(e) };
416
+ }
417
+ drain();
418
+ }
419
+ )
420
+ );
421
+ }
422
+ };
423
+
424
+ drain();
425
+
426
+ // `inflight` grows as settles drain newly-refreshed queries
427
+ for (const promise of inflight) {
428
+ await promise;
429
+ }
430
+ }
431
+
432
+ if (state.remote.implicit) {
433
+ for (const [internals, record] of state.remote.implicit) {
434
+ // Private (non-exported) remote functions have no `id` and must never be
435
+ // serialized into the response — otherwise their (potentially private) result
436
+ // would be shipped to the client under a malformed `undefined/...` key.
437
+ if (!internals.id) continue;
438
+
439
+ for (const key in record) {
440
+ // form outputs are registered under the client-side action id directly
441
+ const remote_key = internals.type === 'form' ? key : create_remote_key(internals.id, key);
442
+
443
+ // already serialized by the explicit pass (which always awaits and wins),
444
+ // so don't reprocess it here with the implicit "still loading" heuristic
445
+ if (processed.has(remote_key)) continue;
446
+
447
+ const type = /** @type {'p' | 'q' | 'l' | 'f'} */ (
448
+ internals.type === 'query_live' ? 'l' : internals.type[0]
449
+ );
450
+
451
+ const promise = state.remote.data?.get(internals)?.[key] ?? record[key]();
452
+
453
+ // If the promise is still pending (e.g. the query was rendered in its loading
454
+ // state during SSR), omit it from the payload entirely so that the client
455
+ // fetches it itself — an entry without `v`/`e` would hydrate as `undefined`.
456
+ let resolved = true;
457
+
458
+ await Promise.race([
459
+ Promise.resolve(promise).then(
460
+ (v) => {
461
+ if (resolved) {
462
+ ((data[type] ??= {})[remote_key] ??= {}).v = v;
463
+ }
464
+ },
465
+ (e) => {
466
+ if (e instanceof Redirect) {
467
+ // already handled elsewhere
468
+ return;
469
+ }
470
+
471
+ if (resolved) {
472
+ promises.push(
473
+ convert_error(e).then((e) => {
474
+ ((data[type] ??= {})[remote_key] ??= {}).e = e;
475
+ })
476
+ );
477
+ }
478
+ }
479
+ ),
480
+ Promise.resolve().then(() => (resolved = false))
481
+ ]);
482
+ }
483
+ }
484
+ }
485
+
486
+ await Promise.all(promises);
487
+
488
+ return data;
489
+ }
490
+
491
+ /**
492
+ * @param {string[] | undefined} refreshes
493
+ */
494
+ function create_requested_map(refreshes) {
495
+ /** @type {Map<string, string[]>} */
496
+ const requested = new Map();
497
+
498
+ for (const key of refreshes ?? []) {
499
+ const parts = split_remote_key(key);
500
+
501
+ const existing = requested.get(parts.id);
502
+
503
+ if (existing) {
504
+ existing.push(parts.payload);
505
+ } else {
506
+ requested.set(parts.id, [parts.payload]);
507
+ }
508
+ }
509
+
510
+ return requested;
511
+ }
512
+
513
+ /** @type {typeof handle_remote_form_post_internal} */
514
+ export async function handle_remote_form_post(event, state, manifest, id) {
515
+ return record_span({
516
+ name: 'sveltekit.remote.form.post',
517
+ attributes: {
518
+ 'sveltekit.remote.form.post.id': id
519
+ },
520
+ fn: (current) => {
521
+ const traced_event = merge_tracing(event, current);
522
+ return with_request_store({ event: traced_event, state }, () =>
523
+ handle_remote_form_post_internal(traced_event, state, manifest, id)
524
+ );
525
+ }
526
+ });
527
+ }
528
+
529
+ /**
530
+ * @param {RequestEvent} event
531
+ * @param {RequestState} state
532
+ * @param {SSRManifest} manifest
533
+ * @param {string} id
534
+ * @returns {Promise<ActionResult>}
535
+ */
536
+ async function handle_remote_form_post_internal(event, state, manifest, id) {
537
+ const location = get_action_location(event.url);
538
+ // `hash` and `name` can never contain a `/`, but the JSON-stringified key of a
539
+ // keyed (`form.for(key)`) instance can — rejoin the remaining segments
540
+ const [hash, name, ...rest] = id.split('/');
541
+ const action_id = rest.join('/');
542
+ const remotes = manifest._.remotes;
543
+ const module = Object.hasOwn(remotes, hash) ? await remotes[hash]() : undefined;
544
+
545
+ let form = /** @type {RemoteForm<any, any>} */ (
546
+ module && Object.hasOwn(module.default, name) ? module.default[name] : undefined
547
+ );
548
+
549
+ if (!form) {
550
+ event.setHeaders({
551
+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
552
+ // "The server must generate an Allow header field in a 405 status code response"
553
+ allow: 'GET'
554
+ });
555
+ return {
556
+ type: 'error',
557
+ location,
558
+ // We're lying a bit with the types here; this will be transformed into a proper App.Error object later
559
+ error: new SvelteKitError(
560
+ 405,
561
+ 'Method Not Allowed',
562
+ `POST method not allowed. No form actions exist for ${DEV ? `the page at ${event.route.id}` : 'this page'}`
563
+ )
564
+ };
565
+ }
566
+
567
+ if (action_id) {
568
+ // @ts-expect-error
569
+ form = with_request_store({ event, state }, () => form.for(JSON.parse(action_id)));
570
+ }
571
+
572
+ try {
573
+ const __ = /** @type {RemoteFormInternals} */ (/** @type {any} */ (form).__);
574
+
575
+ const { data, meta, form_data } = await deserialize_binary_form(event.request, __.id);
576
+
577
+ if (action_id && !('id' in data)) {
578
+ data.id = JSON.parse(decodeURIComponent(action_id));
579
+ }
580
+
581
+ await with_request_store(
582
+ { event, state: { ...state, is_in_remote_form_or_command: true } },
583
+ () => __.fn(data, meta, form_data)
584
+ );
585
+
586
+ // We don't want the data to appear on `let { form } = $props()`, which is why we're not returning it.
587
+ // It is instead available on `myForm.result`, setting of which happens within the remote `form` function.
588
+ return {
589
+ type: 'success',
590
+ status: 200,
591
+ location
592
+ };
593
+ } catch (e) {
594
+ const err = normalize_error(e);
595
+
596
+ if (err instanceof Redirect) {
597
+ return {
598
+ type: 'redirect',
599
+ status: err.status,
600
+ location: err.location
601
+ };
602
+ }
603
+
604
+ return {
605
+ type: 'error',
606
+ location,
607
+ // @ts-expect-error We're lying a bit with the types here; this will be transformed into a proper App.Error object later
608
+ error: check_incorrect_fail_use(err)
609
+ };
610
+ }
611
+ }
612
+
613
+ /**
614
+ * @param {URL} url
615
+ */
616
+ export function has_remote_prefix(url) {
617
+ return url.pathname.startsWith(`${base}/${app_dir}/remote/`);
618
+ }
619
+
620
+ /**
621
+ * @param {URL} url
622
+ */
623
+ export function strip_remote_prefix(url) {
624
+ return url.pathname.replace(`${base}/${app_dir}/remote/`, '');
625
+ }
626
+
627
+ /**
628
+ * @param {URL} url
629
+ */
630
+ export function get_remote_id(url) {
631
+ return has_remote_prefix(url) && strip_remote_prefix(url);
632
+ }
633
+
634
+ /**
635
+ * @param {URL} url
636
+ */
637
+ export function get_remote_action(url) {
638
+ return url.searchParams.get('/remote');
639
+ }