@tanstack/react-start-client 1.114.3 → 1.114.5

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 (97) hide show
  1. package/dist/cjs/StartClient.cjs +2 -2
  2. package/dist/cjs/StartClient.cjs.map +1 -1
  3. package/dist/cjs/StartClient.d.cts +1 -1
  4. package/dist/cjs/createServerFn.cjs +13 -230
  5. package/dist/cjs/createServerFn.cjs.map +1 -1
  6. package/dist/cjs/createServerFn.d.cts +1 -141
  7. package/dist/cjs/index.cjs +37 -16
  8. package/dist/cjs/index.cjs.map +1 -1
  9. package/dist/cjs/index.d.cts +11 -9
  10. package/dist/cjs/tests/setupTests.d.cts +0 -0
  11. package/dist/esm/StartClient.d.ts +1 -1
  12. package/dist/esm/StartClient.js +1 -1
  13. package/dist/esm/StartClient.js.map +1 -1
  14. package/dist/esm/createServerFn.d.ts +1 -141
  15. package/dist/esm/createServerFn.js +6 -201
  16. package/dist/esm/createServerFn.js.map +1 -1
  17. package/dist/esm/index.d.ts +11 -9
  18. package/dist/esm/index.js +1 -7
  19. package/dist/esm/index.js.map +1 -1
  20. package/dist/esm/tests/setupTests.d.ts +0 -0
  21. package/package.json +4 -3
  22. package/src/StartClient.tsx +2 -2
  23. package/src/createServerFn.ts +29 -692
  24. package/src/index.tsx +20 -20
  25. package/src/tests/createServerFn.test-d.tsx +1 -1
  26. package/src/tests/setupTests.tsx +1 -0
  27. package/dist/cjs/createIsomorphicFn.cjs +0 -7
  28. package/dist/cjs/createIsomorphicFn.cjs.map +0 -1
  29. package/dist/cjs/createIsomorphicFn.d.cts +0 -12
  30. package/dist/cjs/createMiddleware.cjs +0 -34
  31. package/dist/cjs/createMiddleware.cjs.map +0 -1
  32. package/dist/cjs/createMiddleware.d.cts +0 -131
  33. package/dist/cjs/envOnly.cjs +0 -7
  34. package/dist/cjs/envOnly.cjs.map +0 -1
  35. package/dist/cjs/envOnly.d.cts +0 -4
  36. package/dist/cjs/headers.cjs +0 -30
  37. package/dist/cjs/headers.cjs.map +0 -1
  38. package/dist/cjs/headers.d.cts +0 -5
  39. package/dist/cjs/json.cjs +0 -14
  40. package/dist/cjs/json.cjs.map +0 -1
  41. package/dist/cjs/json.d.cts +0 -2
  42. package/dist/cjs/registerGlobalMiddleware.cjs +0 -9
  43. package/dist/cjs/registerGlobalMiddleware.cjs.map +0 -1
  44. package/dist/cjs/registerGlobalMiddleware.d.cts +0 -5
  45. package/dist/cjs/serializer.cjs +0 -152
  46. package/dist/cjs/serializer.cjs.map +0 -1
  47. package/dist/cjs/serializer.d.cts +0 -2
  48. package/dist/cjs/ssr-client.cjs +0 -130
  49. package/dist/cjs/ssr-client.cjs.map +0 -1
  50. package/dist/cjs/ssr-client.d.cts +0 -65
  51. package/dist/cjs/tests/createIsomorphicFn.test-d.d.cts +0 -1
  52. package/dist/cjs/tests/createServerMiddleware.test-d.d.cts +0 -1
  53. package/dist/cjs/tests/envOnly.test-d.d.cts +0 -1
  54. package/dist/cjs/tests/json.test.d.cts +0 -1
  55. package/dist/cjs/tests/transformer.test.d.cts +0 -1
  56. package/dist/esm/createIsomorphicFn.d.ts +0 -12
  57. package/dist/esm/createIsomorphicFn.js +0 -7
  58. package/dist/esm/createIsomorphicFn.js.map +0 -1
  59. package/dist/esm/createMiddleware.d.ts +0 -131
  60. package/dist/esm/createMiddleware.js +0 -34
  61. package/dist/esm/createMiddleware.js.map +0 -1
  62. package/dist/esm/envOnly.d.ts +0 -4
  63. package/dist/esm/envOnly.js +0 -7
  64. package/dist/esm/envOnly.js.map +0 -1
  65. package/dist/esm/headers.d.ts +0 -5
  66. package/dist/esm/headers.js +0 -30
  67. package/dist/esm/headers.js.map +0 -1
  68. package/dist/esm/json.d.ts +0 -2
  69. package/dist/esm/json.js +0 -14
  70. package/dist/esm/json.js.map +0 -1
  71. package/dist/esm/registerGlobalMiddleware.d.ts +0 -5
  72. package/dist/esm/registerGlobalMiddleware.js +0 -9
  73. package/dist/esm/registerGlobalMiddleware.js.map +0 -1
  74. package/dist/esm/serializer.d.ts +0 -2
  75. package/dist/esm/serializer.js +0 -152
  76. package/dist/esm/serializer.js.map +0 -1
  77. package/dist/esm/ssr-client.d.ts +0 -65
  78. package/dist/esm/ssr-client.js +0 -130
  79. package/dist/esm/ssr-client.js.map +0 -1
  80. package/dist/esm/tests/createIsomorphicFn.test-d.d.ts +0 -1
  81. package/dist/esm/tests/createServerMiddleware.test-d.d.ts +0 -1
  82. package/dist/esm/tests/envOnly.test-d.d.ts +0 -1
  83. package/dist/esm/tests/json.test.d.ts +0 -1
  84. package/dist/esm/tests/transformer.test.d.ts +0 -1
  85. package/src/createIsomorphicFn.ts +0 -36
  86. package/src/createMiddleware.ts +0 -595
  87. package/src/envOnly.ts +0 -9
  88. package/src/headers.ts +0 -50
  89. package/src/json.ts +0 -15
  90. package/src/registerGlobalMiddleware.ts +0 -9
  91. package/src/serializer.ts +0 -177
  92. package/src/ssr-client.tsx +0 -246
  93. package/src/tests/createIsomorphicFn.test-d.ts +0 -72
  94. package/src/tests/createServerMiddleware.test-d.ts +0 -611
  95. package/src/tests/envOnly.test-d.ts +0 -34
  96. package/src/tests/json.test.ts +0 -37
  97. package/src/tests/transformer.test.tsx +0 -147
@@ -2,12 +2,12 @@
2
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
3
  const jsxRuntime = require("react/jsx-runtime");
4
4
  const reactRouter = require("@tanstack/react-router");
5
- const ssrClient = require("./ssr-client.cjs");
5
+ const startClientCore = require("@tanstack/start-client-core");
6
6
  let hydrationPromise;
7
7
  function StartClient(props) {
8
8
  if (!hydrationPromise) {
9
9
  if (!props.router.state.matches.length) {
10
- hydrationPromise = ssrClient.hydrate(props.router);
10
+ hydrationPromise = startClientCore.hydrate(props.router);
11
11
  } else {
12
12
  hydrationPromise = Promise.resolve();
13
13
  }
@@ -1 +1 @@
1
- {"version":3,"file":"StartClient.cjs","sources":["../../src/StartClient.tsx"],"sourcesContent":["import { Await, RouterProvider } from '@tanstack/react-router'\nimport { hydrate } from './ssr-client'\nimport type { AnyRouter } from '@tanstack/react-router'\n\nlet hydrationPromise: Promise<void | Array<Array<void>>> | undefined\n\nexport function StartClient(props: { router: AnyRouter }) {\n if (!hydrationPromise) {\n if (!props.router.state.matches.length) {\n hydrationPromise = hydrate(props.router)\n } else {\n hydrationPromise = Promise.resolve()\n }\n }\n return (\n <Await\n promise={hydrationPromise}\n children={() => <RouterProvider router={props.router} />}\n />\n )\n}\n"],"names":["hydrate","jsx","Await","RouterProvider"],"mappings":";;;;;AAIA,IAAI;AAEG,SAAS,YAAY,OAA8B;AACxD,MAAI,CAAC,kBAAkB;AACrB,QAAI,CAAC,MAAM,OAAO,MAAM,QAAQ,QAAQ;AACnB,yBAAAA,UAAAA,QAAQ,MAAM,MAAM;AAAA,IAAA,OAClC;AACL,yBAAmB,QAAQ,QAAQ;AAAA,IAAA;AAAA,EACrC;AAGA,SAAAC,2BAAA;AAAA,IAACC,YAAA;AAAA,IAAA;AAAA,MACC,SAAS;AAAA,MACT,UAAU,MAAMD,2BAAAA,IAACE,YAAAA,gBAAe,EAAA,QAAQ,MAAM,OAAQ,CAAA;AAAA,IAAA;AAAA,EACxD;AAEJ;;"}
1
+ {"version":3,"file":"StartClient.cjs","sources":["../../src/StartClient.tsx"],"sourcesContent":["import { Await, RouterProvider } from '@tanstack/react-router'\nimport { hydrate } from '@tanstack/start-client-core'\nimport type { AnyRouter } from '@tanstack/router-core'\n\nlet hydrationPromise: Promise<void | Array<Array<void>>> | undefined\n\nexport function StartClient(props: { router: AnyRouter }) {\n if (!hydrationPromise) {\n if (!props.router.state.matches.length) {\n hydrationPromise = hydrate(props.router)\n } else {\n hydrationPromise = Promise.resolve()\n }\n }\n return (\n <Await\n promise={hydrationPromise}\n children={() => <RouterProvider router={props.router} />}\n />\n )\n}\n"],"names":["hydrate","jsx","Await","RouterProvider"],"mappings":";;;;;AAIA,IAAI;AAEG,SAAS,YAAY,OAA8B;AACxD,MAAI,CAAC,kBAAkB;AACrB,QAAI,CAAC,MAAM,OAAO,MAAM,QAAQ,QAAQ;AACnB,yBAAAA,gBAAAA,QAAQ,MAAM,MAAM;AAAA,IAAA,OAClC;AACL,yBAAmB,QAAQ,QAAQ;AAAA,IAAA;AAAA,EACrC;AAGA,SAAAC,2BAAA;AAAA,IAACC,YAAA;AAAA,IAAA;AAAA,MACC,SAAS;AAAA,MACT,UAAU,MAAMD,2BAAAA,IAACE,YAAAA,gBAAe,EAAA,QAAQ,MAAM,OAAQ,CAAA;AAAA,IAAA;AAAA,EACxD;AAEJ;;"}
@@ -1,4 +1,4 @@
1
- import { AnyRouter } from '@tanstack/react-router';
1
+ import { AnyRouter } from '@tanstack/router-core';
2
2
  export declare function StartClient(props: {
3
3
  router: AnyRouter;
4
4
  }): import("react/jsx-runtime").JSX.Element;
@@ -1,101 +1,8 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __copyProps = (to, from, except, desc) => {
9
- if (from && typeof from === "object" || typeof from === "function") {
10
- for (let key of __getOwnPropNames(from))
11
- if (!__hasOwnProp.call(to, key) && key !== except)
12
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
- }
14
- return to;
15
- };
16
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
- // If the importer is in node compatibility mode or this is not an ESM
18
- // file that has been converted to a CommonJS file using a Babel-
19
- // compatible transform (i.e. "__esModule" has not been set), then set
20
- // "default" to the CommonJS "module.exports" for node compatibility.
21
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
- mod
23
- ));
24
2
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
25
- const invariant = require("tiny-invariant");
26
- const warning = require("tiny-warning");
27
3
  const reactRouter = require("@tanstack/react-router");
28
- const headers = require("./headers.cjs");
29
- const registerGlobalMiddleware = require("./registerGlobalMiddleware.cjs");
30
- const serializer = require("./serializer.cjs");
31
- let serverFnStaticCache;
32
- function setServerFnStaticCache(cache) {
33
- const previousCache = serverFnStaticCache;
34
- serverFnStaticCache = typeof cache === "function" ? cache() : cache;
35
- return () => {
36
- serverFnStaticCache = previousCache;
37
- };
38
- }
39
- function createServerFnStaticCache(serverFnStaticCache2) {
40
- return serverFnStaticCache2;
41
- }
42
- setServerFnStaticCache(() => {
43
- const getStaticCacheUrl = (options, hash) => {
44
- return `/__tsr/staticServerFnCache/${options.functionId}__${hash}.json`;
45
- };
46
- const jsonToFilenameSafeString = (json) => {
47
- const sortedKeysReplacer = (key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).sort().reduce((acc, curr) => {
48
- acc[curr] = value[curr];
49
- return acc;
50
- }, {}) : value;
51
- const jsonString = JSON.stringify(json ?? "", sortedKeysReplacer);
52
- return jsonString.replace(/[/\\?%*:|"<>]/g, "-").replace(/\s+/g, "_");
53
- };
54
- const staticClientCache = typeof document !== "undefined" ? /* @__PURE__ */ new Map() : null;
55
- return createServerFnStaticCache({
56
- getItem: async (ctx) => {
57
- if (typeof document === "undefined") {
58
- const hash = jsonToFilenameSafeString(ctx.data);
59
- const url = getStaticCacheUrl(ctx, hash);
60
- const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR;
61
- const { promises: fs } = await import("node:fs");
62
- const path = await import("node:path");
63
- const filePath = path.join(publicUrl, url);
64
- const [cachedResult, readError] = await fs.readFile(filePath, "utf-8").then((c) => [
65
- serializer.startSerializer.parse(c),
66
- null
67
- ]).catch((e) => [null, e]);
68
- if (readError && readError.code !== "ENOENT") {
69
- throw readError;
70
- }
71
- return cachedResult;
72
- }
73
- return void 0;
74
- },
75
- setItem: async (ctx, response) => {
76
- const { promises: fs } = await import("node:fs");
77
- const path = await import("node:path");
78
- const hash = jsonToFilenameSafeString(ctx.data);
79
- const url = getStaticCacheUrl(ctx, hash);
80
- const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR;
81
- const filePath = path.join(publicUrl, url);
82
- await fs.mkdir(path.dirname(filePath), { recursive: true });
83
- await fs.writeFile(filePath, serializer.startSerializer.stringify(response));
84
- },
85
- fetchItem: async (ctx) => {
86
- const hash = jsonToFilenameSafeString(ctx.data);
87
- const url = getStaticCacheUrl(ctx, hash);
88
- let result = staticClientCache == null ? void 0 : staticClientCache.get(url);
89
- if (!result) {
90
- result = await fetch(url, {
91
- method: "GET"
92
- }).then((r) => r.text()).then((d) => serializer.startSerializer.parse(d));
93
- staticClientCache == null ? void 0 : staticClientCache.set(url, result);
94
- }
95
- return result;
96
- }
97
- });
98
- });
4
+ const startClientCore = require("@tanstack/start-client-core");
5
+ const invariant = require("tiny-invariant");
99
6
  function createServerFn(options, __opts) {
100
7
  const resolvedOptions = __opts || options || {};
101
8
  if (typeof resolvedOptions.method === "undefined") {
@@ -121,7 +28,7 @@ function createServerFn(options, __opts) {
121
28
  });
122
29
  const resolvedMiddleware = [
123
30
  ...resolvedOptions.middleware || [],
124
- serverFnBaseToMiddleware(resolvedOptions)
31
+ startClientCore.serverFnBaseToMiddleware(resolvedOptions)
125
32
  ];
126
33
  return Object.assign(
127
34
  async (opts) => {
@@ -146,7 +53,8 @@ function createServerFn(options, __opts) {
146
53
  // The extracted function on the server-side calls
147
54
  // this function
148
55
  __executeServer: async (opts_, signal) => {
149
- const opts = opts_ instanceof FormData ? extractFormDataContext(opts_) : opts_;
56
+ var _a, _b;
57
+ const opts = opts_ instanceof FormData ? startClientCore.extractFormDataContext(opts_) : opts_;
150
58
  opts.type = typeof resolvedOptions.type === "function" ? resolvedOptions.type(opts) : resolvedOptions.type;
151
59
  const ctx = {
152
60
  ...extractedFn,
@@ -163,8 +71,8 @@ function createServerFn(options, __opts) {
163
71
  );
164
72
  if (ctx.type === "static") {
165
73
  let response;
166
- if (serverFnStaticCache == null ? void 0 : serverFnStaticCache.getItem) {
167
- response = await serverFnStaticCache.getItem(ctx);
74
+ if ((_a = startClientCore.serverFnStaticCache) == null ? void 0 : _a.getItem) {
75
+ response = await startClientCore.serverFnStaticCache.getItem(ctx);
168
76
  }
169
77
  if (!response) {
170
78
  response = await run().then((d) => {
@@ -178,8 +86,8 @@ function createServerFn(options, __opts) {
178
86
  error: e
179
87
  };
180
88
  });
181
- if (serverFnStaticCache == null ? void 0 : serverFnStaticCache.setItem) {
182
- await serverFnStaticCache.setItem(ctx, response);
89
+ if ((_b = startClientCore.serverFnStaticCache) == null ? void 0 : _b.setItem) {
90
+ await startClientCore.serverFnStaticCache.setItem(ctx, response);
183
91
  }
184
92
  }
185
93
  invariant(
@@ -198,87 +106,9 @@ function createServerFn(options, __opts) {
198
106
  }
199
107
  };
200
108
  }
201
- function extractFormDataContext(formData) {
202
- const serializedContext = formData.get("__TSR_CONTEXT");
203
- formData.delete("__TSR_CONTEXT");
204
- if (typeof serializedContext !== "string") {
205
- return {
206
- context: {},
207
- data: formData
208
- };
209
- }
210
- try {
211
- const context = serializer.startSerializer.parse(serializedContext);
212
- return {
213
- context,
214
- data: formData
215
- };
216
- } catch {
217
- return {
218
- data: formData
219
- };
220
- }
221
- }
222
- function flattenMiddlewares(middlewares) {
223
- const seen = /* @__PURE__ */ new Set();
224
- const flattened = [];
225
- const recurse = (middleware) => {
226
- middleware.forEach((m) => {
227
- if (m.options.middleware) {
228
- recurse(m.options.middleware);
229
- }
230
- if (!seen.has(m)) {
231
- seen.add(m);
232
- flattened.push(m);
233
- }
234
- });
235
- };
236
- recurse(middlewares);
237
- return flattened;
238
- }
239
- const applyMiddleware = async (middlewareFn, ctx, nextFn) => {
240
- return middlewareFn({
241
- ...ctx,
242
- next: async (userCtx = {}) => {
243
- return nextFn({
244
- ...ctx,
245
- ...userCtx,
246
- context: {
247
- ...ctx.context,
248
- ...userCtx.context
249
- },
250
- sendContext: {
251
- ...ctx.sendContext,
252
- ...userCtx.sendContext ?? {}
253
- },
254
- headers: headers.mergeHeaders(ctx.headers, userCtx.headers),
255
- result: userCtx.result !== void 0 ? userCtx.result : ctx.response === "raw" ? userCtx : ctx.result,
256
- error: userCtx.error ?? ctx.error
257
- });
258
- }
259
- });
260
- };
261
- function execValidator(validator, input) {
262
- if (validator == null) return {};
263
- if ("~standard" in validator) {
264
- const result = validator["~standard"].validate(input);
265
- if (result instanceof Promise)
266
- throw new Error("Async validation not supported");
267
- if (result.issues)
268
- throw new Error(JSON.stringify(result.issues, void 0, 2));
269
- return result.value;
270
- }
271
- if ("parse" in validator) {
272
- return validator.parse(input);
273
- }
274
- if (typeof validator === "function") {
275
- return validator(input);
276
- }
277
- throw new Error("Invalid validator type!");
278
- }
279
109
  async function executeMiddleware(middlewares, env, opts) {
280
- const flattenedMiddlewares = flattenMiddlewares([
281
- ...registerGlobalMiddleware.globalMiddleware,
110
+ const flattenedMiddlewares = startClientCore.flattenMiddlewares([
111
+ ...startClientCore.globalMiddleware,
282
112
  ...middlewares
283
113
  ]);
284
114
  const next = async (ctx) => {
@@ -287,11 +117,11 @@ async function executeMiddleware(middlewares, env, opts) {
287
117
  return ctx;
288
118
  }
289
119
  if (nextMiddleware.options.validator && (env === "client" ? nextMiddleware.options.validateClient : true)) {
290
- ctx.data = await execValidator(nextMiddleware.options.validator, ctx.data);
120
+ ctx.data = await startClientCore.execValidator(nextMiddleware.options.validator, ctx.data);
291
121
  }
292
122
  const middlewareFn = env === "client" ? nextMiddleware.options.client : nextMiddleware.options.server;
293
123
  if (middlewareFn) {
294
- return applyMiddleware(middlewareFn, ctx, async (newCtx) => {
124
+ return startClientCore.applyMiddleware(middlewareFn, ctx, async (newCtx) => {
295
125
  return next(newCtx).catch((error) => {
296
126
  if (reactRouter.isRedirect(error) || reactRouter.isNotFound(error)) {
297
127
  return {
@@ -312,52 +142,5 @@ async function executeMiddleware(middlewares, env, opts) {
312
142
  context: opts.context || {}
313
143
  });
314
144
  }
315
- function serverFnBaseToMiddleware(options) {
316
- return {
317
- _types: void 0,
318
- options: {
319
- validator: options.validator,
320
- validateClient: options.validateClient,
321
- client: async ({ next, sendContext, ...ctx }) => {
322
- var _a;
323
- const payload = {
324
- ...ctx,
325
- // switch the sendContext over to context
326
- context: sendContext,
327
- type: typeof ctx.type === "function" ? ctx.type(ctx) : ctx.type
328
- };
329
- if (ctx.type === "static" && process.env.NODE_ENV === "production" && typeof document !== "undefined") {
330
- invariant(
331
- serverFnStaticCache,
332
- "serverFnStaticCache.fetchItem is not available!"
333
- );
334
- const result = await serverFnStaticCache.fetchItem(payload);
335
- if (result) {
336
- if (result.error) {
337
- throw result.error;
338
- }
339
- return next(result.ctx);
340
- }
341
- warning(
342
- result,
343
- `No static cache item found for ${payload.functionId}__${JSON.stringify(payload.data)}, falling back to server function...`
344
- );
345
- }
346
- const res = await ((_a = options.extractedFn) == null ? void 0 : _a.call(options, payload));
347
- return next(res);
348
- },
349
- server: async ({ next, ...ctx }) => {
350
- var _a;
351
- const result = await ((_a = options.serverFn) == null ? void 0 : _a.call(options, ctx));
352
- return next({
353
- ...ctx,
354
- result
355
- });
356
- }
357
- }
358
- };
359
- }
360
145
  exports.createServerFn = createServerFn;
361
- exports.createServerFnStaticCache = createServerFnStaticCache;
362
- exports.setServerFnStaticCache = setServerFnStaticCache;
363
146
  //# sourceMappingURL=createServerFn.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"createServerFn.cjs","sources":["../../src/createServerFn.ts"],"sourcesContent":["import { default as invariant } from 'tiny-invariant'\nimport { default as warning } from 'tiny-warning'\nimport { isNotFound, isRedirect } from '@tanstack/react-router'\nimport { mergeHeaders } from './headers'\nimport { globalMiddleware } from './registerGlobalMiddleware'\nimport { startSerializer } from './serializer'\nimport type { Readable } from 'node:stream'\nimport type {\n AnyValidator,\n Constrain,\n Expand,\n ResolveValidatorInput,\n SerializerParse,\n SerializerStringify,\n SerializerStringifyBy,\n Validator,\n} from '@tanstack/router-core'\nimport type {\n AnyMiddleware,\n AssignAllClientSendContext,\n AssignAllServerContext,\n IntersectAllValidatorInputs,\n IntersectAllValidatorOutputs,\n MiddlewareClientFnResult,\n MiddlewareServerFnResult,\n} from './createMiddleware'\n\nexport interface JsonResponse<TData> extends Response {\n json: () => Promise<TData>\n}\n\nexport type CompiledFetcherFnOptions = {\n method: Method\n data: unknown\n response?: ServerFnResponseType\n headers?: HeadersInit\n signal?: AbortSignal\n context?: any\n}\n\nexport type Fetcher<\n TMiddlewares,\n TValidator,\n TResponse,\n TServerFnResponseType extends ServerFnResponseType,\n> =\n undefined extends IntersectAllValidatorInputs<TMiddlewares, TValidator>\n ? OptionalFetcher<\n TMiddlewares,\n TValidator,\n TResponse,\n TServerFnResponseType\n >\n : RequiredFetcher<\n TMiddlewares,\n TValidator,\n TResponse,\n TServerFnResponseType\n >\n\nexport interface FetcherBase {\n url: string\n __executeServer: (opts: {\n method: Method\n response?: ServerFnResponseType\n data: unknown\n headers?: HeadersInit\n context?: any\n signal: AbortSignal\n }) => Promise<unknown>\n}\n\nexport type FetchResult<\n TMiddlewares,\n TResponse,\n TServerFnResponseType extends ServerFnResponseType,\n> = TServerFnResponseType extends 'raw'\n ? Promise<Response>\n : TServerFnResponseType extends 'full'\n ? Promise<FullFetcherData<TMiddlewares, TResponse>>\n : Promise<FetcherData<TResponse>>\n\nexport interface OptionalFetcher<\n TMiddlewares,\n TValidator,\n TResponse,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FetcherBase {\n (\n options?: OptionalFetcherDataOptions<TMiddlewares, TValidator>,\n ): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>\n}\n\nexport interface RequiredFetcher<\n TMiddlewares,\n TValidator,\n TResponse,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FetcherBase {\n (\n opts: RequiredFetcherDataOptions<TMiddlewares, TValidator>,\n ): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>\n}\n\nexport type FetcherBaseOptions = {\n headers?: HeadersInit\n type?: ServerFnType\n signal?: AbortSignal\n}\n\nexport type ServerFnType = 'static' | 'dynamic'\n\nexport interface OptionalFetcherDataOptions<TMiddlewares, TValidator>\n extends FetcherBaseOptions {\n data?: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>\n}\n\nexport interface RequiredFetcherDataOptions<TMiddlewares, TValidator>\n extends FetcherBaseOptions {\n data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>\n}\n\nexport interface FullFetcherData<TMiddlewares, TResponse> {\n error: unknown\n result: FetcherData<TResponse>\n context: AssignAllClientSendContext<TMiddlewares>\n}\n\nexport type FetcherData<TResponse> =\n TResponse extends JsonResponse<any>\n ? SerializerParse<ReturnType<TResponse['json']>>\n : SerializerParse<TResponse>\n\nexport type RscStream<T> = {\n __cacheState: T\n}\n\nexport type Method = 'GET' | 'POST'\nexport type ServerFnResponseType = 'data' | 'full' | 'raw'\n\n// see https://h3.unjs.io/guide/event-handler#responses-types\nexport type RawResponse = Response | ReadableStream | Readable | null | string\n\nexport type ServerFnReturnType<\n TServerFnResponseType extends ServerFnResponseType,\n TResponse,\n> = TServerFnResponseType extends 'raw'\n ? RawResponse | Promise<RawResponse>\n : Promise<SerializerStringify<TResponse>> | SerializerStringify<TResponse>\nexport type ServerFn<\n TMethod,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n TResponse,\n> = (\n ctx: ServerFnCtx<TMethod, TServerFnResponseType, TMiddlewares, TValidator>,\n) => ServerFnReturnType<TServerFnResponseType, TResponse>\n\nexport interface ServerFnCtx<\n TMethod,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n> {\n method: TMethod\n response: TServerFnResponseType\n data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllServerContext<TMiddlewares>>\n signal: AbortSignal\n}\n\nexport type CompiledFetcherFn<\n TResponse,\n TServerFnResponseType extends ServerFnResponseType,\n> = {\n (\n opts: CompiledFetcherFnOptions &\n ServerFnBaseOptions<Method, TServerFnResponseType>,\n ): Promise<TResponse>\n url: string\n}\n\ntype ServerFnBaseOptions<\n TMethod extends Method = 'GET',\n TServerFnResponseType extends ServerFnResponseType = 'data',\n TResponse = unknown,\n TMiddlewares = unknown,\n TInput = unknown,\n> = {\n method: TMethod\n response?: TServerFnResponseType\n validateClient?: boolean\n middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyMiddleware>>\n validator?: ConstrainValidator<TInput>\n extractedFn?: CompiledFetcherFn<TResponse, TServerFnResponseType>\n serverFn?: ServerFn<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TInput,\n TResponse\n >\n functionId: string\n type: ServerFnTypeOrTypeFn<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n AnyValidator\n >\n}\n\nexport type ValidatorSerializerStringify<TValidator> = Validator<\n SerializerStringifyBy<\n ResolveValidatorInput<TValidator>,\n Date | undefined | FormData\n >,\n any\n>\n\nexport type ConstrainValidator<TValidator> = unknown extends TValidator\n ? TValidator\n : Constrain<TValidator, ValidatorSerializerStringify<TValidator>>\n\nexport interface ServerFnMiddleware<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TValidator,\n> {\n middleware: <const TNewMiddlewares = undefined>(\n middlewares: Constrain<TNewMiddlewares, ReadonlyArray<AnyMiddleware>>,\n ) => ServerFnAfterMiddleware<\n TMethod,\n TServerFnResponseType,\n TNewMiddlewares,\n TValidator\n >\n}\n\nexport interface ServerFnAfterMiddleware<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n> extends ServerFnValidator<TMethod, TServerFnResponseType, TMiddlewares>,\n ServerFnTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>,\n ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {}\n\nexport type ValidatorFn<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n> = <TValidator>(\n validator: ConstrainValidator<TValidator>,\n) => ServerFnAfterValidator<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n>\n\nexport interface ServerFnValidator<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n> {\n validator: ValidatorFn<TMethod, TServerFnResponseType, TMiddlewares>\n}\n\nexport interface ServerFnAfterValidator<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n> extends ServerFnMiddleware<TMethod, TServerFnResponseType, TValidator>,\n ServerFnTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>,\n ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {}\n\n// Typer\nexport interface ServerFnTyper<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n> {\n type: (\n typer: ServerFnTypeOrTypeFn<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n >,\n ) => ServerFnAfterTyper<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n >\n}\n\nexport type ServerFnTypeOrTypeFn<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n> =\n | ServerFnType\n | ((\n ctx: ServerFnCtx<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n >,\n ) => ServerFnType)\n\nexport interface ServerFnAfterTyper<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n> extends ServerFnHandler<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n > {}\n\n// Handler\nexport interface ServerFnHandler<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType,\n TMiddlewares,\n TValidator,\n> {\n handler: <TNewResponse>(\n fn?: ServerFn<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator,\n TNewResponse\n >,\n ) => Fetcher<TMiddlewares, TValidator, TNewResponse, TServerFnResponseType>\n}\n\nexport interface ServerFnBuilder<\n TMethod extends Method = 'GET',\n TServerFnResponseType extends ServerFnResponseType = 'data',\n> extends ServerFnMiddleware<TMethod, TServerFnResponseType, undefined>,\n ServerFnValidator<TMethod, TServerFnResponseType, undefined>,\n ServerFnTyper<TMethod, TServerFnResponseType, undefined, undefined>,\n ServerFnHandler<TMethod, TServerFnResponseType, undefined, undefined> {\n options: ServerFnBaseOptions<\n TMethod,\n TServerFnResponseType,\n unknown,\n undefined,\n undefined\n >\n}\n\ntype StaticCachedResult = {\n ctx?: {\n result: any\n context: any\n }\n error?: any\n}\n\nexport type ServerFnStaticCache = {\n getItem: (\n ctx: MiddlewareResult,\n ) => StaticCachedResult | Promise<StaticCachedResult | undefined>\n setItem: (\n ctx: MiddlewareResult,\n response: StaticCachedResult,\n ) => Promise<void>\n fetchItem: (\n ctx: MiddlewareResult,\n ) => StaticCachedResult | Promise<StaticCachedResult | undefined>\n}\n\nlet serverFnStaticCache: ServerFnStaticCache | undefined\n\nexport function setServerFnStaticCache(\n cache?: ServerFnStaticCache | (() => ServerFnStaticCache | undefined),\n) {\n const previousCache = serverFnStaticCache\n serverFnStaticCache = typeof cache === 'function' ? cache() : cache\n\n return () => {\n serverFnStaticCache = previousCache\n }\n}\n\nexport function createServerFnStaticCache(\n serverFnStaticCache: ServerFnStaticCache,\n) {\n return serverFnStaticCache\n}\n\nsetServerFnStaticCache(() => {\n const getStaticCacheUrl = (options: MiddlewareResult, hash: string) => {\n return `/__tsr/staticServerFnCache/${options.functionId}__${hash}.json`\n }\n\n const jsonToFilenameSafeString = (json: any) => {\n // Custom replacer to sort keys\n const sortedKeysReplacer = (key: string, value: any) =>\n value && typeof value === 'object' && !Array.isArray(value)\n ? Object.keys(value)\n .sort()\n .reduce((acc: any, curr: string) => {\n acc[curr] = value[curr]\n return acc\n }, {})\n : value\n\n // Convert JSON to string with sorted keys\n const jsonString = JSON.stringify(json ?? '', sortedKeysReplacer)\n\n // Replace characters invalid in filenames\n return jsonString\n .replace(/[/\\\\?%*:|\"<>]/g, '-') // Replace invalid characters with a dash\n .replace(/\\s+/g, '_') // Optionally replace whitespace with underscores\n }\n\n const staticClientCache =\n typeof document !== 'undefined' ? new Map<string, any>() : null\n\n return createServerFnStaticCache({\n getItem: async (ctx) => {\n if (typeof document === 'undefined') {\n const hash = jsonToFilenameSafeString(ctx.data)\n const url = getStaticCacheUrl(ctx, hash)\n const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR!\n\n // Use fs instead of fetch to read from filesystem\n const { promises: fs } = await import('node:fs')\n const path = await import('node:path')\n const filePath = path.join(publicUrl, url)\n\n const [cachedResult, readError] = await fs\n .readFile(filePath, 'utf-8')\n .then((c) => [\n startSerializer.parse(c) as {\n ctx: unknown\n error: any\n },\n null,\n ])\n .catch((e) => [null, e])\n\n if (readError && readError.code !== 'ENOENT') {\n throw readError\n }\n\n return cachedResult as StaticCachedResult\n }\n\n return undefined\n },\n setItem: async (ctx, response) => {\n const { promises: fs } = await import('node:fs')\n const path = await import('node:path')\n\n const hash = jsonToFilenameSafeString(ctx.data)\n const url = getStaticCacheUrl(ctx, hash)\n const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR!\n const filePath = path.join(publicUrl, url)\n\n // Ensure the directory exists\n await fs.mkdir(path.dirname(filePath), { recursive: true })\n\n // Store the result with fs\n await fs.writeFile(filePath, startSerializer.stringify(response))\n },\n fetchItem: async (ctx) => {\n const hash = jsonToFilenameSafeString(ctx.data)\n const url = getStaticCacheUrl(ctx, hash)\n\n let result: any = staticClientCache?.get(url)\n\n if (!result) {\n result = await fetch(url, {\n method: 'GET',\n })\n .then((r) => r.text())\n .then((d) => startSerializer.parse(d))\n\n staticClientCache?.set(url, result)\n }\n\n return result\n },\n })\n})\n\nexport function createServerFn<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType = 'data',\n TResponse = unknown,\n TMiddlewares = undefined,\n TValidator = undefined,\n>(\n options?: {\n method?: TMethod\n response?: TServerFnResponseType\n type?: ServerFnType\n },\n __opts?: ServerFnBaseOptions<\n TMethod,\n TServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >,\n): ServerFnBuilder<TMethod, TServerFnResponseType> {\n const resolvedOptions = (__opts || options || {}) as ServerFnBaseOptions<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >\n\n if (typeof resolvedOptions.method === 'undefined') {\n resolvedOptions.method = 'GET' as TMethod\n }\n\n return {\n options: resolvedOptions as any,\n middleware: (middleware) => {\n return createServerFn<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >(undefined, Object.assign(resolvedOptions, { middleware })) as any\n },\n validator: (validator) => {\n return createServerFn<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >(undefined, Object.assign(resolvedOptions, { validator })) as any\n },\n type: (type) => {\n return createServerFn<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >(undefined, Object.assign(resolvedOptions, { type })) as any\n },\n handler: (...args) => {\n // This function signature changes due to AST transformations\n // in the babel plugin. We need to cast it to the correct\n // function signature post-transformation\n const [extractedFn, serverFn] = args as unknown as [\n CompiledFetcherFn<TResponse, TServerFnResponseType>,\n ServerFn<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator,\n TResponse\n >,\n ]\n\n // Keep the original function around so we can use it\n // in the server environment\n Object.assign(resolvedOptions, {\n ...extractedFn,\n extractedFn,\n serverFn,\n })\n\n const resolvedMiddleware = [\n ...(resolvedOptions.middleware || []),\n serverFnBaseToMiddleware(resolvedOptions),\n ]\n\n // We want to make sure the new function has the same\n // properties as the original function\n return Object.assign(\n async (opts?: CompiledFetcherFnOptions) => {\n // Start by executing the client-side middleware chain\n return executeMiddleware(resolvedMiddleware, 'client', {\n ...extractedFn,\n ...resolvedOptions,\n data: opts?.data as any,\n headers: opts?.headers,\n signal: opts?.signal,\n context: {},\n }).then((d) => {\n if (resolvedOptions.response === 'full') {\n return d\n }\n if (d.error) throw d.error\n return d.result\n })\n },\n {\n // This copies over the URL, function ID\n ...extractedFn,\n // The extracted function on the server-side calls\n // this function\n __executeServer: async (opts_: any, signal: AbortSignal) => {\n const opts =\n opts_ instanceof FormData ? extractFormDataContext(opts_) : opts_\n\n opts.type =\n typeof resolvedOptions.type === 'function'\n ? resolvedOptions.type(opts)\n : resolvedOptions.type\n\n const ctx = {\n ...extractedFn,\n ...opts,\n signal,\n }\n\n const run = () =>\n executeMiddleware(resolvedMiddleware, 'server', ctx).then(\n (d) => ({\n // Only send the result and sendContext back to the client\n result: d.result,\n error: d.error,\n context: d.sendContext,\n }),\n )\n\n if (ctx.type === 'static') {\n let response: StaticCachedResult | undefined\n\n // If we can get the cached item, try to get it\n if (serverFnStaticCache?.getItem) {\n // If this throws, it's okay to let it bubble up\n response = await serverFnStaticCache.getItem(ctx)\n }\n\n if (!response) {\n // If there's no cached item, execute the server function\n response = await run()\n .then((d) => {\n return {\n ctx: d,\n error: null,\n }\n })\n .catch((e) => {\n return {\n ctx: undefined,\n error: e,\n }\n })\n\n if (serverFnStaticCache?.setItem) {\n await serverFnStaticCache.setItem(ctx, response)\n }\n }\n\n invariant(\n response,\n 'No response from both server and static cache!',\n )\n\n if (response.error) {\n throw response.error\n }\n\n return response.ctx\n }\n\n return run()\n },\n },\n ) as any\n },\n }\n}\n\nfunction extractFormDataContext(formData: FormData) {\n const serializedContext = formData.get('__TSR_CONTEXT')\n formData.delete('__TSR_CONTEXT')\n\n if (typeof serializedContext !== 'string') {\n return {\n context: {},\n data: formData,\n }\n }\n\n try {\n const context = startSerializer.parse(serializedContext)\n return {\n context,\n data: formData,\n }\n } catch {\n return {\n data: formData,\n }\n }\n}\n\nfunction flattenMiddlewares(\n middlewares: Array<AnyMiddleware>,\n): Array<AnyMiddleware> {\n const seen = new Set<AnyMiddleware>()\n const flattened: Array<AnyMiddleware> = []\n\n const recurse = (middleware: Array<AnyMiddleware>) => {\n middleware.forEach((m) => {\n if (m.options.middleware) {\n recurse(m.options.middleware)\n }\n\n if (!seen.has(m)) {\n seen.add(m)\n flattened.push(m)\n }\n })\n }\n\n recurse(middlewares)\n\n return flattened\n}\n\nexport type MiddlewareOptions = {\n method: Method\n response?: ServerFnResponseType\n data: any\n headers?: HeadersInit\n signal?: AbortSignal\n sendContext?: any\n context?: any\n type: ServerFnTypeOrTypeFn<any, any, any, any>\n functionId: string\n}\n\nexport type MiddlewareResult = MiddlewareOptions & {\n result?: unknown\n error?: unknown\n type: ServerFnTypeOrTypeFn<any, any, any, any>\n}\n\nexport type NextFn = (ctx: MiddlewareResult) => Promise<MiddlewareResult>\n\nexport type MiddlewareFn = (\n ctx: MiddlewareOptions & {\n next: NextFn\n },\n) => Promise<MiddlewareResult>\n\nconst applyMiddleware = async (\n middlewareFn: MiddlewareFn,\n ctx: MiddlewareOptions,\n nextFn: NextFn,\n) => {\n return middlewareFn({\n ...ctx,\n next: (async (userCtx: MiddlewareResult | undefined = {} as any) => {\n // Return the next middleware\n return nextFn({\n ...ctx,\n ...userCtx,\n context: {\n ...ctx.context,\n ...userCtx.context,\n },\n sendContext: {\n ...ctx.sendContext,\n ...(userCtx.sendContext ?? {}),\n },\n headers: mergeHeaders(ctx.headers, userCtx.headers),\n result:\n userCtx.result !== undefined\n ? userCtx.result\n : ctx.response === 'raw'\n ? userCtx\n : (ctx as any).result,\n error: userCtx.error ?? (ctx as any).error,\n })\n }) as any,\n } as any)\n}\n\nfunction execValidator(validator: AnyValidator, input: unknown): unknown {\n if (validator == null) return {}\n\n if ('~standard' in validator) {\n const result = validator['~standard'].validate(input)\n\n if (result instanceof Promise)\n throw new Error('Async validation not supported')\n\n if (result.issues)\n throw new Error(JSON.stringify(result.issues, undefined, 2))\n\n return result.value\n }\n\n if ('parse' in validator) {\n return validator.parse(input)\n }\n\n if (typeof validator === 'function') {\n return validator(input)\n }\n\n throw new Error('Invalid validator type!')\n}\n\nasync function executeMiddleware(\n middlewares: Array<AnyMiddleware>,\n env: 'client' | 'server',\n opts: MiddlewareOptions,\n): Promise<MiddlewareResult> {\n const flattenedMiddlewares = flattenMiddlewares([\n ...globalMiddleware,\n ...middlewares,\n ])\n\n const next: NextFn = async (ctx) => {\n // Get the next middleware\n const nextMiddleware = flattenedMiddlewares.shift()\n\n // If there are no more middlewares, return the context\n if (!nextMiddleware) {\n return ctx\n }\n\n if (\n nextMiddleware.options.validator &&\n (env === 'client' ? nextMiddleware.options.validateClient : true)\n ) {\n // Execute the middleware's input function\n ctx.data = await execValidator(nextMiddleware.options.validator, ctx.data)\n }\n\n const middlewareFn = (\n env === 'client'\n ? nextMiddleware.options.client\n : nextMiddleware.options.server\n ) as MiddlewareFn | undefined\n\n if (middlewareFn) {\n // Execute the middleware\n return applyMiddleware(middlewareFn, ctx, async (newCtx) => {\n return next(newCtx).catch((error) => {\n if (isRedirect(error) || isNotFound(error)) {\n return {\n ...newCtx,\n error,\n }\n }\n\n throw error\n })\n })\n }\n\n return next(ctx)\n }\n\n // Start the middleware chain\n return next({\n ...opts,\n headers: opts.headers || {},\n sendContext: opts.sendContext || {},\n context: opts.context || {},\n })\n}\n\nfunction serverFnBaseToMiddleware(\n options: ServerFnBaseOptions<any, any, any, any, any>,\n): AnyMiddleware {\n return {\n _types: undefined!,\n options: {\n validator: options.validator,\n validateClient: options.validateClient,\n client: async ({ next, sendContext, ...ctx }) => {\n const payload = {\n ...ctx,\n // switch the sendContext over to context\n context: sendContext,\n type: typeof ctx.type === 'function' ? ctx.type(ctx) : ctx.type,\n } as any\n\n if (\n ctx.type === 'static' &&\n process.env.NODE_ENV === 'production' &&\n typeof document !== 'undefined'\n ) {\n invariant(\n serverFnStaticCache,\n 'serverFnStaticCache.fetchItem is not available!',\n )\n\n const result = await serverFnStaticCache.fetchItem(payload)\n\n if (result) {\n if (result.error) {\n throw result.error\n }\n\n return next(result.ctx)\n }\n\n warning(\n result,\n `No static cache item found for ${payload.functionId}__${JSON.stringify(payload.data)}, falling back to server function...`,\n )\n }\n\n // Execute the extracted function\n // but not before serializing the context\n const res = await options.extractedFn?.(payload)\n\n return next(res) as unknown as MiddlewareClientFnResult<any, any, any>\n },\n server: async ({ next, ...ctx }) => {\n // Execute the server function\n const result = await options.serverFn?.(ctx)\n\n return next({\n ...ctx,\n result,\n } as any) as unknown as MiddlewareServerFnResult<any, any, any, any>\n },\n },\n }\n}\n"],"names":["serverFnStaticCache","startSerializer","mergeHeaders","globalMiddleware","isRedirect","isNotFound"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+XA,IAAI;AAEG,SAAS,uBACd,OACA;AACA,QAAM,gBAAgB;AACtB,wBAAsB,OAAO,UAAU,aAAa,MAAU,IAAA;AAE9D,SAAO,MAAM;AACW,0BAAA;AAAA,EACxB;AACF;AAEO,SAAS,0BACdA,sBACA;AACOA,SAAAA;AACT;AAEA,uBAAuB,MAAM;AACrB,QAAA,oBAAoB,CAAC,SAA2B,SAAiB;AACrE,WAAO,8BAA8B,QAAQ,UAAU,KAAK,IAAI;AAAA,EAClE;AAEM,QAAA,2BAA2B,CAAC,SAAc;AAExC,UAAA,qBAAqB,CAAC,KAAa,UACvC,SAAS,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACtD,OAAO,KAAK,KAAK,EACd,OACA,OAAO,CAAC,KAAU,SAAiB;AAC9B,UAAA,IAAI,IAAI,MAAM,IAAI;AACf,aAAA;AAAA,IAAA,GACN,CAAA,CAAE,IACP;AAGN,UAAM,aAAa,KAAK,UAAU,QAAQ,IAAI,kBAAkB;AAGhE,WAAO,WACJ,QAAQ,kBAAkB,GAAG,EAC7B,QAAQ,QAAQ,GAAG;AAAA,EACxB;AAEA,QAAM,oBACJ,OAAO,aAAa,cAAc,oBAAI,IAAqB,IAAA;AAE7D,SAAO,0BAA0B;AAAA,IAC/B,SAAS,OAAO,QAAQ;AAClB,UAAA,OAAO,aAAa,aA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;AAAA,UACV,GAAG;AAAA,UACH;AAAA,QAAA,CACM;AAAA,MAAA;AAAA,IACV;AAAA,EAEJ;AACF;;;;"}
1
+ {"version":3,"file":"createServerFn.cjs","sources":["../../src/createServerFn.ts"],"sourcesContent":["import { isNotFound, isRedirect } from '@tanstack/react-router'\nimport {\n applyMiddleware,\n execValidator,\n extractFormDataContext,\n flattenMiddlewares,\n globalMiddleware,\n serverFnBaseToMiddleware,\n serverFnStaticCache,\n} from '@tanstack/start-client-core'\nimport invariant from 'tiny-invariant'\nimport type {\n AnyMiddleware,\n CompiledFetcherFn,\n CompiledFetcherFnOptions,\n Method,\n MiddlewareFn,\n NextFn,\n ServerFn,\n ServerFnBaseOptions,\n ServerFnBuilder,\n ServerFnMiddlewareOptions,\n ServerFnMiddlewareResult,\n ServerFnResponseType,\n ServerFnType,\n StaticCachedResult,\n} from '@tanstack/start-client-core'\n\nexport function createServerFn<\n TMethod extends Method,\n TServerFnResponseType extends ServerFnResponseType = 'data',\n TResponse = unknown,\n TMiddlewares = undefined,\n TValidator = undefined,\n>(\n options?: {\n method?: TMethod\n response?: TServerFnResponseType\n type?: ServerFnType\n },\n __opts?: ServerFnBaseOptions<\n TMethod,\n TServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >,\n): ServerFnBuilder<TMethod, TServerFnResponseType> {\n const resolvedOptions = (__opts || options || {}) as ServerFnBaseOptions<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >\n\n if (typeof resolvedOptions.method === 'undefined') {\n resolvedOptions.method = 'GET' as TMethod\n }\n\n return {\n options: resolvedOptions as any,\n middleware: (middleware) => {\n return createServerFn<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >(undefined, Object.assign(resolvedOptions, { middleware })) as any\n },\n validator: (validator) => {\n return createServerFn<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >(undefined, Object.assign(resolvedOptions, { validator })) as any\n },\n type: (type) => {\n return createServerFn<\n TMethod,\n ServerFnResponseType,\n TResponse,\n TMiddlewares,\n TValidator\n >(undefined, Object.assign(resolvedOptions, { type })) as any\n },\n handler: (...args) => {\n // This function signature changes due to AST transformations\n // in the babel plugin. We need to cast it to the correct\n // function signature post-transformation\n const [extractedFn, serverFn] = args as unknown as [\n CompiledFetcherFn<TResponse, TServerFnResponseType>,\n ServerFn<\n TMethod,\n TServerFnResponseType,\n TMiddlewares,\n TValidator,\n TResponse\n >,\n ]\n\n // Keep the original function around so we can use it\n // in the server environment\n Object.assign(resolvedOptions, {\n ...extractedFn,\n extractedFn,\n serverFn,\n })\n\n const resolvedMiddleware = [\n ...(resolvedOptions.middleware || []),\n serverFnBaseToMiddleware(resolvedOptions),\n ]\n\n // We want to make sure the new function has the same\n // properties as the original function\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n return Object.assign(\n async (opts?: CompiledFetcherFnOptions) => {\n // Start by executing the client-side middleware chain\n return executeMiddleware(resolvedMiddleware, 'client', {\n ...extractedFn,\n ...resolvedOptions,\n data: opts?.data as any,\n headers: opts?.headers,\n signal: opts?.signal,\n context: {},\n }).then((d) => {\n if (resolvedOptions.response === 'full') {\n return d\n }\n if (d.error) throw d.error\n return d.result\n })\n },\n {\n // This copies over the URL, function ID\n ...extractedFn,\n // The extracted function on the server-side calls\n // this function\n __executeServer: async (opts_: any, signal: AbortSignal) => {\n const opts =\n opts_ instanceof FormData ? extractFormDataContext(opts_) : opts_\n\n opts.type =\n typeof resolvedOptions.type === 'function'\n ? resolvedOptions.type(opts)\n : resolvedOptions.type\n\n const ctx = {\n ...extractedFn,\n ...opts,\n signal,\n }\n\n const run = () =>\n executeMiddleware(resolvedMiddleware, 'server', ctx).then(\n (d) => ({\n // Only send the result and sendContext back to the client\n result: d.result,\n error: d.error,\n context: d.sendContext,\n }),\n )\n\n if (ctx.type === 'static') {\n let response: StaticCachedResult | undefined\n\n // If we can get the cached item, try to get it\n if (serverFnStaticCache?.getItem) {\n // If this throws, it's okay to let it bubble up\n response = await serverFnStaticCache.getItem(ctx)\n }\n\n if (!response) {\n // If there's no cached item, execute the server function\n response = await run()\n .then((d) => {\n return {\n ctx: d,\n error: null,\n }\n })\n .catch((e) => {\n return {\n ctx: undefined,\n error: e,\n }\n })\n\n if (serverFnStaticCache?.setItem) {\n await serverFnStaticCache.setItem(ctx, response)\n }\n }\n\n invariant(\n response,\n 'No response from both server and static cache!',\n )\n\n if (response.error) {\n throw response.error\n }\n\n return response.ctx\n }\n\n return run()\n },\n },\n ) as any\n },\n }\n}\n\nasync function executeMiddleware(\n middlewares: Array<AnyMiddleware>,\n env: 'client' | 'server',\n opts: ServerFnMiddlewareOptions,\n): Promise<ServerFnMiddlewareResult> {\n const flattenedMiddlewares = flattenMiddlewares([\n ...globalMiddleware,\n ...middlewares,\n ])\n\n const next: NextFn = async (ctx) => {\n // Get the next middleware\n const nextMiddleware = flattenedMiddlewares.shift()\n\n // If there are no more middlewares, return the context\n if (!nextMiddleware) {\n return ctx\n }\n\n if (\n nextMiddleware.options.validator &&\n (env === 'client' ? nextMiddleware.options.validateClient : true)\n ) {\n // Execute the middleware's input function\n ctx.data = await execValidator(nextMiddleware.options.validator, ctx.data)\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion\n const middlewareFn = (\n env === 'client'\n ? nextMiddleware.options.client\n : nextMiddleware.options.server\n ) as MiddlewareFn | undefined\n\n if (middlewareFn) {\n // Execute the middleware\n return applyMiddleware(middlewareFn, ctx, async (newCtx) => {\n return next(newCtx).catch((error: any) => {\n if (isRedirect(error) || isNotFound(error)) {\n return {\n ...newCtx,\n error,\n }\n }\n\n throw error\n })\n })\n }\n\n return next(ctx)\n }\n\n // Start the middleware chain\n return next({\n ...opts,\n headers: opts.headers || {},\n sendContext: opts.sendContext || {},\n context: opts.context || {},\n })\n}\n"],"names":["serverFnBaseToMiddleware","extractFormDataContext","serverFnStaticCache","flattenMiddlewares","globalMiddleware","execVal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C;AACnC,QAAM,uBAAuBC,gBAAAA,mBAAmB;AAAA,IAC9C,GAAGC,gBAAA;AAAA,IACH,GAAG;AAAA,EAAA,CACJ;AAEK,QAAA,OAAe,OAAO,QAAQ;AAE5B,UAAA,iBAAiB,qBAAqB,MAAM;AAGlD,QAAI,CAAC,gBAAgB;AACZ,aAAA;AAAA,IAAA;AAIP,QAAA,eAAe,QAAQ,cACtB,QAAQ,WAAW,eAAe,QAAQ,iBAAiB,OAC5D;AAEA,UAAI,OAAO,MAAMC,8BAAc,eAAe,QAAQ,WAAW,IAAI,IAAI;AAAA,IAAA;AAI3E,UAAM,eACJ,QAAQ,WACJ,eAAe,QAAQ,SACvB,eAAe,QAAQ;AAG7B,QAAI,cAAc;AAEhB,aAAOC,gCAAgB,cAAc,KAAK,OAAO,WAAW;AAC1D,eAAO,KAAK,MAAM,EAAE,MAAM,CAAC,UAAe;AACxC,cAAIC,YAAW,WAAA,KAAK,KAAKC,YAAA,WAAW,KAAK,GAAG;AACnC,mBAAA;AAAA,cACL,GAAG;AAAA,cACH;AAAA,YACF;AAAA,UAAA;AAGI,gBAAA;AAAA,QAAA,CACP;AAAA,MAAA,CACF;AAAA,IAAA;AAGH,WAAO,KAAK,GAAG;AAAA,EACjB;AAGA,SAAO,KAAK;AAAA,IACV,GAAG;AAAA,IACH,SAAS,KAAK,WAAW,CAAC;AAAA,IAC1B,aAAa,KAAK,eAAe,CAAC;AAAA,IAClC,SAAS,KAAK,WAAW,CAAA;AAAA,EAAC,CAC3B;AACH;;"}
@@ -1,146 +1,6 @@
1
- import { Readable } from 'node:stream';
2
- import { AnyValidator, Constrain, Expand, ResolveValidatorInput, SerializerParse, SerializerStringify, SerializerStringifyBy, Validator } from '@tanstack/router-core';
3
- import { AnyMiddleware, AssignAllClientSendContext, AssignAllServerContext, IntersectAllValidatorInputs, IntersectAllValidatorOutputs } from './createMiddleware.cjs';
4
- export interface JsonResponse<TData> extends Response {
5
- json: () => Promise<TData>;
6
- }
7
- export type CompiledFetcherFnOptions = {
8
- method: Method;
9
- data: unknown;
10
- response?: ServerFnResponseType;
11
- headers?: HeadersInit;
12
- signal?: AbortSignal;
13
- context?: any;
14
- };
15
- export type Fetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType extends ServerFnResponseType> = undefined extends IntersectAllValidatorInputs<TMiddlewares, TValidator> ? OptionalFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType> : RequiredFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType>;
16
- export interface FetcherBase {
17
- url: string;
18
- __executeServer: (opts: {
19
- method: Method;
20
- response?: ServerFnResponseType;
21
- data: unknown;
22
- headers?: HeadersInit;
23
- context?: any;
24
- signal: AbortSignal;
25
- }) => Promise<unknown>;
26
- }
27
- export type FetchResult<TMiddlewares, TResponse, TServerFnResponseType extends ServerFnResponseType> = TServerFnResponseType extends 'raw' ? Promise<Response> : TServerFnResponseType extends 'full' ? Promise<FullFetcherData<TMiddlewares, TResponse>> : Promise<FetcherData<TResponse>>;
28
- export interface OptionalFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType extends ServerFnResponseType> extends FetcherBase {
29
- (options?: OptionalFetcherDataOptions<TMiddlewares, TValidator>): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>;
30
- }
31
- export interface RequiredFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType extends ServerFnResponseType> extends FetcherBase {
32
- (opts: RequiredFetcherDataOptions<TMiddlewares, TValidator>): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>;
33
- }
34
- export type FetcherBaseOptions = {
35
- headers?: HeadersInit;
36
- type?: ServerFnType;
37
- signal?: AbortSignal;
38
- };
39
- export type ServerFnType = 'static' | 'dynamic';
40
- export interface OptionalFetcherDataOptions<TMiddlewares, TValidator> extends FetcherBaseOptions {
41
- data?: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>;
42
- }
43
- export interface RequiredFetcherDataOptions<TMiddlewares, TValidator> extends FetcherBaseOptions {
44
- data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>;
45
- }
46
- export interface FullFetcherData<TMiddlewares, TResponse> {
47
- error: unknown;
48
- result: FetcherData<TResponse>;
49
- context: AssignAllClientSendContext<TMiddlewares>;
50
- }
51
- export type FetcherData<TResponse> = TResponse extends JsonResponse<any> ? SerializerParse<ReturnType<TResponse['json']>> : SerializerParse<TResponse>;
52
- export type RscStream<T> = {
53
- __cacheState: T;
54
- };
55
- export type Method = 'GET' | 'POST';
56
- export type ServerFnResponseType = 'data' | 'full' | 'raw';
57
- export type RawResponse = Response | ReadableStream | Readable | null | string;
58
- export type ServerFnReturnType<TServerFnResponseType extends ServerFnResponseType, TResponse> = TServerFnResponseType extends 'raw' ? RawResponse | Promise<RawResponse> : Promise<SerializerStringify<TResponse>> | SerializerStringify<TResponse>;
59
- export type ServerFn<TMethod, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator, TResponse> = (ctx: ServerFnCtx<TMethod, TServerFnResponseType, TMiddlewares, TValidator>) => ServerFnReturnType<TServerFnResponseType, TResponse>;
60
- export interface ServerFnCtx<TMethod, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> {
61
- method: TMethod;
62
- response: TServerFnResponseType;
63
- data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>;
64
- context: Expand<AssignAllServerContext<TMiddlewares>>;
65
- signal: AbortSignal;
66
- }
67
- export type CompiledFetcherFn<TResponse, TServerFnResponseType extends ServerFnResponseType> = {
68
- (opts: CompiledFetcherFnOptions & ServerFnBaseOptions<Method, TServerFnResponseType>): Promise<TResponse>;
69
- url: string;
70
- };
71
- type ServerFnBaseOptions<TMethod extends Method = 'GET', TServerFnResponseType extends ServerFnResponseType = 'data', TResponse = unknown, TMiddlewares = unknown, TInput = unknown> = {
72
- method: TMethod;
73
- response?: TServerFnResponseType;
74
- validateClient?: boolean;
75
- middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyMiddleware>>;
76
- validator?: ConstrainValidator<TInput>;
77
- extractedFn?: CompiledFetcherFn<TResponse, TServerFnResponseType>;
78
- serverFn?: ServerFn<TMethod, TServerFnResponseType, TMiddlewares, TInput, TResponse>;
79
- functionId: string;
80
- type: ServerFnTypeOrTypeFn<TMethod, TServerFnResponseType, TMiddlewares, AnyValidator>;
81
- };
82
- export type ValidatorSerializerStringify<TValidator> = Validator<SerializerStringifyBy<ResolveValidatorInput<TValidator>, Date | undefined | FormData>, any>;
83
- export type ConstrainValidator<TValidator> = unknown extends TValidator ? TValidator : Constrain<TValidator, ValidatorSerializerStringify<TValidator>>;
84
- export interface ServerFnMiddleware<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TValidator> {
85
- middleware: <const TNewMiddlewares = undefined>(middlewares: Constrain<TNewMiddlewares, ReadonlyArray<AnyMiddleware>>) => ServerFnAfterMiddleware<TMethod, TServerFnResponseType, TNewMiddlewares, TValidator>;
86
- }
87
- export interface ServerFnAfterMiddleware<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> extends ServerFnValidator<TMethod, TServerFnResponseType, TMiddlewares>, ServerFnTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>, ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {
88
- }
89
- export type ValidatorFn<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares> = <TValidator>(validator: ConstrainValidator<TValidator>) => ServerFnAfterValidator<TMethod, TServerFnResponseType, TMiddlewares, TValidator>;
90
- export interface ServerFnValidator<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares> {
91
- validator: ValidatorFn<TMethod, TServerFnResponseType, TMiddlewares>;
92
- }
93
- export interface ServerFnAfterValidator<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> extends ServerFnMiddleware<TMethod, TServerFnResponseType, TValidator>, ServerFnTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>, ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {
94
- }
95
- export interface ServerFnTyper<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> {
96
- type: (typer: ServerFnTypeOrTypeFn<TMethod, TServerFnResponseType, TMiddlewares, TValidator>) => ServerFnAfterTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>;
97
- }
98
- export type ServerFnTypeOrTypeFn<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> = ServerFnType | ((ctx: ServerFnCtx<TMethod, TServerFnResponseType, TMiddlewares, TValidator>) => ServerFnType);
99
- export interface ServerFnAfterTyper<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> extends ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {
100
- }
101
- export interface ServerFnHandler<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> {
102
- handler: <TNewResponse>(fn?: ServerFn<TMethod, TServerFnResponseType, TMiddlewares, TValidator, TNewResponse>) => Fetcher<TMiddlewares, TValidator, TNewResponse, TServerFnResponseType>;
103
- }
104
- export interface ServerFnBuilder<TMethod extends Method = 'GET', TServerFnResponseType extends ServerFnResponseType = 'data'> extends ServerFnMiddleware<TMethod, TServerFnResponseType, undefined>, ServerFnValidator<TMethod, TServerFnResponseType, undefined>, ServerFnTyper<TMethod, TServerFnResponseType, undefined, undefined>, ServerFnHandler<TMethod, TServerFnResponseType, undefined, undefined> {
105
- options: ServerFnBaseOptions<TMethod, TServerFnResponseType, unknown, undefined, undefined>;
106
- }
107
- type StaticCachedResult = {
108
- ctx?: {
109
- result: any;
110
- context: any;
111
- };
112
- error?: any;
113
- };
114
- export type ServerFnStaticCache = {
115
- getItem: (ctx: MiddlewareResult) => StaticCachedResult | Promise<StaticCachedResult | undefined>;
116
- setItem: (ctx: MiddlewareResult, response: StaticCachedResult) => Promise<void>;
117
- fetchItem: (ctx: MiddlewareResult) => StaticCachedResult | Promise<StaticCachedResult | undefined>;
118
- };
119
- export declare function setServerFnStaticCache(cache?: ServerFnStaticCache | (() => ServerFnStaticCache | undefined)): () => void;
120
- export declare function createServerFnStaticCache(serverFnStaticCache: ServerFnStaticCache): ServerFnStaticCache;
1
+ import { Method, ServerFnBaseOptions, ServerFnBuilder, ServerFnResponseType, ServerFnType } from '@tanstack/start-client-core';
121
2
  export declare function createServerFn<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType = 'data', TResponse = unknown, TMiddlewares = undefined, TValidator = undefined>(options?: {
122
3
  method?: TMethod;
123
4
  response?: TServerFnResponseType;
124
5
  type?: ServerFnType;
125
6
  }, __opts?: ServerFnBaseOptions<TMethod, TServerFnResponseType, TResponse, TMiddlewares, TValidator>): ServerFnBuilder<TMethod, TServerFnResponseType>;
126
- export type MiddlewareOptions = {
127
- method: Method;
128
- response?: ServerFnResponseType;
129
- data: any;
130
- headers?: HeadersInit;
131
- signal?: AbortSignal;
132
- sendContext?: any;
133
- context?: any;
134
- type: ServerFnTypeOrTypeFn<any, any, any, any>;
135
- functionId: string;
136
- };
137
- export type MiddlewareResult = MiddlewareOptions & {
138
- result?: unknown;
139
- error?: unknown;
140
- type: ServerFnTypeOrTypeFn<any, any, any, any>;
141
- };
142
- export type NextFn = (ctx: MiddlewareResult) => Promise<MiddlewareResult>;
143
- export type MiddlewareFn = (ctx: MiddlewareOptions & {
144
- next: NextFn;
145
- }) => Promise<MiddlewareResult>;
146
- export {};