heliumts 0.9.7 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -12
- package/dist/bin/helium.js +15 -10
- package/dist/bin/helium.js.map +1 -1
- package/dist/client/Router.d.ts.map +1 -1
- package/dist/client/Router.js +2 -4
- package/dist/client/Router.js.map +1 -1
- package/dist/client/callMethod.d.ts +2 -7
- package/dist/client/callMethod.d.ts.map +1 -1
- package/dist/client/callMethod.js +4 -5
- package/dist/client/callMethod.js.map +1 -1
- package/dist/client/index.d.ts +3 -3
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -1
- package/dist/client/index.js.map +1 -1
- package/dist/client/rpcClient.d.ts +7 -41
- package/dist/client/rpcClient.d.ts.map +1 -1
- package/dist/client/rpcClient.js +118 -752
- package/dist/client/rpcClient.js.map +1 -1
- package/dist/client/rpcStreaming.d.ts +10 -0
- package/dist/client/rpcStreaming.d.ts.map +1 -0
- package/dist/client/rpcStreaming.js +125 -0
- package/dist/client/rpcStreaming.js.map +1 -0
- package/dist/client/useStreaming.d.ts +26 -0
- package/dist/client/useStreaming.d.ts.map +1 -0
- package/dist/client/useStreaming.js +126 -0
- package/dist/client/useStreaming.js.map +1 -0
- package/dist/runtime/protocol.d.ts +14 -0
- package/dist/runtime/protocol.d.ts.map +1 -1
- package/dist/runtime/protocol.js +3 -1
- package/dist/runtime/protocol.js.map +1 -1
- package/dist/server/config.d.ts +16 -101
- package/dist/server/config.d.ts.map +1 -1
- package/dist/server/config.js +5 -27
- package/dist/server/config.js.map +1 -1
- package/dist/server/context.d.ts +8 -6
- package/dist/server/context.d.ts.map +1 -1
- package/dist/server/context.js.map +1 -1
- package/dist/server/defineWorker.d.ts +1 -1
- package/dist/server/defineWorker.d.ts.map +1 -1
- package/dist/server/defineWorker.js +2 -1
- package/dist/server/defineWorker.js.map +1 -1
- package/dist/server/devServer.d.ts +1 -1
- package/dist/server/devServer.d.ts.map +1 -1
- package/dist/server/devServer.js +13 -235
- package/dist/server/devServer.js.map +1 -1
- package/dist/server/httpRouter.d.ts.map +1 -1
- package/dist/server/httpRouter.js +5 -2
- package/dist/server/httpRouter.js.map +1 -1
- package/dist/server/httpRpc.d.ts +10 -0
- package/dist/server/httpRpc.d.ts.map +1 -0
- package/dist/server/httpRpc.js +186 -0
- package/dist/server/httpRpc.js.map +1 -0
- package/dist/server/prodServer.d.ts +3 -1
- package/dist/server/prodServer.d.ts.map +1 -1
- package/dist/server/prodServer.js +36 -214
- package/dist/server/prodServer.js.map +1 -1
- package/dist/server/rateLimiter.d.ts +6 -36
- package/dist/server/rateLimiter.d.ts.map +1 -1
- package/dist/server/rateLimiter.js +18 -125
- package/dist/server/rateLimiter.js.map +1 -1
- package/dist/server/requestSignal.d.ts +10 -0
- package/dist/server/requestSignal.d.ts.map +1 -0
- package/dist/server/requestSignal.js +79 -0
- package/dist/server/requestSignal.js.map +1 -0
- package/dist/server/rpcRegistry.d.ts +10 -22
- package/dist/server/rpcRegistry.d.ts.map +1 -1
- package/dist/server/rpcRegistry.js +181 -274
- package/dist/server/rpcRegistry.js.map +1 -1
- package/dist/vite/heliumPlugin.d.ts.map +1 -1
- package/dist/vite/heliumPlugin.js +73 -43
- package/dist/vite/heliumPlugin.js.map +1 -1
- package/dist/vite/ssg.d.ts.map +1 -1
- package/dist/vite/ssg.js +16 -1
- package/dist/vite/ssg.js.map +1 -1
- package/package.json +2 -4
package/dist/server/config.d.ts
CHANGED
|
@@ -1,45 +1,16 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* WebSocket per-message compression configuration.
|
|
3
|
-
* Uses the permessage-deflate extension to compress messages on the wire.
|
|
4
|
-
*/
|
|
5
|
-
export interface HeliumCompressionConfig {
|
|
6
|
-
/**
|
|
7
|
-
* Enable WebSocket per-message compression (permessage-deflate extension).
|
|
8
|
-
* When enabled, messages are compressed before sending to reduce bandwidth usage.
|
|
9
|
-
*
|
|
10
|
-
* @default true
|
|
11
|
-
*/
|
|
12
|
-
enabled?: boolean;
|
|
13
|
-
/**
|
|
14
|
-
* Minimum message size in bytes to apply compression.
|
|
15
|
-
* Messages smaller than this threshold will not be compressed to avoid overhead.
|
|
16
|
-
* Only applies when compression is enabled.
|
|
17
|
-
*
|
|
18
|
-
* @default 1024 (1KB)
|
|
19
|
-
*/
|
|
20
|
-
threshold?: number;
|
|
21
|
-
}
|
|
22
1
|
/**
|
|
23
2
|
* RPC security and rate limiting configuration.
|
|
24
|
-
* Controls
|
|
3
|
+
* Controls per-IP HTTP request limits and token-based protection.
|
|
25
4
|
*/
|
|
26
5
|
export interface HeliumRpcSecurityConfig {
|
|
27
6
|
/**
|
|
28
|
-
* Maximum number of
|
|
29
|
-
* Helps prevent
|
|
30
|
-
* Set to 0 to disable this limit.
|
|
31
|
-
*
|
|
32
|
-
* @default 10
|
|
33
|
-
*/
|
|
34
|
-
maxConnectionsPerIP?: number;
|
|
35
|
-
/**
|
|
36
|
-
* Maximum number of RPC messages allowed per connection within the time window.
|
|
37
|
-
* Helps prevent abuse by limiting message throughput per connection.
|
|
7
|
+
* Maximum number of HTTP RPC requests allowed per client IP within the time window.
|
|
8
|
+
* Helps prevent abuse by limiting HTTP request throughput per client.
|
|
38
9
|
* Set to 0 to disable rate limiting.
|
|
39
10
|
*
|
|
40
11
|
* @default 100
|
|
41
12
|
*/
|
|
42
|
-
|
|
13
|
+
maxRequestsPerWindow?: number;
|
|
43
14
|
/**
|
|
44
15
|
* Time window in milliseconds for rate limiting.
|
|
45
16
|
* Rate limits reset after this duration.
|
|
@@ -48,7 +19,7 @@ export interface HeliumRpcSecurityConfig {
|
|
|
48
19
|
*/
|
|
49
20
|
rateLimitWindowMs?: number;
|
|
50
21
|
/**
|
|
51
|
-
*
|
|
22
|
+
* HTTP RPC token validity duration in milliseconds.
|
|
52
23
|
* Tokens are generated server-side and must be used within this timeframe.
|
|
53
24
|
* Shorter durations improve security but may cause issues with slow networks.
|
|
54
25
|
*
|
|
@@ -107,8 +78,8 @@ export interface HeliumSecurityConfig {
|
|
|
107
78
|
/**
|
|
108
79
|
* Helium framework configuration.
|
|
109
80
|
*
|
|
110
|
-
* Configure your Helium application behavior including RPC
|
|
111
|
-
*
|
|
81
|
+
* Configure your Helium application behavior including HTTP RPC settings,
|
|
82
|
+
* security, and proxy configuration for production deployments.
|
|
112
83
|
*/
|
|
113
84
|
export interface HeliumConfig {
|
|
114
85
|
/**
|
|
@@ -140,7 +111,7 @@ export interface HeliumConfig {
|
|
|
140
111
|
* **Security note:** Setting this too high can allow IP spoofing. Only trust as many
|
|
141
112
|
* proxy levels as you actually have in your infrastructure.
|
|
142
113
|
*
|
|
143
|
-
* This setting applies to
|
|
114
|
+
* This setting applies to HTTP requests.
|
|
144
115
|
*
|
|
145
116
|
* @default 0
|
|
146
117
|
*/
|
|
@@ -151,50 +122,11 @@ export interface HeliumConfig {
|
|
|
151
122
|
*/
|
|
152
123
|
security?: HeliumSecurityConfig;
|
|
153
124
|
/**
|
|
154
|
-
* RPC
|
|
125
|
+
* HTTP RPC configuration.
|
|
155
126
|
*
|
|
156
|
-
* Configure
|
|
157
|
-
* and security settings.
|
|
127
|
+
* Configure HTTP RPC request limits and security settings.
|
|
158
128
|
*/
|
|
159
129
|
rpc?: {
|
|
160
|
-
/**
|
|
161
|
-
* Client-side transport mode for RPC calls.
|
|
162
|
-
*
|
|
163
|
-
* - `"websocket"` (default): Uses persistent WebSocket connection
|
|
164
|
-
* - ✅ Lower latency for subsequent calls (connection reuse)
|
|
165
|
-
* - ✅ Real-time bidirectional communication ready
|
|
166
|
-
* - ⚠️ Higher initial connection overhead
|
|
167
|
-
*
|
|
168
|
-
* - `"http"`: Uses HTTP POST requests for each RPC call
|
|
169
|
-
* - ✅ Better performance on mobile/cellular networks (HTTP/2 optimizations)
|
|
170
|
-
* - ✅ No connection state to maintain
|
|
171
|
-
* - ⚠️ Slightly higher per-request overhead on fast networks
|
|
172
|
-
*
|
|
173
|
-
* - `"auto"`: Automatically selects based on network conditions
|
|
174
|
-
* - Uses HTTP on cellular/slow networks when `autoHttpOnMobile` is true
|
|
175
|
-
* - Uses WebSocket on fast networks (WiFi, wired)
|
|
176
|
-
*
|
|
177
|
-
* @default "websocket"
|
|
178
|
-
*/
|
|
179
|
-
transport?: "http" | "websocket" | "auto";
|
|
180
|
-
/**
|
|
181
|
-
* Automatically switch to HTTP transport on mobile/cellular networks.
|
|
182
|
-
*
|
|
183
|
-
* When enabled and `transport` is `"auto"`, the client will use HTTP
|
|
184
|
-
* instead of WebSocket on cellular connections (4G/LTE, 5G) and slow
|
|
185
|
-
* connections (2G, 3G). This improves performance on mobile networks
|
|
186
|
-
* where HTTP/2 is more efficient due to carrier network optimizations.
|
|
187
|
-
*
|
|
188
|
-
* @default false
|
|
189
|
-
*/
|
|
190
|
-
autoHttpOnMobile?: boolean;
|
|
191
|
-
/**
|
|
192
|
-
* WebSocket per-message compression configuration.
|
|
193
|
-
*
|
|
194
|
-
* Enable and configure the permessage-deflate extension to compress
|
|
195
|
-
* messages on the wire, reducing bandwidth usage.
|
|
196
|
-
*/
|
|
197
|
-
compression?: HeliumCompressionConfig;
|
|
198
130
|
/**
|
|
199
131
|
* RPC security and rate limiting configuration.
|
|
200
132
|
*
|
|
@@ -216,13 +148,6 @@ export interface HeliumConfig {
|
|
|
216
148
|
* @default 20
|
|
217
149
|
*/
|
|
218
150
|
maxBatchSize?: number;
|
|
219
|
-
/**
|
|
220
|
-
* Maximum WebSocket message payload size in bytes.
|
|
221
|
-
* Messages exceeding this limit cause the connection to be closed.
|
|
222
|
-
*
|
|
223
|
-
* @default 1048576 (1 MB)
|
|
224
|
-
*/
|
|
225
|
-
maxWsPayload?: number;
|
|
226
151
|
};
|
|
227
152
|
}
|
|
228
153
|
/**
|
|
@@ -245,45 +170,35 @@ export declare function loadConfig(root?: string): Promise<HeliumConfig>;
|
|
|
245
170
|
export declare function getTrustProxyDepth(config?: HeliumConfig): number;
|
|
246
171
|
/**
|
|
247
172
|
* Get RPC security configuration with defaults applied.
|
|
248
|
-
* Returns rate limiting
|
|
173
|
+
* Returns HTTP rate limiting and token settings.
|
|
249
174
|
*
|
|
250
175
|
* @internal - Used by framework internals only
|
|
251
176
|
*/
|
|
252
177
|
export declare function getRpcSecurityConfig(config?: HeliumConfig): Required<HeliumRpcSecurityConfig>;
|
|
253
178
|
/**
|
|
254
|
-
* Get
|
|
255
|
-
*
|
|
256
|
-
* @internal - Used by framework internals only
|
|
257
|
-
*/
|
|
258
|
-
export declare function getCompressionConfig(config?: HeliumConfig): Required<HeliumCompressionConfig>;
|
|
259
|
-
/**
|
|
260
|
-
* Get complete RPC configuration including compression, and security.
|
|
179
|
+
* Get HTTP RPC configuration, including request limits and security.
|
|
261
180
|
*
|
|
262
181
|
* @internal - Used by framework internals only
|
|
263
182
|
*/
|
|
264
183
|
export declare function getRpcConfig(config?: HeliumConfig): {
|
|
265
|
-
compression: Required<HeliumCompressionConfig>;
|
|
266
184
|
security: Required<HeliumRpcSecurityConfig>;
|
|
267
185
|
maxBodySize: number;
|
|
268
186
|
maxBatchSize: number;
|
|
269
|
-
maxWsPayload: number;
|
|
270
187
|
};
|
|
271
188
|
/**
|
|
272
|
-
* Client-side RPC
|
|
189
|
+
* Client-side HTTP RPC configuration.
|
|
273
190
|
* This is injected into the client bundle at build time.
|
|
274
191
|
*/
|
|
275
|
-
export interface
|
|
276
|
-
transport: "http" | "websocket" | "auto";
|
|
277
|
-
autoHttpOnMobile: boolean;
|
|
192
|
+
export interface RpcClientConfig {
|
|
278
193
|
tokenValidityMs: number;
|
|
279
194
|
}
|
|
280
195
|
/**
|
|
281
|
-
* Get client-side RPC
|
|
196
|
+
* Get client-side HTTP RPC configuration.
|
|
282
197
|
* This configuration is injected into the client bundle via Vite defines.
|
|
283
198
|
*
|
|
284
199
|
* @internal - Used by framework internals only
|
|
285
200
|
*/
|
|
286
|
-
export declare function getRpcClientConfig(config?: HeliumConfig):
|
|
201
|
+
export declare function getRpcClientConfig(config?: HeliumConfig): RpcClientConfig;
|
|
287
202
|
/**
|
|
288
203
|
* Clear the cached configuration.
|
|
289
204
|
* Useful for testing or when you need to reload config.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/server/config.ts"],"names":[],"mappings":"AAKA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACpC
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/server/config.ts"],"names":[],"mappings":"AAKA;;;GAGG;AACH,MAAM,WAAW,uBAAuB;IACpC;;;;;;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;;;;;;;;OAQG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC,CAAC;IAEhD;;;;;;OAMG;IACH,qBAAqB,CAAC,EAAE,MAAM,CAAC;IAE/B;;;;;;OAMG;IACH,IAAI,CAAC,EAAE,OAAO,CAAC;IAEf;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CAC1B;AAED;;;;;GAKG;AACH,MAAM,WAAW,YAAY;IACzB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAgCG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;;OAGG;IACH,QAAQ,CAAC,EAAE,oBAAoB,CAAC;IAEhC;;;;OAIG;IACH,GAAG,CAAC,EAAE;QACF;;;;;WAKG;QACH,QAAQ,CAAC,EAAE,uBAAuB,CAAC;QAEnC;;;;;WAKG;QACH,WAAW,CAAC,EAAE,MAAM,CAAC;QAErB;;;;;WAKG;QACH,YAAY,CAAC,EAAE,MAAM,CAAC;KACzB,CAAC;CACL;AAUD;;;;;;;;;GASG;AACH,wBAAsB,UAAU,CAAC,IAAI,GAAE,MAAsB,GAAG,OAAO,CAAC,YAAY,CAAC,CAoCpF;AA6BD;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,GAAE,YAAiB,GAAG,MAAM,CAEpE;AAED;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,GAAE,YAAiB,GAAG,QAAQ,CAAC,uBAAuB,CAAC,CAQjG;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,MAAM,GAAE,YAAiB;;;;EAMrD;AAED;;;GAGG;AACH,MAAM,WAAW,eAAe;IAC5B,eAAe,EAAE,MAAM,CAAC;CAC3B;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,GAAE,YAAiB,GAAG,eAAe,CAI7E;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,SAE/B"}
|
package/dist/server/config.js
CHANGED
|
@@ -3,15 +3,10 @@ import fs from "fs";
|
|
|
3
3
|
import path from "path";
|
|
4
4
|
import { pathToFileURL } from "url";
|
|
5
5
|
const DEFAULT_RPC_SECURITY = {
|
|
6
|
-
|
|
7
|
-
maxMessagesPerWindow: 100,
|
|
6
|
+
maxRequestsPerWindow: 100,
|
|
8
7
|
rateLimitWindowMs: 60000,
|
|
9
8
|
tokenValidityMs: 30000,
|
|
10
9
|
};
|
|
11
|
-
const DEFAULT_COMPRESSION = {
|
|
12
|
-
enabled: true,
|
|
13
|
-
threshold: 1024,
|
|
14
|
-
};
|
|
15
10
|
const cachedConfigs = new Map();
|
|
16
11
|
/**
|
|
17
12
|
* Load Helium configuration from the project root.
|
|
@@ -95,55 +90,38 @@ export function getTrustProxyDepth(config = {}) {
|
|
|
95
90
|
}
|
|
96
91
|
/**
|
|
97
92
|
* Get RPC security configuration with defaults applied.
|
|
98
|
-
* Returns rate limiting
|
|
93
|
+
* Returns HTTP rate limiting and token settings.
|
|
99
94
|
*
|
|
100
95
|
* @internal - Used by framework internals only
|
|
101
96
|
*/
|
|
102
97
|
export function getRpcSecurityConfig(config = {}) {
|
|
103
98
|
const src = config.rpc?.security;
|
|
104
99
|
return {
|
|
105
|
-
|
|
106
|
-
maxMessagesPerWindow: src?.maxMessagesPerWindow ?? DEFAULT_RPC_SECURITY.maxMessagesPerWindow,
|
|
100
|
+
maxRequestsPerWindow: src?.maxRequestsPerWindow ?? DEFAULT_RPC_SECURITY.maxRequestsPerWindow,
|
|
107
101
|
rateLimitWindowMs: src?.rateLimitWindowMs ?? DEFAULT_RPC_SECURITY.rateLimitWindowMs,
|
|
108
102
|
tokenValidityMs: src?.tokenValidityMs ?? DEFAULT_RPC_SECURITY.tokenValidityMs,
|
|
109
103
|
};
|
|
110
104
|
}
|
|
111
105
|
/**
|
|
112
|
-
* Get
|
|
113
|
-
*
|
|
114
|
-
* @internal - Used by framework internals only
|
|
115
|
-
*/
|
|
116
|
-
export function getCompressionConfig(config = {}) {
|
|
117
|
-
const src = config.rpc?.compression;
|
|
118
|
-
return {
|
|
119
|
-
enabled: src?.enabled ?? DEFAULT_COMPRESSION.enabled,
|
|
120
|
-
threshold: src?.threshold ?? DEFAULT_COMPRESSION.threshold,
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
/**
|
|
124
|
-
* Get complete RPC configuration including compression, and security.
|
|
106
|
+
* Get HTTP RPC configuration, including request limits and security.
|
|
125
107
|
*
|
|
126
108
|
* @internal - Used by framework internals only
|
|
127
109
|
*/
|
|
128
110
|
export function getRpcConfig(config = {}) {
|
|
129
111
|
return {
|
|
130
|
-
compression: getCompressionConfig(config),
|
|
131
112
|
security: getRpcSecurityConfig(config),
|
|
132
113
|
maxBodySize: config.rpc?.maxBodySize ?? 1048576,
|
|
133
114
|
maxBatchSize: config.rpc?.maxBatchSize ?? 20,
|
|
134
|
-
maxWsPayload: config.rpc?.maxWsPayload ?? 1048576,
|
|
135
115
|
};
|
|
136
116
|
}
|
|
137
117
|
/**
|
|
138
|
-
* Get client-side RPC
|
|
118
|
+
* Get client-side HTTP RPC configuration.
|
|
139
119
|
* This configuration is injected into the client bundle via Vite defines.
|
|
140
120
|
*
|
|
141
121
|
* @internal - Used by framework internals only
|
|
142
122
|
*/
|
|
143
123
|
export function getRpcClientConfig(config = {}) {
|
|
144
124
|
return {
|
|
145
|
-
transport: config.rpc?.transport ?? "websocket",
|
|
146
|
-
autoHttpOnMobile: config.rpc?.autoHttpOnMobile ?? false,
|
|
147
125
|
tokenValidityMs: getRpcSecurityConfig(config).tokenValidityMs,
|
|
148
126
|
};
|
|
149
127
|
}
|
|
@@ -1 +1 @@
|
|
|
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,IAAI,IAAI,CAAC;IACxD,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE,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AAS;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
|
+
{"version":3,"file":"config.js","source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AU,YAAY,CAAC,SAAuB,EAAE;IAClD,OAAO;QACH,QAAQ,EAAE,oBAAoB,CAAC,MAAM,CAAC;QACtC,WAAW,EAAE,MAAM,CAAC,GAAG,EAAE,WAAW,IAAI,OAAS;QACjD,YAAY,EAAE,MAAM,CAAC,GAAG,EAAE,YAAY,IAAI,EAAE;KAC/C,CAAC;AACN,CAAC;AAUD;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAAC,SAAuB,EAAE;IACxD,OAAO;QACH,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 * RPC security and rate limiting configuration.\n * Controls per-IP HTTP request limits and token-based protection.\n */\nexport interface HeliumRpcSecurityConfig {\n /**\n * Maximum number of HTTP RPC requests allowed per client IP within the time window.\n * Helps prevent abuse by limiting HTTP request throughput per client.\n * Set to 0 to disable rate limiting.\n *\n * @default 100\n */\n maxRequestsPerWindow?: 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 * HTTP RPC 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 HTTP RPC settings,\n * 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 HTTP requests.\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 * HTTP RPC configuration.\n *\n * Configure HTTP RPC request limits and security settings.\n */\n rpc?: {\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\nconst DEFAULT_RPC_SECURITY: Required<HeliumRpcSecurityConfig> = {\n maxRequestsPerWindow: 100,\n rateLimitWindowMs: 60000,\n tokenValidityMs: 30000,\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 HTTP rate limiting 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 maxRequestsPerWindow: src?.maxRequestsPerWindow ?? DEFAULT_RPC_SECURITY.maxRequestsPerWindow,\n rateLimitWindowMs: src?.rateLimitWindowMs ?? DEFAULT_RPC_SECURITY.rateLimitWindowMs,\n tokenValidityMs: src?.tokenValidityMs ?? DEFAULT_RPC_SECURITY.tokenValidityMs,\n };\n}\n\n/**\n * Get HTTP RPC configuration, including request limits and security.\n *\n * @internal - Used by framework internals only\n */\nexport function getRpcConfig(config: HeliumConfig = {}) {\n return {\n security: getRpcSecurityConfig(config),\n maxBodySize: config.rpc?.maxBodySize ?? 1_048_576,\n maxBatchSize: config.rpc?.maxBatchSize ?? 20,\n };\n}\n\n/**\n * Client-side HTTP RPC configuration.\n * This is injected into the client bundle at build time.\n */\nexport interface RpcClientConfig {\n tokenValidityMs: number;\n}\n\n/**\n * Get client-side HTTP RPC 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 = {}): RpcClientConfig {\n return {\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"]}
|
package/dist/server/context.d.ts
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
import type http from "http";
|
|
2
2
|
/**
|
|
3
3
|
* Context passed to RPC method handlers.
|
|
4
|
-
* Contains request information and metadata
|
|
4
|
+
* Contains request information and cancellation metadata.
|
|
5
5
|
*/
|
|
6
6
|
export interface HeliumContext {
|
|
7
|
+
/** Aborted when the caller disconnects. Pass to upstream fetch/LLM providers. */
|
|
8
|
+
signal: AbortSignal;
|
|
7
9
|
/**
|
|
8
|
-
* The HTTP request
|
|
9
|
-
* Contains headers, client IP, and
|
|
10
|
+
* The current HTTP request.
|
|
11
|
+
* Contains headers, client IP, and request metadata.
|
|
10
12
|
*/
|
|
11
13
|
req: {
|
|
12
14
|
/**
|
|
@@ -14,15 +16,15 @@ export interface HeliumContext {
|
|
|
14
16
|
*/
|
|
15
17
|
ip: string;
|
|
16
18
|
/**
|
|
17
|
-
* HTTP headers
|
|
19
|
+
* HTTP request headers.
|
|
18
20
|
*/
|
|
19
21
|
headers: http.IncomingHttpHeaders;
|
|
20
22
|
/**
|
|
21
|
-
* The
|
|
23
|
+
* The HTTP request URL.
|
|
22
24
|
*/
|
|
23
25
|
url?: string;
|
|
24
26
|
/**
|
|
25
|
-
* The HTTP method
|
|
27
|
+
* The HTTP request method.
|
|
26
28
|
*/
|
|
27
29
|
method?: string;
|
|
28
30
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/server/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC1B;;;OAGG;IACH,GAAG,EAAE;QACD;;WAEG;QACH,EAAE,EAAE,MAAM,CAAC;QACX;;WAEG;QACH,OAAO,EAAE,IAAI,CAAC,mBAAmB,CAAC;QAClC;;WAEG;QACH,GAAG,CAAC,EAAE,MAAM,CAAC;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB;;WAEG;QACH,GAAG,EAAE,IAAI,CAAC,eAAe,CAAC;KAC7B,CAAC;IACF;;OAEG;IACH,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B"}
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/server/context.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC1B,iFAAiF;IACjF,MAAM,EAAE,WAAW,CAAC;IACpB;;;OAGG;IACH,GAAG,EAAE;QACD;;WAEG;QACH,EAAE,EAAE,MAAM,CAAC;QACX;;WAEG;QACH,OAAO,EAAE,IAAI,CAAC,mBAAmB,CAAC;QAClC;;WAEG;QACH,GAAG,CAAC,EAAE,MAAM,CAAC;QACb;;WAEG;QACH,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB;;WAEG;QACH,GAAG,EAAE,IAAI,CAAC,eAAe,CAAC;KAC7B,CAAC;IACF;;OAEG;IACH,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;CAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/server/context.ts"],"names":[],"mappings":"","sourcesContent":["import type http from \"http\";\n\n/**\n * Context passed to RPC method handlers.\n * Contains request information and metadata
|
|
1
|
+
{"version":3,"file":"context.js","sourceRoot":"","sources":["../../src/server/context.ts"],"names":[],"mappings":"","sourcesContent":["import type http from \"http\";\n\n/**\n * Context passed to RPC method handlers.\n * Contains request information and cancellation metadata.\n */\nexport interface HeliumContext {\n /** Aborted when the caller disconnects. Pass to upstream fetch/LLM providers. */\n signal: AbortSignal;\n /**\n * The current HTTP request.\n * Contains headers, client IP, and request metadata.\n */\n req: {\n /**\n * The client's IP address, extracted based on trustProxyDepth configuration.\n */\n ip: string;\n /**\n * HTTP request headers.\n */\n headers: http.IncomingHttpHeaders;\n /**\n * The HTTP request URL.\n */\n url?: string;\n /**\n * The HTTP request method.\n */\n method?: string;\n /**\n * The original http.IncomingMessage for advanced use cases.\n */\n raw: http.IncomingMessage;\n };\n /**\n * Custom properties can be added by middleware.\n */\n [key: string]: unknown;\n}\n"]}
|
|
@@ -58,7 +58,7 @@ export interface WorkerInstance {
|
|
|
58
58
|
* - Background task processors
|
|
59
59
|
* - Scheduled jobs and cron-like tasks
|
|
60
60
|
* - Real-time data synchronization
|
|
61
|
-
* -
|
|
61
|
+
* - External connection managers
|
|
62
62
|
* - Cache warmers and data pre-loaders
|
|
63
63
|
*
|
|
64
64
|
* @example
|
|
@@ -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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EAAE,SAAS,GAAG,SAAS,GAAG,SAAS,GAAG,YAAY,CAAC;IACzD,SAAS,EAAE,IAAI,GAAG,IAAI,CAAC;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,KAAK,CAAC;IAClB,IAAI,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;CAC7B;AA4FD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,aAAa,EAAE,OAAO,GAAE,aAAkB,GAAG,eAAe,CAsBjG;AAED;;;GAGG;AACH,wBAAsB,WAAW,CAAC,MAAM,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,aAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CAmHtH;AAED;;GAEG;AACH,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAOhD;AAED;;GAEG;AACH,wBAAsB,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC,CAIpD;AAED;;GAEG;AACH,wBAAgB,eAAe,IAAI,cAAc,EAAE,CAElD;AAED;;GAEG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAEtE"}
|
|
@@ -81,7 +81,7 @@ function waitForAbort(signal) {
|
|
|
81
81
|
* - Background task processors
|
|
82
82
|
* - Scheduled jobs and cron-like tasks
|
|
83
83
|
* - Real-time data synchronization
|
|
84
|
-
* -
|
|
84
|
+
* - External connection managers
|
|
85
85
|
* - Cache warmers and data pre-loaders
|
|
86
86
|
*
|
|
87
87
|
* @example
|
|
@@ -181,6 +181,7 @@ export async function startWorker(worker, createContext) {
|
|
|
181
181
|
instance.startedAt = new Date();
|
|
182
182
|
log("info", `Starting worker '${name}'`);
|
|
183
183
|
const ctx = createContext();
|
|
184
|
+
ctx.signal = abortController.signal;
|
|
184
185
|
const lifecycle = {
|
|
185
186
|
signal: abortController.signal,
|
|
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AAC,IAAI,EAAE,WAAW,CAAC,CAAC;IACtC,WAAW,CAAC,OAAO,GAAG,SAAS,EAAE,CAAC;IAElC,OAAO,QAAQ,CAAC;AACpB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,IAAY;IACnC,MAAM,MAAM,GAAG,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;IACxC,IAAI,MAAM,EAAE,CAAC;QACT,KAAK,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC;QAC5B,OAAO,IAAI,CAAC;IAChB,CAAC;IACD,OAAO,KAAK,CAAC;AACjB,CAAC;AAED;;GAEG;AACH,MAAM,CAAC,KAAK,UAAU,cAAc;IAChC,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC;IACpD,MAAM,OAAO,CAAC,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC;IACnE,GAAG,CAAC,MAAM,EAAE,WAAW,OAAO,CAAC,MAAM,YAAY,CAAC,CAAC;AACvD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,eAAe;IAC3B,OAAO,KAAK,CAAC,IAAI,CAAC,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AACtE,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACtC,OAAO,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC;AAC9C,CAAC","sourcesContent":["import { log } from \"../utils/logger.js\";\nimport type { HeliumContext } from \"./context.js\";\n\nexport type WorkerCleanup = (() => Promise<void> | void) | void;\n\nexport interface WorkerLifecycle {\n signal: AbortSignal;\n onCleanup: (cleanup: WorkerCleanup) => void;\n}\n\nexport interface WorkerOptions {\n /**\n * The name of the worker, used for logging and identification.\n * If not provided, the handler function name will be used.\n */\n name?: string;\n\n /**\n * Whether the worker should automatically restart if it crashes.\n * Default: true\n */\n autoRestart?: boolean;\n\n /**\n * Delay in milliseconds before restarting the worker after a crash.\n * Default: 5000 (5 seconds)\n */\n restartDelayMs?: number;\n\n /**\n * Maximum number of restart attempts before giving up.\n * Set to 0 for unlimited restarts.\n * Default: 0 (unlimited)\n */\n maxRestarts?: number;\n\n /**\n * Whether to start the worker automatically on server startup.\n * Default: true\n */\n autoStart?: boolean;\n}\n\nexport type WorkerHandler = (ctx: HeliumContext, lifecycle: WorkerLifecycle) => Promise<WorkerCleanup> | WorkerCleanup;\n\nexport type HeliumWorkerDef = {\n __kind: \"worker\";\n __id: string;\n name: string;\n handler: WorkerHandler;\n options: Required<WorkerOptions>;\n};\n\nexport interface WorkerInstance {\n id: string;\n name: string;\n status: \"running\" | \"stopped\" | \"crashed\" | \"restarting\";\n startedAt: Date | null;\n restartCount: number;\n lastError?: Error;\n stop: () => Promise<void>;\n}\n\ninterface WorkerState {\n abortController: AbortController;\n promise: Promise<void>;\n instance: WorkerInstance;\n cleanupHandlers: Array<() => Promise<void> | void>;\n cleanupPromise: Promise<void> | null;\n cleanupRequested: boolean;\n}\n\nconst runningWorkers = new Map<string, WorkerState>();\n\nfunction removeWorker(name: string, workerState: WorkerState): void {\n if (runningWorkers.get(name) === workerState) {\n runningWorkers.delete(name);\n }\n}\n\nfunction isCleanupHandler(cleanup: WorkerCleanup): cleanup is () => Promise<void> | void {\n return typeof cleanup === \"function\";\n}\n\nfunction registerCleanup(name: string, workerState: WorkerState, cleanup: WorkerCleanup) {\n if (!isCleanupHandler(cleanup)) {\n return;\n }\n\n workerState.cleanupHandlers.push(cleanup);\n // Async setup may finish after stop() has returned. Dispose its resources too.\n if (workerState.cleanupRequested) {\n void runWorkerCleanup(name, workerState);\n }\n}\n\nasync function runWorkerCleanup(name: string, workerState: WorkerState): Promise<void> {\n workerState.cleanupRequested = true;\n if (workerState.cleanupPromise) {\n await workerState.cleanupPromise;\n if (workerState.cleanupHandlers.length > 0) {\n await runWorkerCleanup(name, workerState);\n }\n return;\n }\n\n const cleanupPromise = (async () => {\n while (workerState.cleanupHandlers.length > 0) {\n const cleanupHandlers = workerState.cleanupHandlers.splice(0).reverse();\n for (const cleanup of cleanupHandlers) {\n try {\n await cleanup();\n } catch (error) {\n log(\"error\", `Worker '${name}' cleanup failed:`, error);\n }\n }\n }\n })();\n workerState.cleanupPromise = cleanupPromise;\n try {\n await cleanupPromise;\n } finally {\n if (workerState.cleanupPromise === cleanupPromise) {\n workerState.cleanupPromise = null;\n }\n }\n}\n\nfunction waitForRestart(signal: AbortSignal, delay: number): Promise<void> {\n if (signal.aborted) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n const done = () => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, delay);\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nfunction waitForAbort(signal: AbortSignal): Promise<void> {\n if (signal.aborted) {\n return Promise.resolve();\n }\n\n return new Promise((resolve) => {\n signal.addEventListener(\"abort\", () => resolve(), { once: true });\n });\n}\n\n/**\n * Create a Helium background worker definition.\n *\n * Workers are long-running background processes that start when the server\n * starts and continue running until the server shuts down. They are ideal for:\n * - Queue consumers (processing jobs from Redis, RabbitMQ, SQS, etc.)\n * - Background task processors\n * - Scheduled jobs and cron-like tasks\n * - Real-time data synchronization\n * - WebSocket connection managers\n * - Cache warmers and data pre-loaders\n *\n * @example\n * ```typescript\n * // Basic worker\n * export const queueConsumer = defineWorker(async (ctx) => {\n * while (true) {\n * const job = await queue.pop();\n * if (job) {\n * await processJob(job);\n * }\n * await sleep(1000);\n * }\n * }, { name: 'queueConsumer' });\n *\n * // Worker with options\n * export const dataSync = defineWorker(async (ctx) => {\n * // Sync data every 30 seconds\n * while (true) {\n * await syncData();\n * await sleep(30000);\n * }\n * }, {\n * name: 'dataSync',\n * autoRestart: true,\n * restartDelayMs: 10000,\n * maxRestarts: 5\n * });\n * ```\n *\n * @param handler - The worker function that runs in the background\n * @param options - Configuration options for the worker\n * @returns A HeliumWorkerDef that will be started by the server runtime\n */\nexport function defineWorker(handler: WorkerHandler, options: WorkerOptions = {}): HeliumWorkerDef {\n if (!handler) {\n throw new Error(\"defineWorker requires a handler\");\n }\n\n const name = options.name || handler.name || \"anonymous\";\n\n const resolvedOptions: Required<WorkerOptions> = {\n name,\n autoRestart: options.autoRestart ?? true,\n restartDelayMs: options.restartDelayMs ?? 5000,\n maxRestarts: options.maxRestarts ?? 0,\n autoStart: options.autoStart ?? true,\n };\n\n return {\n __kind: \"worker\",\n __id: name,\n name,\n handler,\n options: resolvedOptions,\n };\n}\n\n/**\n * Start a worker and manage its lifecycle.\n * @internal\n */\nexport async function startWorker(worker: HeliumWorkerDef, createContext: () => HeliumContext): Promise<WorkerInstance> {\n const { name, handler, options } = worker;\n\n // Check if worker is already running\n if (runningWorkers.has(name)) {\n const existing = runningWorkers.get(name)!;\n log(\"warn\", `Worker '${name}' is already running`);\n return existing.instance;\n }\n\n const abortController = new AbortController();\n let restartCount = 0;\n const workerState = {\n abortController,\n promise: Promise.resolve(),\n instance: undefined as unknown as WorkerInstance,\n cleanupHandlers: [] as Array<() => Promise<void> | void>,\n cleanupPromise: null as Promise<void> | null,\n cleanupRequested: false,\n };\n\n const instance: WorkerInstance = {\n id: name,\n name,\n status: \"running\",\n startedAt: new Date(),\n restartCount: 0,\n stop: async () => {\n abortController.abort();\n instance.status = \"stopped\";\n await runWorkerCleanup(name, workerState);\n removeWorker(name, workerState);\n log(\"info\", `Worker '${name}' stopped`);\n },\n };\n workerState.instance = instance;\n\n const runWorker = async (): Promise<void> => {\n while (!abortController.signal.aborted) {\n try {\n workerState.cleanupRequested = false;\n instance.status = \"running\";\n instance.startedAt = new Date();\n log(\"info\", `Starting worker '${name}'`);\n\n const ctx = createContext();\n const lifecycle: WorkerLifecycle = {\n signal: abortController.signal,\n onCleanup: (cleanup) => {\n registerCleanup(name, workerState, cleanup);\n },\n };\n const cleanup = await handler(ctx, lifecycle);\n registerCleanup(name, workerState, cleanup);\n\n if (isCleanupHandler(cleanup) && !abortController.signal.aborted) {\n await waitForAbort(abortController.signal);\n }\n\n // If handler completes normally, exit the loop\n if (!abortController.signal.aborted) {\n await runWorkerCleanup(name, workerState);\n log(\"info\", `Worker '${name}' completed successfully`);\n instance.status = \"stopped\";\n removeWorker(name, workerState);\n } else {\n await runWorkerCleanup(name, workerState);\n }\n break;\n } catch (error) {\n if (abortController.signal.aborted) {\n // Worker was intentionally stopped\n break;\n }\n\n await runWorkerCleanup(name, workerState);\n if (abortController.signal.aborted) {\n break;\n }\n\n instance.lastError = error instanceof Error ? error : new Error(String(error));\n instance.status = \"crashed\";\n log(\"error\", `Worker '${name}' crashed:`, error);\n\n // Check if we should restart\n if (options.autoRestart) {\n if (options.maxRestarts > 0 && restartCount >= options.maxRestarts) {\n log(\"error\", `Worker '${name}' exceeded max restarts (${options.maxRestarts}), giving up`);\n removeWorker(name, workerState);\n break;\n }\n\n restartCount++;\n instance.restartCount = restartCount;\n instance.status = \"restarting\";\n log(\n \"info\",\n `Worker '${name}' will restart in ${options.restartDelayMs}ms (attempt ${restartCount}${options.maxRestarts > 0 ? `/${options.maxRestarts}` : \"\"})`\n );\n\n await waitForRestart(abortController.signal, options.restartDelayMs);\n } else {\n removeWorker(name, workerState);\n break;\n }\n }\n }\n };\n\n // Publish state before invoking user code, including synchronous handlers.\n runningWorkers.set(name, workerState);\n workerState.promise = runWorker();\n\n return instance;\n}\n\n/**\n * Stop a running worker by name.\n */\nexport function stopWorker(name: string): boolean {\n const worker = runningWorkers.get(name);\n if (worker) {\n void worker.instance.stop();\n return true;\n }\n return false;\n}\n\n/**\n * Stop all running workers.\n */\nexport async function stopAllWorkers(): Promise<void> {\n const workers = Array.from(runningWorkers.values());\n await Promise.all(workers.map((worker) => worker.instance.stop()));\n log(\"info\", `Stopped ${workers.length} worker(s)`);\n}\n\n/**\n * Get the status of all workers.\n */\nexport function getWorkerStatus(): WorkerInstance[] {\n return Array.from(runningWorkers.values()).map((w) => w.instance);\n}\n\n/**\n * Get a specific worker's status.\n */\nexport function getWorkerById(name: string): WorkerInstance | undefined {\n return runningWorkers.get(name)?.instance;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"defineWorker.js","sourceRoot":"","sources":["../../src/server/defineWorker.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAwEzC,MAAM,cAAc,GAAG,IAAI,GAAG,EAAuB,CAAC;AAEtD,SAAS,YAAY,CAAC,IAAY,EAAE,WAAwB;IACxD,IAAI,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,KAAK,WAAW,EAAE,CAAC;QAC3C,cAAc,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;AACL,CAAC;AAED,SAAS,gBAAgB,CAAC,OAAsB;IAC5C,OAAO,OAAO,OAAO,KAAK,UAAU,CAAC;AACzC,CAAC;AAED,SAAS,eAAe,CAAC,IAAY,EAAE,WAAwB,EAAE,OAAsB;IACnF,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7B,OAAO;IACX,CAAC;IAED,WAAW,CAAC,eAAe,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAC1C,+EAA+E;IAC/E,IAAI,WAAW,CAAC,gBAAgB,EAAE,CAAC;QAC/B,KAAK,gBAAgB,CAAC,IAAI,EAAE,WAAW,CAAC,CAAC;IAC7C,CAAC;AACL,CAAC;AAED,KAAK,UAAU,gBAAgB,CAAC,IAAY,EAAE,WAAwB;IAClE,WAAW,CAAC,gBAAgB,GAAG,IAAI,CAAC;IACpC,IAAI,WAAW,CAAC,cAAc,EAAE,CAAC;QAC7B,MAAM,WAAW,CAAC,cAAc,CAAC;QACjC,IAAI,WAAW,CAAC,eAAe,CAAC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AO,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC;AAC9C,CAAC","sourcesContent":["import { log } from \"../utils/logger.js\";\nimport type { HeliumContext } from \"./context.js\";\n\nexport type WorkerCleanup = (() => Promise<void> | void) | void;\n\nexport interface WorkerLifecycle {\n signal: AbortSignal;\n onCleanup: (cleanup: WorkerCleanup) => void;\n}\n\nexport interface WorkerOptions {\n /**\n * The name of the worker, used for logging and identification.\n * If not provided, the handler function name will be used.\n */\n name?: string;\n\n /**\n * Whether the worker should automatically restart if it crashes.\n * Default: true\n */\n autoRestart?: boolean;\n\n /**\n * Delay in milliseconds before restarting the worker after a crash.\n * Default: 5000 (5 seconds)\n */\n restartDelayMs?: number;\n\n /**\n * Maximum number of restart attempts before giving up.\n * Set to 0 for unlimited restarts.\n * Default: 0 (unlimited)\n */\n maxRestarts?: number;\n\n /**\n * Whether to start the worker automatically on server startup.\n * Default: true\n */\n autoStart?: boolean;\n}\n\nexport type WorkerHandler = (ctx: HeliumContext, lifecycle: WorkerLifecycle) => Promise<WorkerCleanup> | WorkerCleanup;\n\nexport type HeliumWorkerDef = {\n __kind: \"worker\";\n __id: string;\n name: string;\n handler: WorkerHandler;\n options: Required<WorkerOptions>;\n};\n\nexport interface WorkerInstance {\n id: string;\n name: string;\n status: \"running\" | \"stopped\" | \"crashed\" | \"restarting\";\n startedAt: Date | null;\n restartCount: number;\n lastError?: Error;\n stop: () => Promise<void>;\n}\n\ninterface WorkerState {\n abortController: AbortController;\n promise: Promise<void>;\n instance: WorkerInstance;\n cleanupHandlers: Array<() => Promise<void> | void>;\n cleanupPromise: Promise<void> | null;\n cleanupRequested: boolean;\n}\n\nconst runningWorkers = new Map<string, WorkerState>();\n\nfunction removeWorker(name: string, workerState: WorkerState): void {\n if (runningWorkers.get(name) === workerState) {\n runningWorkers.delete(name);\n }\n}\n\nfunction isCleanupHandler(cleanup: WorkerCleanup): cleanup is () => Promise<void> | void {\n return typeof cleanup === \"function\";\n}\n\nfunction registerCleanup(name: string, workerState: WorkerState, cleanup: WorkerCleanup) {\n if (!isCleanupHandler(cleanup)) {\n return;\n }\n\n workerState.cleanupHandlers.push(cleanup);\n // Async setup may finish after stop() has returned. Dispose its resources too.\n if (workerState.cleanupRequested) {\n void runWorkerCleanup(name, workerState);\n }\n}\n\nasync function runWorkerCleanup(name: string, workerState: WorkerState): Promise<void> {\n workerState.cleanupRequested = true;\n if (workerState.cleanupPromise) {\n await workerState.cleanupPromise;\n if (workerState.cleanupHandlers.length > 0) {\n await runWorkerCleanup(name, workerState);\n }\n return;\n }\n\n const cleanupPromise = (async () => {\n while (workerState.cleanupHandlers.length > 0) {\n const cleanupHandlers = workerState.cleanupHandlers.splice(0).reverse();\n for (const cleanup of cleanupHandlers) {\n try {\n await cleanup();\n } catch (error) {\n log(\"error\", `Worker '${name}' cleanup failed:`, error);\n }\n }\n }\n })();\n workerState.cleanupPromise = cleanupPromise;\n try {\n await cleanupPromise;\n } finally {\n if (workerState.cleanupPromise === cleanupPromise) {\n workerState.cleanupPromise = null;\n }\n }\n}\n\nfunction waitForRestart(signal: AbortSignal, delay: number): Promise<void> {\n if (signal.aborted) {\n return Promise.resolve();\n }\n return new Promise((resolve) => {\n const done = () => {\n clearTimeout(timer);\n signal.removeEventListener(\"abort\", done);\n resolve();\n };\n const timer = setTimeout(done, delay);\n signal.addEventListener(\"abort\", done, { once: true });\n });\n}\n\nfunction waitForAbort(signal: AbortSignal): Promise<void> {\n if (signal.aborted) {\n return Promise.resolve();\n }\n\n return new Promise((resolve) => {\n signal.addEventListener(\"abort\", () => resolve(), { once: true });\n });\n}\n\n/**\n * Create a Helium background worker definition.\n *\n * Workers are long-running background processes that start when the server\n * starts and continue running until the server shuts down. They are ideal for:\n * - Queue consumers (processing jobs from Redis, RabbitMQ, SQS, etc.)\n * - Background task processors\n * - Scheduled jobs and cron-like tasks\n * - Real-time data synchronization\n * - External connection managers\n * - Cache warmers and data pre-loaders\n *\n * @example\n * ```typescript\n * // Basic worker\n * export const queueConsumer = defineWorker(async (ctx) => {\n * while (true) {\n * const job = await queue.pop();\n * if (job) {\n * await processJob(job);\n * }\n * await sleep(1000);\n * }\n * }, { name: 'queueConsumer' });\n *\n * // Worker with options\n * export const dataSync = defineWorker(async (ctx) => {\n * // Sync data every 30 seconds\n * while (true) {\n * await syncData();\n * await sleep(30000);\n * }\n * }, {\n * name: 'dataSync',\n * autoRestart: true,\n * restartDelayMs: 10000,\n * maxRestarts: 5\n * });\n * ```\n *\n * @param handler - The worker function that runs in the background\n * @param options - Configuration options for the worker\n * @returns A HeliumWorkerDef that will be started by the server runtime\n */\nexport function defineWorker(handler: WorkerHandler, options: WorkerOptions = {}): HeliumWorkerDef {\n if (!handler) {\n throw new Error(\"defineWorker requires a handler\");\n }\n\n const name = options.name || handler.name || \"anonymous\";\n\n const resolvedOptions: Required<WorkerOptions> = {\n name,\n autoRestart: options.autoRestart ?? true,\n restartDelayMs: options.restartDelayMs ?? 5000,\n maxRestarts: options.maxRestarts ?? 0,\n autoStart: options.autoStart ?? true,\n };\n\n return {\n __kind: \"worker\",\n __id: name,\n name,\n handler,\n options: resolvedOptions,\n };\n}\n\n/**\n * Start a worker and manage its lifecycle.\n * @internal\n */\nexport async function startWorker(worker: HeliumWorkerDef, createContext: () => HeliumContext): Promise<WorkerInstance> {\n const { name, handler, options } = worker;\n\n // Check if worker is already running\n if (runningWorkers.has(name)) {\n const existing = runningWorkers.get(name)!;\n log(\"warn\", `Worker '${name}' is already running`);\n return existing.instance;\n }\n\n const abortController = new AbortController();\n let restartCount = 0;\n const workerState = {\n abortController,\n promise: Promise.resolve(),\n instance: undefined as unknown as WorkerInstance,\n cleanupHandlers: [] as Array<() => Promise<void> | void>,\n cleanupPromise: null as Promise<void> | null,\n cleanupRequested: false,\n };\n\n const instance: WorkerInstance = {\n id: name,\n name,\n status: \"running\",\n startedAt: new Date(),\n restartCount: 0,\n stop: async () => {\n abortController.abort();\n instance.status = \"stopped\";\n await runWorkerCleanup(name, workerState);\n removeWorker(name, workerState);\n log(\"info\", `Worker '${name}' stopped`);\n },\n };\n workerState.instance = instance;\n\n const runWorker = async (): Promise<void> => {\n while (!abortController.signal.aborted) {\n try {\n workerState.cleanupRequested = false;\n instance.status = \"running\";\n instance.startedAt = new Date();\n log(\"info\", `Starting worker '${name}'`);\n\n const ctx = createContext();\n ctx.signal = abortController.signal;\n const lifecycle: WorkerLifecycle = {\n signal: abortController.signal,\n onCleanup: (cleanup) => {\n registerCleanup(name, workerState, cleanup);\n },\n };\n const cleanup = await handler(ctx, lifecycle);\n registerCleanup(name, workerState, cleanup);\n\n if (isCleanupHandler(cleanup) && !abortController.signal.aborted) {\n await waitForAbort(abortController.signal);\n }\n\n // If handler completes normally, exit the loop\n if (!abortController.signal.aborted) {\n await runWorkerCleanup(name, workerState);\n log(\"info\", `Worker '${name}' completed successfully`);\n instance.status = \"stopped\";\n removeWorker(name, workerState);\n } else {\n await runWorkerCleanup(name, workerState);\n }\n break;\n } catch (error) {\n if (abortController.signal.aborted) {\n // Worker was intentionally stopped\n break;\n }\n\n await runWorkerCleanup(name, workerState);\n if (abortController.signal.aborted) {\n break;\n }\n\n instance.lastError = error instanceof Error ? error : new Error(String(error));\n instance.status = \"crashed\";\n log(\"error\", `Worker '${name}' crashed:`, error);\n\n // Check if we should restart\n if (options.autoRestart) {\n if (options.maxRestarts > 0 && restartCount >= options.maxRestarts) {\n log(\"error\", `Worker '${name}' exceeded max restarts (${options.maxRestarts}), giving up`);\n removeWorker(name, workerState);\n break;\n }\n\n restartCount++;\n instance.restartCount = restartCount;\n instance.status = \"restarting\";\n log(\n \"info\",\n `Worker '${name}' will restart in ${options.restartDelayMs}ms (attempt ${restartCount}${options.maxRestarts > 0 ? `/${options.maxRestarts}` : \"\"})`\n );\n\n await waitForRestart(abortController.signal, options.restartDelayMs);\n } else {\n removeWorker(name, workerState);\n break;\n }\n }\n }\n };\n\n // Publish state before invoking user code, including synchronous handlers.\n runningWorkers.set(name, workerState);\n workerState.promise = runWorker();\n\n return instance;\n}\n\n/**\n * Stop a running worker by name.\n */\nexport function stopWorker(name: string): boolean {\n const worker = runningWorkers.get(name);\n if (worker) {\n void worker.instance.stop();\n return true;\n }\n return false;\n}\n\n/**\n * Stop all running workers.\n */\nexport async function stopAllWorkers(): Promise<void> {\n const workers = Array.from(runningWorkers.values());\n await Promise.all(workers.map((worker) => worker.instance.stop()));\n log(\"info\", `Stopped ${workers.length} worker(s)`);\n}\n\n/**\n * Get the status of all workers.\n */\nexport function getWorkerStatus(): WorkerInstance[] {\n return Array.from(runningWorkers.values()).map((w) => w.instance);\n}\n\n/**\n * Get a specific worker's status.\n */\nexport function getWorkerById(name: string): WorkerInstance | undefined {\n return runningWorkers.get(name)?.instance;\n}\n"]}
|
|
@@ -20,7 +20,7 @@ type AppShellLoader = (() => Promise<ComponentType<{
|
|
|
20
20
|
children?: ReactNode;
|
|
21
21
|
}>>) | null;
|
|
22
22
|
/**
|
|
23
|
-
* Attaches HeliumTS HTTP handlers and
|
|
23
|
+
* Attaches HeliumTS HTTP handlers and RPC endpoints to an existing HTTP server.
|
|
24
24
|
* This is used in dev mode to attach to Vite's dev server.
|
|
25
25
|
*/
|
|
26
26
|
export declare function attachToDevServer(httpServer: HttpServer, loadHandlers: LoadHandlersFn, config?: HeliumConfig, workers?: WorkerEntry[], ssrPages?: SSRPageDef[], appShell?: AppShellLoader): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devServer.d.ts","sourceRoot":"","sources":["../../src/server/devServer.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"devServer.d.ts","sourceRoot":"","sources":["../../src/server/devServer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAE/B,OAAO,KAAK,EAAE,aAAa,EAAE,SAAS,EAAE,MAAM,OA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