@tanstack/start-client-core 1.128.7 → 1.129.0
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/dist/cjs/createIsomorphicFn.cjs +6 -1
- package/dist/cjs/createIsomorphicFn.cjs.map +1 -1
- package/dist/cjs/createMiddleware.cjs.map +1 -1
- package/dist/cjs/createMiddleware.d.cts +6 -5
- package/dist/cjs/createServerFn.cjs +8 -1
- package/dist/cjs/createServerFn.cjs.map +1 -1
- package/dist/cjs/createServerFn.d.cts +2 -1
- package/dist/esm/createIsomorphicFn.js +6 -1
- package/dist/esm/createIsomorphicFn.js.map +1 -1
- package/dist/esm/createMiddleware.d.ts +6 -5
- package/dist/esm/createMiddleware.js.map +1 -1
- package/dist/esm/createServerFn.d.ts +2 -1
- package/dist/esm/createServerFn.js +8 -1
- package/dist/esm/createServerFn.js.map +1 -1
- package/package.json +3 -2
- package/src/createIsomorphicFn.ts +6 -1
- package/src/createMiddleware.ts +10 -2
- package/src/createServerFn.ts +11 -0
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
3
|
function createIsomorphicFn() {
|
|
4
|
-
return
|
|
4
|
+
return {
|
|
5
|
+
server: () => ({ client: () => () => {
|
|
6
|
+
} }),
|
|
7
|
+
client: () => ({ server: () => () => {
|
|
8
|
+
} })
|
|
9
|
+
};
|
|
5
10
|
}
|
|
6
11
|
exports.createIsomorphicFn = createIsomorphicFn;
|
|
7
12
|
//# sourceMappingURL=createIsomorphicFn.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createIsomorphicFn.cjs","sources":["../../src/createIsomorphicFn.ts"],"sourcesContent":["// a function that can have different implementations on the client and server.\n// implementations not provided will default to a no-op function.\n\nexport type IsomorphicFn<\n TArgs extends Array<any> = [],\n TServer = undefined,\n TClient = undefined,\n> = (...args: TArgs) => TServer | TClient\n\nexport interface ServerOnlyFn<TArgs extends Array<any>, TServer>\n extends IsomorphicFn<TArgs, TServer> {\n client: <TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface ClientOnlyFn<TArgs extends Array<any>, TClient>\n extends IsomorphicFn<TArgs, undefined, TClient> {\n server: <TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface IsomorphicFnBase extends IsomorphicFn {\n server: <TArgs extends Array<any>, TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => ServerOnlyFn<TArgs, TServer>\n client: <TArgs extends Array<any>, TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => ClientOnlyFn<TArgs, TClient>\n}\n\n// this is a dummy function, it will be replaced by the transformer\nexport function createIsomorphicFn(): IsomorphicFnBase {\n return
|
|
1
|
+
{"version":3,"file":"createIsomorphicFn.cjs","sources":["../../src/createIsomorphicFn.ts"],"sourcesContent":["// a function that can have different implementations on the client and server.\n// implementations not provided will default to a no-op function.\n\nexport type IsomorphicFn<\n TArgs extends Array<any> = [],\n TServer = undefined,\n TClient = undefined,\n> = (...args: TArgs) => TServer | TClient\n\nexport interface ServerOnlyFn<TArgs extends Array<any>, TServer>\n extends IsomorphicFn<TArgs, TServer> {\n client: <TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface ClientOnlyFn<TArgs extends Array<any>, TClient>\n extends IsomorphicFn<TArgs, undefined, TClient> {\n server: <TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface IsomorphicFnBase extends IsomorphicFn {\n server: <TArgs extends Array<any>, TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => ServerOnlyFn<TArgs, TServer>\n client: <TArgs extends Array<any>, TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => ClientOnlyFn<TArgs, TClient>\n}\n\n// this is a dummy function, it will be replaced by the transformer\n// if we use `createIsomorphicFn` in this library itself, vite tries to execute it before the transformer runs\n// therefore we must return a dummy function that allows calling `server` and `client` method chains.\nexport function createIsomorphicFn(): IsomorphicFnBase {\n return {\n server: () => ({ client: () => () => {} }),\n client: () => ({ server: () => () => {} }),\n } as any\n}\n"],"names":[],"mappings":";;AAmCO,SAAS,qBAAuC;AAC9C,SAAA;AAAA,IACL,QAAQ,OAAO,EAAE,QAAQ,MAAM,MAAM;AAAA,IAAA;IACrC,QAAQ,OAAO,EAAE,QAAQ,MAAM,MAAM;AAAA,IAAA,EAAG;AAAA,EAC1C;AACF;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createMiddleware.cjs","sources":["../../src/createMiddleware.ts"],"sourcesContent":["import type {\n ConstrainValidator,\n Method,\n ServerFnResponseType,\n ServerFnTypeOrTypeFn,\n} from './createServerFn'\nimport type {\n Assign,\n Constrain,\n Expand,\n IntersectAssign,\n ResolveValidatorInput,\n ResolveValidatorOutput,\n} from '@tanstack/router-core'\nimport type { SerializerStringify } from './serializer'\n\nexport function createMiddleware<TType extends MiddlewareType>(\n options: {\n type: TType\n validateClient?: boolean\n },\n __opts?: FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n): CreateMiddlewareResult<TType> {\n // const resolvedOptions = (__opts || options) as MiddlewareOptions<\n const resolvedOptions = {\n type: 'function',\n ...(__opts ||\n (options as FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >)),\n }\n\n return {\n options: resolvedOptions,\n middleware: (middleware: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { middleware }),\n ) as any\n },\n validator: (validator: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { validator }),\n ) as any\n },\n client: (client: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { client }),\n ) as any\n },\n server: (server: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { server }),\n ) as any\n },\n } as unknown as CreateMiddlewareResult<TType>\n}\n\nexport type MiddlewareType = 'request' | 'function'\n\nexport type CreateMiddlewareResult<TType extends MiddlewareType> =\n 'function' extends TType\n ? FunctionMiddleware<ServerFnResponseType>\n : RequestMiddleware\n\nexport interface FunctionMiddleware<\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareAfterMiddleware<unknown, TServerFnResponseType> {\n middleware: <const TNewMiddlewares = undefined>(\n middlewares: Constrain<\n TNewMiddlewares,\n ReadonlyArray<AnyFunctionMiddleware>\n >,\n ) => FunctionMiddlewareAfterMiddleware<TNewMiddlewares, TServerFnResponseType>\n}\n\nexport interface FunctionMiddlewareAfterMiddleware<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, undefined, TServerFnResponseType>,\n FunctionMiddlewareValidator<TMiddlewares, TServerFnResponseType> {}\n\nexport interface FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n _types: FunctionMiddlewareTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext\n >\n options: FunctionMiddlewareOptions<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareTypes<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TServerSendContext,\n in out TClientContext,\n in out TClientSendContext,\n> {\n type: 'function'\n middlewares: TMiddlewares\n input: ResolveValidatorInput<TValidator>\n allInput: IntersectAllValidatorInputs<TMiddlewares, TValidator>\n output: ResolveValidatorOutput<TValidator>\n allOutput: IntersectAllValidatorOutputs<TMiddlewares, TValidator>\n clientContext: TClientContext\n allClientContextBeforeNext: AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext\n >\n allClientContextAfterNext: AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext,\n TClientSendContext\n >\n serverContext: TServerContext\n serverSendContext: TServerSendContext\n allServerSendContext: AssignAllServerSendContext<\n TMiddlewares,\n TServerSendContext\n >\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext\n >\n clientSendContext: TClientSendContext\n allClientSendContext: AssignAllClientSendContext<\n TMiddlewares,\n TClientSendContext\n >\n validator: TValidator\n}\n\n/**\n * Recursively resolve the input type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorInputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allInput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allInput'>,\n ResolveValidatorInput<TValidator>\n >\n\nexport type IntersectAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? IntersectAllMiddleware<\n TRest,\n TType,\n IntersectAssign<\n TAcc,\n TMiddleware['_types'][TType & keyof TMiddleware['_types']]\n >\n >\n : TAcc\n : TAcc\n\nexport type AnyFunctionMiddleware = FunctionMiddlewareWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\n/**\n * Recursively merge the output type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorOutputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allOutput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allOutput'>,\n ResolveValidatorOutput<TValidator>\n >\n\n/**\n * Recursively resolve the client context type produced by a sequence of middleware\n */\nexport type AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext = undefined,\n> = unknown extends TClientContext\n ? TClientContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextBeforeNext'>,\n TClientContext\n >\n\nexport type AssignAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? AssignAllMiddleware<\n TRest,\n TType,\n Assign<TAcc, TMiddleware['_types'][TType & keyof TMiddleware['_types']]>\n >\n : TAcc\n : TAcc\n\nexport type AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext = undefined,\n TSendContext = undefined,\n> = unknown extends TClientContext\n ? Assign<TClientContext, TSendContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextAfterNext'>,\n Assign<TClientContext, TSendContext>\n >\n\nexport type AssignAllServerSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerSendContext'>,\n TSendContext\n >\n\n/**\n * Recursively resolve the server context type produced by a sequence of middleware\n */\nexport type AssignAllServerContext<\n TMiddlewares,\n TSendContext = undefined,\n TServerContext = undefined,\n> = unknown extends TSendContext\n ? Assign<TSendContext, TServerContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerContext'>,\n Assign<TSendContext, TServerContext>\n >\n\nexport type AssignAllClientSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientSendContext'>,\n TSendContext\n >\n\nexport interface FunctionMiddlewareOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TClientContext,\n in out TServerFnResponseType extends ServerFnResponseType,\n> {\n validateClient?: boolean\n middleware?: TMiddlewares\n validator?: ConstrainValidator<TValidator>\n client?: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n server?: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n unknown,\n unknown,\n TServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientNextFn<TMiddlewares> = <\n TSendContext = undefined,\n TNewClientContext = undefined,\n>(ctx?: {\n context?: TNewClientContext\n sendContext?: SerializerStringify<TSendContext>\n headers?: HeadersInit\n}) => Promise<\n FunctionClientResultWithContext<TMiddlewares, TSendContext, TNewClientContext>\n>\n\nexport interface FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n server: <TNewServerContext = undefined, TSendContext = undefined>(\n server: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType\n >,\n ) => FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TNewServerContext,\n TServerSendContext,\n TClientContext,\n TSendContext,\n ServerFnResponseType\n >\n}\nexport type FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> = (\n options: FunctionMiddlewareServerFnOptions<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TServerFnResponseType\n >,\n) => FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n>\n\nexport interface RequestMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TServerSendContext,\n> {\n request: Request\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: Response\n method: Method\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext> = <\n TNewServerContext = undefined,\n TSendContext = undefined,\n>(ctx?: {\n context?: TNewServerContext\n sendContext?: SerializerStringify<TSendContext>\n}) => Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n >\n>\n\nexport type FunctionServerResultWithContext<\n in out TMiddlewares,\n in out TServerSendContext,\n in out TServerContext,\n in out TSendContext,\n> = {\n 'use functions must return the result of next()': true\n _types: {\n context: TServerContext\n sendContext: TSendContext\n }\n context: Expand<\n AssignAllServerContext<TMiddlewares, TServerSendContext, TServerContext>\n >\n sendContext: Expand<AssignAllClientSendContext<TMiddlewares, TSendContext>>\n}\n\nexport interface FunctionMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerSendContext,\n in out TServerFnResponseType,\n> {\n data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: TServerFnResponseType\n method: Method\n filename: string\n functionId: string\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext,\n> =\n | Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n >\n | FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n\nexport interface FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareClient<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n client: <TSendServerContext = undefined, TNewClientContext = undefined>(\n client: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n TServerFnResponseType\n >,\n ) => FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n ServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> = (\n options: FunctionMiddlewareClientFnOptions<\n TMiddlewares,\n TValidator,\n TServerFnResponseType\n >,\n) => FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext\n>\n\nexport interface FunctionMiddlewareClientFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerFnResponseType extends ServerFnResponseType,\n> {\n data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllClientContextBeforeNext<TMiddlewares>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares>>\n method: Method\n response: TServerFnResponseType\n signal: AbortSignal\n next: FunctionMiddlewareClientNextFn<TMiddlewares>\n filename: string\n functionId: string\n type: ServerFnTypeOrTypeFn<\n Method,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n >\n}\n\nexport type FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext,\n> =\n | Promise<\n FunctionClientResultWithContext<\n TMiddlewares,\n TSendContext,\n TClientContext\n >\n >\n | FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>\n\nexport type FunctionClientResultWithContext<\n in out TMiddlewares,\n in out TSendContext,\n in out TClientContext,\n> = {\n 'use functions must return the result of next()': true\n context: Expand<AssignAllClientContextAfterNext<TMiddlewares, TClientContext>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares, TSendContext>>\n headers: HeadersInit\n}\n\nexport interface FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n TServerSendContext,\n TClientContext,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareValidator<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n validator: <TNewValidator>(\n input: ConstrainValidator<TNewValidator>,\n ) => FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TNewValidator,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, TValidator, ServerFnResponseType> {}\n\nexport interface RequestMiddleware\n extends RequestMiddlewareAfterMiddleware<undefined> {\n middleware: <const TMiddlewares = undefined>(\n middlewares: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>,\n ) => RequestMiddlewareAfterMiddleware<TMiddlewares>\n}\n\nexport type AnyRequestMiddleware = RequestMiddlewareWithTypes<any, any>\n\nexport interface RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {\n _types: RequestMiddlewareTypes<TMiddlewares, TServerContext>\n}\n\nexport interface RequestMiddlewareTypes<TMiddlewares, TServerContext> {\n type: 'request'\n middlewares: TMiddlewares\n serverContext: TServerContext\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n undefined,\n TServerContext\n >\n}\n\nexport interface RequestMiddlewareAfterMiddleware<TMiddlewares>\n extends RequestMiddlewareWithTypes<TMiddlewares, undefined>,\n RequestMiddlewareServer<TMiddlewares> {}\n\nexport interface RequestMiddlewareServer<TMiddlewares> {\n server: <TServerContext = undefined>(\n fn: RequestServerFn<TMiddlewares, TServerContext>,\n ) => RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n}\n\nexport type RequestServerFn<TMiddlewares, TServerContext> = (\n options: RequestServerOptions<TMiddlewares>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerOptions<TMiddlewares> {\n request: Request\n pathname: string\n context: AssignAllServerContext<TMiddlewares>\n next: RequestServerNextFn<TMiddlewares>\n}\n\nexport type RequestServerNextFn<TMiddlewares> = <TServerContext = undefined>(\n options?: RequestServerNextFnOptions<TServerContext>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerNextFnOptions<TServerContext> {\n context?: TServerContext\n}\n\nexport type RequestMiddlewareServerFnResult<TMiddlewares, TServerContext> =\n | Promise<RequestServerResult<TMiddlewares, TServerContext>>\n | RequestServerResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerResult<TMiddlewares, TServerContext> {\n request: Request\n pathname: string\n context: Expand<\n AssignAllServerContext<TMiddlewares, undefined, TServerContext>\n >\n response: Response\n}\n\nexport interface RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n extends RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {}\n"],"names":[],"mappings":";;AAgBgB,SAAA,iBACd,SAIA,QAO+B;AAE/B,QAAM,kBAAkB;AAAA,IACtB,MAAM;AAAA,IACN,GAAI,UACD;AAAA,EAOL;AAEO,SAAA;AAAA,IACL,SAAS;AAAA,IACT,YAAY,CAAC,eAAoB;AACxB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,WAAY,CAAA;AAAA,MAC/C;AAAA,IACF;AAAA,IACA,WAAW,CAAC,cAAmB;AACtB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,UAAW,CAAA;AAAA,MAC9C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IAAA;AAAA,EAEJ;AACF;;"}
|
|
1
|
+
{"version":3,"file":"createMiddleware.cjs","sources":["../../src/createMiddleware.ts"],"sourcesContent":["import type {\n ConstrainValidator,\n Method,\n ServerFnResponseType,\n ServerFnTypeOrTypeFn,\n} from './createServerFn'\nimport type {\n AnyRouter,\n Assign,\n Constrain,\n Expand,\n IntersectAssign,\n RegisteredRouter,\n ResolveValidatorInput,\n ResolveValidatorOutput,\n} from '@tanstack/router-core'\nimport type { SerializerStringify } from './serializer'\n\nexport function createMiddleware<TType extends MiddlewareType>(\n options: {\n type: TType\n validateClient?: boolean\n },\n __opts?: FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n): CreateMiddlewareResult<TType> {\n // const resolvedOptions = (__opts || options) as MiddlewareOptions<\n const resolvedOptions = {\n type: 'function',\n ...(__opts ||\n (options as FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >)),\n }\n\n return {\n options: resolvedOptions,\n middleware: (middleware: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { middleware }),\n ) as any\n },\n validator: (validator: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { validator }),\n ) as any\n },\n client: (client: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { client }),\n ) as any\n },\n server: (server: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { server }),\n ) as any\n },\n } as unknown as CreateMiddlewareResult<TType>\n}\n\nexport type MiddlewareType = 'request' | 'function'\n\nexport type CreateMiddlewareResult<TType extends MiddlewareType> =\n 'function' extends TType\n ? FunctionMiddleware<ServerFnResponseType>\n : RequestMiddleware\n\nexport interface FunctionMiddleware<\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareAfterMiddleware<unknown, TServerFnResponseType> {\n middleware: <const TNewMiddlewares = undefined>(\n middlewares: Constrain<\n TNewMiddlewares,\n ReadonlyArray<AnyFunctionMiddleware>\n >,\n ) => FunctionMiddlewareAfterMiddleware<TNewMiddlewares, TServerFnResponseType>\n}\n\nexport interface FunctionMiddlewareAfterMiddleware<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, undefined, TServerFnResponseType>,\n FunctionMiddlewareValidator<TMiddlewares, TServerFnResponseType> {}\n\nexport interface FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n _types: FunctionMiddlewareTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext\n >\n options: FunctionMiddlewareOptions<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareTypes<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TServerSendContext,\n in out TClientContext,\n in out TClientSendContext,\n> {\n type: 'function'\n middlewares: TMiddlewares\n input: ResolveValidatorInput<TValidator>\n allInput: IntersectAllValidatorInputs<TMiddlewares, TValidator>\n output: ResolveValidatorOutput<TValidator>\n allOutput: IntersectAllValidatorOutputs<TMiddlewares, TValidator>\n clientContext: TClientContext\n allClientContextBeforeNext: AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext\n >\n allClientContextAfterNext: AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext,\n TClientSendContext\n >\n serverContext: TServerContext\n serverSendContext: TServerSendContext\n allServerSendContext: AssignAllServerSendContext<\n TMiddlewares,\n TServerSendContext\n >\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext\n >\n clientSendContext: TClientSendContext\n allClientSendContext: AssignAllClientSendContext<\n TMiddlewares,\n TClientSendContext\n >\n validator: TValidator\n}\n\n/**\n * Recursively resolve the input type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorInputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allInput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allInput'>,\n ResolveValidatorInput<TValidator>\n >\n\nexport type IntersectAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? IntersectAllMiddleware<\n TRest,\n TType,\n IntersectAssign<\n TAcc,\n TMiddleware['_types'][TType & keyof TMiddleware['_types']]\n >\n >\n : TAcc\n : TAcc\n\nexport type AnyFunctionMiddleware = FunctionMiddlewareWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\n/**\n * Recursively merge the output type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorOutputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allOutput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allOutput'>,\n ResolveValidatorOutput<TValidator>\n >\n\n/**\n * Recursively resolve the client context type produced by a sequence of middleware\n */\nexport type AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext = undefined,\n> = unknown extends TClientContext\n ? TClientContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextBeforeNext'>,\n TClientContext\n >\n\nexport type AssignAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? AssignAllMiddleware<\n TRest,\n TType,\n Assign<TAcc, TMiddleware['_types'][TType & keyof TMiddleware['_types']]>\n >\n : TAcc\n : TAcc\n\nexport type AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext = undefined,\n TSendContext = undefined,\n> = unknown extends TClientContext\n ? Assign<TClientContext, TSendContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextAfterNext'>,\n Assign<TClientContext, TSendContext>\n >\n\nexport type AssignAllServerSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerSendContext'>,\n TSendContext\n >\n\n/**\n * Recursively resolve the server context type produced by a sequence of middleware\n */\nexport type AssignAllServerContext<\n TMiddlewares,\n TSendContext = undefined,\n TServerContext = undefined,\n> = unknown extends TSendContext\n ? Assign<TSendContext, TServerContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerContext'>,\n Assign<TSendContext, TServerContext>\n >\n\nexport type AssignAllClientSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientSendContext'>,\n TSendContext\n >\n\nexport interface FunctionMiddlewareOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TClientContext,\n in out TServerFnResponseType extends ServerFnResponseType,\n> {\n validateClient?: boolean\n middleware?: TMiddlewares\n validator?: ConstrainValidator<TValidator>\n client?: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n server?: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n unknown,\n unknown,\n TServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientNextFn<TMiddlewares> = <\n TSendContext = undefined,\n TNewClientContext = undefined,\n>(ctx?: {\n context?: TNewClientContext\n sendContext?: SerializerStringify<TSendContext>\n headers?: HeadersInit\n}) => Promise<\n FunctionClientResultWithContext<TMiddlewares, TSendContext, TNewClientContext>\n>\n\nexport interface FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n server: <TNewServerContext = undefined, TSendContext = undefined>(\n server: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType\n >,\n ) => FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TNewServerContext,\n TServerSendContext,\n TClientContext,\n TSendContext,\n ServerFnResponseType\n >\n}\nexport type FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> = (\n options: FunctionMiddlewareServerFnOptions<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TServerFnResponseType\n >,\n) => FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n>\n\nexport interface RequestMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TServerSendContext,\n> {\n request: Request\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: Response\n method: Method\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext> = <\n TNewServerContext = undefined,\n TSendContext = undefined,\n>(ctx?: {\n context?: TNewServerContext\n sendContext?: SerializerStringify<TSendContext>\n}) => Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n >\n>\n\nexport type FunctionServerResultWithContext<\n in out TMiddlewares,\n in out TServerSendContext,\n in out TServerContext,\n in out TSendContext,\n> = {\n 'use functions must return the result of next()': true\n _types: {\n context: TServerContext\n sendContext: TSendContext\n }\n context: Expand<\n AssignAllServerContext<TMiddlewares, TServerSendContext, TServerContext>\n >\n sendContext: Expand<AssignAllClientSendContext<TMiddlewares, TSendContext>>\n}\n\nexport interface FunctionMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerSendContext,\n in out TServerFnResponseType,\n> {\n data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: TServerFnResponseType\n method: Method\n filename: string\n functionId: string\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext,\n> =\n | Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n >\n | FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n\nexport interface FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareClient<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n TRouter extends AnyRouter = RegisteredRouter,\n> {\n client: <TSendServerContext = undefined, TNewClientContext = undefined>(\n client: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n TServerFnResponseType,\n TRouter\n >,\n ) => FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n ServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n TRouter extends AnyRouter = RegisteredRouter,\n> = (\n options: FunctionMiddlewareClientFnOptions<\n TMiddlewares,\n TValidator,\n TServerFnResponseType,\n TRouter\n >,\n) => FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext\n>\n\nexport interface FunctionMiddlewareClientFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerFnResponseType extends ServerFnResponseType,\n in out TRouter extends AnyRouter,\n> {\n data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllClientContextBeforeNext<TMiddlewares>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares>>\n method: Method\n response: TServerFnResponseType\n signal: AbortSignal\n next: FunctionMiddlewareClientNextFn<TMiddlewares>\n filename: string\n functionId: string\n type: ServerFnTypeOrTypeFn<\n Method,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n >\n router: TRouter\n}\n\nexport type FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext,\n> =\n | Promise<\n FunctionClientResultWithContext<\n TMiddlewares,\n TSendContext,\n TClientContext\n >\n >\n | FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>\n\nexport type FunctionClientResultWithContext<\n in out TMiddlewares,\n in out TSendContext,\n in out TClientContext,\n> = {\n 'use functions must return the result of next()': true\n context: Expand<AssignAllClientContextAfterNext<TMiddlewares, TClientContext>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares, TSendContext>>\n headers: HeadersInit\n}\n\nexport interface FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n TServerSendContext,\n TClientContext,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareValidator<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n validator: <TNewValidator>(\n input: ConstrainValidator<TNewValidator>,\n ) => FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TNewValidator,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, TValidator, ServerFnResponseType> {}\n\nexport interface RequestMiddleware\n extends RequestMiddlewareAfterMiddleware<undefined> {\n middleware: <const TMiddlewares = undefined>(\n middlewares: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>,\n ) => RequestMiddlewareAfterMiddleware<TMiddlewares>\n}\n\nexport type AnyRequestMiddleware = RequestMiddlewareWithTypes<any, any>\n\nexport interface RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {\n _types: RequestMiddlewareTypes<TMiddlewares, TServerContext>\n}\n\nexport interface RequestMiddlewareTypes<TMiddlewares, TServerContext> {\n type: 'request'\n middlewares: TMiddlewares\n serverContext: TServerContext\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n undefined,\n TServerContext\n >\n}\n\nexport interface RequestMiddlewareAfterMiddleware<TMiddlewares>\n extends RequestMiddlewareWithTypes<TMiddlewares, undefined>,\n RequestMiddlewareServer<TMiddlewares> {}\n\nexport interface RequestMiddlewareServer<TMiddlewares> {\n server: <TServerContext = undefined>(\n fn: RequestServerFn<TMiddlewares, TServerContext>,\n ) => RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n}\n\nexport type RequestServerFn<TMiddlewares, TServerContext> = (\n options: RequestServerOptions<TMiddlewares>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerOptions<TMiddlewares> {\n request: Request\n pathname: string\n context: AssignAllServerContext<TMiddlewares>\n next: RequestServerNextFn<TMiddlewares>\n}\n\nexport type RequestServerNextFn<TMiddlewares> = <TServerContext = undefined>(\n options?: RequestServerNextFnOptions<TServerContext>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerNextFnOptions<TServerContext> {\n context?: TServerContext\n}\n\nexport type RequestMiddlewareServerFnResult<TMiddlewares, TServerContext> =\n | Promise<RequestServerResult<TMiddlewares, TServerContext>>\n | RequestServerResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerResult<TMiddlewares, TServerContext> {\n request: Request\n pathname: string\n context: Expand<\n AssignAllServerContext<TMiddlewares, undefined, TServerContext>\n >\n response: Response\n}\n\nexport interface RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n extends RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {}\n"],"names":[],"mappings":";;AAkBgB,SAAA,iBACd,SAIA,QAO+B;AAE/B,QAAM,kBAAkB;AAAA,IACtB,MAAM;AAAA,IACN,GAAI,UACD;AAAA,EAOL;AAEO,SAAA;AAAA,IACL,SAAS;AAAA,IACT,YAAY,CAAC,eAAoB;AACxB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,WAAY,CAAA;AAAA,MAC/C;AAAA,IACF;AAAA,IACA,WAAW,CAAC,cAAmB;AACtB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,UAAW,CAAA;AAAA,MAC9C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IAAA;AAAA,EAEJ;AACF;;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ConstrainValidator, Method, ServerFnResponseType, ServerFnTypeOrTypeFn } from './createServerFn.cjs';
|
|
2
|
-
import { Assign, Constrain, Expand, IntersectAssign, ResolveValidatorInput, ResolveValidatorOutput } from '@tanstack/router-core';
|
|
2
|
+
import { AnyRouter, Assign, Constrain, Expand, IntersectAssign, RegisteredRouter, ResolveValidatorInput, ResolveValidatorOutput } from '@tanstack/router-core';
|
|
3
3
|
import { SerializerStringify } from './serializer.cjs';
|
|
4
4
|
export declare function createMiddleware<TType extends MiddlewareType>(options: {
|
|
5
5
|
type: TType;
|
|
@@ -106,11 +106,11 @@ export interface FunctionMiddlewareServerFnOptions<in out TMiddlewares, in out T
|
|
|
106
106
|
export type FunctionMiddlewareServerFnResult<TMiddlewares, TServerSendContext, TServerContext, TSendContext> = Promise<FunctionServerResultWithContext<TMiddlewares, TServerSendContext, TServerContext, TSendContext>> | FunctionServerResultWithContext<TMiddlewares, TServerSendContext, TServerContext, TSendContext>;
|
|
107
107
|
export interface FunctionMiddlewareAfterServer<TMiddlewares, TValidator, TServerContext, TServerSendContext, TClientContext, TClientSendContext, TServerFnResponseType extends ServerFnResponseType> extends FunctionMiddlewareWithTypes<TMiddlewares, TValidator, TServerContext, TServerSendContext, TClientContext, TClientSendContext, TServerFnResponseType> {
|
|
108
108
|
}
|
|
109
|
-
export interface FunctionMiddlewareClient<TMiddlewares, TValidator, TServerFnResponseType extends ServerFnResponseType> {
|
|
110
|
-
client: <TSendServerContext = undefined, TNewClientContext = undefined>(client: FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, TServerFnResponseType>) => FunctionMiddlewareAfterClient<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, ServerFnResponseType>;
|
|
109
|
+
export interface FunctionMiddlewareClient<TMiddlewares, TValidator, TServerFnResponseType extends ServerFnResponseType, TRouter extends AnyRouter = RegisteredRouter> {
|
|
110
|
+
client: <TSendServerContext = undefined, TNewClientContext = undefined>(client: FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, TServerFnResponseType, TRouter>) => FunctionMiddlewareAfterClient<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, ServerFnResponseType>;
|
|
111
111
|
}
|
|
112
|
-
export type FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendContext, TClientContext, TServerFnResponseType extends ServerFnResponseType> = (options: FunctionMiddlewareClientFnOptions<TMiddlewares, TValidator, TServerFnResponseType>) => FunctionMiddlewareClientFnResult<TMiddlewares, TSendContext, TClientContext>;
|
|
113
|
-
export interface FunctionMiddlewareClientFnOptions<in out TMiddlewares, in out TValidator, in out TServerFnResponseType extends ServerFnResponseType> {
|
|
112
|
+
export type FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendContext, TClientContext, TServerFnResponseType extends ServerFnResponseType, TRouter extends AnyRouter = RegisteredRouter> = (options: FunctionMiddlewareClientFnOptions<TMiddlewares, TValidator, TServerFnResponseType, TRouter>) => FunctionMiddlewareClientFnResult<TMiddlewares, TSendContext, TClientContext>;
|
|
113
|
+
export interface FunctionMiddlewareClientFnOptions<in out TMiddlewares, in out TValidator, in out TServerFnResponseType extends ServerFnResponseType, in out TRouter extends AnyRouter> {
|
|
114
114
|
data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>;
|
|
115
115
|
context: Expand<AssignAllClientContextBeforeNext<TMiddlewares>>;
|
|
116
116
|
sendContext: Expand<AssignAllServerSendContext<TMiddlewares>>;
|
|
@@ -121,6 +121,7 @@ export interface FunctionMiddlewareClientFnOptions<in out TMiddlewares, in out T
|
|
|
121
121
|
filename: string;
|
|
122
122
|
functionId: string;
|
|
123
123
|
type: ServerFnTypeOrTypeFn<Method, TServerFnResponseType, TMiddlewares, TValidator>;
|
|
124
|
+
router: TRouter;
|
|
124
125
|
}
|
|
125
126
|
export type FunctionMiddlewareClientFnResult<TMiddlewares, TSendContext, TClientContext> = Promise<FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>> | FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>;
|
|
126
127
|
export type FunctionClientResultWithContext<in out TMiddlewares, in out TSendContext, in out TClientContext> = {
|
|
@@ -26,8 +26,14 @@ const invariant = require("tiny-invariant");
|
|
|
26
26
|
const warning = require("tiny-warning");
|
|
27
27
|
const routerCore = require("@tanstack/router-core");
|
|
28
28
|
const client = require("@tanstack/router-core/ssr/client");
|
|
29
|
+
const startStorageContext = require("@tanstack/start-storage-context");
|
|
29
30
|
const registerGlobalMiddleware = require("./registerGlobalMiddleware.cjs");
|
|
30
31
|
const serializer = require("./serializer.cjs");
|
|
32
|
+
const createIsomorphicFn = require("./createIsomorphicFn.cjs");
|
|
33
|
+
const getRouterInstance = createIsomorphicFn.createIsomorphicFn().client(() => window.__TSR_ROUTER__).server(() => {
|
|
34
|
+
var _a;
|
|
35
|
+
return (_a = startStorageContext.getStartContext({ throwIfNotFound: false })) == null ? void 0 : _a.router;
|
|
36
|
+
});
|
|
31
37
|
function createServerFn(options, __opts) {
|
|
32
38
|
const resolvedOptions = __opts || options || {};
|
|
33
39
|
if (typeof resolvedOptions.method === "undefined") {
|
|
@@ -63,7 +69,8 @@ function createServerFn(options, __opts) {
|
|
|
63
69
|
data: opts == null ? void 0 : opts.data,
|
|
64
70
|
headers: opts == null ? void 0 : opts.headers,
|
|
65
71
|
signal: opts == null ? void 0 : opts.signal,
|
|
66
|
-
context: {}
|
|
72
|
+
context: {},
|
|
73
|
+
router: getRouterInstance()
|
|
67
74
|
}).then((d) => {
|
|
68
75
|
if (resolvedOptions.response === "full") {
|
|
69
76
|
return d;
|
|
@@ -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/router-core'\nimport { mergeHeaders } from '@tanstack/router-core/ssr/client'\nimport { globalMiddleware } from './registerGlobalMiddleware'\n\nimport { startSerializer } from './serializer'\nimport type {\n SerializerParse,\n SerializerStringify,\n SerializerStringifyBy,\n} from './serializer'\nimport type {\n AnyValidator,\n Constrain,\n Expand,\n ResolveValidatorInput,\n Validator,\n} from '@tanstack/router-core'\nimport type { JsonResponse } from '@tanstack/router-core/ssr/client'\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCgB,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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AO,UAAU,KAAK;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
|
+
{"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 { mergeHeaders } from '@tanstack/router-core/ssr/client'\nimport { getStartContext } from '@tanstack/start-storage-context'\nimport { globalMiddleware } from './registerGlobalMiddleware'\n\nimport { startSerializer } from './serializer'\n\nimport { createIsomorphicFn } from './createIsomorphicFn'\nimport type {\n SerializerParse,\n SerializerStringify,\n SerializerStringifyBy,\n} from './serializer'\nimport type {\n AnyRouter,\n AnyValidator,\n Constrain,\n Expand,\n ResolveValidatorInput,\n Validator,\n} from '@tanstack/router-core'\nimport type { JsonResponse } from '@tanstack/router-core/ssr/client'\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\nconst getRouterInstance = createIsomorphicFn()\n .client(() => window.__TSR_ROUTER__!)\n .server(() => getStartContext({ throwIfNotFound: false })?.router)\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 router: getRouterInstance(),\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 type CompiledFetcherFnOptions = {\n method: Method\n data: unknown\n response?: ServerFnResponseType\n headers?: HeadersInit\n signal?: AbortSignal\n context?: any\n // router?: AnyRouter\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 router?: AnyRouter\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":["createIsomorphicFn","getStartContext","serverFnStaticCache","globalMiddleware","isRedirect","isNotFound","startSerializer","mergeHeaders"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAM,oBAAoBA,mBAAAA,mBAAmB,EAC1C,OAAO,MAAM,OAAO,cAAe,EACnC,OAAO,MAAA;;AAAMC,mDAAgB,EAAE,iBAAiB,MAAO,CAAA,MAA1CA,mBAA6C;AAAA,CAAM;AAEnD,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,QAAW,OAAO,OAAO,iBAAiB,EAAE,UAAA,CAAW,CAAC;AAAA,IAC5D;AAAA,IACA,MAAM,CAAC,SAAS;AACP,aAAA,eAML,QAAW,OAAO,OAAO,iBAAiB,EAAE,KAAA,CAAM,CAAC;AAAA,IACvD;AAAA,IACA,SAAS,IA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B,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,5 +1,5 @@
|
|
|
1
1
|
import { SerializerParse, SerializerStringify, SerializerStringifyBy } from './serializer.cjs';
|
|
2
|
-
import { AnyValidator, Constrain, Expand, ResolveValidatorInput, Validator } from '@tanstack/router-core';
|
|
2
|
+
import { AnyRouter, AnyValidator, Constrain, Expand, ResolveValidatorInput, Validator } from '@tanstack/router-core';
|
|
3
3
|
import { JsonResponse } from '@tanstack/router-core/ssr/client';
|
|
4
4
|
import { Readable } from 'node:stream';
|
|
5
5
|
import { AnyFunctionMiddleware, AssignAllClientSendContext, AssignAllServerContext, IntersectAllValidatorInputs, IntersectAllValidatorOutputs } from './createMiddleware.cjs';
|
|
@@ -143,6 +143,7 @@ export type ServerFnMiddlewareOptions = {
|
|
|
143
143
|
context?: any;
|
|
144
144
|
type: ServerFnTypeOrTypeFn<any, any, any, any>;
|
|
145
145
|
functionId: string;
|
|
146
|
+
router?: AnyRouter;
|
|
146
147
|
};
|
|
147
148
|
export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {
|
|
148
149
|
result?: unknown;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createIsomorphicFn.js","sources":["../../src/createIsomorphicFn.ts"],"sourcesContent":["// a function that can have different implementations on the client and server.\n// implementations not provided will default to a no-op function.\n\nexport type IsomorphicFn<\n TArgs extends Array<any> = [],\n TServer = undefined,\n TClient = undefined,\n> = (...args: TArgs) => TServer | TClient\n\nexport interface ServerOnlyFn<TArgs extends Array<any>, TServer>\n extends IsomorphicFn<TArgs, TServer> {\n client: <TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface ClientOnlyFn<TArgs extends Array<any>, TClient>\n extends IsomorphicFn<TArgs, undefined, TClient> {\n server: <TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface IsomorphicFnBase extends IsomorphicFn {\n server: <TArgs extends Array<any>, TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => ServerOnlyFn<TArgs, TServer>\n client: <TArgs extends Array<any>, TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => ClientOnlyFn<TArgs, TClient>\n}\n\n// this is a dummy function, it will be replaced by the transformer\nexport function createIsomorphicFn(): IsomorphicFnBase {\n return
|
|
1
|
+
{"version":3,"file":"createIsomorphicFn.js","sources":["../../src/createIsomorphicFn.ts"],"sourcesContent":["// a function that can have different implementations on the client and server.\n// implementations not provided will default to a no-op function.\n\nexport type IsomorphicFn<\n TArgs extends Array<any> = [],\n TServer = undefined,\n TClient = undefined,\n> = (...args: TArgs) => TServer | TClient\n\nexport interface ServerOnlyFn<TArgs extends Array<any>, TServer>\n extends IsomorphicFn<TArgs, TServer> {\n client: <TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface ClientOnlyFn<TArgs extends Array<any>, TClient>\n extends IsomorphicFn<TArgs, undefined, TClient> {\n server: <TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => IsomorphicFn<TArgs, TServer, TClient>\n}\n\nexport interface IsomorphicFnBase extends IsomorphicFn {\n server: <TArgs extends Array<any>, TServer>(\n serverImpl: (...args: TArgs) => TServer,\n ) => ServerOnlyFn<TArgs, TServer>\n client: <TArgs extends Array<any>, TClient>(\n clientImpl: (...args: TArgs) => TClient,\n ) => ClientOnlyFn<TArgs, TClient>\n}\n\n// this is a dummy function, it will be replaced by the transformer\n// if we use `createIsomorphicFn` in this library itself, vite tries to execute it before the transformer runs\n// therefore we must return a dummy function that allows calling `server` and `client` method chains.\nexport function createIsomorphicFn(): IsomorphicFnBase {\n return {\n server: () => ({ client: () => () => {} }),\n client: () => ({ server: () => () => {} }),\n } as any\n}\n"],"names":[],"mappings":"AAmCO,SAAS,qBAAuC;AAC9C,SAAA;AAAA,IACL,QAAQ,OAAO,EAAE,QAAQ,MAAM,MAAM;AAAA,IAAA;IACrC,QAAQ,OAAO,EAAE,QAAQ,MAAM,MAAM;AAAA,IAAA,EAAG;AAAA,EAC1C;AACF;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ConstrainValidator, Method, ServerFnResponseType, ServerFnTypeOrTypeFn } from './createServerFn.js';
|
|
2
|
-
import { Assign, Constrain, Expand, IntersectAssign, ResolveValidatorInput, ResolveValidatorOutput } from '@tanstack/router-core';
|
|
2
|
+
import { AnyRouter, Assign, Constrain, Expand, IntersectAssign, RegisteredRouter, ResolveValidatorInput, ResolveValidatorOutput } from '@tanstack/router-core';
|
|
3
3
|
import { SerializerStringify } from './serializer.js';
|
|
4
4
|
export declare function createMiddleware<TType extends MiddlewareType>(options: {
|
|
5
5
|
type: TType;
|
|
@@ -106,11 +106,11 @@ export interface FunctionMiddlewareServerFnOptions<in out TMiddlewares, in out T
|
|
|
106
106
|
export type FunctionMiddlewareServerFnResult<TMiddlewares, TServerSendContext, TServerContext, TSendContext> = Promise<FunctionServerResultWithContext<TMiddlewares, TServerSendContext, TServerContext, TSendContext>> | FunctionServerResultWithContext<TMiddlewares, TServerSendContext, TServerContext, TSendContext>;
|
|
107
107
|
export interface FunctionMiddlewareAfterServer<TMiddlewares, TValidator, TServerContext, TServerSendContext, TClientContext, TClientSendContext, TServerFnResponseType extends ServerFnResponseType> extends FunctionMiddlewareWithTypes<TMiddlewares, TValidator, TServerContext, TServerSendContext, TClientContext, TClientSendContext, TServerFnResponseType> {
|
|
108
108
|
}
|
|
109
|
-
export interface FunctionMiddlewareClient<TMiddlewares, TValidator, TServerFnResponseType extends ServerFnResponseType> {
|
|
110
|
-
client: <TSendServerContext = undefined, TNewClientContext = undefined>(client: FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, TServerFnResponseType>) => FunctionMiddlewareAfterClient<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, ServerFnResponseType>;
|
|
109
|
+
export interface FunctionMiddlewareClient<TMiddlewares, TValidator, TServerFnResponseType extends ServerFnResponseType, TRouter extends AnyRouter = RegisteredRouter> {
|
|
110
|
+
client: <TSendServerContext = undefined, TNewClientContext = undefined>(client: FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, TServerFnResponseType, TRouter>) => FunctionMiddlewareAfterClient<TMiddlewares, TValidator, TSendServerContext, TNewClientContext, ServerFnResponseType>;
|
|
111
111
|
}
|
|
112
|
-
export type FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendContext, TClientContext, TServerFnResponseType extends ServerFnResponseType> = (options: FunctionMiddlewareClientFnOptions<TMiddlewares, TValidator, TServerFnResponseType>) => FunctionMiddlewareClientFnResult<TMiddlewares, TSendContext, TClientContext>;
|
|
113
|
-
export interface FunctionMiddlewareClientFnOptions<in out TMiddlewares, in out TValidator, in out TServerFnResponseType extends ServerFnResponseType> {
|
|
112
|
+
export type FunctionMiddlewareClientFn<TMiddlewares, TValidator, TSendContext, TClientContext, TServerFnResponseType extends ServerFnResponseType, TRouter extends AnyRouter = RegisteredRouter> = (options: FunctionMiddlewareClientFnOptions<TMiddlewares, TValidator, TServerFnResponseType, TRouter>) => FunctionMiddlewareClientFnResult<TMiddlewares, TSendContext, TClientContext>;
|
|
113
|
+
export interface FunctionMiddlewareClientFnOptions<in out TMiddlewares, in out TValidator, in out TServerFnResponseType extends ServerFnResponseType, in out TRouter extends AnyRouter> {
|
|
114
114
|
data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>;
|
|
115
115
|
context: Expand<AssignAllClientContextBeforeNext<TMiddlewares>>;
|
|
116
116
|
sendContext: Expand<AssignAllServerSendContext<TMiddlewares>>;
|
|
@@ -121,6 +121,7 @@ export interface FunctionMiddlewareClientFnOptions<in out TMiddlewares, in out T
|
|
|
121
121
|
filename: string;
|
|
122
122
|
functionId: string;
|
|
123
123
|
type: ServerFnTypeOrTypeFn<Method, TServerFnResponseType, TMiddlewares, TValidator>;
|
|
124
|
+
router: TRouter;
|
|
124
125
|
}
|
|
125
126
|
export type FunctionMiddlewareClientFnResult<TMiddlewares, TSendContext, TClientContext> = Promise<FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>> | FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>;
|
|
126
127
|
export type FunctionClientResultWithContext<in out TMiddlewares, in out TSendContext, in out TClientContext> = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createMiddleware.js","sources":["../../src/createMiddleware.ts"],"sourcesContent":["import type {\n ConstrainValidator,\n Method,\n ServerFnResponseType,\n ServerFnTypeOrTypeFn,\n} from './createServerFn'\nimport type {\n Assign,\n Constrain,\n Expand,\n IntersectAssign,\n ResolveValidatorInput,\n ResolveValidatorOutput,\n} from '@tanstack/router-core'\nimport type { SerializerStringify } from './serializer'\n\nexport function createMiddleware<TType extends MiddlewareType>(\n options: {\n type: TType\n validateClient?: boolean\n },\n __opts?: FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n): CreateMiddlewareResult<TType> {\n // const resolvedOptions = (__opts || options) as MiddlewareOptions<\n const resolvedOptions = {\n type: 'function',\n ...(__opts ||\n (options as FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >)),\n }\n\n return {\n options: resolvedOptions,\n middleware: (middleware: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { middleware }),\n ) as any\n },\n validator: (validator: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { validator }),\n ) as any\n },\n client: (client: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { client }),\n ) as any\n },\n server: (server: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { server }),\n ) as any\n },\n } as unknown as CreateMiddlewareResult<TType>\n}\n\nexport type MiddlewareType = 'request' | 'function'\n\nexport type CreateMiddlewareResult<TType extends MiddlewareType> =\n 'function' extends TType\n ? FunctionMiddleware<ServerFnResponseType>\n : RequestMiddleware\n\nexport interface FunctionMiddleware<\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareAfterMiddleware<unknown, TServerFnResponseType> {\n middleware: <const TNewMiddlewares = undefined>(\n middlewares: Constrain<\n TNewMiddlewares,\n ReadonlyArray<AnyFunctionMiddleware>\n >,\n ) => FunctionMiddlewareAfterMiddleware<TNewMiddlewares, TServerFnResponseType>\n}\n\nexport interface FunctionMiddlewareAfterMiddleware<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, undefined, TServerFnResponseType>,\n FunctionMiddlewareValidator<TMiddlewares, TServerFnResponseType> {}\n\nexport interface FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n _types: FunctionMiddlewareTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext\n >\n options: FunctionMiddlewareOptions<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareTypes<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TServerSendContext,\n in out TClientContext,\n in out TClientSendContext,\n> {\n type: 'function'\n middlewares: TMiddlewares\n input: ResolveValidatorInput<TValidator>\n allInput: IntersectAllValidatorInputs<TMiddlewares, TValidator>\n output: ResolveValidatorOutput<TValidator>\n allOutput: IntersectAllValidatorOutputs<TMiddlewares, TValidator>\n clientContext: TClientContext\n allClientContextBeforeNext: AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext\n >\n allClientContextAfterNext: AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext,\n TClientSendContext\n >\n serverContext: TServerContext\n serverSendContext: TServerSendContext\n allServerSendContext: AssignAllServerSendContext<\n TMiddlewares,\n TServerSendContext\n >\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext\n >\n clientSendContext: TClientSendContext\n allClientSendContext: AssignAllClientSendContext<\n TMiddlewares,\n TClientSendContext\n >\n validator: TValidator\n}\n\n/**\n * Recursively resolve the input type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorInputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allInput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allInput'>,\n ResolveValidatorInput<TValidator>\n >\n\nexport type IntersectAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? IntersectAllMiddleware<\n TRest,\n TType,\n IntersectAssign<\n TAcc,\n TMiddleware['_types'][TType & keyof TMiddleware['_types']]\n >\n >\n : TAcc\n : TAcc\n\nexport type AnyFunctionMiddleware = FunctionMiddlewareWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\n/**\n * Recursively merge the output type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorOutputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allOutput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allOutput'>,\n ResolveValidatorOutput<TValidator>\n >\n\n/**\n * Recursively resolve the client context type produced by a sequence of middleware\n */\nexport type AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext = undefined,\n> = unknown extends TClientContext\n ? TClientContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextBeforeNext'>,\n TClientContext\n >\n\nexport type AssignAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? AssignAllMiddleware<\n TRest,\n TType,\n Assign<TAcc, TMiddleware['_types'][TType & keyof TMiddleware['_types']]>\n >\n : TAcc\n : TAcc\n\nexport type AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext = undefined,\n TSendContext = undefined,\n> = unknown extends TClientContext\n ? Assign<TClientContext, TSendContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextAfterNext'>,\n Assign<TClientContext, TSendContext>\n >\n\nexport type AssignAllServerSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerSendContext'>,\n TSendContext\n >\n\n/**\n * Recursively resolve the server context type produced by a sequence of middleware\n */\nexport type AssignAllServerContext<\n TMiddlewares,\n TSendContext = undefined,\n TServerContext = undefined,\n> = unknown extends TSendContext\n ? Assign<TSendContext, TServerContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerContext'>,\n Assign<TSendContext, TServerContext>\n >\n\nexport type AssignAllClientSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientSendContext'>,\n TSendContext\n >\n\nexport interface FunctionMiddlewareOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TClientContext,\n in out TServerFnResponseType extends ServerFnResponseType,\n> {\n validateClient?: boolean\n middleware?: TMiddlewares\n validator?: ConstrainValidator<TValidator>\n client?: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n server?: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n unknown,\n unknown,\n TServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientNextFn<TMiddlewares> = <\n TSendContext = undefined,\n TNewClientContext = undefined,\n>(ctx?: {\n context?: TNewClientContext\n sendContext?: SerializerStringify<TSendContext>\n headers?: HeadersInit\n}) => Promise<\n FunctionClientResultWithContext<TMiddlewares, TSendContext, TNewClientContext>\n>\n\nexport interface FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n server: <TNewServerContext = undefined, TSendContext = undefined>(\n server: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType\n >,\n ) => FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TNewServerContext,\n TServerSendContext,\n TClientContext,\n TSendContext,\n ServerFnResponseType\n >\n}\nexport type FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> = (\n options: FunctionMiddlewareServerFnOptions<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TServerFnResponseType\n >,\n) => FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n>\n\nexport interface RequestMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TServerSendContext,\n> {\n request: Request\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: Response\n method: Method\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext> = <\n TNewServerContext = undefined,\n TSendContext = undefined,\n>(ctx?: {\n context?: TNewServerContext\n sendContext?: SerializerStringify<TSendContext>\n}) => Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n >\n>\n\nexport type FunctionServerResultWithContext<\n in out TMiddlewares,\n in out TServerSendContext,\n in out TServerContext,\n in out TSendContext,\n> = {\n 'use functions must return the result of next()': true\n _types: {\n context: TServerContext\n sendContext: TSendContext\n }\n context: Expand<\n AssignAllServerContext<TMiddlewares, TServerSendContext, TServerContext>\n >\n sendContext: Expand<AssignAllClientSendContext<TMiddlewares, TSendContext>>\n}\n\nexport interface FunctionMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerSendContext,\n in out TServerFnResponseType,\n> {\n data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: TServerFnResponseType\n method: Method\n filename: string\n functionId: string\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext,\n> =\n | Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n >\n | FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n\nexport interface FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareClient<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n client: <TSendServerContext = undefined, TNewClientContext = undefined>(\n client: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n TServerFnResponseType\n >,\n ) => FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n ServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> = (\n options: FunctionMiddlewareClientFnOptions<\n TMiddlewares,\n TValidator,\n TServerFnResponseType\n >,\n) => FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext\n>\n\nexport interface FunctionMiddlewareClientFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerFnResponseType extends ServerFnResponseType,\n> {\n data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllClientContextBeforeNext<TMiddlewares>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares>>\n method: Method\n response: TServerFnResponseType\n signal: AbortSignal\n next: FunctionMiddlewareClientNextFn<TMiddlewares>\n filename: string\n functionId: string\n type: ServerFnTypeOrTypeFn<\n Method,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n >\n}\n\nexport type FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext,\n> =\n | Promise<\n FunctionClientResultWithContext<\n TMiddlewares,\n TSendContext,\n TClientContext\n >\n >\n | FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>\n\nexport type FunctionClientResultWithContext<\n in out TMiddlewares,\n in out TSendContext,\n in out TClientContext,\n> = {\n 'use functions must return the result of next()': true\n context: Expand<AssignAllClientContextAfterNext<TMiddlewares, TClientContext>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares, TSendContext>>\n headers: HeadersInit\n}\n\nexport interface FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n TServerSendContext,\n TClientContext,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareValidator<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n validator: <TNewValidator>(\n input: ConstrainValidator<TNewValidator>,\n ) => FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TNewValidator,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, TValidator, ServerFnResponseType> {}\n\nexport interface RequestMiddleware\n extends RequestMiddlewareAfterMiddleware<undefined> {\n middleware: <const TMiddlewares = undefined>(\n middlewares: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>,\n ) => RequestMiddlewareAfterMiddleware<TMiddlewares>\n}\n\nexport type AnyRequestMiddleware = RequestMiddlewareWithTypes<any, any>\n\nexport interface RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {\n _types: RequestMiddlewareTypes<TMiddlewares, TServerContext>\n}\n\nexport interface RequestMiddlewareTypes<TMiddlewares, TServerContext> {\n type: 'request'\n middlewares: TMiddlewares\n serverContext: TServerContext\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n undefined,\n TServerContext\n >\n}\n\nexport interface RequestMiddlewareAfterMiddleware<TMiddlewares>\n extends RequestMiddlewareWithTypes<TMiddlewares, undefined>,\n RequestMiddlewareServer<TMiddlewares> {}\n\nexport interface RequestMiddlewareServer<TMiddlewares> {\n server: <TServerContext = undefined>(\n fn: RequestServerFn<TMiddlewares, TServerContext>,\n ) => RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n}\n\nexport type RequestServerFn<TMiddlewares, TServerContext> = (\n options: RequestServerOptions<TMiddlewares>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerOptions<TMiddlewares> {\n request: Request\n pathname: string\n context: AssignAllServerContext<TMiddlewares>\n next: RequestServerNextFn<TMiddlewares>\n}\n\nexport type RequestServerNextFn<TMiddlewares> = <TServerContext = undefined>(\n options?: RequestServerNextFnOptions<TServerContext>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerNextFnOptions<TServerContext> {\n context?: TServerContext\n}\n\nexport type RequestMiddlewareServerFnResult<TMiddlewares, TServerContext> =\n | Promise<RequestServerResult<TMiddlewares, TServerContext>>\n | RequestServerResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerResult<TMiddlewares, TServerContext> {\n request: Request\n pathname: string\n context: Expand<\n AssignAllServerContext<TMiddlewares, undefined, TServerContext>\n >\n response: Response\n}\n\nexport interface RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n extends RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {}\n"],"names":[],"mappings":"AAgBgB,SAAA,iBACd,SAIA,QAO+B;AAE/B,QAAM,kBAAkB;AAAA,IACtB,MAAM;AAAA,IACN,GAAI,UACD;AAAA,EAOL;AAEO,SAAA;AAAA,IACL,SAAS;AAAA,IACT,YAAY,CAAC,eAAoB;AACxB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,WAAY,CAAA;AAAA,MAC/C;AAAA,IACF;AAAA,IACA,WAAW,CAAC,cAAmB;AACtB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,UAAW,CAAA;AAAA,MAC9C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IAAA;AAAA,EAEJ;AACF;"}
|
|
1
|
+
{"version":3,"file":"createMiddleware.js","sources":["../../src/createMiddleware.ts"],"sourcesContent":["import type {\n ConstrainValidator,\n Method,\n ServerFnResponseType,\n ServerFnTypeOrTypeFn,\n} from './createServerFn'\nimport type {\n AnyRouter,\n Assign,\n Constrain,\n Expand,\n IntersectAssign,\n RegisteredRouter,\n ResolveValidatorInput,\n ResolveValidatorOutput,\n} from '@tanstack/router-core'\nimport type { SerializerStringify } from './serializer'\n\nexport function createMiddleware<TType extends MiddlewareType>(\n options: {\n type: TType\n validateClient?: boolean\n },\n __opts?: FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n): CreateMiddlewareResult<TType> {\n // const resolvedOptions = (__opts || options) as MiddlewareOptions<\n const resolvedOptions = {\n type: 'function',\n ...(__opts ||\n (options as FunctionMiddlewareOptions<\n unknown,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >)),\n }\n\n return {\n options: resolvedOptions,\n middleware: (middleware: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { middleware }),\n ) as any\n },\n validator: (validator: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { validator }),\n ) as any\n },\n client: (client: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { client }),\n ) as any\n },\n server: (server: any) => {\n return createMiddleware(\n {} as any,\n Object.assign(resolvedOptions, { server }),\n ) as any\n },\n } as unknown as CreateMiddlewareResult<TType>\n}\n\nexport type MiddlewareType = 'request' | 'function'\n\nexport type CreateMiddlewareResult<TType extends MiddlewareType> =\n 'function' extends TType\n ? FunctionMiddleware<ServerFnResponseType>\n : RequestMiddleware\n\nexport interface FunctionMiddleware<\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareAfterMiddleware<unknown, TServerFnResponseType> {\n middleware: <const TNewMiddlewares = undefined>(\n middlewares: Constrain<\n TNewMiddlewares,\n ReadonlyArray<AnyFunctionMiddleware>\n >,\n ) => FunctionMiddlewareAfterMiddleware<TNewMiddlewares, TServerFnResponseType>\n}\n\nexport interface FunctionMiddlewareAfterMiddleware<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n undefined,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, undefined, TServerFnResponseType>,\n FunctionMiddlewareValidator<TMiddlewares, TServerFnResponseType> {}\n\nexport interface FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n _types: FunctionMiddlewareTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext\n >\n options: FunctionMiddlewareOptions<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareTypes<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TServerSendContext,\n in out TClientContext,\n in out TClientSendContext,\n> {\n type: 'function'\n middlewares: TMiddlewares\n input: ResolveValidatorInput<TValidator>\n allInput: IntersectAllValidatorInputs<TMiddlewares, TValidator>\n output: ResolveValidatorOutput<TValidator>\n allOutput: IntersectAllValidatorOutputs<TMiddlewares, TValidator>\n clientContext: TClientContext\n allClientContextBeforeNext: AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext\n >\n allClientContextAfterNext: AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext,\n TClientSendContext\n >\n serverContext: TServerContext\n serverSendContext: TServerSendContext\n allServerSendContext: AssignAllServerSendContext<\n TMiddlewares,\n TServerSendContext\n >\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext\n >\n clientSendContext: TClientSendContext\n allClientSendContext: AssignAllClientSendContext<\n TMiddlewares,\n TClientSendContext\n >\n validator: TValidator\n}\n\n/**\n * Recursively resolve the input type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorInputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allInput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allInput'>,\n ResolveValidatorInput<TValidator>\n >\n\nexport type IntersectAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? IntersectAllMiddleware<\n TRest,\n TType,\n IntersectAssign<\n TAcc,\n TMiddleware['_types'][TType & keyof TMiddleware['_types']]\n >\n >\n : TAcc\n : TAcc\n\nexport type AnyFunctionMiddleware = FunctionMiddlewareWithTypes<\n any,\n any,\n any,\n any,\n any,\n any,\n any\n>\n\n/**\n * Recursively merge the output type produced by a sequence of middleware\n */\nexport type IntersectAllValidatorOutputs<TMiddlewares, TValidator> =\n unknown extends TValidator\n ? TValidator\n : TValidator extends undefined\n ? IntersectAllMiddleware<TMiddlewares, 'allOutput'>\n : IntersectAssign<\n IntersectAllMiddleware<TMiddlewares, 'allOutput'>,\n ResolveValidatorOutput<TValidator>\n >\n\n/**\n * Recursively resolve the client context type produced by a sequence of middleware\n */\nexport type AssignAllClientContextBeforeNext<\n TMiddlewares,\n TClientContext = undefined,\n> = unknown extends TClientContext\n ? TClientContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextBeforeNext'>,\n TClientContext\n >\n\nexport type AssignAllMiddleware<\n TMiddlewares,\n TType extends\n | keyof AnyFunctionMiddleware['_types']\n | keyof AnyRequestMiddleware['_types'],\n TAcc = undefined,\n> = TMiddlewares extends readonly [infer TMiddleware, ...infer TRest]\n ? TMiddleware extends AnyFunctionMiddleware | AnyRequestMiddleware\n ? AssignAllMiddleware<\n TRest,\n TType,\n Assign<TAcc, TMiddleware['_types'][TType & keyof TMiddleware['_types']]>\n >\n : TAcc\n : TAcc\n\nexport type AssignAllClientContextAfterNext<\n TMiddlewares,\n TClientContext = undefined,\n TSendContext = undefined,\n> = unknown extends TClientContext\n ? Assign<TClientContext, TSendContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientContextAfterNext'>,\n Assign<TClientContext, TSendContext>\n >\n\nexport type AssignAllServerSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerSendContext'>,\n TSendContext\n >\n\n/**\n * Recursively resolve the server context type produced by a sequence of middleware\n */\nexport type AssignAllServerContext<\n TMiddlewares,\n TSendContext = undefined,\n TServerContext = undefined,\n> = unknown extends TSendContext\n ? Assign<TSendContext, TServerContext>\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allServerContext'>,\n Assign<TSendContext, TServerContext>\n >\n\nexport type AssignAllClientSendContext<\n TMiddlewares,\n TSendContext = undefined,\n> = unknown extends TSendContext\n ? TSendContext\n : Assign<\n AssignAllMiddleware<TMiddlewares, 'allClientSendContext'>,\n TSendContext\n >\n\nexport interface FunctionMiddlewareOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerContext,\n in out TClientContext,\n in out TServerFnResponseType extends ServerFnResponseType,\n> {\n validateClient?: boolean\n middleware?: TMiddlewares\n validator?: ConstrainValidator<TValidator>\n client?: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n TClientContext,\n TServerFnResponseType\n >\n server?: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerContext,\n unknown,\n unknown,\n TServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientNextFn<TMiddlewares> = <\n TSendContext = undefined,\n TNewClientContext = undefined,\n>(ctx?: {\n context?: TNewClientContext\n sendContext?: SerializerStringify<TSendContext>\n headers?: HeadersInit\n}) => Promise<\n FunctionClientResultWithContext<TMiddlewares, TSendContext, TNewClientContext>\n>\n\nexport interface FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n server: <TNewServerContext = undefined, TSendContext = undefined>(\n server: FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType\n >,\n ) => FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TNewServerContext,\n TServerSendContext,\n TClientContext,\n TSendContext,\n ServerFnResponseType\n >\n}\nexport type FunctionMiddlewareServerFn<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TNewServerContext,\n TSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> = (\n options: FunctionMiddlewareServerFnOptions<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TServerFnResponseType\n >,\n) => FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n>\n\nexport interface RequestMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TServerSendContext,\n> {\n request: Request\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: Response\n method: Method\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext> = <\n TNewServerContext = undefined,\n TSendContext = undefined,\n>(ctx?: {\n context?: TNewServerContext\n sendContext?: SerializerStringify<TSendContext>\n}) => Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TNewServerContext,\n TSendContext\n >\n>\n\nexport type FunctionServerResultWithContext<\n in out TMiddlewares,\n in out TServerSendContext,\n in out TServerContext,\n in out TSendContext,\n> = {\n 'use functions must return the result of next()': true\n _types: {\n context: TServerContext\n sendContext: TSendContext\n }\n context: Expand<\n AssignAllServerContext<TMiddlewares, TServerSendContext, TServerContext>\n >\n sendContext: Expand<AssignAllClientSendContext<TMiddlewares, TSendContext>>\n}\n\nexport interface FunctionMiddlewareServerFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerSendContext,\n in out TServerFnResponseType,\n> {\n data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllServerContext<TMiddlewares, TServerSendContext>>\n next: FunctionMiddlewareServerNextFn<TMiddlewares, TServerSendContext>\n response: TServerFnResponseType\n method: Method\n filename: string\n functionId: string\n signal: AbortSignal\n}\n\nexport type FunctionMiddlewareServerFnResult<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext,\n> =\n | Promise<\n FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n >\n | FunctionServerResultWithContext<\n TMiddlewares,\n TServerSendContext,\n TServerContext,\n TSendContext\n >\n\nexport interface FunctionMiddlewareAfterServer<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n TServerContext,\n TServerSendContext,\n TClientContext,\n TClientSendContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareClient<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n TRouter extends AnyRouter = RegisteredRouter,\n> {\n client: <TSendServerContext = undefined, TNewClientContext = undefined>(\n client: FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n TServerFnResponseType,\n TRouter\n >,\n ) => FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TSendServerContext,\n TNewClientContext,\n ServerFnResponseType\n >\n}\n\nexport type FunctionMiddlewareClientFn<\n TMiddlewares,\n TValidator,\n TSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n TRouter extends AnyRouter = RegisteredRouter,\n> = (\n options: FunctionMiddlewareClientFnOptions<\n TMiddlewares,\n TValidator,\n TServerFnResponseType,\n TRouter\n >,\n) => FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext\n>\n\nexport interface FunctionMiddlewareClientFnOptions<\n in out TMiddlewares,\n in out TValidator,\n in out TServerFnResponseType extends ServerFnResponseType,\n in out TRouter extends AnyRouter,\n> {\n data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>\n context: Expand<AssignAllClientContextBeforeNext<TMiddlewares>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares>>\n method: Method\n response: TServerFnResponseType\n signal: AbortSignal\n next: FunctionMiddlewareClientNextFn<TMiddlewares>\n filename: string\n functionId: string\n type: ServerFnTypeOrTypeFn<\n Method,\n TServerFnResponseType,\n TMiddlewares,\n TValidator\n >\n router: TRouter\n}\n\nexport type FunctionMiddlewareClientFnResult<\n TMiddlewares,\n TSendContext,\n TClientContext,\n> =\n | Promise<\n FunctionClientResultWithContext<\n TMiddlewares,\n TSendContext,\n TClientContext\n >\n >\n | FunctionClientResultWithContext<TMiddlewares, TSendContext, TClientContext>\n\nexport type FunctionClientResultWithContext<\n in out TMiddlewares,\n in out TSendContext,\n in out TClientContext,\n> = {\n 'use functions must return the result of next()': true\n context: Expand<AssignAllClientContextAfterNext<TMiddlewares, TClientContext>>\n sendContext: Expand<AssignAllServerSendContext<TMiddlewares, TSendContext>>\n headers: HeadersInit\n}\n\nexport interface FunctionMiddlewareAfterClient<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n TServerSendContext,\n TClientContext,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n TServerSendContext,\n TClientContext,\n TServerFnResponseType\n > {}\n\nexport interface FunctionMiddlewareValidator<\n TMiddlewares,\n TServerFnResponseType extends ServerFnResponseType,\n> {\n validator: <TNewValidator>(\n input: ConstrainValidator<TNewValidator>,\n ) => FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TNewValidator,\n TServerFnResponseType\n >\n}\n\nexport interface FunctionMiddlewareAfterValidator<\n TMiddlewares,\n TValidator,\n TServerFnResponseType extends ServerFnResponseType,\n> extends FunctionMiddlewareWithTypes<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n undefined,\n undefined,\n ServerFnResponseType\n >,\n FunctionMiddlewareServer<\n TMiddlewares,\n TValidator,\n undefined,\n undefined,\n TServerFnResponseType\n >,\n FunctionMiddlewareClient<TMiddlewares, TValidator, ServerFnResponseType> {}\n\nexport interface RequestMiddleware\n extends RequestMiddlewareAfterMiddleware<undefined> {\n middleware: <const TMiddlewares = undefined>(\n middlewares: Constrain<TMiddlewares, ReadonlyArray<AnyRequestMiddleware>>,\n ) => RequestMiddlewareAfterMiddleware<TMiddlewares>\n}\n\nexport type AnyRequestMiddleware = RequestMiddlewareWithTypes<any, any>\n\nexport interface RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {\n _types: RequestMiddlewareTypes<TMiddlewares, TServerContext>\n}\n\nexport interface RequestMiddlewareTypes<TMiddlewares, TServerContext> {\n type: 'request'\n middlewares: TMiddlewares\n serverContext: TServerContext\n allServerContext: AssignAllServerContext<\n TMiddlewares,\n undefined,\n TServerContext\n >\n}\n\nexport interface RequestMiddlewareAfterMiddleware<TMiddlewares>\n extends RequestMiddlewareWithTypes<TMiddlewares, undefined>,\n RequestMiddlewareServer<TMiddlewares> {}\n\nexport interface RequestMiddlewareServer<TMiddlewares> {\n server: <TServerContext = undefined>(\n fn: RequestServerFn<TMiddlewares, TServerContext>,\n ) => RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n}\n\nexport type RequestServerFn<TMiddlewares, TServerContext> = (\n options: RequestServerOptions<TMiddlewares>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerOptions<TMiddlewares> {\n request: Request\n pathname: string\n context: AssignAllServerContext<TMiddlewares>\n next: RequestServerNextFn<TMiddlewares>\n}\n\nexport type RequestServerNextFn<TMiddlewares> = <TServerContext = undefined>(\n options?: RequestServerNextFnOptions<TServerContext>,\n) => RequestMiddlewareServerFnResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerNextFnOptions<TServerContext> {\n context?: TServerContext\n}\n\nexport type RequestMiddlewareServerFnResult<TMiddlewares, TServerContext> =\n | Promise<RequestServerResult<TMiddlewares, TServerContext>>\n | RequestServerResult<TMiddlewares, TServerContext>\n\nexport interface RequestServerResult<TMiddlewares, TServerContext> {\n request: Request\n pathname: string\n context: Expand<\n AssignAllServerContext<TMiddlewares, undefined, TServerContext>\n >\n response: Response\n}\n\nexport interface RequestMiddlewareAfterServer<TMiddlewares, TServerContext>\n extends RequestMiddlewareWithTypes<TMiddlewares, TServerContext> {}\n"],"names":[],"mappings":"AAkBgB,SAAA,iBACd,SAIA,QAO+B;AAE/B,QAAM,kBAAkB;AAAA,IACtB,MAAM;AAAA,IACN,GAAI,UACD;AAAA,EAOL;AAEO,SAAA;AAAA,IACL,SAAS;AAAA,IACT,YAAY,CAAC,eAAoB;AACxB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,WAAY,CAAA;AAAA,MAC/C;AAAA,IACF;AAAA,IACA,WAAW,CAAC,cAAmB;AACtB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,UAAW,CAAA;AAAA,MAC9C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IACF;AAAA,IACA,QAAQ,CAAC,WAAgB;AAChB,aAAA;AAAA,QACL,CAAC;AAAA,QACD,OAAO,OAAO,iBAAiB,EAAE,OAAQ,CAAA;AAAA,MAC3C;AAAA,IAAA;AAAA,EAEJ;AACF;"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { SerializerParse, SerializerStringify, SerializerStringifyBy } from './serializer.js';
|
|
2
|
-
import { AnyValidator, Constrain, Expand, ResolveValidatorInput, Validator } from '@tanstack/router-core';
|
|
2
|
+
import { AnyRouter, AnyValidator, Constrain, Expand, ResolveValidatorInput, Validator } from '@tanstack/router-core';
|
|
3
3
|
import { JsonResponse } from '@tanstack/router-core/ssr/client';
|
|
4
4
|
import { Readable } from 'node:stream';
|
|
5
5
|
import { AnyFunctionMiddleware, AssignAllClientSendContext, AssignAllServerContext, IntersectAllValidatorInputs, IntersectAllValidatorOutputs } from './createMiddleware.js';
|
|
@@ -143,6 +143,7 @@ export type ServerFnMiddlewareOptions = {
|
|
|
143
143
|
context?: any;
|
|
144
144
|
type: ServerFnTypeOrTypeFn<any, any, any, any>;
|
|
145
145
|
functionId: string;
|
|
146
|
+
router?: AnyRouter;
|
|
146
147
|
};
|
|
147
148
|
export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {
|
|
148
149
|
result?: unknown;
|
|
@@ -2,8 +2,14 @@ import invariant from "tiny-invariant";
|
|
|
2
2
|
import warning from "tiny-warning";
|
|
3
3
|
import { isRedirect, isNotFound } from "@tanstack/router-core";
|
|
4
4
|
import { mergeHeaders } from "@tanstack/router-core/ssr/client";
|
|
5
|
+
import { getStartContext } from "@tanstack/start-storage-context";
|
|
5
6
|
import { globalMiddleware } from "./registerGlobalMiddleware.js";
|
|
6
7
|
import { startSerializer } from "./serializer.js";
|
|
8
|
+
import { createIsomorphicFn } from "./createIsomorphicFn.js";
|
|
9
|
+
const getRouterInstance = createIsomorphicFn().client(() => window.__TSR_ROUTER__).server(() => {
|
|
10
|
+
var _a;
|
|
11
|
+
return (_a = getStartContext({ throwIfNotFound: false })) == null ? void 0 : _a.router;
|
|
12
|
+
});
|
|
7
13
|
function createServerFn(options, __opts) {
|
|
8
14
|
const resolvedOptions = __opts || options || {};
|
|
9
15
|
if (typeof resolvedOptions.method === "undefined") {
|
|
@@ -39,7 +45,8 @@ function createServerFn(options, __opts) {
|
|
|
39
45
|
data: opts == null ? void 0 : opts.data,
|
|
40
46
|
headers: opts == null ? void 0 : opts.headers,
|
|
41
47
|
signal: opts == null ? void 0 : opts.signal,
|
|
42
|
-
context: {}
|
|
48
|
+
context: {},
|
|
49
|
+
router: getRouterInstance()
|
|
43
50
|
}).then((d) => {
|
|
44
51
|
if (resolvedOptions.response === "full") {
|
|
45
52
|
return d;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createServerFn.js","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 { mergeHeaders } from '@tanstack/router-core/ssr/client'\nimport { globalMiddleware } from './registerGlobalMiddleware'\n\nimport { startSerializer } from './serializer'\nimport type {\n SerializerParse,\n SerializerStringify,\n SerializerStringifyBy,\n} from './serializer'\nimport type {\n AnyValidator,\n Constrain,\n Expand,\n ResolveValidatorInput,\n Validator,\n} from '@tanstack/router-core'\nimport type { JsonResponse } from '@tanstack/router-core/ssr/client'\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 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"],"mappings":";;;;;;AAiCgB,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,QAAW,OAAO,OAAO,iBAAiB,EAAE,UAAA,CAAW,CAAC;AAAA,IAC5D;AAAA,IACA,MAAM,CAAC,SAAS;AACP,aAA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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,YACE;AAAA,YACA;AAAA,UACF;AAEA,gBAAM,SAAS,MAAM,oBAAoB,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
|
+
{"version":3,"file":"createServerFn.js","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 { mergeHeaders } from '@tanstack/router-core/ssr/client'\nimport { getStartContext } from '@tanstack/start-storage-context'\nimport { globalMiddleware } from './registerGlobalMiddleware'\n\nimport { startSerializer } from './serializer'\n\nimport { createIsomorphicFn } from './createIsomorphicFn'\nimport type {\n SerializerParse,\n SerializerStringify,\n SerializerStringifyBy,\n} from './serializer'\nimport type {\n AnyRouter,\n AnyValidator,\n Constrain,\n Expand,\n ResolveValidatorInput,\n Validator,\n} from '@tanstack/router-core'\nimport type { JsonResponse } from '@tanstack/router-core/ssr/client'\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\nconst getRouterInstance = createIsomorphicFn()\n .client(() => window.__TSR_ROUTER__!)\n .server(() => getStartContext({ throwIfNotFound: false })?.router)\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 router: getRouterInstance(),\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 type CompiledFetcherFnOptions = {\n method: Method\n data: unknown\n response?: ServerFnResponseType\n headers?: HeadersInit\n signal?: AbortSignal\n context?: any\n // router?: AnyRouter\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 router?: AnyRouter\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"],"mappings":";;;;;;;;AAqCA,MAAM,oBAAoB,mBAAmB,EAC1C,OAAO,MAAM,OAAO,cAAe,EACnC,OAAO,MAAA;;AAAM,+BAAgB,EAAE,iBAAiB,MAAO,CAAA,MAA1C,mBAA6C;AAAA,CAAM;AAEnD,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,QAAW,OAAO,OAAO,iBAAiB,EAAE,UAAA,CAAW,CAAC;AAAA,IAC5D;AAAA,IACA,MAAM,CAAC,SAAS;AACP,aAAA,eAML,QAAW,OAAO,OAAO,iBAAiB,EAAE,KAAA,CAAM,CAAC;AAAA,IACvD;AAAA,IACA,SAAS,IAAI,SAAS;AAId,YAAA,CAAC,aAAa,QAAQ,IAAI;AAahC,aAAO,OAAO,iBAAiB;AAAA,QAC7B,GAAG;AAAA,QACH;AAAA,QACA;AAAA,MAAA,CACD;AAED,YAAM,qBAAqB;AAAA,QACzB,GAAI,gBAAgB,cAAc,CAAC;AAAA,QACnC,yBAAyB,eAAe;AAAA,MAC1C;AAKA,aAAO,OAAO;AAAA,QACZ,OAAO,SAAoC;AAElC,iBAAA,kBAAkB,oBAAoB,UAAU;AAAA,YACrD,GAAG;AAAA,YACH,GAAG;AAAA,YACH,MAAM,6BAAM;AAAA,YACZ,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ACA,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;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/start-client-core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.129.0",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -50,7 +50,8 @@
|
|
|
50
50
|
"cookie-es": "^1.2.2",
|
|
51
51
|
"tiny-invariant": "^1.3.3",
|
|
52
52
|
"tiny-warning": "^1.0.3",
|
|
53
|
-
"@tanstack/router-core": "1.
|
|
53
|
+
"@tanstack/router-core": "1.129.0",
|
|
54
|
+
"@tanstack/start-storage-context": "1.129.0"
|
|
54
55
|
},
|
|
55
56
|
"scripts": {}
|
|
56
57
|
}
|
|
@@ -31,6 +31,11 @@ export interface IsomorphicFnBase extends IsomorphicFn {
|
|
|
31
31
|
}
|
|
32
32
|
|
|
33
33
|
// this is a dummy function, it will be replaced by the transformer
|
|
34
|
+
// if we use `createIsomorphicFn` in this library itself, vite tries to execute it before the transformer runs
|
|
35
|
+
// therefore we must return a dummy function that allows calling `server` and `client` method chains.
|
|
34
36
|
export function createIsomorphicFn(): IsomorphicFnBase {
|
|
35
|
-
return
|
|
37
|
+
return {
|
|
38
|
+
server: () => ({ client: () => () => {} }),
|
|
39
|
+
client: () => ({ server: () => () => {} }),
|
|
40
|
+
} as any
|
|
36
41
|
}
|
package/src/createMiddleware.ts
CHANGED
|
@@ -5,10 +5,12 @@ import type {
|
|
|
5
5
|
ServerFnTypeOrTypeFn,
|
|
6
6
|
} from './createServerFn'
|
|
7
7
|
import type {
|
|
8
|
+
AnyRouter,
|
|
8
9
|
Assign,
|
|
9
10
|
Constrain,
|
|
10
11
|
Expand,
|
|
11
12
|
IntersectAssign,
|
|
13
|
+
RegisteredRouter,
|
|
12
14
|
ResolveValidatorInput,
|
|
13
15
|
ResolveValidatorOutput,
|
|
14
16
|
} from '@tanstack/router-core'
|
|
@@ -495,6 +497,7 @@ export interface FunctionMiddlewareClient<
|
|
|
495
497
|
TMiddlewares,
|
|
496
498
|
TValidator,
|
|
497
499
|
TServerFnResponseType extends ServerFnResponseType,
|
|
500
|
+
TRouter extends AnyRouter = RegisteredRouter,
|
|
498
501
|
> {
|
|
499
502
|
client: <TSendServerContext = undefined, TNewClientContext = undefined>(
|
|
500
503
|
client: FunctionMiddlewareClientFn<
|
|
@@ -502,7 +505,8 @@ export interface FunctionMiddlewareClient<
|
|
|
502
505
|
TValidator,
|
|
503
506
|
TSendServerContext,
|
|
504
507
|
TNewClientContext,
|
|
505
|
-
TServerFnResponseType
|
|
508
|
+
TServerFnResponseType,
|
|
509
|
+
TRouter
|
|
506
510
|
>,
|
|
507
511
|
) => FunctionMiddlewareAfterClient<
|
|
508
512
|
TMiddlewares,
|
|
@@ -519,11 +523,13 @@ export type FunctionMiddlewareClientFn<
|
|
|
519
523
|
TSendContext,
|
|
520
524
|
TClientContext,
|
|
521
525
|
TServerFnResponseType extends ServerFnResponseType,
|
|
526
|
+
TRouter extends AnyRouter = RegisteredRouter,
|
|
522
527
|
> = (
|
|
523
528
|
options: FunctionMiddlewareClientFnOptions<
|
|
524
529
|
TMiddlewares,
|
|
525
530
|
TValidator,
|
|
526
|
-
TServerFnResponseType
|
|
531
|
+
TServerFnResponseType,
|
|
532
|
+
TRouter
|
|
527
533
|
>,
|
|
528
534
|
) => FunctionMiddlewareClientFnResult<
|
|
529
535
|
TMiddlewares,
|
|
@@ -535,6 +541,7 @@ export interface FunctionMiddlewareClientFnOptions<
|
|
|
535
541
|
in out TMiddlewares,
|
|
536
542
|
in out TValidator,
|
|
537
543
|
in out TServerFnResponseType extends ServerFnResponseType,
|
|
544
|
+
in out TRouter extends AnyRouter,
|
|
538
545
|
> {
|
|
539
546
|
data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>
|
|
540
547
|
context: Expand<AssignAllClientContextBeforeNext<TMiddlewares>>
|
|
@@ -551,6 +558,7 @@ export interface FunctionMiddlewareClientFnOptions<
|
|
|
551
558
|
TMiddlewares,
|
|
552
559
|
TValidator
|
|
553
560
|
>
|
|
561
|
+
router: TRouter
|
|
554
562
|
}
|
|
555
563
|
|
|
556
564
|
export type FunctionMiddlewareClientFnResult<
|
package/src/createServerFn.ts
CHANGED
|
@@ -2,15 +2,19 @@ import { default as invariant } from 'tiny-invariant'
|
|
|
2
2
|
import { default as warning } from 'tiny-warning'
|
|
3
3
|
import { isNotFound, isRedirect } from '@tanstack/router-core'
|
|
4
4
|
import { mergeHeaders } from '@tanstack/router-core/ssr/client'
|
|
5
|
+
import { getStartContext } from '@tanstack/start-storage-context'
|
|
5
6
|
import { globalMiddleware } from './registerGlobalMiddleware'
|
|
6
7
|
|
|
7
8
|
import { startSerializer } from './serializer'
|
|
9
|
+
|
|
10
|
+
import { createIsomorphicFn } from './createIsomorphicFn'
|
|
8
11
|
import type {
|
|
9
12
|
SerializerParse,
|
|
10
13
|
SerializerStringify,
|
|
11
14
|
SerializerStringifyBy,
|
|
12
15
|
} from './serializer'
|
|
13
16
|
import type {
|
|
17
|
+
AnyRouter,
|
|
14
18
|
AnyValidator,
|
|
15
19
|
Constrain,
|
|
16
20
|
Expand,
|
|
@@ -31,6 +35,10 @@ import type {
|
|
|
31
35
|
|
|
32
36
|
type TODO = any
|
|
33
37
|
|
|
38
|
+
const getRouterInstance = createIsomorphicFn()
|
|
39
|
+
.client(() => window.__TSR_ROUTER__!)
|
|
40
|
+
.server(() => getStartContext({ throwIfNotFound: false })?.router)
|
|
41
|
+
|
|
34
42
|
export function createServerFn<
|
|
35
43
|
TMethod extends Method,
|
|
36
44
|
TServerFnResponseType extends ServerFnResponseType = 'data',
|
|
@@ -133,6 +141,7 @@ export function createServerFn<
|
|
|
133
141
|
headers: opts?.headers,
|
|
134
142
|
signal: opts?.signal,
|
|
135
143
|
context: {},
|
|
144
|
+
router: getRouterInstance(),
|
|
136
145
|
}).then((d) => {
|
|
137
146
|
if (resolvedOptions.response === 'full') {
|
|
138
147
|
return d
|
|
@@ -289,6 +298,7 @@ export type CompiledFetcherFnOptions = {
|
|
|
289
298
|
headers?: HeadersInit
|
|
290
299
|
signal?: AbortSignal
|
|
291
300
|
context?: any
|
|
301
|
+
// router?: AnyRouter
|
|
292
302
|
}
|
|
293
303
|
|
|
294
304
|
export type Fetcher<
|
|
@@ -851,6 +861,7 @@ export type ServerFnMiddlewareOptions = {
|
|
|
851
861
|
context?: any
|
|
852
862
|
type: ServerFnTypeOrTypeFn<any, any, any, any>
|
|
853
863
|
functionId: string
|
|
864
|
+
router?: AnyRouter
|
|
854
865
|
}
|
|
855
866
|
|
|
856
867
|
export type ServerFnMiddlewareResult = ServerFnMiddlewareOptions & {
|