heliumts 0.10.0 → 0.10.2
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 +1 -1
- package/dist/client/Router.d.ts.map +1 -1
- package/dist/client/Router.js +19 -5
- package/dist/client/Router.js.map +1 -1
- package/dist/server/rpcDecoder.d.ts +4 -0
- package/dist/server/rpcDecoder.d.ts.map +1 -0
- package/dist/server/rpcDecoder.js +151 -0
- package/dist/server/rpcDecoder.js.map +1 -0
- package/dist/server/rpcRegistry.d.ts.map +1 -1
- package/dist/server/rpcRegistry.js +3 -3
- package/dist/server/rpcRegistry.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -31,7 +31,7 @@ HeliumTS is a lightweight, opinionated full-stack React + Vite framework designe
|
|
|
31
31
|
|
|
32
32
|
## 1. Getting Started
|
|
33
33
|
|
|
34
|
-
The current release is **0.10.
|
|
34
|
+
The current release is **0.10.2**. See the [changelog](./CHANGELOG.md) for fixes and upgrade notes.
|
|
35
35
|
|
|
36
36
|
### 1.1. Installation
|
|
37
37
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Router.d.ts","sourceRoot":"","sources":["../../src/client/Router.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAC3C,OAAO,KAAuD,MAAM,OAAO,CAAC;AA8F5E,KAAK,WAAW,GAAG,YAAY,GAAG,mBAAmB,CAAC;AACtD,KAAK,aAAa,GAAG,CAAC,KAAK,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,EAAE,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,IAAI,CAAA;CAAE,KAAK,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"Router.d.ts","sourceRoot":"","sources":["../../src/client/Router.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;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iB,CAC3C,IAAI,CAAC,KAAK,CAAC,oBAAoB,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC,GAAG;IAC1D,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,0EAA0E;IAC1E,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qDAAqD;IACrD,WAAW,CAAC,EAAE,OAAO,CAAC;CACzB,CACJ,CAAC;AA+BF;;;;;;;;;GASG;AACH,wBAAgB,IAAI,CAAC,KAAK,EAAE,SAAS,qBA4DpC;AAGD;;;;GAIG;AACH,MAAM,MAAM,aAAa,CAAC,UAAU,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,IAAI;IAC9F,SAAS,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC;IACrC,SAAS,EAAE,UAAU,CAAC;IACtB,QAAQ,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;CAC9B,CAAC;AAqBF,wBAAgB,SAAS,CAAC,EAAE,QAAQ,EAAE,EAAE;IAAE,QAAQ,CAAC,EAAE,aAAa,CAAC,aAAa,CAAC,CAAA;CAAE,qBA2KlF"}
|
package/dist/client/Router.js
CHANGED
|
@@ -99,6 +99,7 @@ function getLocation() {
|
|
|
99
99
|
const { pathname, search } = window.location;
|
|
100
100
|
return {
|
|
101
101
|
path: pathname,
|
|
102
|
+
search,
|
|
102
103
|
searchParams: new URLSearchParams(search),
|
|
103
104
|
isNavigating: false,
|
|
104
105
|
};
|
|
@@ -132,7 +133,7 @@ else if (typeof window !== "undefined") {
|
|
|
132
133
|
locationListeners = new Set();
|
|
133
134
|
}
|
|
134
135
|
else {
|
|
135
|
-
currentLocation = { path: "/", searchParams: new URLSearchParams(), isNavigating: false };
|
|
136
|
+
currentLocation = { path: "/", search: "", searchParams: new URLSearchParams(), isNavigating: false };
|
|
136
137
|
locationListeners = new Set();
|
|
137
138
|
}
|
|
138
139
|
// Helper to re-extract params from path using stored routes during HMR
|
|
@@ -156,9 +157,22 @@ function subscribeToLocation(callback) {
|
|
|
156
157
|
function getLocationSnapshot() {
|
|
157
158
|
return currentLocation;
|
|
158
159
|
}
|
|
159
|
-
const SERVER_SNAPSHOT = { path: "/", searchParams: new URLSearchParams(), isNavigating: false };
|
|
160
|
+
const SERVER_SNAPSHOT = { path: "/", search: "", searchParams: new URLSearchParams(), isNavigating: false };
|
|
161
|
+
let hydrationSnapshot;
|
|
160
162
|
function getServerSnapshot() {
|
|
161
|
-
|
|
163
|
+
if (typeof window === "undefined") {
|
|
164
|
+
return SERVER_SNAPSHOT;
|
|
165
|
+
}
|
|
166
|
+
if (!hydrationSnapshot) {
|
|
167
|
+
const bootstrap = getInitialSSRBootstrap();
|
|
168
|
+
const staticPath = document.getElementById("root")?.getAttribute("data-ssg-page");
|
|
169
|
+
// Static pages were rendered with their canonical pathname and no query.
|
|
170
|
+
// SSR pages serialize the exact request search, including its encoding.
|
|
171
|
+
const path = bootstrap?.path ?? staticPath ?? window.location.pathname;
|
|
172
|
+
const search = bootstrap ? (bootstrap.search ?? window.location.search) : staticPath !== null && staticPath !== undefined ? "" : window.location.search;
|
|
173
|
+
hydrationSnapshot = { path, search, searchParams: new URLSearchParams(search), isNavigating: false };
|
|
174
|
+
}
|
|
175
|
+
return hydrationSnapshot;
|
|
162
176
|
}
|
|
163
177
|
function updateLocation(isNavigating = false) {
|
|
164
178
|
const newLocation = { ...getLocation(), isNavigating };
|
|
@@ -410,7 +424,7 @@ export function AppRouter({ AppShell }) {
|
|
|
410
424
|
// Use useSyncExternalStore to subscribe to location changes
|
|
411
425
|
// This ensures synchronous updates when location changes
|
|
412
426
|
const state = useSyncExternalStore(subscribeToLocation, getLocationSnapshot, getServerSnapshot);
|
|
413
|
-
const targetPath = `${state.path}${typeof window !== "undefined" ? window.location.search : ""}`;
|
|
427
|
+
const targetPath = `${state.path}${state.search ?? (typeof window !== "undefined" ? window.location.search : "")}`;
|
|
414
428
|
const [runtimeSSRProps, setRuntimeSSRProps] = React.useState(() => {
|
|
415
429
|
const payload = getInitialSSRBootstrap();
|
|
416
430
|
if (!payload) {
|
|
@@ -424,7 +438,7 @@ export function AppRouter({ AppShell }) {
|
|
|
424
438
|
// Use matched params, or fall back to re-extracting from path using global routes during HMR
|
|
425
439
|
const currentParams = match?.params ?? (isDevEnvironment() ? extractParamsFromPath(state.path) : {});
|
|
426
440
|
// In dev mode, always read fresh searchParams from URL to handle HMR edge cases
|
|
427
|
-
const currentSearchParams = isDevEnvironment() ? new URLSearchParams(window.location.search) : state.searchParams;
|
|
441
|
+
const currentSearchParams = isDevEnvironment() && state !== hydrationSnapshot ? new URLSearchParams(window.location.search) : state.searchParams;
|
|
428
442
|
const routerValue = {
|
|
429
443
|
path: state.path,
|
|
430
444
|
params: currentParams,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Router.js","sourceRoot":"","sources":["../../src/client/Router.tsx"],"names":[],"mappings":";AACA,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAE5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA2BzC,SAAS,sBAAsB;IAC3B,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAChC,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,MAAM,YAAY,GAAG,MAEpB,CAAC;IAEF,MAAM,OAAO,GAAG,YAAY,CAAC,mBAAmB,CAAC;IACjD,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,KAAK,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b,CAAC;QAED,IAAI,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,KAAK,MAAM,EAAE,CAAC;YACxC,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;YAC3D,IAAI,GAAG,KAAK,WAAW,EAAE,CAAC;gBACtB,IAAI,CAAC,MAAM,EAAE,CAAC;YAClB,CAAC;YACD,SAAS;QACb,CAAC;QAED,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7D,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAErE,IAAI,IAAI,KAAK,aAAa,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7E,IAAI,CAAC,MAAM,EAAE,CAAC;YACd,SAAS;QACb,CAAC;QAED,IAAI,QAAQ,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7B,IAAI,CAAC,MAAM,EAAE,CAAC;QAClB,CAAC;IACL,CAAC;AACL,CAAC","sourcesContent":["import type { ComponentType } from \"react\";\nimport React, { useMemo, useSyncExternalStore, useTransition } from \"react\";\n\nimport { SEO_METADATA_RPC_METHOD } from \"../runtime/internalMethods.js\";\nimport { isDevEnvironment } from \"./env.js\";\nimport type { RouteEntry } from \"./routerManifest.js\";\nimport { buildRoutes } from \"./routerManifest.js\";\nimport { rpcCall } from \"./rpcClient.js\";\n\ntype HeliumSSRBootstrap = {\n path: string;\n search?: string;\n props: Record<string, unknown>;\n};\n\ntype SSRRedirectPayload = {\n destination: string;\n statusCode?: 301 | 302 | 303 | 307 | 308;\n replace?: boolean;\n};\n\ntype SSRPagePropsPayload =\n | {\n kind: \"props\";\n props: Record<string, unknown>;\n }\n | {\n kind: \"redirect\";\n redirect: SSRRedirectPayload;\n }\n | {\n kind: \"none\";\n };\n\nfunction getInitialSSRBootstrap(): HeliumSSRBootstrap | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n const globalWindow = window as typeof window & {\n __HELIUM_SSR_DATA__?: HeliumSSRBootstrap;\n };\n\n const payload = globalWindow.__HELIUM_SSR_DATA__;\n if (!payload || typeof payload !== \"object\" || typeof payload.path !== \"string\" || typeof payload.props !== \"object\" || payload.props === null) {\n return null;\n }\n\n return payload;\n}\n\nasync function fetchSSRPageProps(path: string): Promise<SSRPagePropsPayload> {\n try {\n const response = await fetch(`/__helium__/page-props?path=${encodeURIComponent(path)}`, {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n },\n });\n\n if (!response.ok) {\n return { kind: \"none\" };\n }\n\n const payload = (await response.json()) as {\n ssr?: boolean;\n props?: Record<string, unknown> | null;\n redirect?: SSRRedirectPayload;\n };\n\n if (!payload.ssr) {\n return { kind: \"none\" };\n }\n\n if (payload.redirect && typeof payload.redirect.destination === \"string\" && payload.redirect.destination.length > 0) {\n return {\n kind: \"redirect\",\n redirect: payload.redirect,\n };\n }\n\n if (!payload.props) {\n return { kind: \"none\" };\n }\n\n return {\n kind: \"props\",\n props: payload.props,\n };\n } catch {\n return { kind: \"none\" };\n }\n}\n\n// Event emitter for router events\ntype RouterEvent = \"navigation\" | \"before-navigation\";\ntype EventListener = (event: { from: string; to: string; preventDefault?: () => void }) => void;\n\nclass RouterEventEmitter {\n private listeners: Map<RouterEvent, Set<EventListener>> = new Map();\n\n on(event: RouterEvent, listener: EventListener): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener);\n };\n }\n\n emit(event: RouterEvent, data: { from: string; to: string }): boolean {\n const eventListeners = this.listeners.get(event);\n if (!eventListeners || eventListeners.size === 0) {\n return true;\n }\n\n let prevented = false;\n const preventDefault = () => {\n prevented = true;\n };\n\n const eventData = event === \"before-navigation\" ? { ...data, preventDefault } : data;\n\n eventListeners.forEach((listener) => {\n listener(eventData);\n });\n\n return !prevented;\n }\n\n // Clear all listeners - useful for HMR\n clear() {\n this.listeners.clear();\n }\n}\n\n// Use a singleton that survives HMR by attaching to window in dev mode\nlet routerEventEmitter: RouterEventEmitter;\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n // In dev mode, reuse the same emitter instance across HMR\n const globalWindow = window as typeof window & { __heliumRouterEmitter?: RouterEventEmitter };\n if (!globalWindow.__heliumRouterEmitter) {\n globalWindow.__heliumRouterEmitter = new RouterEventEmitter();\n }\n routerEventEmitter = globalWindow.__heliumRouterEmitter;\n} else {\n routerEventEmitter = new RouterEventEmitter();\n}\n\ntype RouterState = {\n path: string;\n searchParams: URLSearchParams;\n isNavigating: boolean;\n};\n\nfunction getLocation(): RouterState {\n const { pathname, search } = window.location;\n return {\n path: pathname,\n searchParams: new URLSearchParams(search),\n isNavigating: false,\n };\n}\n\nfunction matchRoute(path: string, routes: RouteEntry[]) {\n for (const r of routes) {\n const m = r.matcher(path);\n if (m) {\n return { params: m.params, route: r };\n }\n }\n return null;\n}\n\n// Location store for useSyncExternalStore\n// Preserve across HMR by attaching to window in dev mode\nlet currentLocation: RouterState;\nlet locationListeners: Set<() => void>;\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & {\n __heliumCurrentLocation?: RouterState;\n __heliumLocationListeners?: Set<() => void>;\n };\n if (!globalWindow.__heliumCurrentLocation) {\n globalWindow.__heliumCurrentLocation = getLocation();\n }\n if (!globalWindow.__heliumLocationListeners) {\n globalWindow.__heliumLocationListeners = new Set();\n }\n currentLocation = globalWindow.__heliumCurrentLocation;\n locationListeners = globalWindow.__heliumLocationListeners;\n} else if (typeof window !== \"undefined\") {\n currentLocation = getLocation();\n locationListeners = new Set();\n} else {\n currentLocation = { path: \"/\", searchParams: new URLSearchParams(), isNavigating: false };\n locationListeners = new Set();\n}\n\n// Helper to re-extract params from path using stored routes during HMR\nfunction extractParamsFromPath(path: string): Record<string, string | string[]> {\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n const routes = globalWindow.__heliumGlobalRoutes;\n if (routes && routes.length > 0) {\n const match = matchRoute(path, routes);\n if (match) {\n return match.params;\n }\n }\n }\n return {};\n}\n\nfunction subscribeToLocation(callback: () => void) {\n locationListeners.add(callback);\n return () => locationListeners.delete(callback);\n}\n\nfunction getLocationSnapshot() {\n return currentLocation;\n}\n\nconst SERVER_SNAPSHOT: RouterState = { path: \"/\", searchParams: new URLSearchParams(), isNavigating: false };\nfunction getServerSnapshot() {\n return SERVER_SNAPSHOT;\n}\n\nfunction updateLocation(isNavigating = false) {\n const newLocation = { ...getLocation(), isNavigating };\n currentLocation = newLocation;\n // Update the global reference in dev mode\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n (window as typeof window & { __heliumCurrentLocation?: RouterState }).__heliumCurrentLocation = newLocation;\n }\n locationListeners.forEach((listener) => listener());\n}\n\n// Set up global listeners once\nif (typeof window !== \"undefined\") {\n // Only set up once, survives HMR\n const globalWindow = window as typeof window & { __heliumLocationListenerSetup?: boolean };\n if (!globalWindow.__heliumLocationListenerSetup) {\n globalWindow.__heliumLocationListenerSetup = true;\n\n window.addEventListener(\"popstate\", () => updateLocation(false));\n\n // Also listen to navigation events from the emitter\n routerEventEmitter.on(\"navigation\", () => updateLocation(false));\n }\n}\n\n/** Options for push/replace navigation methods */\nexport interface RouterNavigationOptions {\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n}\n\n// Context for useRouter hook\ntype RouterContext = {\n path: string;\n params: Record<string, string | string[]>;\n searchParams: URLSearchParams;\n push: (href: string, options?: RouterNavigationOptions) => void;\n replace: (href: string, options?: RouterNavigationOptions) => void;\n on: (event: RouterEvent, listener: EventListener) => () => void;\n status: 200 | 404;\n isNavigating: boolean;\n /** Indicates content is stale (old content shown while new content renders) - React 18+ concurrent feature */\n isPending: boolean;\n};\n\nexport const RouterContext = React.createContext<RouterContext | null>(null);\n\n/**\n * Access router context inside a component tree managed by <AppRouter />.\n *\n * Provides current path, route params, URL search params and navigation helpers\n * (\\`push\\`, \\`replace\\`) as well as an \\`on\\` method to subscribe to navigation events.\n * The \\`isNavigating\\` property indicates when a navigation is in progress.\n * The \\`isPending\\` property indicates when content is stale (React concurrent features).\n * Throws when used outside of an <AppRouter /> provider.\n */\nexport function useRouter() {\n const ctx = React.useContext(RouterContext);\n if (!ctx) {\n // During HMR in development, context might be temporarily unavailable\n // Provide a temporary fallback to prevent white screen of death\n // Re-extract params from current path using stored routes\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n const currentPath = window.location.pathname;\n return {\n path: currentPath,\n params: extractParamsFromPath(currentPath),\n searchParams: new URLSearchParams(window.location.search),\n push: (href: string, options?: RouterNavigationOptions) => {\n window.history.pushState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n replace: (href: string, options?: RouterNavigationOptions) => {\n window.history.replaceState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n on: () => () => {},\n status: 200 as const,\n isNavigating: false,\n isPending: false,\n };\n }\n throw new Error(\"useRouter must be used inside <AppRouter>\");\n }\n return ctx;\n}\n\n/**\n * Redirect component for declarative navigation.\n * Use this instead of calling router.push() during render.\n *\n * @example\n * \\`\\`\\`tsx\n * export default function Docs() {\n * return <Redirect to=\"/docs/getting-started\" />;\n * }\n * \\`\\`\\`\n */\nexport function Redirect({ to, replace = false }: { to: string; replace?: boolean }) {\n const hasRedirected = React.useRef(false);\n\n // Use useLayoutEffect to redirect before paint\n React.useLayoutEffect(() => {\n const targetPath = to.split(\"?\")[0];\n if (!hasRedirected.current && window.location.pathname !== targetPath) {\n hasRedirected.current = true;\n\n // Perform navigation\n if (replace) {\n window.history.replaceState(null, \"\", to);\n } else {\n window.history.pushState(null, \"\", to);\n }\n\n // Emit navigation event to update router state\n routerEventEmitter.emit(\"navigation\", {\n from: window.location.pathname,\n to: targetPath,\n });\n }\n }, [to, replace]);\n\n return null;\n}\n\n/** Options for navigation */\ninterface NavigateOptions {\n replace?: boolean;\n scrollToTop?: boolean;\n}\n\n// Navigation helper\nfunction navigate(href: string, options: NavigateOptions = {}) {\n const { replace = false, scrollToTop = true } = options;\n const from = window.location.pathname;\n const to = href.split(\"?\")[0]; // Extract pathname from href\n\n // Emit before-navigation event (can be prevented)\n const canNavigate = routerEventEmitter.emit(\"before-navigation\", { from, to });\n if (!canNavigate) {\n return; // Navigation was prevented\n }\n\n // Set navigating state to true before navigation\n currentLocation = { ...currentLocation, isNavigating: true };\n locationListeners.forEach((listener) => listener());\n\n if (replace) {\n window.history.replaceState(null, \"\", href);\n } else {\n window.history.pushState(null, \"\", href);\n }\n\n // Scroll to top immediately after pushState, before React re-renders.\n // Using instant scroll avoids race conditions where smooth scrolling\n // gets interrupted by React DOM updates, especially on Safari mobile.\n if (scrollToTop) {\n window.scrollTo({ top: 0, left: 0, behavior: \"instant\" });\n }\n\n // Update location state synchronously so there is no stale-state window\n // between pushState and the next render.\n updateLocation(false);\n\n // Emit navigation event after state is consistent\n routerEventEmitter.emit(\"navigation\", { from, to });\n}\n\nexport type LinkProps = React.PropsWithChildren<\n Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> & {\n href: string;\n replace?: boolean;\n /** Disable prefetching on hover (default: false - prefetch is enabled) */\n prefetch?: boolean;\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n }\n>;\n\n/**\n * Check if a URL is external (different origin).\n */\nfunction isExternalUrl(href: string): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n const url = new URL(href, window.location.origin);\n return url.origin !== window.location.origin;\n } catch {\n return false;\n }\n}\n\n// Store routes globally for prefetching (set by AppRouter)\n// Preserve across HMR in dev mode\nlet globalRoutes: RouteEntry[];\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n if (!globalWindow.__heliumGlobalRoutes) {\n globalWindow.__heliumGlobalRoutes = [];\n }\n globalRoutes = globalWindow.__heliumGlobalRoutes;\n} else {\n globalRoutes = [];\n}\n\n/**\n * Client-side navigation link.\n *\n * Intercepts left-clicks and uses the router's navigation helpers for SPA\n * navigation. Keeps normal anchor behaviour when modifier keys are used,\n * when the link is external, or when `target` / `download` attributes\n * are present.\n *\n * Automatically prefetches page chunks on hover for faster navigation.\n */\nexport function Link(props: LinkProps) {\n const {\n children,\n href,\n className,\n prefetch: prefetchProp = true,\n scrollToTop = true,\n replace: replaceProp,\n target,\n download,\n onClick: userOnClick,\n onMouseEnter: userOnMouseEnter,\n onFocus: userOnFocus,\n ...restProps\n } = props;\n\n const onClick = (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Let user's onClick run first so they can call e.preventDefault()\n userOnClick?.(e);\n\n if (\n e.defaultPrevented ||\n e.button !== 0 || // only left click\n e.metaKey ||\n e.ctrlKey ||\n e.shiftKey ||\n e.altKey ||\n target || // let browser handle target=\"_blank\" etc.\n download != null || // let browser handle downloads\n isExternalUrl(href) // let browser handle external links\n ) {\n return;\n }\n e.preventDefault();\n navigate(href, { replace: replaceProp, scrollToTop });\n };\n\n const onMouseEnter = async (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Prefetch the route on hover if enabled and not external (lazy-load prefetch logic)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnMouseEnter?.(e);\n };\n\n const onFocus = async (e: React.FocusEvent<HTMLAnchorElement>) => {\n // Also prefetch on focus (keyboard navigation)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnFocus?.(e);\n };\n\n return (\n <a {...restProps} href={href} target={target} download={download} onClick={onClick} onMouseEnter={onMouseEnter} onFocus={onFocus} className={className}>\n {children}\n </a>\n );\n}\n\n// AppShell props type\n/**\n * Props passed to an optional \\`AppShell\\` wrapper component used by <AppRouter />.\n *\n * \\`Component\\` — the page component to render. \\`pageProps\\` — props provided to the page.\n */\nexport type AppShellProps<TPageProps extends Record<string, unknown> = Record<string, unknown>> = {\n Component: ComponentType<TPageProps>;\n pageProps: TPageProps;\n children?: React.ReactNode;\n};\n\n// Keep the component type and shared layout positions stable across router\n// updates, so loading page props or navigating does not discard local state.\nconst PageRouteContext = React.createContext<RouteEntry | null>(null);\n\nfunction RoutedPage(pageProps: Record<string, unknown>) {\n const route = React.useContext(PageRouteContext);\n if (!route) {\n return null;\n }\n const Page = route.Component as ComponentType<Record<string, unknown>>;\n let content = <Page {...pageProps} />;\n for (let i = route.layouts.length - 1; i >= 0; i--) {\n const Layout = route.layouts[i];\n content = <Layout>{content}</Layout>;\n }\n return content;\n}\n\n// Main router component\nexport function AppRouter({ AppShell }: { AppShell?: ComponentType<AppShellProps> }) {\n // useTransition for concurrent rendering - allows React to keep UI responsive during navigation\n const [isPending, startTransition] = useTransition();\n\n // Build routes once on mount (client-side only)\n const { routes, NotFound } = useMemo(() => {\n if (typeof window === \"undefined\") {\n return { routes: [], NotFound: undefined };\n }\n const result = buildRoutes();\n // Store routes globally for Link prefetching\n // In dev mode, also update the global reference to survive HMR\n if (isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n globalWindow.__heliumGlobalRoutes = result.routes;\n // Update the module-level reference as well\n globalRoutes.length = 0;\n globalRoutes.push(...result.routes);\n } else {\n globalRoutes = result.routes;\n }\n return result;\n }, []);\n\n // Use useSyncExternalStore to subscribe to location changes\n // This ensures synchronous updates when location changes\n const state = useSyncExternalStore(subscribeToLocation, getLocationSnapshot, getServerSnapshot);\n const targetPath = `${state.path}${typeof window !== \"undefined\" ? window.location.search : \"\"}`;\n const [runtimeSSRProps, setRuntimeSSRProps] = React.useState<{ path: string; props: Record<string, unknown> }>(() => {\n const payload = getInitialSSRBootstrap();\n if (!payload) {\n return { path: targetPath, props: {} };\n }\n\n const bootstrapPath = `${payload.path}${payload.search ?? window.location.search}`;\n return { path: bootstrapPath, props: payload.props };\n });\n const hydrationDoneRef = React.useRef(false);\n\n const match = useMemo(() => matchRoute(state.path, routes), [state.path, routes]);\n // Use matched params, or fall back to re-extracting from path using global routes during HMR\n const currentParams = match?.params ?? (isDevEnvironment() ? extractParamsFromPath(state.path) : {});\n\n // In dev mode, always read fresh searchParams from URL to handle HMR edge cases\n const currentSearchParams = isDevEnvironment() ? new URLSearchParams(window.location.search) : state.searchParams;\n\n const routerValue: RouterContext = {\n path: state.path,\n params: currentParams,\n searchParams: currentSearchParams,\n push: (href, options) => {\n // Wrap navigation in startTransition for smoother updates\n startTransition(() => {\n navigate(href, { scrollToTop: options?.scrollToTop });\n });\n },\n replace: (href, options) => {\n startTransition(() => {\n navigate(href, { replace: true, scrollToTop: options?.scrollToTop });\n });\n },\n on: (event, listener) => routerEventEmitter.on(event, listener),\n status: match ? 200 : 404,\n isNavigating: state.isNavigating,\n isPending,\n };\n\n React.useEffect(() => {\n // On first client render, keep the matching SSR payload. A ref avoids\n // restarting this effect and remounting content just to mark hydration.\n if (!hydrationDoneRef.current) {\n hydrationDoneRef.current = true;\n const bootstrap = getInitialSSRBootstrap();\n if (bootstrap && `${bootstrap.path}${bootstrap.search ?? window.location.search}` === targetPath) {\n return;\n }\n }\n\n let cancelled = false;\n\n const load = async () => {\n const ssrPayload = await fetchSSRPageProps(targetPath);\n if (cancelled) {\n return;\n }\n\n if (ssrPayload.kind === \"redirect\") {\n const destination = ssrPayload.redirect.destination;\n\n if (isExternalUrl(destination)) {\n window.location.assign(destination);\n return;\n }\n\n navigate(destination, {\n replace: ssrPayload.redirect.replace ?? true,\n scrollToTop: true,\n });\n return;\n }\n\n if (ssrPayload.kind === \"props\") {\n setRuntimeSSRProps({ path: targetPath, props: ssrPayload.props });\n return;\n }\n\n setRuntimeSSRProps({ path: targetPath, props: {} });\n };\n\n void load();\n\n return () => {\n cancelled = true;\n };\n }, [targetPath]);\n\n React.useEffect(() => {\n const controller = new AbortController();\n const targetPath = `${state.path}${window.location.search || \"\"}`;\n\n const syncMetadata = async () => {\n try {\n if (controller.signal.aborted) {\n return;\n }\n\n const result = await rpcCall<ClientSocialMeta | null, { path: string }>(SEO_METADATA_RPC_METHOD, { path: targetPath });\n\n if (controller.signal.aborted) {\n return;\n }\n\n applyRouteMetadata(result.data ?? null);\n } catch (error) {\n if ((error as { name?: string })?.name === \"AbortError\") {\n return;\n }\n }\n };\n\n syncMetadata();\n\n return () => controller.abort();\n }, [state.path, currentSearchParams.toString()]);\n\n if (!match) {\n const NotFoundComp = NotFound ?? (() => <div>Not found</div>);\n const content = <NotFoundComp />;\n\n return <RouterContext.Provider value={routerValue}>{AppShell ? <AppShell Component={NotFoundComp} pageProps={{}} /> : content}</RouterContext.Provider>;\n }\n\n const pageProps = {\n ...(runtimeSSRProps.path === targetPath ? runtimeSSRProps.props : {}),\n params: match.params,\n searchParams: currentSearchParams,\n };\n\n const finalContent = AppShell ? (\n <AppShell Component={RoutedPage} pageProps={pageProps}>\n <RoutedPage {...pageProps} />\n </AppShell>\n ) : (\n <RoutedPage {...pageProps} />\n );\n\n return (\n <RouterContext.Provider value={routerValue}>\n <PageRouteContext.Provider value={match.route}>{finalContent}</PageRouteContext.Provider>\n </RouterContext.Provider>\n );\n}\n\ntype ClientSocialMeta = {\n title: string;\n description?: string;\n image?: string;\n canonicalUrl?: string;\n siteName?: string;\n type?: string;\n robots?: string;\n twitterCard?: \"summary\" | \"summary_large_image\" | \"app\" | \"player\";\n twitterSite?: string;\n twitterCreator?: string;\n};\n\nfunction applyRouteMetadata(meta: ClientSocialMeta | null) {\n if (typeof document === \"undefined\") {\n return;\n }\n\n removeExistingSeoTags();\n\n if (!meta) {\n return;\n }\n\n document.title = meta.title;\n\n const entries: Array<{ tag: \"meta\" | \"link\"; attrs: Record<string, string> }> = [];\n\n entries.push({ tag: \"meta\", attrs: { property: \"og:title\", content: meta.title } });\n entries.push({ tag: \"meta\", attrs: { property: \"og:type\", content: meta.type ?? \"website\" } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:card\", content: meta.twitterCard ?? \"summary_large_image\" } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:title\", content: meta.title } });\n\n if (meta.description) {\n entries.push({ tag: \"meta\", attrs: { name: \"description\", content: meta.description } });\n entries.push({ tag: \"meta\", attrs: { property: \"og:description\", content: meta.description } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:description\", content: meta.description } });\n }\n\n if (meta.image) {\n entries.push({ tag: \"meta\", attrs: { property: \"og:image\", content: meta.image } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:image\", content: meta.image } });\n }\n\n if (meta.canonicalUrl) {\n entries.push({ tag: \"meta\", attrs: { property: \"og:url\", content: meta.canonicalUrl } });\n entries.push({ tag: \"link\", attrs: { rel: \"canonical\", href: meta.canonicalUrl } });\n }\n\n if (meta.siteName) {\n entries.push({ tag: \"meta\", attrs: { property: \"og:site_name\", content: meta.siteName } });\n }\n\n if (meta.robots) {\n entries.push({ tag: \"meta\", attrs: { name: \"robots\", content: meta.robots } });\n }\n\n if (meta.twitterSite) {\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:site\", content: meta.twitterSite } });\n }\n\n if (meta.twitterCreator) {\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:creator\", content: meta.twitterCreator } });\n }\n\n for (const entry of entries) {\n const node = document.createElement(entry.tag);\n for (const [key, value] of Object.entries(entry.attrs)) {\n node.setAttribute(key, value);\n }\n node.setAttribute(\"data-helium-seo\", \"true\");\n document.head.appendChild(node);\n }\n}\n\nfunction removeExistingSeoTags() {\n const headNodes = Array.from(document.head.querySelectorAll(\"meta, link\"));\n\n for (const node of headNodes) {\n if (node.getAttribute(\"data-helium-seo\") === \"true\") {\n node.remove();\n continue;\n }\n\n if (node.tagName.toLowerCase() === \"link\") {\n const rel = (node.getAttribute(\"rel\") || \"\").toLowerCase();\n if (rel === \"canonical\") {\n node.remove();\n }\n continue;\n }\n\n const name = (node.getAttribute(\"name\") || \"\").toLowerCase();\n const property = (node.getAttribute(\"property\") || \"\").toLowerCase();\n\n if (name === \"description\" || name === \"robots\" || name.startsWith(\"twitter:\")) {\n node.remove();\n continue;\n }\n\n if (property.startsWith(\"og:\")) {\n node.remove();\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"Router.js","sourceRoot":"","sources":["../../src/client/Router.tsx"],"names":[],"mappings":";AACA,OAAO,KAAK,EAAE,EAAE,OAAO,EAAE,oBAAoB,EAAE,aAAa,EAAE,MAAM,OAAO,CAAC;AAE5E,OAAO,EAAE,uBAAuB,EAAE,MAAM,+BAA+B,CAAC;AACxE,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAC;AAE5C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,EAAE,OAAO,EAAE,MAAM,gBAAgB,CAAC;AA2BzC,SAAS,sBAAsB;IAC3B,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAAC;QAChC,OAAO,IAAI,CAAC;IAChB,CAAC;IAED,MAAM,YAAY,GAAG,MAEpB,CAAC;IAEF,MAAM,OAAO,GAAG,YAAY,CAAC,mBAAmB,CAAC;IACjD,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,OAAO,CAAC,KAAK,KAAK,QAAQ,IAAI,OA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AAI,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,MAAM,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAC7D,MAAM,QAAQ,GAAG,CAAC,IAAI,CAAC,YAAY,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;QAErE,IAAI,IAAI,KAAK,aAAa,IAAI,IAAI,KAAK,QAAQ,IAAI,IAAI,CAAC,UAAU,CAAC,UAAU,CAAC,EAAE,CAAC;YAC7E,IAAI,CAAC,MAAM,EAAE,CAAC;YACd,SAAS;QACb,CAAC;QAED,IAAI,QAAQ,CAAC,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;YAC7B,IAAI,CAAC,MAAM,EAAE,CAAC;QAClB,CAAC;IACL,CAAC;AACL,CAAC","sourcesContent":["import type { ComponentType } from \"react\";\nimport React, { useMemo, useSyncExternalStore, useTransition } from \"react\";\n\nimport { SEO_METADATA_RPC_METHOD } from \"../runtime/internalMethods.js\";\nimport { isDevEnvironment } from \"./env.js\";\nimport type { RouteEntry } from \"./routerManifest.js\";\nimport { buildRoutes } from \"./routerManifest.js\";\nimport { rpcCall } from \"./rpcClient.js\";\n\ntype HeliumSSRBootstrap = {\n path: string;\n search?: string;\n props: Record<string, unknown>;\n};\n\ntype SSRRedirectPayload = {\n destination: string;\n statusCode?: 301 | 302 | 303 | 307 | 308;\n replace?: boolean;\n};\n\ntype SSRPagePropsPayload =\n | {\n kind: \"props\";\n props: Record<string, unknown>;\n }\n | {\n kind: \"redirect\";\n redirect: SSRRedirectPayload;\n }\n | {\n kind: \"none\";\n };\n\nfunction getInitialSSRBootstrap(): HeliumSSRBootstrap | null {\n if (typeof window === \"undefined\") {\n return null;\n }\n\n const globalWindow = window as typeof window & {\n __HELIUM_SSR_DATA__?: HeliumSSRBootstrap;\n };\n\n const payload = globalWindow.__HELIUM_SSR_DATA__;\n if (!payload || typeof payload !== \"object\" || typeof payload.path !== \"string\" || typeof payload.props !== \"object\" || payload.props === null) {\n return null;\n }\n\n return payload;\n}\n\nasync function fetchSSRPageProps(path: string): Promise<SSRPagePropsPayload> {\n try {\n const response = await fetch(`/__helium__/page-props?path=${encodeURIComponent(path)}`, {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n },\n });\n\n if (!response.ok) {\n return { kind: \"none\" };\n }\n\n const payload = (await response.json()) as {\n ssr?: boolean;\n props?: Record<string, unknown> | null;\n redirect?: SSRRedirectPayload;\n };\n\n if (!payload.ssr) {\n return { kind: \"none\" };\n }\n\n if (payload.redirect && typeof payload.redirect.destination === \"string\" && payload.redirect.destination.length > 0) {\n return {\n kind: \"redirect\",\n redirect: payload.redirect,\n };\n }\n\n if (!payload.props) {\n return { kind: \"none\" };\n }\n\n return {\n kind: \"props\",\n props: payload.props,\n };\n } catch {\n return { kind: \"none\" };\n }\n}\n\n// Event emitter for router events\ntype RouterEvent = \"navigation\" | \"before-navigation\";\ntype EventListener = (event: { from: string; to: string; preventDefault?: () => void }) => void;\n\nclass RouterEventEmitter {\n private listeners: Map<RouterEvent, Set<EventListener>> = new Map();\n\n on(event: RouterEvent, listener: EventListener): () => void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener);\n\n // Return unsubscribe function\n return () => {\n this.listeners.get(event)?.delete(listener);\n };\n }\n\n emit(event: RouterEvent, data: { from: string; to: string }): boolean {\n const eventListeners = this.listeners.get(event);\n if (!eventListeners || eventListeners.size === 0) {\n return true;\n }\n\n let prevented = false;\n const preventDefault = () => {\n prevented = true;\n };\n\n const eventData = event === \"before-navigation\" ? { ...data, preventDefault } : data;\n\n eventListeners.forEach((listener) => {\n listener(eventData);\n });\n\n return !prevented;\n }\n\n // Clear all listeners - useful for HMR\n clear() {\n this.listeners.clear();\n }\n}\n\n// Use a singleton that survives HMR by attaching to window in dev mode\nlet routerEventEmitter: RouterEventEmitter;\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n // In dev mode, reuse the same emitter instance across HMR\n const globalWindow = window as typeof window & { __heliumRouterEmitter?: RouterEventEmitter };\n if (!globalWindow.__heliumRouterEmitter) {\n globalWindow.__heliumRouterEmitter = new RouterEventEmitter();\n }\n routerEventEmitter = globalWindow.__heliumRouterEmitter;\n} else {\n routerEventEmitter = new RouterEventEmitter();\n}\n\ntype RouterState = {\n path: string;\n search: string;\n searchParams: URLSearchParams;\n isNavigating: boolean;\n};\n\nfunction getLocation(): RouterState {\n const { pathname, search } = window.location;\n return {\n path: pathname,\n search,\n searchParams: new URLSearchParams(search),\n isNavigating: false,\n };\n}\n\nfunction matchRoute(path: string, routes: RouteEntry[]) {\n for (const r of routes) {\n const m = r.matcher(path);\n if (m) {\n return { params: m.params, route: r };\n }\n }\n return null;\n}\n\n// Location store for useSyncExternalStore\n// Preserve across HMR by attaching to window in dev mode\nlet currentLocation: RouterState;\nlet locationListeners: Set<() => void>;\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & {\n __heliumCurrentLocation?: RouterState;\n __heliumLocationListeners?: Set<() => void>;\n };\n if (!globalWindow.__heliumCurrentLocation) {\n globalWindow.__heliumCurrentLocation = getLocation();\n }\n if (!globalWindow.__heliumLocationListeners) {\n globalWindow.__heliumLocationListeners = new Set();\n }\n currentLocation = globalWindow.__heliumCurrentLocation;\n locationListeners = globalWindow.__heliumLocationListeners;\n} else if (typeof window !== \"undefined\") {\n currentLocation = getLocation();\n locationListeners = new Set();\n} else {\n currentLocation = { path: \"/\", search: \"\", searchParams: new URLSearchParams(), isNavigating: false };\n locationListeners = new Set();\n}\n\n// Helper to re-extract params from path using stored routes during HMR\nfunction extractParamsFromPath(path: string): Record<string, string | string[]> {\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n const routes = globalWindow.__heliumGlobalRoutes;\n if (routes && routes.length > 0) {\n const match = matchRoute(path, routes);\n if (match) {\n return match.params;\n }\n }\n }\n return {};\n}\n\nfunction subscribeToLocation(callback: () => void) {\n locationListeners.add(callback);\n return () => locationListeners.delete(callback);\n}\n\nfunction getLocationSnapshot() {\n return currentLocation;\n}\n\nconst SERVER_SNAPSHOT: RouterState = { path: \"/\", search: \"\", searchParams: new URLSearchParams(), isNavigating: false };\nlet hydrationSnapshot: RouterState | undefined;\nfunction getServerSnapshot() {\n if (typeof window === \"undefined\") {\n return SERVER_SNAPSHOT;\n }\n if (!hydrationSnapshot) {\n const bootstrap = getInitialSSRBootstrap();\n const staticPath = document.getElementById(\"root\")?.getAttribute(\"data-ssg-page\");\n // Static pages were rendered with their canonical pathname and no query.\n // SSR pages serialize the exact request search, including its encoding.\n const path = bootstrap?.path ?? staticPath ?? window.location.pathname;\n const search = bootstrap ? (bootstrap.search ?? window.location.search) : staticPath !== null && staticPath !== undefined ? \"\" : window.location.search;\n hydrationSnapshot = { path, search, searchParams: new URLSearchParams(search), isNavigating: false };\n }\n return hydrationSnapshot;\n}\n\nfunction updateLocation(isNavigating = false) {\n const newLocation = { ...getLocation(), isNavigating };\n currentLocation = newLocation;\n // Update the global reference in dev mode\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n (window as typeof window & { __heliumCurrentLocation?: RouterState }).__heliumCurrentLocation = newLocation;\n }\n locationListeners.forEach((listener) => listener());\n}\n\n// Set up global listeners once\nif (typeof window !== \"undefined\") {\n // Only set up once, survives HMR\n const globalWindow = window as typeof window & { __heliumLocationListenerSetup?: boolean };\n if (!globalWindow.__heliumLocationListenerSetup) {\n globalWindow.__heliumLocationListenerSetup = true;\n\n window.addEventListener(\"popstate\", () => updateLocation(false));\n\n // Also listen to navigation events from the emitter\n routerEventEmitter.on(\"navigation\", () => updateLocation(false));\n }\n}\n\n/** Options for push/replace navigation methods */\nexport interface RouterNavigationOptions {\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n}\n\n// Context for useRouter hook\ntype RouterContext = {\n path: string;\n params: Record<string, string | string[]>;\n searchParams: URLSearchParams;\n push: (href: string, options?: RouterNavigationOptions) => void;\n replace: (href: string, options?: RouterNavigationOptions) => void;\n on: (event: RouterEvent, listener: EventListener) => () => void;\n status: 200 | 404;\n isNavigating: boolean;\n /** Indicates content is stale (old content shown while new content renders) - React 18+ concurrent feature */\n isPending: boolean;\n};\n\nexport const RouterContext = React.createContext<RouterContext | null>(null);\n\n/**\n * Access router context inside a component tree managed by <AppRouter />.\n *\n * Provides current path, route params, URL search params and navigation helpers\n * (\\`push\\`, \\`replace\\`) as well as an \\`on\\` method to subscribe to navigation events.\n * The \\`isNavigating\\` property indicates when a navigation is in progress.\n * The \\`isPending\\` property indicates when content is stale (React concurrent features).\n * Throws when used outside of an <AppRouter /> provider.\n */\nexport function useRouter() {\n const ctx = React.useContext(RouterContext);\n if (!ctx) {\n // During HMR in development, context might be temporarily unavailable\n // Provide a temporary fallback to prevent white screen of death\n // Re-extract params from current path using stored routes\n if (typeof window !== \"undefined\" && isDevEnvironment()) {\n const currentPath = window.location.pathname;\n return {\n path: currentPath,\n params: extractParamsFromPath(currentPath),\n searchParams: new URLSearchParams(window.location.search),\n push: (href: string, options?: RouterNavigationOptions) => {\n window.history.pushState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n replace: (href: string, options?: RouterNavigationOptions) => {\n window.history.replaceState({}, \"\", href);\n if (options?.scrollToTop !== false) {\n window.scrollTo({ top: 0, left: 0, behavior: \"smooth\" });\n }\n window.dispatchEvent(new PopStateEvent(\"popstate\"));\n },\n on: () => () => {},\n status: 200 as const,\n isNavigating: false,\n isPending: false,\n };\n }\n throw new Error(\"useRouter must be used inside <AppRouter>\");\n }\n return ctx;\n}\n\n/**\n * Redirect component for declarative navigation.\n * Use this instead of calling router.push() during render.\n *\n * @example\n * \\`\\`\\`tsx\n * export default function Docs() {\n * return <Redirect to=\"/docs/getting-started\" />;\n * }\n * \\`\\`\\`\n */\nexport function Redirect({ to, replace = false }: { to: string; replace?: boolean }) {\n const hasRedirected = React.useRef(false);\n\n // Use useLayoutEffect to redirect before paint\n React.useLayoutEffect(() => {\n const targetPath = to.split(\"?\")[0];\n if (!hasRedirected.current && window.location.pathname !== targetPath) {\n hasRedirected.current = true;\n\n // Perform navigation\n if (replace) {\n window.history.replaceState(null, \"\", to);\n } else {\n window.history.pushState(null, \"\", to);\n }\n\n // Emit navigation event to update router state\n routerEventEmitter.emit(\"navigation\", {\n from: window.location.pathname,\n to: targetPath,\n });\n }\n }, [to, replace]);\n\n return null;\n}\n\n/** Options for navigation */\ninterface NavigateOptions {\n replace?: boolean;\n scrollToTop?: boolean;\n}\n\n// Navigation helper\nfunction navigate(href: string, options: NavigateOptions = {}) {\n const { replace = false, scrollToTop = true } = options;\n const from = window.location.pathname;\n const to = href.split(\"?\")[0]; // Extract pathname from href\n\n // Emit before-navigation event (can be prevented)\n const canNavigate = routerEventEmitter.emit(\"before-navigation\", { from, to });\n if (!canNavigate) {\n return; // Navigation was prevented\n }\n\n // Set navigating state to true before navigation\n currentLocation = { ...currentLocation, isNavigating: true };\n locationListeners.forEach((listener) => listener());\n\n if (replace) {\n window.history.replaceState(null, \"\", href);\n } else {\n window.history.pushState(null, \"\", href);\n }\n\n // Scroll to top immediately after pushState, before React re-renders.\n // Using instant scroll avoids race conditions where smooth scrolling\n // gets interrupted by React DOM updates, especially on Safari mobile.\n if (scrollToTop) {\n window.scrollTo({ top: 0, left: 0, behavior: \"instant\" });\n }\n\n // Update location state synchronously so there is no stale-state window\n // between pushState and the next render.\n updateLocation(false);\n\n // Emit navigation event after state is consistent\n routerEventEmitter.emit(\"navigation\", { from, to });\n}\n\nexport type LinkProps = React.PropsWithChildren<\n Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, \"href\"> & {\n href: string;\n replace?: boolean;\n /** Disable prefetching on hover (default: false - prefetch is enabled) */\n prefetch?: boolean;\n /** Scroll to top after navigation (default: true) */\n scrollToTop?: boolean;\n }\n>;\n\n/**\n * Check if a URL is external (different origin).\n */\nfunction isExternalUrl(href: string): boolean {\n if (typeof window === \"undefined\") {\n return false;\n }\n try {\n const url = new URL(href, window.location.origin);\n return url.origin !== window.location.origin;\n } catch {\n return false;\n }\n}\n\n// Store routes globally for prefetching (set by AppRouter)\n// Preserve across HMR in dev mode\nlet globalRoutes: RouteEntry[];\n\nif (typeof window !== \"undefined\" && isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n if (!globalWindow.__heliumGlobalRoutes) {\n globalWindow.__heliumGlobalRoutes = [];\n }\n globalRoutes = globalWindow.__heliumGlobalRoutes;\n} else {\n globalRoutes = [];\n}\n\n/**\n * Client-side navigation link.\n *\n * Intercepts left-clicks and uses the router's navigation helpers for SPA\n * navigation. Keeps normal anchor behaviour when modifier keys are used,\n * when the link is external, or when `target` / `download` attributes\n * are present.\n *\n * Automatically prefetches page chunks on hover for faster navigation.\n */\nexport function Link(props: LinkProps) {\n const {\n children,\n href,\n className,\n prefetch: prefetchProp = true,\n scrollToTop = true,\n replace: replaceProp,\n target,\n download,\n onClick: userOnClick,\n onMouseEnter: userOnMouseEnter,\n onFocus: userOnFocus,\n ...restProps\n } = props;\n\n const onClick = (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Let user's onClick run first so they can call e.preventDefault()\n userOnClick?.(e);\n\n if (\n e.defaultPrevented ||\n e.button !== 0 || // only left click\n e.metaKey ||\n e.ctrlKey ||\n e.shiftKey ||\n e.altKey ||\n target || // let browser handle target=\"_blank\" etc.\n download != null || // let browser handle downloads\n isExternalUrl(href) // let browser handle external links\n ) {\n return;\n }\n e.preventDefault();\n navigate(href, { replace: replaceProp, scrollToTop });\n };\n\n const onMouseEnter = async (e: React.MouseEvent<HTMLAnchorElement>) => {\n // Prefetch the route on hover if enabled and not external (lazy-load prefetch logic)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnMouseEnter?.(e);\n };\n\n const onFocus = async (e: React.FocusEvent<HTMLAnchorElement>) => {\n // Also prefetch on focus (keyboard navigation)\n if (prefetchProp && !isExternalUrl(href) && globalRoutes.length > 0) {\n const { prefetchRoute } = await import(\"./prefetch.js\");\n prefetchRoute(href, globalRoutes);\n }\n userOnFocus?.(e);\n };\n\n return (\n <a {...restProps} href={href} target={target} download={download} onClick={onClick} onMouseEnter={onMouseEnter} onFocus={onFocus} className={className}>\n {children}\n </a>\n );\n}\n\n// AppShell props type\n/**\n * Props passed to an optional \\`AppShell\\` wrapper component used by <AppRouter />.\n *\n * \\`Component\\` — the page component to render. \\`pageProps\\` — props provided to the page.\n */\nexport type AppShellProps<TPageProps extends Record<string, unknown> = Record<string, unknown>> = {\n Component: ComponentType<TPageProps>;\n pageProps: TPageProps;\n children?: React.ReactNode;\n};\n\n// Keep the component type and shared layout positions stable across router\n// updates, so loading page props or navigating does not discard local state.\nconst PageRouteContext = React.createContext<RouteEntry | null>(null);\n\nfunction RoutedPage(pageProps: Record<string, unknown>) {\n const route = React.useContext(PageRouteContext);\n if (!route) {\n return null;\n }\n const Page = route.Component as ComponentType<Record<string, unknown>>;\n let content = <Page {...pageProps} />;\n for (let i = route.layouts.length - 1; i >= 0; i--) {\n const Layout = route.layouts[i];\n content = <Layout>{content}</Layout>;\n }\n return content;\n}\n\n// Main router component\nexport function AppRouter({ AppShell }: { AppShell?: ComponentType<AppShellProps> }) {\n // useTransition for concurrent rendering - allows React to keep UI responsive during navigation\n const [isPending, startTransition] = useTransition();\n\n // Build routes once on mount (client-side only)\n const { routes, NotFound } = useMemo(() => {\n if (typeof window === \"undefined\") {\n return { routes: [], NotFound: undefined };\n }\n const result = buildRoutes();\n // Store routes globally for Link prefetching\n // In dev mode, also update the global reference to survive HMR\n if (isDevEnvironment()) {\n const globalWindow = window as typeof window & { __heliumGlobalRoutes?: RouteEntry[] };\n globalWindow.__heliumGlobalRoutes = result.routes;\n // Update the module-level reference as well\n globalRoutes.length = 0;\n globalRoutes.push(...result.routes);\n } else {\n globalRoutes = result.routes;\n }\n return result;\n }, []);\n\n // Use useSyncExternalStore to subscribe to location changes\n // This ensures synchronous updates when location changes\n const state = useSyncExternalStore(subscribeToLocation, getLocationSnapshot, getServerSnapshot);\n const targetPath = `${state.path}${state.search ?? (typeof window !== \"undefined\" ? window.location.search : \"\")}`;\n const [runtimeSSRProps, setRuntimeSSRProps] = React.useState<{ path: string; props: Record<string, unknown> }>(() => {\n const payload = getInitialSSRBootstrap();\n if (!payload) {\n return { path: targetPath, props: {} };\n }\n\n const bootstrapPath = `${payload.path}${payload.search ?? window.location.search}`;\n return { path: bootstrapPath, props: payload.props };\n });\n const hydrationDoneRef = React.useRef(false);\n\n const match = useMemo(() => matchRoute(state.path, routes), [state.path, routes]);\n // Use matched params, or fall back to re-extracting from path using global routes during HMR\n const currentParams = match?.params ?? (isDevEnvironment() ? extractParamsFromPath(state.path) : {});\n\n // In dev mode, always read fresh searchParams from URL to handle HMR edge cases\n const currentSearchParams = isDevEnvironment() && state !== hydrationSnapshot ? new URLSearchParams(window.location.search) : state.searchParams;\n\n const routerValue: RouterContext = {\n path: state.path,\n params: currentParams,\n searchParams: currentSearchParams,\n push: (href, options) => {\n // Wrap navigation in startTransition for smoother updates\n startTransition(() => {\n navigate(href, { scrollToTop: options?.scrollToTop });\n });\n },\n replace: (href, options) => {\n startTransition(() => {\n navigate(href, { replace: true, scrollToTop: options?.scrollToTop });\n });\n },\n on: (event, listener) => routerEventEmitter.on(event, listener),\n status: match ? 200 : 404,\n isNavigating: state.isNavigating,\n isPending,\n };\n\n React.useEffect(() => {\n // On first client render, keep the matching SSR payload. A ref avoids\n // restarting this effect and remounting content just to mark hydration.\n if (!hydrationDoneRef.current) {\n hydrationDoneRef.current = true;\n const bootstrap = getInitialSSRBootstrap();\n if (bootstrap && `${bootstrap.path}${bootstrap.search ?? window.location.search}` === targetPath) {\n return;\n }\n }\n\n let cancelled = false;\n\n const load = async () => {\n const ssrPayload = await fetchSSRPageProps(targetPath);\n if (cancelled) {\n return;\n }\n\n if (ssrPayload.kind === \"redirect\") {\n const destination = ssrPayload.redirect.destination;\n\n if (isExternalUrl(destination)) {\n window.location.assign(destination);\n return;\n }\n\n navigate(destination, {\n replace: ssrPayload.redirect.replace ?? true,\n scrollToTop: true,\n });\n return;\n }\n\n if (ssrPayload.kind === \"props\") {\n setRuntimeSSRProps({ path: targetPath, props: ssrPayload.props });\n return;\n }\n\n setRuntimeSSRProps({ path: targetPath, props: {} });\n };\n\n void load();\n\n return () => {\n cancelled = true;\n };\n }, [targetPath]);\n\n React.useEffect(() => {\n const controller = new AbortController();\n const targetPath = `${state.path}${window.location.search || \"\"}`;\n\n const syncMetadata = async () => {\n try {\n if (controller.signal.aborted) {\n return;\n }\n\n const result = await rpcCall<ClientSocialMeta | null, { path: string }>(SEO_METADATA_RPC_METHOD, { path: targetPath });\n\n if (controller.signal.aborted) {\n return;\n }\n\n applyRouteMetadata(result.data ?? null);\n } catch (error) {\n if ((error as { name?: string })?.name === \"AbortError\") {\n return;\n }\n }\n };\n\n syncMetadata();\n\n return () => controller.abort();\n }, [state.path, currentSearchParams.toString()]);\n\n if (!match) {\n const NotFoundComp = NotFound ?? (() => <div>Not found</div>);\n const content = <NotFoundComp />;\n\n return <RouterContext.Provider value={routerValue}>{AppShell ? <AppShell Component={NotFoundComp} pageProps={{}} /> : content}</RouterContext.Provider>;\n }\n\n const pageProps = {\n ...(runtimeSSRProps.path === targetPath ? runtimeSSRProps.props : {}),\n params: match.params,\n searchParams: currentSearchParams,\n };\n\n const finalContent = AppShell ? (\n <AppShell Component={RoutedPage} pageProps={pageProps}>\n <RoutedPage {...pageProps} />\n </AppShell>\n ) : (\n <RoutedPage {...pageProps} />\n );\n\n return (\n <RouterContext.Provider value={routerValue}>\n <PageRouteContext.Provider value={match.route}>{finalContent}</PageRouteContext.Provider>\n </RouterContext.Provider>\n );\n}\n\ntype ClientSocialMeta = {\n title: string;\n description?: string;\n image?: string;\n canonicalUrl?: string;\n siteName?: string;\n type?: string;\n robots?: string;\n twitterCard?: \"summary\" | \"summary_large_image\" | \"app\" | \"player\";\n twitterSite?: string;\n twitterCreator?: string;\n};\n\nfunction applyRouteMetadata(meta: ClientSocialMeta | null) {\n if (typeof document === \"undefined\") {\n return;\n }\n\n removeExistingSeoTags();\n\n if (!meta) {\n return;\n }\n\n document.title = meta.title;\n\n const entries: Array<{ tag: \"meta\" | \"link\"; attrs: Record<string, string> }> = [];\n\n entries.push({ tag: \"meta\", attrs: { property: \"og:title\", content: meta.title } });\n entries.push({ tag: \"meta\", attrs: { property: \"og:type\", content: meta.type ?? \"website\" } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:card\", content: meta.twitterCard ?? \"summary_large_image\" } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:title\", content: meta.title } });\n\n if (meta.description) {\n entries.push({ tag: \"meta\", attrs: { name: \"description\", content: meta.description } });\n entries.push({ tag: \"meta\", attrs: { property: \"og:description\", content: meta.description } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:description\", content: meta.description } });\n }\n\n if (meta.image) {\n entries.push({ tag: \"meta\", attrs: { property: \"og:image\", content: meta.image } });\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:image\", content: meta.image } });\n }\n\n if (meta.canonicalUrl) {\n entries.push({ tag: \"meta\", attrs: { property: \"og:url\", content: meta.canonicalUrl } });\n entries.push({ tag: \"link\", attrs: { rel: \"canonical\", href: meta.canonicalUrl } });\n }\n\n if (meta.siteName) {\n entries.push({ tag: \"meta\", attrs: { property: \"og:site_name\", content: meta.siteName } });\n }\n\n if (meta.robots) {\n entries.push({ tag: \"meta\", attrs: { name: \"robots\", content: meta.robots } });\n }\n\n if (meta.twitterSite) {\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:site\", content: meta.twitterSite } });\n }\n\n if (meta.twitterCreator) {\n entries.push({ tag: \"meta\", attrs: { name: \"twitter:creator\", content: meta.twitterCreator } });\n }\n\n for (const entry of entries) {\n const node = document.createElement(entry.tag);\n for (const [key, value] of Object.entries(entry.attrs)) {\n node.setAttribute(key, value);\n }\n node.setAttribute(\"data-helium-seo\", \"true\");\n document.head.appendChild(node);\n }\n}\n\nfunction removeExistingSeoTags() {\n const headNodes = Array.from(document.head.querySelectorAll(\"meta, link\"));\n\n for (const node of headNodes) {\n if (node.getAttribute(\"data-helium-seo\") === \"true\") {\n node.remove();\n continue;\n }\n\n if (node.tagName.toLowerCase() === \"link\") {\n const rel = (node.getAttribute(\"rel\") || \"\").toLowerCase();\n if (rel === \"canonical\") {\n node.remove();\n }\n continue;\n }\n\n const name = (node.getAttribute(\"name\") || \"\").toLowerCase();\n const property = (node.getAttribute(\"property\") || \"\").toLowerCase();\n\n if (name === \"description\" || name === \"robots\" || name.startsWith(\"twitter:\")) {\n node.remove();\n continue;\n }\n\n if (property.startsWith(\"og:\")) {\n node.remove();\n }\n }\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpcDecoder.d.ts","sourceRoot":"","sources":["../../src/server/rpcDecoder.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,qBAAqB,MAAM,CAAC;AAwIzC,sFAAsF;AACtF,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,CAU/D"}
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { decode } from "@msgpack/msgpack";
|
|
2
|
+
export const MAX_RPC_REQUEST_DEPTH = 128;
|
|
3
|
+
/** Validate container obligations before the decoder preallocates their arrays. */
|
|
4
|
+
function validateStructure(bytes) {
|
|
5
|
+
const remainingChildren = new Uint32Array(MAX_RPC_REQUEST_DEPTH);
|
|
6
|
+
let depth = 0;
|
|
7
|
+
let offset = 0;
|
|
8
|
+
let outstandingValues = 1;
|
|
9
|
+
const invalid = () => {
|
|
10
|
+
throw new RangeError("Invalid MessagePack request structure");
|
|
11
|
+
};
|
|
12
|
+
const skip = (size) => {
|
|
13
|
+
if (size > bytes.byteLength - offset) {
|
|
14
|
+
invalid();
|
|
15
|
+
}
|
|
16
|
+
offset += size;
|
|
17
|
+
};
|
|
18
|
+
const length = (size) => {
|
|
19
|
+
skip(size);
|
|
20
|
+
return size === 1 ? bytes[offset - 1] : size === 2 ? bytes.readUInt16BE(offset - 2) : bytes.readUInt32BE(offset - 4);
|
|
21
|
+
};
|
|
22
|
+
while (outstandingValues > 0) {
|
|
23
|
+
if (offset >= bytes.byteLength) {
|
|
24
|
+
invalid();
|
|
25
|
+
}
|
|
26
|
+
while (depth > 0 && remainingChildren[depth - 1] === 0) {
|
|
27
|
+
depth--;
|
|
28
|
+
}
|
|
29
|
+
if (depth > 0) {
|
|
30
|
+
remainingChildren[depth - 1] = remainingChildren[depth - 1] - 1;
|
|
31
|
+
}
|
|
32
|
+
outstandingValues--;
|
|
33
|
+
const tag = bytes[offset++];
|
|
34
|
+
let children = 0;
|
|
35
|
+
let container = false;
|
|
36
|
+
if (tag <= 0x7f || tag >= 0xe0 || tag === 0xc0 || tag === 0xc2 || tag === 0xc3) {
|
|
37
|
+
// Integers, nil, and booleans carry no additional bytes.
|
|
38
|
+
}
|
|
39
|
+
else if (tag <= 0x8f) {
|
|
40
|
+
container = true;
|
|
41
|
+
children = 2 * (tag & 0x0f);
|
|
42
|
+
}
|
|
43
|
+
else if (tag <= 0x9f) {
|
|
44
|
+
container = true;
|
|
45
|
+
children = tag & 0x0f;
|
|
46
|
+
}
|
|
47
|
+
else if (tag <= 0xbf) {
|
|
48
|
+
skip(tag & 0x1f);
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
switch (tag) {
|
|
52
|
+
case 0xc4: // bin8
|
|
53
|
+
case 0xd9: // str8
|
|
54
|
+
skip(length(1));
|
|
55
|
+
break;
|
|
56
|
+
case 0xc5: // bin16
|
|
57
|
+
case 0xda: // str16
|
|
58
|
+
skip(length(2));
|
|
59
|
+
break;
|
|
60
|
+
case 0xc6: // bin32
|
|
61
|
+
case 0xdb: // str32
|
|
62
|
+
skip(length(4));
|
|
63
|
+
break;
|
|
64
|
+
case 0xc7: // ext8 includes its type byte
|
|
65
|
+
skip(length(1) + 1);
|
|
66
|
+
break;
|
|
67
|
+
case 0xc8: // ext16
|
|
68
|
+
skip(length(2) + 1);
|
|
69
|
+
break;
|
|
70
|
+
case 0xc9: // ext32
|
|
71
|
+
skip(length(4) + 1);
|
|
72
|
+
break;
|
|
73
|
+
case 0xcc: // uint8
|
|
74
|
+
case 0xd0: // int8
|
|
75
|
+
skip(1);
|
|
76
|
+
break;
|
|
77
|
+
case 0xcd: // uint16
|
|
78
|
+
case 0xd1: // int16
|
|
79
|
+
skip(2);
|
|
80
|
+
break;
|
|
81
|
+
case 0xca: // float32
|
|
82
|
+
case 0xce: // uint32
|
|
83
|
+
case 0xd2: // int32
|
|
84
|
+
skip(4);
|
|
85
|
+
break;
|
|
86
|
+
case 0xcb: // float64
|
|
87
|
+
case 0xcf: // uint64
|
|
88
|
+
case 0xd3: // int64
|
|
89
|
+
skip(8);
|
|
90
|
+
break;
|
|
91
|
+
case 0xd4: // fixext1, plus type byte
|
|
92
|
+
skip(2);
|
|
93
|
+
break;
|
|
94
|
+
case 0xd5: // fixext2
|
|
95
|
+
skip(3);
|
|
96
|
+
break;
|
|
97
|
+
case 0xd6: // fixext4, including timestamp32
|
|
98
|
+
skip(5);
|
|
99
|
+
break;
|
|
100
|
+
case 0xd7: // fixext8, including timestamp64
|
|
101
|
+
skip(9);
|
|
102
|
+
break;
|
|
103
|
+
case 0xd8: // fixext16
|
|
104
|
+
skip(17);
|
|
105
|
+
break;
|
|
106
|
+
case 0xdc: // array16
|
|
107
|
+
case 0xdd: // array32
|
|
108
|
+
container = true;
|
|
109
|
+
children = length(tag === 0xdc ? 2 : 4);
|
|
110
|
+
break;
|
|
111
|
+
case 0xde: // map16
|
|
112
|
+
case 0xdf: // map32
|
|
113
|
+
container = true;
|
|
114
|
+
children = 2 * length(tag === 0xde ? 2 : 4);
|
|
115
|
+
break;
|
|
116
|
+
default: // 0xc1 is reserved.
|
|
117
|
+
invalid();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
outstandingValues += children;
|
|
121
|
+
// Every outstanding child needs at least one encoded byte. Checking the
|
|
122
|
+
// sum also rejects nested declarations that pass individual size caps.
|
|
123
|
+
if (outstandingValues > bytes.byteLength - offset) {
|
|
124
|
+
invalid();
|
|
125
|
+
}
|
|
126
|
+
if (container) {
|
|
127
|
+
if (depth >= MAX_RPC_REQUEST_DEPTH) {
|
|
128
|
+
invalid();
|
|
129
|
+
}
|
|
130
|
+
if (children > 0) {
|
|
131
|
+
remainingChildren[depth++] = children;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (offset !== bytes.byteLength) {
|
|
136
|
+
invalid();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
/** Reject impossible declared sizes before the MessagePack decoder allocates them. */
|
|
140
|
+
export function decodeRpcRequest(body) {
|
|
141
|
+
const bytes = Buffer.isBuffer(body) ? body : Buffer.from(body);
|
|
142
|
+
validateStructure(bytes);
|
|
143
|
+
return decode(bytes, {
|
|
144
|
+
maxStrLength: bytes.byteLength,
|
|
145
|
+
maxBinLength: bytes.byteLength,
|
|
146
|
+
maxArrayLength: bytes.byteLength,
|
|
147
|
+
maxMapLength: bytes.byteLength,
|
|
148
|
+
maxExtLength: bytes.byteLength,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
//# sourceMappingURL=rpcDecoder.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpcDecoder.js","sourceRoot":"","sources":["../../src/server/rpcDecoder.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,MAAM,CAAC,MAAM,qBAAqB,GAAG,GAAG,CAAC;AAEzC,mFAAmF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,CAAC,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC/D,iBAAiB,CAAC,KAAK,CAAC,CAAC;IACzB,OAAO,MAAM,CAAC,KAAK,EAAE;QACjB,YAAY,EAAE,KAAK,CAAC,UAAU;QAC9B,YAAY,EAAE,KAAK,CAAC,UAAU;QAC9B,cAAc,EAAE,KAAK,CAAC,UAAU;QAChC,YAAY,EAAE,KAAK,CAAC,UAAU;QAC9B,YAAY,EAAE,KAAK,CAAC,UAAU;KACjC,CAAC,CAAC;AACP,CAAC","sourcesContent":["import { decode } from \"@msgpack/msgpack\";\n\nexport const MAX_RPC_REQUEST_DEPTH = 128;\n\n/** Validate container obligations before the decoder preallocates their arrays. */\nfunction validateStructure(bytes: Buffer): void {\n const remainingChildren = new Uint32Array(MAX_RPC_REQUEST_DEPTH);\n let depth = 0;\n let offset = 0;\n let outstandingValues = 1;\n const invalid = () => {\n throw new RangeError(\"Invalid MessagePack request structure\");\n };\n const skip = (size: number) => {\n if (size > bytes.byteLength - offset) {\n invalid();\n }\n offset += size;\n };\n const length = (size: 1 | 2 | 4): number => {\n skip(size);\n return size === 1 ? bytes[offset - 1]! : size === 2 ? bytes.readUInt16BE(offset - 2) : bytes.readUInt32BE(offset - 4);\n };\n\n while (outstandingValues > 0) {\n if (offset >= bytes.byteLength) {\n invalid();\n }\n while (depth > 0 && remainingChildren[depth - 1] === 0) {\n depth--;\n }\n if (depth > 0) {\n remainingChildren[depth - 1] = remainingChildren[depth - 1]! - 1;\n }\n outstandingValues--;\n const tag = bytes[offset++]!;\n let children = 0;\n let container = false;\n if (tag <= 0x7f || tag >= 0xe0 || tag === 0xc0 || tag === 0xc2 || tag === 0xc3) {\n // Integers, nil, and booleans carry no additional bytes.\n } else if (tag <= 0x8f) {\n container = true;\n children = 2 * (tag & 0x0f);\n } else if (tag <= 0x9f) {\n container = true;\n children = tag & 0x0f;\n } else if (tag <= 0xbf) {\n skip(tag & 0x1f);\n } else {\n switch (tag) {\n case 0xc4: // bin8\n case 0xd9: // str8\n skip(length(1));\n break;\n case 0xc5: // bin16\n case 0xda: // str16\n skip(length(2));\n break;\n case 0xc6: // bin32\n case 0xdb: // str32\n skip(length(4));\n break;\n case 0xc7: // ext8 includes its type byte\n skip(length(1) + 1);\n break;\n case 0xc8: // ext16\n skip(length(2) + 1);\n break;\n case 0xc9: // ext32\n skip(length(4) + 1);\n break;\n case 0xcc: // uint8\n case 0xd0: // int8\n skip(1);\n break;\n case 0xcd: // uint16\n case 0xd1: // int16\n skip(2);\n break;\n case 0xca: // float32\n case 0xce: // uint32\n case 0xd2: // int32\n skip(4);\n break;\n case 0xcb: // float64\n case 0xcf: // uint64\n case 0xd3: // int64\n skip(8);\n break;\n case 0xd4: // fixext1, plus type byte\n skip(2);\n break;\n case 0xd5: // fixext2\n skip(3);\n break;\n case 0xd6: // fixext4, including timestamp32\n skip(5);\n break;\n case 0xd7: // fixext8, including timestamp64\n skip(9);\n break;\n case 0xd8: // fixext16\n skip(17);\n break;\n case 0xdc: // array16\n case 0xdd: // array32\n container = true;\n children = length(tag === 0xdc ? 2 : 4);\n break;\n case 0xde: // map16\n case 0xdf: // map32\n container = true;\n children = 2 * length(tag === 0xde ? 2 : 4);\n break;\n default: // 0xc1 is reserved.\n invalid();\n }\n }\n outstandingValues += children;\n // Every outstanding child needs at least one encoded byte. Checking the\n // sum also rejects nested declarations that pass individual size caps.\n if (outstandingValues > bytes.byteLength - offset) {\n invalid();\n }\n if (container) {\n if (depth >= MAX_RPC_REQUEST_DEPTH) {\n invalid();\n }\n if (children > 0) {\n remainingChildren[depth++] = children;\n }\n }\n }\n if (offset !== bytes.byteLength) {\n invalid();\n }\n}\n\n/** Reject impossible declared sizes before the MessagePack decoder allocates them. */\nexport function decodeRpcRequest(body: Buffer | string): unknown {\n const bytes = Buffer.isBuffer(body) ? body : Buffer.from(body);\n validateStructure(bytes);\n return decode(bytes, {\n maxStrLength: bytes.byteLength,\n maxBinLength: bytes.byteLength,\n maxArrayLength: bytes.byteLength,\n maxMapLength: bytes.byteLength,\n maxExtLength: bytes.byteLength,\n });\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpcRegistry.d.ts","sourceRoot":"","sources":["../../src/server/rpcRegistry.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"rpcRegistry.d.ts","sourceRoot":"","sources":["../../src/server/rpcRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAE7B,OAAO,KAAK,EAAc,WAAW,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAGhF,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACzD,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AACxD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAIpD,MAAM,WAAW,aAAa;IAC1B,QAAQ,EAAE,WAAW,GAAG,WAAW,EAAE,CAAC;CACzC;AAED,qBAAa,WAAY,SAAQ,KAAK;IAClC,SAAgB,MAAM,QAAQ;CACjC;AAED,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,aAAa,CAAC,OAAO,CAAC,CAE/E;AAED,iFAAiF;AACjF,wBAAgB,SAAS,CAAC,CAAC,EAAE,KAAK,EAAE,WAAW,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAwBvF;AAED,qBAAa,WAAW;IACpB,OAAO,CAAC,OAAO,CAAgD;IAC/D,OAAO,CAAC,UAAU,CAAiC;IACnD,OAAO,CAAC,WAAW,CAA4B;IAC/C,OAAO,CAAC,YAAY,CAAM;IAE1B,QAAQ,CAAC,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,eAAe,CAAC,GAAG,EAAE,GAAG,CAAC;IAInD,aAAa,CAAC,UAAU,EAAE,gBAAgB;IAG1C,cAAc,CAAC,WAAW,EAAE,WAAW;IAGvC,eAAe,CAAC,IAAI,EAAE,MAAM;IAG5B,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,QAAQ;YAIhB,MAAM;IA+EpB,OAAO,CAAC,cAAc;IAMhB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,MAAM,GAAE,WAA0C,GAAG,OAAO,CAAC,aAAa,CAAC;IA6C3J,mBAAmB,CACrB,IAAI,EAAE,MAAM,EACZ,EAAE,EAAE,MAAM,EACV,GAAG,EAAE,IAAI,CAAC,eAAe,EACzB,MAAM,EAAE,WAAW,EACnB,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,GAChE,OAAO,CAAC,QAAQ,CAAC;CA2CvB;AAsBD,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAI3D"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { decode as msgpackDecode } from "@msgpack/msgpack";
|
|
2
1
|
import { log } from "../utils/logger.js";
|
|
3
2
|
import { trackRequestCleanup } from "./requestSignal.js";
|
|
3
|
+
import { decodeRpcRequest } from "./rpcDecoder.js";
|
|
4
4
|
export class PublicError extends Error {
|
|
5
5
|
constructor() {
|
|
6
6
|
super(...arguments);
|
|
@@ -140,7 +140,7 @@ export class RpcRegistry {
|
|
|
140
140
|
async handleHttpRequest(body, ip, req, signal = new AbortController().signal) {
|
|
141
141
|
let value;
|
|
142
142
|
try {
|
|
143
|
-
value =
|
|
143
|
+
value = decodeRpcRequest(body);
|
|
144
144
|
}
|
|
145
145
|
catch {
|
|
146
146
|
return { response: { id: "unknown", ok: false, stats: this.getStats(ip), error: "Invalid request format" } };
|
|
@@ -187,7 +187,7 @@ export class RpcRegistry {
|
|
|
187
187
|
async handleStreamRequest(body, ip, req, signal, onChunk) {
|
|
188
188
|
let request;
|
|
189
189
|
try {
|
|
190
|
-
request =
|
|
190
|
+
request = decodeRpcRequest(body);
|
|
191
191
|
}
|
|
192
192
|
catch {
|
|
193
193
|
throw new PublicError("Invalid request format");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rpcRegistry.js","sourceRoot":"","sources":["../../src/server/rpcRegistry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAI3D,OAAO,EAAE,GAAG,EAAE,MAAM,oBAAoB,CAAC;AAKzC,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAMzD,MAAM,OAAO,WAAY,SAAQ,KAAK;IAAtC;;QACoB,WAAM,GAAG,IAAI,CAAC;IAClC,CAAC;CAAA;AAED,MAAM,UAAU,eAAe,CAAC,KAAc;IAC1C,OAAO,KAAK,KAAK,IAAI,IAAI,CAAC,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,UAAU,CAAC,IAAI,OAAQ,KAAgC,CAAC,MAAM,CAAC,aAAa,CAAC,KAAK,UAAU,CAAC;AACzK,CAAC;AAED,iFAAiF;AACjF,MAAM,UAAU,SAAS,CAAI,KAAyB,EAAE,MAAmB;IACvE,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACvC,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;QACjB,KAAK,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;QAC7B,OAAO,OAAO,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,IAAI,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;IACzE,CAAC;IACD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACnC,MAAM,OAAO,GAAG,GAAG,EAAE;YACjB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rB,CAAC;AAED,SAAS,YAAY,CAAC,KAAc;IAChC,OAAO,CACH,KAAK,KAAK,IAAI;QACd,OAAO,KAAK,KAAK,QAAQ;QACzB,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QACrB,IAAI,IAAI,KAAK;QACb,CAAC,OAAO,KAAK,CAAC,EAAE,KAAK,QAAQ,IAAI,CAAC,OAAO,KAAK,CAAC,EAAE,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;QAC7F,QAAQ,IAAI,KAAK;QACjB,OAAO,KAAK,CAAC,MAAM,KAAK,QAAQ;QAChC,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAC1B,CAAC;AACN,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,KAAc;IAC/C,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,SAAS,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IAC9K,MAAM,QAAQ,GAAG,KAAK,YAAY,WAAW,IAAI,CAAC,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IAC7I,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,IAAI,cAAc,CAAC;AAC3G,CAAC","sourcesContent":["import { decode as msgpackDecode } from \"@msgpack/msgpack\";\nimport type http from \"http\";\n\nimport type { RpcRequest, RpcResponse, RpcStats } from \"../runtime/protocol.js\";\nimport { log } from \"../utils/logger.js\";\nimport type { HeliumContext } from \"./context.js\";\nimport type { HeliumMethodDef } from \"./defineMethod.js\";\nimport type { HeliumMiddleware } from \"./middleware.js\";\nimport type { RateLimiter } from \"./rateLimiter.js\";\nimport { trackRequestCleanup } from \"./requestSignal.js\";\n\nexport interface HttpRpcResult {\n response: RpcResponse | RpcResponse[];\n}\n\nexport class PublicError extends Error {\n public readonly public = true;\n}\n\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return value !== null && (typeof value === \"object\" || typeof value === \"function\") && typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\";\n}\n\n/** Reject promptly on disconnect even when provider work has not settled yet. */\nexport function abortable<T>(value: PromiseLike<T> | T, signal: AbortSignal): Promise<T> {\n const promise = Promise.resolve(value);\n if (signal.aborted) {\n void promise.catch(() => {});\n return Promise.reject(signal.reason ?? new Error(\"Request aborted\"));\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n cleanup();\n reject(signal.reason ?? new Error(\"Request aborted\"));\n };\n const cleanup = () => signal.removeEventListener(\"abort\", onAbort);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (result) => {\n cleanup();\n resolve(result);\n },\n (error) => {\n cleanup();\n reject(error);\n }\n );\n });\n}\n\nexport class RpcRegistry {\n private methods = new Map<string, HeliumMethodDef<any, any>>();\n private middleware: HeliumMiddleware | null = null;\n private rateLimiter: RateLimiter | null = null;\n private maxBatchSize = 20;\n\n register(id: string, def: HeliumMethodDef<any, any>) {\n def.__id = id;\n this.methods.set(id, def);\n }\n setMiddleware(middleware: HeliumMiddleware) {\n this.middleware = middleware;\n }\n setRateLimiter(rateLimiter: RateLimiter) {\n this.rateLimiter = rateLimiter;\n }\n setMaxBatchSize(size: number) {\n this.maxBatchSize = size;\n }\n getStats(ip: string): RpcStats {\n return this.rateLimiter?.getHttpStats(ip) ?? { remainingRequests: Infinity, resetInSeconds: 0 };\n }\n\n private async invoke(\n request: RpcRequest,\n ip: string,\n req: http.IncomingMessage,\n signal: AbortSignal,\n consume: (result: unknown, signal: AbortSignal) => Promise<void>\n ): Promise<void> {\n signal.throwIfAborted();\n const def = this.methods.get(request.method);\n if (!def) {\n throw new PublicError(`Unknown method ${request.method}`);\n }\n // A method can also stop when middleware fails while next() is running.\n // Keep the response signal alive long enough to deliver a terminal error.\n const controller = new AbortController();\n const abort = () => controller.abort(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) {\n abort();\n }\n const activeSignal = controller.signal;\n const ctx: HeliumContext = { signal: activeSignal, req: { ip, headers: req.headers, url: req.url, method: req.method, raw: req } };\n let called = false;\n let work: Promise<void> | undefined;\n const next = (): Promise<void> => {\n if (called) {\n const error = new PublicError(\"Middleware next() may only be called once\");\n controller.abort(error);\n const rejected = Promise.reject(error);\n void rejected.catch(() => {});\n return rejected;\n }\n called = true;\n work = (async () => {\n activeSignal.throwIfAborted();\n const pending = Promise.resolve(def.handler(request.args, ctx));\n let result: unknown;\n try {\n result = await abortable(pending, activeSignal);\n } catch (error) {\n if (activeSignal.aborted) {\n void pending\n .then(async (late) => {\n if (isAsyncIterable(late)) {\n await trackRequestCleanup(req, late[Symbol.asyncIterator]().return?.());\n }\n })\n .catch(() => {});\n }\n throw error;\n }\n await consume(result, activeSignal);\n })();\n // Middleware may call next() without returning/awaiting it. Observe\n // failures immediately, and still await the original work below.\n void work.catch(() => {});\n return work;\n };\n try {\n activeSignal.throwIfAborted();\n if (this.middleware) {\n await abortable(this.middleware.handler({ ctx, type: \"method\", methodName: request.method }, next), activeSignal);\n if (!called) {\n throw new PublicError(\"Request blocked by middleware\");\n }\n } else {\n next();\n }\n if (work) {\n await abortable(work, activeSignal);\n }\n } catch (error) {\n controller.abort(error);\n throw error;\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n }\n\n private checkRateLimit(ip: string): void {\n if (this.rateLimiter && !this.rateLimiter.checkHttpRateLimit(ip)) {\n throw new PublicError(\"Rate limit exceeded\");\n }\n }\n\n async handleHttpRequest(body: Buffer | string, ip: string, req: http.IncomingMessage, signal: AbortSignal = new AbortController().signal): Promise<HttpRpcResult> {\n let value: unknown;\n try {\n value = msgpackDecode(Buffer.isBuffer(body) ? body : Buffer.from(body));\n } catch {\n return { response: { id: \"unknown\", ok: false, stats: this.getStats(ip), error: \"Invalid request format\" } };\n }\n const errorResponse = (input: unknown, error: string): RpcResponse => ({ id: requestId(input), ok: false, stats: this.getStats(ip), error });\n try {\n this.checkRateLimit(ip);\n } catch (error) {\n return {\n response: Array.isArray(value)\n ? value.slice(0, this.maxBatchSize).map((item) => errorResponse(item, sanitizeErrorMessage(error)))\n : errorResponse(value, sanitizeErrorMessage(error)),\n };\n }\n if (Array.isArray(value) && value.length > this.maxBatchSize) {\n return { response: { id: \"batch\", ok: false, stats: this.getStats(ip), error: `Batch size ${value.length} exceeds maximum of ${this.maxBatchSize}` } };\n }\n const process = async (input: unknown): Promise<RpcResponse> => {\n if (!isRpcRequest(input)) {\n return errorResponse(input, \"Invalid request format\");\n }\n try {\n let result: unknown;\n await this.invoke(input, ip, req, signal, async (value) => {\n if (isAsyncIterable(value)) {\n const iterator = value[Symbol.asyncIterator]();\n void trackRequestCleanup(req, iterator.return?.()).catch(() => {});\n throw new PublicError(\"This method returns a stream. Use useStreaming() instead of a unary RPC call.\");\n }\n result = value;\n });\n return { id: input.id, ok: true, stats: this.getStats(ip), result };\n } catch (error) {\n if (!signal.aborted) {\n log(\"error\", `RPC method '${input.method}' failed:`, error);\n }\n return errorResponse(input, sanitizeErrorMessage(error));\n }\n };\n return { response: Array.isArray(value) ? await Promise.all(value.map(process)) : await process(value) };\n }\n\n async handleStreamRequest(\n body: Buffer,\n ip: string,\n req: http.IncomingMessage,\n signal: AbortSignal,\n onChunk: (value: unknown, signal: AbortSignal) => Promise<void>\n ): Promise<RpcStats> {\n let request: unknown;\n try {\n request = msgpackDecode(body);\n } catch {\n throw new PublicError(\"Invalid request format\");\n }\n if (Array.isArray(request)) {\n throw new PublicError(\"Streaming RPC accepts one call, not a batch\");\n }\n if (!isRpcRequest(request)) {\n throw new PublicError(\"Invalid request format\");\n }\n this.checkRateLimit(ip);\n await this.invoke(request, ip, req, signal, async (result, iterationSignal) => {\n if (!isAsyncIterable(result)) {\n throw new PublicError(\"Streaming RPC requires a method returning an AsyncIterable. Use callMethod() for unary methods.\");\n }\n const iterator = result[Symbol.asyncIterator]();\n let completed = false;\n try {\n while (!iterationSignal.aborted) {\n const item = await abortable(iterator.next(), iterationSignal);\n if (item.done) {\n completed = true;\n break;\n }\n iterationSignal.throwIfAborted();\n await abortable(onChunk(item.value, iterationSignal), iterationSignal);\n }\n } finally {\n if (!completed && iterator.return) {\n const cleanup = trackRequestCleanup(req, iterator.return());\n if (iterationSignal.aborted) {\n void cleanup.catch(() => {});\n } else {\n await abortable(cleanup, iterationSignal);\n }\n }\n }\n });\n return this.getStats(ip);\n }\n}\n\nfunction requestId(value: unknown): string | number {\n if (value && typeof value === \"object\" && \"id\" in value && (typeof value.id === \"string\" || (typeof value.id === \"number\" && Number.isFinite(value.id)))) {\n return value.id;\n }\n return \"unknown\";\n}\n\nfunction isRpcRequest(value: unknown): value is RpcRequest {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n \"id\" in value &&\n (typeof value.id === \"string\" || (typeof value.id === \"number\" && Number.isFinite(value.id))) &&\n \"method\" in value &&\n typeof value.method === \"string\" &&\n value.method.length > 0\n );\n}\n\nexport function sanitizeErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : error && typeof error === \"object\" && \"message\" in error && typeof error.message === \"string\" ? error.message : null;\n const isPublic = error instanceof PublicError || (error !== null && typeof error === \"object\" && \"public\" in error && error.public === true);\n return process.env.NODE_ENV === \"production\" && !isPublic ? \"Server error\" : message || \"Server error\";\n}\n"]}
|
|
1
|
+
{"version":3,"file":"rpcRegistry.js","sourceRoot":"","sources":["../../src/server/rpcRegistry.ts"],"names":[],"mappings":"AAG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K,QAAQ;QAChC,KAAK,CAAC,MAAM,CAAC,MAAM,GAAG,CAAC,CAC1B,CAAC;AACN,CAAC;AAED,MAAM,UAAU,oBAAoB,CAAC,KAAc;IAC/C,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,SAAS,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,CAAC;IAC9K,MAAM,QAAQ,GAAG,KAAK,YAAY,WAAW,IAAI,CAAC,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,QAAQ,IAAI,KAAK,IAAI,KAAK,CAAC,MAAM,KAAK,IAAI,CAAC,CAAC;IAC7I,OAAO,OAAO,CAAC,GAAG,CAAC,QAAQ,KAAK,YAAY,IAAI,CAAC,QAAQ,CAAC,CAAC,CAAC,cAAc,CAAC,CAAC,CAAC,OAAO,IAAI,cAAc,CAAC;AAC3G,CAAC","sourcesContent":["import type http from \"http\";\n\nimport type { RpcRequest, RpcResponse, RpcStats } from \"../runtime/protocol.js\";\nimport { log } from \"../utils/logger.js\";\nimport type { HeliumContext } from \"./context.js\";\nimport type { HeliumMethodDef } from \"./defineMethod.js\";\nimport type { HeliumMiddleware } from \"./middleware.js\";\nimport type { RateLimiter } from \"./rateLimiter.js\";\nimport { trackRequestCleanup } from \"./requestSignal.js\";\nimport { decodeRpcRequest } from \"./rpcDecoder.js\";\n\nexport interface HttpRpcResult {\n response: RpcResponse | RpcResponse[];\n}\n\nexport class PublicError extends Error {\n public readonly public = true;\n}\n\nexport function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return value !== null && (typeof value === \"object\" || typeof value === \"function\") && typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === \"function\";\n}\n\n/** Reject promptly on disconnect even when provider work has not settled yet. */\nexport function abortable<T>(value: PromiseLike<T> | T, signal: AbortSignal): Promise<T> {\n const promise = Promise.resolve(value);\n if (signal.aborted) {\n void promise.catch(() => {});\n return Promise.reject(signal.reason ?? new Error(\"Request aborted\"));\n }\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n cleanup();\n reject(signal.reason ?? new Error(\"Request aborted\"));\n };\n const cleanup = () => signal.removeEventListener(\"abort\", onAbort);\n signal.addEventListener(\"abort\", onAbort, { once: true });\n promise.then(\n (result) => {\n cleanup();\n resolve(result);\n },\n (error) => {\n cleanup();\n reject(error);\n }\n );\n });\n}\n\nexport class RpcRegistry {\n private methods = new Map<string, HeliumMethodDef<any, any>>();\n private middleware: HeliumMiddleware | null = null;\n private rateLimiter: RateLimiter | null = null;\n private maxBatchSize = 20;\n\n register(id: string, def: HeliumMethodDef<any, any>) {\n def.__id = id;\n this.methods.set(id, def);\n }\n setMiddleware(middleware: HeliumMiddleware) {\n this.middleware = middleware;\n }\n setRateLimiter(rateLimiter: RateLimiter) {\n this.rateLimiter = rateLimiter;\n }\n setMaxBatchSize(size: number) {\n this.maxBatchSize = size;\n }\n getStats(ip: string): RpcStats {\n return this.rateLimiter?.getHttpStats(ip) ?? { remainingRequests: Infinity, resetInSeconds: 0 };\n }\n\n private async invoke(\n request: RpcRequest,\n ip: string,\n req: http.IncomingMessage,\n signal: AbortSignal,\n consume: (result: unknown, signal: AbortSignal) => Promise<void>\n ): Promise<void> {\n signal.throwIfAborted();\n const def = this.methods.get(request.method);\n if (!def) {\n throw new PublicError(`Unknown method ${request.method}`);\n }\n // A method can also stop when middleware fails while next() is running.\n // Keep the response signal alive long enough to deliver a terminal error.\n const controller = new AbortController();\n const abort = () => controller.abort(signal.reason);\n signal.addEventListener(\"abort\", abort, { once: true });\n if (signal.aborted) {\n abort();\n }\n const activeSignal = controller.signal;\n const ctx: HeliumContext = { signal: activeSignal, req: { ip, headers: req.headers, url: req.url, method: req.method, raw: req } };\n let called = false;\n let work: Promise<void> | undefined;\n const next = (): Promise<void> => {\n if (called) {\n const error = new PublicError(\"Middleware next() may only be called once\");\n controller.abort(error);\n const rejected = Promise.reject(error);\n void rejected.catch(() => {});\n return rejected;\n }\n called = true;\n work = (async () => {\n activeSignal.throwIfAborted();\n const pending = Promise.resolve(def.handler(request.args, ctx));\n let result: unknown;\n try {\n result = await abortable(pending, activeSignal);\n } catch (error) {\n if (activeSignal.aborted) {\n void pending\n .then(async (late) => {\n if (isAsyncIterable(late)) {\n await trackRequestCleanup(req, late[Symbol.asyncIterator]().return?.());\n }\n })\n .catch(() => {});\n }\n throw error;\n }\n await consume(result, activeSignal);\n })();\n // Middleware may call next() without returning/awaiting it. Observe\n // failures immediately, and still await the original work below.\n void work.catch(() => {});\n return work;\n };\n try {\n activeSignal.throwIfAborted();\n if (this.middleware) {\n await abortable(this.middleware.handler({ ctx, type: \"method\", methodName: request.method }, next), activeSignal);\n if (!called) {\n throw new PublicError(\"Request blocked by middleware\");\n }\n } else {\n next();\n }\n if (work) {\n await abortable(work, activeSignal);\n }\n } catch (error) {\n controller.abort(error);\n throw error;\n } finally {\n signal.removeEventListener(\"abort\", abort);\n }\n }\n\n private checkRateLimit(ip: string): void {\n if (this.rateLimiter && !this.rateLimiter.checkHttpRateLimit(ip)) {\n throw new PublicError(\"Rate limit exceeded\");\n }\n }\n\n async handleHttpRequest(body: Buffer | string, ip: string, req: http.IncomingMessage, signal: AbortSignal = new AbortController().signal): Promise<HttpRpcResult> {\n let value: unknown;\n try {\n value = decodeRpcRequest(body);\n } catch {\n return { response: { id: \"unknown\", ok: false, stats: this.getStats(ip), error: \"Invalid request format\" } };\n }\n const errorResponse = (input: unknown, error: string): RpcResponse => ({ id: requestId(input), ok: false, stats: this.getStats(ip), error });\n try {\n this.checkRateLimit(ip);\n } catch (error) {\n return {\n response: Array.isArray(value)\n ? value.slice(0, this.maxBatchSize).map((item) => errorResponse(item, sanitizeErrorMessage(error)))\n : errorResponse(value, sanitizeErrorMessage(error)),\n };\n }\n if (Array.isArray(value) && value.length > this.maxBatchSize) {\n return { response: { id: \"batch\", ok: false, stats: this.getStats(ip), error: `Batch size ${value.length} exceeds maximum of ${this.maxBatchSize}` } };\n }\n const process = async (input: unknown): Promise<RpcResponse> => {\n if (!isRpcRequest(input)) {\n return errorResponse(input, \"Invalid request format\");\n }\n try {\n let result: unknown;\n await this.invoke(input, ip, req, signal, async (value) => {\n if (isAsyncIterable(value)) {\n const iterator = value[Symbol.asyncIterator]();\n void trackRequestCleanup(req, iterator.return?.()).catch(() => {});\n throw new PublicError(\"This method returns a stream. Use useStreaming() instead of a unary RPC call.\");\n }\n result = value;\n });\n return { id: input.id, ok: true, stats: this.getStats(ip), result };\n } catch (error) {\n if (!signal.aborted) {\n log(\"error\", `RPC method '${input.method}' failed:`, error);\n }\n return errorResponse(input, sanitizeErrorMessage(error));\n }\n };\n return { response: Array.isArray(value) ? await Promise.all(value.map(process)) : await process(value) };\n }\n\n async handleStreamRequest(\n body: Buffer,\n ip: string,\n req: http.IncomingMessage,\n signal: AbortSignal,\n onChunk: (value: unknown, signal: AbortSignal) => Promise<void>\n ): Promise<RpcStats> {\n let request: unknown;\n try {\n request = decodeRpcRequest(body);\n } catch {\n throw new PublicError(\"Invalid request format\");\n }\n if (Array.isArray(request)) {\n throw new PublicError(\"Streaming RPC accepts one call, not a batch\");\n }\n if (!isRpcRequest(request)) {\n throw new PublicError(\"Invalid request format\");\n }\n this.checkRateLimit(ip);\n await this.invoke(request, ip, req, signal, async (result, iterationSignal) => {\n if (!isAsyncIterable(result)) {\n throw new PublicError(\"Streaming RPC requires a method returning an AsyncIterable. Use callMethod() for unary methods.\");\n }\n const iterator = result[Symbol.asyncIterator]();\n let completed = false;\n try {\n while (!iterationSignal.aborted) {\n const item = await abortable(iterator.next(), iterationSignal);\n if (item.done) {\n completed = true;\n break;\n }\n iterationSignal.throwIfAborted();\n await abortable(onChunk(item.value, iterationSignal), iterationSignal);\n }\n } finally {\n if (!completed && iterator.return) {\n const cleanup = trackRequestCleanup(req, iterator.return());\n if (iterationSignal.aborted) {\n void cleanup.catch(() => {});\n } else {\n await abortable(cleanup, iterationSignal);\n }\n }\n }\n });\n return this.getStats(ip);\n }\n}\n\nfunction requestId(value: unknown): string | number {\n if (value && typeof value === \"object\" && \"id\" in value && (typeof value.id === \"string\" || (typeof value.id === \"number\" && Number.isFinite(value.id)))) {\n return value.id;\n }\n return \"unknown\";\n}\n\nfunction isRpcRequest(value: unknown): value is RpcRequest {\n return (\n value !== null &&\n typeof value === \"object\" &&\n !Array.isArray(value) &&\n \"id\" in value &&\n (typeof value.id === \"string\" || (typeof value.id === \"number\" && Number.isFinite(value.id))) &&\n \"method\" in value &&\n typeof value.method === \"string\" &&\n value.method.length > 0\n );\n}\n\nexport function sanitizeErrorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : error && typeof error === \"object\" && \"message\" in error && typeof error.message === \"string\" ? error.message : null;\n const isPublic = error instanceof PublicError || (error !== null && typeof error === \"object\" && \"public\" in error && error.public === true);\n return process.env.NODE_ENV === \"production\" && !isPublic ? \"Server error\" : message || \"Server error\";\n}\n"]}
|