heliumts 0.10.2 → 0.11.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 +45 -46
- package/dist/bin/helium.js +117 -172
- package/dist/bin/helium.js.map +1 -1
- package/dist/bin/projectCommands.d.ts +59 -0
- package/dist/bin/projectCommands.d.ts.map +1 -0
- package/dist/bin/projectCommands.js +103 -0
- package/dist/bin/projectCommands.js.map +1 -0
- package/dist/bin/publicApi.d.ts +30 -0
- package/dist/bin/publicApi.d.ts.map +1 -0
- package/dist/bin/publicApi.js +155 -0
- package/dist/bin/publicApi.js.map +1 -0
- package/dist/client/Router.d.ts.map +1 -1
- package/dist/client/Router.js +5 -1
- package/dist/client/Router.js.map +1 -1
- package/dist/client/callMethod.d.ts +2 -2
- package/dist/client/callMethod.d.ts.map +1 -1
- package/dist/client/callMethod.js +3 -2
- package/dist/client/callMethod.js.map +1 -1
- package/dist/client/index.d.ts +3 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +1 -2
- package/dist/client/index.js.map +1 -1
- package/dist/client/pageModules.d.ts +18 -0
- package/dist/client/pageModules.d.ts.map +1 -0
- package/dist/client/pageModules.js +3 -0
- package/dist/client/pageModules.js.map +1 -0
- package/dist/client/routerManifest.d.ts +2 -11
- package/dist/client/routerManifest.d.ts.map +1 -1
- package/dist/client/routerManifest.js +15 -187
- package/dist/client/routerManifest.js.map +1 -1
- package/dist/client/types.d.ts +12 -12
- package/dist/client/types.d.ts.map +1 -1
- package/dist/client/types.js +8 -1
- package/dist/client/types.js.map +1 -1
- package/dist/client/useCall.d.ts +20 -9
- package/dist/client/useCall.d.ts.map +1 -1
- package/dist/client/useCall.js +21 -6
- package/dist/client/useCall.js.map +1 -1
- package/dist/client/useFetch.d.ts +3 -3
- package/dist/client/useFetch.d.ts.map +1 -1
- package/dist/client/useFetch.js +8 -5
- package/dist/client/useFetch.js.map +1 -1
- package/dist/client/useStreaming.d.ts +3 -3
- package/dist/client/useStreaming.d.ts.map +1 -1
- package/dist/client/useStreaming.js +9 -7
- package/dist/client/useStreaming.js.map +1 -1
- package/dist/internal/index.d.ts +4 -0
- package/dist/internal/index.d.ts.map +1 -0
- package/dist/internal/index.js +4 -0
- package/dist/internal/index.js.map +1 -0
- package/dist/runtime/pageRoutes.d.ts +11 -0
- package/dist/runtime/pageRoutes.d.ts.map +1 -0
- package/dist/runtime/pageRoutes.js +50 -0
- package/dist/runtime/pageRoutes.js.map +1 -0
- package/dist/server/defineMethod.d.ts +16 -2
- package/dist/server/defineMethod.d.ts.map +1 -1
- package/dist/server/defineMethod.js +27 -3
- package/dist/server/defineMethod.js.map +1 -1
- package/dist/server/defineWorker.d.ts.map +1 -1
- package/dist/server/defineWorker.js +4 -6
- package/dist/server/defineWorker.js.map +1 -1
- package/dist/server/devServer.d.ts +2 -1
- package/dist/server/devServer.d.ts.map +1 -1
- package/dist/server/devServer.js +6 -9
- package/dist/server/devServer.js.map +1 -1
- package/dist/server/index.d.ts +16 -9
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +9 -12
- package/dist/server/index.js.map +1 -1
- package/dist/server/prodServer.d.ts +2 -0
- package/dist/server/prodServer.d.ts.map +1 -1
- package/dist/server/prodServer.js +7 -5
- package/dist/server/prodServer.js.map +1 -1
- package/dist/server/ssr.d.ts +4 -1
- package/dist/server/ssr.d.ts.map +1 -1
- package/dist/server/ssr.js +27 -61
- package/dist/server/ssr.js.map +1 -1
- package/dist/vite/heliumPlugin.d.ts +0 -14
- package/dist/vite/heliumPlugin.d.ts.map +1 -1
- package/dist/vite/heliumPlugin.js +68 -294
- package/dist/vite/heliumPlugin.js.map +1 -1
- package/dist/vite/paths.d.ts +0 -2
- package/dist/vite/paths.d.ts.map +1 -1
- package/dist/vite/paths.js +0 -2
- package/dist/vite/paths.js.map +1 -1
- package/dist/vite/rpcDiscovery.d.ts +10 -0
- package/dist/vite/rpcDiscovery.d.ts.map +1 -0
- package/dist/vite/rpcDiscovery.js +237 -0
- package/dist/vite/rpcDiscovery.js.map +1 -0
- package/dist/vite/rpcModule.d.ts +4 -0
- package/dist/vite/rpcModule.d.ts.map +1 -0
- package/dist/vite/rpcModule.js +64 -0
- package/dist/vite/rpcModule.js.map +1 -0
- package/dist/vite/scanner.d.ts +14 -4
- package/dist/vite/scanner.d.ts.map +1 -1
- package/dist/vite/scanner.js +130 -236
- package/dist/vite/scanner.js.map +1 -1
- package/dist/vite/serverClientAdapter.d.ts +103 -0
- package/dist/vite/serverClientAdapter.d.ts.map +1 -0
- package/dist/vite/serverClientAdapter.js +139 -0
- package/dist/vite/serverClientAdapter.js.map +1 -0
- package/dist/vite/ssg.d.ts +5 -8
- package/dist/vite/ssg.d.ts.map +1 -1
- package/dist/vite/ssg.js +32 -263
- package/dist/vite/ssg.js.map +1 -1
- package/dist/vite/virtualServerModule.d.ts +4 -4
- package/dist/vite/virtualServerModule.d.ts.map +1 -1
- package/dist/vite/virtualServerModule.js +18 -62
- package/dist/vite/virtualServerModule.js.map +1 -1
- package/docs/agent/api-reference.md +45 -0
- package/docs/agent/editable-forms.md +37 -0
- package/docs/agent/guide-get.md +13 -0
- package/docs/agent/guide-index.md +15 -0
- package/docs/agent/http-handlers.md +9 -0
- package/docs/agent/imports.md +16 -0
- package/docs/agent/index.md +48 -0
- package/docs/agent/input-validation.md +9 -0
- package/docs/agent/measuring.md +7 -0
- package/docs/agent/mutations.md +11 -0
- package/docs/agent/operations.md +9 -0
- package/docs/agent/query-params.md +28 -0
- package/docs/agent/rendering.md +9 -0
- package/docs/agent/request-context.md +13 -0
- package/docs/agent/routing.md +11 -0
- package/docs/agent/scaffold.md +15 -0
- package/docs/agent/security.md +9 -0
- package/docs/agent/server-files.md +9 -0
- package/docs/agent/streaming.md +9 -0
- package/docs/agent/validation-page.md +21 -0
- package/docs/agent/validation.md +33 -0
- package/docs/agent/verify.md +19 -0
- package/docs/agent/workflow.md +11 -0
- package/docs/agent-guide.md +266 -0
- package/docs/agent-start.md +87 -0
- package/docs/migration-0.11.md +15 -0
- package/package.json +20 -5
- package/dist/server/handlerLoader.d.ts +0 -1
- package/dist/server/handlerLoader.d.ts.map +0 -1
- package/dist/server/handlerLoader.js +0 -2
- package/dist/server/handlerLoader.js.map +0 -1
- package/dist/server/ipExtractor.d.ts +0 -48
- package/dist/server/ipExtractor.d.ts.map +0 -1
- package/dist/server/ipExtractor.js +0 -96
- package/dist/server/ipExtractor.js.map +0 -1
- package/dist/server/requestRouting.d.ts +0 -4
- package/dist/server/requestRouting.d.ts.map +0 -1
- package/dist/server/requestRouting.js +0 -67
- package/dist/server/requestRouting.js.map +0 -1
- package/dist/utils/deepEqual.d.ts +0 -1
- package/dist/utils/deepEqual.d.ts.map +0 -1
- package/dist/utils/deepEqual.js +0 -2
- package/dist/utils/deepEqual.js.map +0 -1
- package/dist/utils/formatError.d.ts +0 -2
- package/dist/utils/formatError.d.ts.map +0 -1
- package/dist/utils/formatError.js +0 -18
- package/dist/utils/formatError.js.map +0 -1
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
# HeliumTS compact application reference
|
|
2
|
+
|
|
3
|
+
HeliumTS 0.11.0 application reference. Use matching framework and scaffolder versions; see the upgrade notes when migrating from 0.10.2.
|
|
4
|
+
|
|
5
|
+
## Start and verify
|
|
6
|
+
|
|
7
|
+
### Orient in an installed app
|
|
8
|
+
|
|
9
|
+
Read the app's AGENTS.md first. For a known app method or route, use `npx helium inspect --rpc name --json` or `--route '/posts/:id' --json`. For an exact framework signature, use `npx helium api useCall --from client --json` or `npx helium api defineMethod --from server --json`. Discover unknown API names with `npx helium api --list --match fragment`.
|
|
10
|
+
|
|
11
|
+
Open one focused topic from node_modules/heliumts/docs/agent/index.md when you need a concept or example. Follow prerequisite links only to fill a gap; the full reference at node_modules/heliumts/docs/agent-guide.md is available for broader context.
|
|
12
|
+
|
|
13
|
+
### Scaffold a minimal app
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm create heliumts-app@latest my-app
|
|
17
|
+
cd my-app
|
|
18
|
+
npm run dev
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The default starter has one page, one typed RPC method and plain CSS. Pass `--template examples` for the tasks and streaming demo, or `--tailwind` for Tailwind CSS. If you pass `--skip-install`, run `npm install` before starting the dev server.
|
|
22
|
+
|
|
23
|
+
### Verify an application
|
|
24
|
+
|
|
25
|
+
In a new starter, run the single verification script:
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
npm run verify
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
It runs `check`, `lint`, then `build` once each and stops on the first failure. Fix that failure and rerun verify. Check generates `src/rpc.generated.ts`, validates discovery and checks every referenced TypeScript project. A separate typegen or typecheck invocation is unnecessary in this sequence. Keep runtime tests required by your task; production build and type checks do not replace them.
|
|
32
|
+
|
|
33
|
+
For an existing app without verify, run its supplied check, lint and production-build scripts. `helium check` itself remains generation plus TypeScript: it does not run app scripts. `helium typegen` is available for generation alone; dev and build also keep RPC references current. Treat the RPC module as generated output.
|
|
34
|
+
|
|
35
|
+
Use inspect/api only to answer a specific discovery question, before verification when needed; they are not extra verification stages.
|
|
36
|
+
|
|
37
|
+
### Open the guide index
|
|
38
|
+
|
|
39
|
+
Read the Markdown index shipped with the installed framework:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
cat node_modules/heliumts/docs/agent/index.md
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
The index groups 22 focused task guides by subject and links directly to their Markdown files. Choose only the guide needed for the current task. The full compact reference remains at node_modules/heliumts/docs/agent-guide.md.
|
|
46
|
+
|
|
47
|
+
### Read one guide
|
|
48
|
+
|
|
49
|
+
Open the Markdown file linked from the index. For example, the validation guide contains the complete server method example:
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
cat node_modules/heliumts/docs/agent/validation.md
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
Read the whole short guide so prerequisites, complete examples and related links stay together. Each guide includes its release warning and belongs to the installed framework package. Check node_modules/heliumts/package.json if you need the exact installed version. Follow prerequisite links only when the task needs that background; use the full compact reference for a task spanning several subjects.
|
|
56
|
+
|
|
57
|
+
## Imports and files
|
|
58
|
+
|
|
59
|
+
### Keep imports at the right boundary
|
|
60
|
+
|
|
61
|
+
- Import hooks, `Link` and router APIs from `heliumts/client`.
|
|
62
|
+
- Define server methods and middleware with primitives from `heliumts/server`.
|
|
63
|
+
- In browser application files, import RPC method references from the generated `src/rpc.generated.ts` module. For a page in `src/pages/`, use `../rpc.generated`. Pass the reference to a client hook or call helper to infer the method's arguments and result.
|
|
64
|
+
- Never import src/server implementations directly into browser files. Keep credentials, database clients and authorization on the server.
|
|
65
|
+
- Generated server bundles use heliumts/internal for framework helpers; application code should not import this internal entry point. Older helper exports from heliumts/server remain compatible.
|
|
66
|
+
- Use heliumts/vite only in build configuration. The package root is a namespace convenience, not the preferred browser import.
|
|
67
|
+
|
|
68
|
+
When upgrading from 0.10.2, switch browser RPC imports from `heliumts/server` to your generated module, delete the old generated `src/types/heliumts-server.d.ts` if it exists, and run `npx helium check`.
|
|
69
|
+
### Find installed public API types
|
|
70
|
+
|
|
71
|
+
Use public imports from heliumts/client and heliumts/server. Look up one exact exported symbol in the installed package without loading application modules:
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
npx helium api useCall --json
|
|
75
|
+
npx helium api useRouter --from client --json
|
|
76
|
+
npx helium api defineMethod --from server --json
|
|
77
|
+
npx helium api UseCallOptions --from client --json
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
If you do not know a symbol name, discover public names first:
|
|
81
|
+
|
|
82
|
+
```bash
|
|
83
|
+
npx helium api --list --from client --match router --json
|
|
84
|
+
npx helium api --list --from server --match method --json
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Then look up one returned name. --match requires --list and matches a case-insensitive literal name fragment, not a regular expression. A symbol lookup and --list cannot be combined. Listings are sorted, include public aliases and type exports, and report an empty array when nothing matches. Declaration kinds do not imply runtime availability: an export may be type-only. More than 100 matches or 16 KiB of output fails with a request to narrow the filter; results are never silently truncated.
|
|
88
|
+
|
|
89
|
+
The default entrypoint is client. The result retains overloads, generics and documentation comments, with declaration source paths and related public type names for follow-up queries. Unexported local type shapes are included one level deep for reference, not as import suggestions. Other local, built-in and external references may remain; excerpts are not standalone code. The public module and selected name identify the supported import, even when the declaration uses a different internal alias. Output is capped at 16 KiB; missing, private or oversized lookups fail explicitly. This tool reads this installed framework's declarations, not application-generated RPC methods (use inspect --rpc for those).
|
|
90
|
+
|
|
91
|
+
If needed, open only the relevant declaration in the installed package:
|
|
92
|
+
|
|
93
|
+
- Client exports: node_modules/heliumts/dist/client/index.d.ts.
|
|
94
|
+
- Read and mutation hooks: node_modules/heliumts/dist/client/useFetch.d.ts and node_modules/heliumts/dist/client/useCall.d.ts.
|
|
95
|
+
- Router state and navigation: node_modules/heliumts/dist/client/Router.d.ts.
|
|
96
|
+
- Server exports: node_modules/heliumts/dist/server/index.d.ts.
|
|
97
|
+
- Request context and method options: node_modules/heliumts/dist/server/context.d.ts and node_modules/heliumts/dist/server/defineMethod.d.ts.
|
|
98
|
+
|
|
99
|
+
For a symbol search, restrict output to declarations:
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
rg -n -g '*.d.ts' 'useRouter|useCall' node_modules/heliumts/dist/client
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Avoid recursively searching generated JavaScript or source maps for API signatures; those files can produce very large tool outputs.
|
|
106
|
+
|
|
107
|
+
These are files to read, not application deep-import paths. There is no dist/client/hooks directory. Longer docs linked on the source repository are not all shipped in the npm package; use this task index and the installed declarations first. Check the installed package version before relying on external examples.
|
|
108
|
+
|
|
109
|
+
### Place discoverable server files
|
|
110
|
+
|
|
111
|
+
Put pages under src/pages, methods under src/server and middleware in src/server/_middleware.ts. Start with the explicit exported defineMethod form below; discovery also supports import aliases, typed declarations and relative re-exports within src/server. Arbitrary wrapper factories, computed calls and tsconfig path aliases are not inferred; use an explicit defineMethod export at the discovery boundary.
|
|
112
|
+
|
|
113
|
+
## One validated method and page
|
|
114
|
+
|
|
115
|
+
### Define one validated method
|
|
116
|
+
|
|
117
|
+
In the framework repository, npm run test:docs compiles these two examples together and tests the extracted server example with valid and malformed inputs.
|
|
118
|
+
|
|
119
|
+
```ts file=src/server/greeting.ts
|
|
120
|
+
import { defineMethod } from "heliumts/server";
|
|
121
|
+
|
|
122
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
123
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export const greet = defineMethod(
|
|
127
|
+
({ name }: { name: string }) => ({ message: `Hello ${name}` }),
|
|
128
|
+
{
|
|
129
|
+
input(value: unknown) {
|
|
130
|
+
if (!isRecord(value) || typeof value.name !== "string") {
|
|
131
|
+
throw new Error("Expected a name");
|
|
132
|
+
}
|
|
133
|
+
const name = value.name.trim();
|
|
134
|
+
if (!name || name.length > 80) throw new Error("Invalid name");
|
|
135
|
+
return { name };
|
|
136
|
+
},
|
|
137
|
+
}
|
|
138
|
+
);
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
Start with unknown, narrow to a record, then validate each field before using it. Keep the handler argument type explicit so the parser return and client arguments agree; return the transformed object rather than asserting a type with a cast.
|
|
142
|
+
|
|
143
|
+
### Understand input parser behavior
|
|
144
|
+
|
|
145
|
+
The optional input parser accepts unknown and returns validated arguments, synchronously or asynchronously. A parser object with parse(input) is also supported. Parser failures return a safe Invalid method arguments error without leaking submitted values or schema details. TypeScript types alone do not validate network input. Validation does not replace authentication or ownership checks in the handler/middleware.
|
|
146
|
+
|
|
147
|
+
### Use request context safely
|
|
148
|
+
|
|
149
|
+
defineMethod handlers receive (args, ctx), where ctx has the public HeliumContext type from heliumts/server. Read request headers from ctx.req.headers, not ctx.headers. Values use Node's IncomingHttpHeaders shape: narrow string, string[] or undefined as appropriate.
|
|
150
|
+
|
|
151
|
+
ctx.req also contains ip, optional url and method, and the raw Node request. In RPC handlers, req.url is the RPC endpoint URL, not the browser page URL; pass page parameters explicitly as validated method arguments. Do not return or log authorization headers, cookies or the whole request.
|
|
152
|
+
|
|
153
|
+
ctx.signal is an AbortSignal for cancellation/disconnect. Pass it to upstream fetch/provider calls and clean up resources in finally. Cancellation only stops work that observes the signal. Middleware-added context fields are unknown until narrowed. For exact fields, read node_modules/heliumts/dist/server/context.d.ts; the public type is HeliumContext, not MethodContext or getRequestContext.
|
|
154
|
+
|
|
155
|
+
### Call a validated method from a page
|
|
156
|
+
|
|
157
|
+
This page uses the `greet` method from the validated-method guide. Define it first, then run `npx helium typegen` if the development server is stopped.
|
|
158
|
+
|
|
159
|
+
```tsx file=src/pages/index.tsx
|
|
160
|
+
import { useFetch } from "heliumts/client";
|
|
161
|
+
import { greet } from "../rpc.generated";
|
|
162
|
+
|
|
163
|
+
export default function Home() {
|
|
164
|
+
const { data, isLoading, error } = useFetch(greet, { name: "Helium" });
|
|
165
|
+
if (isLoading) return <p>Loading...</p>;
|
|
166
|
+
if (error) return <p role="alert">{error}</p>;
|
|
167
|
+
return <h1>{data?.message}</h1>;
|
|
168
|
+
}
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## Choose one operation
|
|
172
|
+
|
|
173
|
+
### Read and cache data
|
|
174
|
+
|
|
175
|
+
useFetch(method, args) reads and caches. Required method arguments must be provided. For an argumentless method, useFetch(method) is valid. Use enabled: false to postpone a valid request.
|
|
176
|
+
### Mutate and invalidate data
|
|
177
|
+
|
|
178
|
+
useCall(method, options) mutates. call(args) returns the inferred result; onSuccess receives that same type. Failed calls set error state and reject, so catch the promise in event handlers. For ordinary forms, submit(args) returns a handled outcome: { status: "success", data }, { status: "error", error: RpcError }, or { status: "busy" }. It synchronously suppresses another submission while any call from this hook is pending, so the form needs no extra ref lock or rejection catch. isCalling/error still drive the UI. Busy performs no request or callbacks. This is per hook, not cross-component deduplication or server idempotency; call remains concurrent/rejecting. A submission error can also come from a callback after a committed write, so it does not prove rollback. Invalidation starts the existing eventual refresh; submit does not await related reads.
|
|
179
|
+
|
|
180
|
+
Invalidate every related read after success. For a detail edit that changes a title shown in a list, pass both references in `useCall(saveArticle, { invalidate: [getArticle, listArticles] })`. Invalidating only `getArticle` leaves a cached list stale when the user navigates back. Include related filtered lists and summary reads affected by the change. Use the returned result for immediate feedback when needed. Invalidation refetches cached reads.
|
|
181
|
+
|
|
182
|
+
### Edit fetched data without a synchronization effect
|
|
183
|
+
|
|
184
|
+
Pass a loaded article into this component. The app must already define getArticle({ id }), listArticles() and saveArticle({ id, title }) with server-side validation and authorization. The detail parent should show its loading, error and not-found states before rendering the editor.
|
|
185
|
+
|
|
186
|
+
```tsx file=src/components/ArticleEditor.tsx
|
|
187
|
+
import { useState, type FormEvent } from "react";
|
|
188
|
+
import { useCall } from "heliumts/client";
|
|
189
|
+
import { getArticle, listArticles, saveArticle } from "../rpc.generated";
|
|
190
|
+
|
|
191
|
+
type Article = { id: string; title: string };
|
|
192
|
+
|
|
193
|
+
export default function ArticleEditor({ article }: { article: Article }) {
|
|
194
|
+
const save = useCall(saveArticle, { invalidate: [getArticle, listArticles] });
|
|
195
|
+
const [draft, setDraft] = useState<Article | null>(null);
|
|
196
|
+
const title = draft?.id === article.id ? draft.title : article.title;
|
|
197
|
+
|
|
198
|
+
async function submit(event: FormEvent<HTMLFormElement>) {
|
|
199
|
+
event.preventDefault();
|
|
200
|
+
const outcome = await save.submit({ id: article.id, title });
|
|
201
|
+
if (outcome.status === "success") setDraft(null);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
return <form onSubmit={submit}>
|
|
205
|
+
<label>Title <input value={title} onChange={(event) => setDraft({ id: article.id, title: event.currentTarget.value })} disabled={save.isCalling} required /></label>
|
|
206
|
+
{save.error && <p role="alert">{save.error}</p>}
|
|
207
|
+
<button type="submit" disabled={save.isCalling}>Save</button>
|
|
208
|
+
</form>;
|
|
209
|
+
}
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
The displayed title comes from the current record until the user edits it. A draft is scoped to its record ID, so changing records does not display the previous record's draft. This avoids copying fetched data into state in a useEffect. Clear the draft only after a successful save; retain it when saving fails. The two invalidations refresh both the detail and its list.
|
|
213
|
+
|
|
214
|
+
### Consume an HTTP stream
|
|
215
|
+
|
|
216
|
+
useStreaming(method) consumes an AsyncIterable method over HTTP with length-prefixed MessagePack frames. Unary hooks reject streaming methods at compile time. Keep cancellation and server abort handling intact.
|
|
217
|
+
### Choose an explicit HTTP endpoint
|
|
218
|
+
|
|
219
|
+
defineHTTPRequest is for explicit HTTP endpoints, webhooks and integrations. Do not replace ordinary RPC with hand-written transport glue unless the task requires it.
|
|
220
|
+
|
|
221
|
+
## Routing and navigation
|
|
222
|
+
|
|
223
|
+
### Navigate with file routes
|
|
224
|
+
|
|
225
|
+
Put pages in src/pages: index.tsx maps to /, articles/index.tsx to /articles, and articles/[id].tsx to /articles/:id. Parenthesized route groups do not appear in the URL. Use Link from heliumts/client for links and useRouter inside the AppRouter tree for navigation and route state.
|
|
226
|
+
|
|
227
|
+
router.params.id holds a dynamic parameter (string or string[]); narrow it before using it as a method argument. router.push(href) adds a history entry, while router.replace(href) replaces the current entry. Use Redirect for declarative redirects rather than navigating during render. For exact signatures, read node_modules/heliumts/dist/client/Router.d.ts.
|
|
228
|
+
|
|
229
|
+
### Read and update query parameters
|
|
230
|
+
|
|
231
|
+
Use useRouter().searchParams, a URLSearchParams object. There is no separate useSearchParams export. Clone the current parameters before updating them, then navigate with push or replace; mutating the current object alone does not navigate.
|
|
232
|
+
|
|
233
|
+
```tsx file=src/components/ArticleFilters.tsx
|
|
234
|
+
import { useRouter } from "heliumts/client";
|
|
235
|
+
|
|
236
|
+
export default function ArticleFilters() {
|
|
237
|
+
const router = useRouter();
|
|
238
|
+
const status = router.searchParams.get("status") ?? "all";
|
|
239
|
+
|
|
240
|
+
function showOpen() {
|
|
241
|
+
const next = new URLSearchParams(router.searchParams);
|
|
242
|
+
next.set("status", "open");
|
|
243
|
+
router.replace(`${router.path}?${next.toString()}`, { scrollToTop: false });
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
return <button type="button" onClick={showOpen}>Show open (current: {status})</button>;
|
|
247
|
+
}
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
This preserves unrelated query parameters and replaces the URL without adding a history entry. Validate query values against the app's allowed values before passing them to RPC methods; query strings are untrusted input.
|
|
251
|
+
|
|
252
|
+
## Rendering and security
|
|
253
|
+
|
|
254
|
+
### Choose a rendering mode
|
|
255
|
+
|
|
256
|
+
Pages render on the client unless their file starts with "use ssr" or "use ssg". SSR and SSG adapters expose the same client hook shapes but do not perform browser RPC during rendering. Use the documented server-side props and static props mechanisms for initial data, not a client fetch in server render. A shared adapter does not make browser-only APIs available on the server.
|
|
257
|
+
|
|
258
|
+
### Preserve application security
|
|
259
|
+
|
|
260
|
+
Keep rate limits, input-size limits, origin checks, authorization, output escaping and cancellation. Do not send secrets or private user data to the browser. See the focused routing, SSR, SSG, middleware and streaming guides only when the task needs them.
|
|
261
|
+
|
|
262
|
+
## Measuring AI efficiency
|
|
263
|
+
|
|
264
|
+
### Measure successful agent tasks
|
|
265
|
+
|
|
266
|
+
HeliumTS reduces explicit client/server wiring. Source length is not total AI cost. Compare successful matched tasks and count input context, output, tool results, retries and failures with fixed models and versions. Do not claim HeliumTS uses fewer tokens than every framework without reproducible evidence.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# HeliumTS application context
|
|
2
|
+
|
|
3
|
+
Read this once to implement a normal app. It is self-contained; no prerequisite reading or API lookup is required for the path below. Use HeliumTS 0.11.0 or later with a matching scaffolder. For an unfamiliar feature, query one exact public signature with `npx helium api NAME --from client` (or `server`). Static discovery: `npx helium inspect --rpc NAME --json` or `--route '/items/:id' --json`. These are lookup tools, not mandatory verification steps.
|
|
4
|
+
|
|
5
|
+
## Files and boundaries
|
|
6
|
+
|
|
7
|
+
- `src/pages/index.tsx` maps to `/`; `src/pages/items/index.tsx` to `/items`; `src/pages/items/[id].tsx` to `/items/:id`. Pages default-export a React component. Use `src/components/` for shared UI, `src/styles.css` for styles, `src/server/` for discoverable named `defineMethod` exports, and `helium.config.ts`/`vite.config.ts` for framework/build configuration.
|
|
8
|
+
- Import hooks, `Link`, and `useRouter` from `heliumts/client`. Import server primitives only in server files from `heliumts/server`. Browser imports from `heliumts/server` are unsupported.
|
|
9
|
+
- App RPC references come exclusively from generated `src/rpc.generated.ts`, using the relative path appropriate to the page. Never edit that file or import an application server implementation into browser code. Dev, check, typegen and build maintain the references from source without executing server modules during discovery.
|
|
10
|
+
- React/React DOM remain peers. RPC uses HTTP, streaming uses HTTP with length-prefixed MessagePack frames. Normal app code should use public hooks/references, not construct transport URLs, tokens, envelopes or batches.
|
|
11
|
+
|
|
12
|
+
## One validated, authenticated method and page
|
|
13
|
+
|
|
14
|
+
Integrate your real authentication in a **server-only** `src/server/session.ts` adapter with this contract: `getSession(headers: IncomingHttpHeaders): Promise<{ userId: string } | null>` (a synchronous result is also fine). It must verify the request's actual session, not trust an owner ID supplied in input. There is intentionally no permissive demo implementation here. Use your existing trusted session provider when the app supplies one.
|
|
15
|
+
|
|
16
|
+
```ts file=src/server/greeting.ts
|
|
17
|
+
import { defineMethod } from "heliumts/server";
|
|
18
|
+
import { getSession } from "./session";
|
|
19
|
+
|
|
20
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
21
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const greet = defineMethod(
|
|
25
|
+
async ({ name }: { name: string }, ctx) => {
|
|
26
|
+
const session = await getSession(ctx.req.headers);
|
|
27
|
+
if (!session) throw new Error("Authentication required");
|
|
28
|
+
return { message: `Hello ${name}`, userId: session.userId };
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
input(value: unknown) {
|
|
32
|
+
if (!isRecord(value) || typeof value.name !== "string") {
|
|
33
|
+
throw new Error("Expected a name");
|
|
34
|
+
}
|
|
35
|
+
const name = value.name.trim();
|
|
36
|
+
if (!name || Array.from(name).length > 80) throw new Error("Invalid name");
|
|
37
|
+
return { name };
|
|
38
|
+
},
|
|
39
|
+
}
|
|
40
|
+
);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`input` starts with unknown, validates/transforms fields, and returns the handler's explicit argument type. Throwing rejects malformed requests before the handler. An object check alone narrows to `object`, not `Record<string, unknown>`; use the type guard above rather than asserting a type. Unicode code-point limits use `Array.from(text).length`; JavaScript string length counts UTF-16 units. Omit/ignore extra fields deliberately; never spread unchecked input into persistence.
|
|
44
|
+
|
|
45
|
+
`ctx` is `HeliumContext`: headers are **`ctx.req.headers`**, not `ctx.headers`. Header values are Node strings/string arrays/undefined. `ctx.req.url` is the RPC URL, not the current browser page; send validated page parameters explicitly. Pass `ctx.signal` to cancellable upstream work. Never return/log cookies, authorization headers or the whole request.
|
|
46
|
+
|
|
47
|
+
```tsx file=src/pages/index.tsx
|
|
48
|
+
import { useFetch } from "heliumts/client";
|
|
49
|
+
import { greet } from "../rpc.generated";
|
|
50
|
+
|
|
51
|
+
export default function Home() {
|
|
52
|
+
const { data, isLoading, error, refetch } = useFetch(greet, { name: "Helium" });
|
|
53
|
+
if (isLoading) return <p>Loading...</p>;
|
|
54
|
+
if (error) return <main><p role="alert">{error}</p>
|
|
55
|
+
<button onClick={() => void refetch()}>Retry</button></main>;
|
|
56
|
+
return <main><h1>{data?.message}</h1></main>;
|
|
57
|
+
}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
Required method arguments must be provided. `useFetch(method, args, options)` returns `{ data, isLoading, error, stats, refetch }`; `data` is initially undefined, `error` is a string or null. `refetch()` retries a read; `enabled: false` postpones a valid request. It does not make invalid arguments valid. Choose explicit loading, error and empty/not-found states; `undefined` during loading is not a missing record. For detail reads returning null, show the app's not-found message/back link and no stale editor.
|
|
61
|
+
|
|
62
|
+
## Persistence, mutations and forms
|
|
63
|
+
|
|
64
|
+
Validation is not authorization. Authenticate **every** read/write on the server. Derive owner ID from the verified session; scope list/get/update/delete to it. Fetch/check ownership before changing a record; missing or another user's record must not be exposed or mutated. Return null/not-found or a safe error as the app contract requires. Denied writes must not report success. Validate all update fields before a single atomic write; malformed partial updates must not persist anything. Use the app's real persistent repository, not component state or reset-on-start arrays. Preserve rate limits, cancellation and all framework security checks.
|
|
65
|
+
|
|
66
|
+
`useCall(method, { invalidate: [relatedRead, otherRelatedRead] })` returns `{ call, isCalling, error, data, stats }`. `await call(args)` returns the inferred result; failures set error and **reject**, so catch promises in event handlers. For an edit affecting a list and a detail, invalidate both references (for example `[getTask, listTasks]`), including related filtered/summary reads. Do not recreate raw RPC requests. `callMethod` is the public imperative alternative outside hooks; it does not update hook state or invalidate queries automatically.
|
|
67
|
+
|
|
68
|
+
Keep form state local. For a form, `await mutation.submit(args)` returns `{status:"success",data}`, `{status:"error",error:RpcError}` or `{status:"busy"}` and suppresses same-hook rapid duplicate submissions synchronously. Use `isCalling` to disable the button; no extra ref lock or rejection catch is needed. Clear the draft only for success. This is per-hook guarding, not server idempotency; `call()` remains the concurrent/rejecting primitive for advanced flows. Keep the same form, user input and retry button after failure, show an accessible `role="alert"`, and clear/reset input only after success. Do not replace a failed mutation form with a route-wide error page. A save may use its returned record for immediate UI feedback while invalidated reads refresh.
|
|
69
|
+
|
|
70
|
+
For a detail editor, mount it only after the requested record is available. Key the editor by record identity and pass fetched values as initial props; this avoids a synchronization effect overwriting unsaved edits. After navigation, do not show a cached record for a different ID. Disable duplicate toggle/delete/save operations and show pending feedback.
|
|
71
|
+
|
|
72
|
+
## Navigation and URL state
|
|
73
|
+
|
|
74
|
+
Use `<Link href="/items">Items</Link>` for client navigation. Ordinary browser back/forward should work without full-document reloads. `useRouter()` returns `path`, `params`, `searchParams`, `push`, `replace`, `on`, `status`, `isNavigating`, `isPending`.
|
|
75
|
+
|
|
76
|
+
- Dynamic `[id]` values are in `router.params.id` (string or string array); narrow before use. `router.path` is the current pathname.
|
|
77
|
+
- `router.searchParams` is a `URLSearchParams`. There is no separate `useSearchParams` hook. Derive the displayed filter directly from the URL on each render, validating allowed values; do not initialize a disconnected local filter once and forget back/forward.
|
|
78
|
+
- To change a filter, clone the current parameters, set/delete the value, then `router.push(router.path + "?" + next.toString(), { scrollToTop: false })`. Use `push` when filter changes need history entries; `replace` when replacing the current entry is intended. Mutating the existing object alone does not navigate. Preserve unrelated parameters.
|
|
79
|
+
- Fetch keys include method and arguments. Pass the current validated URL filter/ID to the read, and invalidate the methods affected by writes. Keep real SSR/SSG differences explicit if the task requests those rendering modes; the normal interactive path here does not require them.
|
|
80
|
+
|
|
81
|
+
## Verify and exercise the app
|
|
82
|
+
|
|
83
|
+
Run `npm run verify` in a new starter: it runs check (generation + TypeScript), lint, production build, stopping on failure. Fix that failure, then rerun; separate typegen/typecheck calls are unnecessary in this sequence. In existing apps without verify, use their supplied check/lint/build scripts. Run only the task's required checks, not every lookup command as an additional check. File-writing shell scripts should stop on write failures before invoking verification; a successful check of an unchanged scaffold is not proof the intended app was written.
|
|
84
|
+
|
|
85
|
+
For runtime checks, start the built app with its supplied start command and use the **public browser UI/client references**: navigate list/detail/back/forward, submit valid and invalid forms, test pending/error/retry behavior, and check persistent data after restart and owner/anonymous isolation. Do not grep private `dist/` transport implementations or source maps to discover a wire protocol. If startup is denied by the environment (for example listen EPERM), report the concrete restriction; do not replace real validation with a protocol guess or claim the test passed. In an externally evaluated task, follow the supplied evaluator/repair workflow for runtime coverage.
|
|
86
|
+
|
|
87
|
+
If a specific gap remains, use one exact `api`/`inspect` lookup or the matching concept guide. Do not read the full reference or traverse prerequisite chains by default. Keep implementation and checks truthful; fewer bytes do not prove lower successful-task token usage.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Upgrade to HeliumTS 0.11.0
|
|
2
|
+
|
|
3
|
+
0.11.0 replaces generated application RPC stubs from `heliumts/server` with opaque, typed references in each application's `src/rpc.generated.ts`. This is a breaking change from 0.10.2. Server primitives stay in `heliumts/server`; React/React DOM remain peers and the Node/Vite requirements are unchanged.
|
|
4
|
+
|
|
5
|
+
1. Update the framework with `npm install heliumts@^0.11.0` and keep the resulting project lockfile. Use create-heliumts-app 0.11.0 for new applications.
|
|
6
|
+
2. Stop the old dev process. Remove the obsolete generated `src/types/heliumts-server.d.ts` if present; do not remove user-authored server types.
|
|
7
|
+
3. In browser pages/components, replace imports of app methods from `heliumts/server` or server implementation files with imports from the relative `src/rpc.generated.ts` module. Keep hooks/router imports from `heliumts/client` and server-side `defineMethod`, workers, HTTP handlers and other primitives from `heliumts/server`.
|
|
8
|
+
4. Run `npx helium check` to regenerate references and check types. `npx helium typegen` generates without starting a server. Do not hand-edit generated references. Resolve duplicate RPC names/equivalent dynamic routes when discovery reports them.
|
|
9
|
+
5. Supply required method arguments explicitly. Unary hooks reject streaming references; use `useStreaming` for async-iterable methods. Remove uses of the legacy `MethodStub` type and direct server definitions as client references.
|
|
10
|
+
6. For forms, `useCall(...).submit(args)` is additive: it handles success/error/busy outcomes and suppresses same-hook pending duplicates. Existing `call()` still rejects and permits concurrency. Keep explicit `invalidate` references for every affected read; successful submission does not wait for those reads to refresh.
|
|
11
|
+
7. Restart with the updated package and deploy matching client/server builds together. Existing applications can keep their verification commands; new starters provide `npm run verify` (check, lint, production build). Preserve task-specific runtime and security tests.
|
|
12
|
+
|
|
13
|
+
The HTTP RPC and streaming codec is unchanged: unary JSON/MessagePack and length-prefixed MessagePack stream frames. App code should use public hooks/references rather than construct private transport requests. Keep validation, authorization, rate limits, cancellation and error privacy. An optional `defineMethod(..., { input })` parser validates untrusted input before the handler; it does not replace authorization.
|
|
14
|
+
|
|
15
|
+
`helium inspect --rpc NAME --json`, `--route PATTERN --json` and `helium api NAME --from client|server` provide bounded source/API context. They are optional lookups, not a mandatory sequence. Read the installed `docs/agent-start.md` once for the normal application path.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "heliumts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"description": "A lightweight full-stack React framework with file-based routing, RPC, and SSG support",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"react",
|
|
@@ -62,6 +62,11 @@
|
|
|
62
62
|
"types": "./dist/vite/index.d.ts",
|
|
63
63
|
"import": "./dist/vite/index.js",
|
|
64
64
|
"require": "./dist/vite/index.js"
|
|
65
|
+
},
|
|
66
|
+
"./internal": {
|
|
67
|
+
"types": "./dist/internal/index.d.ts",
|
|
68
|
+
"import": "./dist/internal/index.js",
|
|
69
|
+
"require": "./dist/internal/index.js"
|
|
65
70
|
}
|
|
66
71
|
},
|
|
67
72
|
"scripts": {
|
|
@@ -77,7 +82,13 @@
|
|
|
77
82
|
"test:watch": "vitest",
|
|
78
83
|
"test:coverage": "vitest run --coverage",
|
|
79
84
|
"typecheck": "tsc -p tsconfig.test.json --noEmit",
|
|
80
|
-
"test:smoke": "node scripts/smoke.mjs"
|
|
85
|
+
"test:smoke": "node scripts/smoke.mjs",
|
|
86
|
+
"test:api": "node scripts/test-public-api.mjs",
|
|
87
|
+
"test:docs": "npm run docs:check && node --test scripts/agent-topics.test.mjs && node scripts/test-agent-guide.mjs && node scripts/test-agent-start.mjs",
|
|
88
|
+
"check": "npm run build && npm run typecheck && npm test && npm run lint && npm run test:docs && npm run test:api",
|
|
89
|
+
"docs:sync": "node scripts/sync-agent-topics.mjs",
|
|
90
|
+
"docs:check": "node scripts/sync-agent-topics.mjs --check",
|
|
91
|
+
"prepack": "node scripts/sync-agent-topics.mjs --check --quiet"
|
|
81
92
|
},
|
|
82
93
|
"peerDependencies": {
|
|
83
94
|
"cac": "^6.7.14",
|
|
@@ -88,10 +99,15 @@
|
|
|
88
99
|
},
|
|
89
100
|
"dependencies": {
|
|
90
101
|
"@msgpack/msgpack": "^3.1.2",
|
|
91
|
-
"dotenv": "^17.2.3"
|
|
102
|
+
"dotenv": "^17.2.3",
|
|
103
|
+
"typescript": "^5.9.3"
|
|
92
104
|
},
|
|
93
105
|
"files": [
|
|
94
|
-
"dist"
|
|
106
|
+
"dist",
|
|
107
|
+
"docs/agent-guide.md",
|
|
108
|
+
"docs/agent-start.md",
|
|
109
|
+
"docs/agent",
|
|
110
|
+
"docs/migration-0.11.md"
|
|
95
111
|
],
|
|
96
112
|
"devDependencies": {
|
|
97
113
|
"@testing-library/dom": "^10.4.1",
|
|
@@ -110,7 +126,6 @@
|
|
|
110
126
|
"eslint-plugin-unused-imports": "^4.3.0",
|
|
111
127
|
"jsdom": "^27.2.0",
|
|
112
128
|
"prettier": "^3.6.2",
|
|
113
|
-
"typescript": "^5.9.3",
|
|
114
129
|
"vite": "^7.3.7",
|
|
115
130
|
"vitest": "^4.1.12"
|
|
116
131
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
//# sourceMappingURL=handlerLoader.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"handlerLoader.d.ts","sourceRoot":"","sources":["../../src/server/handlerLoader.ts"],"names":[],"mappings":""}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"handlerLoader.js","sourceRoot":"","sources":["../../src/server/handlerLoader.ts"],"names":[],"mappings":"","sourcesContent":[""]}
|
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import type http from "http";
|
|
2
|
-
/**
|
|
3
|
-
* Extracts the client IP address from an HTTP request, taking into account proxy configurations.
|
|
4
|
-
*
|
|
5
|
-
* When behind proxies (like Vercel, Cloudflare, AWS ALB, etc.), the X-Forwarded-For header
|
|
6
|
-
* contains a chain of IP addresses. The format is: "client, proxy1, proxy2, ..."
|
|
7
|
-
*
|
|
8
|
-
* @param req - The HTTP request object
|
|
9
|
-
* @param trustProxyDepth - Number of proxy levels to trust
|
|
10
|
-
* - 0: Only use req.socket.remoteAddress (no proxy trust)
|
|
11
|
-
* - 1: Trust 1 proxy level (get the last IP before your server)
|
|
12
|
-
* - 2+: Trust multiple proxy levels (for complex setups)
|
|
13
|
-
*
|
|
14
|
-
* Examples:
|
|
15
|
-
* - trustProxyDepth=0: Direct connection, no proxies
|
|
16
|
-
* X-Forwarded-For: ignored
|
|
17
|
-
* Result: req.socket.remoteAddress
|
|
18
|
-
*
|
|
19
|
-
* - trustProxyDepth=1: Behind one proxy (e.g., Vercel, Netlify)
|
|
20
|
-
* X-Forwarded-For: "203.0.113.1, 198.51.100.1"
|
|
21
|
-
* Result: "203.0.113.1" (client IP)
|
|
22
|
-
*
|
|
23
|
-
* - trustProxyDepth=2: Behind two proxies (e.g., Cloudflare -> Load Balancer)
|
|
24
|
-
* X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
|
|
25
|
-
* Result: "203.0.113.1" (client IP)
|
|
26
|
-
*
|
|
27
|
-
* Common configurations:
|
|
28
|
-
* - Vercel/Netlify/Railway: trustProxyDepth=1
|
|
29
|
-
* - Cloudflare -> Origin: trustProxyDepth=1 or 2 (depending on your setup)
|
|
30
|
-
* - AWS ALB -> EC2: trustProxyDepth=1
|
|
31
|
-
* - Nginx -> Node: trustProxyDepth=1
|
|
32
|
-
* - Cloudflare -> Nginx -> Node: trustProxyDepth=2
|
|
33
|
-
*/
|
|
34
|
-
export declare function extractClientIP(req: http.IncomingMessage, trustProxyDepth?: number): string;
|
|
35
|
-
/**
|
|
36
|
-
* Alternative extraction method that works from the right (trusts the rightmost IPs).
|
|
37
|
-
* This is useful when you want to trust the last N proxies in the chain.
|
|
38
|
-
*
|
|
39
|
-
* @param req - The HTTP request object
|
|
40
|
-
* @param trustProxyDepth - Number of proxy levels to trust from the right
|
|
41
|
-
*
|
|
42
|
-
* Example:
|
|
43
|
-
* X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
|
|
44
|
-
* trustProxyDepth=1: Result is "198.51.100.1" (skip the last trusted proxy)
|
|
45
|
-
* trustProxyDepth=2: Result is "203.0.113.1" (skip the last 2 trusted proxies)
|
|
46
|
-
*/
|
|
47
|
-
export declare function extractClientIPFromRight(req: http.IncomingMessage, trustProxyDepth?: number): string;
|
|
48
|
-
//# sourceMappingURL=ipExtractor.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ipExtractor.d.ts","sourceRoot":"","sources":["../../src/server/ipExtractor.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,eAAe,GAAE,MAAU,GAAG,MAAM,CAqC9F;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,eAAe,GAAE,MAAU,GAAG,MAAM,CAsBvG"}
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Extracts the client IP address from an HTTP request, taking into account proxy configurations.
|
|
3
|
-
*
|
|
4
|
-
* When behind proxies (like Vercel, Cloudflare, AWS ALB, etc.), the X-Forwarded-For header
|
|
5
|
-
* contains a chain of IP addresses. The format is: "client, proxy1, proxy2, ..."
|
|
6
|
-
*
|
|
7
|
-
* @param req - The HTTP request object
|
|
8
|
-
* @param trustProxyDepth - Number of proxy levels to trust
|
|
9
|
-
* - 0: Only use req.socket.remoteAddress (no proxy trust)
|
|
10
|
-
* - 1: Trust 1 proxy level (get the last IP before your server)
|
|
11
|
-
* - 2+: Trust multiple proxy levels (for complex setups)
|
|
12
|
-
*
|
|
13
|
-
* Examples:
|
|
14
|
-
* - trustProxyDepth=0: Direct connection, no proxies
|
|
15
|
-
* X-Forwarded-For: ignored
|
|
16
|
-
* Result: req.socket.remoteAddress
|
|
17
|
-
*
|
|
18
|
-
* - trustProxyDepth=1: Behind one proxy (e.g., Vercel, Netlify)
|
|
19
|
-
* X-Forwarded-For: "203.0.113.1, 198.51.100.1"
|
|
20
|
-
* Result: "203.0.113.1" (client IP)
|
|
21
|
-
*
|
|
22
|
-
* - trustProxyDepth=2: Behind two proxies (e.g., Cloudflare -> Load Balancer)
|
|
23
|
-
* X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
|
|
24
|
-
* Result: "203.0.113.1" (client IP)
|
|
25
|
-
*
|
|
26
|
-
* Common configurations:
|
|
27
|
-
* - Vercel/Netlify/Railway: trustProxyDepth=1
|
|
28
|
-
* - Cloudflare -> Origin: trustProxyDepth=1 or 2 (depending on your setup)
|
|
29
|
-
* - AWS ALB -> EC2: trustProxyDepth=1
|
|
30
|
-
* - Nginx -> Node: trustProxyDepth=1
|
|
31
|
-
* - Cloudflare -> Nginx -> Node: trustProxyDepth=2
|
|
32
|
-
*/
|
|
33
|
-
export function extractClientIP(req, trustProxyDepth = 0) {
|
|
34
|
-
// If not trusting any proxies, return the direct connection IP
|
|
35
|
-
if (trustProxyDepth === 0) {
|
|
36
|
-
return req.socket.remoteAddress || "unknown";
|
|
37
|
-
}
|
|
38
|
-
// Get X-Forwarded-For header
|
|
39
|
-
const forwardedFor = req.headers["x-forwarded-for"];
|
|
40
|
-
if (!forwardedFor) {
|
|
41
|
-
// No X-Forwarded-For header, fall back to direct connection
|
|
42
|
-
return req.socket.remoteAddress || "unknown";
|
|
43
|
-
}
|
|
44
|
-
// Parse X-Forwarded-For header (can be a string or array of strings)
|
|
45
|
-
const forwardedIPs = (Array.isArray(forwardedFor) ? forwardedFor.join(",") : forwardedFor)
|
|
46
|
-
.split(",")
|
|
47
|
-
.map((ip) => ip.trim())
|
|
48
|
-
.filter((ip) => ip.length > 0);
|
|
49
|
-
if (forwardedIPs.length === 0) {
|
|
50
|
-
// Empty X-Forwarded-For, fall back to direct connection
|
|
51
|
-
return req.socket.remoteAddress || "unknown";
|
|
52
|
-
}
|
|
53
|
-
// The client IP is at the beginning of the chain
|
|
54
|
-
// We trust the chain up to trustProxyDepth levels
|
|
55
|
-
// Format: [clientIP, proxy1, proxy2, ..., lastProxy]
|
|
56
|
-
// We want the clientIP, but we need to verify we have enough trusted proxies
|
|
57
|
-
if (forwardedIPs.length < trustProxyDepth) {
|
|
58
|
-
// Not enough IPs in the chain, the chain might be incomplete or spoofed
|
|
59
|
-
// Fall back to direct connection for safety
|
|
60
|
-
return req.socket.remoteAddress || "unknown";
|
|
61
|
-
}
|
|
62
|
-
// Return the client IP (first in the chain)
|
|
63
|
-
return forwardedIPs[0];
|
|
64
|
-
}
|
|
65
|
-
/**
|
|
66
|
-
* Alternative extraction method that works from the right (trusts the rightmost IPs).
|
|
67
|
-
* This is useful when you want to trust the last N proxies in the chain.
|
|
68
|
-
*
|
|
69
|
-
* @param req - The HTTP request object
|
|
70
|
-
* @param trustProxyDepth - Number of proxy levels to trust from the right
|
|
71
|
-
*
|
|
72
|
-
* Example:
|
|
73
|
-
* X-Forwarded-For: "203.0.113.1, 198.51.100.1, 192.0.2.1"
|
|
74
|
-
* trustProxyDepth=1: Result is "198.51.100.1" (skip the last trusted proxy)
|
|
75
|
-
* trustProxyDepth=2: Result is "203.0.113.1" (skip the last 2 trusted proxies)
|
|
76
|
-
*/
|
|
77
|
-
export function extractClientIPFromRight(req, trustProxyDepth = 0) {
|
|
78
|
-
if (trustProxyDepth === 0) {
|
|
79
|
-
return req.socket.remoteAddress || "unknown";
|
|
80
|
-
}
|
|
81
|
-
const forwardedFor = req.headers["x-forwarded-for"];
|
|
82
|
-
if (!forwardedFor) {
|
|
83
|
-
return req.socket.remoteAddress || "unknown";
|
|
84
|
-
}
|
|
85
|
-
const forwardedIPs = (Array.isArray(forwardedFor) ? forwardedFor.join(",") : forwardedFor)
|
|
86
|
-
.split(",")
|
|
87
|
-
.map((ip) => ip.trim())
|
|
88
|
-
.filter((ip) => ip.length > 0);
|
|
89
|
-
if (forwardedIPs.length === 0) {
|
|
90
|
-
return req.socket.remoteAddress || "unknown";
|
|
91
|
-
}
|
|
92
|
-
// Calculate which IP to trust by skipping the rightmost N trusted proxies
|
|
93
|
-
const clientIPIndex = Math.max(0, forwardedIPs.length - trustProxyDepth - 1);
|
|
94
|
-
return forwardedIPs[clientIPIndex];
|
|
95
|
-
}
|
|
96
|
-
//# sourceMappingURL=ipExtractor.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ipExtractor.js","sourceRoot":"","sources":["../../src/server/ipExtractor.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,MAAM,UAAU,eAAe,CAAC,GAAyB,EAAE,kBAA0B,CAAC;IAClF,+DAA+D;IAC/D,IAAI,eAAe,KAAK,CAAC,EAAE,CAAC;QACxB,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,6BAA6B;IAC7B,MAAM,YAAY,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACpD,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,4DAA4D;QAC5D,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,qEAAqE;IACrE,MAAM,YAAY,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;SACrF,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC;SACtB,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAEnC,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,wDAAwD;QACxD,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,iDAAiD;IACjD,kDAAkD;IAClD,qDAAqD;IACrD,6EAA6E;IAE7E,IAAI,YAAY,CAAC,MAAM,GAAG,eAAe,EAAE,CAAC;QACxC,wEAAwE;QACxE,4CAA4C;QAC5C,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,4CAA4C;IAC5C,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC;AAC3B,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,wBAAwB,CAAC,GAAyB,EAAE,kBAA0B,CAAC;IAC3F,IAAI,eAAe,KAAK,CAAC,EAAE,CAAC;QACxB,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,MAAM,YAAY,GAAG,GAAG,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;IACpD,IAAI,CAAC,YAAY,EAAE,CAAC;QAChB,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,MAAM,YAAY,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,YAAY,CAAC;SACrF,KAAK,CAAC,GAAG,CAAC;SACV,GAAG,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC;SACtB,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;IAEnC,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC5B,OAAO,GAAG,CAAC,MAAM,CAAC,aAAa,IAAI,SAAS,CAAC;IACjD,CAAC;IAED,0EAA0E;IAC1E,MAAM,aAAa,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY,CAAC,MAAM,GAAG,eAAe,GAAG,CAAC,CAAC,CAAC;IAC7E,OAAO,YAAY,CAAC,aAAa,CAAC,CAAC;AACvC,CAAC"}
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
export declare function getRequestPath(url: string | undefined): string;
|
|
2
|
-
export declare function isDevInternalOrAssetRequest(url: string | undefined): boolean;
|
|
3
|
-
export declare function resolveDirectStaticAssetPath(staticDir: string, url: string | undefined): string | null;
|
|
4
|
-
//# sourceMappingURL=requestRouting.d.ts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"requestRouting.d.ts","sourceRoot":"","sources":["../../src/server/requestRouting.ts"],"names":[],"mappings":"AAsCA,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAE9D;AAED,wBAAgB,2BAA2B,CAAC,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,OAAO,CAS5E;AAED,wBAAgB,4BAA4B,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAwBtG"}
|