heliumts 0.9.5 → 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +5 -1
  2. package/dist/bin/helium.js +57 -53
  3. package/dist/bin/helium.js.map +1 -1
  4. package/dist/client/Router.d.ts +2 -2
  5. package/dist/client/Router.d.ts.map +1 -1
  6. package/dist/client/Router.js +32 -29
  7. package/dist/client/Router.js.map +1 -1
  8. package/dist/client/cache.d.ts.map +1 -1
  9. package/dist/client/cache.js +13 -13
  10. package/dist/client/cache.js.map +1 -1
  11. package/dist/client/env.js.map +1 -1
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/index.js.map +1 -1
  14. package/dist/client/routerManifest.d.ts.map +1 -1
  15. package/dist/client/routerManifest.js +18 -29
  16. package/dist/client/routerManifest.js.map +1 -1
  17. package/dist/client/rpcClient.d.ts.map +1 -1
  18. package/dist/client/rpcClient.js +71 -72
  19. package/dist/client/rpcClient.js.map +1 -1
  20. package/dist/client/transitions.d.ts +1 -1
  21. package/dist/client/transitions.d.ts.map +1 -1
  22. package/dist/client/useCall.d.ts.map +1 -1
  23. package/dist/client/useCall.js +4 -1
  24. package/dist/client/useCall.js.map +1 -1
  25. package/dist/client/useFetch.d.ts.map +1 -1
  26. package/dist/client/useFetch.js +48 -92
  27. package/dist/client/useFetch.js.map +1 -1
  28. package/dist/runtime/routeOrder.d.ts +3 -0
  29. package/dist/runtime/routeOrder.d.ts.map +1 -0
  30. package/dist/runtime/routeOrder.js +15 -0
  31. package/dist/runtime/routeOrder.js.map +1 -0
  32. package/dist/server/config.d.ts.map +1 -1
  33. package/dist/server/config.js +51 -26
  34. package/dist/server/config.js.map +1 -1
  35. package/dist/server/defineHTTPRequest.d.ts +1 -1
  36. package/dist/server/defineHTTPRequest.d.ts.map +1 -1
  37. package/dist/server/defineHTTPRequest.js.map +1 -1
  38. package/dist/server/defineWorker.d.ts.map +1 -1
  39. package/dist/server/defineWorker.js +68 -37
  40. package/dist/server/defineWorker.js.map +1 -1
  41. package/dist/server/devServer.d.ts.map +1 -1
  42. package/dist/server/devServer.js +62 -17
  43. package/dist/server/devServer.js.map +1 -1
  44. package/dist/server/httpRouter.d.ts.map +1 -1
  45. package/dist/server/httpRouter.js +138 -43
  46. package/dist/server/httpRouter.js.map +1 -1
  47. package/dist/server/meta.d.ts.map +1 -1
  48. package/dist/server/meta.js +23 -15
  49. package/dist/server/meta.js.map +1 -1
  50. package/dist/server/prodServer.d.ts.map +1 -1
  51. package/dist/server/prodServer.js +79 -23
  52. package/dist/server/prodServer.js.map +1 -1
  53. package/dist/server/rateLimiter.d.ts +9 -0
  54. package/dist/server/rateLimiter.d.ts.map +1 -1
  55. package/dist/server/rateLimiter.js +46 -0
  56. package/dist/server/rateLimiter.js.map +1 -1
  57. package/dist/server/requestHandler.d.ts +4 -0
  58. package/dist/server/requestHandler.d.ts.map +1 -0
  59. package/dist/server/requestHandler.js +20 -0
  60. package/dist/server/requestHandler.js.map +1 -0
  61. package/dist/server/rpcRegistry.d.ts.map +1 -1
  62. package/dist/server/rpcRegistry.js +46 -6
  63. package/dist/server/rpcRegistry.js.map +1 -1
  64. package/dist/server/security.d.ts.map +1 -1
  65. package/dist/server/security.js +3 -2
  66. package/dist/server/security.js.map +1 -1
  67. package/dist/server/serializer.js +11 -6
  68. package/dist/server/serializer.js.map +1 -1
  69. package/dist/server/ssr.d.ts +2 -1
  70. package/dist/server/ssr.d.ts.map +1 -1
  71. package/dist/server/ssr.js +29 -32
  72. package/dist/server/ssr.js.map +1 -1
  73. package/dist/utils/envLoader.js +1 -1
  74. package/dist/utils/envLoader.js.map +1 -1
  75. package/dist/utils/html.d.ts +7 -0
  76. package/dist/utils/html.d.ts.map +1 -0
  77. package/dist/utils/html.js +197 -0
  78. package/dist/utils/html.js.map +1 -0
  79. package/dist/utils/ipExtractor.d.ts +6 -52
  80. package/dist/utils/ipExtractor.d.ts.map +1 -1
  81. package/dist/utils/ipExtractor.js +21 -118
  82. package/dist/utils/ipExtractor.js.map +1 -1
  83. package/dist/vite/heliumPlugin.d.ts.map +1 -1
  84. package/dist/vite/heliumPlugin.js +71 -83
  85. package/dist/vite/heliumPlugin.js.map +1 -1
  86. package/dist/vite/scanner.d.ts +3 -0
  87. package/dist/vite/scanner.d.ts.map +1 -1
  88. package/dist/vite/scanner.js +89 -18
  89. package/dist/vite/scanner.js.map +1 -1
  90. package/dist/vite/ssg.d.ts +4 -0
  91. package/dist/vite/ssg.d.ts.map +1 -1
  92. package/dist/vite/ssg.js +62 -39
  93. package/dist/vite/ssg.js.map +1 -1
  94. package/dist/vite/virtualServerModule.d.ts +1 -1
  95. package/dist/vite/virtualServerModule.d.ts.map +1 -1
  96. package/dist/vite/virtualServerModule.js +28 -16
  97. package/dist/vite/virtualServerModule.js.map +1 -1
  98. package/package.json +12 -7
@@ -90,6 +90,14 @@ export function useFetch(method, args, options) {
90
90
  showLoaderOnInvalidateRef.current = showLoaderOnInvalidate;
91
91
  // Track if component is mounted
92
92
  const isMountedRef = useRef(true);
93
+ const requestIdRef = useRef(0);
94
+ const identityRef = useRef({ key, enabled });
95
+ if (identityRef.current.key !== key || identityRef.current.enabled !== enabled) {
96
+ requestIdRef.current++;
97
+ queuedRefetchRef.current = false;
98
+ queuedRefetchShowLoaderRef.current = false;
99
+ identityRef.current = { key, enabled };
100
+ }
93
101
  const [data, setData] = useState(() => (has(key) ? get(key) : undefined));
94
102
  const [isLoading, setLoading] = useState(!has(key) && enabled);
95
103
  const [error, setError] = useState(null);
@@ -104,81 +112,59 @@ export function useFetch(method, args, options) {
104
112
  if (!isMountedRef.current) {
105
113
  return undefined;
106
114
  }
115
+ const currentKey = keyRef.current;
116
+ const requestId = ++requestIdRef.current;
117
+ const canUpdate = () => isMountedRef.current && keyRef.current === currentKey && requestIdRef.current === requestId;
107
118
  const replayQueuedRefetch = () => {
108
- if (!queuedRefetchRef.current || !isMountedRef.current || !enabledRef.current) {
119
+ if (!queuedRefetchRef.current || !canUpdate() || !enabledRef.current) {
109
120
  return;
110
121
  }
111
122
  const nextShowLoader = queuedRefetchShowLoaderRef.current;
112
123
  queuedRefetchRef.current = false;
113
124
  queuedRefetchShowLoaderRef.current = false;
114
- clearPendingFetch(keyRef.current);
125
+ clearPendingFetch(currentKey);
115
126
  queueMicrotask(() => {
116
- if (!isMountedRef.current || !enabledRef.current) {
117
- return;
127
+ if (canUpdate() && enabledRef.current) {
128
+ void doFetch(nextShowLoader);
118
129
  }
119
- void doFetch(nextShowLoader);
120
130
  });
121
131
  };
122
- const currentKey = keyRef.current;
123
- // Check if there's already a pending fetch for this key (global deduplication)
124
- const existingFetch = getPendingFetch(currentKey);
125
- if (existingFetch) {
126
- // Wait for the existing fetch and use its result
127
- if (showLoader) {
128
- setLoading(true);
129
- }
130
- try {
131
- const result = await existingFetch;
132
- if (isMountedRef.current) {
133
- setData(result.data);
134
- setStats(result.stats);
135
- setError(null);
136
- }
137
- return result.data;
138
- }
139
- catch (err) {
140
- if (isMountedRef.current) {
141
- const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : "Unknown error");
142
- setError(rpcError.message);
143
- setStats(rpcError.stats);
144
- }
145
- return undefined;
146
- }
147
- finally {
148
- if (isMountedRef.current && showLoader) {
149
- setLoading(false);
150
- }
151
- replayQueuedRefetch();
152
- }
153
- }
154
132
  if (showLoader) {
155
133
  setLoading(true);
156
134
  }
157
135
  setError(null);
158
- // Create the fetch promise and register it globally
159
- const fetchPromise = rpcCall(methodIdRef.current, argsRef.current);
160
- const dedupedPromise = setPendingFetch(currentKey, fetchPromise);
136
+ let fetchPromise = getPendingFetch(currentKey);
137
+ if (!fetchPromise) {
138
+ const currentTtl = ttlRef.current;
139
+ // Cache before pending cleanup runs, and only while this request is
140
+ // still registered. An invalidated response must not restore stale data.
141
+ const request = rpcCall(methodIdRef.current, argsRef.current).then((result) => {
142
+ if (getPendingFetch(currentKey) === fetchPromise) {
143
+ set(currentKey, result.data, currentTtl);
144
+ }
145
+ return result;
146
+ });
147
+ fetchPromise = setPendingFetch(currentKey, request);
148
+ }
161
149
  try {
162
- const result = await dedupedPromise;
163
- if (!isMountedRef.current) {
164
- return undefined;
150
+ const result = await fetchPromise;
151
+ if (canUpdate()) {
152
+ setData(result.data);
153
+ setStats(result.stats);
154
+ setError(null);
165
155
  }
166
- set(currentKey, result.data, ttlRef.current);
167
- setData(result.data);
168
- setStats(result.stats);
169
156
  return result.data;
170
157
  }
171
158
  catch (err) {
172
- if (!isMountedRef.current) {
173
- return undefined;
159
+ if (canUpdate()) {
160
+ const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : "Unknown error");
161
+ setError(rpcError.message);
162
+ setStats(rpcError.stats);
174
163
  }
175
- const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : "Unknown error");
176
- setError(rpcError.message);
177
- setStats(rpcError.stats);
178
164
  return undefined;
179
165
  }
180
166
  finally {
181
- if (isMountedRef.current && showLoader) {
167
+ if (canUpdate()) {
182
168
  setLoading(false);
183
169
  }
184
170
  replayQueuedRefetch();
@@ -189,54 +175,24 @@ export function useFetch(method, args, options) {
189
175
  isMountedRef.current = true;
190
176
  return () => {
191
177
  isMountedRef.current = false;
178
+ requestIdRef.current++;
192
179
  };
193
180
  }, []);
194
- // Sync data from cache when key changes
181
+ // Reset result state when the query changes, including cached undefined values.
195
182
  useEffect(() => {
196
- if (has(key)) {
197
- const cachedData = get(key);
198
- if (cachedData !== undefined) {
199
- setData(cachedData);
200
- setLoading(false);
201
- }
202
- }
203
- }, [key]);
204
- // Initial fetch on mount or when key/enabled changes
183
+ setData(get(key));
184
+ setError(null);
185
+ setStats(null);
186
+ setLoading(enabled && !has(key));
187
+ }, [key, enabled]);
188
+ // Joining a pending request goes through the same guarded path as a new fetch.
205
189
  useEffect(() => {
206
190
  if (!enabled) {
207
191
  setLoading(false);
208
192
  return;
209
193
  }
210
- // Only fetch if not in cache and not already pending globally
211
- if (!has(key) && !isPending(key)) {
212
- doFetch(true);
213
- }
214
- else if (isPending(key)) {
215
- // There's a pending fetch - wait for it
216
- setLoading(true);
217
- const pendingFetch = getPendingFetch(key);
218
- if (pendingFetch) {
219
- pendingFetch
220
- .then((result) => {
221
- if (isMountedRef.current) {
222
- setData(result.data);
223
- setStats(result.stats);
224
- setError(null);
225
- }
226
- })
227
- .catch((err) => {
228
- if (isMountedRef.current) {
229
- const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : "Unknown error");
230
- setError(rpcError.message);
231
- setStats(rpcError.stats);
232
- }
233
- })
234
- .finally(() => {
235
- if (isMountedRef.current) {
236
- setLoading(false);
237
- }
238
- });
239
- }
194
+ if (!has(key) || isPending(key)) {
195
+ void doFetch(true);
240
196
  }
241
197
  }, [key, enabled, doFetch]);
242
198
  // Register for focus/visibility refetch
@@ -1 +1 @@
1
- {"version":3,"file":"useFetch.js","sourceRoot":"","sources":["../../src/client/useFetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAGjE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAC7I,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AA2BzC,SAAS,oBAAoB;IACzB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAChC,OAAO,IAAI,GAAG,EAAE,CAAC;IACrB,CAAC;IACD,MAAM,GAAG,GAAG,MAEX,CAAC;IACF,IAAI,CAAC,GAAG,CAAC,sBAAsB,EAAE,CAAC;QAC9B,GAAG,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;IAC3C,CAAC;IACD,O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E,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;IAEjC,0BAA0B;IAC1B,MAAM,OAAO,GAAG,WAAW,CAAC,CAAC,aAAsB,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC;IAE5F,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport type { RpcStats } from \"../runtime/protocol.js\";\nimport { cacheKey, clearPendingFetch, get, getPendingFetch, has, isPending, set, setPendingFetch, subscribeInvalidations } from \"./cache.js\";\nimport { rpcCall } from \"./rpcClient.js\";\nimport { RpcError } from \"./RpcError.js\";\nimport type { MethodStub } from \"./types.js\";\n\n/**\n * Options controlling `useFetch` behaviour.\n *\n * - ttl: optional time-to-live for the cached response (milliseconds).\n * - refetchOnWindowFocus: when true the hook will invalidate cache on\n * window focus/visibility change and re-run the fetch.\n * - showLoaderOnRefocus: when false (default), refetches triggered by window\n * focus/visibility will update data silently without showing the loading state.\n * - showLoaderOnInvalidate: when false (default), refetches triggered by cache\n * invalidation will update data silently without showing the loading state.\n * - enabled: disable automatic fetching (defaults to true) — useful when\n * you only want to fetch when a required value (e.g. id) is present.\n */\nexport interface UseFetchOptions {\n ttl?: number; // TTL in milliseconds\n refetchOnWindowFocus?: boolean; // Whether to refetch when tab becomes visible\n showLoaderOnRefocus?: boolean; // Whether to show loader when refetching on focus (defaults to false)\n showLoaderOnInvalidate?: boolean; // Whether to show loader when refetching on cache invalidation (defaults to false)\n enabled?: boolean; // Whether to fetch data. Defaults to true. Useful for conditional fetching (e.g., only fetch when an ID exists)\n}\n\n// Store focus refetch callbacks globally (survives HMR)\ntype FocusCallback = (showLoader: boolean) => void;\n\nfunction getFocusCallbacksSet(): Set<FocusCallback> {\n if (typeof window === \"undefined\") {\n return new Set();\n }\n const win = window as typeof window & {\n __heliumFocusCallbacks?: Set<FocusCallback>;\n };\n if (!win.__heliumFocusCallbacks) {\n win.__heliumFocusCallbacks = new Set();\n }\n return win.__heliumFocusCallbacks;\n}\n\nfunction getVisibilityState(): { registered: boolean; lastTrigger: number } {\n if (typeof window === \"undefined\") {\n return { registered: false, lastTrigger: 0 };\n }\n const win = window as typeof window & {\n __heliumVisibilityState?: { registered: boolean; lastTrigger: number };\n };\n if (!win.__heliumVisibilityState) {\n win.__heliumVisibilityState = { registered: false, lastTrigger: 0 };\n }\n return win.__heliumVisibilityState;\n}\n\n// Minimum time between focus-triggered refetches (debounce)\nconst FOCUS_DEBOUNCE_MS = 2000;\n\nfunction setupFocusListeners() {\n const state = getVisibilityState();\n if (state.registered || typeof document === \"undefined\") {\n return;\n }\n state.registered = true;\n\n const triggerRefetch = () => {\n const now = Date.now();\n // Debounce to prevent rapid refetches during HMR\n if (now - state.lastTrigger < FOCUS_DEBOUNCE_MS) {\n return;\n }\n state.lastTrigger = now;\n\n // Get all registered callbacks and call them\n const callbacks = getFocusCallbacksSet();\n callbacks.forEach((cb) => {\n try {\n cb(false); // Silent refetch on focus\n } catch {\n // Ignore errors from stale callbacks\n }\n });\n };\n\n const handleVisibilityChange = () => {\n if (!document.hidden) {\n triggerRefetch();\n }\n };\n\n document.addEventListener(\"visibilitychange\", handleVisibilityChange, { passive: true });\n window.addEventListener(\"focus\", triggerRefetch, { passive: true });\n}\n\n/**\n * React hook for fetching and caching the result of a server method.\n *\n * @template TArgs - method argument type\n * @template TResult - expected return type\n * @param method - a MethodStub representing the server method to call\n * @param args - optional argument object passed to the server method\n * @param options - controls caching and refetch behavior (see UseFetchOptions)\n * @returns { data, isLoading, error, stats, refetch } — `data` is the cached or latest value; `refetch` triggers an immediate request\n */\nexport function useFetch<TArgs, TResult>(method: MethodStub<TArgs, TResult>, args?: TArgs, options?: UseFetchOptions) {\n // Compute cache key\n const key = cacheKey(method.__id, args);\n\n const { ttl, refetchOnWindowFocus = true, showLoaderOnRefocus = false, showLoaderOnInvalidate = false, enabled = true } = options ?? {};\n\n // Use refs to store latest values without causing effect re-runs\n const methodIdRef = useRef(method.__id);\n const argsRef = useRef(args);\n const keyRef = useRef(key);\n const ttlRef = useRef(ttl);\n const enabledRef = useRef(enabled);\n const showLoaderOnRefocusRef = useRef(showLoaderOnRefocus);\n const showLoaderOnInvalidateRef = useRef(showLoaderOnInvalidate);\n const queuedRefetchRef = useRef(false);\n const queuedRefetchShowLoaderRef = useRef(false);\n\n // Update refs on each render\n methodIdRef.current = method.__id;\n argsRef.current = args;\n keyRef.current = key;\n ttlRef.current = ttl;\n enabledRef.current = enabled;\n showLoaderOnRefocusRef.current = showLoaderOnRefocus;\n showLoaderOnInvalidateRef.current = showLoaderOnInvalidate;\n\n // Track if component is mounted\n const isMountedRef = useRef(true);\n\n const [data, setData] = useState<TResult | undefined>(() => (has(key) ? get<TResult>(key) : undefined));\n const [isLoading, setLoading] = useState(!has(key) && enabled);\n const [error, setError] = useState<string | null>(null);\n const [stats, setStats] = useState<RpcStats | null>(null);\n\n const queueRefetch = useCallback((showLoader: boolean) => {\n queuedRefetchRef.current = true;\n queuedRefetchShowLoaderRef.current = queuedRefetchShowLoaderRef.current || showLoader;\n }, []);\n\n // Core fetch function using refs (stable reference)\n // Uses global deduplication to prevent multiple fetches for the same key\n const doFetch = useCallback(async (showLoader: boolean = true): Promise<TResult | undefined> => {\n if (!isMountedRef.current) {\n return undefined;\n }\n\n const replayQueuedRefetch = () => {\n if (!queuedRefetchRef.current || !isMountedRef.current || !enabledRef.current) {\n return;\n }\n const nextShowLoader = queuedRefetchShowLoaderRef.current;\n queuedRefetchRef.current = false;\n queuedRefetchShowLoaderRef.current = false;\n clearPendingFetch(keyRef.current);\n queueMicrotask(() => {\n if (!isMountedRef.current || !enabledRef.current) {\n return;\n }\n void doFetch(nextShowLoader);\n });\n };\n\n const currentKey = keyRef.current;\n\n // Check if there's already a pending fetch for this key (global deduplication)\n const existingFetch = getPendingFetch<{ data: TResult; stats: RpcStats }>(currentKey);\n if (existingFetch) {\n // Wait for the existing fetch and use its result\n if (showLoader) {\n setLoading(true);\n }\n try {\n const result = await existingFetch;\n if (isMountedRef.current) {\n setData(result.data);\n setStats(result.stats);\n setError(null);\n }\n return result.data;\n } catch (err: unknown) {\n if (isMountedRef.current) {\n const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : \"Unknown error\");\n setError(rpcError.message);\n setStats(rpcError.stats);\n }\n return undefined;\n } finally {\n if (isMountedRef.current && showLoader) {\n setLoading(false);\n }\n replayQueuedRefetch();\n }\n }\n\n if (showLoader) {\n setLoading(true);\n }\n setError(null);\n\n // Create the fetch promise and register it globally\n const fetchPromise = rpcCall<TResult, TArgs>(methodIdRef.current, argsRef.current as TArgs);\n const dedupedPromise = setPendingFetch(currentKey, fetchPromise);\n\n try {\n const result = await dedupedPromise;\n if (!isMountedRef.current) {\n return undefined;\n }\n set(currentKey, result.data, ttlRef.current);\n setData(result.data);\n setStats(result.stats);\n return result.data;\n } catch (err: unknown) {\n if (!isMountedRef.current) {\n return undefined;\n }\n const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : \"Unknown error\");\n setError(rpcError.message);\n setStats(rpcError.stats);\n return undefined;\n } finally {\n if (isMountedRef.current && showLoader) {\n setLoading(false);\n }\n replayQueuedRefetch();\n }\n }, []); // No dependencies - uses refs\n\n // Track mounted state\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n };\n }, []);\n\n // Sync data from cache when key changes\n useEffect(() => {\n if (has(key)) {\n const cachedData = get<TResult>(key);\n if (cachedData !== undefined) {\n setData(cachedData);\n setLoading(false);\n }\n }\n }, [key]);\n\n // Initial fetch on mount or when key/enabled changes\n useEffect(() => {\n if (!enabled) {\n setLoading(false);\n return;\n }\n\n // Only fetch if not in cache and not already pending globally\n if (!has(key) && !isPending(key)) {\n doFetch(true);\n } else if (isPending(key)) {\n // There's a pending fetch - wait for it\n setLoading(true);\n const pendingFetch = getPendingFetch<{ data: TResult; stats: RpcStats }>(key);\n if (pendingFetch) {\n pendingFetch\n .then((result) => {\n if (isMountedRef.current) {\n setData(result.data);\n setStats(result.stats);\n setError(null);\n }\n })\n .catch((err: unknown) => {\n if (isMountedRef.current) {\n const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : \"Unknown error\");\n setError(rpcError.message);\n setStats(rpcError.stats);\n }\n })\n .finally(() => {\n if (isMountedRef.current) {\n setLoading(false);\n }\n });\n }\n }\n }, [key, enabled, doFetch]);\n\n // Register for focus/visibility refetch\n useEffect(() => {\n if (!refetchOnWindowFocus) {\n return;\n }\n\n // Setup global focus listeners once\n setupFocusListeners();\n\n // Create a stable callback for this hook instance\n const focusCallback: FocusCallback = (showLoader: boolean) => {\n if (!enabledRef.current || !isMountedRef.current) {\n return;\n }\n\n const shouldShowLoader = showLoaderOnRefocusRef.current || showLoader;\n\n if (isPending(keyRef.current)) {\n queueRefetch(shouldShowLoader);\n void doFetch(shouldShowLoader);\n return;\n }\n\n void doFetch(shouldShowLoader);\n };\n\n // Register this callback\n const callbacks = getFocusCallbacksSet();\n callbacks.add(focusCallback);\n\n return () => {\n callbacks.delete(focusCallback);\n };\n }, [refetchOnWindowFocus, doFetch, queueRefetch]);\n\n // Subscribe to cache invalidations (from useCall or manual invalidation)\n useEffect(() => {\n const unsubscribe = subscribeInvalidations((methodId) => {\n if (methodId !== methodIdRef.current || !enabledRef.current || !isMountedRef.current) {\n return;\n }\n\n if (isPending(keyRef.current)) {\n queueRefetch(showLoaderOnInvalidateRef.current);\n void doFetch(showLoaderOnInvalidateRef.current);\n return;\n }\n\n void doFetch(showLoaderOnInvalidateRef.current);\n });\n\n return unsubscribe;\n }, [doFetch, queueRefetch]);\n\n // TTL-based auto-refetch\n useEffect(() => {\n if (!enabled || !ttl) {\n return;\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let isActive = true;\n\n const scheduleRefetch = () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n timeoutId = setTimeout(async () => {\n if (!isActive || !enabledRef.current || !isMountedRef.current) {\n return;\n }\n await doFetch(false); // Silent refetch for TTL\n if (isActive) {\n scheduleRefetch();\n }\n }, ttl);\n };\n\n scheduleRefetch();\n\n return () => {\n isActive = false;\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n };\n }, [key, ttl, enabled, doFetch]);\n\n // Public refetch function\n const refetch = useCallback((showLoader: boolean = true) => doFetch(showLoader), [doFetch]);\n\n return { data, isLoading, error, stats, refetch };\n}\n"]}
1
+ {"version":3,"file":"useFetch.js","sourceRoot":"","sources":["../../src/client/useFetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AAGjE,OAAO,EAAE,QAAQ,EAAE,iBAAiB,EAAE,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,SAAS,EAAE,GAAG,EAAE,eAAe,EAAE,sBAAsB,EAAE,MAAM,YAAY,CAAC;AAC7I,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AACzC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AA2BzC,SAAS,oBAAoB;IACzB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAChC,OAAO,IAAI,GAAG,EAAE,CAAC;IACrB,CAAC;IACD,MAAM,GAAG,GAAG,MAEX,CAAC;IACF,IAAI,CAAC,GAAG,CAAC,sBAAsB,EAAE,CAAC;QAC9B,GAAG,CAAC,sBAAsB,GAAG,IAAI,GAAG,EAAE,CAAC;IAC3C,CAAC;IACD,OAAO,GAAG,CAAC,sBAAsB,CAAC;AACtC,CAAC;AAED,SAAS,kBAAkB;IACvB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAChC,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,WAAW,EAAE,CAAC,E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,SAAS,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { useCallback, useEffect, useRef, useState } from \"react\";\n\nimport type { RpcStats } from \"../runtime/protocol.js\";\nimport { cacheKey, clearPendingFetch, get, getPendingFetch, has, isPending, set, setPendingFetch, subscribeInvalidations } from \"./cache.js\";\nimport { rpcCall } from \"./rpcClient.js\";\nimport { RpcError } from \"./RpcError.js\";\nimport type { MethodStub } from \"./types.js\";\n\n/**\n * Options controlling `useFetch` behaviour.\n *\n * - ttl: optional time-to-live for the cached response (milliseconds).\n * - refetchOnWindowFocus: when true the hook will invalidate cache on\n * window focus/visibility change and re-run the fetch.\n * - showLoaderOnRefocus: when false (default), refetches triggered by window\n * focus/visibility will update data silently without showing the loading state.\n * - showLoaderOnInvalidate: when false (default), refetches triggered by cache\n * invalidation will update data silently without showing the loading state.\n * - enabled: disable automatic fetching (defaults to true) — useful when\n * you only want to fetch when a required value (e.g. id) is present.\n */\nexport interface UseFetchOptions {\n ttl?: number; // TTL in milliseconds\n refetchOnWindowFocus?: boolean; // Whether to refetch when tab becomes visible\n showLoaderOnRefocus?: boolean; // Whether to show loader when refetching on focus (defaults to false)\n showLoaderOnInvalidate?: boolean; // Whether to show loader when refetching on cache invalidation (defaults to false)\n enabled?: boolean; // Whether to fetch data. Defaults to true. Useful for conditional fetching (e.g., only fetch when an ID exists)\n}\n\n// Store focus refetch callbacks globally (survives HMR)\ntype FocusCallback = (showLoader: boolean) => void;\n\nfunction getFocusCallbacksSet(): Set<FocusCallback> {\n if (typeof window === \"undefined\") {\n return new Set();\n }\n const win = window as typeof window & {\n __heliumFocusCallbacks?: Set<FocusCallback>;\n };\n if (!win.__heliumFocusCallbacks) {\n win.__heliumFocusCallbacks = new Set();\n }\n return win.__heliumFocusCallbacks;\n}\n\nfunction getVisibilityState(): { registered: boolean; lastTrigger: number } {\n if (typeof window === \"undefined\") {\n return { registered: false, lastTrigger: 0 };\n }\n const win = window as typeof window & {\n __heliumVisibilityState?: { registered: boolean; lastTrigger: number };\n };\n if (!win.__heliumVisibilityState) {\n win.__heliumVisibilityState = { registered: false, lastTrigger: 0 };\n }\n return win.__heliumVisibilityState;\n}\n\n// Minimum time between focus-triggered refetches (debounce)\nconst FOCUS_DEBOUNCE_MS = 2000;\n\nfunction setupFocusListeners() {\n const state = getVisibilityState();\n if (state.registered || typeof document === \"undefined\") {\n return;\n }\n state.registered = true;\n\n const triggerRefetch = () => {\n const now = Date.now();\n // Debounce to prevent rapid refetches during HMR\n if (now - state.lastTrigger < FOCUS_DEBOUNCE_MS) {\n return;\n }\n state.lastTrigger = now;\n\n // Get all registered callbacks and call them\n const callbacks = getFocusCallbacksSet();\n callbacks.forEach((cb) => {\n try {\n cb(false); // Silent refetch on focus\n } catch {\n // Ignore errors from stale callbacks\n }\n });\n };\n\n const handleVisibilityChange = () => {\n if (!document.hidden) {\n triggerRefetch();\n }\n };\n\n document.addEventListener(\"visibilitychange\", handleVisibilityChange, { passive: true });\n window.addEventListener(\"focus\", triggerRefetch, { passive: true });\n}\n\n/**\n * React hook for fetching and caching the result of a server method.\n *\n * @template TArgs - method argument type\n * @template TResult - expected return type\n * @param method - a MethodStub representing the server method to call\n * @param args - optional argument object passed to the server method\n * @param options - controls caching and refetch behavior (see UseFetchOptions)\n * @returns { data, isLoading, error, stats, refetch } — `data` is the cached or latest value; `refetch` triggers an immediate request\n */\nexport function useFetch<TArgs, TResult>(method: MethodStub<TArgs, TResult>, args?: TArgs, options?: UseFetchOptions) {\n // Compute cache key\n const key = cacheKey(method.__id, args);\n\n const { ttl, refetchOnWindowFocus = true, showLoaderOnRefocus = false, showLoaderOnInvalidate = false, enabled = true } = options ?? {};\n\n // Use refs to store latest values without causing effect re-runs\n const methodIdRef = useRef(method.__id);\n const argsRef = useRef(args);\n const keyRef = useRef(key);\n const ttlRef = useRef(ttl);\n const enabledRef = useRef(enabled);\n const showLoaderOnRefocusRef = useRef(showLoaderOnRefocus);\n const showLoaderOnInvalidateRef = useRef(showLoaderOnInvalidate);\n const queuedRefetchRef = useRef(false);\n const queuedRefetchShowLoaderRef = useRef(false);\n\n // Update refs on each render\n methodIdRef.current = method.__id;\n argsRef.current = args;\n keyRef.current = key;\n ttlRef.current = ttl;\n enabledRef.current = enabled;\n showLoaderOnRefocusRef.current = showLoaderOnRefocus;\n showLoaderOnInvalidateRef.current = showLoaderOnInvalidate;\n\n // Track if component is mounted\n const isMountedRef = useRef(true);\n const requestIdRef = useRef(0);\n const identityRef = useRef({ key, enabled });\n if (identityRef.current.key !== key || identityRef.current.enabled !== enabled) {\n requestIdRef.current++;\n queuedRefetchRef.current = false;\n queuedRefetchShowLoaderRef.current = false;\n identityRef.current = { key, enabled };\n }\n\n const [data, setData] = useState<TResult | undefined>(() => (has(key) ? get<TResult>(key) : undefined));\n const [isLoading, setLoading] = useState(!has(key) && enabled);\n const [error, setError] = useState<string | null>(null);\n const [stats, setStats] = useState<RpcStats | null>(null);\n\n const queueRefetch = useCallback((showLoader: boolean) => {\n queuedRefetchRef.current = true;\n queuedRefetchShowLoaderRef.current = queuedRefetchShowLoaderRef.current || showLoader;\n }, []);\n\n // Core fetch function using refs (stable reference)\n // Uses global deduplication to prevent multiple fetches for the same key\n const doFetch = useCallback(async (showLoader: boolean = true): Promise<TResult | undefined> => {\n if (!isMountedRef.current) {\n return undefined;\n }\n\n const currentKey = keyRef.current;\n const requestId = ++requestIdRef.current;\n const canUpdate = () => isMountedRef.current && keyRef.current === currentKey && requestIdRef.current === requestId;\n\n const replayQueuedRefetch = () => {\n if (!queuedRefetchRef.current || !canUpdate() || !enabledRef.current) {\n return;\n }\n const nextShowLoader = queuedRefetchShowLoaderRef.current;\n queuedRefetchRef.current = false;\n queuedRefetchShowLoaderRef.current = false;\n clearPendingFetch(currentKey);\n queueMicrotask(() => {\n if (canUpdate() && enabledRef.current) {\n void doFetch(nextShowLoader);\n }\n });\n };\n\n if (showLoader) {\n setLoading(true);\n }\n setError(null);\n\n let fetchPromise = getPendingFetch<{ data: TResult; stats: RpcStats }>(currentKey);\n if (!fetchPromise) {\n const currentTtl = ttlRef.current;\n // Cache before pending cleanup runs, and only while this request is\n // still registered. An invalidated response must not restore stale data.\n const request = rpcCall<TResult, TArgs>(methodIdRef.current, argsRef.current as TArgs).then((result) => {\n if (getPendingFetch(currentKey) === fetchPromise) {\n set(currentKey, result.data, currentTtl);\n }\n return result;\n });\n fetchPromise = setPendingFetch(currentKey, request);\n }\n\n try {\n const result = await fetchPromise;\n if (canUpdate()) {\n setData(result.data);\n setStats(result.stats);\n setError(null);\n }\n return result.data;\n } catch (err: unknown) {\n if (canUpdate()) {\n const rpcError = err instanceof RpcError ? err : new RpcError(err instanceof Error ? err.message : \"Unknown error\");\n setError(rpcError.message);\n setStats(rpcError.stats);\n }\n return undefined;\n } finally {\n if (canUpdate()) {\n setLoading(false);\n }\n replayQueuedRefetch();\n }\n }, []); // No dependencies - uses refs\n\n // Track mounted state\n useEffect(() => {\n isMountedRef.current = true;\n return () => {\n isMountedRef.current = false;\n requestIdRef.current++;\n };\n }, []);\n\n // Reset result state when the query changes, including cached undefined values.\n useEffect(() => {\n setData(get<TResult>(key));\n setError(null);\n setStats(null);\n setLoading(enabled && !has(key));\n }, [key, enabled]);\n\n // Joining a pending request goes through the same guarded path as a new fetch.\n useEffect(() => {\n if (!enabled) {\n setLoading(false);\n return;\n }\n if (!has(key) || isPending(key)) {\n void doFetch(true);\n }\n }, [key, enabled, doFetch]);\n\n // Register for focus/visibility refetch\n useEffect(() => {\n if (!refetchOnWindowFocus) {\n return;\n }\n\n // Setup global focus listeners once\n setupFocusListeners();\n\n // Create a stable callback for this hook instance\n const focusCallback: FocusCallback = (showLoader: boolean) => {\n if (!enabledRef.current || !isMountedRef.current) {\n return;\n }\n\n const shouldShowLoader = showLoaderOnRefocusRef.current || showLoader;\n\n if (isPending(keyRef.current)) {\n queueRefetch(shouldShowLoader);\n void doFetch(shouldShowLoader);\n return;\n }\n\n void doFetch(shouldShowLoader);\n };\n\n // Register this callback\n const callbacks = getFocusCallbacksSet();\n callbacks.add(focusCallback);\n\n return () => {\n callbacks.delete(focusCallback);\n };\n }, [refetchOnWindowFocus, doFetch, queueRefetch]);\n\n // Subscribe to cache invalidations (from useCall or manual invalidation)\n useEffect(() => {\n const unsubscribe = subscribeInvalidations((methodId) => {\n if (methodId !== methodIdRef.current || !enabledRef.current || !isMountedRef.current) {\n return;\n }\n\n if (isPending(keyRef.current)) {\n queueRefetch(showLoaderOnInvalidateRef.current);\n void doFetch(showLoaderOnInvalidateRef.current);\n return;\n }\n\n void doFetch(showLoaderOnInvalidateRef.current);\n });\n\n return unsubscribe;\n }, [doFetch, queueRefetch]);\n\n // TTL-based auto-refetch\n useEffect(() => {\n if (!enabled || !ttl) {\n return;\n }\n\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n let isActive = true;\n\n const scheduleRefetch = () => {\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n\n timeoutId = setTimeout(async () => {\n if (!isActive || !enabledRef.current || !isMountedRef.current) {\n return;\n }\n await doFetch(false); // Silent refetch for TTL\n if (isActive) {\n scheduleRefetch();\n }\n }, ttl);\n };\n\n scheduleRefetch();\n\n return () => {\n isActive = false;\n if (timeoutId !== undefined) {\n clearTimeout(timeoutId);\n }\n };\n }, [key, ttl, enabled, doFetch]);\n\n // Public refetch function\n const refetch = useCallback((showLoader: boolean = true) => doFetch(showLoader), [doFetch]);\n\n return { data, isLoading, error, stats, refetch };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ /** Order overlapping routes by the specificity of each segment, left to right. */
2
+ export declare function compareRoutePatterns(a: string, b: string): number;
3
+ //# sourceMappingURL=routeOrder.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeOrder.d.ts","sourceRoot":"","sources":["../../src/runtime/routeOrder.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,wBAAgB,oBAAoB,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAcjE"}
@@ -0,0 +1,15 @@
1
+ /** Order overlapping routes by the specificity of each segment, left to right. */
2
+ export function compareRoutePatterns(a, b) {
3
+ const aSegments = a.split("/").filter(Boolean);
4
+ const bSegments = b.split("/").filter(Boolean);
5
+ const rank = (segment) => (segment.startsWith("*") ? 0 : segment.startsWith(":") ? 1 : 2);
6
+ for (let index = 0; index < Math.min(aSegments.length, bSegments.length); index++) {
7
+ const difference = rank(bSegments[index]) - rank(aSegments[index]);
8
+ if (difference !== 0) {
9
+ return difference;
10
+ }
11
+ }
12
+ // Exact routes precede a catch-all that can also match an empty suffix.
13
+ return aSegments.length - bSegments.length;
14
+ }
15
+ //# sourceMappingURL=routeOrder.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routeOrder.js","sourceRoot":"","sources":["../../src/runtime/routeOrder.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,MAAM,UAAU,oBAAoB,CAAC,CAAS,EAAE,CAAS;IACrD,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC/C,MAAM,SAAS,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAC/C,MAAM,IAAI,GAAG,CAAC,OAAe,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAElG,KAAK,IAAI,KAAK,GAAG,CAAC,EAAE,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QAChF,MAAM,UAAU,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC;QACnE,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;YACnB,OAAO,UAAU,CAAC;QACtB,CAAC;IACL,CAAC;IAED,wEAAwE;IACxE,OAAO,SAAS,CAAC,MAAM,GAAG,SAAS,CAAC,MAAM,CAAC;AAC/C,CAAC","sourcesContent":["/** Order overlapping routes by the specificity of each segment, left to right. */\nexport function compareRoutePatterns(a: string, b: string): number {\n const aSegments = a.split(\"/\").filter(Boolean);\n const bSegments = b.split(\"/\").filter(Boolean);\n const rank = (segment: string) => (segment.startsWith(\"*\") ? 0 : segment.startsWith(\":\") ? 1 : 2);\n\n for (let index = 0; index < Math.min(aSegments.length, bSegments.length); index++) {\n const difference = rank(bSegments[index]) - rank(aSegments[index]);\n if (difference !== 0) {\n return difference;\n }\n }\n\n // Exact routes precede a catch-all that can also match an empty suffix.\n return aSegments.length - bSegments.length;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/server/config.ts"],"names":[],"mappings":"AAIA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACpC;;;;;OAKG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAElB;;;;;;OAMG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACpC;;;;;;OAMG;IACH,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B;;;;;;OAMG;IACH,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAE9B;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAE3B;;;;;;OAMG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACjC;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,OAAO,CAAC;IAEzB;;;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C,SAAS,EAAE,MAAM,GAAG,WAAW,GAAG,MAAM,CAAC;IACzC,gBAAgB,EAAE,OAAO,CAAC;IAC1B,eAAe,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,GAAE,YAAiB,GAAG,wBAAwB,CAMtF;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,SAE/B"}
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "crypto";
1
2
  import fs from "fs";
2
3
  import path from "path";
3
4
  import { pathToFileURL } from "url";
@@ -11,7 +12,7 @@ const DEFAULT_COMPRESSION = {
11
12
  enabled: true,
12
13
  threshold: 1024,
13
14
  };
14
- let cachedConfig = null;
15
+ const cachedConfigs = new Map();
15
16
  /**
16
17
  * Load Helium configuration from the project root.
17
18
  * Searches for helium.config.js, helium.config.mjs, or helium.config.ts.
@@ -23,41 +24,65 @@ let cachedConfig = null;
23
24
  * @internal - Used by framework internals only
24
25
  */
25
26
  export async function loadConfig(root = process.cwd()) {
27
+ // Check if there's a custom config directory (used in production)
28
+ const configDir = process.env.HELIUM_CONFIG_DIR || root;
29
+ const cacheKey = JSON.stringify([path.resolve(root), path.resolve(configDir)]);
30
+ const cachedConfig = cachedConfigs.get(cacheKey);
26
31
  if (cachedConfig) {
27
32
  return cachedConfig;
28
33
  }
29
- // Check if there's a custom config directory (used in production)
30
- const configDir = process.env.HELIUM_CONFIG_DIR || root;
31
- // Prioritize .js/.mjs (work in both dev and production)
32
- // .ts files work in dev with Vite but fail in production without transpilation
33
34
  const configFiles = ["helium.config.js", "helium.config.mjs", "helium.config.ts"];
34
- // In production with HELIUM_CONFIG_DIR set, check dist directory first
35
35
  const searchPaths = configDir !== root ? [configDir, root] : [root];
36
36
  for (const searchPath of searchPaths) {
37
37
  for (const configFile of configFiles) {
38
- const configPath = path.join(searchPath, configFile);
39
- if (fs.existsSync(configPath)) {
40
- try {
41
- const fileUrl = pathToFileURL(configPath).href;
42
- const module = await import(/* @vite-ignore */ `${fileUrl}?t=${Date.now()}`);
43
- const config = module.default || {};
44
- cachedConfig = config;
45
- return config;
46
- }
47
- catch (err) {
48
- // In production, .ts files will fail to load without a TypeScript loader
49
- if (configFile.endsWith(".ts") && err instanceof Error && "code" in err && err.code === "ERR_UNKNOWN_FILE_EXTENSION") {
50
- console.warn(`[Helium] Cannot load ${configFile} in production. The build process should have transpiled it.`);
51
- }
52
- else {
53
- console.warn(`[Helium] Failed to load config from ${configFile}:`, err);
54
- }
38
+ const configPath = path.resolve(searchPath, configFile);
39
+ if (!fs.existsSync(configPath)) {
40
+ continue;
41
+ }
42
+ try {
43
+ const module = await importConfig(configPath);
44
+ const config = module.default;
45
+ if (!config || typeof config !== "object" || Array.isArray(config)) {
46
+ throw new Error("Expected a configuration object as the default export");
55
47
  }
48
+ cachedConfigs.set(cacheKey, config);
49
+ return config;
50
+ }
51
+ catch (error) {
52
+ // Never silently replace security settings with defaults after a load failure.
53
+ throw new Error(`Failed to load Helium config at ${configPath}: ${error instanceof Error ? error.message : String(error)}`);
56
54
  }
57
55
  }
58
56
  }
59
- cachedConfig = {};
60
- return cachedConfig;
57
+ const config = {};
58
+ cachedConfigs.set(cacheKey, config);
59
+ return config;
60
+ }
61
+ async function importConfig(configPath) {
62
+ if (!configPath.endsWith(".ts")) {
63
+ return import(/* @vite-ignore */ `${pathToFileURL(configPath).href}?t=${randomUUID()}`);
64
+ }
65
+ // Node 20 cannot execute TypeScript. Bundle local helpers as well as stripping types.
66
+ const { build } = await import("esbuild");
67
+ const result = await build({
68
+ entryPoints: [configPath],
69
+ bundle: true,
70
+ packages: "external",
71
+ platform: "node",
72
+ format: "esm",
73
+ target: "node20",
74
+ write: false,
75
+ logLevel: "silent",
76
+ });
77
+ // Keep package resolution and import.meta.url relative to the original config directory.
78
+ const tempPath = path.join(path.dirname(configPath), `.helium-config-${randomUUID()}.mjs`);
79
+ try {
80
+ fs.writeFileSync(tempPath, result.outputFiles[0].text);
81
+ return await import(/* @vite-ignore */ pathToFileURL(tempPath).href);
82
+ }
83
+ finally {
84
+ fs.rmSync(tempPath, { force: true });
85
+ }
61
86
  }
62
87
  /**
63
88
  * Get the proxy trust depth from config.
@@ -129,6 +154,6 @@ export function getRpcClientConfig(config = {}) {
129
154
  * @internal - Used by framework internals only
130
155
  */
131
156
  export function clearConfigCache() {
132
- cachedConfig = null;
157
+ cachedConfigs.clear();
133
158
  }
134
159
  //# sourceMappingURL=config.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/server/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAyPpC,MAAM,oBAAoB,GAAsC;IAC5D,mBAAmB,EAAE,EAAE;IACvB,oBAAoB,EAAE,GAAG;IACzB,iBAAiB,EAAE,KAAK;IACxB,eAAe,EAAE,KAAK;CACzB,CAAC;AAEF,MAAM,mBAAmB,GAAsC;IAC3D,OAAO,EAAE,IAAI;IACb,SAAS,EAAE,IAAI;CAClB,CAAC;AAEF,IAAI,YAAY,GAAwB,IAAI,CAAC;AAE7C;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAAe,OAAO,CAAC,GAAG,EAAE;IACzD,IAAI,YAAY,EAAE,CAAC;QACf,OAAO,YAAY,CAAC;IACxB,CAAC;IAED,kEAAkE;IAClE,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAAI,IAAI,CAAC;IAExD,wDAAwD;IACxD,+EAA+E;IAC/E,MAAM,WAAW,GAAG,CAAC,kBAAkB,EAAE,mBAAmB,EAAE,kBAAkB,CAAC,CAAC;IAElF,uEAAuE;IACvE,MAAM,WAAW,GAAG,SAAS,KAAK,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC,CAAC,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B,IAAI,KAAK;QACvD,eAAe,EAAE,oBAAoB,CAAC,MAAM,CAAC,CAAC,eAAe;KAChE,CAAC;AACN,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB;IAC5B,YAAY,GAAG,IAAI,CAAC;AACxB,CAAC","sourcesContent":["import fs from \"fs\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\n\n/**\n * WebSocket per-message compression configuration.\n * Uses the permessage-deflate extension to compress messages on the wire.\n */\nexport interface HeliumCompressionConfig {\n /**\n * Enable WebSocket per-message compression (permessage-deflate extension).\n * When enabled, messages are compressed before sending to reduce bandwidth usage.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Minimum message size in bytes to apply compression.\n * Messages smaller than this threshold will not be compressed to avoid overhead.\n * Only applies when compression is enabled.\n *\n * @default 1024 (1KB)\n */\n threshold?: number;\n}\n\n/**\n * RPC security and rate limiting configuration.\n * Controls WebSocket connection limits, message rate limits, and token-based authentication.\n */\nexport interface HeliumRpcSecurityConfig {\n /**\n * Maximum number of concurrent WebSocket connections allowed per IP address.\n * Helps prevent a single client from exhausting connection resources.\n * Set to 0 to disable this limit.\n *\n * @default 10\n */\n maxConnectionsPerIP?: number;\n\n /**\n * Maximum number of RPC messages allowed per connection within the time window.\n * Helps prevent abuse by limiting message throughput per connection.\n * Set to 0 to disable rate limiting.\n *\n * @default 100\n */\n maxMessagesPerWindow?: number;\n\n /**\n * Time window in milliseconds for rate limiting.\n * Rate limits reset after this duration.\n *\n * @default 60000 (1 minute)\n */\n rateLimitWindowMs?: number;\n\n /**\n * WebSocket connection token validity duration in milliseconds.\n * Tokens are generated server-side and must be used within this timeframe.\n * Shorter durations improve security but may cause issues with slow networks.\n *\n * @default 30000 (30 seconds)\n */\n tokenValidityMs?: number;\n}\n\n/**\n * Security configuration for HTTP responses.\n */\nexport interface HeliumSecurityConfig {\n /**\n * Apply Helium's built-in default security headers.\n *\n * When set to `false`, Helium will not set default security headers,\n * allowing full manual control via `headerOverrides` and your own server logic.\n *\n * @default true\n */\n defaultHeaders?: boolean;\n\n /**\n * Header overrides applied after Helium's default security headers.\n *\n * - Set a header value to override (or add) that header.\n * - Set a header value to `null` to remove that header.\n *\n * This is useful for custom framing policies, custom permissions policy,\n * or disabling a specific default header.\n */\n headerOverrides?: Record<string, string | null>;\n\n /**\n * Content-Security-Policy header value.\n * Set to a CSP string to enable, or omit to skip CSP.\n * Applied when `defaultHeaders` is enabled.\n *\n * @default undefined (no CSP header)\n */\n contentSecurityPolicy?: string;\n\n /**\n * Enable Strict-Transport-Security header.\n * Set to false to disable HSTS.\n * Applied when `defaultHeaders` is enabled.\n *\n * @default true\n */\n hsts?: boolean;\n\n /**\n * Allowed CORS origins.\n * Set to [\"*\"] to allow all origins, or provide specific origins.\n * Empty array or omit to restrict to same-origin only (default, most secure).\n *\n * @default [] (same-origin only)\n */\n corsOrigins?: string[];\n}\n\n/**\n * Helium framework configuration.\n *\n * Configure your Helium application behavior including RPC transport settings,\n * compression, security, and proxy configuration for production deployments.\n */\nexport interface HeliumConfig {\n /**\n * Number of proxy levels to trust when extracting client IP addresses.\n *\n * This setting is crucial for deployments behind reverse proxies, load balancers,\n * or CDNs (like Vercel, Cloudflare, AWS ALB, etc.). It determines how the framework\n * extracts the real client IP from headers like X-Forwarded-For.\n *\n * **How it works:**\n * When behind proxies, the X-Forwarded-For header contains a chain of IPs:\n * `X-Forwarded-For: <client-ip>, <proxy1-ip>, <proxy2-ip>`\n *\n * This setting tells Helium how many proxy IPs to skip from the right to find the real client IP.\n *\n * **Values:**\n * - `0`: Don't trust any proxies, use direct connection IP (default, most secure)\n * - `1`: Trust 1 proxy level (recommended for most platforms: Vercel, Netlify, Railway)\n * - `2+`: Trust multiple proxy levels (for complex setups like Cloudflare → Load Balancer → Your Server)\n *\n * **Common configurations:**\n * - Local development: `0`\n * - Vercel/Netlify/Railway: `1`\n * - Cloudflare → Your server: `1` or `2`\n * - AWS ALB → EC2: `1`\n * - Nginx → Node.js: `1`\n * - Cloudflare → AWS ALB → EC2: `2`\n *\n * **Security note:** Setting this too high can allow IP spoofing. Only trust as many\n * proxy levels as you actually have in your infrastructure.\n *\n * This setting applies to both HTTP requests and WebSocket connections.\n *\n * @default 0\n */\n trustProxyDepth?: number;\n\n /**\n * HTTP response security configuration.\n * Controls CORS, CSP, HSTS, and other security headers.\n */\n security?: HeliumSecurityConfig;\n\n /**\n * RPC transport configuration.\n *\n * Configure the WebSocket-based RPC layer including compression\n * and security settings.\n */\n rpc?: {\n /**\n * Client-side transport mode for RPC calls.\n *\n * - `\"websocket\"` (default): Uses persistent WebSocket connection\n * - ✅ Lower latency for subsequent calls (connection reuse)\n * - ✅ Real-time bidirectional communication ready\n * - ⚠️ Higher initial connection overhead\n *\n * - `\"http\"`: Uses HTTP POST requests for each RPC call\n * - ✅ Better performance on mobile/cellular networks (HTTP/2 optimizations)\n * - ✅ No connection state to maintain\n * - ⚠️ Slightly higher per-request overhead on fast networks\n *\n * - `\"auto\"`: Automatically selects based on network conditions\n * - Uses HTTP on cellular/slow networks when `autoHttpOnMobile` is true\n * - Uses WebSocket on fast networks (WiFi, wired)\n *\n * @default \"websocket\"\n */\n transport?: \"http\" | \"websocket\" | \"auto\";\n\n /**\n * Automatically switch to HTTP transport on mobile/cellular networks.\n *\n * When enabled and `transport` is `\"auto\"`, the client will use HTTP\n * instead of WebSocket on cellular connections (4G/LTE, 5G) and slow\n * connections (2G, 3G). This improves performance on mobile networks\n * where HTTP/2 is more efficient due to carrier network optimizations.\n *\n * @default false\n */\n autoHttpOnMobile?: boolean;\n\n /**\n * WebSocket per-message compression configuration.\n *\n * Enable and configure the permessage-deflate extension to compress\n * messages on the wire, reducing bandwidth usage.\n */\n compression?: HeliumCompressionConfig;\n\n /**\n * RPC security and rate limiting configuration.\n *\n * Configure connection limits, message rate limits, and token validity\n * to protect your RPC endpoints from abuse.\n */\n security?: HeliumRpcSecurityConfig;\n\n /**\n * Maximum HTTP request body size in bytes.\n * Requests exceeding this limit receive a 413 status.\n *\n * @default 1048576 (1 MB)\n */\n maxBodySize?: number;\n\n /**\n * Maximum number of RPC calls in a single batch request.\n * Batches exceeding this limit are rejected.\n *\n * @default 20\n */\n maxBatchSize?: number;\n\n /**\n * Maximum WebSocket message payload size in bytes.\n * Messages exceeding this limit cause the connection to be closed.\n *\n * @default 1048576 (1 MB)\n */\n maxWsPayload?: number;\n };\n}\n\nconst DEFAULT_RPC_SECURITY: Required<HeliumRpcSecurityConfig> = {\n maxConnectionsPerIP: 10,\n maxMessagesPerWindow: 100,\n rateLimitWindowMs: 60000,\n tokenValidityMs: 30000,\n};\n\nconst DEFAULT_COMPRESSION: Required<HeliumCompressionConfig> = {\n enabled: true,\n threshold: 1024,\n};\n\nlet cachedConfig: HeliumConfig | null = null;\n\n/**\n * Load Helium configuration from the project root.\n * Searches for helium.config.js, helium.config.mjs, or helium.config.ts.\n * Results are cached for the lifetime of the process.\n *\n * In production, the build process automatically transpiles .ts config files\n * to .js in the dist directory. The loader checks dist/ first when available.\n *\n * @internal - Used by framework internals only\n */\nexport async function loadConfig(root: string = process.cwd()): Promise<HeliumConfig> {\n if (cachedConfig) {\n return cachedConfig;\n }\n\n // Check if there's a custom config directory (used in production)\n const configDir = process.env.HELIUM_CONFIG_DIR || root;\n\n // Prioritize .js/.mjs (work in both dev and production)\n // .ts files work in dev with Vite but fail in production without transpilation\n const configFiles = [\"helium.config.js\", \"helium.config.mjs\", \"helium.config.ts\"];\n\n // In production with HELIUM_CONFIG_DIR set, check dist directory first\n const searchPaths = configDir !== root ? [configDir, root] : [root];\n\n for (const searchPath of searchPaths) {\n for (const configFile of configFiles) {\n const configPath = path.join(searchPath, configFile);\n if (fs.existsSync(configPath)) {\n try {\n const fileUrl = pathToFileURL(configPath).href;\n const module = await import(/* @vite-ignore */ `${fileUrl}?t=${Date.now()}`);\n const config = module.default || {};\n cachedConfig = config;\n return config;\n } catch (err) {\n // In production, .ts files will fail to load without a TypeScript loader\n if (configFile.endsWith(\".ts\") && err instanceof Error && \"code\" in err && err.code === \"ERR_UNKNOWN_FILE_EXTENSION\") {\n console.warn(`[Helium] Cannot load ${configFile} in production. The build process should have transpiled it.`);\n } else {\n console.warn(`[Helium] Failed to load config from ${configFile}:`, err);\n }\n }\n }\n }\n }\n\n cachedConfig = {};\n return cachedConfig;\n}\n\n/**\n * Get the proxy trust depth from config.\n * Used for extracting client IPs from X-Forwarded-For headers.\n *\n * @internal - Used by framework internals only\n */\nexport function getTrustProxyDepth(config: HeliumConfig = {}): number {\n return config.trustProxyDepth ?? 0;\n}\n\n/**\n * Get RPC security configuration with defaults applied.\n * Returns rate limiting, connection limits, and token settings.\n *\n * @internal - Used by framework internals only\n */\nexport function getRpcSecurityConfig(config: HeliumConfig = {}): Required<HeliumRpcSecurityConfig> {\n const src = config.rpc?.security;\n\n return {\n maxConnectionsPerIP: src?.maxConnectionsPerIP ?? DEFAULT_RPC_SECURITY.maxConnectionsPerIP,\n maxMessagesPerWindow: src?.maxMessagesPerWindow ?? DEFAULT_RPC_SECURITY.maxMessagesPerWindow,\n rateLimitWindowMs: src?.rateLimitWindowMs ?? DEFAULT_RPC_SECURITY.rateLimitWindowMs,\n tokenValidityMs: src?.tokenValidityMs ?? DEFAULT_RPC_SECURITY.tokenValidityMs,\n };\n}\n\n/**\n * Get WebSocket compression configuration with defaults applied.\n *\n * @internal - Used by framework internals only\n */\nexport function getCompressionConfig(config: HeliumConfig = {}): Required<HeliumCompressionConfig> {\n const src = config.rpc?.compression;\n\n return {\n enabled: src?.enabled ?? DEFAULT_COMPRESSION.enabled,\n threshold: src?.threshold ?? DEFAULT_COMPRESSION.threshold,\n };\n}\n\n/**\n * Get complete RPC configuration including compression, and security.\n *\n * @internal - Used by framework internals only\n */\nexport function getRpcConfig(config: HeliumConfig = {}) {\n return {\n compression: getCompressionConfig(config),\n security: getRpcSecurityConfig(config),\n maxBodySize: config.rpc?.maxBodySize ?? 1_048_576,\n maxBatchSize: config.rpc?.maxBatchSize ?? 20,\n maxWsPayload: config.rpc?.maxWsPayload ?? 1_048_576,\n };\n}\n\n/**\n * Client-side RPC transport configuration.\n * This is injected into the client bundle at build time.\n */\nexport interface RpcClientTransportConfig {\n transport: \"http\" | \"websocket\" | \"auto\";\n autoHttpOnMobile: boolean;\n tokenValidityMs: number;\n}\n\n/**\n * Get client-side RPC transport configuration.\n * This configuration is injected into the client bundle via Vite defines.\n *\n * @internal - Used by framework internals only\n */\nexport function getRpcClientConfig(config: HeliumConfig = {}): RpcClientTransportConfig {\n return {\n transport: config.rpc?.transport ?? \"websocket\",\n autoHttpOnMobile: config.rpc?.autoHttpOnMobile ?? false,\n tokenValidityMs: getRpcSecurityConfig(config).tokenValidityMs,\n };\n}\n\n/**\n * Clear the cached configuration.\n * Useful for testing or when you need to reload config.\n *\n * @internal - Used by framework internals only\n */\nexport function clearConfigCache() {\n cachedConfig = null;\n}\n"]}
1
+ {"version":3,"file":"config.js","sourceRoot":"","sources":["../../src/server/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,QAAQ,CAAC;AACpC,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,IAAI,MAAM,MAAM,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,KAAK,CAAC;AAyPpC,MAAM,oBAAoB,GAAsC;IAC5D,mBAAmB,EAAE,EAAE;IACvB,oBAAoB,EAAE,GAAG;IACzB,iBAAiB,EAAE,KAAK;IACxB,eAAe,EAAE,KAAK;CACzB,CAAC;AAEF,MAAM,mBAAmB,GAAsC;IAC3D,OAAO,EAAE,IAAI;IACb,SAAS,EAAE,IAAI;CAClB,CAAC;AAEF,MAAM,aAAa,GAAG,IAAI,GAAG,EAAwB,CAAC;AAEtD;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAAe,OAAO,CAAC,GAAG,EAAE;IACzD,kEAAkE;IAClE,MAAM,SAAS,GAAG,OAAO,CAAC,GAAG,CAAC,iBAAiB,IAA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,YAAY,EAAE,MAAM,CAAC,GAAG,EAAE,YAAY,IAAI,EAAE;QAC5C,YAAY,EAAE,MAAM,CAAC,GAAG,EAAE,YAAY,IAAI,OAAS;KACtD,CAAC;AACN,CAAC;AAYD;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAuB,EAAE;IACxD,OAAO;QACH,SAAS,EAAE,MAAM,CAAC,GAAG,EAAE,SAAS,IAAI,WAAW;QAC/C,gBAAgB,EAAE,MAAM,CAAC,GAAG,EAAE,gBAAgB,IAAI,KAAK;QACvD,eAAe,EAAE,oBAAoB,CAAC,MAAM,CAAC,CAAC,eAAe;KAChE,CAAC;AACN,CAAC;AAED;;;;;GAKG;AACH,MAAM,UAAU,gBAAgB;IAC5B,aAAa,CAAC,KAAK,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { pathToFileURL } from \"url\";\n\n/**\n * WebSocket per-message compression configuration.\n * Uses the permessage-deflate extension to compress messages on the wire.\n */\nexport interface HeliumCompressionConfig {\n /**\n * Enable WebSocket per-message compression (permessage-deflate extension).\n * When enabled, messages are compressed before sending to reduce bandwidth usage.\n *\n * @default true\n */\n enabled?: boolean;\n\n /**\n * Minimum message size in bytes to apply compression.\n * Messages smaller than this threshold will not be compressed to avoid overhead.\n * Only applies when compression is enabled.\n *\n * @default 1024 (1KB)\n */\n threshold?: number;\n}\n\n/**\n * RPC security and rate limiting configuration.\n * Controls WebSocket connection limits, message rate limits, and token-based authentication.\n */\nexport interface HeliumRpcSecurityConfig {\n /**\n * Maximum number of concurrent WebSocket connections allowed per IP address.\n * Helps prevent a single client from exhausting connection resources.\n * Set to 0 to disable this limit.\n *\n * @default 10\n */\n maxConnectionsPerIP?: number;\n\n /**\n * Maximum number of RPC messages allowed per connection within the time window.\n * Helps prevent abuse by limiting message throughput per connection.\n * Set to 0 to disable rate limiting.\n *\n * @default 100\n */\n maxMessagesPerWindow?: number;\n\n /**\n * Time window in milliseconds for rate limiting.\n * Rate limits reset after this duration.\n *\n * @default 60000 (1 minute)\n */\n rateLimitWindowMs?: number;\n\n /**\n * WebSocket connection token validity duration in milliseconds.\n * Tokens are generated server-side and must be used within this timeframe.\n * Shorter durations improve security but may cause issues with slow networks.\n *\n * @default 30000 (30 seconds)\n */\n tokenValidityMs?: number;\n}\n\n/**\n * Security configuration for HTTP responses.\n */\nexport interface HeliumSecurityConfig {\n /**\n * Apply Helium's built-in default security headers.\n *\n * When set to `false`, Helium will not set default security headers,\n * allowing full manual control via `headerOverrides` and your own server logic.\n *\n * @default true\n */\n defaultHeaders?: boolean;\n\n /**\n * Header overrides applied after Helium's default security headers.\n *\n * - Set a header value to override (or add) that header.\n * - Set a header value to `null` to remove that header.\n *\n * This is useful for custom framing policies, custom permissions policy,\n * or disabling a specific default header.\n */\n headerOverrides?: Record<string, string | null>;\n\n /**\n * Content-Security-Policy header value.\n * Set to a CSP string to enable, or omit to skip CSP.\n * Applied when `defaultHeaders` is enabled.\n *\n * @default undefined (no CSP header)\n */\n contentSecurityPolicy?: string;\n\n /**\n * Enable Strict-Transport-Security header.\n * Set to false to disable HSTS.\n * Applied when `defaultHeaders` is enabled.\n *\n * @default true\n */\n hsts?: boolean;\n\n /**\n * Allowed CORS origins.\n * Set to [\"*\"] to allow all origins, or provide specific origins.\n * Empty array or omit to restrict to same-origin only (default, most secure).\n *\n * @default [] (same-origin only)\n */\n corsOrigins?: string[];\n}\n\n/**\n * Helium framework configuration.\n *\n * Configure your Helium application behavior including RPC transport settings,\n * compression, security, and proxy configuration for production deployments.\n */\nexport interface HeliumConfig {\n /**\n * Number of proxy levels to trust when extracting client IP addresses.\n *\n * This setting is crucial for deployments behind reverse proxies, load balancers,\n * or CDNs (like Vercel, Cloudflare, AWS ALB, etc.). It determines how the framework\n * extracts the real client IP from headers like X-Forwarded-For.\n *\n * **How it works:**\n * When behind proxies, the X-Forwarded-For header contains a chain of IPs:\n * `X-Forwarded-For: <client-ip>, <proxy1-ip>, <proxy2-ip>`\n *\n * This setting tells Helium how many proxy IPs to skip from the right to find the real client IP.\n *\n * **Values:**\n * - `0`: Don't trust any proxies, use direct connection IP (default, most secure)\n * - `1`: Trust 1 proxy level (recommended for most platforms: Vercel, Netlify, Railway)\n * - `2+`: Trust multiple proxy levels (for complex setups like Cloudflare → Load Balancer → Your Server)\n *\n * **Common configurations:**\n * - Local development: `0`\n * - Vercel/Netlify/Railway: `1`\n * - Cloudflare → Your server: `1` or `2`\n * - AWS ALB → EC2: `1`\n * - Nginx → Node.js: `1`\n * - Cloudflare → AWS ALB → EC2: `2`\n *\n * **Security note:** Setting this too high can allow IP spoofing. Only trust as many\n * proxy levels as you actually have in your infrastructure.\n *\n * This setting applies to both HTTP requests and WebSocket connections.\n *\n * @default 0\n */\n trustProxyDepth?: number;\n\n /**\n * HTTP response security configuration.\n * Controls CORS, CSP, HSTS, and other security headers.\n */\n security?: HeliumSecurityConfig;\n\n /**\n * RPC transport configuration.\n *\n * Configure the WebSocket-based RPC layer including compression\n * and security settings.\n */\n rpc?: {\n /**\n * Client-side transport mode for RPC calls.\n *\n * - `\"websocket\"` (default): Uses persistent WebSocket connection\n * - ✅ Lower latency for subsequent calls (connection reuse)\n * - ✅ Real-time bidirectional communication ready\n * - ⚠️ Higher initial connection overhead\n *\n * - `\"http\"`: Uses HTTP POST requests for each RPC call\n * - ✅ Better performance on mobile/cellular networks (HTTP/2 optimizations)\n * - ✅ No connection state to maintain\n * - ⚠️ Slightly higher per-request overhead on fast networks\n *\n * - `\"auto\"`: Automatically selects based on network conditions\n * - Uses HTTP on cellular/slow networks when `autoHttpOnMobile` is true\n * - Uses WebSocket on fast networks (WiFi, wired)\n *\n * @default \"websocket\"\n */\n transport?: \"http\" | \"websocket\" | \"auto\";\n\n /**\n * Automatically switch to HTTP transport on mobile/cellular networks.\n *\n * When enabled and `transport` is `\"auto\"`, the client will use HTTP\n * instead of WebSocket on cellular connections (4G/LTE, 5G) and slow\n * connections (2G, 3G). This improves performance on mobile networks\n * where HTTP/2 is more efficient due to carrier network optimizations.\n *\n * @default false\n */\n autoHttpOnMobile?: boolean;\n\n /**\n * WebSocket per-message compression configuration.\n *\n * Enable and configure the permessage-deflate extension to compress\n * messages on the wire, reducing bandwidth usage.\n */\n compression?: HeliumCompressionConfig;\n\n /**\n * RPC security and rate limiting configuration.\n *\n * Configure connection limits, message rate limits, and token validity\n * to protect your RPC endpoints from abuse.\n */\n security?: HeliumRpcSecurityConfig;\n\n /**\n * Maximum HTTP request body size in bytes.\n * Requests exceeding this limit receive a 413 status.\n *\n * @default 1048576 (1 MB)\n */\n maxBodySize?: number;\n\n /**\n * Maximum number of RPC calls in a single batch request.\n * Batches exceeding this limit are rejected.\n *\n * @default 20\n */\n maxBatchSize?: number;\n\n /**\n * Maximum WebSocket message payload size in bytes.\n * Messages exceeding this limit cause the connection to be closed.\n *\n * @default 1048576 (1 MB)\n */\n maxWsPayload?: number;\n };\n}\n\nconst DEFAULT_RPC_SECURITY: Required<HeliumRpcSecurityConfig> = {\n maxConnectionsPerIP: 10,\n maxMessagesPerWindow: 100,\n rateLimitWindowMs: 60000,\n tokenValidityMs: 30000,\n};\n\nconst DEFAULT_COMPRESSION: Required<HeliumCompressionConfig> = {\n enabled: true,\n threshold: 1024,\n};\n\nconst cachedConfigs = new Map<string, HeliumConfig>();\n\n/**\n * Load Helium configuration from the project root.\n * Searches for helium.config.js, helium.config.mjs, or helium.config.ts.\n * Results are cached for the lifetime of the process.\n *\n * In production, the build process automatically transpiles .ts config files\n * to .js in the dist directory. The loader checks dist/ first when available.\n *\n * @internal - Used by framework internals only\n */\nexport async function loadConfig(root: string = process.cwd()): Promise<HeliumConfig> {\n // Check if there's a custom config directory (used in production)\n const configDir = process.env.HELIUM_CONFIG_DIR || root;\n const cacheKey = JSON.stringify([path.resolve(root), path.resolve(configDir)]);\n const cachedConfig = cachedConfigs.get(cacheKey);\n if (cachedConfig) {\n return cachedConfig;\n }\n\n const configFiles = [\"helium.config.js\", \"helium.config.mjs\", \"helium.config.ts\"];\n const searchPaths = configDir !== root ? [configDir, root] : [root];\n\n for (const searchPath of searchPaths) {\n for (const configFile of configFiles) {\n const configPath = path.resolve(searchPath, configFile);\n if (!fs.existsSync(configPath)) {\n continue;\n }\n try {\n const module = await importConfig(configPath);\n const config = module.default;\n if (!config || typeof config !== \"object\" || Array.isArray(config)) {\n throw new Error(\"Expected a configuration object as the default export\");\n }\n cachedConfigs.set(cacheKey, config);\n return config;\n } catch (error) {\n // Never silently replace security settings with defaults after a load failure.\n throw new Error(`Failed to load Helium config at ${configPath}: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n }\n\n const config = {};\n cachedConfigs.set(cacheKey, config);\n return config;\n}\n\nasync function importConfig(configPath: string): Promise<{ default?: HeliumConfig }> {\n if (!configPath.endsWith(\".ts\")) {\n return import(/* @vite-ignore */ `${pathToFileURL(configPath).href}?t=${randomUUID()}`);\n }\n\n // Node 20 cannot execute TypeScript. Bundle local helpers as well as stripping types.\n const { build } = await import(\"esbuild\");\n const result = await build({\n entryPoints: [configPath],\n bundle: true,\n packages: \"external\",\n platform: \"node\",\n format: \"esm\",\n target: \"node20\",\n write: false,\n logLevel: \"silent\",\n });\n // Keep package resolution and import.meta.url relative to the original config directory.\n const tempPath = path.join(path.dirname(configPath), `.helium-config-${randomUUID()}.mjs`);\n try {\n fs.writeFileSync(tempPath, result.outputFiles[0].text);\n return await import(/* @vite-ignore */ pathToFileURL(tempPath).href);\n } finally {\n fs.rmSync(tempPath, { force: true });\n }\n}\n\n/**\n * Get the proxy trust depth from config.\n * Used for extracting client IPs from X-Forwarded-For headers.\n *\n * @internal - Used by framework internals only\n */\nexport function getTrustProxyDepth(config: HeliumConfig = {}): number {\n return config.trustProxyDepth ?? 0;\n}\n\n/**\n * Get RPC security configuration with defaults applied.\n * Returns rate limiting, connection limits, and token settings.\n *\n * @internal - Used by framework internals only\n */\nexport function getRpcSecurityConfig(config: HeliumConfig = {}): Required<HeliumRpcSecurityConfig> {\n const src = config.rpc?.security;\n\n return {\n maxConnectionsPerIP: src?.maxConnectionsPerIP ?? DEFAULT_RPC_SECURITY.maxConnectionsPerIP,\n maxMessagesPerWindow: src?.maxMessagesPerWindow ?? DEFAULT_RPC_SECURITY.maxMessagesPerWindow,\n rateLimitWindowMs: src?.rateLimitWindowMs ?? DEFAULT_RPC_SECURITY.rateLimitWindowMs,\n tokenValidityMs: src?.tokenValidityMs ?? DEFAULT_RPC_SECURITY.tokenValidityMs,\n };\n}\n\n/**\n * Get WebSocket compression configuration with defaults applied.\n *\n * @internal - Used by framework internals only\n */\nexport function getCompressionConfig(config: HeliumConfig = {}): Required<HeliumCompressionConfig> {\n const src = config.rpc?.compression;\n\n return {\n enabled: src?.enabled ?? DEFAULT_COMPRESSION.enabled,\n threshold: src?.threshold ?? DEFAULT_COMPRESSION.threshold,\n };\n}\n\n/**\n * Get complete RPC configuration including compression, and security.\n *\n * @internal - Used by framework internals only\n */\nexport function getRpcConfig(config: HeliumConfig = {}) {\n return {\n compression: getCompressionConfig(config),\n security: getRpcSecurityConfig(config),\n maxBodySize: config.rpc?.maxBodySize ?? 1_048_576,\n maxBatchSize: config.rpc?.maxBatchSize ?? 20,\n maxWsPayload: config.rpc?.maxWsPayload ?? 1_048_576,\n };\n}\n\n/**\n * Client-side RPC transport configuration.\n * This is injected into the client bundle at build time.\n */\nexport interface RpcClientTransportConfig {\n transport: \"http\" | \"websocket\" | \"auto\";\n autoHttpOnMobile: boolean;\n tokenValidityMs: number;\n}\n\n/**\n * Get client-side RPC transport configuration.\n * This configuration is injected into the client bundle via Vite defines.\n *\n * @internal - Used by framework internals only\n */\nexport function getRpcClientConfig(config: HeliumConfig = {}): RpcClientTransportConfig {\n return {\n transport: config.rpc?.transport ?? \"websocket\",\n autoHttpOnMobile: config.rpc?.autoHttpOnMobile ?? false,\n tokenValidityMs: getRpcSecurityConfig(config).tokenValidityMs,\n };\n}\n\n/**\n * Clear the cached configuration.\n * Useful for testing or when you need to reload config.\n *\n * @internal - Used by framework internals only\n */\nexport function clearConfigCache() {\n cachedConfigs.clear();\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import type { HeliumContext } from "./context.js";
2
- export type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "ALL";
2
+ export type HTTPMethod = "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "PATCH" | "OPTIONS" | "ALL";
3
3
  export interface HTTPRequest {
4
4
  method: string;
5
5
  path: string;
@@ -1 +1 @@
1
- {"version":3,"file":"defineHTTPRequest.d.ts","sourceRoot":"","sources":["../../src/server/defineHTTPRequest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,MAAM,MAAM,UAAU,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK,GAAG,QAAQ,GAAG,OAAO,GAAG,KAAK,CAAC;AAE7E,MAAM,WAAW,WAAW;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC,CAAC;IACvD,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC9B,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAC/B,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAChC,IAAI,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7B,IAAI,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;IAC5B,QAAQ,EAAE,MAAM,OAAO,CAAC,QAAQ,CAAC,CAAC;IAClC;;;;;;;;;OASG;IACH,YAAY,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;CACxC;AAED,MAAM,MAAM,WAAW,CAAC,OAAO,GAAG,OAAO,IAAI,CAAC,GA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,CAAC,CAAC;IACzD,CAAC;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC5D,CAAC;IAED,OAAO;QACH,MAAM,EAAE,MAAM;QACd,MAAM;QACN,IAAI;QACJ,OAAO;KACV,CAAC;AACN,CAAC","sourcesContent":["import type { HeliumContext } from \"./context.js\";\n\nexport type HTTPMethod = \"GET\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"ALL\";\n\nexport interface HTTPRequest {\n method: string;\n path: string;\n headers: Record<string, string | string[] | undefined>;\n query: Record<string, string>;\n params: Record<string, string>;\n cookies: Record<string, string>;\n json: () => Promise<unknown>;\n text: () => Promise<string>;\n formData: () => Promise<FormData>;\n /**\n * Convert the normalized Helium HTTPRequest into a standard Web `Request`.\n *\n * This is useful when integrating with APIs or libraries that expect the\n * Fetch/Web Request API (for example, third-party auth handlers or cloud SDKs).\n * The implementation will build a Request with matching method, headers\n * and body where appropriate.\n *\n * @returns a Promise resolving to a Web `Request` instance representing the same request\n */\n toWebRequest: () => Promise<Request>;\n}\n\nexport type HTTPHandler<TResult = unknown> = (req: HTTPRequest, ctx: HeliumContext) => Promise<TResult> | TResult;\n\nexport type HeliumHTTPDef<TMethod extends HTTPMethod = HTTPMethod, TPath extends string = string> = {\n __kind: \"http\";\n method: TMethod;\n path: TPath;\n handler: HTTPHandler;\n};\n\n/**\n * Define an HTTP endpoint for the server.\n *\n * Handlers created with `defineHTTPRequest(method, path, handler)` are\n * discoverable by the Vite plugin and will be registered as server HTTP\n * endpoints. The provided handler receives a normalized `HTTPRequest` and\n * the Helium context.\n *\n * @typeParam TMethod - exact HTTP method literal (GET/POST/etc.)\n * @typeParam TPath - the path string used to discover and register the handler\n * @typeParam TResult - expected return type\n * @param method - HTTP verb or \"ALL\" for any method\n * @param path - route path\n * @param handler - function handling the request\n * @returns a HeliumHTTPDef used for server registration\n */\nexport function defineHTTPRequest<TMethod extends HTTPMethod, TPath extends string, TResult = unknown>(\n method: TMethod,\n path: TPath,\n handler: HTTPHandler<TResult>\n): HeliumHTTPDef<TMethod, TPath> {\n if (!method) {\n throw new Error(\"defineHTTPRequest requires a method (GET, POST, etc.)\");\n }\n if (!path) {\n throw new Error(\"defineHTTPRequest requires a path\");\n }\n if (!handler) {\n throw new Error(\"defineHTTPRequest requires a handler\");\n }\n\n return {\n __kind: \"http\",\n method,\n path,\n handler,\n };\n}\n"]}
1
+ {"version":3,"file":"defineHTTPRequest.js","sourceRoot":"","sources":["../../src/server/defineHTTPRequest.ts"],"names":[],"mappings":"AAoCA;;;;;;;;;;;;;;;GAeG;AACH,MAAM,UAAU,iBAAiB,CAC7B,MAAe,EACf,IAAW,EACX,OAA6B;IAE7B,IAAI,CAAC,MAAM,EAAE,CAAC;QACV,MAAM,IAAI,KAAK,CAAC,uDAAuD,CAAC,CAAC;IAC7E,CAAC;IACD,IAAI,CAAC,IAAI,EAAE,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACzD,CAAC;IACD,IAAI,CAAC,OAAO,EAAE,CAAC;QACX,MAAM,IAAI,KAAK,CAAC,sCAAsC,CAAC,CAAC;IAC5D,CAAC;IAED,OAAO;QACH,MAAM,EAAE,MAAM;QACd,MAAM;QACN,IAAI;QACJ,OAAO;KACV,CAAC;AACN,CAAC","sourcesContent":["import type { HeliumContext } from \"./context.js\";\n\nexport type HTTPMethod = \"GET\" | \"HEAD\" | \"POST\" | \"PUT\" | \"DELETE\" | \"PATCH\" | \"OPTIONS\" | \"ALL\";\n\nexport interface HTTPRequest {\n method: string;\n path: string;\n headers: Record<string, string | string[] | undefined>;\n query: Record<string, string>;\n params: Record<string, string>;\n cookies: Record<string, string>;\n json: () => Promise<unknown>;\n text: () => Promise<string>;\n formData: () => Promise<FormData>;\n /**\n * Convert the normalized Helium HTTPRequest into a standard Web `Request`.\n *\n * This is useful when integrating with APIs or libraries that expect the\n * Fetch/Web Request API (for example, third-party auth handlers or cloud SDKs).\n * The implementation will build a Request with matching method, headers\n * and body where appropriate.\n *\n * @returns a Promise resolving to a Web `Request` instance representing the same request\n */\n toWebRequest: () => Promise<Request>;\n}\n\nexport type HTTPHandler<TResult = unknown> = (req: HTTPRequest, ctx: HeliumContext) => Promise<TResult> | TResult;\n\nexport type HeliumHTTPDef<TMethod extends HTTPMethod = HTTPMethod, TPath extends string = string> = {\n __kind: \"http\";\n method: TMethod;\n path: TPath;\n handler: HTTPHandler;\n};\n\n/**\n * Define an HTTP endpoint for the server.\n *\n * Handlers created with `defineHTTPRequest(method, path, handler)` are\n * discoverable by the Vite plugin and will be registered as server HTTP\n * endpoints. The provided handler receives a normalized `HTTPRequest` and\n * the Helium context.\n *\n * @typeParam TMethod - exact HTTP method literal (GET/POST/etc.)\n * @typeParam TPath - the path string used to discover and register the handler\n * @typeParam TResult - expected return type\n * @param method - HTTP verb or \"ALL\" for any method\n * @param path - route path\n * @param handler - function handling the request\n * @returns a HeliumHTTPDef used for server registration\n */\nexport function defineHTTPRequest<TMethod extends HTTPMethod, TPath extends string, TResult = unknown>(\n method: TMethod,\n path: TPath,\n handler: HTTPHandler<TResult>\n): HeliumHTTPDef<TMethod, TPath> {\n if (!method) {\n throw new Error(\"defineHTTPRequest requires a method (GET, POST, etc.)\");\n }\n if (!path) {\n throw new Error(\"defineHTTPRequest requires a path\");\n }\n if (!handler) {\n throw new Error(\"defineHTTPRequest requires a handler\");\n }\n\n return {\n __kind: \"http\",\n method,\n path,\n handler,\n };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"defineWorker.d.ts","sourceRoot":"","sources":["../../src/server/defineWorker.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,MAAM,MAAM,aAAa,GAAG,CAAC,MAAM,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC;AAEhE,MAAM,WAAW,eAAe;IAC5B,MA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