@danylohotvianskyi/bobra-framework 0.1.8 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/batteries/auth/hash.ts +102 -36
- package/batteries/auth/token-metadata.ts +25 -8
- package/batteries/auth/token.ts +5 -5
- package/batteries/openapi/index.ts +62 -41
- package/batteries/openapi/merge-openapi.ts +125 -33
- package/core/config.ts +40 -14
- package/core/discovery.ts +16 -10
- package/core/env-resolver.ts +25 -11
- package/core/factory.ts +150 -77
- package/core/spa.ts +14 -8
- package/db/client.ts +85 -245
- package/db/drizzle-clients.ts +65 -0
- package/db/failover.ts +300 -0
- package/db/index.ts +1 -0
- package/db/migrate.ts +7 -6
- package/db/pgedge.ts +307 -0
- package/db/test/client.test.ts +297 -0
- package/db/token-auth.ts +40 -0
- package/db/types.ts +96 -0
- package/dist/batteries/auth/hash.d.ts +10 -2
- package/dist/batteries/auth/hash.js +78 -43
- package/dist/batteries/auth/hash.js.map +1 -1
- package/dist/batteries/auth/token-metadata.d.ts +3 -3
- package/dist/batteries/auth/token-metadata.js +14 -6
- package/dist/batteries/auth/token-metadata.js.map +1 -1
- package/dist/batteries/auth/token.d.ts +3 -3
- package/dist/batteries/auth/token.js +2 -2
- package/dist/batteries/auth/token.js.map +1 -1
- package/dist/batteries/openapi/index.d.ts +51 -13
- package/dist/batteries/openapi/index.js +25 -15
- package/dist/batteries/openapi/index.js.map +1 -1
- package/dist/batteries/openapi/merge-openapi.d.ts +26 -2
- package/dist/batteries/openapi/merge-openapi.js +83 -26
- package/dist/batteries/openapi/merge-openapi.js.map +1 -1
- package/dist/core/config.d.ts +26 -9
- package/dist/core/config.js +8 -7
- package/dist/core/config.js.map +1 -1
- package/dist/core/discovery.d.ts +18 -9
- package/dist/core/discovery.js +1 -1
- package/dist/core/discovery.js.map +1 -1
- package/dist/core/env-resolver.d.ts +7 -4
- package/dist/core/env-resolver.js +7 -5
- package/dist/core/env-resolver.js.map +1 -1
- package/dist/core/factory.d.ts +36 -16
- package/dist/core/factory.js +70 -38
- package/dist/core/factory.js.map +1 -1
- package/dist/core/spa.js +9 -4
- package/dist/core/spa.js.map +1 -1
- package/dist/db/client.d.ts +16 -59
- package/dist/db/client.js +47 -171
- package/dist/db/client.js.map +1 -1
- package/dist/db/drizzle-clients.d.ts +6 -0
- package/dist/db/drizzle-clients.js +42 -0
- package/dist/db/drizzle-clients.js.map +1 -0
- package/dist/db/failover.d.ts +39 -0
- package/dist/db/failover.js +251 -0
- package/dist/db/failover.js.map +1 -0
- package/dist/db/index.d.ts +1 -0
- package/dist/db/index.js +1 -0
- package/dist/db/index.js.map +1 -1
- package/dist/db/migrate.js +4 -4
- package/dist/db/migrate.js.map +1 -1
- package/dist/db/pgedge.d.ts +14 -0
- package/dist/db/pgedge.js +218 -0
- package/dist/db/pgedge.js.map +1 -0
- package/dist/db/token-auth.d.ts +34 -0
- package/dist/db/token-auth.js +15 -0
- package/dist/db/token-auth.js.map +1 -0
- package/dist/db/types.d.ts +82 -0
- package/dist/db/types.js +2 -0
- package/dist/db/types.js.map +1 -0
- package/dist/logging/logger.d.ts +13 -13
- package/dist/logging/logger.js +11 -2
- package/dist/logging/logger.js.map +1 -1
- package/dist/logging/logging-middleware.d.ts +1 -1
- package/dist/logging/logging-middleware.js +6 -6
- package/dist/logging/logging-middleware.js.map +1 -1
- package/dist/middleware/ensure-api-token.d.ts +33 -4
- package/dist/middleware/ensure-api-token.js.map +1 -1
- package/dist/middleware/utils.d.ts +5 -1
- package/dist/middleware/utils.js +11 -7
- package/dist/middleware/utils.js.map +1 -1
- package/dist/network/router.d.ts +9 -6
- package/dist/network/router.js +3 -1
- package/dist/network/router.js.map +1 -1
- package/dist/network/service-discovery.d.ts +1 -1
- package/dist/network/service-discovery.js.map +1 -1
- package/dist/network/service-fetch.d.ts +6 -9
- package/dist/network/service-fetch.js +14 -4
- package/dist/network/service-fetch.js.map +1 -1
- package/dist/node/generate-wrangler-config.d.ts +28 -4
- package/dist/node/generate-wrangler-config.js +75 -20
- package/dist/node/generate-wrangler-config.js.map +1 -1
- package/logging/logger.ts +31 -21
- package/logging/logging-middleware.ts +12 -9
- package/middleware/ensure-api-token.ts +8 -6
- package/middleware/utils.ts +26 -8
- package/network/router.ts +17 -13
- package/network/service-discovery.ts +1 -1
- package/network/service-fetch.ts +26 -17
- package/node/generate-wrangler-config.ts +160 -24
- package/package.json +10 -7
|
@@ -12,7 +12,7 @@ export interface HonoLoggerOptions {
|
|
|
12
12
|
/**
|
|
13
13
|
* Custom function to extract additional metadata
|
|
14
14
|
*/
|
|
15
|
-
getMetadata?: (c: Context) => Record<string,
|
|
15
|
+
getMetadata?: (c: Context) => Record<string, unknown>;
|
|
16
16
|
|
|
17
17
|
/**
|
|
18
18
|
* Skip logging for certain paths (e.g., health checks)
|
|
@@ -81,12 +81,15 @@ const defaultOptions: HonoLoggerOptions = {
|
|
|
81
81
|
async function setupLoggerContext(c: Context, path: string) {
|
|
82
82
|
const logger = getLogger();
|
|
83
83
|
try {
|
|
84
|
-
const
|
|
85
|
-
|
|
84
|
+
const envBindings = c.env as Record<string, unknown> & {
|
|
85
|
+
WORKER_NAME?: string;
|
|
86
|
+
CONFIG_CONTENT?: string;
|
|
87
|
+
};
|
|
88
|
+
const workerName = typeof envBindings.WORKER_NAME === 'string' ? envBindings.WORKER_NAME : undefined;
|
|
86
89
|
|
|
87
90
|
// config access is safe here because loadConfig handles decompression/caching
|
|
88
|
-
if (workerName &&
|
|
89
|
-
const config = await loadConfig(
|
|
91
|
+
if (workerName && typeof envBindings.CONFIG_CONTENT === 'string') {
|
|
92
|
+
const config = await loadConfig(envBindings);
|
|
90
93
|
const basePath = getWorkerBasePath(config, workerName);
|
|
91
94
|
const handlers = config.workers?.[workerName]?.handlers || [];
|
|
92
95
|
const handlerNames = new Set<string>(handlers);
|
|
@@ -143,7 +146,7 @@ export function honoLogger(options: HonoLoggerOptions = {}) {
|
|
|
143
146
|
}
|
|
144
147
|
|
|
145
148
|
// Log request body if enabled
|
|
146
|
-
let requestBody:
|
|
149
|
+
let requestBody: unknown = undefined;
|
|
147
150
|
if (opts.logRequestBody && ['POST', 'PUT', 'PATCH'].includes(method)) {
|
|
148
151
|
try {
|
|
149
152
|
const contentType = c.req.header('Content-Type');
|
|
@@ -153,7 +156,7 @@ export function honoLogger(options: HonoLoggerOptions = {}) {
|
|
|
153
156
|
requestBody = JSON.parse(body);
|
|
154
157
|
}
|
|
155
158
|
}
|
|
156
|
-
} catch
|
|
159
|
+
} catch {
|
|
157
160
|
// Ignore body parsing errors
|
|
158
161
|
}
|
|
159
162
|
}
|
|
@@ -163,7 +166,7 @@ export function honoLogger(options: HonoLoggerOptions = {}) {
|
|
|
163
166
|
const ms = Date.now() - start;
|
|
164
167
|
|
|
165
168
|
// Log response body if enabled
|
|
166
|
-
let responseBody:
|
|
169
|
+
let responseBody: unknown = undefined;
|
|
167
170
|
if (opts.logResponseBody && c.res.body) {
|
|
168
171
|
try {
|
|
169
172
|
const contentType = c.res.headers.get('Content-Type');
|
|
@@ -174,7 +177,7 @@ export function honoLogger(options: HonoLoggerOptions = {}) {
|
|
|
174
177
|
responseBody = JSON.parse(body);
|
|
175
178
|
}
|
|
176
179
|
}
|
|
177
|
-
} catch
|
|
180
|
+
} catch {
|
|
178
181
|
// Ignore response body parsing errors
|
|
179
182
|
}
|
|
180
183
|
}
|
|
@@ -1,15 +1,17 @@
|
|
|
1
1
|
import type { TokenValidationProvider } from '../batteries/auth/token-validation';
|
|
2
2
|
import { validateToken, extractAuthToken } from '../batteries/auth/token-validation';
|
|
3
|
+
import { Context } from 'hono';
|
|
4
|
+
import type { RouterEnv } from '../network/router';
|
|
3
5
|
|
|
4
6
|
export interface EnsureApiTokenOptions {
|
|
5
|
-
getTokenValidationProvider: (c:
|
|
6
|
-
getOrgContext?: (c:
|
|
7
|
-
verifyTokenScope?: (env:
|
|
7
|
+
getTokenValidationProvider: (c: Context<{ Bindings: RouterEnv; Variables: { _apiTokenFromQuery?: string; apiToken?: unknown } }>) => TokenValidationProvider;
|
|
8
|
+
getOrgContext?: (c: Context<{ Bindings: RouterEnv; Variables: { _apiTokenFromQuery?: string; apiToken?: unknown } }>) => Promise<string | null> | string | null;
|
|
9
|
+
verifyTokenScope?: (env: RouterEnv, orgContext: string, tokenUid: string) => Promise<boolean>;
|
|
8
10
|
}
|
|
9
11
|
|
|
10
12
|
export function ensureApiToken(options: EnsureApiTokenOptions) {
|
|
11
|
-
return async (c:
|
|
12
|
-
const env = c.env
|
|
13
|
+
return async (c: Context<{ Bindings: RouterEnv; Variables: { _apiTokenFromQuery?: string; apiToken?: unknown } }>, next: () => Promise<void>) => {
|
|
14
|
+
const env = c.env;
|
|
13
15
|
|
|
14
16
|
let rawToken = extractAuthToken(c.req.raw as Request);
|
|
15
17
|
|
|
@@ -39,7 +41,7 @@ export function ensureApiToken(options: EnsureApiTokenOptions) {
|
|
|
39
41
|
return c.json({ valid: false, reason: 'Organization context required' }, 400);
|
|
40
42
|
}
|
|
41
43
|
|
|
42
|
-
const isLinked = await options.verifyTokenScope(env, orgContext
|
|
44
|
+
const isLinked = await options.verifyTokenScope(env, orgContext, result.tokenInfo.uid);
|
|
43
45
|
if (!isLinked) {
|
|
44
46
|
return c.json({ valid: false, reason: 'Token is not linked to this organization' }, 403);
|
|
45
47
|
}
|
package/middleware/utils.ts
CHANGED
|
@@ -2,35 +2,53 @@ export function nowMs(): number {
|
|
|
2
2
|
return Date.now();
|
|
3
3
|
}
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
type JwtPayloadLike = { exp?: number } | Record<string, unknown> | null | undefined;
|
|
6
|
+
|
|
7
|
+
interface GlobalBase64Support {
|
|
8
|
+
btoa?: (input: string) => string;
|
|
9
|
+
Buffer?: {
|
|
10
|
+
from: (input: string) => { toString: (encoding: string) => string };
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function computeExpiryFromJwtPayload(payload: JwtPayloadLike, fallbackMs = 5 * 60 * 1000): number {
|
|
15
|
+
if (payload && typeof payload === 'object' && 'exp' in payload && typeof payload.exp === 'number') {
|
|
7
16
|
return payload.exp * 1000 - 30_000; // safety window
|
|
8
17
|
}
|
|
9
18
|
return nowMs() + fallbackMs;
|
|
10
19
|
}
|
|
11
20
|
|
|
12
21
|
export function toBase64(input: string): string {
|
|
22
|
+
const globals = globalThis as typeof globalThis & GlobalBase64Support;
|
|
23
|
+
|
|
13
24
|
try {
|
|
14
|
-
const btoaFn =
|
|
25
|
+
const btoaFn = globals.btoa;
|
|
15
26
|
if (typeof btoaFn === 'function') return btoaFn(input);
|
|
16
27
|
} catch { }
|
|
28
|
+
|
|
17
29
|
try {
|
|
18
|
-
const
|
|
19
|
-
if (
|
|
30
|
+
const bufferRef = globals.Buffer;
|
|
31
|
+
if (bufferRef?.from) return bufferRef.from(input).toString('base64');
|
|
20
32
|
} catch { }
|
|
33
|
+
|
|
21
34
|
// Minimal fallback
|
|
22
35
|
const encoder = new TextEncoder();
|
|
23
36
|
const bytes = encoder.encode(input);
|
|
24
37
|
let binary = '';
|
|
25
38
|
for (const b of bytes) binary += String.fromCharCode(b);
|
|
26
|
-
|
|
27
|
-
|
|
39
|
+
|
|
40
|
+
const fallbackBtoa = globals.btoa;
|
|
41
|
+
if (typeof fallbackBtoa === 'function') {
|
|
42
|
+
return fallbackBtoa(binary);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
throw new Error('No Base64 encoder available in current runtime');
|
|
28
46
|
}
|
|
29
47
|
|
|
30
48
|
export async function sha256Hex(input: string): Promise<string> {
|
|
31
49
|
const data = new TextEncoder().encode(input);
|
|
32
50
|
// crypto.subtle is available in Workers runtime
|
|
33
|
-
const digest = await
|
|
51
|
+
const digest = await crypto.subtle.digest('SHA-256', data);
|
|
34
52
|
const bytes = new Uint8Array(digest);
|
|
35
53
|
let hex = '';
|
|
36
54
|
for (const b of bytes) hex += b.toString(16).padStart(2, '0');
|
package/network/router.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { Hono } from 'hono';
|
|
1
|
+
import { Hono, Context } from 'hono';
|
|
2
2
|
import { cors } from 'hono/cors';
|
|
3
3
|
import type { AppConfig, RouteConfig } from '../core/config';
|
|
4
|
+
import type { ExecutionContext } from '@cloudflare/workers-types';
|
|
4
5
|
import {
|
|
5
6
|
getRouterBasePath,
|
|
6
7
|
getWorkerBasePath,
|
|
@@ -13,7 +14,8 @@ import { simpleHonoLogger } from '../logging/logging-middleware';
|
|
|
13
14
|
|
|
14
15
|
export interface RouterEnv {
|
|
15
16
|
CONFIG_CONTENT?: string;
|
|
16
|
-
|
|
17
|
+
// Dynamic service bindings - unknown is necessary here because bindings are determined at runtime
|
|
18
|
+
[key: string]: unknown;
|
|
17
19
|
}
|
|
18
20
|
|
|
19
21
|
export function getServicesFromRoutes(routes: RouteConfig[]): string[] {
|
|
@@ -33,13 +35,15 @@ export function findMatchingRoute(path: string, routes: RouteConfig[]): RouteCon
|
|
|
33
35
|
return null;
|
|
34
36
|
}
|
|
35
37
|
|
|
36
|
-
export function getServiceBinding(serviceName: string, env: RouterEnv):
|
|
38
|
+
export function getServiceBinding(serviceName: string, env: RouterEnv): unknown {
|
|
37
39
|
const bindingName = serviceToBindingName(serviceName);
|
|
38
40
|
const binding = env[bindingName];
|
|
39
41
|
|
|
40
42
|
if (!binding) {
|
|
41
43
|
getLogger().error(`Service binding not found: ${bindingName} for service ${serviceName}`);
|
|
42
|
-
getLogger().info('Available bindings:',
|
|
44
|
+
getLogger().info('Available bindings:', {
|
|
45
|
+
bindings: Object.keys(env).filter(key => key.endsWith('_WORKER') || key.endsWith('_SERVICE'))
|
|
46
|
+
});
|
|
43
47
|
}
|
|
44
48
|
|
|
45
49
|
return binding;
|
|
@@ -50,7 +54,7 @@ export function getServiceBinding(serviceName: string, env: RouterEnv): any {
|
|
|
50
54
|
* `workerName` is injected into `X-Forwarded-By` for tracing.
|
|
51
55
|
*/
|
|
52
56
|
export async function handleServiceProxy(
|
|
53
|
-
c:
|
|
57
|
+
c: Context<{ Bindings: RouterEnv }>,
|
|
54
58
|
config: AppConfig,
|
|
55
59
|
serviceName: string,
|
|
56
60
|
remainingPath: string,
|
|
@@ -64,13 +68,13 @@ export async function handleServiceProxy(
|
|
|
64
68
|
}, 404);
|
|
65
69
|
}
|
|
66
70
|
|
|
67
|
-
const serviceConfig = config.router.services.find((s:
|
|
71
|
+
const serviceConfig = config.router.services.find((s: { service: string }) => s.service === serviceName);
|
|
68
72
|
if (!serviceConfig) {
|
|
69
73
|
return c.json({
|
|
70
74
|
success: false,
|
|
71
75
|
error: 'Service not found in router configuration',
|
|
72
76
|
service: serviceName,
|
|
73
|
-
available_services: config.router.services.map((s:
|
|
77
|
+
available_services: config.router.services.map((s: { service: string }) => s.service)
|
|
74
78
|
}, 404);
|
|
75
79
|
}
|
|
76
80
|
|
|
@@ -89,7 +93,7 @@ export async function handleServiceProxy(
|
|
|
89
93
|
newHeaders.set('X-Forwarded-By', workerName);
|
|
90
94
|
newHeaders.set('X-Original-Path', c.req.path);
|
|
91
95
|
// Forward CF location data for pgEdge geo-routing
|
|
92
|
-
const cf = (c.req.raw as
|
|
96
|
+
const cf = (c.req.raw as Request & { cf?: { continent?: string; colo?: string } }).cf;
|
|
93
97
|
if (cf?.continent) newHeaders.set('X-CF-Continent', cf.continent);
|
|
94
98
|
if (cf?.colo) newHeaders.set('X-CF-Colo', cf.colo);
|
|
95
99
|
|
|
@@ -127,7 +131,7 @@ export async function handleServiceProxy(
|
|
|
127
131
|
body: c.req.method !== 'GET' && c.req.method !== 'HEAD' ? await c.req.text() : undefined
|
|
128
132
|
});
|
|
129
133
|
|
|
130
|
-
response = await serviceBinding.fetch(newRequest);
|
|
134
|
+
response = await (serviceBinding as { fetch: (req: Request) => Promise<Response> }).fetch(newRequest);
|
|
131
135
|
}
|
|
132
136
|
|
|
133
137
|
return response;
|
|
@@ -154,7 +158,7 @@ export interface CreateRouterAppOptions {
|
|
|
154
158
|
* Optional hook to build the public config response object.
|
|
155
159
|
* If omitted, a default response with router basePath + workers is returned.
|
|
156
160
|
*/
|
|
157
|
-
buildPublicConfig?: (config: AppConfig, env: RouterEnv) => Record<string,
|
|
161
|
+
buildPublicConfig?: (config: AppConfig, env: RouterEnv) => Record<string, unknown>;
|
|
158
162
|
}
|
|
159
163
|
|
|
160
164
|
/**
|
|
@@ -345,7 +349,7 @@ export function createRouterApp(
|
|
|
345
349
|
const newHeaders = new Headers(c.req.raw.headers);
|
|
346
350
|
newHeaders.set('X-Forwarded-Url', c.req.url);
|
|
347
351
|
// Forward CF location data for pgEdge geo-routing
|
|
348
|
-
const cf = (c.req.raw as
|
|
352
|
+
const cf = (c.req.raw as Request & { cf?: { continent?: string; colo?: string } }).cf;
|
|
349
353
|
if (cf?.continent) newHeaders.set('X-CF-Continent', cf.continent);
|
|
350
354
|
if (cf?.colo) newHeaders.set('X-CF-Colo', cf.colo);
|
|
351
355
|
const orgUid = c.req.query('org_uid');
|
|
@@ -359,7 +363,7 @@ export function createRouterApp(
|
|
|
359
363
|
body: c.req.method !== 'GET' && c.req.method !== 'HEAD' ? await c.req.text() : undefined
|
|
360
364
|
});
|
|
361
365
|
|
|
362
|
-
const response = await service.fetch(newRequest);
|
|
366
|
+
const response = await (service as { fetch: (req: Request) => Promise<Response> }).fetch(newRequest);
|
|
363
367
|
return response;
|
|
364
368
|
|
|
365
369
|
} catch (error) {
|
|
@@ -381,7 +385,7 @@ export function createRouterApp(
|
|
|
381
385
|
*/
|
|
382
386
|
export function createRouterWorker(options: CreateRouterAppOptions) {
|
|
383
387
|
return {
|
|
384
|
-
async fetch(request: Request, env: RouterEnv, ctx:
|
|
388
|
+
async fetch(request: Request, env: RouterEnv, ctx: ExecutionContext): Promise<Response> {
|
|
385
389
|
try {
|
|
386
390
|
const config = await loadConfig(env);
|
|
387
391
|
|
|
@@ -9,7 +9,7 @@ import { Context, Next } from 'hono';
|
|
|
9
9
|
* Logs warnings when config doesn't match available bindings/handlers.
|
|
10
10
|
*/
|
|
11
11
|
export function serviceDiscoveryMiddleware(
|
|
12
|
-
env:
|
|
12
|
+
env: Record<string, unknown>,
|
|
13
13
|
config: AppConfig,
|
|
14
14
|
workerName: string
|
|
15
15
|
): MiddlewareHandler {
|
package/network/service-fetch.ts
CHANGED
|
@@ -7,12 +7,16 @@ import {
|
|
|
7
7
|
getServiceDiscovery,
|
|
8
8
|
getFetchInstance,
|
|
9
9
|
getRouterBasePath,
|
|
10
|
-
getRouterWorkerName
|
|
10
|
+
getRouterWorkerName,
|
|
11
|
+
type FetchInstance
|
|
11
12
|
} from '../core/config';
|
|
13
|
+
import { Context } from 'hono';
|
|
14
|
+
import type { RouterEnv } from './router';
|
|
12
15
|
|
|
13
16
|
// Convenience function for simple handler calls
|
|
14
17
|
export async function callHandler(
|
|
15
|
-
|
|
18
|
+
// Replaced WorkerEnv with RouterEnv for consistency
|
|
19
|
+
env: RouterEnv,
|
|
16
20
|
handlerName: string,
|
|
17
21
|
uri: string,
|
|
18
22
|
options: RequestInit = {}
|
|
@@ -22,7 +26,8 @@ export async function callHandler(
|
|
|
22
26
|
|
|
23
27
|
// Convenience function for simple service calls
|
|
24
28
|
export async function callService(
|
|
25
|
-
|
|
29
|
+
// Replaced WorkerEnv with RouterEnv for consistency
|
|
30
|
+
env: RouterEnv,
|
|
26
31
|
serviceName: string,
|
|
27
32
|
uri: string,
|
|
28
33
|
options: RequestInit = {}
|
|
@@ -31,9 +36,9 @@ export async function callService(
|
|
|
31
36
|
}
|
|
32
37
|
|
|
33
38
|
// Redact Authorization headers from options for debug logging
|
|
34
|
-
function redactOptions(options?: RequestInit):
|
|
39
|
+
function redactOptions(options?: RequestInit): RequestInit | undefined {
|
|
35
40
|
try {
|
|
36
|
-
const o:
|
|
41
|
+
const o: RequestInit | undefined = options ? JSON.parse(JSON.stringify(options)) : undefined;
|
|
37
42
|
if (o && o.headers) {
|
|
38
43
|
const h = new Headers(o.headers);
|
|
39
44
|
if (h.has('Authorization')) h.set('Authorization', 'Bearer ***');
|
|
@@ -46,20 +51,22 @@ function redactOptions(options?: RequestInit): any {
|
|
|
46
51
|
|
|
47
52
|
// Core inter-service communication utility
|
|
48
53
|
export async function serviceFetch(
|
|
49
|
-
|
|
50
|
-
|
|
54
|
+
// Replaced any with RouterEnv - matches framework's environment interface
|
|
55
|
+
env: RouterEnv,
|
|
56
|
+
fetchInstance: FetchInstance | string,
|
|
51
57
|
uri: string,
|
|
52
58
|
options: RequestInit = {},
|
|
53
|
-
|
|
59
|
+
// Replaced any with Hono Context - standard request context
|
|
60
|
+
ctx?: Context
|
|
54
61
|
): Promise<Response> {
|
|
55
62
|
const config = await loadConfig(env);
|
|
56
63
|
const workerName = env.WORKER_NAME || 'default-worker';
|
|
57
64
|
|
|
58
|
-
const discovery = getServiceDiscovery(env, config, workerName, appWorkerRegistry);
|
|
65
|
+
const discovery = getServiceDiscovery(env, config, workerName as string, appWorkerRegistry);
|
|
59
66
|
const routerWorkerName = getRouterWorkerName(config);
|
|
60
67
|
|
|
61
68
|
// If fetchInstance is a string, resolve it to an actual instance
|
|
62
|
-
let instance:
|
|
69
|
+
let instance: FetchInstance | null;
|
|
63
70
|
|
|
64
71
|
if (typeof fetchInstance === 'string') {
|
|
65
72
|
instance = getFetchInstance(fetchInstance, discovery, env);
|
|
@@ -82,7 +89,9 @@ export async function serviceFetch(
|
|
|
82
89
|
const headers = new Headers(initCopy.headers || {});
|
|
83
90
|
if (!headers.has('Authorization') && !headers.has('X-Authorization')) {
|
|
84
91
|
try {
|
|
85
|
-
const ctxHeaders
|
|
92
|
+
const ctxHeaders = {
|
|
93
|
+
get: (name: string) => ctx?.req?.header(name) || null
|
|
94
|
+
};
|
|
86
95
|
const authVal = ctxHeaders?.get?.('Authorization') || ctxHeaders?.get?.('X-Authorization');
|
|
87
96
|
if (authVal) headers.set('Authorization', authVal);
|
|
88
97
|
} catch { }
|
|
@@ -109,17 +118,17 @@ export async function serviceFetch(
|
|
|
109
118
|
hasExternalUrl: !!instance.external_url
|
|
110
119
|
});
|
|
111
120
|
|
|
112
|
-
const workerBasePath = getWorkerBasePath(config, workerName);
|
|
121
|
+
const workerBasePath = getWorkerBasePath(config, workerName as string);
|
|
113
122
|
const routerBasePath = getRouterBasePath(config);
|
|
114
123
|
|
|
115
124
|
// Case 1: Handler on same worker — use in-memory Hono app.fetch
|
|
116
125
|
if (instance.type === 'handler' && discovery.initializedHandlers.includes(instance.name)) {
|
|
117
|
-
const handler = appWorkerRegistry.getHandler(workerName, instance.name);
|
|
126
|
+
const handler = appWorkerRegistry.getHandler(workerName as string, instance.name);
|
|
118
127
|
if (!handler) {
|
|
119
128
|
throw new Error(`Handler '${instance.name}' not found in discovery`);
|
|
120
129
|
}
|
|
121
130
|
|
|
122
|
-
const workerApp = appWorkerRegistry.getMainApp(workerName);
|
|
131
|
+
const workerApp = appWorkerRegistry.getMainApp(workerName as string);
|
|
123
132
|
if (!workerApp) {
|
|
124
133
|
throw new Error(`Worker app '${workerName}' not found in registry`);
|
|
125
134
|
}
|
|
@@ -175,7 +184,7 @@ export async function serviceFetch(
|
|
|
175
184
|
});
|
|
176
185
|
const init = ensureAuthHeader(options);
|
|
177
186
|
const url = uri.startsWith('http') ? uri : `http://internal${uri.startsWith('/') ? uri : '/' + uri}`;
|
|
178
|
-
return await instance.binding.fetch(url, init);
|
|
187
|
+
return await (instance.binding as { fetch: (url: string, init?: RequestInit) => Promise<Response> }).fetch(url, init);
|
|
179
188
|
} catch (error) {
|
|
180
189
|
getLogger().error(`Direct service binding call failed for ${instance.name}`, error instanceof Error ? error : new Error(String(error)));
|
|
181
190
|
throw error;
|
|
@@ -247,7 +256,7 @@ export async function serviceFetch(
|
|
|
247
256
|
});
|
|
248
257
|
const init = ensureAuthHeader(options);
|
|
249
258
|
const url = routerPath.startsWith('http') ? routerPath : `http://internal${routerPath.startsWith('/') ? routerPath : '/' + routerPath}`;
|
|
250
|
-
return await routerBinding.fetch(url, init);
|
|
259
|
+
return await (routerBinding as { fetch: (url: string, init?: RequestInit) => Promise<Response> }).fetch(url, init);
|
|
251
260
|
}
|
|
252
261
|
}
|
|
253
262
|
|
|
@@ -291,7 +300,7 @@ export async function serviceFetch(
|
|
|
291
300
|
});
|
|
292
301
|
const init = ensureAuthHeader(options);
|
|
293
302
|
const url = serviceProxyPath.startsWith('http') ? serviceProxyPath : `http://internal${serviceProxyPath.startsWith('/') ? serviceProxyPath : '/' + serviceProxyPath}`;
|
|
294
|
-
return await routerBinding.fetch(url, init);
|
|
303
|
+
return await (routerBinding as { fetch: (url: string, init?: RequestInit) => Promise<Response> }).fetch(url, init);
|
|
295
304
|
}
|
|
296
305
|
}
|
|
297
306
|
|