@tanstack/start-client-core 1.121.16 → 1.121.17
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -2
- package/dist/cjs/createIsomorphicFn.cjs +0 -7
- package/dist/cjs/createIsomorphicFn.cjs.map +0 -1
- package/dist/cjs/createIsomorphicFn.d.cts +0 -12
- package/dist/cjs/createMiddleware.cjs +0 -37
- package/dist/cjs/createMiddleware.cjs.map +0 -1
- package/dist/cjs/createMiddleware.d.cts +0 -175
- package/dist/cjs/createServerFn.cjs +0 -378
- package/dist/cjs/createServerFn.cjs.map +0 -1
- package/dist/cjs/createServerFn.d.cts +0 -159
- package/dist/cjs/envOnly.cjs +0 -7
- package/dist/cjs/envOnly.cjs.map +0 -1
- package/dist/cjs/envOnly.d.cts +0 -4
- package/dist/cjs/headers.cjs +0 -30
- package/dist/cjs/headers.cjs.map +0 -1
- package/dist/cjs/headers.d.cts +0 -5
- package/dist/cjs/index.cjs +0 -33
- package/dist/cjs/index.cjs.map +0 -1
- package/dist/cjs/index.d.cts +0 -11
- package/dist/cjs/json.cjs +0 -14
- package/dist/cjs/json.cjs.map +0 -1
- package/dist/cjs/json.d.cts +0 -2
- package/dist/cjs/registerGlobalMiddleware.cjs +0 -9
- package/dist/cjs/registerGlobalMiddleware.cjs.map +0 -1
- package/dist/cjs/registerGlobalMiddleware.d.cts +0 -5
- package/dist/cjs/serializer.cjs +0 -152
- package/dist/cjs/serializer.cjs.map +0 -1
- package/dist/cjs/serializer.d.cts +0 -2
- package/dist/cjs/ssr-client.cjs +0 -131
- package/dist/cjs/ssr-client.cjs.map +0 -1
- package/dist/cjs/ssr-client.d.cts +0 -65
- package/dist/cjs/tests/createIsomorphicFn.test-d.d.cts +0 -1
- package/dist/cjs/tests/createServerFn.test-d.d.cts +0 -1
- package/dist/cjs/tests/createServerMiddleware.test-d.d.cts +0 -1
- package/dist/cjs/tests/envOnly.test-d.d.cts +0 -1
- package/dist/cjs/tests/json.test.d.cts +0 -1
- package/dist/cjs/tests/transformer.test.d.cts +0 -1
- package/dist/esm/createIsomorphicFn.d.ts +0 -12
- package/dist/esm/createIsomorphicFn.js +0 -7
- package/dist/esm/createIsomorphicFn.js.map +0 -1
- package/dist/esm/createMiddleware.d.ts +0 -175
- package/dist/esm/createMiddleware.js +0 -37
- package/dist/esm/createMiddleware.js.map +0 -1
- package/dist/esm/createServerFn.d.ts +0 -159
- package/dist/esm/createServerFn.js +0 -356
- package/dist/esm/createServerFn.js.map +0 -1
- package/dist/esm/envOnly.d.ts +0 -4
- package/dist/esm/envOnly.js +0 -7
- package/dist/esm/envOnly.js.map +0 -1
- package/dist/esm/headers.d.ts +0 -5
- package/dist/esm/headers.js +0 -30
- package/dist/esm/headers.js.map +0 -1
- package/dist/esm/index.d.ts +0 -11
- package/dist/esm/index.js +0 -30
- package/dist/esm/index.js.map +0 -1
- package/dist/esm/json.d.ts +0 -2
- package/dist/esm/json.js +0 -14
- package/dist/esm/json.js.map +0 -1
- package/dist/esm/registerGlobalMiddleware.d.ts +0 -5
- package/dist/esm/registerGlobalMiddleware.js +0 -9
- package/dist/esm/registerGlobalMiddleware.js.map +0 -1
- package/dist/esm/serializer.d.ts +0 -2
- package/dist/esm/serializer.js +0 -152
- package/dist/esm/serializer.js.map +0 -1
- package/dist/esm/ssr-client.d.ts +0 -65
- package/dist/esm/ssr-client.js +0 -131
- package/dist/esm/ssr-client.js.map +0 -1
- package/dist/esm/tests/createIsomorphicFn.test-d.d.ts +0 -1
- package/dist/esm/tests/createServerFn.test-d.d.ts +0 -1
- package/dist/esm/tests/createServerMiddleware.test-d.d.ts +0 -1
- package/dist/esm/tests/envOnly.test-d.d.ts +0 -1
- package/dist/esm/tests/json.test.d.ts +0 -1
- package/dist/esm/tests/transformer.test.d.ts +0 -1
|
@@ -1,378 +0,0 @@
|
|
|
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
|
-
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
25
|
-
const invariant = require("tiny-invariant");
|
|
26
|
-
const warning = require("tiny-warning");
|
|
27
|
-
const routerCore = require("@tanstack/router-core");
|
|
28
|
-
const serializer = require("./serializer.cjs");
|
|
29
|
-
const headers = require("./headers.cjs");
|
|
30
|
-
const registerGlobalMiddleware = require("./registerGlobalMiddleware.cjs");
|
|
31
|
-
function createServerFn(options, __opts) {
|
|
32
|
-
const resolvedOptions = __opts || options || {};
|
|
33
|
-
if (typeof resolvedOptions.method === "undefined") {
|
|
34
|
-
resolvedOptions.method = "GET";
|
|
35
|
-
}
|
|
36
|
-
return {
|
|
37
|
-
options: resolvedOptions,
|
|
38
|
-
middleware: (middleware) => {
|
|
39
|
-
return createServerFn(void 0, Object.assign(resolvedOptions, { middleware }));
|
|
40
|
-
},
|
|
41
|
-
validator: (validator) => {
|
|
42
|
-
return createServerFn(void 0, Object.assign(resolvedOptions, { validator }));
|
|
43
|
-
},
|
|
44
|
-
type: (type) => {
|
|
45
|
-
return createServerFn(void 0, Object.assign(resolvedOptions, { type }));
|
|
46
|
-
},
|
|
47
|
-
handler: (...args) => {
|
|
48
|
-
const [extractedFn, serverFn] = args;
|
|
49
|
-
Object.assign(resolvedOptions, {
|
|
50
|
-
...extractedFn,
|
|
51
|
-
extractedFn,
|
|
52
|
-
serverFn
|
|
53
|
-
});
|
|
54
|
-
const resolvedMiddleware = [
|
|
55
|
-
...resolvedOptions.middleware || [],
|
|
56
|
-
serverFnBaseToMiddleware(resolvedOptions)
|
|
57
|
-
];
|
|
58
|
-
return Object.assign(
|
|
59
|
-
async (opts) => {
|
|
60
|
-
return executeMiddleware(resolvedMiddleware, "client", {
|
|
61
|
-
...extractedFn,
|
|
62
|
-
...resolvedOptions,
|
|
63
|
-
data: opts == null ? void 0 : opts.data,
|
|
64
|
-
headers: opts == null ? void 0 : opts.headers,
|
|
65
|
-
signal: opts == null ? void 0 : opts.signal,
|
|
66
|
-
context: {}
|
|
67
|
-
}).then((d) => {
|
|
68
|
-
if (resolvedOptions.response === "full") {
|
|
69
|
-
return d;
|
|
70
|
-
}
|
|
71
|
-
if (d.error) throw d.error;
|
|
72
|
-
return d.result;
|
|
73
|
-
});
|
|
74
|
-
},
|
|
75
|
-
{
|
|
76
|
-
// This copies over the URL, function ID
|
|
77
|
-
...extractedFn,
|
|
78
|
-
// The extracted function on the server-side calls
|
|
79
|
-
// this function
|
|
80
|
-
__executeServer: async (opts_, signal) => {
|
|
81
|
-
var _a, _b;
|
|
82
|
-
const opts = opts_ instanceof FormData ? extractFormDataContext(opts_) : opts_;
|
|
83
|
-
opts.type = typeof resolvedOptions.type === "function" ? resolvedOptions.type(opts) : resolvedOptions.type;
|
|
84
|
-
const ctx = {
|
|
85
|
-
...extractedFn,
|
|
86
|
-
...opts,
|
|
87
|
-
signal
|
|
88
|
-
};
|
|
89
|
-
const run = () => executeMiddleware(resolvedMiddleware, "server", ctx).then(
|
|
90
|
-
(d) => ({
|
|
91
|
-
// Only send the result and sendContext back to the client
|
|
92
|
-
result: d.result,
|
|
93
|
-
error: d.error,
|
|
94
|
-
context: d.sendContext
|
|
95
|
-
})
|
|
96
|
-
);
|
|
97
|
-
if (ctx.type === "static") {
|
|
98
|
-
let response;
|
|
99
|
-
if ((_a = exports.serverFnStaticCache) == null ? void 0 : _a.getItem) {
|
|
100
|
-
response = await exports.serverFnStaticCache.getItem(ctx);
|
|
101
|
-
}
|
|
102
|
-
if (!response) {
|
|
103
|
-
response = await run().then((d) => {
|
|
104
|
-
return {
|
|
105
|
-
ctx: d,
|
|
106
|
-
error: null
|
|
107
|
-
};
|
|
108
|
-
}).catch((e) => {
|
|
109
|
-
return {
|
|
110
|
-
ctx: void 0,
|
|
111
|
-
error: e
|
|
112
|
-
};
|
|
113
|
-
});
|
|
114
|
-
if ((_b = exports.serverFnStaticCache) == null ? void 0 : _b.setItem) {
|
|
115
|
-
await exports.serverFnStaticCache.setItem(ctx, response);
|
|
116
|
-
}
|
|
117
|
-
}
|
|
118
|
-
invariant(
|
|
119
|
-
response,
|
|
120
|
-
"No response from both server and static cache!"
|
|
121
|
-
);
|
|
122
|
-
if (response.error) {
|
|
123
|
-
throw response.error;
|
|
124
|
-
}
|
|
125
|
-
return response.ctx;
|
|
126
|
-
}
|
|
127
|
-
return run();
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
);
|
|
131
|
-
}
|
|
132
|
-
};
|
|
133
|
-
}
|
|
134
|
-
async function executeMiddleware(middlewares, env, opts) {
|
|
135
|
-
const flattenedMiddlewares = flattenMiddlewares([
|
|
136
|
-
...registerGlobalMiddleware.globalMiddleware,
|
|
137
|
-
...middlewares
|
|
138
|
-
]);
|
|
139
|
-
const next = async (ctx) => {
|
|
140
|
-
const nextMiddleware = flattenedMiddlewares.shift();
|
|
141
|
-
if (!nextMiddleware) {
|
|
142
|
-
return ctx;
|
|
143
|
-
}
|
|
144
|
-
if (nextMiddleware.options.validator && (env === "client" ? nextMiddleware.options.validateClient : true)) {
|
|
145
|
-
ctx.data = await execValidator(nextMiddleware.options.validator, ctx.data);
|
|
146
|
-
}
|
|
147
|
-
const middlewareFn = env === "client" ? nextMiddleware.options.client : nextMiddleware.options.server;
|
|
148
|
-
if (middlewareFn) {
|
|
149
|
-
return applyMiddleware(middlewareFn, ctx, async (newCtx) => {
|
|
150
|
-
return next(newCtx).catch((error) => {
|
|
151
|
-
if (routerCore.isRedirect(error) || routerCore.isNotFound(error)) {
|
|
152
|
-
return {
|
|
153
|
-
...newCtx,
|
|
154
|
-
error
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
throw error;
|
|
158
|
-
});
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
return next(ctx);
|
|
162
|
-
};
|
|
163
|
-
return next({
|
|
164
|
-
...opts,
|
|
165
|
-
headers: opts.headers || {},
|
|
166
|
-
sendContext: opts.sendContext || {},
|
|
167
|
-
context: opts.context || {}
|
|
168
|
-
});
|
|
169
|
-
}
|
|
170
|
-
exports.serverFnStaticCache = void 0;
|
|
171
|
-
function setServerFnStaticCache(cache) {
|
|
172
|
-
const previousCache = exports.serverFnStaticCache;
|
|
173
|
-
exports.serverFnStaticCache = typeof cache === "function" ? cache() : cache;
|
|
174
|
-
return () => {
|
|
175
|
-
exports.serverFnStaticCache = previousCache;
|
|
176
|
-
};
|
|
177
|
-
}
|
|
178
|
-
function createServerFnStaticCache(serverFnStaticCache2) {
|
|
179
|
-
return serverFnStaticCache2;
|
|
180
|
-
}
|
|
181
|
-
async function sha1Hash(message) {
|
|
182
|
-
const msgBuffer = new TextEncoder().encode(message);
|
|
183
|
-
const hashBuffer = await crypto.subtle.digest("SHA-1", msgBuffer);
|
|
184
|
-
const hashArray = Array.from(new Uint8Array(hashBuffer));
|
|
185
|
-
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
186
|
-
return hashHex;
|
|
187
|
-
}
|
|
188
|
-
setServerFnStaticCache(() => {
|
|
189
|
-
const getStaticCacheUrl = async (options, hash) => {
|
|
190
|
-
const filename = await sha1Hash(`${options.functionId}__${hash}`);
|
|
191
|
-
return `/__tsr/staticServerFnCache/${filename}.json`;
|
|
192
|
-
};
|
|
193
|
-
const jsonToFilenameSafeString = (json) => {
|
|
194
|
-
const sortedKeysReplacer = (key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.keys(value).sort().reduce((acc, curr) => {
|
|
195
|
-
acc[curr] = value[curr];
|
|
196
|
-
return acc;
|
|
197
|
-
}, {}) : value;
|
|
198
|
-
const jsonString = JSON.stringify(json ?? "", sortedKeysReplacer);
|
|
199
|
-
return jsonString.replace(/[/\\?%*:|"<>]/g, "-").replace(/\s+/g, "_");
|
|
200
|
-
};
|
|
201
|
-
const staticClientCache = typeof document !== "undefined" ? /* @__PURE__ */ new Map() : null;
|
|
202
|
-
return createServerFnStaticCache({
|
|
203
|
-
getItem: async (ctx) => {
|
|
204
|
-
if (typeof document === "undefined") {
|
|
205
|
-
const hash = jsonToFilenameSafeString(ctx.data);
|
|
206
|
-
const url = await getStaticCacheUrl(ctx, hash);
|
|
207
|
-
const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR;
|
|
208
|
-
const { promises: fs } = await import("node:fs");
|
|
209
|
-
const path = await import("node:path");
|
|
210
|
-
const filePath = path.join(publicUrl, url);
|
|
211
|
-
const [cachedResult, readError] = await fs.readFile(filePath, "utf-8").then((c) => [
|
|
212
|
-
serializer.startSerializer.parse(c),
|
|
213
|
-
null
|
|
214
|
-
]).catch((e) => [null, e]);
|
|
215
|
-
if (readError && readError.code !== "ENOENT") {
|
|
216
|
-
throw readError;
|
|
217
|
-
}
|
|
218
|
-
return cachedResult;
|
|
219
|
-
}
|
|
220
|
-
return void 0;
|
|
221
|
-
},
|
|
222
|
-
setItem: async (ctx, response) => {
|
|
223
|
-
const { promises: fs } = await import("node:fs");
|
|
224
|
-
const path = await import("node:path");
|
|
225
|
-
const hash = jsonToFilenameSafeString(ctx.data);
|
|
226
|
-
const url = await getStaticCacheUrl(ctx, hash);
|
|
227
|
-
const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR;
|
|
228
|
-
const filePath = path.join(publicUrl, url);
|
|
229
|
-
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
230
|
-
await fs.writeFile(filePath, serializer.startSerializer.stringify(response));
|
|
231
|
-
},
|
|
232
|
-
fetchItem: async (ctx) => {
|
|
233
|
-
const hash = jsonToFilenameSafeString(ctx.data);
|
|
234
|
-
const url = await getStaticCacheUrl(ctx, hash);
|
|
235
|
-
let result = staticClientCache == null ? void 0 : staticClientCache.get(url);
|
|
236
|
-
if (!result) {
|
|
237
|
-
result = await fetch(url, {
|
|
238
|
-
method: "GET"
|
|
239
|
-
}).then((r) => r.text()).then((d) => serializer.startSerializer.parse(d));
|
|
240
|
-
staticClientCache == null ? void 0 : staticClientCache.set(url, result);
|
|
241
|
-
}
|
|
242
|
-
return result;
|
|
243
|
-
}
|
|
244
|
-
});
|
|
245
|
-
});
|
|
246
|
-
function extractFormDataContext(formData) {
|
|
247
|
-
const serializedContext = formData.get("__TSR_CONTEXT");
|
|
248
|
-
formData.delete("__TSR_CONTEXT");
|
|
249
|
-
if (typeof serializedContext !== "string") {
|
|
250
|
-
return {
|
|
251
|
-
context: {},
|
|
252
|
-
data: formData
|
|
253
|
-
};
|
|
254
|
-
}
|
|
255
|
-
try {
|
|
256
|
-
const context = serializer.startSerializer.parse(serializedContext);
|
|
257
|
-
return {
|
|
258
|
-
context,
|
|
259
|
-
data: formData
|
|
260
|
-
};
|
|
261
|
-
} catch {
|
|
262
|
-
return {
|
|
263
|
-
data: formData
|
|
264
|
-
};
|
|
265
|
-
}
|
|
266
|
-
}
|
|
267
|
-
function flattenMiddlewares(middlewares) {
|
|
268
|
-
const seen = /* @__PURE__ */ new Set();
|
|
269
|
-
const flattened = [];
|
|
270
|
-
const recurse = (middleware) => {
|
|
271
|
-
middleware.forEach((m) => {
|
|
272
|
-
if (m.options.middleware) {
|
|
273
|
-
recurse(m.options.middleware);
|
|
274
|
-
}
|
|
275
|
-
if (!seen.has(m)) {
|
|
276
|
-
seen.add(m);
|
|
277
|
-
flattened.push(m);
|
|
278
|
-
}
|
|
279
|
-
});
|
|
280
|
-
};
|
|
281
|
-
recurse(middlewares);
|
|
282
|
-
return flattened;
|
|
283
|
-
}
|
|
284
|
-
const applyMiddleware = async (middlewareFn, ctx, nextFn) => {
|
|
285
|
-
return middlewareFn({
|
|
286
|
-
...ctx,
|
|
287
|
-
next: async (userCtx = {}) => {
|
|
288
|
-
return nextFn({
|
|
289
|
-
...ctx,
|
|
290
|
-
...userCtx,
|
|
291
|
-
context: {
|
|
292
|
-
...ctx.context,
|
|
293
|
-
...userCtx.context
|
|
294
|
-
},
|
|
295
|
-
sendContext: {
|
|
296
|
-
...ctx.sendContext,
|
|
297
|
-
...userCtx.sendContext ?? {}
|
|
298
|
-
},
|
|
299
|
-
headers: headers.mergeHeaders(ctx.headers, userCtx.headers),
|
|
300
|
-
result: userCtx.result !== void 0 ? userCtx.result : ctx.response === "raw" ? userCtx : ctx.result,
|
|
301
|
-
error: userCtx.error ?? ctx.error
|
|
302
|
-
});
|
|
303
|
-
}
|
|
304
|
-
});
|
|
305
|
-
};
|
|
306
|
-
function execValidator(validator, input) {
|
|
307
|
-
if (validator == null) return {};
|
|
308
|
-
if ("~standard" in validator) {
|
|
309
|
-
const result = validator["~standard"].validate(input);
|
|
310
|
-
if (result instanceof Promise)
|
|
311
|
-
throw new Error("Async validation not supported");
|
|
312
|
-
if (result.issues)
|
|
313
|
-
throw new Error(JSON.stringify(result.issues, void 0, 2));
|
|
314
|
-
return result.value;
|
|
315
|
-
}
|
|
316
|
-
if ("parse" in validator) {
|
|
317
|
-
return validator.parse(input);
|
|
318
|
-
}
|
|
319
|
-
if (typeof validator === "function") {
|
|
320
|
-
return validator(input);
|
|
321
|
-
}
|
|
322
|
-
throw new Error("Invalid validator type!");
|
|
323
|
-
}
|
|
324
|
-
function serverFnBaseToMiddleware(options) {
|
|
325
|
-
return {
|
|
326
|
-
_types: void 0,
|
|
327
|
-
options: {
|
|
328
|
-
validator: options.validator,
|
|
329
|
-
validateClient: options.validateClient,
|
|
330
|
-
client: async ({ next, sendContext, ...ctx }) => {
|
|
331
|
-
var _a;
|
|
332
|
-
const payload = {
|
|
333
|
-
...ctx,
|
|
334
|
-
// switch the sendContext over to context
|
|
335
|
-
context: sendContext,
|
|
336
|
-
type: typeof ctx.type === "function" ? ctx.type(ctx) : ctx.type
|
|
337
|
-
};
|
|
338
|
-
if (ctx.type === "static" && process.env.NODE_ENV === "production" && typeof document !== "undefined") {
|
|
339
|
-
invariant(
|
|
340
|
-
exports.serverFnStaticCache,
|
|
341
|
-
"serverFnStaticCache.fetchItem is not available!"
|
|
342
|
-
);
|
|
343
|
-
const result = await exports.serverFnStaticCache.fetchItem(payload);
|
|
344
|
-
if (result) {
|
|
345
|
-
if (result.error) {
|
|
346
|
-
throw result.error;
|
|
347
|
-
}
|
|
348
|
-
return next(result.ctx);
|
|
349
|
-
}
|
|
350
|
-
warning(
|
|
351
|
-
result,
|
|
352
|
-
`No static cache item found for ${payload.functionId}__${JSON.stringify(payload.data)}, falling back to server function...`
|
|
353
|
-
);
|
|
354
|
-
}
|
|
355
|
-
const res = await ((_a = options.extractedFn) == null ? void 0 : _a.call(options, payload));
|
|
356
|
-
return next(res);
|
|
357
|
-
},
|
|
358
|
-
server: async ({ next, ...ctx }) => {
|
|
359
|
-
var _a;
|
|
360
|
-
const result = await ((_a = options.serverFn) == null ? void 0 : _a.call(options, ctx));
|
|
361
|
-
return next({
|
|
362
|
-
...ctx,
|
|
363
|
-
result
|
|
364
|
-
});
|
|
365
|
-
}
|
|
366
|
-
}
|
|
367
|
-
};
|
|
368
|
-
}
|
|
369
|
-
exports.applyMiddleware = applyMiddleware;
|
|
370
|
-
exports.createServerFn = createServerFn;
|
|
371
|
-
exports.createServerFnStaticCache = createServerFnStaticCache;
|
|
372
|
-
exports.execValidator = execValidator;
|
|
373
|
-
exports.executeMiddleware = executeMiddleware;
|
|
374
|
-
exports.extractFormDataContext = extractFormDataContext;
|
|
375
|
-
exports.flattenMiddlewares = flattenMiddlewares;
|
|
376
|
-
exports.serverFnBaseToMiddleware = serverFnBaseToMiddleware;
|
|
377
|
-
exports.setServerFnStaticCache = setServerFnStaticCache;
|
|
378
|
-
//# sourceMappingURL=createServerFn.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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/router-core'\nimport { startSerializer } from './serializer'\nimport { mergeHeaders } from './headers'\nimport { globalMiddleware } from './registerGlobalMiddleware'\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 { Readable } from 'node:stream'\nimport type {\n AnyFunctionMiddleware,\n AssignAllClientSendContext,\n AssignAllServerContext,\n FunctionMiddlewareClientFnResult,\n FunctionMiddlewareServerFnResult,\n IntersectAllValidatorInputs,\n IntersectAllValidatorOutputs,\n} from './createMiddleware'\n\ntype TODO = any\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\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\nexport async function executeMiddleware(\n middlewares: Array<AnyFunctionMiddleware>,\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 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\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>\n\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\nexport type 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<AnyFunctionMiddleware>>\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 ValidatorInputStringify<TValidator> = SerializerStringifyBy<\n ResolveValidatorInput<TValidator>,\n Date | undefined | FormData\n>\n\nexport type ValidatorSerializerStringify<TValidator> =\n ValidatorInputStringify<TValidator> extends infer TInput\n ? Validator<TInput, any>\n : never\n\nexport type ConstrainValidator<TValidator> =\n | (unknown extends TValidator\n ? TValidator\n : ResolveValidatorInput<TValidator> extends ValidatorInputStringify<TValidator>\n ? TValidator\n : never)\n | 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<\n TNewMiddlewares,\n ReadonlyArray<AnyFunctionMiddleware>\n >,\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\nexport type StaticCachedResult = {\n ctx?: {\n result: any\n context: any\n }\n error?: any\n}\n\nexport type ServerFnStaticCache = {\n getItem: (\n ctx: ServerFnMiddlewareResult,\n ) => StaticCachedResult | Promise<StaticCachedResult | undefined>\n setItem: (\n ctx: ServerFnMiddlewareResult,\n response: StaticCachedResult,\n ) => Promise<void>\n fetchItem: (\n ctx: ServerFnMiddlewareResult,\n ) => StaticCachedResult | Promise<StaticCachedResult | undefined>\n}\n\nexport let 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\n/**\n * This is a simple hash function for generating a hash from a string to make the filenames shorter.\n *\n * It is not cryptographically secure (as its using SHA-1) and should not be used for any security purposes.\n *\n * It is only used to generate a hash for the static cache filenames.\n *\n * @param message - The input string to hash.\n * @returns A promise that resolves to the SHA-1 hash of the input string in hexadecimal format.\n *\n * @example\n * ```typescript\n * const hash = await sha1Hash(\"hello\");\n * console.log(hash); // Outputs the SHA-1 hash of \"hello\" -> \"aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d\"\n * ```\n */\nasync function sha1Hash(message: string): Promise<string> {\n // Encode the string as UTF-8\n const msgBuffer = new TextEncoder().encode(message)\n\n // Hash the message\n const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer)\n\n // Convert the ArrayBuffer to a string\n const hashArray = Array.from(new Uint8Array(hashBuffer))\n const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')\n return hashHex\n}\n\nsetServerFnStaticCache(() => {\n const getStaticCacheUrl = async (\n options: ServerFnMiddlewareResult,\n hash: string,\n ) => {\n const filename = await sha1Hash(`${options.functionId}__${hash}`)\n return `/__tsr/staticServerFnCache/${filename}.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 = await 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 = await 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 = await 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 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\nexport function flattenMiddlewares(\n middlewares: Array<AnyFunctionMiddleware>,\n): Array<AnyFunctionMiddleware> {\n const seen = new Set<AnyFunctionMiddleware>()\n const flattened: Array<AnyFunctionMiddleware> = []\n\n const recurse = (middleware: Array<AnyFunctionMiddleware>) => {\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 ServerFnMiddlewareOptions = {\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 ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {\n result?: unknown\n error?: unknown\n type: ServerFnTypeOrTypeFn<any, any, any, any>\n}\n\nexport type NextFn = (\n ctx: ServerFnMiddlewareResult,\n) => Promise<ServerFnMiddlewareResult>\n\nexport type MiddlewareFn = (\n ctx: ServerFnMiddlewareOptions & {\n next: NextFn\n },\n) => Promise<ServerFnMiddlewareResult>\n\nexport const applyMiddleware = async (\n middlewareFn: MiddlewareFn,\n ctx: ServerFnMiddlewareOptions,\n nextFn: NextFn,\n) => {\n return middlewareFn({\n ...ctx,\n next: (async (\n userCtx: ServerFnMiddlewareResult | undefined = {} as any,\n ) => {\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\nexport function execValidator(\n validator: AnyValidator,\n input: unknown,\n): 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\nexport function serverFnBaseToMiddleware(\n options: ServerFnBaseOptions<any, any, any, any, any>,\n): AnyFunctionMiddleware {\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 FunctionMiddlewareClientFnResult<\n any,\n any,\n any\n >\n },\n server: async ({ next, ...ctx }) => {\n // Execute the server function\n const result = await options.serverFn?.(ctx as TODO)\n\n return next({\n ...ctx,\n result,\n } as any) as unknown as FunctionMiddlewareServerFnResult<\n any,\n any,\n any,\n any\n >\n },\n },\n }\n}\n"],"names":["serverFnStaticCache","globalMiddleware","isRedirect","isNotFound","startSerializer","mergeHeaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BgB,SAAA,eAOd,SAKA,QAOiD;AAC3C,QAAA,kBAAmB,UAAU,WAAW,CAAC;AAQ3C,MAAA,OAAO,gBAAgB,WAAW,aAAa;AACjD,oBAAgB,SAAS;AAAA,EAAA;AAGpB,SAAA;AAAA,IACL,SAAS;AAAA,IACT,YAAY,CAAC,eAAe;AACnB,aAAA,eAML,QAAW,OAAO,OAAO,iBAAiB,EAAE,WAAA,CAAY,CAAC;AAAA,IAC7D;AAAA,IACA,WAAW,CAAC,cAAc;AACjB,aAAA,eAML,QAA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AAAA,EAAA;AAGlB,QAAA,IAAI,MAAM,yBAAyB;AAC3C;AAEO,SAAS,yBACd,SACuB;AAChB,SAAA;AAAA,IACL,QAAQ;AAAA,IACR,SAAS;AAAA,MACP,WAAW,QAAQ;AAAA,MACnB,gBAAgB,QAAQ;AAAA,MACxB,QAAQ,OAAO,EAAE,MAAM,aAAa,GAAG,UAAU;;AAC/C,cAAM,UAAU;AAAA,UACd,GAAG;AAAA;AAAA,UAEH,SAAS;AAAA,UACT,MAAM,OAAO,IAAI,SAAS,aAAa,IAAI,KAAK,GAAG,IAAI,IAAI;AAAA,QAC7D;AAGE,YAAA,IAAI,SAAS,YACb,QAAQ,IAAI,aAAa,gBACzB,OAAO,aAAa,aACpB;AACA;AAAA,YACEL,QAAA;AAAA,YACA;AAAA,UACF;AAEA,gBAAM,SAAS,MAAMA,4BAAoB,UAAU,OAAO;AAE1D,cAAI,QAAQ;AACV,gBAAI,OAAO,OAAO;AAChB,oBAAM,OAAO;AAAA,YAAA;AAGR,mBAAA,KAAK,OAAO,GAAG;AAAA,UAAA;AAGxB;AAAA,YACE;AAAA,YACA,kCAAkC,QAAQ,UAAU,KAAK,KAAK,UAAU,QAAQ,IAAI,CAAC;AAAA,UACvF;AAAA,QAAA;AAKF,cAAM,MAAM,QAAM,aAAQ,gBAAR,iCAAsB;AAExC,eAAO,KAAK,GAAG;AAAA,MAKjB;AAAA,MACA,QAAQ,OAAO,EAAE,MAAM,GAAG,UAAU;;AAElC,cAAM,SAAS,QAAM,aAAQ,aAAR,iCAAmB;AAExC,eAAO,KAAK;AAAA,UACV,GAAG;AAAA,UACH;AAAA,QAAA,CACM;AAAA,MAAA;AAAA,IAMV;AAAA,EAEJ;AACF;;;;;;;;;;"}
|
|
@@ -1,159 +0,0 @@
|
|
|
1
|
-
import { AnyValidator, Constrain, Expand, ResolveValidatorInput, SerializerParse, SerializerStringify, SerializerStringifyBy, Validator } from '@tanstack/router-core';
|
|
2
|
-
import { Readable } from 'node:stream';
|
|
3
|
-
import { AnyFunctionMiddleware, AssignAllClientSendContext, AssignAllServerContext, IntersectAllValidatorInputs, IntersectAllValidatorOutputs } from './createMiddleware.cjs';
|
|
4
|
-
export declare function createServerFn<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType = 'data', TResponse = unknown, TMiddlewares = undefined, TValidator = undefined>(options?: {
|
|
5
|
-
method?: TMethod;
|
|
6
|
-
response?: TServerFnResponseType;
|
|
7
|
-
type?: ServerFnType;
|
|
8
|
-
}, __opts?: ServerFnBaseOptions<TMethod, TServerFnResponseType, TResponse, TMiddlewares, TValidator>): ServerFnBuilder<TMethod, TServerFnResponseType>;
|
|
9
|
-
export declare function executeMiddleware(middlewares: Array<AnyFunctionMiddleware>, env: 'client' | 'server', opts: ServerFnMiddlewareOptions): Promise<ServerFnMiddlewareResult>;
|
|
10
|
-
export interface JsonResponse<TData> extends Response {
|
|
11
|
-
json: () => Promise<TData>;
|
|
12
|
-
}
|
|
13
|
-
export type CompiledFetcherFnOptions = {
|
|
14
|
-
method: Method;
|
|
15
|
-
data: unknown;
|
|
16
|
-
response?: ServerFnResponseType;
|
|
17
|
-
headers?: HeadersInit;
|
|
18
|
-
signal?: AbortSignal;
|
|
19
|
-
context?: any;
|
|
20
|
-
};
|
|
21
|
-
export type Fetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType extends ServerFnResponseType> = undefined extends IntersectAllValidatorInputs<TMiddlewares, TValidator> ? OptionalFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType> : RequiredFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType>;
|
|
22
|
-
export interface FetcherBase {
|
|
23
|
-
url: string;
|
|
24
|
-
__executeServer: (opts: {
|
|
25
|
-
method: Method;
|
|
26
|
-
response?: ServerFnResponseType;
|
|
27
|
-
data: unknown;
|
|
28
|
-
headers?: HeadersInit;
|
|
29
|
-
context?: any;
|
|
30
|
-
signal: AbortSignal;
|
|
31
|
-
}) => Promise<unknown>;
|
|
32
|
-
}
|
|
33
|
-
export type FetchResult<TMiddlewares, TResponse, TServerFnResponseType extends ServerFnResponseType> = TServerFnResponseType extends 'raw' ? Promise<Response> : TServerFnResponseType extends 'full' ? Promise<FullFetcherData<TMiddlewares, TResponse>> : Promise<FetcherData<TResponse>>;
|
|
34
|
-
export interface OptionalFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType extends ServerFnResponseType> extends FetcherBase {
|
|
35
|
-
(options?: OptionalFetcherDataOptions<TMiddlewares, TValidator>): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>;
|
|
36
|
-
}
|
|
37
|
-
export interface RequiredFetcher<TMiddlewares, TValidator, TResponse, TServerFnResponseType extends ServerFnResponseType> extends FetcherBase {
|
|
38
|
-
(opts: RequiredFetcherDataOptions<TMiddlewares, TValidator>): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>;
|
|
39
|
-
}
|
|
40
|
-
export type FetcherBaseOptions = {
|
|
41
|
-
headers?: HeadersInit;
|
|
42
|
-
type?: ServerFnType;
|
|
43
|
-
signal?: AbortSignal;
|
|
44
|
-
};
|
|
45
|
-
export type ServerFnType = 'static' | 'dynamic';
|
|
46
|
-
export interface OptionalFetcherDataOptions<TMiddlewares, TValidator> extends FetcherBaseOptions {
|
|
47
|
-
data?: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>;
|
|
48
|
-
}
|
|
49
|
-
export interface RequiredFetcherDataOptions<TMiddlewares, TValidator> extends FetcherBaseOptions {
|
|
50
|
-
data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>;
|
|
51
|
-
}
|
|
52
|
-
export interface FullFetcherData<TMiddlewares, TResponse> {
|
|
53
|
-
error: unknown;
|
|
54
|
-
result: FetcherData<TResponse>;
|
|
55
|
-
context: AssignAllClientSendContext<TMiddlewares>;
|
|
56
|
-
}
|
|
57
|
-
export type FetcherData<TResponse> = TResponse extends JsonResponse<any> ? SerializerParse<ReturnType<TResponse['json']>> : SerializerParse<TResponse>;
|
|
58
|
-
export type RscStream<T> = {
|
|
59
|
-
__cacheState: T;
|
|
60
|
-
};
|
|
61
|
-
export type Method = 'GET' | 'POST';
|
|
62
|
-
export type ServerFnResponseType = 'data' | 'full' | 'raw';
|
|
63
|
-
export type RawResponse = Response | ReadableStream | Readable | null | string;
|
|
64
|
-
export type ServerFnReturnType<TServerFnResponseType extends ServerFnResponseType, TResponse> = TServerFnResponseType extends 'raw' ? RawResponse | Promise<RawResponse> : Promise<SerializerStringify<TResponse>> | SerializerStringify<TResponse>;
|
|
65
|
-
export type ServerFn<TMethod, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator, TResponse> = (ctx: ServerFnCtx<TMethod, TServerFnResponseType, TMiddlewares, TValidator>) => ServerFnReturnType<TServerFnResponseType, TResponse>;
|
|
66
|
-
export interface ServerFnCtx<TMethod, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> {
|
|
67
|
-
method: TMethod;
|
|
68
|
-
response: TServerFnResponseType;
|
|
69
|
-
data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>;
|
|
70
|
-
context: Expand<AssignAllServerContext<TMiddlewares>>;
|
|
71
|
-
signal: AbortSignal;
|
|
72
|
-
}
|
|
73
|
-
export type CompiledFetcherFn<TResponse, TServerFnResponseType extends ServerFnResponseType> = {
|
|
74
|
-
(opts: CompiledFetcherFnOptions & ServerFnBaseOptions<Method, TServerFnResponseType>): Promise<TResponse>;
|
|
75
|
-
url: string;
|
|
76
|
-
};
|
|
77
|
-
export type ServerFnBaseOptions<TMethod extends Method = 'GET', TServerFnResponseType extends ServerFnResponseType = 'data', TResponse = unknown, TMiddlewares = unknown, TInput = unknown> = {
|
|
78
|
-
method: TMethod;
|
|
79
|
-
response?: TServerFnResponseType;
|
|
80
|
-
validateClient?: boolean;
|
|
81
|
-
middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyFunctionMiddleware>>;
|
|
82
|
-
validator?: ConstrainValidator<TInput>;
|
|
83
|
-
extractedFn?: CompiledFetcherFn<TResponse, TServerFnResponseType>;
|
|
84
|
-
serverFn?: ServerFn<TMethod, TServerFnResponseType, TMiddlewares, TInput, TResponse>;
|
|
85
|
-
functionId: string;
|
|
86
|
-
type: ServerFnTypeOrTypeFn<TMethod, TServerFnResponseType, TMiddlewares, AnyValidator>;
|
|
87
|
-
};
|
|
88
|
-
export type ValidatorInputStringify<TValidator> = SerializerStringifyBy<ResolveValidatorInput<TValidator>, Date | undefined | FormData>;
|
|
89
|
-
export type ValidatorSerializerStringify<TValidator> = ValidatorInputStringify<TValidator> extends infer TInput ? Validator<TInput, any> : never;
|
|
90
|
-
export type ConstrainValidator<TValidator> = (unknown extends TValidator ? TValidator : ResolveValidatorInput<TValidator> extends ValidatorInputStringify<TValidator> ? TValidator : never) | ValidatorSerializerStringify<TValidator>;
|
|
91
|
-
export interface ServerFnMiddleware<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TValidator> {
|
|
92
|
-
middleware: <const TNewMiddlewares = undefined>(middlewares: Constrain<TNewMiddlewares, ReadonlyArray<AnyFunctionMiddleware>>) => ServerFnAfterMiddleware<TMethod, TServerFnResponseType, TNewMiddlewares, TValidator>;
|
|
93
|
-
}
|
|
94
|
-
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> {
|
|
95
|
-
}
|
|
96
|
-
export type ValidatorFn<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares> = <TValidator>(validator: ConstrainValidator<TValidator>) => ServerFnAfterValidator<TMethod, TServerFnResponseType, TMiddlewares, TValidator>;
|
|
97
|
-
export interface ServerFnValidator<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares> {
|
|
98
|
-
validator: ValidatorFn<TMethod, TServerFnResponseType, TMiddlewares>;
|
|
99
|
-
}
|
|
100
|
-
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> {
|
|
101
|
-
}
|
|
102
|
-
export interface ServerFnTyper<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> {
|
|
103
|
-
type: (typer: ServerFnTypeOrTypeFn<TMethod, TServerFnResponseType, TMiddlewares, TValidator>) => ServerFnAfterTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>;
|
|
104
|
-
}
|
|
105
|
-
export type ServerFnTypeOrTypeFn<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> = ServerFnType | ((ctx: ServerFnCtx<TMethod, TServerFnResponseType, TMiddlewares, TValidator>) => ServerFnType);
|
|
106
|
-
export interface ServerFnAfterTyper<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> extends ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {
|
|
107
|
-
}
|
|
108
|
-
export interface ServerFnHandler<TMethod extends Method, TServerFnResponseType extends ServerFnResponseType, TMiddlewares, TValidator> {
|
|
109
|
-
handler: <TNewResponse>(fn?: ServerFn<TMethod, TServerFnResponseType, TMiddlewares, TValidator, TNewResponse>) => Fetcher<TMiddlewares, TValidator, TNewResponse, TServerFnResponseType>;
|
|
110
|
-
}
|
|
111
|
-
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> {
|
|
112
|
-
options: ServerFnBaseOptions<TMethod, TServerFnResponseType, unknown, undefined, undefined>;
|
|
113
|
-
}
|
|
114
|
-
export type StaticCachedResult = {
|
|
115
|
-
ctx?: {
|
|
116
|
-
result: any;
|
|
117
|
-
context: any;
|
|
118
|
-
};
|
|
119
|
-
error?: any;
|
|
120
|
-
};
|
|
121
|
-
export type ServerFnStaticCache = {
|
|
122
|
-
getItem: (ctx: ServerFnMiddlewareResult) => StaticCachedResult | Promise<StaticCachedResult | undefined>;
|
|
123
|
-
setItem: (ctx: ServerFnMiddlewareResult, response: StaticCachedResult) => Promise<void>;
|
|
124
|
-
fetchItem: (ctx: ServerFnMiddlewareResult) => StaticCachedResult | Promise<StaticCachedResult | undefined>;
|
|
125
|
-
};
|
|
126
|
-
export declare let serverFnStaticCache: ServerFnStaticCache | undefined;
|
|
127
|
-
export declare function setServerFnStaticCache(cache?: ServerFnStaticCache | (() => ServerFnStaticCache | undefined)): () => void;
|
|
128
|
-
export declare function createServerFnStaticCache(serverFnStaticCache: ServerFnStaticCache): ServerFnStaticCache;
|
|
129
|
-
export declare function extractFormDataContext(formData: FormData): {
|
|
130
|
-
context: unknown;
|
|
131
|
-
data: FormData;
|
|
132
|
-
} | {
|
|
133
|
-
data: FormData;
|
|
134
|
-
context?: undefined;
|
|
135
|
-
};
|
|
136
|
-
export declare function flattenMiddlewares(middlewares: Array<AnyFunctionMiddleware>): Array<AnyFunctionMiddleware>;
|
|
137
|
-
export type ServerFnMiddlewareOptions = {
|
|
138
|
-
method: Method;
|
|
139
|
-
response?: ServerFnResponseType;
|
|
140
|
-
data: any;
|
|
141
|
-
headers?: HeadersInit;
|
|
142
|
-
signal?: AbortSignal;
|
|
143
|
-
sendContext?: any;
|
|
144
|
-
context?: any;
|
|
145
|
-
type: ServerFnTypeOrTypeFn<any, any, any, any>;
|
|
146
|
-
functionId: string;
|
|
147
|
-
};
|
|
148
|
-
export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {
|
|
149
|
-
result?: unknown;
|
|
150
|
-
error?: unknown;
|
|
151
|
-
type: ServerFnTypeOrTypeFn<any, any, any, any>;
|
|
152
|
-
};
|
|
153
|
-
export type NextFn = (ctx: ServerFnMiddlewareResult) => Promise<ServerFnMiddlewareResult>;
|
|
154
|
-
export type MiddlewareFn = (ctx: ServerFnMiddlewareOptions & {
|
|
155
|
-
next: NextFn;
|
|
156
|
-
}) => Promise<ServerFnMiddlewareResult>;
|
|
157
|
-
export declare const applyMiddleware: (middlewareFn: MiddlewareFn, ctx: ServerFnMiddlewareOptions, nextFn: NextFn) => Promise<ServerFnMiddlewareResult>;
|
|
158
|
-
export declare function execValidator(validator: AnyValidator, input: unknown): unknown;
|
|
159
|
-
export declare function serverFnBaseToMiddleware(options: ServerFnBaseOptions<any, any, any, any, any>): AnyFunctionMiddleware;
|
package/dist/cjs/envOnly.cjs
DELETED
package/dist/cjs/envOnly.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"envOnly.cjs","sources":["../../src/envOnly.ts"],"sourcesContent":["type EnvOnlyFn = <TFn extends (...args: Array<any>) => any>(fn: TFn) => TFn\n\n// A function that will only be available in the server build\n// If called on the client, it will throw an error\nexport const serverOnly: EnvOnlyFn = (fn) => fn\n\n// A function that will only be available in the client build\n// If called on the server, it will throw an error\nexport const clientOnly: EnvOnlyFn = (fn) => fn\n"],"names":[],"mappings":";;AAIa,MAAA,aAAwB,CAAC,OAAO;AAIhC,MAAA,aAAwB,CAAC,OAAO;;;"}
|
package/dist/cjs/envOnly.d.cts
DELETED