-
-
Notifications
You must be signed in to change notification settings - Fork 895
/
Copy pathcreateServerFn.ts
945 lines (833 loc) · 24.6 KB
/
createServerFn.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
import { default as invariant } from 'tiny-invariant'
import { default as warning } from 'tiny-warning'
import { isNotFound, isRedirect } from '@tanstack/react-router'
import { normalizeValidatorIssues } from '@tanstack/router-core'
import { mergeHeaders } from './headers'
import { globalMiddleware } from './registerGlobalMiddleware'
import { startSerializer } from './serializer'
import type { Readable } from 'node:stream'
import type {
AnyValidator,
Constrain,
Expand,
ResolveValidatorInput,
SerializerParse,
SerializerStringify,
SerializerStringifyBy,
Validator,
} from '@tanstack/router-core'
import type {
AnyMiddleware,
AssignAllClientSendContext,
AssignAllServerContext,
IntersectAllValidatorInputs,
IntersectAllValidatorOutputs,
MiddlewareClientFnResult,
MiddlewareServerFnResult,
} from './createMiddleware'
export interface JsonResponse<TData> extends Response {
json: () => Promise<TData>
}
export type CompiledFetcherFnOptions = {
method: Method
data: unknown
response?: ServerFnResponseType
headers?: HeadersInit
signal?: AbortSignal
context?: any
}
export type Fetcher<
TMiddlewares,
TValidator,
TResponse,
TServerFnResponseType extends ServerFnResponseType,
> =
undefined extends IntersectAllValidatorInputs<TMiddlewares, TValidator>
? OptionalFetcher<
TMiddlewares,
TValidator,
TResponse,
TServerFnResponseType
>
: RequiredFetcher<
TMiddlewares,
TValidator,
TResponse,
TServerFnResponseType
>
export interface FetcherBase {
url: string
__executeServer: (opts: {
method: Method
response?: ServerFnResponseType
data: unknown
headers?: HeadersInit
context?: any
signal: AbortSignal
}) => Promise<unknown>
}
export type FetchResult<
TMiddlewares,
TResponse,
TServerFnResponseType extends ServerFnResponseType,
> = TServerFnResponseType extends 'raw'
? Promise<Response>
: TServerFnResponseType extends 'full'
? Promise<FullFetcherData<TMiddlewares, TResponse>>
: Promise<FetcherData<TResponse>>
export interface OptionalFetcher<
TMiddlewares,
TValidator,
TResponse,
TServerFnResponseType extends ServerFnResponseType,
> extends FetcherBase {
(
options?: OptionalFetcherDataOptions<TMiddlewares, TValidator>,
): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>
}
export interface RequiredFetcher<
TMiddlewares,
TValidator,
TResponse,
TServerFnResponseType extends ServerFnResponseType,
> extends FetcherBase {
(
opts: RequiredFetcherDataOptions<TMiddlewares, TValidator>,
): FetchResult<TMiddlewares, TResponse, TServerFnResponseType>
}
export type FetcherBaseOptions = {
headers?: HeadersInit
type?: ServerFnType
signal?: AbortSignal
}
export type ServerFnType = 'static' | 'dynamic'
export interface OptionalFetcherDataOptions<TMiddlewares, TValidator>
extends FetcherBaseOptions {
data?: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>
}
export interface RequiredFetcherDataOptions<TMiddlewares, TValidator>
extends FetcherBaseOptions {
data: Expand<IntersectAllValidatorInputs<TMiddlewares, TValidator>>
}
export interface FullFetcherData<TMiddlewares, TResponse> {
error: unknown
result: FetcherData<TResponse>
context: AssignAllClientSendContext<TMiddlewares>
}
export type FetcherData<TResponse> =
TResponse extends JsonResponse<any>
? SerializerParse<ReturnType<TResponse['json']>>
: SerializerParse<TResponse>
export type RscStream<T> = {
__cacheState: T
}
export type Method = 'GET' | 'POST'
export type ServerFnResponseType = 'data' | 'full' | 'raw'
// see https://h3.unjs.io/guide/event-handler#responses-types
export type RawResponse = Response | ReadableStream | Readable | null | string
export type ServerFnReturnType<
TServerFnResponseType extends ServerFnResponseType,
TResponse,
> = TServerFnResponseType extends 'raw'
? RawResponse | Promise<RawResponse>
: Promise<SerializerStringify<TResponse>> | SerializerStringify<TResponse>
export type ServerFn<
TMethod,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
TResponse,
> = (
ctx: ServerFnCtx<TMethod, TServerFnResponseType, TMiddlewares, TValidator>,
) => ServerFnReturnType<TServerFnResponseType, TResponse>
export interface ServerFnCtx<
TMethod,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
> {
method: TMethod
response: TServerFnResponseType
data: Expand<IntersectAllValidatorOutputs<TMiddlewares, TValidator>>
context: Expand<AssignAllServerContext<TMiddlewares>>
signal: AbortSignal
}
export type CompiledFetcherFn<
TResponse,
TServerFnResponseType extends ServerFnResponseType,
> = {
(
opts: CompiledFetcherFnOptions &
ServerFnBaseOptions<Method, TServerFnResponseType>,
): Promise<TResponse>
url: string
}
type ServerFnBaseOptions<
TMethod extends Method = 'GET',
TServerFnResponseType extends ServerFnResponseType = 'data',
TResponse = unknown,
TMiddlewares = unknown,
TInput = unknown,
> = {
method: TMethod
response?: TServerFnResponseType
validateClient?: boolean
middleware?: Constrain<TMiddlewares, ReadonlyArray<AnyMiddleware>>
validator?: ConstrainValidator<TInput>
extractedFn?: CompiledFetcherFn<TResponse, TServerFnResponseType>
serverFn?: ServerFn<
TMethod,
TServerFnResponseType,
TMiddlewares,
TInput,
TResponse
>
functionId: string
type: ServerFnTypeOrTypeFn<
TMethod,
TServerFnResponseType,
TMiddlewares,
AnyValidator
>
}
export type ValidatorSerializerStringify<TValidator> = Validator<
SerializerStringifyBy<
ResolveValidatorInput<TValidator>,
Date | undefined | FormData
>,
any
>
export type ConstrainValidator<TValidator> = unknown extends TValidator
? TValidator
: Constrain<TValidator, ValidatorSerializerStringify<TValidator>>
export interface ServerFnMiddleware<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TValidator,
> {
middleware: <const TNewMiddlewares = undefined>(
middlewares: Constrain<TNewMiddlewares, ReadonlyArray<AnyMiddleware>>,
) => ServerFnAfterMiddleware<
TMethod,
TServerFnResponseType,
TNewMiddlewares,
TValidator
>
}
export interface ServerFnAfterMiddleware<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
> extends ServerFnValidator<TMethod, TServerFnResponseType, TMiddlewares>,
ServerFnTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>,
ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {}
export type ValidatorFn<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
> = <TValidator>(
validator: ConstrainValidator<TValidator>,
) => ServerFnAfterValidator<
TMethod,
TServerFnResponseType,
TMiddlewares,
TValidator
>
export interface ServerFnValidator<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
> {
validator: ValidatorFn<TMethod, TServerFnResponseType, TMiddlewares>
}
export interface ServerFnAfterValidator<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
> extends ServerFnMiddleware<TMethod, TServerFnResponseType, TValidator>,
ServerFnTyper<TMethod, TServerFnResponseType, TMiddlewares, TValidator>,
ServerFnHandler<TMethod, TServerFnResponseType, TMiddlewares, TValidator> {}
// Typer
export interface ServerFnTyper<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
> {
type: (
typer: ServerFnTypeOrTypeFn<
TMethod,
TServerFnResponseType,
TMiddlewares,
TValidator
>,
) => ServerFnAfterTyper<
TMethod,
TServerFnResponseType,
TMiddlewares,
TValidator
>
}
export type ServerFnTypeOrTypeFn<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
> =
| ServerFnType
| ((
ctx: ServerFnCtx<
TMethod,
TServerFnResponseType,
TMiddlewares,
TValidator
>,
) => ServerFnType)
export interface ServerFnAfterTyper<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
> extends ServerFnHandler<
TMethod,
TServerFnResponseType,
TMiddlewares,
TValidator
> {}
// Handler
export interface ServerFnHandler<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType,
TMiddlewares,
TValidator,
> {
handler: <TNewResponse>(
fn?: ServerFn<
TMethod,
TServerFnResponseType,
TMiddlewares,
TValidator,
TNewResponse
>,
) => Fetcher<TMiddlewares, TValidator, TNewResponse, TServerFnResponseType>
}
export interface ServerFnBuilder<
TMethod extends Method = 'GET',
TServerFnResponseType extends ServerFnResponseType = 'data',
> extends ServerFnMiddleware<TMethod, TServerFnResponseType, undefined>,
ServerFnValidator<TMethod, TServerFnResponseType, undefined>,
ServerFnTyper<TMethod, TServerFnResponseType, undefined, undefined>,
ServerFnHandler<TMethod, TServerFnResponseType, undefined, undefined> {
options: ServerFnBaseOptions<
TMethod,
TServerFnResponseType,
unknown,
undefined,
undefined
>
}
type StaticCachedResult = {
ctx?: {
result: any
context: any
}
error?: any
}
export type ServerFnStaticCache = {
getItem: (
ctx: MiddlewareResult,
) => StaticCachedResult | Promise<StaticCachedResult | undefined>
setItem: (
ctx: MiddlewareResult,
response: StaticCachedResult,
) => Promise<void>
fetchItem: (
ctx: MiddlewareResult,
) => StaticCachedResult | Promise<StaticCachedResult | undefined>
}
let serverFnStaticCache: ServerFnStaticCache | undefined
export function setServerFnStaticCache(
cache?: ServerFnStaticCache | (() => ServerFnStaticCache | undefined),
) {
const previousCache = serverFnStaticCache
serverFnStaticCache = typeof cache === 'function' ? cache() : cache
return () => {
serverFnStaticCache = previousCache
}
}
export function createServerFnStaticCache(
serverFnStaticCache: ServerFnStaticCache,
) {
return serverFnStaticCache
}
setServerFnStaticCache(() => {
const getStaticCacheUrl = (options: MiddlewareResult, hash: string) => {
return `/__tsr/staticServerFnCache/${options.functionId}__${hash}.json`
}
const jsonToFilenameSafeString = (json: any) => {
// Custom replacer to sort keys
const sortedKeysReplacer = (key: string, value: any) =>
value && typeof value === 'object' && !Array.isArray(value)
? Object.keys(value)
.sort()
.reduce((acc: any, curr: string) => {
acc[curr] = value[curr]
return acc
}, {})
: value
// Convert JSON to string with sorted keys
const jsonString = JSON.stringify(json ?? '', sortedKeysReplacer)
// Replace characters invalid in filenames
return jsonString
.replace(/[/\\?%*:|"<>]/g, '-') // Replace invalid characters with a dash
.replace(/\s+/g, '_') // Optionally replace whitespace with underscores
}
const staticClientCache =
typeof document !== 'undefined' ? new Map<string, any>() : null
return createServerFnStaticCache({
getItem: async (ctx) => {
if (typeof document === 'undefined') {
const hash = jsonToFilenameSafeString(ctx.data)
const url = getStaticCacheUrl(ctx, hash)
const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR!
// Use fs instead of fetch to read from filesystem
const { promises: fs } = await import('node:fs')
const path = await import('node:path')
const filePath = path.join(publicUrl, url)
const [cachedResult, readError] = await fs
.readFile(filePath, 'utf-8')
.then((c) => [
startSerializer.parse(c) as {
ctx: unknown
error: any
},
null,
])
.catch((e) => [null, e])
if (readError && readError.code !== 'ENOENT') {
throw readError
}
return cachedResult as StaticCachedResult
}
return undefined
},
setItem: async (ctx, response) => {
const { promises: fs } = await import('node:fs')
const path = await import('node:path')
const hash = jsonToFilenameSafeString(ctx.data)
const url = getStaticCacheUrl(ctx, hash)
const publicUrl = process.env.TSS_OUTPUT_PUBLIC_DIR!
const filePath = path.join(publicUrl, url)
// Ensure the directory exists
await fs.mkdir(path.dirname(filePath), { recursive: true })
// Store the result with fs
await fs.writeFile(filePath, startSerializer.stringify(response))
},
fetchItem: async (ctx) => {
const hash = jsonToFilenameSafeString(ctx.data)
const url = getStaticCacheUrl(ctx, hash)
let result: any = staticClientCache?.get(url)
if (!result) {
result = await fetch(url, {
method: 'GET',
})
.then((r) => r.text())
.then((d) => startSerializer.parse(d))
staticClientCache?.set(url, result)
}
return result
},
})
})
export function createServerFn<
TMethod extends Method,
TServerFnResponseType extends ServerFnResponseType = 'data',
TResponse = unknown,
TMiddlewares = undefined,
TValidator = undefined,
>(
options?: {
method?: TMethod
response?: TServerFnResponseType
type?: ServerFnType
},
__opts?: ServerFnBaseOptions<
TMethod,
TServerFnResponseType,
TResponse,
TMiddlewares,
TValidator
>,
): ServerFnBuilder<TMethod, TServerFnResponseType> {
const resolvedOptions = (__opts || options || {}) as ServerFnBaseOptions<
TMethod,
ServerFnResponseType,
TResponse,
TMiddlewares,
TValidator
>
if (typeof resolvedOptions.method === 'undefined') {
resolvedOptions.method = 'GET' as TMethod
}
return {
options: resolvedOptions as any,
middleware: (middleware) => {
return createServerFn<
TMethod,
ServerFnResponseType,
TResponse,
TMiddlewares,
TValidator
>(undefined, Object.assign(resolvedOptions, { middleware })) as any
},
validator: (validator) => {
return createServerFn<
TMethod,
ServerFnResponseType,
TResponse,
TMiddlewares,
TValidator
>(undefined, Object.assign(resolvedOptions, { validator })) as any
},
type: (type) => {
return createServerFn<
TMethod,
ServerFnResponseType,
TResponse,
TMiddlewares,
TValidator
>(undefined, Object.assign(resolvedOptions, { type })) as any
},
handler: (...args) => {
// This function signature changes due to AST transformations
// in the babel plugin. We need to cast it to the correct
// function signature post-transformation
const [extractedFn, serverFn] = args as unknown as [
CompiledFetcherFn<TResponse, TServerFnResponseType>,
ServerFn<
TMethod,
TServerFnResponseType,
TMiddlewares,
TValidator,
TResponse
>,
]
// Keep the original function around so we can use it
// in the server environment
Object.assign(resolvedOptions, {
...extractedFn,
extractedFn,
serverFn,
})
const resolvedMiddleware = [
...(resolvedOptions.middleware || []),
serverFnBaseToMiddleware(resolvedOptions),
]
// We want to make sure the new function has the same
// properties as the original function
return Object.assign(
async (opts?: CompiledFetcherFnOptions) => {
// Start by executing the client-side middleware chain
return executeMiddleware(resolvedMiddleware, 'client', {
...extractedFn,
...resolvedOptions,
data: opts?.data as any,
headers: opts?.headers,
signal: opts?.signal,
context: {},
}).then((d) => {
if (resolvedOptions.response === 'full') {
return d
}
if (d.error) throw d.error
return d.result
})
},
{
// This copies over the URL, function ID
...extractedFn,
// The extracted function on the server-side calls
// this function
__executeServer: async (opts_: any, signal: AbortSignal) => {
const opts =
opts_ instanceof FormData ? extractFormDataContext(opts_) : opts_
opts.type =
typeof resolvedOptions.type === 'function'
? resolvedOptions.type(opts)
: resolvedOptions.type
const ctx = {
...extractedFn,
...opts,
signal,
}
const run = () =>
executeMiddleware(resolvedMiddleware, 'server', ctx).then(
(d) => ({
// Only send the result and sendContext back to the client
result: d.result,
error: d.error,
context: d.sendContext,
}),
)
if (ctx.type === 'static') {
let response: StaticCachedResult | undefined
// If we can get the cached item, try to get it
if (serverFnStaticCache?.getItem) {
// If this throws, it's okay to let it bubble up
response = await serverFnStaticCache.getItem(ctx)
}
if (!response) {
// If there's no cached item, execute the server function
response = await run()
.then((d) => {
return {
ctx: d,
error: null,
}
})
.catch((e) => {
return {
ctx: undefined,
error: e,
}
})
if (serverFnStaticCache?.setItem) {
await serverFnStaticCache.setItem(ctx, response)
}
}
invariant(
response,
'No response from both server and static cache!',
)
if (response.error) {
throw response.error
}
return response.ctx
}
return run()
},
},
) as any
},
}
}
function extractFormDataContext(formData: FormData) {
const serializedContext = formData.get('__TSR_CONTEXT')
formData.delete('__TSR_CONTEXT')
if (typeof serializedContext !== 'string') {
return {
context: {},
data: formData,
}
}
try {
const context = startSerializer.parse(serializedContext)
return {
context,
data: formData,
}
} catch {
return {
data: formData,
}
}
}
function flattenMiddlewares(
middlewares: Array<AnyMiddleware>,
): Array<AnyMiddleware> {
const seen = new Set<AnyMiddleware>()
const flattened: Array<AnyMiddleware> = []
const recurse = (middleware: Array<AnyMiddleware>) => {
middleware.forEach((m) => {
if (m.options.middleware) {
recurse(m.options.middleware)
}
if (!seen.has(m)) {
seen.add(m)
flattened.push(m)
}
})
}
recurse(middlewares)
return flattened
}
export type MiddlewareOptions = {
method: Method
response?: ServerFnResponseType
data: any
headers?: HeadersInit
signal?: AbortSignal
sendContext?: any
context?: any
type: ServerFnTypeOrTypeFn<any, any, any, any>
functionId: string
}
export type MiddlewareResult = MiddlewareOptions & {
result?: unknown
error?: unknown
type: ServerFnTypeOrTypeFn<any, any, any, any>
}
export type NextFn = (ctx: MiddlewareResult) => Promise<MiddlewareResult>
export type MiddlewareFn = (
ctx: MiddlewareOptions & {
next: NextFn
},
) => Promise<MiddlewareResult>
const applyMiddleware = async (
middlewareFn: MiddlewareFn,
ctx: MiddlewareOptions,
nextFn: NextFn,
) => {
return middlewareFn({
...ctx,
next: (async (userCtx: MiddlewareResult | undefined = {} as any) => {
// Return the next middleware
return nextFn({
...ctx,
...userCtx,
context: {
...ctx.context,
...userCtx.context,
},
sendContext: {
...ctx.sendContext,
...(userCtx.sendContext ?? {}),
},
headers: mergeHeaders(ctx.headers, userCtx.headers),
result:
userCtx.result !== undefined
? userCtx.result
: ctx.response === 'raw'
? userCtx
: (ctx as any).result,
error: userCtx.error ?? (ctx as any).error,
})
}) as any,
} as any)
}
function execValidator(validator: AnyValidator, input: unknown): unknown {
if (validator == null) return {}
if ('~standard' in validator) {
const result = validator['~standard'].validate(input)
if (result instanceof Promise)
throw new Error('Async validation not supported')
if (result.issues) {
const issues = normalizeValidatorIssues(result.issues)
throw new Error(JSON.stringify(issues, undefined, 2))
}
return result.value
}
if ('parse' in validator) {
return validator.parse(input)
}
if (typeof validator === 'function') {
return validator(input)
}
throw new Error('Invalid validator type!')
}
async function executeMiddleware(
middlewares: Array<AnyMiddleware>,
env: 'client' | 'server',
opts: MiddlewareOptions,
): Promise<MiddlewareResult> {
const flattenedMiddlewares = flattenMiddlewares([
...globalMiddleware,
...middlewares,
])
const next: NextFn = async (ctx) => {
// Get the next middleware
const nextMiddleware = flattenedMiddlewares.shift()
// If there are no more middlewares, return the context
if (!nextMiddleware) {
return ctx
}
if (
nextMiddleware.options.validator &&
(env === 'client' ? nextMiddleware.options.validateClient : true)
) {
// Execute the middleware's input function
ctx.data = await execValidator(nextMiddleware.options.validator, ctx.data)
}
const middlewareFn = (
env === 'client'
? nextMiddleware.options.client
: nextMiddleware.options.server
) as MiddlewareFn | undefined
if (middlewareFn) {
// Execute the middleware
return applyMiddleware(middlewareFn, ctx, async (newCtx) => {
return next(newCtx).catch((error) => {
if (isRedirect(error) || isNotFound(error)) {
return {
...newCtx,
error,
}
}
throw error
})
})
}
return next(ctx)
}
// Start the middleware chain
return next({
...opts,
headers: opts.headers || {},
sendContext: opts.sendContext || {},
context: opts.context || {},
})
}
function serverFnBaseToMiddleware(
options: ServerFnBaseOptions<any, any, any, any, any>,
): AnyMiddleware {
return {
_types: undefined!,
options: {
validator: options.validator,
validateClient: options.validateClient,
client: async ({ next, sendContext, ...ctx }) => {
const payload = {
...ctx,
// switch the sendContext over to context
context: sendContext,
type: typeof ctx.type === 'function' ? ctx.type(ctx) : ctx.type,
} as any
if (
ctx.type === 'static' &&
process.env.NODE_ENV === 'production' &&
typeof document !== 'undefined'
) {
invariant(
serverFnStaticCache,
'serverFnStaticCache.fetchItem is not available!',
)
const result = await serverFnStaticCache.fetchItem(payload)
if (result) {
if (result.error) {
throw result.error
}
return next(result.ctx)
}
warning(
result,
`No static cache item found for ${payload.functionId}__${JSON.stringify(payload.data)}, falling back to server function...`,
)
}
// Execute the extracted function
// but not before serializing the context
const res = await options.extractedFn?.(payload)
return next(res) as unknown as MiddlewareClientFnResult<any, any, any>
},
server: async ({ next, ...ctx }) => {
// Execute the server function
const result = await options.serverFn?.(ctx)
return next({
...ctx,
result,
} as any) as unknown as MiddlewareServerFnResult<any, any, any, any>
},
},
}
}