Open History to see the last commit
1import fs from 'node:fs/promises'
2import path from 'node:path'
3import {
4 createMiddleware,
5 getDefaultSerovalPlugins,
6} from '@tanstack/start-client-core'
7import { fromJSON, toJSONAsync } from 'seroval'
8β
9type StaticCachedResult = {
10 result: any
11 context: any
12}
13β
14/**
15 * This is a simple hash function for generating a hash from a string to make the filenames shorter.
16 *
17 * It is not cryptographically secure (as its using SHA-1) and should not be used for any security purposes.
18 *
19 * It is only used to generate a hash for the static cache filenames.
20 *
21 * @param message - The input string to hash.
22 * @returns A promise that resolves to the SHA-1 hash of the input string in hexadecimal format.
23 *
24 * @example
25 * ```typescript
26 * const hash = await sha1Hash("hello");
27 * console.log(hash); // Outputs the SHA-1 hash of "hello" -> "aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d"
28 * ```
29 */
30async function sha1Hash(message: string): Promise<string> {
31 // Encode the string as UTF-8
32 const msgBuffer = new TextEncoder().encode(message)
33β
34 // Hash the message
35 const hashBuffer = await crypto.subtle.digest('SHA-1', msgBuffer)
36β
37 // Convert the ArrayBuffer to a string
38 const hashArray = Array.from(new Uint8Array(hashBuffer))
39 const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('')
40 return hashHex
41}
42β
43const getStaticCacheUrl = async (opts: {
44 functionId: string
45 hash: string
46}) => {
47 const filename = await sha1Hash(`${opts.functionId}__${opts.hash}`)
48 return `/__tsr/staticServerFnCache/${filename}.json`
49}
50β
51const jsonToFilenameSafeString = (json: any) => {
52 // Custom replacer to sort keys
53 const sortedKeysReplacer = (key: string, value: any) =>
54 value && typeof value === 'object' && !Array.isArray(value)
55 ? Object.keys(value)
56 .sort()
57 .reduce((acc: any, curr: string) => {
58 acc[curr] = value[curr]
59 return acc
60 }, {})
61 : value
62β
63 // Convert JSON to string with sorted keys
64 const jsonString = JSON.stringify(json ?? '', sortedKeysReplacer)
65β
66 // Replace characters invalid in filenames
67 return jsonString
68 .replace(/[/\\?%*:|"<>]/g, '-') // Replace invalid characters with a dash
69 .replace(/\s+/g, '_') // Optionally replace whitespace with underscores
70}
71β
72const staticClientCache =
73 typeof document !== 'undefined' ? new Map<string, any>() : null
74β
75async function addItemToCache({
76 functionId,
77 data,
78 response,
79}: {
80 functionId: string
81 data: any
82 response: StaticCachedResult
83}): Promise<void> {
84 {
85 const hash = jsonToFilenameSafeString(data)
86 const url = await getStaticCacheUrl({ functionId, hash })
87 const clientUrl = process.env.TSS_CLIENT_OUTPUT_DIR!
88 const filePath = path.join(clientUrl, url)
89β
90 // Ensure the directory exists
91 await fs.mkdir(path.dirname(filePath), { recursive: true })
92β
93 // Store the result with fs
94 const stringifiedResult = JSON.stringify(
95 await toJSONAsync(
96 {
97 result: response.result,
98 context: response.context.sendContext,
99 },
100 { plugins: getDefaultSerovalPlugins() },
101 ),
102 )
103 await fs.writeFile(filePath, stringifiedResult, 'utf-8')
104 }
105}
106β
107const fetchItem = async ({
108 data,
109 functionId,
110}: {
111 data: any
112 functionId: string
113}) => {
114 const hash = jsonToFilenameSafeString(data)
115 const url = await getStaticCacheUrl({ functionId, hash })
116β
117 let result: any = staticClientCache?.get(url)
118β
119 result = await fetch(url, {
120 method: 'GET',
121 })
122 .then((r) => r.json())
123 .then((d) => fromJSON(d, { plugins: getDefaultSerovalPlugins() }))
124β
125 return result
126}
127β
128export const staticFunctionMiddleware = createMiddleware({ type: 'function' })
129 .client(async (ctx) => {
130 if (
131 process.env.NODE_ENV === 'production' &&
132 // do not run this during SSR on the server
133 typeof document !== 'undefined'
134 ) {
135 const response = await fetchItem({
136 functionId: ctx.functionId,
137 data: ctx.data,
138 })
139β
140 if (response) {
141 return {
142 result: response.result,
143 context: { ...(ctx as any).context, ...response.context },
144 } as any
145 }
146 }
147 return ctx.next()
148 })
149 .server(async (ctx) => {
150 const response = await ctx.next()
151 if (process.env.NODE_ENV === 'production') {
152 await addItemToCache({
153 functionId: ctx.functionId,
154 response: { result: (response as any).result, context: ctx },
155 data: ctx.data,
156 })
157 }
158β
159 return response
160 })