@dunx/http 0.8.0 → 1.0.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/dist/client.js +4 -1
- package/dist/client.js.map +3 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +39 -13
- package/dist/index.js.map +7 -7
- package/dist/route/discover.d.ts +12 -1
- package/dist/server/application.d.ts +17 -4
- package/dist/server/errors.d.ts +65 -1
- package/dist/server/routes.d.ts +9 -2
- package/package.json +2 -2
package/dist/client.js
CHANGED
|
@@ -408,6 +408,7 @@ var namedModule = (name, options) => {
|
|
|
408
408
|
const optionsProvider = options instanceof HttpClientOptions ? provide(optionsToken, { useValue: options }) : provide(optionsToken, options);
|
|
409
409
|
return {
|
|
410
410
|
module: HttpModule,
|
|
411
|
+
exports: [optionsToken, httpClient(name)],
|
|
411
412
|
providers: [optionsProvider, serviceFrom(httpClient(name), optionsToken)]
|
|
412
413
|
};
|
|
413
414
|
};
|
|
@@ -419,6 +420,7 @@ class HttpModule {
|
|
|
419
420
|
return namedModule(options.name, options);
|
|
420
421
|
return {
|
|
421
422
|
module: HttpModule,
|
|
423
|
+
exports: [HttpClientOptions, HttpService],
|
|
422
424
|
providers: [
|
|
423
425
|
provide(HttpClientOptions, { useValue: options }),
|
|
424
426
|
serviceFrom(HttpService, HttpClientOptions)
|
|
@@ -434,6 +436,7 @@ class HttpModule {
|
|
|
434
436
|
}
|
|
435
437
|
return {
|
|
436
438
|
module: HttpModule,
|
|
439
|
+
exports: [HttpClientOptions, HttpService],
|
|
437
440
|
providers: [
|
|
438
441
|
provide(HttpClientOptions, { useFactory, inject }),
|
|
439
442
|
serviceFrom(HttpService, HttpClientOptions)
|
|
@@ -458,5 +461,5 @@ export {
|
|
|
458
461
|
DEFAULT_REQUEST_ID_HEADER
|
|
459
462
|
};
|
|
460
463
|
|
|
461
|
-
//# debugId=
|
|
464
|
+
//# debugId=67E96F658C57D72264756E2164756E21
|
|
462
465
|
//# sourceMappingURL=client.js.map
|
package/dist/client.js.map
CHANGED
|
@@ -6,10 +6,10 @@
|
|
|
6
6
|
"/**\n * A `JSON.stringify` that survives a cycle. **For logging only.**\n *\n * Never for a request body. The implementation this was ported from used it for\n * both, so a circular payload was *sent* upstream as `\"[Circular]\"` - a wrong body\n * that reads as a successful call and comes back as someone else's 400. A body goes\n * through plain `JSON.stringify`, which throws, because a cycle there is a bug in\n * the caller and should say so.\n */\nexport const safeStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n return JSON.stringify(value, (_key, entry: unknown) => {\n if (typeof entry === 'object' && entry !== null) {\n if (seen.has(entry)) return '[Circular]';\n seen.add(entry);\n }\n return entry;\n });\n};\n\n/**\n * A plain object: `{}`, `Object.create(null)`, or a JSON-parsed value. Anything\n * with its own prototype - `Date`, `Map`, `Error`, a class instance - is not one.\n *\n * The prototype check rather than the reference's `typeof === 'object' && !Array\n * && !(instanceof Error)`, which answered `true` for a `Date` and for every class\n * instance, so \"is this a plain object\" did not mean what it said. Body routing\n * does not use this - see {@link isJsonBody} - so tightening it changes no\n * behaviour beyond making the predicate honest.\n */\nexport const isPlainObject = (\n value: unknown,\n): value is Record<string, unknown> => {\n if (typeof value !== 'object' || value === null) return false;\n const proto = Object.getPrototypeOf(value) as object | null;\n return proto === Object.prototype || proto === null;\n};\n\n/**\n * Whether a payload should be JSON-encoded, or handed to `fetch` as-is.\n *\n * `fetch` already knows what to do with a `BodyInit` - it sets the boundary for a\n * `FormData`, the content type for a `URLSearchParams`, streams a `ReadableStream`\n * - so the only question is whether this value is one. Everything else, including\n * a `Date` or a class instance, is JSON: that is what `JSON.stringify` is for.\n *\n * Listed explicitly rather than inferred from `isPlainObject`, because the two\n * questions have different answers. `new Date()` is not a plain object but is\n * JSON-encodable; a `Blob` is neither.\n */\nexport const isJsonBody = (payload: unknown): boolean => {\n if (payload === null || payload === undefined) return false;\n if (typeof payload !== 'object') return typeof payload !== 'string';\n return !(\n payload instanceof FormData ||\n payload instanceof URLSearchParams ||\n payload instanceof Blob ||\n payload instanceof ArrayBuffer ||\n payload instanceof ReadableStream ||\n ArrayBuffer.isView(payload)\n );\n};\n",
|
|
7
7
|
"import type { RetryOptions } from './retry.js';\n\n/**\n * Named `HttpClientOptions`, not `HttpOptions`: the server half already exports\n * that from `@dunx/http` for `HttpFactory.create`, and two things called\n * `HttpOptions` meaning opposite directions of traffic is the confusion this\n * subpath exists to avoid.\n */\nexport interface HttpClientOptionsInit {\n /**\n * Prefixed to a relative `path`. With it, calls name a path; without it, every\n * call passes a whole url.\n */\n readonly baseUrl?: string | URL;\n /** Per-request budget, enforced with `AbortSignal.timeout`. @default 30000 */\n readonly timeoutMs?: number;\n /** Sent on every request, under anything a call sets itself. */\n readonly headers?: Readonly<Record<string, string>>;\n readonly retry?: RetryOptions<unknown>;\n /**\n * Forward the inbound request id to the upstream, so one trace spans both\n * services. `true` uses `x-request-id`; a string names the header. Read from\n * `RequestContext`, so it only carries when there is a request in scope.\n *\n * @default true\n */\n readonly propagateRequestId?: boolean | string;\n /** Bound as its own token, so a second client can be injected by name. */\n readonly name?: string;\n /**\n * Bun-only `fetch` extensions, passed straight through. None of these exist on\n * Node's fetch, and they are the reason an outbound client on Bun can do things a\n * ported one cannot: talk through a proxy, pin a certificate, or reach a unix\n * socket, with no dependency.\n */\n readonly proxy?: string;\n readonly tls?: Bun.TLSOptions;\n readonly unix?: string;\n /** @default true - Bun decompresses by default. */\n readonly decompress?: boolean;\n /** Bun's own request/response tracing on stderr. Never on in production. */\n readonly verbose?: boolean;\n}\n\nexport const DEFAULT_REQUEST_ID_HEADER = 'x-request-id';\n\n/**\n * The resolved options, as a class so it is both the injection token and the type\n * a factory annotates - the same trick `RedisOptions` and `ConfigService` use.\n */\nexport class HttpClientOptions {\n readonly baseUrl: string | undefined;\n readonly timeoutMs: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly retry: RetryOptions<unknown>;\n readonly requestIdHeader: string | undefined;\n readonly name: string | undefined;\n readonly fetchOptions: Readonly<Record<string, unknown>>;\n\n constructor(init: HttpClientOptionsInit = {}) {\n this.baseUrl =\n init.baseUrl === undefined ? undefined : String(init.baseUrl);\n this.timeoutMs = init.timeoutMs ?? 30_000;\n this.headers = init.headers ?? {};\n this.retry = init.retry ?? {};\n this.name = init.name;\n\n const propagate = init.propagateRequestId ?? true;\n this.requestIdHeader =\n propagate === false\n ? undefined\n : propagate === true\n ? DEFAULT_REQUEST_ID_HEADER\n : propagate;\n\n // Only the keys actually set: `exactOptionalPropertyTypes` means passing\n // `proxy: undefined` is not the same as omitting it, and Bun reads presence.\n this.fetchOptions = Object.fromEntries(\n (\n [\n ['proxy', init.proxy],\n ['tls', init.tls],\n ['unix', init.unix],\n ['decompress', init.decompress],\n ['verbose', init.verbose],\n ] as const\n ).filter(([, value]) => value !== undefined),\n );\n }\n}\nObject.defineProperty(HttpClientOptions, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"init: HttpClientOptionsInit = {}\" }],\n});\n",
|
|
8
8
|
"import { HttpStatusCode } from '../server/status.js';\nimport { FetchError, FetchTransportError } from './errors.js';\n\n/**\n * Retry, backoff and `Retry-After`, with no dependency.\n *\n * `crypto.getRandomValues` supplies the jitter. `Math.random` is what the source\n * this was ported from used and is banned repo-wide for anything that matters -\n * jitter matters, because decorrelating retries is the whole reason it exists. The\n * alternative, `@arkv/rng`, is a 64 KB WebAssembly PRNG, which is a lot of weight\n * to put in every deployment of the most-imported package to choose a number of\n * milliseconds. `crypto.getRandomValues` is a Web standard Bun implements natively,\n * is a CSPRNG, and costs nothing.\n */\nconst uniform = (): number => {\n const buffer = new Uint32Array(1);\n crypto.getRandomValues(buffer);\n // 2**32 rather than 0xffffffff, so the result is [0, 1) and never exactly 1.\n return (buffer[0] ?? 0) / 2 ** 32;\n};\n\nexport interface BackoffOptions {\n /** Base delay, doubled each attempt. */\n readonly baseMs: number;\n /** @default 2 */\n readonly power?: number;\n /** Upper bound of the random component added to each delay. @default 1000 */\n readonly jitterMs?: number;\n /** @default 30000 */\n readonly maxMs?: number;\n}\n\n/** `base * power^attempt + jitter`, capped. `attempt` is 0 for the first retry. */\nexport const backoffDelay = (\n attempt: number,\n { baseMs, power = 2, jitterMs = 1000, maxMs = 30_000 }: BackoffOptions,\n): number => Math.min(baseMs * power ** attempt + uniform() * jitterMs, maxMs);\n\n/**\n * The wait an upstream asked for, in ms, or undefined.\n *\n * RFC 9110 allows either a delay in seconds or an HTTP date, and both appear in\n * the wild - GitHub sends seconds, some CDNs send a date. Ignoring the header, as\n * the reference did, means retrying straight back into a rate limit that had just\n * told you exactly how long to wait.\n */\nexport const retryAfterMs = (\n headers: Headers,\n now: number = Date.now(),\n): number | undefined => {\n const header = headers.get('retry-after');\n if (header === null) return undefined;\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n\n const at = Date.parse(header);\n return Number.isNaN(at) ? undefined : Math.max(0, at - now);\n};\n\n/**\n * Statuses worth trying again: a server that failed, one that is overloaded, and\n * one that timed out. Deliberately narrower than the source, which also retried\n * 409 and 422 - both of those are the server rejecting the *request*, and sending\n * it again unchanged gets the same answer.\n */\nexport const isRetryableStatus = (status: number): boolean =>\n status >= HttpStatusCode.INTERNAL_SERVER_ERROR ||\n status === HttpStatusCode.REQUEST_TIMEOUT ||\n status === HttpStatusCode.TOO_MANY_REQUESTS;\n\nexport interface RetryOptions<T> {\n /** Retries *after* the first attempt, so 3 means up to 4 calls. @default 3 */\n readonly maxRetries?: number;\n /** @default 1000 */\n readonly retryDelayMs?: number;\n readonly backoff?: Omit<BackoffOptions, 'baseMs'>;\n /** @default isRetryableStatus */\n readonly shouldRetryOnStatus?: (status: number) => boolean;\n /** Honour a `Retry-After` header over the computed backoff. @default true */\n readonly respectRetryAfter?: boolean;\n readonly onAttempt?: (attempt: number, isRetry: boolean) => void;\n readonly onError?: (\n error: unknown,\n attempt: number,\n willRetry: boolean,\n ) => void;\n readonly onSuccess?: (result: T, attempt: number) => void;\n}\n\n/**\n * Whether an error is worth another attempt, and how long to wait first.\n *\n * An abort is never retried: the caller's signal fired or the timeout expired, and\n * both mean the budget for this call is spent. A transport failure is retried,\n * because a refused connection is the case retrying exists for.\n */\nconst decide = <T>(\n error: unknown,\n attempt: number,\n options: RetryOptions<T>,\n): { readonly retry: boolean; readonly delayMs: number } => {\n const {\n retryDelayMs = 1000,\n backoff,\n shouldRetryOnStatus = isRetryableStatus,\n respectRetryAfter = true,\n } = options;\n const computed = backoffDelay(attempt, { baseMs: retryDelayMs, ...backoff });\n\n if (error instanceof FetchTransportError) {\n return { retry: !error.aborted, delayMs: computed };\n }\n\n if (error instanceof FetchError) {\n if (!shouldRetryOnStatus(error.status)) return { retry: false, delayMs: 0 };\n const asked = respectRetryAfter\n ? retryAfterMs(error.response.headers)\n : undefined;\n // Still capped by the backoff ceiling: an upstream asking for an hour should\n // not park a request handler for an hour.\n const maxMs = backoff?.maxMs ?? 30_000;\n return {\n retry: true,\n delayMs: asked === undefined ? computed : Math.min(asked, maxMs),\n };\n }\n\n // Something other than a fetch failure - a JSON parse, a callback throwing.\n // Retried, matching the source, because a non-HTTP error carries no verdict.\n return { retry: true, delayMs: computed };\n};\n\n/**\n * Runs `operation`, retrying per `options`.\n *\n * `Bun.sleep` rather than a `setTimeout` promise: it is the runtime's own timer and\n * needs no wrapper.\n */\nexport const executeWithRetry = async <T>(\n operation: () => Promise<T> | T,\n options: RetryOptions<T> = {},\n): Promise<T> => {\n const { maxRetries = 3, onAttempt, onError, onSuccess } = options;\n let lastError: unknown;\n\n for (let attempt = 0; attempt <= maxRetries; attempt += 1) {\n onAttempt?.(attempt + 1, attempt > 0);\n try {\n const result = await operation();\n onSuccess?.(result, attempt + 1);\n return result;\n } catch (error) {\n lastError = error;\n const { retry, delayMs } = decide(error, attempt, options);\n const willRetry = retry && attempt < maxRetries;\n onError?.(error, attempt + 1, willRetry);\n\n if (!willRetry) throw error;\n await Bun.sleep(delayMs);\n }\n }\n\n // Unreachable: the loop either returns or throws. Kept so the signature does not\n // need `T | undefined`.\n throw lastError;\n};\n",
|
|
9
|
-
"import {\n Logger,\n provide,\n RequestContext,\n token,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type Token,\n} from '@dunx/core';\nimport { HttpClientOptions, type HttpClientOptionsInit } from './options.js';\nimport { HttpService } from './service.js';\n\nconst tokens = new Map<string, Token<HttpService>>();\n\n/**\n * The token a named client is bound to.\n *\n * Memoised, because `token()` returns a fresh object every call - without this the\n * module and the consumer would hold different tokens for `'stripe'` and the lookup\n * would miss. Same name in, same token out.\n *\n * A `Token` is not a constructor type, so a named client cannot be a constructor\n * parameter. Reach it with `inject()` in a field initialiser:\n *\n * ```ts\n * class Payments {\n * readonly stripe = inject(httpClient('stripe'));\n * }\n * ```\n */\nexport const httpClient = (name: string): Token<HttpService> => {\n const existing = tokens.get(name);\n if (existing) return existing;\n const created = token<HttpService>(`HttpService(${name})`);\n tokens.set(name, created);\n return created;\n};\n\nconst serviceFrom = (\n target: Token<HttpService> | typeof HttpService,\n optionsToken: Token<HttpClientOptions> | typeof HttpClientOptions,\n) =>\n provide(target, {\n useFactory: (\n options: HttpClientOptions,\n logger: Logger,\n context: RequestContext,\n ) => new HttpService(options, logger, context),\n inject: [optionsToken, Logger, RequestContext] as const,\n });\n\n/**\n * A named client binds its own options token, so two of them do not collide on\n * `HttpClientOptions` - the flat container reports that as a duplicate binding.\n */\nconst namedModule = (\n name: string,\n options: HttpClientOptions | FactoryProvider<HttpClientOptions, Deps>,\n): DynamicModule => {\n const optionsToken = token<HttpClientOptions>(`HttpClientOptions(${name})`);\n const optionsProvider =\n options instanceof HttpClientOptions\n ? provide(optionsToken, { useValue: options })\n : provide(optionsToken, options);\n\n return {\n module: HttpModule,\n providers: [optionsProvider, serviceFrom(httpClient(name), optionsToken)],\n };\n};\n\n/**\n * The outbound half of `@dunx/http`.\n *\n * Named `HttpModule` and `HttpService` under the `./client` subpath rather than in\n * the root barrel, where `HttpFactory` already means the inbound direction. The\n * subpath is what keeps the name unambiguous at the import site:\n *\n * ```ts\n * import { HttpFactory } from '@dunx/http'; // serving\n * import { HttpModule } from '@dunx/http/client'; // calling out\n * ```\n *\n * It depends on `Logger` and `RequestContext`, both of which core always binds, so\n * it works in an app that imported no logging module at all.\n */\nexport class HttpModule {\n /**\n * Binds `HttpService` and `HttpClientOptions`, or `httpClient(init.name)` alone\n * when `name` is set - a named registration deliberately does not also claim\n * `HttpService`, so several upstreams can coexist alongside one default.\n */\n static forRoot(init: HttpClientOptionsInit = {}): DynamicModule {\n const options = new HttpClientOptions(init);\n if (options.name !== undefined) return namedModule(options.name, options);\n\n return {\n module: HttpModule,\n providers: [\n provide(HttpClientOptions, { useValue: options }),\n serviceFrom(HttpService, HttpClientOptions),\n ],\n };\n }\n\n /**\n * `forRoot` with the options behind a factory, which is the one thing a\n * zero-argument `forRoot` cannot do: read the base url or the timeout off\n * `ConfigService`.\n *\n * There is no separate async machinery - the container resolves eagerly and\n * awaits factories before any constructor runs, so awaited config is settled by\n * the time anything is built.\n *\n * ```ts\n * HttpModule.forRootAsync({\n * useFactory: (config: AppConfigService) => ({\n * baseUrl: config.get('upstream').url,\n * }),\n * inject: [AppConfigService],\n * });\n * ```\n *\n * `name` is a parameter rather than a field of the awaited init, because the\n * token has to exist before the factory runs.\n */\n static forRootAsync(\n load: () => HttpClientOptionsInit | Promise<HttpClientOptionsInit>,\n name?: string,\n ): DynamicModule;\n static forRootAsync<const D extends Deps>(\n config: FactoryProvider<HttpClientOptionsInit, D>,\n name?: string,\n ): DynamicModule;\n static forRootAsync(\n source:\n | (() => HttpClientOptionsInit | Promise<HttpClientOptionsInit>)\n | FactoryProvider<HttpClientOptionsInit, Deps>,\n name?: string,\n ): DynamicModule {\n const load = typeof source === 'function' ? source : source.useFactory;\n const inject = typeof source === 'function' ? [] : (source.inject ?? []);\n const useFactory = async (\n ...deps: readonly unknown[]\n ): Promise<HttpClientOptions> => new HttpClientOptions(await load(...deps));\n\n if (name !== undefined) {\n return namedModule(name, { useFactory, inject } as FactoryProvider<\n HttpClientOptions,\n Deps\n >);\n }\n\n return {\n module: HttpModule,\n providers: [\n provide(HttpClientOptions, { useFactory, inject } as FactoryProvider<\n HttpClientOptions,\n Deps\n >),\n serviceFrom(HttpService, HttpClientOptions),\n ],\n };\n }\n}\n",
|
|
9
|
+
"import {\n Logger,\n provide,\n RequestContext,\n token,\n type Deps,\n type DynamicModule,\n type FactoryProvider,\n type Token,\n} from '@dunx/core';\nimport { HttpClientOptions, type HttpClientOptionsInit } from './options.js';\nimport { HttpService } from './service.js';\n\nconst tokens = new Map<string, Token<HttpService>>();\n\n/**\n * The token a named client is bound to.\n *\n * Memoised, because `token()` returns a fresh object every call - without this the\n * module and the consumer would hold different tokens for `'stripe'` and the lookup\n * would miss. Same name in, same token out.\n *\n * A `Token` is not a constructor type, so a named client cannot be a constructor\n * parameter. Reach it with `inject()` in a field initialiser:\n *\n * ```ts\n * class Payments {\n * readonly stripe = inject(httpClient('stripe'));\n * }\n * ```\n */\nexport const httpClient = (name: string): Token<HttpService> => {\n const existing = tokens.get(name);\n if (existing) return existing;\n const created = token<HttpService>(`HttpService(${name})`);\n tokens.set(name, created);\n return created;\n};\n\nconst serviceFrom = (\n target: Token<HttpService> | typeof HttpService,\n optionsToken: Token<HttpClientOptions> | typeof HttpClientOptions,\n) =>\n provide(target, {\n useFactory: (\n options: HttpClientOptions,\n logger: Logger,\n context: RequestContext,\n ) => new HttpService(options, logger, context),\n inject: [optionsToken, Logger, RequestContext] as const,\n });\n\n/**\n * A named client binds its own options token, so two of them do not collide on\n * `HttpClientOptions` - the flat container reports that as a duplicate binding.\n */\nconst namedModule = (\n name: string,\n options: HttpClientOptions | FactoryProvider<HttpClientOptions, Deps>,\n): DynamicModule => {\n const optionsToken = token<HttpClientOptions>(`HttpClientOptions(${name})`);\n const optionsProvider =\n options instanceof HttpClientOptions\n ? provide(optionsToken, { useValue: options })\n : provide(optionsToken, options);\n\n return {\n module: HttpModule,\n exports: [optionsToken, httpClient(name)],\n providers: [optionsProvider, serviceFrom(httpClient(name), optionsToken)],\n };\n};\n\n/**\n * The outbound half of `@dunx/http`.\n *\n * Named `HttpModule` and `HttpService` under the `./client` subpath rather than in\n * the root barrel, where `HttpFactory` already means the inbound direction. The\n * subpath is what keeps the name unambiguous at the import site:\n *\n * ```ts\n * import { HttpFactory } from '@dunx/http'; // serving\n * import { HttpModule } from '@dunx/http/client'; // calling out\n * ```\n *\n * It depends on `Logger` and `RequestContext`, both of which core always binds, so\n * it works in an app that imported no logging module at all.\n */\nexport class HttpModule {\n /**\n * Binds `HttpService` and `HttpClientOptions`, or `httpClient(init.name)` alone\n * when `name` is set - a named registration deliberately does not also claim\n * `HttpService`, so several upstreams can coexist alongside one default.\n */\n static forRoot(init: HttpClientOptionsInit = {}): DynamicModule {\n const options = new HttpClientOptions(init);\n if (options.name !== undefined) return namedModule(options.name, options);\n\n return {\n module: HttpModule,\n exports: [HttpClientOptions, HttpService],\n providers: [\n provide(HttpClientOptions, { useValue: options }),\n serviceFrom(HttpService, HttpClientOptions),\n ],\n };\n }\n\n /**\n * `forRoot` with the options behind a factory, which is the one thing a\n * zero-argument `forRoot` cannot do: read the base url or the timeout off\n * `ConfigService`.\n *\n * There is no separate async machinery - the container resolves eagerly and\n * awaits factories before any constructor runs, so awaited config is settled by\n * the time anything is built.\n *\n * ```ts\n * HttpModule.forRootAsync({\n * useFactory: (config: AppConfigService) => ({\n * baseUrl: config.get('upstream').url,\n * }),\n * inject: [AppConfigService],\n * });\n * ```\n *\n * `name` is a parameter rather than a field of the awaited init, because the\n * token has to exist before the factory runs.\n */\n static forRootAsync(\n load: () => HttpClientOptionsInit | Promise<HttpClientOptionsInit>,\n name?: string,\n ): DynamicModule;\n static forRootAsync<const D extends Deps>(\n config: FactoryProvider<HttpClientOptionsInit, D>,\n name?: string,\n ): DynamicModule;\n static forRootAsync(\n source:\n | (() => HttpClientOptionsInit | Promise<HttpClientOptionsInit>)\n | FactoryProvider<HttpClientOptionsInit, Deps>,\n name?: string,\n ): DynamicModule {\n const load = typeof source === 'function' ? source : source.useFactory;\n const inject = typeof source === 'function' ? [] : (source.inject ?? []);\n const useFactory = async (\n ...deps: readonly unknown[]\n ): Promise<HttpClientOptions> => new HttpClientOptions(await load(...deps));\n\n if (name !== undefined) {\n return namedModule(name, { useFactory, inject } as FactoryProvider<\n HttpClientOptions,\n Deps\n >);\n }\n\n return {\n module: HttpModule,\n exports: [HttpClientOptions, HttpService],\n providers: [\n provide(HttpClientOptions, { useFactory, inject } as FactoryProvider<\n HttpClientOptions,\n Deps\n >),\n serviceFrom(HttpService, HttpClientOptions),\n ],\n };\n }\n}\n",
|
|
10
10
|
"import { Logger, RequestContext } from '@dunx/core';\nimport { UrlHelper, type ParamsType } from '@arkv/shared';\nimport type { HttpMethod } from '../route/marker.js';\nimport { FetchError, FetchTransportError } from './errors.js';\nimport { isJsonBody, safeStringify } from './json.js';\nimport { HttpClientOptions } from './options.js';\nimport { executeWithRetry, type RetryOptions } from './retry.js';\n\n/** The client speaks two more verbs than a route can declare. */\nexport type RequestMethod = HttpMethod | 'HEAD' | 'OPTIONS';\n\n/**\n * `@arkv/shared`'s own param type, imported rather than restated - a local copy\n * would drift from what `buildUrl` actually accepts, which is how `null` ended up\n * in the first draft of this file and `interpolate` would never have seen it.\n */\ntype Params = ParamsType;\n\n/**\n * `fetch`'s own body type, derived from its signature. `BodyInit` is not a global\n * here: the root tsconfig sets `lib: [\"ESNext\"]` with no DOM, so the name does not\n * exist even though the value does. Reading it off `typeof fetch` needs no lib and\n * cannot disagree with the runtime.\n */\ntype FetchBody = NonNullable<NonNullable<Parameters<typeof fetch>[1]>['body']>;\n\nexport type HeaderFactory = (params: {\n /** Unix seconds, which is what every HMAC scheme signs. */\n readonly timestamp: number;\n readonly method: RequestMethod;\n /** `pathname + search`, the part such schemes sign. */\n readonly requestPath: string;\n /** The serialised body, or `''`. */\n readonly body: string;\n}) => Record<string, string>;\n\nexport interface RequestConfig<TRequest = unknown, TResponse = unknown> {\n readonly method: RequestMethod;\n /** Absolute, or relative to `baseUrl`. Omit when `baseUrl` plus `path` is enough. */\n readonly url?: string | URL;\n readonly payload?: TRequest;\n readonly headers?: Readonly<Record<string, string>>;\n /** Appended to the base, with `{param}` interpolated from `pathParams`. */\n readonly path?: string;\n readonly pathParams?: Params;\n readonly queryParams?: Params;\n /** Overrides the client's default budget. */\n readonly timeoutMs?: number;\n /** Called once per attempt, so a signature covers the body it is sent with. */\n readonly headerFactory?: HeaderFactory;\n /** Merged into the async context for this call, so its logs carry it. */\n readonly flow?: string;\n readonly retry?: RetryOptions<TResponse>;\n /** Cancels the call. Combined with the timeout, whichever fires first. */\n readonly signal?: AbortSignal;\n}\n\ntype BaseOptions<TRequest, TResponse> = Omit<\n RequestConfig<TRequest, TResponse>,\n 'method' | 'url' | 'payload'\n>;\n\n/**\n * What `send` reads. Narrower than `RequestConfig` on purpose: `RetryOptions<T>` is\n * invariant in `T` - its `onSuccess` takes a `T` and its callbacks return one - so a\n * `RequestConfig<_, TResponse>` is not assignable to a `RequestConfig<_, unknown>`.\n * `send` never touches `retry`, so leaving it out is both true and assignable.\n */\ninterface SendConfig {\n readonly method: RequestMethod;\n readonly headers?: Readonly<Record<string, string>>;\n readonly timeoutMs?: number;\n readonly headerFactory?: HeaderFactory;\n readonly signal?: AbortSignal;\n}\n\n/**\n * A `fetch` client with a per-request timeout, retry with backoff, request-id\n * propagation and one log line per call.\n *\n * `fetch` and nothing else: it is a Web standard Bun implements natively, so there\n * is no client dependency to justify - which is also why `axios` and `node-fetch`\n * are banned repo-wide. What this adds over calling `fetch` yourself is the parts\n * every caller otherwise reimplements slightly differently: the timeout, the\n * retry policy, `Retry-After`, url building, and a failure that says which call\n * failed.\n *\n * Extends `UrlHelper` from `@arkv/shared`, so `buildUrl` and `interpolate` are\n * available on the service, and there is one implementation of them across the\n * owner's projects rather than a fork per repo.\n */\nexport class HttpService extends UrlHelper {\n constructor(\n private readonly options: HttpClientOptions,\n private readonly logger: Logger,\n private readonly requestContext: RequestContext,\n ) {\n super();\n }\n\n async request<TRequest = unknown, TResponse = unknown>(\n config: RequestConfig<TRequest, TResponse>,\n ): Promise<TResponse> {\n const url = this.urlFor(config);\n const startedAt = Date.now();\n let attempts = 0;\n let status: number | undefined;\n\n /**\n * Serialised **once**, outside the retry loop. A body does not change between\n * attempts - only the signature over it does, and `headerFactory` gets a fresh\n * timestamp per attempt from `send`.\n *\n * Doing it inside meant a caller's own `JSON.stringify` failure, a circular\n * payload, was treated as a retryable error: three attempts and eight seconds of\n * backoff before surfacing a bug that no amount of retrying could fix. It also\n * re-serialised a large body on every attempt.\n */\n const { body, serialised } = this.bodyFor(config.payload);\n\n /**\n * A stream body is consumed by the first attempt, so a second would send an\n * empty one. Retrying is switched off rather than left to fail as a confusing\n * \"body already used\" on the retry.\n */\n const replayable = !(config.payload instanceof ReadableStream);\n\n const attempt = async (): Promise<TResponse> => {\n attempts += 1;\n const response = await this.send(config, url, body, serialised);\n status = response.status;\n\n if (!response.ok) {\n throw new FetchError(\n response.status,\n response.statusText,\n await readBody(response),\n {\n method: config.method,\n url: url.href,\n headers: response.headers,\n },\n );\n }\n\n return (await readBody(response)) as TResponse;\n };\n\n const describe = (): string => `${config.method} ${url.href}`;\n\n try {\n const result = await this.requestContext.runWithContext(\n {\n ...(config.flow === undefined ? {} : { flow: config.flow }),\n event: config.path ?? url.pathname,\n },\n () =>\n executeWithRetry(attempt, {\n ...this.options.retry,\n ...config.retry,\n ...(replayable ? {} : { maxRetries: 0 }),\n } as RetryOptions<TResponse>),\n );\n\n this.logger.debug(`${describe()} succeeded`, {\n status,\n attempts,\n elapsedMs: Date.now() - startedAt,\n });\n return result;\n } catch (error) {\n this.logger.error(`${describe()} failed`, {\n // `safeStringify`, not the error object: an upstream body can carry a cycle\n // and this is the one place that must not throw while reporting a throw.\n err: safeStringify(describeError(error)),\n attempts,\n elapsedMs: Date.now() - startedAt,\n });\n throw error;\n }\n }\n\n get<TResponse = unknown>(\n url?: string | URL,\n options?: BaseOptions<never, TResponse>,\n ): Promise<TResponse> {\n return this.request<never, TResponse>({\n method: 'GET',\n ...options,\n ...urlOf(url),\n });\n }\n\n post<TRequest = unknown, TResponse = unknown>(\n url?: string | URL,\n payload?: TRequest,\n options?: BaseOptions<TRequest, TResponse>,\n ): Promise<TResponse> {\n return this.request<TRequest, TResponse>({\n method: 'POST',\n ...options,\n ...urlOf(url),\n ...(payload === undefined ? {} : { payload }),\n });\n }\n\n put<TRequest = unknown, TResponse = unknown>(\n url?: string | URL,\n payload?: TRequest,\n options?: BaseOptions<TRequest, TResponse>,\n ): Promise<TResponse> {\n return this.request<TRequest, TResponse>({\n method: 'PUT',\n ...options,\n ...urlOf(url),\n ...(payload === undefined ? {} : { payload }),\n });\n }\n\n patch<TRequest = unknown, TResponse = unknown>(\n url?: string | URL,\n payload?: TRequest,\n options?: BaseOptions<TRequest, TResponse>,\n ): Promise<TResponse> {\n return this.request<TRequest, TResponse>({\n method: 'PATCH',\n ...options,\n ...urlOf(url),\n ...(payload === undefined ? {} : { payload }),\n });\n }\n\n delete<TResponse = unknown>(\n url?: string | URL,\n options?: BaseOptions<never, TResponse>,\n ): Promise<TResponse> {\n return this.request<never, TResponse>({\n method: 'DELETE',\n ...options,\n ...urlOf(url),\n });\n }\n\n /**\n * Yields each `data:` payload of a Server-Sent-Events response, consuming the\n * terminating `[DONE]` sentinel rather than yielding it.\n *\n * **No retry**, deliberately: a partially consumed stream cannot be replayed, so\n * retrying would re-deliver events the caller has already seen. The timeout\n * covers the connect only - it is dropped once headers arrive, or a long-lived\n * stream would be cut off mid-flight.\n *\n * Hand-rolled rather than delegated: Bun exposes no `EventSource` global and no\n * SSE parser, which was measured rather than assumed.\n */\n async *streamSse<TRequest = unknown>(\n config: Omit<RequestConfig<TRequest>, 'method' | 'retry'> & {\n readonly method?: 'GET' | 'POST';\n },\n ): AsyncGenerator<string> {\n const url = this.urlFor(config);\n const method = config.method ?? 'POST';\n const startedAt = Date.now();\n const { body, serialised } = this.bodyFor(config.payload);\n\n const response = await this.send(\n { ...config, method },\n url,\n body,\n serialised,\n 'text/event-stream',\n );\n\n if (!response.ok || response.body === null) {\n throw new FetchError(\n response.status,\n response.statusText,\n await readBody(response),\n { method, url: url.href, headers: response.headers },\n );\n }\n\n const decoder = new TextDecoder();\n let buffer = '';\n\n try {\n // Async iteration, not `getReader()`: it acquires the reader and releases it\n // on completion, on `break`, and on the `return` below when `[DONE]` arrives -\n // which is the case the manual form needed `releaseLock()` in a `finally` for.\n for await (const chunk of response.body) {\n buffer += decoder.decode(chunk, { stream: true });\n\n let newline = buffer.indexOf('\\n');\n while (newline !== -1) {\n const line = buffer.slice(0, newline).trim();\n buffer = buffer.slice(newline + 1);\n newline = buffer.indexOf('\\n');\n\n if (!line.startsWith('data:')) continue;\n const data = line.slice(5).trim();\n if (data === '[DONE]') return;\n yield data;\n }\n }\n } finally {\n this.logger.debug(`SSE ${method} ${url.href} closed`, {\n elapsedMs: Date.now() - startedAt,\n });\n }\n }\n\n /**\n * Resolves the target, accepting the three forms a caller actually reaches for:\n * an absolute url, a path relative to `baseUrl`, or `baseUrl` plus an explicit\n * `path`.\n *\n * `get('/users')` is the one worth calling out. A relative first argument is what\n * every HTTP client takes once a base url exists, and passing it straight to\n * `buildUrl` throws `ERR_INVALID_URL` from inside `new URL()` - a message naming\n * neither the call nor the missing base. So a first argument that is not an\n * absolute url is treated as the path, which is what it reads as.\n *\n * `URL.canParse` decides, rather than a regex over `//` or `:` - it is the same\n * parser `new URL` uses, so the two cannot disagree.\n */\n private urlFor(config: {\n readonly url?: string | URL;\n readonly path?: string;\n readonly pathParams?: Params;\n readonly queryParams?: Params;\n }): URL {\n const given = config.url === undefined ? undefined : String(config.url);\n const absolute =\n given !== undefined && given !== '' && URL.canParse(given)\n ? given\n : undefined;\n const relative = given === '' || absolute !== undefined ? undefined : given;\n const base = absolute ?? this.options.baseUrl;\n\n if (base === undefined) {\n throw new FetchTransportError(\n { method: 'GET', url: given ?? config.path ?? '(none)' },\n false,\n {\n cause: new Error(\n 'No url to call. Pass an absolute url, or set baseUrl on ' +\n 'HttpModule.forRoot and pass a path.',\n ),\n },\n );\n }\n\n // An explicit `path` wins over a relative first argument, so a call cannot\n // silently request two different paths.\n const path = config.path ?? relative;\n\n return this.buildUrl({\n base,\n ...(path === undefined ? {} : { path }),\n ...(config.pathParams === undefined\n ? {}\n : { pathParams: config.pathParams }),\n ...(config.queryParams === undefined\n ? {}\n : { queryParams: config.queryParams }),\n });\n }\n\n /** `serialised` is what a `headerFactory` signs, and is `''` for no body. */\n private bodyFor(payload: unknown): {\n body: FetchBody | undefined;\n serialised: string;\n json: boolean;\n } {\n if (payload === undefined || payload === null) {\n return { body: undefined, serialised: '', json: false };\n }\n if (!isJsonBody(payload)) {\n return { body: payload as FetchBody, serialised: '', json: false };\n }\n // Plain `JSON.stringify`, deliberately not `safeStringify`: a cycle here must\n // throw rather than be sent upstream as \"[Circular]\".\n const serialised = JSON.stringify(payload);\n return { body: serialised, serialised, json: true };\n }\n\n private async send(\n config: SendConfig,\n url: URL,\n body: FetchBody | undefined,\n serialised: string,\n accept = 'application/json',\n ): Promise<Response> {\n const requestId =\n this.options.requestIdHeader === undefined\n ? undefined\n : this.requestContext.getContext().requestId;\n\n const headers: Record<string, string> = {\n accept,\n ...(serialised === '' ? {} : { 'content-type': 'application/json' }),\n ...this.options.headers,\n ...(requestId === undefined || this.options.requestIdHeader === undefined\n ? {}\n : { [this.options.requestIdHeader]: requestId }),\n ...config.headerFactory?.({\n timestamp: Math.floor(Date.now() / 1000),\n method: config.method,\n requestPath: url.pathname + url.search,\n body: serialised,\n }),\n ...config.headers,\n };\n\n /**\n * `AbortSignal.timeout` plus `AbortSignal.any`, rather than an\n * `AbortController` with a `setTimeout` and a `clearTimeout` in a `finally`.\n * Both are Web standards Bun implements, the timer is the runtime's to cancel,\n * and combining the caller's signal with the budget is one call instead of a\n * second listener that has to be removed.\n */\n const timeoutMs = config.timeoutMs ?? this.options.timeoutMs;\n const signals = [\n ...(timeoutMs > 0 ? [AbortSignal.timeout(timeoutMs)] : []),\n ...(config.signal === undefined ? [] : [config.signal]),\n ];\n\n try {\n return await fetch(url.href, {\n method: config.method,\n headers,\n ...(body === undefined ? {} : { body }),\n ...(signals.length === 0 ? {} : { signal: AbortSignal.any(signals) }),\n ...this.options.fetchOptions,\n });\n } catch (error) {\n // `fetch` reports a refused connection, a DNS failure and an abort all as\n // exceptions with nothing naming the call. Wrapped so the message does.\n const aborted =\n error instanceof Error &&\n (error.name === 'AbortError' || error.name === 'TimeoutError');\n throw new FetchTransportError(\n { method: config.method, url: url.href },\n aborted,\n { cause: error },\n );\n }\n }\n}\nObject.defineProperty(HttpService, Symbol.for('dunx.deps'), {\n value: () => [HttpClientOptions, Logger, RequestContext],\n});\n\nconst urlOf = (url?: string | URL): { url?: string | URL } =>\n url === undefined ? {} : { url };\n\n/** JSON when the upstream said so or the body parses; text otherwise; undefined for empty. */\nconst readBody = async (response: Response): Promise<unknown> => {\n const text = await response.text().catch(() => '');\n if (text === '') return undefined;\n try {\n return JSON.parse(text) as unknown;\n } catch {\n return text;\n }\n};\n\nconst describeError = (error: unknown): Record<string, unknown> => {\n if (error instanceof FetchError) {\n return {\n name: error.name,\n message: error.message,\n status: error.status,\n body: error.body,\n };\n }\n if (error instanceof Error) {\n return { name: error.name, message: error.message };\n }\n return { message: String(error) };\n};\n"
|
|
11
11
|
],
|
|
12
|
-
"mappings": ";;;;;;AAAA;AAAA;AAsBO,MAAM,mBAAmB,SAAS;AAAA,EAI5B;AAAA,EACA;AAAA,EAEA;AAAA,EACA;AAAA,EAPO,OAAO;AAAA,EAEzB,WAAW,CACA,QACA,YAEA,MACA,UAKT;AAAA,IACA,MACE,QAAQ,UAAU,mBAAmB,SAAS,UAAU,SAAS,KACnE;AAAA,IAZS;AAAA,IACA;AAAA,IAEA;AAAA,IACA;AAAA;AAUb;AACA,OAAO,eAAe,YAAY,OAAO,IAAI,WAAW,GAAG;AAAA,EAC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,EAAE,YAAY,OAAO,CAG/C;AAAA,QACD,YAAY,aAAa,iBAAiB;AAAA,MAC5C;AAAA,IACF;AAAA;AAEJ;",
|
|
13
|
+
"debugId": "67E96F658C57D72264756E2164756E21",
|
|
14
14
|
"names": []
|
|
15
15
|
}
|
package/dist/index.d.ts
CHANGED
|
@@ -6,7 +6,7 @@ export type { InferOutput, Input, RouteInput, RouteSchemas, StandardSchemaIssue,
|
|
|
6
6
|
export { ClientAddress } from './server/client-address.js';
|
|
7
7
|
export { buildContext, type RouteContext } from './server/context.js';
|
|
8
8
|
export { preflight, withCors, type CorsOptions, type CorsOrigin, } from './server/cors.js';
|
|
9
|
-
export { defaultErrorMapper, errorMapper, HttpError, ValidationError, type ErrorMapper, type InputSource, type ValidationIssue, } from './server/errors.js';
|
|
9
|
+
export { defaultErrorMapper, ErrorFilter, errorMapper, HttpError, isErrorFilter, toErrorMapper, ValidationError, type ErrorHandler, type ErrorMapper, type InputSource, type ValidationIssue, } from './server/errors.js';
|
|
10
10
|
export { HttpFactory, type HttpApp, type HttpOptions, } from './server/factory.js';
|
|
11
11
|
export { REQUEST_ID_HEADER, RequestLoggingMiddleware, type RequestLoggingOptions, } from './server/request-logging.js';
|
|
12
12
|
export { compose, type Middleware, type Next, type RouteHandler, } from './server/middleware.js';
|
package/dist/index.js
CHANGED
|
@@ -225,6 +225,11 @@ class ValidationError extends HttpError {
|
|
|
225
225
|
Object.defineProperty(ValidationError, Symbol.for("dunx.deps"), {
|
|
226
226
|
value: () => [{ unresolved: "readonly source: InputSource" }, { unresolved: "readonly issues: readonly ValidationIssue[]" }]
|
|
227
227
|
});
|
|
228
|
+
|
|
229
|
+
class ErrorFilter {
|
|
230
|
+
}
|
|
231
|
+
var isErrorFilter = (handler) => typeof handler === "function" && typeof handler.prototype?.catch === "function";
|
|
232
|
+
var toErrorMapper = (handler, resolve) => isErrorFilter(handler) ? (error, req) => resolve(handler).catch(error, req) : handler;
|
|
228
233
|
var errorMapper = (logger) => (error) => {
|
|
229
234
|
if (error instanceof ValidationError) {
|
|
230
235
|
return Response.json({ error: error.message, status: error.status, issues: error.issues }, { status: error.status });
|
|
@@ -1055,18 +1060,22 @@ var buildRoutes = (discovered, middleware = [], onError = defaultErrorMapper, co
|
|
|
1055
1060
|
assertNoCollisions(discovered);
|
|
1056
1061
|
const routes = {};
|
|
1057
1062
|
const instances = new Map;
|
|
1058
|
-
const guardOf = (guard) => {
|
|
1063
|
+
const guardOf = (guard, from) => {
|
|
1059
1064
|
const existing = instances.get(guard);
|
|
1060
1065
|
if (existing)
|
|
1061
1066
|
return existing;
|
|
1062
|
-
const created = resolve(guard);
|
|
1067
|
+
const created = resolve(guard, from);
|
|
1063
1068
|
instances.set(guard, created);
|
|
1064
1069
|
return created;
|
|
1065
1070
|
};
|
|
1066
1071
|
for (const route of discovered) {
|
|
1067
1072
|
const read = buildInputReader(route.options);
|
|
1068
1073
|
const status = statusFor(route);
|
|
1069
|
-
const chain = [
|
|
1074
|
+
const chain = [
|
|
1075
|
+
...middleware,
|
|
1076
|
+
...(route.moduleMiddleware ?? []).map((entry) => guardOf(entry, route.module)),
|
|
1077
|
+
...(route.guards ?? []).map((guard) => guardOf(guard, route.module))
|
|
1078
|
+
];
|
|
1070
1079
|
const chained = compose(chain, buildContext(route), async (req) => toResponse(await route.handler(await read(req)), status));
|
|
1071
1080
|
const guarded = async (req) => {
|
|
1072
1081
|
try {
|
|
@@ -1091,6 +1100,8 @@ var defaultSettings = () => ({ "trust proxy": false });
|
|
|
1091
1100
|
|
|
1092
1101
|
// src/server/application.ts
|
|
1093
1102
|
class HttpApplication {
|
|
1103
|
+
warnings;
|
|
1104
|
+
#root;
|
|
1094
1105
|
closed;
|
|
1095
1106
|
gatewayPaths;
|
|
1096
1107
|
#app;
|
|
@@ -1111,14 +1122,16 @@ class HttpApplication {
|
|
|
1111
1122
|
#resolveClosed;
|
|
1112
1123
|
#shuttingDown;
|
|
1113
1124
|
#hooked = false;
|
|
1114
|
-
constructor(app, discovered, options, websocket) {
|
|
1125
|
+
constructor(app, discovered, options, root, websocket) {
|
|
1115
1126
|
this.#app = app;
|
|
1127
|
+
this.#root = root;
|
|
1128
|
+
this.warnings = app.warnings;
|
|
1116
1129
|
this.#discovered = discovered;
|
|
1117
1130
|
this.#middleware = [
|
|
1118
1131
|
...options.requestLogging === false ? [] : [RequestLoggingMiddleware],
|
|
1119
1132
|
...options.middleware ?? []
|
|
1120
1133
|
];
|
|
1121
|
-
this.#onError = options.onError
|
|
1134
|
+
this.#onError = options.onError === undefined ? errorMapper(app.get(Logger2)) : toErrorMapper(options.onError, (token) => app.get(token, root));
|
|
1122
1135
|
this.#port = options.port ?? 3000;
|
|
1123
1136
|
this.#websocket = websocket;
|
|
1124
1137
|
this.#relay = options.relay;
|
|
@@ -1162,9 +1175,9 @@ class HttpApplication {
|
|
|
1162
1175
|
async listen(port = this.#port) {
|
|
1163
1176
|
this.#assertNotStarted("listen()");
|
|
1164
1177
|
this.#started = true;
|
|
1165
|
-
const middleware = this.#middleware.map((entry) => this.#app.get(entry));
|
|
1178
|
+
const middleware = this.#middleware.map((entry) => this.#app.get(entry, this.#root));
|
|
1166
1179
|
const prefixed = this.#prefixed();
|
|
1167
|
-
const routes = buildRoutes(prefixed, middleware, this.#onError, this.#cors, (guard) => this.#app.get(guard));
|
|
1180
|
+
const routes = buildRoutes(prefixed, middleware, this.#onError, this.#cors, (guard, from) => from === undefined ? this.#app.get(guard) : this.#app.get(guard, from));
|
|
1168
1181
|
const ws = this.#websocket;
|
|
1169
1182
|
if (ws)
|
|
1170
1183
|
assertNoGatewayCollisions(prefixed, ws.paths);
|
|
@@ -1232,7 +1245,7 @@ class HttpApplication {
|
|
|
1232
1245
|
}
|
|
1233
1246
|
}
|
|
1234
1247
|
Object.defineProperty(HttpApplication, Symbol.for("dunx.deps"), {
|
|
1235
|
-
value: () => [{ unresolved: "app: App", typeOnly: "App" }, { unresolved: "discovered: readonly DiscoveredRoute[]" }, { unresolved: "options: HttpOptions" }, { unresolved: "websocket?: WebSocketRuntime", typeOnly: "WebSocketRuntime" }]
|
|
1248
|
+
value: () => [{ unresolved: "app: App", typeOnly: "App" }, { unresolved: "discovered: readonly DiscoveredRoute[]" }, { unresolved: "options: HttpOptions" }, { unresolved: "root: ModuleRef", typeOnly: "ModuleRef" }, { unresolved: "websocket?: WebSocketRuntime", typeOnly: "WebSocketRuntime" }]
|
|
1236
1249
|
});
|
|
1237
1250
|
|
|
1238
1251
|
// src/server/factory.ts
|
|
@@ -1245,27 +1258,37 @@ class HttpFactory {
|
|
|
1245
1258
|
useFactory: (logger, context) => new RequestLoggingMiddleware(logger, context, typeof options.requestLogging === "object" ? options.requestLogging : {}),
|
|
1246
1259
|
inject: [Logger3, RequestContext2]
|
|
1247
1260
|
});
|
|
1261
|
+
const providers = options.requestLogging === false ? [PubSub] : [PubSub, logging];
|
|
1248
1262
|
const scope = {
|
|
1249
1263
|
module: HttpModule,
|
|
1264
|
+
global: true,
|
|
1250
1265
|
imports: [root],
|
|
1251
|
-
providers
|
|
1266
|
+
providers,
|
|
1267
|
+
exports: providers.map((entry) => typeof entry === "function" ? entry : entry.token)
|
|
1252
1268
|
};
|
|
1253
1269
|
const app = await AppFactory.create(scope, options.overrides ? { overrides: options.overrides } : {});
|
|
1254
1270
|
const modules = collectModules(scope);
|
|
1255
1271
|
const discovered = [];
|
|
1256
1272
|
for (const module of modules) {
|
|
1273
|
+
const moduleMiddleware = module.options.middleware ?? [];
|
|
1257
1274
|
for (const controller of readControllers(module)) {
|
|
1258
|
-
const routes = discoverRoutes(app.get(controller));
|
|
1275
|
+
const routes = discoverRoutes(app.get(controller, module.ref));
|
|
1259
1276
|
if (routes.length === 0) {
|
|
1260
1277
|
throw new AppError8(`${controller.name} is registered as a controller but declares no routes. ` + "Add a @Get/@Post/... method, or move it to providers.");
|
|
1261
1278
|
}
|
|
1262
|
-
discovered.push(...routes)
|
|
1279
|
+
discovered.push(...routes.map((route) => ({
|
|
1280
|
+
...route,
|
|
1281
|
+
module: module.ref,
|
|
1282
|
+
...moduleMiddleware.length === 0 ? {} : {
|
|
1283
|
+
moduleMiddleware
|
|
1284
|
+
}
|
|
1285
|
+
})));
|
|
1263
1286
|
}
|
|
1264
1287
|
}
|
|
1265
1288
|
assertNoCollisions(discovered);
|
|
1266
1289
|
const gateways = discoverGateways(modules, (token) => app.get(token));
|
|
1267
1290
|
const websocket = gateways.length > 0 ? buildWebSocket(gateways, options.websocket) : undefined;
|
|
1268
|
-
return new HttpApplication(app, discovered, options, websocket);
|
|
1291
|
+
return new HttpApplication(app, discovered, options, root, websocket);
|
|
1269
1292
|
}
|
|
1270
1293
|
}
|
|
1271
1294
|
// src/ws/decorators.ts
|
|
@@ -1383,6 +1406,7 @@ Object.defineProperty(RedisRelay, Symbol.for("dunx.deps"), {
|
|
|
1383
1406
|
export {
|
|
1384
1407
|
withUpgradeRoutes,
|
|
1385
1408
|
withCors,
|
|
1409
|
+
toErrorMapper,
|
|
1386
1410
|
preflight,
|
|
1387
1411
|
normalizePath,
|
|
1388
1412
|
metaOf,
|
|
@@ -1391,6 +1415,7 @@ export {
|
|
|
1391
1415
|
mergeMeta,
|
|
1392
1416
|
joinPath,
|
|
1393
1417
|
isGateway,
|
|
1418
|
+
isErrorFilter,
|
|
1394
1419
|
guardsOf,
|
|
1395
1420
|
errorMapper,
|
|
1396
1421
|
encodeRelay,
|
|
@@ -1438,6 +1463,7 @@ export {
|
|
|
1438
1463
|
HIDDEN,
|
|
1439
1464
|
Get,
|
|
1440
1465
|
Gateway,
|
|
1466
|
+
ErrorFilter,
|
|
1441
1467
|
Delete,
|
|
1442
1468
|
DEFAULT_RELAY_CHANNEL,
|
|
1443
1469
|
Controller,
|
|
@@ -1445,5 +1471,5 @@ export {
|
|
|
1445
1471
|
ApiHidden
|
|
1446
1472
|
};
|
|
1447
1473
|
|
|
1448
|
-
//# debugId=
|
|
1474
|
+
//# debugId=F88308694CAB730E64756E2164756E21
|
|
1449
1475
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -5,12 +5,12 @@
|
|
|
5
5
|
"// Symbol.for, so two copies of @dunx/http in a tree still agree on the key. The\n// marker goes on the method function itself - nothing accumulates at class\n// definition time, so there is no ordering dependence and no cross-file leak.\n// See docs/architecture/http.md, \"Route discovery\".\nimport type { RouteSchemas } from './schema.js';\n\nconst ROUTE = Symbol.for('dunx.route');\nconst CONTROLLER = Symbol.for('dunx.controller');\n\nexport type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * A literal path, or a thunk read at **discovery** rather than at decoration.\n *\n * Discovery runs after every provider has settled, which is the whole point: a\n * path that came out of validated configuration is knowable by then even though\n * a decorator's arguments were evaluated long before the container existed.\n * `OpenApiModule.forRootAsync` is what needs it - it mounts its page and its\n * document where `ConfigService` says. The thunk is called once per discovery,\n * so it has to answer the same thing every time.\n */\nexport type RoutePath = string | (() => string);\n\nexport interface RouteMeta {\n readonly method: HttpMethod;\n readonly path: RoutePath;\n /** The decorator's second argument. `buildRoutes` resolves it once, at boot. */\n readonly options?: RouteSchemas | undefined;\n}\n\nexport const resolvePath = (path: RoutePath): string =>\n typeof path === 'function' ? path() : path;\n\ninterface RouteMarked {\n readonly [ROUTE]?: RouteMeta;\n}\n\ninterface ControllerMarked {\n readonly [CONTROLLER]?: string;\n}\n\nexport const markRoute = (target: object, meta: RouteMeta): void => {\n Object.defineProperty(target, ROUTE, { value: meta, configurable: true });\n};\n\nexport const routeMetaOf = (value: unknown): RouteMeta | undefined =>\n typeof value === 'function' ? (value as RouteMarked)[ROUTE] : undefined;\n\nexport const markController = (target: object, prefix: string): void => {\n Object.defineProperty(target, CONTROLLER, {\n value: prefix,\n configurable: true,\n });\n};\n\n// Plain lookup, not Object.hasOwn: a subclass inherits its base's prefix, so two\n// subclasses of one decorated base collide loudly instead of silently mounting at\n// the root.\nexport const prefixOf = (target: object): string =>\n (target as ControllerMarked)[CONTROLLER] ?? '';\n",
|
|
6
6
|
"import {\n markController,\n markRoute,\n type HttpMethod,\n type RoutePath,\n} from './marker.js';\nimport type { Input, RouteSchemas } from './schema.js';\n\ntype ControllerTarget = abstract new (...args: never[]) => object;\n\nexport const Controller =\n (prefix = '') =>\n <T extends ControllerTarget>(target: T): T => {\n markController(target, prefix);\n return target;\n };\n\n/**\n * `const O` is load-bearing: without it `{ body: CreateNote, status: 201 }` widens\n * to `RouteSchemas` and `Input<typeof opts>` degrades to bare `{ req }`, taking the\n * type check with it.\n *\n * The `M` constraint is the guarantee. A wrongly annotated `input` is a\n * `TS1241` + `TS1270` naming the mismatched property; an unannotated one is\n * `TS7006`. Inference is impossible here - see docs/architecture/constraints.md, \"A route\n * decorator can *check* a handler's input type but cannot *infer* it\".\n */\nconst verb =\n (method: HttpMethod) =>\n <const O extends RouteSchemas>(path: RoutePath = '/', options?: O) =>\n <M extends (input: Input<O>) => unknown>(\n value: M,\n _context: ClassMethodDecoratorContext,\n ): M => {\n markRoute(value, { method, path, options });\n return value;\n };\n\nexport const Get = verb('GET');\nexport const Post = verb('POST');\nexport const Put = verb('PUT');\nexport const Patch = verb('PATCH');\nexport const Delete = verb('DELETE');\n",
|
|
7
7
|
"// The same technique as marker.ts: a decorator sets a symbol property on the\n// function or the class it receives and returns it. Nothing accumulates at class\n// definition time, so there is no ordering dependence and no cross-file leak.\n// See docs/architecture/http.md, \"Route discovery\".\nimport type { Ctor } from '@dunx/core';\nimport type { Middleware } from '../server/middleware.js';\n\n// Symbol.for for the two storage slots, so two copies of @dunx/http in one tree\n// still read each other's records. The keys themselves are unique - see metaKey.\nconst META = Symbol.for('dunx.meta');\nconst GUARDS = Symbol.for('dunx.guards');\n\n/** What a route's decorators resolved to, keyed by `MetaKey.id`. */\nexport type MetaRecord = ReadonlyMap<symbol, unknown>;\n\nexport interface MetaKey<T> {\n /** For error messages and debugging only. Identity is the symbol. */\n readonly name: string;\n readonly id: symbol;\n // Phantom. Never assigned - it exists so MetaKey<readonly string[]> and\n // MetaKey<boolean> are distinct types rather than both being { name, id }.\n readonly reads?: T;\n}\n\n/**\n * A fresh unique symbol per call, so two libraries that both name a key `roles`\n * never read each other's value. Two `metaKey('roles')` calls are two keys.\n */\nexport const metaKey = <T>(name: string): MetaKey<T> => ({\n name,\n id: Symbol(name),\n});\n\ninterface MetaMarked {\n readonly [META]?: MetaRecord;\n}\n\ninterface GuardMarked {\n readonly [GUARDS]?: readonly Ctor<Middleware>[];\n}\n\n/**\n * Copy-on-write, defined as an **own** property. The seed is read with plain\n * lookup, so a subclass starts from its base's record - but the base's Map is\n * never mutated, which is what keeps two subclasses of one base independent.\n */\nconst write = <T>(target: object, key: MetaKey<T>, value: T): void => {\n const record = new Map<symbol, unknown>((target as MetaMarked)[META]);\n record.set(key.id, value);\n Object.defineProperty(target, META, { value: record, configurable: true });\n};\n\n/**\n * The generic setter, valid on a method or on a class. `@Roles` and `@Public` are\n * thin wrappers over it; a user's own key needs nothing else.\n */\nexport const meta =\n <T>(key: MetaKey<T>, value: T) =>\n <F extends object>(target: F): F => {\n write(target, key, value);\n return target;\n };\n\nexport const ROLES: MetaKey<readonly string[]> = metaKey('roles');\nexport const PUBLIC: MetaKey<boolean> = metaKey('public');\nexport const HIDDEN: MetaKey<boolean> = metaKey('hidden');\n/**\n * Set only by the not-found fallback, never by a route. A guard that wants to\n * authenticate unmatched paths rather than 404 them reads this: the miss reports\n * itself as `PUBLIC` so the common case is a 404, and this is how to tell a\n * genuinely public route from one that matched nothing.\n */\nexport const UNMATCHED: MetaKey<boolean> = metaKey('unmatched');\n\nexport const Roles = (...roles: readonly string[]) => meta(ROLES, roles);\nexport const Public = () => meta(PUBLIC, true);\n\n/**\n * Route, but not documented. Valid on a method or on a class.\n *\n * The motivating case is a handler mounted on a wildcard: `@dunx/auth` routes\n * `<basePath>/*` to Better Auth's own handler, which is real and has to be\n * routed, but `*` is not an OpenAPI path template - so documenting it produced an\n * invalid entry named after an internal class, next to the 45 paths\n * `betterAuthDocument` describes properly.\n *\n * It lives here rather than in `@dunx/openapi` because `@dunx/auth` must not\n * depend on the documentation package to say a route is undocumented, and this is\n * where the rest of the route metadata already is.\n */\nexport const ApiHidden = () => meta(HIDDEN, true);\n\n/**\n * Guards are middleware, so they compose rather than override - which is why they\n * are not a `MetaKey`. Valid on a method or on a class.\n */\nexport const UseGuards =\n (...guards: readonly Ctor<Middleware>[]) =>\n <F extends object>(target: F): F => {\n const existing = (target as GuardMarked)[GUARDS] ?? [];\n // An own record means a second @UseGuards on the same target: decorators apply\n // bottom-up, so the later-applied one goes in front and the list reads\n // top-to-bottom. An inherited one means a subclass, whose guards run after\n // the base's - and defineProperty leaves the base's array untouched.\n const merged = Object.hasOwn(target, GUARDS)\n ? [...guards, ...existing]\n : [...existing, ...guards];\n Object.defineProperty(target, GUARDS, {\n value: merged,\n configurable: true,\n });\n return target;\n };\n\nexport const guardsOf = (target: object): readonly Ctor<Middleware>[] =>\n (target as GuardMarked)[GUARDS] ?? [];\n\nexport const metaOf = (target: object): MetaRecord | undefined =>\n (target as MetaMarked)[META];\n\n/**\n * Later targets win, so `mergeMeta(klass, handler)` is the handler-then-class\n * resolution `RouteContext.get` exposes. Called once per route at boot.\n */\nexport const mergeMeta = (...targets: readonly object[]): MetaRecord => {\n const merged = new Map<symbol, unknown>();\n for (const target of targets) {\n const record = (target as MetaMarked)[META];\n if (record) for (const [id, value] of record) merged.set(id, value);\n }\n return merged;\n};\n",
|
|
8
|
-
"import type { Ctor } from '@dunx/core';\nimport type { Middleware } from '../server/middleware.js';\nimport {\n prefixOf,\n resolvePath,\n routeMetaOf,\n type HttpMethod,\n} from './marker.js';\nimport { guardsOf, mergeMeta, metaOf, type MetaRecord } from './metadata.js';\nimport type { RouteInput, RouteSchemas } from './schema.js';\n\nexport interface DiscoveredRoute {\n readonly method: HttpMethod;\n readonly path: string;\n readonly controller: string;\n readonly handlerName: string;\n readonly handler: (input: RouteInput) => unknown;\n /** Schemas and status from the decorator, carried through to `buildRoutes`. */\n readonly options?: RouteSchemas | undefined;\n /** The class's metadata merged under the handler's, which wins. Resolved here, once. */\n readonly meta?: MetaRecord | undefined;\n /**\n * The class's own record, unmerged. `meta` above is the resolved view, where a\n * handler's value **replaces** the class's - which is what `@Roles` and\n * `@Public` want and what a value composed of independent fields does not:\n * `@ApiDoc`'s class-level `tags` have to survive a method-level `summary`, and\n * a per-field merge cannot be recovered from an already-collapsed record.\n */\n readonly classMeta?: MetaRecord | undefined;\n /** Class-level `@UseGuards` first, then method-level. `buildRoutes` resolves them. */\n readonly guards?: readonly Ctor<Middleware>[] | undefined;\n}\n\nexport const joinPath = (prefix: string, path: string): string => {\n const joined = `/${prefix}/${path}`.replace(/\\/{2,}/g, '/');\n return joined.length > 1 ? joined.replace(/\\/$/, '') : '/';\n};\n\n/**\n * Walks the prototype chain of a constructed controller and collects every marked\n * method. Most-derived wins on a repeated name; an undecorated override does not\n * shadow its decorated base, and dispatch still lands on the override because the\n * handler is bound off the instance.\n */\nexport const discoverRoutes = (\n instance: object,\n): readonly DiscoveredRoute[] => {\n const klass = instance.constructor;\n const prefix = prefixOf(klass);\n const classGuards = guardsOf(klass);\n const members = instance as Record<string, (input: RouteInput) => unknown>;\n const routes: DiscoveredRoute[] = [];\n const seen = new Set<string>();\n\n for (\n let proto = Object.getPrototypeOf(instance) as object | null;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n for (const [name, descriptor] of Object.entries(\n Object.getOwnPropertyDescriptors(proto),\n )) {\n if (name === 'constructor' || seen.has(name)) continue;\n\n const meta = routeMetaOf(descriptor.value);\n if (!meta) continue;\n\n seen.add(name);\n // The marked function, not the instance member: a decorator wrote onto this\n // object, and it is the only place its metadata can have come from.\n const marked = descriptor.value as object;\n routes.push({\n method: meta.method,\n path: joinPath(prefix, resolvePath(meta.path)),\n controller: klass.name,\n handlerName: name,\n handler: members[name]!.bind(instance),\n options: meta.options,\n meta: mergeMeta(klass, marked),\n classMeta: metaOf(klass),\n guards: [...classGuards, ...guardsOf(marked)],\n });\n }\n }\n\n return routes;\n};\n",
|
|
8
|
+
"import type { Ctor, ModuleRef } from '@dunx/core';\nimport type { Middleware } from '../server/middleware.js';\nimport {\n prefixOf,\n resolvePath,\n routeMetaOf,\n type HttpMethod,\n} from './marker.js';\nimport { guardsOf, mergeMeta, metaOf, type MetaRecord } from './metadata.js';\nimport type { RouteInput, RouteSchemas } from './schema.js';\n\nexport interface DiscoveredRoute {\n readonly method: HttpMethod;\n readonly path: string;\n readonly controller: string;\n readonly handlerName: string;\n readonly handler: (input: RouteInput) => unknown;\n /** Schemas and status from the decorator, carried through to `buildRoutes`. */\n readonly options?: RouteSchemas | undefined;\n /** The class's metadata merged under the handler's, which wins. Resolved here, once. */\n readonly meta?: MetaRecord | undefined;\n /**\n * The class's own record, unmerged. `meta` above is the resolved view, where a\n * handler's value **replaces** the class's - which is what `@Roles` and\n * `@Public` want and what a value composed of independent fields does not:\n * `@ApiDoc`'s class-level `tags` have to survive a method-level `summary`, and\n * a per-field merge cannot be recovered from an already-collapsed record.\n */\n readonly classMeta?: MetaRecord | undefined;\n /** Class-level `@UseGuards` first, then method-level. `buildRoutes` resolves them. */\n readonly guards?: readonly Ctor<Middleware>[] | undefined;\n /**\n * The module that declared this route's controller, and the middleware that module\n * declared - applied to these routes and to nothing else.\n *\n * Filled by `HttpFactory`, which is the only place that knows the module graph.\n * `module` is carried alongside so each entry resolves from **that module's scope**,\n * which is the whole point: module middleware can inject providers the module keeps\n * private.\n */\n readonly module?: ModuleRef | undefined;\n readonly moduleMiddleware?: readonly Ctor<Middleware>[] | undefined;\n}\n\nexport const joinPath = (prefix: string, path: string): string => {\n const joined = `/${prefix}/${path}`.replace(/\\/{2,}/g, '/');\n return joined.length > 1 ? joined.replace(/\\/$/, '') : '/';\n};\n\n/**\n * Walks the prototype chain of a constructed controller and collects every marked\n * method. Most-derived wins on a repeated name; an undecorated override does not\n * shadow its decorated base, and dispatch still lands on the override because the\n * handler is bound off the instance.\n */\nexport const discoverRoutes = (\n instance: object,\n): readonly DiscoveredRoute[] => {\n const klass = instance.constructor;\n const prefix = prefixOf(klass);\n const classGuards = guardsOf(klass);\n const members = instance as Record<string, (input: RouteInput) => unknown>;\n const routes: DiscoveredRoute[] = [];\n const seen = new Set<string>();\n\n for (\n let proto = Object.getPrototypeOf(instance) as object | null;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n for (const [name, descriptor] of Object.entries(\n Object.getOwnPropertyDescriptors(proto),\n )) {\n if (name === 'constructor' || seen.has(name)) continue;\n\n const meta = routeMetaOf(descriptor.value);\n if (!meta) continue;\n\n seen.add(name);\n // The marked function, not the instance member: a decorator wrote onto this\n // object, and it is the only place its metadata can have come from.\n const marked = descriptor.value as object;\n routes.push({\n method: meta.method,\n path: joinPath(prefix, resolvePath(meta.path)),\n controller: klass.name,\n handlerName: name,\n handler: members[name]!.bind(instance),\n options: meta.options,\n meta: mergeMeta(klass, marked),\n classMeta: metaOf(klass),\n guards: [...classGuards, ...guardsOf(marked)],\n });\n }\n }\n\n return routes;\n};\n",
|
|
9
9
|
"import type { BunRequest, Server } from 'bun';\nimport { AppError } from '@dunx/core';\n\nexport interface AddressSource {\n readonly server: Server<unknown>;\n readonly trustProxy: boolean;\n}\n\n// Kept off the class so `ClientAddress`'s public shape stays `of(req)`. Per\n// instance rather than module-level, because two apps in one process (every test\n// file) must not share a server.\nconst sources = new WeakMap<ClientAddress, AddressSource>();\n\n/**\n * The client's address, honouring the `'trust proxy'` setting. Every class is\n * injectable, so `inject(ClientAddress)` in a middleware or controller needs no\n * registration; `app.clientIp(req)` is the same instance.\n */\nexport class ClientAddress {\n of(req: BunRequest): string | undefined {\n const source = sources.get(this);\n if (!source) {\n throw new AppError(\n 'ClientAddress has no server yet. The address comes from the live Bun ' +\n 'server, so it is only available once listen() has run.',\n );\n }\n\n if (source.trustProxy) {\n const forwarded = req.headers\n .get('x-forwarded-for')\n ?.split(',')[0]\n ?.trim();\n if (forwarded) return forwarded;\n }\n return source.server.requestIP(req)?.address;\n }\n}\n\n/** Internal: `listen()` hands the bound server to the resolved singleton. */\nexport const attachAddressSource = (\n target: ClientAddress,\n source: AddressSource,\n): void => {\n sources.set(target, source);\n};\n",
|
|
10
10
|
"import type { DiscoveredRoute } from '../route/discover.js';\nimport type { HttpMethod } from '../route/marker.js';\nimport type { MetaKey, MetaRecord } from '../route/metadata.js';\n\n/**\n * Which route the middleware is running for, and what that route's decorators\n * declared. `get` resolves the handler's metadata first and the controller class's\n * second - the usual override direction for handler-over-class metadata.\n */\nexport interface RouteContext {\n readonly controller: string;\n readonly handler: string;\n readonly method: HttpMethod;\n readonly path: string;\n get<T>(key: MetaKey<T>): T | undefined;\n}\n\nconst EMPTY: MetaRecord = new Map();\n\n/**\n * One frozen context per route, built when the table is built and closed over by\n * the chain. The merge already happened at discovery, so `get` is a Map lookup -\n * not a prototype walk, and nothing is read per request.\n */\nexport const buildContext = (route: DiscoveredRoute): RouteContext => {\n const record = route.meta ?? EMPTY;\n return Object.freeze({\n controller: route.controller,\n handler: route.handlerName,\n method: route.method,\n path: route.path,\n get: <T>(key: MetaKey<T>): T | undefined =>\n record.get(key.id) as T | undefined,\n });\n};\n",
|
|
11
11
|
"import type { RouteHandler } from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\nexport type CorsOrigin =\n | string\n | readonly string[]\n | ((origin: string) => boolean);\n\nexport interface CorsOptions {\n /**\n * `'*'` by default. A concrete string, a list, or a predicate all answer with the\n * caller's own origin only when it is allowed - a request from anywhere else gets\n * no CORS headers at all, which is what makes the browser block it.\n */\n readonly origin?: CorsOrigin;\n /** Defaults to the methods actually declared on the path. */\n readonly methods?: readonly string[];\n /** Echoes `Access-Control-Request-Headers` when omitted. */\n readonly allowedHeaders?: readonly string[];\n readonly exposedHeaders?: readonly string[];\n readonly credentials?: boolean;\n /** Seconds a browser may cache the preflight for. */\n readonly maxAge?: number;\n}\n\nconst ORIGIN = 'access-control-allow-origin';\n\n/**\n * `*` is illegal alongside credentials - a browser rejects the pair - so a\n * credentialed wildcard reflects the caller instead.\n */\nconst allowedOrigin = (\n options: CorsOptions,\n requested: string | null,\n): string | undefined => {\n const origin = options.origin ?? '*';\n\n if (typeof origin === 'string') {\n if (origin !== '*') return origin === requested ? origin : undefined;\n if (!options.credentials) return '*';\n return requested ?? undefined;\n }\n if (requested === null) return undefined;\n\n const allowed =\n typeof origin === 'function'\n ? origin(requested)\n : origin.includes(requested);\n return allowed ? requested : undefined;\n};\n\nconst applyCors = (\n options: CorsOptions,\n req: Request,\n response: Response,\n): Response => {\n const origin = allowedOrigin(options, req.headers.get('origin'));\n if (origin === undefined) return response;\n\n response.headers.set(ORIGIN, origin);\n // The response body varies by request origin unless every origin gets the same\n // wildcard, so a shared cache must not serve one origin's copy to another.\n if (origin !== '*') response.headers.append('vary', 'Origin');\n if (options.credentials) {\n response.headers.set('access-control-allow-credentials', 'true');\n }\n if (options.exposedHeaders?.length) {\n response.headers.set(\n 'access-control-expose-headers',\n options.exposedHeaders.join(', '),\n );\n }\n return response;\n};\n\n/** Adds the response-side CORS headers. One extra closure per route, at boot. */\nexport const withCors = (\n options: CorsOptions,\n handler: RouteHandler,\n): RouteHandler => {\n return async (req) => applyCors(options, req, await handler(req));\n};\n\n/**\n * `Bun.serve({ routes })` answers a method miss with 404, so a preflight cannot be\n * inferred - every CORS-enabled path gets its own `OPTIONS` handler, built at boot\n * from the methods that path actually declares.\n */\nexport const preflight = (\n options: CorsOptions,\n methods: readonly string[],\n): RouteHandler => {\n const allowMethods = (options.methods ?? methods).join(', ');\n\n return async (req) => {\n const response = applyCors(\n options,\n req,\n new Response(null, { status: HttpStatusCode.NO_CONTENT }),\n );\n // Origin not allowed: 204 with no CORS headers, which fails the preflight.\n if (!response.headers.has(ORIGIN)) return response;\n\n response.headers.set('access-control-allow-methods', allowMethods);\n\n const allowHeaders =\n options.allowedHeaders ??\n (req.headers.get('access-control-request-headers') ?? '')\n .split(',')\n .map((header) => header.trim())\n .filter((header) => header.length > 0);\n if (allowHeaders.length > 0) {\n response.headers.set(\n 'access-control-allow-headers',\n allowHeaders.join(', '),\n );\n }\n if (options.maxAge !== undefined) {\n response.headers.set('access-control-max-age', String(options.maxAge));\n }\n return response;\n };\n};\n",
|
|
12
|
-
"import { AppError, ConsoleLogger, type Logger } from '@dunx/core';\nimport { HttpStatusCode } from './status.js';\n\nexport class HttpError extends AppError {\n override name = 'HttpError';\n\n constructor(\n readonly status: number,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n }\n}\nObject.defineProperty(HttpError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly status: number\" }, { unresolved: \"message: string\" }, ErrorOptions],\n});\n\n/** Which declared schema rejected the request. */\nexport type InputSource = 'body' | 'query' | 'params';\n\n/** A Standard Schema issue, flattened: `path` is dotted, or absent at the root. */\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: string;\n}\n\n/**\n * A declared schema rejected the input. Always a 400, and the issues survive into\n * the response body - a caller cannot fix what it cannot see.\n */\nexport class ValidationError extends HttpError {\n override name = 'ValidationError';\n\n constructor(\n readonly source: InputSource,\n readonly issues: readonly ValidationIssue[],\n ) {\n super(HttpStatusCode.BAD_REQUEST, `Invalid ${source}`);\n }\n}\nObject.defineProperty(ValidationError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly source: InputSource\" }, { unresolved: \"readonly issues: readonly ValidationIssue[]\" }],\n});\n\nexport type ErrorMapper = (error: unknown, req: Request) => Response;\n\n/**\n * The mapper `HttpFactory` installs unless `onError` replaces it, built from the\n * app's **bound** `Logger` - so a service that imported `@dunx/infra/logger` gets\n * the stack as one `@arkv/logger` entry, sanitized and shaped like every other.\n *\n * An `HttpError` is not logged here at all: the status is the whole record, and\n * `RequestLoggingMiddleware` already writes the 4xx line. Only an error nothing\n * declared - the one that becomes a 500 - is worth a stack.\n *\n * The error goes in as its own argument rather than as a field of an object.\n * `JSON.stringify(new Error('x'))` is `{}`, so `{ err: error }` would drop the\n * stack; every `Logger` implementation picks an `Error` argument out and\n * serialises it.\n */\nexport const errorMapper =\n (logger: Logger): ErrorMapper =>\n (error) => {\n if (error instanceof ValidationError) {\n return Response.json(\n { error: error.message, status: error.status, issues: error.issues },\n { status: error.status },\n );\n }\n if (error instanceof HttpError) {\n return Response.json(\n { error: error.message, status: error.status },\n { status: error.status },\n );\n }\n logger.error('Unhandled error', error);\n return Response.json(\n {\n error: 'Internal Server Error',\n status: HttpStatusCode.INTERNAL_SERVER_ERROR,\n },\n { status: HttpStatusCode.INTERNAL_SERVER_ERROR },\n );\n };\n\n/**\n * The same mapper with no container behind it, for `buildRoutes` and\n * `buildFallback` called directly. It writes through core's `ConsoleLogger`, which\n * is one JSON line - the point being that nothing in this package ever reaches for\n * `console.error` and emits a multi-line dump a collector reads as several broken\n * records. An app gets {@link errorMapper} over its own bound logger instead.\n */\nexport const defaultErrorMapper: ErrorMapper = errorMapper(new ConsoleLogger());\n",
|
|
13
|
-
"import {\n collectModules,\n AppError,\n AppFactory,\n Logger,\n provide,\n readControllers,\n RequestContext,\n type DynamicModule,\n type ModuleRef,\n} from '@dunx/core';\nimport { discoverRoutes, type DiscoveredRoute } from '../route/discover.js';\nimport { buildWebSocket } from '../ws/adapter.js';\nimport { discoverGateways } from '../ws/discover.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport {\n HttpApplication,\n type HttpApp,\n type HttpOptions,\n} from './application.js';\nimport { RequestLoggingMiddleware } from './request-logging.js';\nimport { assertNoCollisions } from './routes.js';\n\nexport type { HttpApp, HttpOptions } from './application.js';\n\n// Bound around the user's root so `PubSub` is injectable without importing\n// anything. Its name is what a duplicate binding of PubSub would be reported\n// against, which is why it is a named class and not an object literal.\nclass HttpModule {}\n\nexport class HttpFactory {\n /**\n * Boots the container, discovers every controller's routes and every gateway's\n * handlers, and rejects a collision in either. The `Bun.serve` route table itself\n * is built by `listen()`, so `setGlobalPrefix`, `use`, `set` and `enableCors` can\n * still affect it.\n */\n static async create(\n root: ModuleRef,\n options: HttpOptions = {},\n ): Promise<HttpApp> {\n // Bound here rather than left to self-binding, because its constructor takes\n // the options object as well as two injectables. `Logger` and\n // `RequestContext` always resolve: @dunx/core binds a default for each.\n const logging = provide(RequestLoggingMiddleware, {\n useFactory: (logger: Logger, context: RequestContext) =>\n new RequestLoggingMiddleware(\n logger,\n context,\n typeof options.requestLogging === 'object'\n ? options.requestLogging\n : {},\n ),\n inject: [Logger, RequestContext] as const,\n });\n\n const scope: DynamicModule = {\n module: HttpModule,\n imports: [root],\n providers
|
|
12
|
+
"import { AppError, ConsoleLogger, type Ctor, type Logger } from '@dunx/core';\nimport { HttpStatusCode } from './status.js';\n\nexport class HttpError extends AppError {\n override name = 'HttpError';\n\n constructor(\n readonly status: number,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n }\n}\nObject.defineProperty(HttpError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly status: number\" }, { unresolved: \"message: string\" }, ErrorOptions],\n});\n\n/** Which declared schema rejected the request. */\nexport type InputSource = 'body' | 'query' | 'params';\n\n/** A Standard Schema issue, flattened: `path` is dotted, or absent at the root. */\nexport interface ValidationIssue {\n readonly message: string;\n readonly path?: string;\n}\n\n/**\n * A declared schema rejected the input. Always a 400, and the issues survive into\n * the response body - a caller cannot fix what it cannot see.\n */\nexport class ValidationError extends HttpError {\n override name = 'ValidationError';\n\n constructor(\n readonly source: InputSource,\n readonly issues: readonly ValidationIssue[],\n ) {\n super(HttpStatusCode.BAD_REQUEST, `Invalid ${source}`);\n }\n}\nObject.defineProperty(ValidationError, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"readonly source: InputSource\" }, { unresolved: \"readonly issues: readonly ValidationIssue[]\" }],\n});\n\nexport type ErrorMapper = (error: unknown, req: Request) => Response;\n\n/**\n * The class form of {@link ErrorMapper}, and the one to reach for in an app.\n *\n * A mapper is a function, which means it cannot inject: the interesting ones need\n * the app's config to decide how much of an error to reveal, or its `Logger` to\n * record the ones that became a 500. dunx's own default proves the point - it is\n * `errorMapper(logger)`, a curried factory, because currying was the only way to\n * hand a function a dependency.\n *\n * A filter is resolved **from the container**, exactly as `HttpOptions.middleware`\n * entries are, so it takes whatever it needs as constructor parameters:\n *\n * ```ts\n * export class AppErrorFilter extends ErrorFilter {\n * constructor(\n * private readonly logger: Logger,\n * private readonly config: AppConfigService,\n * ) {}\n *\n * catch(error: unknown, req: Request): Response {\n * ...\n * }\n * }\n *\n * // It is a provider like any other, so it goes in a module:\n * @Module({ providers: [AppErrorFilter] })\n * // and then:\n * HttpFactory.create(root, { onError: AppErrorFilter });\n * ```\n *\n * `abstract class` rather than an interface, so it is a runtime value and therefore\n * usable as an injection token - an app that wants to swap filters by binding one\n * can. Extending it is optional: `onError` accepts any class with a matching\n * `catch`, because the check is structural.\n *\n * The method is `catch` to match the vocabulary of the thing it replaces, NestJS's\n * `ExceptionFilter.catch`. A filter that cannot handle an error should rethrow it,\n * or delegate to `defaultErrorMapper`.\n */\nexport abstract class ErrorFilter {\n abstract catch(error: unknown, req: Request): Response;\n}\n\n/**\n * What `onError` accepts. A bare mapper still works and is the cheaper thing for a\n * filter with no dependencies; a class is what an app that needs one uses.\n */\nexport type ErrorHandler = ErrorMapper | Ctor<ErrorFilter>;\n\n/**\n * Whether `onError` was given a class rather than a mapper.\n *\n * Both are `typeof === 'function'`, so the discriminator is the prototype carrying\n * a `catch`: a class declaration always has one, and neither an arrow function nor\n * a `function` expression ever does. Checking `prototype` alone would be wrong -\n * `function mapper() {}` has an empty one.\n */\nexport const isErrorFilter = (\n handler: ErrorHandler,\n): handler is Ctor<ErrorFilter> =>\n typeof handler === 'function' &&\n // Narrowed through a structural shape rather than `Ctor`: a construct signature\n // has no `prototype` in the type system, so `Partial<Ctor<T>>` cannot see it.\n typeof (handler as { prototype?: { catch?: unknown } }).prototype?.catch ===\n 'function';\n\n/**\n * Narrows an `ErrorHandler` to the mapper the request path actually calls.\n *\n * `resolve` is typed for this one token rather than generically: the only thing ever\n * looked up here is the filter, and a `<T>(token: Ctor<T>) => T` signature makes\n * every caller - a test included - satisfy a polymorphic contract it does not need.\n */\nexport const toErrorMapper = (\n handler: ErrorHandler,\n resolve: (token: Ctor<ErrorFilter>) => ErrorFilter,\n): ErrorMapper =>\n isErrorFilter(handler)\n ? (error, req) => resolve(handler).catch(error, req)\n : handler;\n\n/**\n * The mapper `HttpFactory` installs unless `onError` replaces it, built from the\n * app's **bound** `Logger` - so a service that imported `@dunx/infra/logger` gets\n * the stack as one `@arkv/logger` entry, sanitized and shaped like every other.\n *\n * An `HttpError` is not logged here at all: the status is the whole record, and\n * `RequestLoggingMiddleware` already writes the 4xx line. Only an error nothing\n * declared - the one that becomes a 500 - is worth a stack.\n *\n * The error goes in as its own argument rather than as a field of an object.\n * `JSON.stringify(new Error('x'))` is `{}`, so `{ err: error }` would drop the\n * stack; every `Logger` implementation picks an `Error` argument out and\n * serialises it.\n */\nexport const errorMapper =\n (logger: Logger): ErrorMapper =>\n (error) => {\n if (error instanceof ValidationError) {\n return Response.json(\n { error: error.message, status: error.status, issues: error.issues },\n { status: error.status },\n );\n }\n if (error instanceof HttpError) {\n return Response.json(\n { error: error.message, status: error.status },\n { status: error.status },\n );\n }\n logger.error('Unhandled error', error);\n return Response.json(\n {\n error: 'Internal Server Error',\n status: HttpStatusCode.INTERNAL_SERVER_ERROR,\n },\n { status: HttpStatusCode.INTERNAL_SERVER_ERROR },\n );\n };\n\n/**\n * The same mapper with no container behind it, for `buildRoutes` and\n * `buildFallback` called directly. It writes through core's `ConsoleLogger`, which\n * is one JSON line - the point being that nothing in this package ever reaches for\n * `console.error` and emits a multi-line dump a collector reads as several broken\n * records. An app gets {@link errorMapper} over its own bound logger instead.\n */\nexport const defaultErrorMapper: ErrorMapper = errorMapper(new ConsoleLogger());\n",
|
|
13
|
+
"import {\n collectModules,\n AppError,\n AppFactory,\n Logger,\n provide,\n readControllers,\n RequestContext,\n type Ctor,\n type DynamicModule,\n type ModuleRef,\n} from '@dunx/core';\nimport { discoverRoutes, type DiscoveredRoute } from '../route/discover.js';\nimport { buildWebSocket } from '../ws/adapter.js';\nimport { discoverGateways } from '../ws/discover.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport {\n HttpApplication,\n type HttpApp,\n type HttpOptions,\n} from './application.js';\nimport type { Middleware } from './middleware.js';\nimport { RequestLoggingMiddleware } from './request-logging.js';\nimport { assertNoCollisions } from './routes.js';\n\nexport type { HttpApp, HttpOptions } from './application.js';\n\n// Bound around the user's root so `PubSub` is injectable without importing\n// anything. Its name is what a duplicate binding of PubSub would be reported\n// against, which is why it is a named class and not an object literal.\n//\n// `global: true` is what makes that \"without importing anything\" true under module\n// scoping. This module *imports* the root rather than being imported by it, and\n// visibility only flows from an import's exports to its importer - so without global\n// these bindings would be invisible to every module in the app, which is the opposite\n// of the intent. They are framework services with no module for an app to import.\nclass HttpModule {}\n\nexport class HttpFactory {\n /**\n * Boots the container, discovers every controller's routes and every gateway's\n * handlers, and rejects a collision in either. The `Bun.serve` route table itself\n * is built by `listen()`, so `setGlobalPrefix`, `use`, `set` and `enableCors` can\n * still affect it.\n */\n static async create(\n root: ModuleRef,\n options: HttpOptions = {},\n ): Promise<HttpApp> {\n // Bound here rather than left to self-binding, because its constructor takes\n // the options object as well as two injectables. `Logger` and\n // `RequestContext` always resolve: @dunx/core binds a default for each.\n const logging = provide(RequestLoggingMiddleware, {\n useFactory: (logger: Logger, context: RequestContext) =>\n new RequestLoggingMiddleware(\n logger,\n context,\n typeof options.requestLogging === 'object'\n ? options.requestLogging\n : {},\n ),\n inject: [Logger, RequestContext] as const,\n });\n\n const providers =\n options.requestLogging === false ? [PubSub] : [PubSub, logging];\n const scope: DynamicModule = {\n module: HttpModule,\n global: true,\n imports: [root],\n providers,\n exports: providers.map((entry) =>\n typeof entry === 'function' ? entry : entry.token,\n ),\n };\n // Spread rather than passed through, because `exactOptionalPropertyTypes`\n // separates an absent `overrides` from one explicitly set to undefined.\n const app = await AppFactory.create(\n scope,\n options.overrides ? { overrides: options.overrides } : {},\n );\n const modules = collectModules(scope);\n\n const discovered: DiscoveredRoute[] = [];\n for (const module of modules) {\n // The module's own middleware, applied to the routes its controllers declare\n // and to nothing else. Carried on each route with the module it came from, so it\n // resolves from that module's scope rather than the app's root.\n const moduleMiddleware = module.options.middleware ?? [];\n for (const controller of readControllers(module)) {\n const routes = discoverRoutes(\n app.get(controller, module.ref) as object,\n );\n if (routes.length === 0) {\n throw new AppError(\n `${controller.name} is registered as a controller but declares no routes. ` +\n 'Add a @Get/@Post/... method, or move it to providers.',\n );\n }\n discovered.push(\n ...routes.map((route) => ({\n ...route,\n module: module.ref,\n ...(moduleMiddleware.length === 0\n ? {}\n : {\n moduleMiddleware:\n moduleMiddleware as readonly Ctor<Middleware>[],\n }),\n })),\n );\n }\n }\n // Eagerly, so a wiring error still surfaces from create() rather than waiting\n // for listen(). A uniform global prefix cannot introduce a new one.\n assertNoCollisions(discovered);\n\n const gateways = discoverGateways(modules, (token) => app.get(token));\n // Handler collisions and two gateways on one path are boot errors too, and the\n // websocket object is built once here rather than per connection.\n const websocket =\n gateways.length > 0\n ? buildWebSocket(gateways, options.websocket)\n : undefined;\n\n // `root` is the app's own module, so global middleware and the error filter\n // resolve as the app sees them rather than as this wrapper does.\n return new HttpApplication(app, discovered, options, root, websocket);\n }\n}\n",
|
|
14
14
|
"/**\n * The whole wire protocol: one JSON object, an event name, and a payload. It is\n * only ever read for a gateway that declares at least one `@OnMessage(event)`\n * handler - a gateway with only a raw `@OnMessage()` never parses anything.\n */\nexport interface Envelope {\n readonly event: string;\n readonly data?: unknown;\n}\n\nexport const encode = (event: string, data: unknown): string =>\n JSON.stringify({ event, data });\n\n/**\n * `undefined` for anything that is not an envelope - binary frames, invalid JSON,\n * a non-object, or a missing `event`. Those fall through to the raw handler\n * instead of being rejected here.\n */\nexport const decode = (message: string | Buffer): Envelope | undefined => {\n if (typeof message !== 'string') return undefined;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch {\n return undefined;\n }\n\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n const { event, data } = parsed as { event?: unknown; data?: unknown };\n return typeof event === 'string' ? { event, data } : undefined;\n};\n",
|
|
15
15
|
"import { AppError } from '@dunx/core';\nimport type {\n DiscoveredGateway,\n DiscoveredHandler,\n Invoke,\n} from './discover.js';\nimport { HandlerKind } from './marker.js';\n\n/**\n * One gateway reduced to direct references, built once at boot. Dispatch reads\n * these fields and nothing else - no lookup, no metadata, no DI per message.\n */\nexport interface GatewayRuntime {\n readonly name: string;\n readonly path: string;\n readonly upgrade: Invoke | undefined;\n readonly open: Invoke | undefined;\n readonly close: Invoke | undefined;\n readonly drain: Invoke | undefined;\n readonly ping: Invoke | undefined;\n readonly pong: Invoke | undefined;\n /** The raw `@OnMessage()` catch-all: every frame no named event claimed. */\n readonly raw: Invoke | undefined;\n readonly events: ReadonlyMap<string, Invoke>;\n}\n\n/** What two handlers would have to share to be a collision. */\nconst slotOf = (handler: DiscoveredHandler): string =>\n handler.kind === HandlerKind.MESSAGE && handler.event !== undefined\n ? `message ${JSON.stringify(handler.event)}`\n : handler.kind;\n\nexport const buildRuntime = (gateway: DiscoveredGateway): GatewayRuntime => {\n if (gateway.handlers.length === 0) {\n throw new AppError(\n `${gateway.name} is registered as a gateway but declares no handlers. ` +\n 'Add an @OnMessage/@OnOpen/... method, or drop the @Gateway decorator.',\n );\n }\n\n const owners = new Map<string, DiscoveredHandler>();\n const events = new Map<string, Invoke>();\n\n for (const handler of gateway.handlers) {\n const slot = slotOf(handler);\n const existing = owners.get(slot);\n if (existing) {\n throw new AppError(\n `Handler collision in ${gateway.name}: ${slot} is claimed by ` +\n `${existing.method}() and by ${handler.method}(). One handler per event.`,\n );\n }\n owners.set(slot, handler);\n if (handler.kind === HandlerKind.MESSAGE && handler.event !== undefined) {\n events.set(handler.event, handler.invoke);\n }\n }\n\n const at = (slot: string): Invoke | undefined => owners.get(slot)?.invoke;\n\n return {\n name: gateway.name,\n path: gateway.path,\n upgrade: at(HandlerKind.UPGRADE),\n open: at(HandlerKind.OPEN),\n close: at(HandlerKind.CLOSE),\n drain: at(HandlerKind.DRAIN),\n ping: at(HandlerKind.PING),\n pong: at(HandlerKind.PONG),\n raw: at(HandlerKind.MESSAGE),\n events,\n };\n};\n\n/**\n * One route per gateway path, so two gateways on one path would mean one of them\n * could never receive a connection. That is a boot error naming both.\n */\nexport const buildGateways = (\n discovered: readonly DiscoveredGateway[],\n): ReadonlyMap<string, GatewayRuntime> => {\n const byPath = new Map<string, GatewayRuntime>();\n\n for (const gateway of discovered) {\n const existing = byPath.get(gateway.path);\n if (existing) {\n throw new AppError(\n `Gateway path collision: ${gateway.path} is served by ${existing.name} ` +\n `and by ${gateway.name}. One gateway per path.`,\n );\n }\n byPath.set(gateway.path, buildRuntime(gateway));\n }\n\n return byPath;\n};\n\nexport const someHandler = (\n gateways: Iterable<GatewayRuntime>,\n pick: (gateway: GatewayRuntime) => Invoke | undefined,\n): boolean => {\n for (const gateway of gateways) if (pick(gateway) !== undefined) return true;\n return false;\n};\n",
|
|
16
16
|
"// Symbol.for, so two copies of @dunx/http in a tree still agree on the key. The\n// marker goes on the method function itself - nothing accumulates at class\n// definition time, so there is no ordering dependence and no cross-file leak.\n// Same technique as the route marker; see docs/ARCHITECTURE.md,\n// \"Route discovery\".\nconst HANDLER = Symbol.for('dunx.ws.handler');\nconst GATEWAY = Symbol.for('dunx.ws.gateway');\n\nexport const HandlerKind = Object.freeze({\n UPGRADE: 'upgrade',\n OPEN: 'open',\n MESSAGE: 'message',\n CLOSE: 'close',\n DRAIN: 'drain',\n PING: 'ping',\n PONG: 'pong',\n} as const);\nexport type HandlerKind = (typeof HandlerKind)[keyof typeof HandlerKind];\n\nexport interface HandlerMeta {\n readonly kind: HandlerKind;\n /**\n * Only meaningful for a message handler: the envelope event it claims.\n * `undefined` is the raw catch-all that sees every unrouted frame.\n */\n readonly event: string | undefined;\n}\n\ninterface HandlerMarked {\n readonly [HANDLER]?: HandlerMeta;\n}\n\ninterface GatewayMarked {\n readonly [GATEWAY]?: string;\n}\n\nexport const markHandler = (target: object, meta: HandlerMeta): void => {\n Object.defineProperty(target, HANDLER, { value: meta, configurable: true });\n};\n\nexport const handlerMetaOf = (value: unknown): HandlerMeta | undefined =>\n typeof value === 'function' ? (value as HandlerMarked)[HANDLER] : undefined;\n\nexport const markGateway = (target: object, path: string): void => {\n Object.defineProperty(target, GATEWAY, { value: path, configurable: true });\n};\n\n// Plain lookup, not Object.hasOwn: a subclass inherits its base's path, so two\n// subclasses of one decorated base collide loudly instead of silently sharing\n// the root path.\nexport const gatewayPathOf = (target: object): string =>\n (target as GatewayMarked)[GATEWAY] ?? '/';\n\n/**\n * `@Gateway` is what separates a gateway from every other provider in the same\n * module, so unlike `@Controller` it is required rather than decorative.\n */\nexport const isGateway = (target: object): boolean =>\n (target as GatewayMarked)[GATEWAY] !== undefined;\n",
|
|
@@ -18,16 +18,16 @@
|
|
|
18
18
|
"import {\n AppError,\n type Ctor,\n type InjectionToken,\n type ProviderEntry,\n type ResolvedModule,\n} from '@dunx/core';\nimport {\n gatewayPathOf,\n handlerMetaOf,\n isGateway,\n type HandlerKind,\n type HandlerMeta,\n} from './marker.js';\n\n/**\n * A discovered handler, already bound to its instance. Every kind has a different\n * signature, so the runtime holds them loosely and the decorators are what keep\n * the declared shapes honest.\n */\nexport type Invoke = (...args: readonly unknown[]) => unknown;\n\nexport interface DiscoveredHandler {\n readonly kind: HandlerKind;\n readonly event: string | undefined;\n readonly method: string;\n readonly invoke: Invoke;\n}\n\nexport interface DiscoveredGateway {\n readonly name: string;\n readonly path: string;\n readonly handlers: readonly DiscoveredHandler[];\n}\n\n/** `chat` and `/chat/` both become `/chat`; an empty path becomes `/`. */\nexport const normalizePath = (path: string): string => {\n const joined = `/${path}`.replace(/\\/{2,}/g, '/');\n return joined.length > 1 ? joined.replace(/\\/$/, '') : '/';\n};\n\n/** Every marked method on a prototype chain, most-derived first, names deduped. */\nconst eachHandler = (\n start: object | null,\n): readonly [string, HandlerMeta][] => {\n const found: [string, HandlerMeta][] = [];\n const seen = new Set<string>();\n\n for (\n let proto = start;\n proto !== null && proto !== Object.prototype;\n proto = Object.getPrototypeOf(proto) as object | null\n ) {\n for (const [name, descriptor] of Object.entries(\n Object.getOwnPropertyDescriptors(proto),\n )) {\n if (name === 'constructor' || seen.has(name)) continue;\n\n const meta = handlerMetaOf(descriptor.value);\n if (!meta) continue;\n\n seen.add(name);\n found.push([name, meta]);\n }\n }\n\n return found;\n};\n\n/**\n * Walks the prototype chain of a constructed gateway and collects every marked\n * method. Most-derived wins on a repeated name; an undecorated override does not\n * shadow its decorated base, and dispatch still lands on the override because the\n * handler is bound off the instance.\n */\nexport const discoverGateway = (instance: object): DiscoveredGateway => {\n const klass = instance.constructor;\n const members = instance as Record<string, Invoke>;\n\n return {\n name: klass.name,\n path: normalizePath(gatewayPathOf(klass)),\n handlers: eachHandler(Object.getPrototypeOf(instance) as object | null).map(\n ([name, meta]) => ({\n kind: meta.kind,\n event: meta.event,\n method: name,\n invoke: members[name]!.bind(instance),\n }),\n ),\n };\n};\n\n/**\n * The name of the first handler a class declares, without constructing it. A\n * provider that declares one but is not a gateway would silently never receive a\n * frame, so that becomes a boot error naming the method.\n */\nexport const findHandlerMethod = (ctor: Ctor<unknown>): string | undefined =>\n eachHandler(ctor.prototype as object | null)[0]?.[0];\n\n/** The class a `providers` entry would construct, or nothing for value/factory. */\nconst classOf = (\n entry: ProviderEntry,\n): { token: InjectionToken<unknown>; ctor: Ctor<unknown> } | undefined => {\n if (typeof entry === 'function') return { token: entry, ctor: entry };\n return entry.provider.kind === 'class'\n ? { token: entry.token, ctor: entry.provider.ctor }\n : undefined;\n};\n\n/**\n * Gateways are declared in `@Module({ providers })` like any other injectable and\n * found here by their marker - the same discovery-by-inspection controllers get,\n * with no second registration key to keep in step.\n */\nexport const discoverGateways = (\n modules: readonly ResolvedModule[],\n resolve: (token: InjectionToken<unknown>) => unknown,\n): readonly DiscoveredGateway[] => {\n const discovered: DiscoveredGateway[] = [];\n\n for (const module of modules) {\n for (const entry of module.options.providers ?? []) {\n const candidate = classOf(entry);\n if (!candidate) continue;\n\n if (isGateway(candidate.ctor)) {\n discovered.push(discoverGateway(resolve(candidate.token) as object));\n continue;\n }\n // Otherwise its handlers could never run, and nothing would say so.\n const orphan = findHandlerMethod(candidate.ctor);\n if (orphan !== undefined) {\n throw new AppError(\n `${candidate.ctor.name}.${orphan}() is a websocket handler, but ` +\n `${candidate.ctor.name} is not a gateway. Decorate the class with ` +\n '@Gateway(path), or drop the handler decorator.',\n );\n }\n }\n }\n\n return discovered;\n};\n",
|
|
19
19
|
"import { AppError } from '@dunx/core';\nimport type { Server } from 'bun';\nimport { encode } from './envelope.js';\nimport {\n decodeRelay,\n DEFAULT_RELAY_CHANNEL,\n defaultRelayError,\n encodeRelay,\n type PubSubRelay,\n type RelayOptions,\n type RelayPhase,\n} from './relay.js';\nimport type { SocketData } from './socket.js';\n\n/**\n * Server-wide publish, delegating to Bun's own pub/sub. Topics live in the\n * runtime, not in a JavaScript registry: `socket.subscribe(topic)` is what joins\n * one, and Bun does the fan-out.\n *\n * Injectable - `HttpFactory` binds it, so a service can publish without holding a\n * socket and without registering anything.\n *\n * With a {@link PubSubRelay} attached the same publish also reaches the other\n * nodes. Without one - the default - nothing here touches a broker and the cost is\n * exactly Bun's.\n */\nexport class PubSub {\n /**\n * Identifies this process on the wire, so a frame this node published and the\n * broker echoed back is recognised and dropped instead of being fanned out\n * locally a second time. `Bun.randomUUIDv7` rather than a counter: two nodes\n * booted in the same millisecond must not collide.\n */\n readonly #origin = Bun.randomUUIDv7();\n #server: Server<SocketData> | undefined;\n #relay: PubSubRelay | undefined;\n #channel = DEFAULT_RELAY_CHANNEL;\n #onRelayError = defaultRelayError;\n /** So a broker that is down is reported once, not once per publish. */\n #relayFailing = false;\n #resubscribeTimer: ReturnType<typeof setTimeout> | undefined;\n #resubscribeLeft = 0;\n #resubscribeDelay = 0;\n\n /** Called with the live server by `listen()`; also usable directly. */\n attach(server: Server<SocketData>): void {\n this.#server = server;\n }\n\n get attached(): boolean {\n return this.#server !== undefined;\n }\n\n /** This process's id on the relay channel. Stable for the process's lifetime. */\n get origin(): string {\n return this.#origin;\n }\n\n get relaying(): boolean {\n return this.#relay !== undefined;\n }\n\n /**\n * Opt into multi-node fan-out: every `publish` from here on also goes to\n * `relay`, and everything other nodes put on the channel is fanned out locally.\n *\n * `HttpFactory.create(root, { relay })` is the shorthand - `listen()` calls this.\n * Call it directly when the relay has to come out of the container, which is the\n * case for an app reusing its own `@dunx/infra/redis` connection:\n * `app.get(PubSub).relayThrough(app.get(RedisConnection))` before `listen()`.\n *\n * A broker that cannot be reached is reported through `onError` and left alone -\n * local fan-out is unaffected, and the app boots either way.\n */\n async relayThrough(\n relay: PubSubRelay,\n options: RelayOptions = {},\n ): Promise<void> {\n if (this.#relay) {\n throw new AppError(\n 'PubSub already relays. Two subscriptions on one channel would deliver ' +\n 'every relayed message twice - pass HttpOptions.relay or call ' +\n 'relayThrough(), not both.',\n );\n }\n this.#relay = relay;\n this.#channel = options.channel ?? DEFAULT_RELAY_CHANNEL;\n this.#onRelayError = options.onError ?? defaultRelayError;\n this.#resubscribeLeft = options.resubscribe?.attempts ?? 5;\n this.#resubscribeDelay = options.resubscribe?.delayMs ?? 500;\n\n await this.#trySubscribe();\n }\n\n /**\n * One subscribe attempt, scheduling the next on failure. Separate from\n * `relayThrough` because a retry has to run the identical path - including the\n * synchronous-throw handling, which Bun's client needs.\n */\n async #trySubscribe(): Promise<void> {\n const relay = this.#relay;\n if (!relay) return;\n\n try {\n // Bun's client throws synchronously for some states, so the call is inside\n // the try rather than only the await.\n await relay.subscribe(this.#channel, (message) => {\n this.#inbound(message);\n });\n this.#relayFailing = false;\n this.#resubscribeLeft = 0;\n } catch (error) {\n this.#degrade(error, 'subscribe');\n this.#scheduleResubscribe();\n }\n }\n\n #scheduleResubscribe(): void {\n if (this.#resubscribeLeft <= 0 || this.#relay === undefined) return;\n this.#resubscribeLeft -= 1;\n const delay = this.#resubscribeDelay;\n // Capped so a long-dead broker settles into a slow poll instead of growing\n // unboundedly; unref'd so it can never be the reason a process stays up.\n this.#resubscribeDelay = Math.min(delay * 2, 30_000);\n this.#resubscribeTimer = setTimeout(() => {\n void this.#trySubscribe();\n }, delay);\n this.#resubscribeTimer.unref?.();\n }\n\n /** Bytes sent locally, `0` if the message was dropped, `-1` under backpressure. */\n publish(\n topic: string,\n data: string | Bun.BufferSource,\n compress?: boolean,\n ): number {\n const sent = this.#live().publish(topic, data, compress);\n // Unconditional, and after the local fan-out: a topic with no subscriber on\n // this node may have thousands on another.\n this.#outbound(topic, data);\n return sent;\n }\n\n /** The same envelope `@OnMessage(event)` reads, published to a topic. */\n publishEvent(topic: string, event: string, data?: unknown): number {\n return this.publish(topic, encode(event, data));\n }\n\n /** Subscribers on **this** node. Bun counts its own sockets and nothing else. */\n subscriberCount(topic: string): number {\n return this.#live().subscriberCount(topic);\n }\n\n /**\n * Releases a relay this `PubSub` was given, if the relay owns connections.\n *\n * The server reference goes too, which is what makes a relay the *app* owns safe\n * to leave subscribed: `PubSubRelay` has no unsubscribe, so a frame may still\n * arrive on a shared connection after this node stopped, and with no server\n * there is nothing for it to fan out to.\n */\n async close(): Promise<void> {\n const relay = this.#relay;\n this.#relay = undefined;\n // Before anything can await: a pending retry must not fire against a relay\n // this call is closing.\n this.#resubscribeLeft = 0;\n if (this.#resubscribeTimer !== undefined) {\n clearTimeout(this.#resubscribeTimer);\n this.#resubscribeTimer = undefined;\n }\n this.#server = undefined;\n if (!relay?.close) return;\n try {\n await relay.close();\n } catch (error) {\n this.#degrade(error, 'close');\n }\n }\n\n #outbound(topic: string, data: string | Bun.BufferSource): void {\n const relay = this.#relay;\n if (!relay) return;\n try {\n const result = relay.publish(\n this.#channel,\n encodeRelay(this.#origin, topic, data),\n );\n if (result instanceof Promise) {\n void result.then(\n () => {\n this.#relayFailing = false;\n },\n (error: unknown) => {\n this.#degrade(error, 'publish');\n },\n );\n return;\n }\n this.#relayFailing = false;\n } catch (error) {\n this.#degrade(error, 'publish');\n }\n }\n\n /**\n * Local fan-out only, and that is the whole rule: republishing to the relay here\n * would put the frame back on the channel that delivered it and loop forever.\n */\n #inbound(message: string): void {\n const frame = decodeRelay(message);\n if (!frame || frame.origin === this.#origin) return;\n this.#server?.publish(frame.topic, frame.data);\n }\n\n #degrade(error: unknown, phase: RelayPhase): void {\n if (this.#relayFailing) return;\n this.#relayFailing = true;\n this.#onRelayError(error, phase);\n }\n\n #live(): Server<SocketData> {\n if (!this.#server) {\n throw new AppError(\n 'PubSub has no server yet. Publish once the server is listening: ' +\n 'HttpApp.listen() is what attaches it.',\n );\n }\n return this.#server;\n }\n}\n",
|
|
20
20
|
"/**\n * What `PubSub` needs from something that carries a message to the other nodes:\n * publish, and subscribe. Nothing else, so anything that already talks to a\n * broker satisfies it - `@dunx/infra/redis`'s `RedisConnection` does, structurally\n * and with no adapter, and so does a bare `Bun.RedisClient` pair.\n *\n * The return types are `unknown` rather than `Promise<void>` deliberately: Bun's\n * `publish` resolves the subscriber count, `@dunx/infra`'s resolves nothing, and a\n * synchronous in-memory bus resolves at all. A returned promise is awaited by\n * `subscribe` and watched for rejection by `publish`; anything else is taken as\n * having succeeded.\n */\nexport interface PubSubRelay {\n /** Hand `message` to every node subscribed to `channel`, this one included. */\n publish(channel: string, message: string): unknown;\n /**\n * Deliver every message published to `channel` to `listener`. Called once, with\n * one channel - pattern subscription is not used, because Bun's `psubscribe`\n * does not work (see docs/bun-apis.md).\n */\n subscribe(channel: string, listener: (message: string) => void): unknown;\n /**\n * Release whatever this relay opened. Implement it only for connections the\n * relay itself owns: a relay that is the application's own shared\n * `RedisConnection` must leave closing to the container, and simply omitting\n * this method is how it says so.\n */\n close?(): unknown;\n}\n\n/** Which relay call failed, so one message can say what degraded. */\nexport type RelayPhase = 'publish' | 'subscribe' | 'close';\n\nexport interface RelayOptions {\n /**\n * The one broker channel every topic's frames travel on.\n *\n * One channel rather than one per topic, because a node cannot know which\n * topics its sockets joined - `socket.subscribe()` goes straight into Bun - and\n * `psubscribe` is unusable. The cost is that every node reads every relayed\n * frame and drops the ones for topics it has no local subscriber on, which is a\n * `server.publish` returning `0`. Two apps sharing a Redis need two channels.\n *\n * @default 'dunx:ws'\n */\n readonly channel?: string;\n /**\n * Where a relay failure goes. Called once when the relay starts failing and not\n * again until it works, so an unreachable broker cannot flood the log.\n *\n * @default console.warn\n */\n readonly onError?: (error: unknown, phase: RelayPhase) => void;\n /**\n * What to do when the **boot** subscribe fails. Publishing recovers on its own -\n * every publish retries the broker - but a failed subscribe used to be retried\n * by nothing, so the node stayed permanently deaf to other nodes while still\n * looking healthy.\n *\n * Bounded rather than infinite, and the timer is unref'd, so a broker that never\n * comes back cannot hold the process open or spin forever.\n */\n readonly resubscribe?: {\n /** Retries after the first failure. `0` disables them. @default 5 */\n readonly attempts?: number;\n /** First delay; doubles each attempt, capped at 30s. @default 500 */\n readonly delayMs?: number;\n };\n}\n\nexport const DEFAULT_RELAY_CHANNEL = 'dunx:ws';\n\nexport const defaultRelayError = (error: unknown, phase: RelayPhase): void => {\n console.warn(\n `[dunx/http] the websocket relay could not ${phase}. Fan-out is local to ` +\n 'this process until it recovers:',\n error,\n );\n};\n\n/**\n * One relayed publish: which process published it, which topic it belongs to, and\n * the frame itself. `origin` is the whole duplicate-delivery defence - the broker\n * echoes a publish back to the publisher, and fanning that out locally a second\n * time would give every client on the originating node the message twice.\n */\nexport interface RelayFrame {\n readonly origin: string;\n readonly topic: string;\n readonly data: string | Uint8Array<ArrayBufferLike>;\n}\n\nconst toBytes = (data: Bun.BufferSource): Uint8Array<ArrayBufferLike> =>\n ArrayBuffer.isView(data)\n ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength)\n : new Uint8Array(data);\n\nexport const encodeRelay = (\n origin: string,\n topic: string,\n data: string | Bun.BufferSource,\n): string =>\n typeof data === 'string'\n ? JSON.stringify({ o: origin, t: topic, d: data })\n : // Base64 through Buffer, which Bun implements natively. A binary frame has\n // to survive a text channel, and Redis pub/sub payloads are text here\n // because Bun's buffer-mode subscription is not implemented.\n JSON.stringify({\n o: origin,\n t: topic,\n d: Buffer.from(toBytes(data)).toString('base64'),\n b: 1,\n });\n\n/** `undefined` for anything that is not one of our frames, which is then ignored. */\nexport const decodeRelay = (message: string): RelayFrame | undefined => {\n let parsed: unknown;\n try {\n parsed = JSON.parse(message);\n } catch {\n return undefined;\n }\n if (typeof parsed !== 'object' || parsed === null) return undefined;\n\n const { o, t, d, b } = parsed as {\n o?: unknown;\n t?: unknown;\n d?: unknown;\n b?: unknown;\n };\n if (typeof o !== 'string' || typeof t !== 'string' || typeof d !== 'string') {\n return undefined;\n }\n return { origin: o, topic: t, data: b ? Buffer.from(d, 'base64') : d };\n};\n",
|
|
21
|
-
"import type { BunRequest, Server } from 'bun';\nimport {\n AppError,\n Logger,\n type App,\n type AppOptions,\n type Ctor,\n type InjectionToken,\n type ShutdownSignal,\n} from '@dunx/core';\nimport { joinPath, type DiscoveredRoute } from '../route/discover.js';\nimport type { WebSocketRuntime } from '../ws/adapter.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport type { PubSubRelay, RelayOptions, RelayPhase } from '../ws/relay.js';\nimport type { SocketData, SocketOptions } from '../ws/socket.js';\nimport { attachAddressSource, ClientAddress } from './client-address.js';\nimport type { CorsOptions } from './cors.js';\nimport { errorMapper, type ErrorMapper } from './errors.js';\nimport type { Middleware } from './middleware.js';\nimport {\n RequestLoggingMiddleware,\n type RequestLoggingOptions,\n} from './request-logging.js';\nimport {\n assertNoGatewayCollisions,\n buildFallback,\n buildRoutes,\n withUpgradeRoutes,\n} from './routes.js';\nimport { defaultSettings, type AppSettings } from './settings.js';\n\nexport interface HttpOptions extends AppOptions {\n readonly port?: number;\n /** Resolved from the container, so middleware can inject(). */\n readonly middleware?: readonly Ctor<Middleware>[];\n readonly onError?: ErrorMapper;\n /**\n * One structured entry per request, on by default. `false` removes it; an\n * options object tunes what it records. See {@link RequestLoggingMiddleware}.\n *\n * It is the **outermost** middleware, ahead of anything `middleware` declares,\n * so a request rejected by a guard is still logged with the status it got.\n */\n readonly requestLogging?: boolean | RequestLoggingOptions;\n /**\n * Bun's `websocket` options, plus where a throwing handler goes. Server-wide, so\n * they live here next to `middleware` rather than on a module: gateways\n * themselves are declared in `@Module({ providers })`.\n */\n readonly websocket?: SocketOptions;\n /**\n * Multi-node websocket fan-out. Absent - the default - means `PubSub` publishes\n * to this process only, which is exactly Bun's native pub/sub and costs nothing.\n *\n * `new RedisRelay({ url })` is the batteries-included one. Anything with a\n * `publish` and a `subscribe` fits, including `@dunx/infra`'s `RedisConnection`,\n * which has to come out of the container and so goes through\n * `app.get(PubSub).relayThrough(...)` instead of this option.\n */\n readonly relay?: PubSubRelay;\n /** The broker channel the relay carries frames on. @default 'dunx:ws' */\n readonly relayChannel?: string;\n /**\n * How hard to retry a subscribe that failed. Same shape as\n * `RelayOptions.resubscribe`: bounded, doubling, and on an unref'd timer, so a\n * broker that never comes back cannot hold the process open.\n *\n * Here rather than only on `relayThrough` because reaching for that to set one\n * option means giving up `relay` above entirely - the two conflict, and the\n * second to run throws `PubSub already relays`.\n */\n readonly relayResubscribe?: RelayOptions['resubscribe'];\n /**\n * What an unmatched path looks like to global middleware.\n *\n * `'guarded'`, the default, gives the miss no route metadata, so a global guard\n * refuses it and an anonymous caller gets that guard's status rather than a 404.\n * That is deliberate: a 404 on a miss while every real path answers 401 tells a\n * prober which paths exist.\n *\n * `'public'` reports the miss as `@Public()`, so a guard honouring that flag\n * passes it through to the conventional 404. The request is still logged and\n * still gets a request id either way, which is the whole reason the fallback\n * runs the middleware at all.\n *\n * A guard can discriminate under either setting: `UNMATCHED` is set on the miss\n * and no real route ever sets it.\n *\n * @default 'guarded'\n */\n readonly notFound?: 'guarded' | 'public';\n}\n\n/**\n * Everything below `listen()` configures the route table, which is built exactly\n * once - when the server binds. Calling any of them afterwards throws rather than\n * being quietly dropped.\n */\nexport interface HttpApp extends App {\n /** Prefixes every discovered route. Last call wins. */\n setGlobalPrefix(prefix: string): this;\n /** Appends middleware, after anything `HttpOptions.middleware` declared. */\n use(...middleware: readonly Ctor<Middleware>[]): this;\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this;\n setting<K extends keyof AppSettings>(key: K): AppSettings[K];\n /** Mounts an `OPTIONS` preflight per path. Last call wins. */\n enableCors(options?: CorsOptions): this;\n /** The same `inject(ClientAddress)` singleton - honours `'trust proxy'`. */\n clientIp(req: BunRequest): string | undefined;\n /** Every gateway path this app upgrades on, exactly as mounted. */\n readonly gatewayPaths: readonly string[];\n listen(port?: number): Promise<string>;\n}\n\nexport class HttpApplication implements HttpApp {\n readonly closed: Promise<void>;\n readonly gatewayPaths: readonly string[];\n readonly #app: App;\n readonly #discovered: readonly DiscoveredRoute[];\n readonly #middleware: Ctor<Middleware>[];\n readonly #settings: AppSettings = defaultSettings();\n readonly #onError: ErrorMapper;\n readonly #port: number;\n readonly #websocket: WebSocketRuntime | undefined;\n readonly #relay: PubSubRelay | undefined;\n readonly #relayChannel: string | undefined;\n readonly #relayResubscribe: RelayOptions['resubscribe'];\n readonly #notFound: 'guarded' | 'public';\n #globalPrefix = '';\n #cors: CorsOptions | undefined;\n #started = false;\n #server: Server<SocketData> | undefined;\n #resolveClosed: (() => void) | undefined;\n #shuttingDown: Promise<void> | undefined;\n #hooked = false;\n\n constructor(\n app: App,\n discovered: readonly DiscoveredRoute[],\n options: HttpOptions,\n websocket?: WebSocketRuntime,\n ) {\n this.#app = app;\n this.#discovered = discovered;\n this.#middleware = [\n ...(options.requestLogging === false ? [] : [RequestLoggingMiddleware]),\n ...(options.middleware ?? []),\n ];\n // The bound Logger, resolved only when the app did not bring its own mapper:\n // a 500's stack belongs in the same stream as everything else.\n this.#onError = options.onError ?? errorMapper(app.get(Logger));\n this.#port = options.port ?? 3000;\n this.#websocket = websocket;\n this.#relay = options.relay;\n this.#relayChannel = options.relayChannel;\n this.#relayResubscribe = options.relayResubscribe;\n this.#notFound = options.notFound ?? 'guarded';\n this.gatewayPaths = websocket?.paths ?? [];\n this.closed = new Promise<void>((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n get<T>(token: InjectionToken<T>): T {\n return this.#app.get(token);\n }\n\n setGlobalPrefix(prefix: string): this {\n this.#assertNotStarted('setGlobalPrefix()');\n this.#globalPrefix = prefix;\n return this;\n }\n\n use(...middleware: readonly Ctor<Middleware>[]): this {\n this.#assertNotStarted('use()');\n this.#middleware.push(...middleware);\n return this;\n }\n\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this {\n this.#assertNotStarted('set()');\n this.#settings[key] = value;\n return this;\n }\n\n setting<K extends keyof AppSettings>(key: K): AppSettings[K] {\n return this.#settings[key];\n }\n\n enableCors(options: CorsOptions = {}): this {\n this.#assertNotStarted('enableCors()');\n this.#cors = options;\n return this;\n }\n\n clientIp(req: BunRequest): string | undefined {\n return this.#app.get(ClientAddress).of(req);\n }\n\n /**\n * The one `Bun.serve` call. A gateway's upgrade is a native `GET` route in the\n * same table, so Bun's router - not a hand-written `fetch` fallback - is what\n * matches an upgrade, and no `fetch` handler is needed at all.\n */\n async listen(port = this.#port): Promise<string> {\n this.#assertNotStarted('listen()');\n this.#started = true;\n\n const middleware = this.#middleware.map((entry) => this.#app.get(entry));\n const prefixed = this.#prefixed();\n // A `@UseGuards` class comes from the container too, so a guard injects exactly\n // like global middleware does.\n const routes = buildRoutes(\n prefixed,\n middleware,\n this.#onError,\n this.#cors,\n (guard) => this.#app.get(guard),\n );\n\n const ws = this.#websocket;\n if (ws) assertNoGatewayCollisions(prefixed, ws.paths);\n\n // Bun's own 404 never reaches the middleware chain, so an unmatched path is\n // invisible to request logging. This runs only after Bun has matched nothing,\n // so Bun is still the router - it just puts the global middleware in front of\n // the 404 and returns it in the framework's error shape.\n const fetch = buildFallback(\n middleware,\n this.#onError,\n this.#cors,\n this.#notFound,\n );\n\n // Two literals, one call: a route that may answer `undefined` because it\n // upgraded is only a valid route table when `websocket` is there to receive it,\n // and Bun's own types say so.\n const options: Bun.Serve.Options<SocketData> = ws\n ? {\n port,\n fetch,\n routes: withUpgradeRoutes(routes, ws.routes),\n websocket: ws.websocket,\n }\n : { port, fetch, routes };\n this.#server = Bun.serve(options);\n\n attachAddressSource(this.#app.get(ClientAddress), {\n server: this.#server,\n trustProxy: this.#settings['trust proxy'],\n });\n const pubsub = this.#app.get(PubSub);\n pubsub.attach(this.#server);\n // After attach, so a frame that arrives during the subscribe already has a\n // server to fan out on. Awaited so a two-node deployment is subscribed by the\n // time listen() resolves; an unreachable broker fails fast and degrades.\n if (this.#relay) {\n const logger = this.#app.get(Logger);\n await pubsub.relayThrough(this.#relay, {\n ...(this.#relayChannel !== undefined && {\n channel: this.#relayChannel,\n }),\n ...(this.#relayResubscribe !== undefined && {\n resubscribe: this.#relayResubscribe,\n }),\n onError: (error: unknown, phase: RelayPhase) => {\n logger.warn(\n `the websocket relay could not ${phase}. Fan-out is local to this ` +\n 'process until it recovers.',\n { error },\n );\n },\n });\n }\n return this.#server.url.href;\n }\n\n // Not delegated to the core app: the server has to stop before providers tear\n // down, so the signal handler must land here. With a gateway the stop is forced -\n // a graceful stop waits for open connections and a WebSocket does not close on\n // its own, so it would hang. Those clients see a 1006 close.\n async shutdown(): Promise<void> {\n this.#shuttingDown ??= (async () => {\n await this.#server?.stop(this.#websocket !== undefined);\n this.#server = undefined;\n // Before the container: a relay this app owns holds two Redis sockets, and\n // `maxRetries: 0` means nothing else will ever close them.\n await this.#app.get(PubSub).close();\n await this.#app.shutdown();\n this.#resolveClosed?.();\n })();\n return this.#shuttingDown;\n }\n\n enableShutdownHooks(\n signals: readonly ShutdownSignal[] = ['SIGTERM', 'SIGINT'],\n ): this {\n if (this.#hooked) return this;\n this.#hooked = true;\n for (const signal of signals) {\n process.once(signal, () => void this.shutdown());\n }\n return this;\n }\n\n // Collision detection re-runs inside buildRoutes on these final paths.\n #prefixed(): readonly DiscoveredRoute[] {\n if (this.#globalPrefix === '') return this.#discovered;\n return this.#discovered.map((route) => ({\n ...route,\n path: joinPath(this.#globalPrefix, route.path),\n }));\n }\n\n // #started rather than #server, which shutdown() clears - a hook called after\n // the server stopped is just as ineffective as one called while it ran.\n #assertNotStarted(hook: string): void {\n if (!this.#started) return;\n throw new AppError(\n `${hook} must be called before listen(). The route table and the middleware ` +\n 'chain are folded into one closure per route when the server binds, so ' +\n 'this call could not take effect.',\n );\n }\n}\nObject.defineProperty(HttpApplication, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"app: App\", typeOnly: \"App\" }, { unresolved: \"discovered: readonly DiscoveredRoute[]\" }, { unresolved: \"options: HttpOptions\" }, { unresolved: \"websocket?: WebSocketRuntime\", typeOnly: \"WebSocketRuntime\" }],\n});\n",
|
|
21
|
+
"import type { BunRequest, Server } from 'bun';\nimport {\n AppError,\n Logger,\n type App,\n type AppOptions,\n type Ctor,\n type InjectionToken,\n type ModuleRef,\n type ShutdownSignal,\n} from '@dunx/core';\nimport { joinPath, type DiscoveredRoute } from '../route/discover.js';\nimport type { WebSocketRuntime } from '../ws/adapter.js';\nimport { PubSub } from '../ws/pubsub.js';\nimport type { PubSubRelay, RelayOptions, RelayPhase } from '../ws/relay.js';\nimport type { SocketData, SocketOptions } from '../ws/socket.js';\nimport { attachAddressSource, ClientAddress } from './client-address.js';\nimport type { CorsOptions } from './cors.js';\nimport {\n errorMapper,\n toErrorMapper,\n type ErrorHandler,\n type ErrorMapper,\n} from './errors.js';\nimport type { Middleware } from './middleware.js';\nimport {\n RequestLoggingMiddleware,\n type RequestLoggingOptions,\n} from './request-logging.js';\nimport {\n assertNoGatewayCollisions,\n buildFallback,\n buildRoutes,\n withUpgradeRoutes,\n} from './routes.js';\nimport { defaultSettings, type AppSettings } from './settings.js';\n\nexport interface HttpOptions extends AppOptions {\n readonly port?: number;\n /** Resolved from the container, so middleware can inject(). */\n readonly middleware?: readonly Ctor<Middleware>[];\n /**\n * Replaces the default mapper.\n *\n * A bare `ErrorMapper` function, or an `ErrorFilter` **class** - which is the one\n * to prefer, because a class is resolved from the container and can therefore\n * inject the `Logger` or the config a real filter needs. A mapper cannot; dunx's\n * own default has to be curried over its logger for exactly that reason.\n *\n * A filter with dependencies needs them bindable, the same rule `middleware`\n * entries follow; one with none self-binds and needs no `providers` entry.\n */\n readonly onError?: ErrorHandler;\n /**\n * One structured entry per request, on by default. `false` removes it; an\n * options object tunes what it records. See {@link RequestLoggingMiddleware}.\n *\n * It is the **outermost** middleware, ahead of anything `middleware` declares,\n * so a request rejected by a guard is still logged with the status it got.\n */\n readonly requestLogging?: boolean | RequestLoggingOptions;\n /**\n * Bun's `websocket` options, plus where a throwing handler goes. Server-wide, so\n * they live here next to `middleware` rather than on a module: gateways\n * themselves are declared in `@Module({ providers })`.\n */\n readonly websocket?: SocketOptions;\n /**\n * Multi-node websocket fan-out. Absent - the default - means `PubSub` publishes\n * to this process only, which is exactly Bun's native pub/sub and costs nothing.\n *\n * `new RedisRelay({ url })` is the batteries-included one. Anything with a\n * `publish` and a `subscribe` fits, including `@dunx/infra`'s `RedisConnection`,\n * which has to come out of the container and so goes through\n * `app.get(PubSub).relayThrough(...)` instead of this option.\n */\n readonly relay?: PubSubRelay;\n /** The broker channel the relay carries frames on. @default 'dunx:ws' */\n readonly relayChannel?: string;\n /**\n * How hard to retry a subscribe that failed. Same shape as\n * `RelayOptions.resubscribe`: bounded, doubling, and on an unref'd timer, so a\n * broker that never comes back cannot hold the process open.\n *\n * Here rather than only on `relayThrough` because reaching for that to set one\n * option means giving up `relay` above entirely - the two conflict, and the\n * second to run throws `PubSub already relays`.\n */\n readonly relayResubscribe?: RelayOptions['resubscribe'];\n /**\n * What an unmatched path looks like to global middleware.\n *\n * `'guarded'`, the default, gives the miss no route metadata, so a global guard\n * refuses it and an anonymous caller gets that guard's status rather than a 404.\n * That is deliberate: a 404 on a miss while every real path answers 401 tells a\n * prober which paths exist.\n *\n * `'public'` reports the miss as `@Public()`, so a guard honouring that flag\n * passes it through to the conventional 404. The request is still logged and\n * still gets a request id either way, which is the whole reason the fallback\n * runs the middleware at all.\n *\n * A guard can discriminate under either setting: `UNMATCHED` is set on the miss\n * and no real route ever sets it.\n *\n * @default 'guarded'\n */\n readonly notFound?: 'guarded' | 'public';\n}\n\n/**\n * Everything below `listen()` configures the route table, which is built exactly\n * once - when the server binds. Calling any of them afterwards throws rather than\n * being quietly dropped.\n */\nexport interface HttpApp extends App {\n /** Prefixes every discovered route. Last call wins. */\n setGlobalPrefix(prefix: string): this;\n /** Appends middleware, after anything `HttpOptions.middleware` declared. */\n use(...middleware: readonly Ctor<Middleware>[]): this;\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this;\n setting<K extends keyof AppSettings>(key: K): AppSettings[K];\n /** Mounts an `OPTIONS` preflight per path. Last call wins. */\n enableCors(options?: CorsOptions): this;\n /** The same `inject(ClientAddress)` singleton - honours `'trust proxy'`. */\n clientIp(req: BunRequest): string | undefined;\n /** Every gateway path this app upgrades on, exactly as mounted. */\n readonly gatewayPaths: readonly string[];\n listen(port?: number): Promise<string>;\n}\n\nexport class HttpApplication implements HttpApp {\n /** Forwarded from the container so an app can log scope warnings at boot. */\n readonly warnings: readonly string[];\n /**\n * The app's own root module, not this package's wrapper around it.\n *\n * Global middleware, guards and an error filter are all listed by the app, so they\n * resolve as the app's root sees them. Resolving them from the wrapper would mean a\n * guard could only inject what the app happened to *export*, which is a boundary the\n * app never asked for - it wrote the list.\n */\n readonly #root: ModuleRef;\n readonly closed: Promise<void>;\n readonly gatewayPaths: readonly string[];\n readonly #app: App;\n readonly #discovered: readonly DiscoveredRoute[];\n readonly #middleware: Ctor<Middleware>[];\n readonly #settings: AppSettings = defaultSettings();\n readonly #onError: ErrorMapper;\n readonly #port: number;\n readonly #websocket: WebSocketRuntime | undefined;\n readonly #relay: PubSubRelay | undefined;\n readonly #relayChannel: string | undefined;\n readonly #relayResubscribe: RelayOptions['resubscribe'];\n readonly #notFound: 'guarded' | 'public';\n #globalPrefix = '';\n #cors: CorsOptions | undefined;\n #started = false;\n #server: Server<SocketData> | undefined;\n #resolveClosed: (() => void) | undefined;\n #shuttingDown: Promise<void> | undefined;\n #hooked = false;\n\n constructor(\n app: App,\n discovered: readonly DiscoveredRoute[],\n options: HttpOptions,\n root: ModuleRef,\n websocket?: WebSocketRuntime,\n ) {\n this.#app = app;\n this.#root = root;\n this.warnings = app.warnings;\n this.#discovered = discovered;\n this.#middleware = [\n ...(options.requestLogging === false ? [] : [RequestLoggingMiddleware]),\n ...(options.middleware ?? []),\n ];\n // The bound Logger, resolved only when the app did not bring its own handler:\n // a 500's stack belongs in the same stream as everything else.\n //\n // A filter class is resolved from the container here rather than per request, so\n // a missing binding is a boot error like any other and the request path stays a\n // method call. Its `catch` is looked up per call, which is what lets a filter be\n // rebound in a test.\n this.#onError =\n options.onError === undefined\n ? errorMapper(app.get(Logger))\n : toErrorMapper(options.onError, (token) => app.get(token, root));\n this.#port = options.port ?? 3000;\n this.#websocket = websocket;\n this.#relay = options.relay;\n this.#relayChannel = options.relayChannel;\n this.#relayResubscribe = options.relayResubscribe;\n this.#notFound = options.notFound ?? 'guarded';\n this.gatewayPaths = websocket?.paths ?? [];\n this.closed = new Promise<void>((resolve) => {\n this.#resolveClosed = resolve;\n });\n }\n\n get<T>(token: InjectionToken<T>): T {\n return this.#app.get(token);\n }\n\n setGlobalPrefix(prefix: string): this {\n this.#assertNotStarted('setGlobalPrefix()');\n this.#globalPrefix = prefix;\n return this;\n }\n\n use(...middleware: readonly Ctor<Middleware>[]): this {\n this.#assertNotStarted('use()');\n this.#middleware.push(...middleware);\n return this;\n }\n\n set<K extends keyof AppSettings>(key: K, value: AppSettings[K]): this {\n this.#assertNotStarted('set()');\n this.#settings[key] = value;\n return this;\n }\n\n setting<K extends keyof AppSettings>(key: K): AppSettings[K] {\n return this.#settings[key];\n }\n\n enableCors(options: CorsOptions = {}): this {\n this.#assertNotStarted('enableCors()');\n this.#cors = options;\n return this;\n }\n\n clientIp(req: BunRequest): string | undefined {\n return this.#app.get(ClientAddress).of(req);\n }\n\n /**\n * The one `Bun.serve` call. A gateway's upgrade is a native `GET` route in the\n * same table, so Bun's router - not a hand-written `fetch` fallback - is what\n * matches an upgrade, and no `fetch` handler is needed at all.\n */\n async listen(port = this.#port): Promise<string> {\n this.#assertNotStarted('listen()');\n this.#started = true;\n\n /**\n * Global middleware resolves **permissively**, not from a named scope.\n *\n * It is the app's own list, and the class it names is usually declared by whichever\n * feature module owns it - so the right instance is the one that module built, with\n * that module's dependencies. Pinning the lookup to the app's root would instead\n * demand the root re-export every guard it lists, which is a boundary nobody asked\n * for. `app.get` finds the single module that declares it, and errors if two do.\n */\n const middleware = this.#middleware.map((entry) =>\n this.#app.get(entry, this.#root),\n );\n const prefixed = this.#prefixed();\n // A `@UseGuards` class comes from the container too, so a guard injects exactly\n // like global middleware does.\n const routes = buildRoutes(\n prefixed,\n middleware,\n this.#onError,\n this.#cors,\n // A module's own middleware resolves from that module, which `from` carries. A\n // `@UseGuards` guard without one takes the same permissive lookup as global\n // middleware.\n (guard, from) =>\n from === undefined ? this.#app.get(guard) : this.#app.get(guard, from),\n );\n\n const ws = this.#websocket;\n if (ws) assertNoGatewayCollisions(prefixed, ws.paths);\n\n // Bun's own 404 never reaches the middleware chain, so an unmatched path is\n // invisible to request logging. This runs only after Bun has matched nothing,\n // so Bun is still the router - it just puts the global middleware in front of\n // the 404 and returns it in the framework's error shape.\n const fetch = buildFallback(\n middleware,\n this.#onError,\n this.#cors,\n this.#notFound,\n );\n\n // Two literals, one call: a route that may answer `undefined` because it\n // upgraded is only a valid route table when `websocket` is there to receive it,\n // and Bun's own types say so.\n const options: Bun.Serve.Options<SocketData> = ws\n ? {\n port,\n fetch,\n routes: withUpgradeRoutes(routes, ws.routes),\n websocket: ws.websocket,\n }\n : { port, fetch, routes };\n this.#server = Bun.serve(options);\n\n attachAddressSource(this.#app.get(ClientAddress), {\n server: this.#server,\n trustProxy: this.#settings['trust proxy'],\n });\n const pubsub = this.#app.get(PubSub);\n pubsub.attach(this.#server);\n // After attach, so a frame that arrives during the subscribe already has a\n // server to fan out on. Awaited so a two-node deployment is subscribed by the\n // time listen() resolves; an unreachable broker fails fast and degrades.\n if (this.#relay) {\n const logger = this.#app.get(Logger);\n await pubsub.relayThrough(this.#relay, {\n ...(this.#relayChannel !== undefined && {\n channel: this.#relayChannel,\n }),\n ...(this.#relayResubscribe !== undefined && {\n resubscribe: this.#relayResubscribe,\n }),\n onError: (error: unknown, phase: RelayPhase) => {\n logger.warn(\n `the websocket relay could not ${phase}. Fan-out is local to this ` +\n 'process until it recovers.',\n { error },\n );\n },\n });\n }\n return this.#server.url.href;\n }\n\n // Not delegated to the core app: the server has to stop before providers tear\n // down, so the signal handler must land here. With a gateway the stop is forced -\n // a graceful stop waits for open connections and a WebSocket does not close on\n // its own, so it would hang. Those clients see a 1006 close.\n async shutdown(): Promise<void> {\n this.#shuttingDown ??= (async () => {\n await this.#server?.stop(this.#websocket !== undefined);\n this.#server = undefined;\n // Before the container: a relay this app owns holds two Redis sockets, and\n // `maxRetries: 0` means nothing else will ever close them.\n await this.#app.get(PubSub).close();\n await this.#app.shutdown();\n this.#resolveClosed?.();\n })();\n return this.#shuttingDown;\n }\n\n enableShutdownHooks(\n signals: readonly ShutdownSignal[] = ['SIGTERM', 'SIGINT'],\n ): this {\n if (this.#hooked) return this;\n this.#hooked = true;\n for (const signal of signals) {\n process.once(signal, () => void this.shutdown());\n }\n return this;\n }\n\n // Collision detection re-runs inside buildRoutes on these final paths.\n #prefixed(): readonly DiscoveredRoute[] {\n if (this.#globalPrefix === '') return this.#discovered;\n return this.#discovered.map((route) => ({\n ...route,\n path: joinPath(this.#globalPrefix, route.path),\n }));\n }\n\n // #started rather than #server, which shutdown() clears - a hook called after\n // the server stopped is just as ineffective as one called while it ran.\n #assertNotStarted(hook: string): void {\n if (!this.#started) return;\n throw new AppError(\n `${hook} must be called before listen(). The route table and the middleware ` +\n 'chain are folded into one closure per route when the server binds, so ' +\n 'this call could not take effect.',\n );\n }\n}\nObject.defineProperty(HttpApplication, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"app: App\", typeOnly: \"App\" }, { unresolved: \"discovered: readonly DiscoveredRoute[]\" }, { unresolved: \"options: HttpOptions\" }, { unresolved: \"root: ModuleRef\", typeOnly: \"ModuleRef\" }, { unresolved: \"websocket?: WebSocketRuntime\", typeOnly: \"WebSocketRuntime\" }],\n});\n",
|
|
22
22
|
"import {\n Logger,\n RequestContext,\n type RequestFields as ScopeFields,\n} from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport type { RouteContext } from './context.js';\nimport { HttpError } from './errors.js';\nimport type { Middleware, Next } from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\nexport const REQUEST_ID_HEADER = 'x-request-id';\n\nexport interface RequestLoggingOptions {\n /** Bodies past this many characters are logged as a size. Default 2048. `0` omits them. */\n readonly maxBodyLength?: number;\n /**\n * Log the request body. Default **`false`**.\n *\n * Reading it means `req.clone().text()` - a second copy of every payload,\n * buffered and parsed, on the hot path. Measured on the `validate` scenario in\n * `tools/bench`, turning both body options on costs roughly two thirds of the\n * throughput. It is also the field most likely to contain a password.\n *\n * Turn it on in development, where seeing the payload is the point.\n */\n readonly requestBody?: boolean;\n /** Log the response body. Default **`false`** - same clone-and-buffer cost. */\n readonly responseBody?: boolean;\n /**\n * Paths to skip entirely - a health check polled every second, say.\n *\n * **Entirely** is literal: no entry, no `x-request-id` on the response, and no\n * `AsyncLocalStorage` scope, so anything the handler logs is uncorrelated. That\n * is what makes it free. `correlateIgnored` buys the correlation back.\n */\n readonly ignore?: readonly string[];\n /**\n * Keep the request id and the async scope on an `ignore`d path. Default\n * **`false`**.\n *\n * \"Do not log the health check, but do keep its request id\" is this. The path\n * still writes no entry of its own; it gets an id - inbound or minted - on the\n * response, and everything the handler logs carries it.\n *\n * It is not the default because it is not free: the ignored path pays for\n * reading the header, `crypto.randomUUID()`, the `runWithContext` scope and the\n * response header. On the `bun run logging` decomposition those four rows are\n * ~2.2 µs, against ~5.4 µs for the whole default path - so it costs the half\n * that buys correlation and not the half that builds and serialises the entry.\n */\n readonly correlateIgnored?: boolean;\n /**\n * Wrap every request in an `AsyncLocalStorage` scope. Default **`true`**.\n *\n * The scope is what lets a service logging four frames down come out carrying\n * `requestId` without being handed a request object. It is measured: the\n * `runWithContext` row of `bun run logging` is **+0.91 µs**, 17% of the 5.38 µs\n * request logging costs over `requestLogging: false`.\n *\n * `correlate: false` skips it. **The request entry is unchanged** - the same\n * `requestId`, `method`, `event`, `flow` and `context` fields are written onto\n * it directly instead of being read back out of the store. What is lost is\n * everything *else* the request logs: those lines carry no `requestId`, and\n * `updateContext` from a handler has nothing to update.\n *\n * Worth it for an app whose handlers never log, or one that passes correlation\n * explicitly. Leave it on otherwise; correlation is most of what a request id\n * is for.\n */\n readonly correlate?: boolean;\n}\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/**\n * An inbound id is honoured so a trace survives across services - but only if it\n * is a UUID, which is what this middleware would have minted. It is a\n * caller-supplied string that ends up in every line the request writes, so a\n * newline, a megabyte, or a deliberate collision with somebody else's trace is\n * replaced by a fresh one rather than trusted. A production template validated it the\n * same way.\n *\n * The length check first: it is what keeps garbage away from the regex, and the\n * common case has no header at all.\n */\nconst traceId = (inbound: string | null): string =>\n inbound !== null && inbound.length === 36 && UUID.test(inbound)\n ? inbound\n : crypto.randomUUID();\n\nconst parse = (text: string, limit: number): unknown => {\n if (limit === 0) return undefined;\n if (text.length === 0) return undefined;\n if (text.length > limit) return `[${text.length} bytes]`;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n};\n\nconst elapsedMs = (started: number): number =>\n Math.round((Bun.nanoseconds() - started) / 1e6);\n\n/** What the entry's `request` field carries, built in the order it is logged. */\ntype RequestFields = Record<string, unknown>;\n\n/**\n * One structured entry per request, carrying the request and its response.\n *\n * Installed by `HttpFactory.create` unless `requestLogging: false`. It injects\n * `Logger` and `RequestContext` - both `@dunx/core` contracts, both bound by\n * default - so it works with no logging module imported, and picks up\n * `@arkv/logger` automatically once `@dunx/infra/logger` is.\n *\n * **One entry, not two.** A framework whose middleware cannot see the response\n * needs a middleware for the inbound half and an\n * interceptor for the outbound one, because they are different classes and the\n * interceptor cannot see what the middleware saw. Here they are the same\n * closure, so there is no pair to correlate by `requestId` to find out how a\n * call ended. A 4xx is the same line at `warn`, a 5xx at `error`.\n *\n * Everything the handler logs in between carries `requestId`, `method`, `event`\n * and `context` without being passed anything, because the whole call runs\n * inside `runWithContext` - unless `correlate: false`, which drops the scope and\n * with it that guarantee, but not the fields on this middleware's own entry.\n *\n * **Nothing here is `async`.** Reading the request or the response body are the\n * only steps that can ever wait, both are off by default, and both are adopted\n * with `.then` rather than awaited - the same rule `input.ts` follows, for the\n * same measured reason. An `async` scope callback alone cost 0.44 µs/request\n * against a synchronous one on raw `Bun.serve`.\n */\nexport class RequestLoggingMiddleware implements Middleware {\n readonly #limit: number;\n readonly #requestBody: boolean;\n readonly #responseBody: boolean;\n readonly #ignore: ReadonlySet<string>;\n readonly #correlateIgnored: boolean;\n readonly #correlate: boolean;\n\n constructor(\n private readonly logger: Logger,\n private readonly context: RequestContext,\n options: RequestLoggingOptions = {},\n ) {\n this.#limit = options.maxBodyLength ?? 2048;\n this.#requestBody = options.requestBody ?? false;\n this.#responseBody = options.responseBody ?? false;\n this.#ignore = new Set(options.ignore ?? []);\n this.#correlateIgnored = options.correlateIgnored ?? false;\n this.#correlate = options.correlate ?? true;\n }\n\n handle(req: BunRequest, ctx: RouteContext, next: Next): Promise<Response> {\n // `new URL(req.url)` parses the scheme, host, port, query and hash to reach one\n // string. This finds the same two offsets once and slices both the pathname and\n // the query out of them, which is what every request needs and all that most of\n // them need.\n const url = req.url;\n const from = url.indexOf('/', url.indexOf('://') + 3);\n const mark = from === -1 ? -1 : url.indexOf('?', from);\n const path =\n from === -1 ? '/' : mark === -1 ? url.slice(from) : url.slice(from, mark);\n if (this.#ignore.size > 0 && this.#ignore.has(path)) {\n return this.#correlateIgnored\n ? this.#correlated(req, ctx, path, next)\n : next();\n }\n\n const started = Bun.nanoseconds();\n const requestId = traceId(req.headers.get(REQUEST_ID_HEADER));\n const scope: ScopeFields = {\n requestId,\n method: ctx.method,\n event: path,\n flow: 'http',\n context: `${ctx.controller}.${ctx.handler}`,\n };\n\n // The same five fields either way. Under `correlate` they go into the store,\n // which the logger reads back for every line the request writes; without it\n // they are merged straight onto this middleware's own entry, so the request\n // log is identical and only the lines in between lose their id.\n return this.#correlate\n ? this.context.runWithContext(scope, () =>\n this.#begin(\n req,\n url,\n mark,\n path,\n requestId,\n started,\n next,\n undefined,\n ),\n )\n : this.#begin(req, url, mark, path, requestId, started, next, scope);\n }\n\n #begin(\n req: BunRequest,\n url: string,\n mark: number,\n path: string,\n requestId: string,\n started: number,\n next: Next,\n scope: ScopeFields | undefined,\n ): Promise<Response> {\n const request: RequestFields = {};\n if (mark !== -1) {\n request['query'] = Object.fromEntries(\n new URLSearchParams(url.slice(mark + 1)),\n );\n }\n const body = this.#body(req);\n if (body === undefined) {\n request['userAgent'] = req.headers.get('user-agent');\n return this.#dispatch(\n req,\n path,\n requestId,\n started,\n request,\n next,\n scope,\n );\n }\n return body.then((value) => {\n if (value !== undefined) request['body'] = value;\n request['userAgent'] = req.headers.get('user-agent');\n return this.#dispatch(\n req,\n path,\n requestId,\n started,\n request,\n next,\n scope,\n );\n });\n }\n\n /**\n * An ignored path under `correlateIgnored`: the scope and the response header,\n * and no entry. Nothing is timed and no fields are collected, because nothing\n * here is ever logged. Under `correlate: false` there is no scope to open here\n * either - only the response header is left, which is all `correlateIgnored`\n * can still mean once nothing reads the store.\n */\n #correlated(\n req: BunRequest,\n ctx: RouteContext,\n path: string,\n next: Next,\n ): Promise<Response> {\n const requestId = traceId(req.headers.get(REQUEST_ID_HEADER));\n const stamp = (response: Response): Response => {\n response.headers.set(REQUEST_ID_HEADER, requestId);\n return response;\n };\n if (!this.#correlate) return next().then(stamp);\n return this.context.runWithContext(\n {\n requestId,\n method: ctx.method,\n event: path,\n flow: 'http',\n context: `${ctx.controller}.${ctx.handler}`,\n },\n () => next().then(stamp),\n );\n }\n\n #dispatch(\n req: BunRequest,\n path: string,\n requestId: string,\n started: number,\n request: RequestFields,\n next: Next,\n scope: ScopeFields | undefined,\n ): Promise<Response> {\n // `next()` is only ever a promise once the chain bottoms out in a route, but a\n // user middleware ahead of the route may throw out of `handle` synchronously,\n // and that request is still one this middleware promised to log.\n let settled: Promise<Response>;\n try {\n settled = next();\n } catch (error) {\n this.#failed(req, path, started, request, error, scope);\n throw error;\n }\n return settled.then(\n (response) =>\n this.#succeeded(\n req,\n path,\n requestId,\n started,\n request,\n response,\n scope,\n ),\n (error: unknown) => {\n this.#failed(req, path, started, request, error, scope);\n throw error;\n },\n );\n }\n\n /**\n * Logged and rethrown: the error mapper still owns the status and the response\n * shape. A 404 or a rejected body is the caller's fault, and logging every probe\n * at `error` would drown the ones that matter.\n */\n #failed(\n req: BunRequest,\n path: string,\n started: number,\n request: RequestFields,\n error: unknown,\n scope: ScopeFields | undefined,\n ): void {\n const status =\n error instanceof HttpError\n ? error.status\n : HttpStatusCode.INTERNAL_SERVER_ERROR;\n const entry = {\n ...scope,\n request,\n err: error,\n statusCode: status,\n elapsedMs: elapsedMs(started),\n };\n const line = `${req.method} ${path} ${status}`;\n if (status < HttpStatusCode.INTERNAL_SERVER_ERROR) {\n this.logger.warn(line, entry);\n } else {\n this.logger.error(line, entry);\n }\n }\n\n #succeeded(\n req: BunRequest,\n path: string,\n requestId: string,\n started: number,\n request: RequestFields,\n response: Response,\n scope: ScopeFields | undefined,\n ): Response | Promise<Response> {\n const body = this.#responseFields(response);\n if (body === undefined) {\n this.logger.info(`${req.method} ${path} ${response.status}`, {\n ...scope,\n request,\n statusCode: response.status,\n elapsedMs: elapsedMs(started),\n });\n response.headers.set(REQUEST_ID_HEADER, requestId);\n return response;\n }\n return body.then((value) => {\n this.logger.info(`${req.method} ${path} ${response.status}`, {\n ...scope,\n request,\n statusCode: response.status,\n ...(value === undefined ? {} : { responseBody: value }),\n elapsedMs: elapsedMs(started),\n });\n response.headers.set(REQUEST_ID_HEADER, requestId);\n return response;\n });\n }\n\n /**\n * `undefined` - the default - means there is nothing to read, and the caller\n * stays on the synchronous path. Clones when there is, so the handler's own\n * stream is never the one that was consumed.\n */\n #body(req: BunRequest): Promise<unknown> | undefined {\n if (!this.#requestBody) return undefined;\n if (req.method === 'GET' || req.method === 'HEAD') return undefined;\n if (!(req.headers.get('content-type') ?? '').includes('application/json')) {\n return undefined;\n }\n return req\n .clone()\n .text()\n .then((text) => parse(text, this.#limit));\n }\n\n #responseFields(response: Response): Promise<unknown> | undefined {\n if (!this.#responseBody) return undefined;\n if (\n !(response.headers.get('content-type') ?? '').includes('application/json')\n ) {\n return undefined;\n }\n return response\n .clone()\n .text()\n .then((text) => parse(text, this.#limit));\n }\n}\nObject.defineProperty(RequestLoggingMiddleware, Symbol.for('dunx.deps'), {\n value: () => [Logger, RequestContext, { unresolved: \"options: RequestLoggingOptions = {}\" }],\n});\n",
|
|
23
|
-
"import { AppError, type Ctor } from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport type { DiscoveredRoute } from '../route/discover.js';\nimport type { HttpMethod } from '../route/marker.js';\nimport { PUBLIC, UNMATCHED, type MetaKey } from '../route/metadata.js';\nimport type { RouteInput } from '../route/schema.js';\nimport type { UpgradeHandler } from '../ws/adapter.js';\nimport { buildContext, type RouteContext } from './context.js';\nimport { preflight, withCors, type CorsOptions } from './cors.js';\nimport { defaultErrorMapper, HttpError, type ErrorMapper } from './errors.js';\nimport { buildInputReader, type InputReader } from './input.js';\nimport {\n compose,\n type Middleware,\n type RouteHandler,\n type ServedHandler,\n} from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\n/** How a `@UseGuards` class becomes an instance. `listen()` passes `app.get`. */\nexport type GuardResolver = (guard: Ctor<Middleware>) => Middleware;\n\nconst construct: GuardResolver = (guard) =>\n new (guard as new () => Middleware)();\n\n/** `OPTIONS` is never a `@Get`-style route - only CORS mounts one. */\nexport type RouteMethod = HttpMethod | 'OPTIONS';\n\nexport type BunRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler>>\n>;\n\n/**\n * What `listen()` hands `Bun.serve`: the HTTP table plus one `GET` per gateway,\n * whose handler may answer `undefined` because the socket was upgraded.\n */\nexport type ServeRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler | UpgradeHandler>>\n>;\n\n/**\n * A `Response` passes through untouched - that is the escape hatch, and nothing\n * about it is worth second-guessing. Nothing at all is a 204: `Response.json(null)`\n * would be a body claiming to be no body.\n */\nconst toResponse = (value: unknown, status: number): Response => {\n if (value instanceof Response) return value;\n if (value === undefined || value === null) {\n return new Response(null, { status: HttpStatusCode.NO_CONTENT });\n }\n return Response.json(value, { status });\n};\n\n/** The usual rule: an explicit `status`, else 201 for POST, else 200. */\nconst statusFor = (route: DiscoveredRoute): number =>\n route.options?.status ??\n (route.method === 'POST' ? HttpStatusCode.CREATED : HttpStatusCode.OK);\n\n/**\n * Bun silently lets one route win on a collision, so a duplicate method+path is a\n * boot error naming both handlers. Run twice: once at `create()` on the discovered\n * paths, and again from `buildRoutes` at `listen()` on the final, prefixed ones.\n */\nexport const assertNoCollisions = (\n discovered: readonly DiscoveredRoute[],\n): void => {\n const owners = new Map<string, string>();\n\n for (const route of discovered) {\n const key = `${route.method} ${route.path}`;\n const owner = `${route.controller}.${route.handlerName}`;\n const existing = owners.get(key);\n\n if (existing !== undefined) {\n throw new AppError(\n `Route collision: ${key} is declared by ${existing} and by ${owner}. ` +\n 'Bun would keep only one of them.',\n );\n }\n owners.set(key, owner);\n }\n};\n\n/**\n * A gateway's upgrade is a native route like any other, so a path claimed by both a\n * controller and a gateway would lose one of them when the two tables merge.\n */\nexport const assertNoGatewayCollisions = (\n discovered: readonly DiscoveredRoute[],\n gatewayPaths: readonly string[],\n): void => {\n const gateways = new Set(gatewayPaths);\n\n for (const route of discovered) {\n if (gateways.has(route.path)) {\n throw new AppError(\n `Gateway path collision: ${route.path} is served by a gateway and by ` +\n `${route.controller}.${route.handlerName}(). The upgrade is a route too, ` +\n 'so one of them would be dropped.',\n );\n }\n }\n};\n\n/**\n * The two tables in one. A gateway's `GET` is what Bun's router matches on an\n * upgrade - the reason no `fetch` handler is needed for a socket to connect.\n */\nexport const withUpgradeRoutes = (\n routes: BunRoutes,\n gateways: ReadonlyMap<string, UpgradeHandler>,\n): ServeRoutes => {\n const merged: ServeRoutes = { ...routes };\n for (const [path, upgrade] of gateways) merged[path] = { GET: upgrade };\n return merged;\n};\n\n/**\n * The context an unmatched request gets. There is no controller and no handler,\n * and saying so is more useful to a log line than an empty string.\n *\n * A miss carries no route metadata, so a global guard reading none of it refuses,\n * which makes every 404 a 401 for an anonymous caller with no `@Public()`\n * anywhere to put. **That is deliberate and stays the default**: an unmatched\n * path answering 404 while every real path answers 401 tells a prober exactly\n * which paths exist.\n *\n * `notFound: 'public'` opts into the conventional 404 by reporting the miss as\n * public. Either way `UNMATCHED` is set, and no real route ever sets it, so a\n * guard can tell a genuinely public route from one that matched nothing.\n */\nconst unmatchedContext = (req: Request, isPublic: boolean): RouteContext =>\n Object.freeze({\n controller: '(unmatched)',\n handler: '(none)',\n method: req.method as HttpMethod,\n path: new URL(req.url).pathname,\n get: <T>(key: MetaKey<T>): T | undefined => {\n if (key.id === UNMATCHED.id) return true as T;\n if (key.id === PUBLIC.id && isPublic) return true as T;\n return undefined;\n },\n });\n\n/**\n * Bun answers an unmatched path itself, so nothing in the middleware chain ever\n * sees it - which makes a 404 invisible to request logging, metrics and tracing.\n *\n * This is the only `fetch` handler dunx installs, and it is not a router: Bun\n * still does all the matching, and this runs only once Bun has decided nothing\n * matched. It puts the global middleware in front of a 404 in the framework's\n * own error shape.\n *\n * Composed per request rather than at boot, because the context names the path\n * that missed. That allocation is on the 404 path only.\n */\nexport const buildFallback = (\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n notFound: 'guarded' | 'public' = 'guarded',\n): RouteHandler => {\n // The canonical status name, not a sentence naming the path back at the\n // caller: an unmatched path is the one place where echoing the request would\n // tell a prober something about the surface it just failed to find.\n const miss: RouteHandler = () => {\n throw new HttpError(HttpStatusCode.NOT_FOUND, 'NOT_FOUND');\n };\n\n const run: RouteHandler = async (req) => {\n try {\n return await compose(\n middleware,\n unmatchedContext(req, notFound === 'public'),\n miss,\n )(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return cors ? withCors(cors, run) : run;\n};\n\n/**\n * The direct path, taken when a route has no middleware and no CORS. Nothing here\n * is `async`: every step looks at what it got and only allocates a promise when\n * there is genuinely something to wait for.\n *\n * The general path is `async (req) => toResponse(await handler(await read(req)))`\n * inside an `async` try/catch - four `await`s across two async frames, on values\n * that are usually not thenable at all. A route with no declared schemas awaits\n * nothing; a route with only `query` or `params` awaits nothing either, because\n * every Standard Schema validator worth using is synchronous. Even a `body` route,\n * which really does have to wait for `req.json()`, pays one promise link instead of\n * six frames.\n *\n * Worth ~6 points of throughput against raw `Bun.serve` on the `params` scenario\n * when it covered only schema-less routes, and a further ~5 on `validate` when it\n * was extended to cover reading ones - which is most of what separated dunx from\n * Elysia, whose whole trick is compiling this shape ahead of time.\n *\n * A handler or a validator that *does* return a promise still works: it is adopted\n * here rather than awaited by a wrapper.\n */\nconst directOr = (\n guarded: RouteHandler,\n route: DiscoveredRoute,\n read: InputReader,\n status: number,\n onError: ErrorMapper,\n noMiddleware: boolean,\n): ServedHandler => {\n if (!noMiddleware) return guarded;\n\n // `toResponse` throws on a value `JSON.stringify` cannot take, so it is inside\n // the mapper's reach on every branch - including the `then` callbacks, where a\n // throw would otherwise escape as an unhandled rejection instead of a 500.\n const settle = (value: unknown, req: BunRequest): Response => {\n try {\n return toResponse(value, status);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const invoke = (\n input: RouteInput,\n req: BunRequest,\n ): Response | Promise<Response> => {\n try {\n const value = route.handler(input);\n return value instanceof Promise\n ? value.then(\n (resolved) => settle(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : settle(value, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return (req) => {\n try {\n const input = read(req);\n return input instanceof Promise\n ? input.then(\n (resolved) => invoke(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : invoke(input, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n};\n\nexport const buildRoutes = (\n discovered: readonly DiscoveredRoute[],\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n resolve: GuardResolver = construct,\n): BunRoutes => {\n assertNoCollisions(discovered);\n const routes: BunRoutes = {};\n // One instance per guard class for the whole table - what the container returns,\n // and what the default resolver has to match to be interchangeable with it.\n const instances = new Map<Ctor<Middleware>, Middleware>();\n const guardOf = (guard: Ctor<Middleware>): Middleware => {\n const existing = instances.get(guard);\n if (existing) return existing;\n const created = resolve(guard);\n instances.set(guard, created);\n return created;\n };\n\n for (const route of discovered) {\n // Schemas, parsers, the status and the route context resolve here, once. What\n // survives into the request path is one closure that reads no metadata.\n const read = buildInputReader(route.options);\n const status = statusFor(route);\n // Global outermost, then the controller's guards, then the method's.\n const chain = [...middleware, ...(route.guards ?? []).map(guardOf)];\n const chained = compose(chain, buildContext(route), async (req) =>\n toResponse(await route.handler(await read(req)), status),\n );\n const guarded: RouteHandler = async (req) => {\n try {\n return await chained(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const byMethod = (routes[route.path] ??= {});\n // Outside the error mapper, so a mapped 500 still carries the CORS headers the\n // browser needs in order to show it.\n byMethod[route.method] = cors\n ? withCors(cors, guarded)\n : directOr(guarded, route, read, status, onError, chain.length === 0);\n }\n\n if (cors) {\n for (const byMethod of Object.values(routes)) {\n byMethod.OPTIONS = preflight(cors, Object.keys(byMethod));\n }\n }\n\n return routes;\n};\n",
|
|
23
|
+
"import { AppError, type Ctor, type ModuleRef } from '@dunx/core';\nimport type { BunRequest } from 'bun';\nimport type { DiscoveredRoute } from '../route/discover.js';\nimport type { HttpMethod } from '../route/marker.js';\nimport { PUBLIC, UNMATCHED, type MetaKey } from '../route/metadata.js';\nimport type { RouteInput } from '../route/schema.js';\nimport type { UpgradeHandler } from '../ws/adapter.js';\nimport { buildContext, type RouteContext } from './context.js';\nimport { preflight, withCors, type CorsOptions } from './cors.js';\nimport { defaultErrorMapper, HttpError, type ErrorMapper } from './errors.js';\nimport { buildInputReader, type InputReader } from './input.js';\nimport {\n compose,\n type Middleware,\n type RouteHandler,\n type ServedHandler,\n} from './middleware.js';\nimport { HttpStatusCode } from './status.js';\n\n/** How a `@UseGuards` class becomes an instance. `listen()` passes `app.get`. */\n/**\n * How a guard or a module's middleware becomes an instance.\n *\n * `from` names the module whose scope it resolves in - module middleware has to be\n * built from the module that declared it, or it could not inject that module's private\n * providers, which is the point of declaring it there.\n */\nexport type GuardResolver = (\n guard: Ctor<Middleware>,\n from?: ModuleRef,\n) => Middleware;\n\nconst construct: GuardResolver = (guard) =>\n new (guard as new () => Middleware)();\n\n/** `OPTIONS` is never a `@Get`-style route - only CORS mounts one. */\nexport type RouteMethod = HttpMethod | 'OPTIONS';\n\nexport type BunRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler>>\n>;\n\n/**\n * What `listen()` hands `Bun.serve`: the HTTP table plus one `GET` per gateway,\n * whose handler may answer `undefined` because the socket was upgraded.\n */\nexport type ServeRoutes = Record<\n string,\n Partial<Record<RouteMethod, ServedHandler | UpgradeHandler>>\n>;\n\n/**\n * A `Response` passes through untouched - that is the escape hatch, and nothing\n * about it is worth second-guessing. Nothing at all is a 204: `Response.json(null)`\n * would be a body claiming to be no body.\n */\nconst toResponse = (value: unknown, status: number): Response => {\n if (value instanceof Response) return value;\n if (value === undefined || value === null) {\n return new Response(null, { status: HttpStatusCode.NO_CONTENT });\n }\n return Response.json(value, { status });\n};\n\n/** The usual rule: an explicit `status`, else 201 for POST, else 200. */\nconst statusFor = (route: DiscoveredRoute): number =>\n route.options?.status ??\n (route.method === 'POST' ? HttpStatusCode.CREATED : HttpStatusCode.OK);\n\n/**\n * Bun silently lets one route win on a collision, so a duplicate method+path is a\n * boot error naming both handlers. Run twice: once at `create()` on the discovered\n * paths, and again from `buildRoutes` at `listen()` on the final, prefixed ones.\n */\nexport const assertNoCollisions = (\n discovered: readonly DiscoveredRoute[],\n): void => {\n const owners = new Map<string, string>();\n\n for (const route of discovered) {\n const key = `${route.method} ${route.path}`;\n const owner = `${route.controller}.${route.handlerName}`;\n const existing = owners.get(key);\n\n if (existing !== undefined) {\n throw new AppError(\n `Route collision: ${key} is declared by ${existing} and by ${owner}. ` +\n 'Bun would keep only one of them.',\n );\n }\n owners.set(key, owner);\n }\n};\n\n/**\n * A gateway's upgrade is a native route like any other, so a path claimed by both a\n * controller and a gateway would lose one of them when the two tables merge.\n */\nexport const assertNoGatewayCollisions = (\n discovered: readonly DiscoveredRoute[],\n gatewayPaths: readonly string[],\n): void => {\n const gateways = new Set(gatewayPaths);\n\n for (const route of discovered) {\n if (gateways.has(route.path)) {\n throw new AppError(\n `Gateway path collision: ${route.path} is served by a gateway and by ` +\n `${route.controller}.${route.handlerName}(). The upgrade is a route too, ` +\n 'so one of them would be dropped.',\n );\n }\n }\n};\n\n/**\n * The two tables in one. A gateway's `GET` is what Bun's router matches on an\n * upgrade - the reason no `fetch` handler is needed for a socket to connect.\n */\nexport const withUpgradeRoutes = (\n routes: BunRoutes,\n gateways: ReadonlyMap<string, UpgradeHandler>,\n): ServeRoutes => {\n const merged: ServeRoutes = { ...routes };\n for (const [path, upgrade] of gateways) merged[path] = { GET: upgrade };\n return merged;\n};\n\n/**\n * The context an unmatched request gets. There is no controller and no handler,\n * and saying so is more useful to a log line than an empty string.\n *\n * A miss carries no route metadata, so a global guard reading none of it refuses,\n * which makes every 404 a 401 for an anonymous caller with no `@Public()`\n * anywhere to put. **That is deliberate and stays the default**: an unmatched\n * path answering 404 while every real path answers 401 tells a prober exactly\n * which paths exist.\n *\n * `notFound: 'public'` opts into the conventional 404 by reporting the miss as\n * public. Either way `UNMATCHED` is set, and no real route ever sets it, so a\n * guard can tell a genuinely public route from one that matched nothing.\n */\nconst unmatchedContext = (req: Request, isPublic: boolean): RouteContext =>\n Object.freeze({\n controller: '(unmatched)',\n handler: '(none)',\n method: req.method as HttpMethod,\n path: new URL(req.url).pathname,\n get: <T>(key: MetaKey<T>): T | undefined => {\n if (key.id === UNMATCHED.id) return true as T;\n if (key.id === PUBLIC.id && isPublic) return true as T;\n return undefined;\n },\n });\n\n/**\n * Bun answers an unmatched path itself, so nothing in the middleware chain ever\n * sees it - which makes a 404 invisible to request logging, metrics and tracing.\n *\n * This is the only `fetch` handler dunx installs, and it is not a router: Bun\n * still does all the matching, and this runs only once Bun has decided nothing\n * matched. It puts the global middleware in front of a 404 in the framework's\n * own error shape.\n *\n * Composed per request rather than at boot, because the context names the path\n * that missed. That allocation is on the 404 path only.\n */\nexport const buildFallback = (\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n notFound: 'guarded' | 'public' = 'guarded',\n): RouteHandler => {\n // The canonical status name, not a sentence naming the path back at the\n // caller: an unmatched path is the one place where echoing the request would\n // tell a prober something about the surface it just failed to find.\n const miss: RouteHandler = () => {\n throw new HttpError(HttpStatusCode.NOT_FOUND, 'NOT_FOUND');\n };\n\n const run: RouteHandler = async (req) => {\n try {\n return await compose(\n middleware,\n unmatchedContext(req, notFound === 'public'),\n miss,\n )(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return cors ? withCors(cors, run) : run;\n};\n\n/**\n * The direct path, taken when a route has no middleware and no CORS. Nothing here\n * is `async`: every step looks at what it got and only allocates a promise when\n * there is genuinely something to wait for.\n *\n * The general path is `async (req) => toResponse(await handler(await read(req)))`\n * inside an `async` try/catch - four `await`s across two async frames, on values\n * that are usually not thenable at all. A route with no declared schemas awaits\n * nothing; a route with only `query` or `params` awaits nothing either, because\n * every Standard Schema validator worth using is synchronous. Even a `body` route,\n * which really does have to wait for `req.json()`, pays one promise link instead of\n * six frames.\n *\n * Worth ~6 points of throughput against raw `Bun.serve` on the `params` scenario\n * when it covered only schema-less routes, and a further ~5 on `validate` when it\n * was extended to cover reading ones - which is most of what separated dunx from\n * Elysia, whose whole trick is compiling this shape ahead of time.\n *\n * A handler or a validator that *does* return a promise still works: it is adopted\n * here rather than awaited by a wrapper.\n */\nconst directOr = (\n guarded: RouteHandler,\n route: DiscoveredRoute,\n read: InputReader,\n status: number,\n onError: ErrorMapper,\n noMiddleware: boolean,\n): ServedHandler => {\n if (!noMiddleware) return guarded;\n\n // `toResponse` throws on a value `JSON.stringify` cannot take, so it is inside\n // the mapper's reach on every branch - including the `then` callbacks, where a\n // throw would otherwise escape as an unhandled rejection instead of a 500.\n const settle = (value: unknown, req: BunRequest): Response => {\n try {\n return toResponse(value, status);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const invoke = (\n input: RouteInput,\n req: BunRequest,\n ): Response | Promise<Response> => {\n try {\n const value = route.handler(input);\n return value instanceof Promise\n ? value.then(\n (resolved) => settle(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : settle(value, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n return (req) => {\n try {\n const input = read(req);\n return input instanceof Promise\n ? input.then(\n (resolved) => invoke(resolved, req),\n (error: unknown) => onError(error, req),\n )\n : invoke(input, req);\n } catch (error) {\n return onError(error, req);\n }\n };\n};\n\nexport const buildRoutes = (\n discovered: readonly DiscoveredRoute[],\n middleware: readonly Middleware[] = [],\n onError: ErrorMapper = defaultErrorMapper,\n cors?: CorsOptions,\n resolve: GuardResolver = construct,\n): BunRoutes => {\n assertNoCollisions(discovered);\n const routes: BunRoutes = {};\n // One instance per guard class for the whole table - what the container returns,\n // and what the default resolver has to match to be interchangeable with it.\n const instances = new Map<Ctor<Middleware>, Middleware>();\n const guardOf = (guard: Ctor<Middleware>, from?: ModuleRef): Middleware => {\n const existing = instances.get(guard);\n if (existing) return existing;\n const created = resolve(guard, from);\n instances.set(guard, created);\n return created;\n };\n\n for (const route of discovered) {\n // Schemas, parsers, the status and the route context resolve here, once. What\n // survives into the request path is one closure that reads no metadata.\n const read = buildInputReader(route.options);\n const status = statusFor(route);\n /**\n * Global outermost, then the declaring module's middleware, then the controller's\n * guards, then the method's.\n *\n * There is no ancestor layer: a module's middleware applies to its own\n * controllers, so importing a module never changes the request path of the\n * importer's routes.\n */\n const chain = [\n ...middleware,\n ...(route.moduleMiddleware ?? []).map((entry) =>\n guardOf(entry, route.module),\n ),\n ...(route.guards ?? []).map((guard) => guardOf(guard, route.module)),\n ];\n const chained = compose(chain, buildContext(route), async (req) =>\n toResponse(await route.handler(await read(req)), status),\n );\n const guarded: RouteHandler = async (req) => {\n try {\n return await chained(req);\n } catch (error) {\n return onError(error, req);\n }\n };\n\n const byMethod = (routes[route.path] ??= {});\n // Outside the error mapper, so a mapped 500 still carries the CORS headers the\n // browser needs in order to show it.\n byMethod[route.method] = cors\n ? withCors(cors, guarded)\n : directOr(guarded, route, read, status, onError, chain.length === 0);\n }\n\n if (cors) {\n for (const byMethod of Object.values(routes)) {\n byMethod.OPTIONS = preflight(cors, Object.keys(byMethod));\n }\n }\n\n return routes;\n};\n",
|
|
24
24
|
"import type { BunRequest } from 'bun';\nimport type {\n RouteInput,\n RouteSchemas,\n StandardSchemaIssue,\n StandardSchemaResult,\n StandardSchemaV1,\n} from '../route/schema.js';\nimport {\n HttpError,\n ValidationError,\n type InputSource,\n type ValidationIssue,\n} from './errors.js';\nimport { HttpStatusCode } from './status.js';\n\n/**\n * Built once per route at boot. A route that declares nothing gets the identity\n * reader - no parse, no validation, not even a promise.\n *\n * A reader **returns a promise only when it has something to wait for**. A `body`\n * schema always does; `query` and `params` against a synchronous validator - which\n * zod, Valibot and ArkType all are - resolve without one.\n */\nexport type InputReader = (req: BunRequest) => RouteInput | Promise<RouteInput>;\n\ninterface InputDraft {\n req: BunRequest;\n body?: unknown;\n query?: unknown;\n params?: unknown;\n}\n\n/**\n * One declared schema's contribution to the draft, returning the draft so the\n * steps chain without a wrapper. A bare `InputDraft` means it finished\n * synchronously, which is the common case and the reason this is not `async`:\n * Standard Schema *permits* a promise, so awaiting unconditionally costs an async\n * frame and a microtask tick per schema for a validator that never returns one.\n */\ntype Fill = (draft: InputDraft) => InputDraft | Promise<InputDraft>;\ntype BodyParser = (req: BunRequest) => Promise<unknown>;\n\n/** What `URLSearchParams` and `FormData` both offer, and all {@link grouped} needs. */\ninterface Enumerable {\n forEach(visit: (value: unknown, key: string) => void): void;\n}\n\n/**\n * A repeated key becomes an array, so `?tag=a&tag=b` reaches the schema whole\n * instead of silently losing `a`. Shared by query strings, urlencoded bodies and\n * multipart form data.\n *\n * `forEach` rather than `for…of`: both collections implement it natively, and\n * destructuring an iterator allocates a two-element array per entry. Measured at\n * ~150 ns/request cheaper on a three-pair query string.\n */\nconst grouped = (entries: Enumerable): Record<string, unknown> => {\n const collected: Record<string, unknown> = {};\n\n entries.forEach((value, key) => {\n const existing = collected[key];\n if (existing === undefined) collected[key] = value;\n else if (Array.isArray(existing)) (existing as unknown[]).push(value);\n else collected[key] = [existing, value];\n });\n\n return collected;\n};\n\nconst asJson: BodyParser = (req) => req.json();\nconst asUrlEncoded: BodyParser = async (req) =>\n grouped(new URLSearchParams(await req.text()));\nconst asMultipart: BodyParser = async (req) => grouped(await req.formData());\nconst asText: BodyParser = (req) => req.text();\n\n/** `application/vnd.api+json` and friends parse as JSON; `text/csv` as text. */\nconst parserFor = (media: string): BodyParser | undefined => {\n if (media === 'application/json' || media.endsWith('+json')) return asJson;\n if (media === 'application/x-www-form-urlencoded') return asUrlEncoded;\n if (media === 'multipart/form-data') return asMultipart;\n if (media.startsWith('text/')) return asText;\n return undefined;\n};\n\nconst JSON_MEDIA = 'application/json';\n\n// No content-type reads as JSON: fetch omits the header for a bodyless request and\n// a 415 there would be useless, since the schema is about to reject `undefined`.\nconst mediaTypeOf = (req: BunRequest): string => {\n const header = req.headers.get('content-type');\n // The header almost every JSON client sends, verbatim - worth not slicing,\n // trimming and lowercasing on the hot path.\n if (header === JSON_MEDIA || header === null) return JSON_MEDIA;\n const end = header.indexOf(';');\n const media = (end === -1 ? header : header.slice(0, end)).trim();\n return media === '' ? JSON_MEDIA : media.toLowerCase();\n};\n\nconst flatten = (issue: StandardSchemaIssue): ValidationIssue => {\n const path = issue.path\n ?.map((segment) =>\n String(typeof segment === 'object' ? segment.key : segment),\n )\n .join('.');\n\n return path === undefined || path === ''\n ? { message: issue.message }\n : { message: issue.message, path };\n};\n\n/** A rejected schema is a 400 carrying every issue, path flattened to dots. */\nconst accept = (source: InputSource, result: StandardSchemaResult<unknown>) => {\n if (result.issues !== undefined) {\n throw new ValidationError(source, result.issues.map(flatten));\n }\n return result.value;\n};\n\n/**\n * Validates, assigns, and hands the draft back. Returning the draft rather than\n * `void` is what lets the reader be `(req) => fill({ req })`: a body route then\n * costs one promise link in total, where threading the draft back through a second\n * `then` cost two - worth ~120 ns per request, measured.\n */\nconst fillWith = (\n draft: InputDraft,\n source: InputSource,\n schema: StandardSchemaV1,\n value: unknown,\n): InputDraft | Promise<InputDraft> => {\n const result = schema['~standard'].validate(value);\n\n if (result instanceof Promise) {\n return result.then((settled) => {\n draft[source] = accept(source, settled);\n return draft;\n });\n }\n draft[source] = accept(source, result);\n return draft;\n};\n\nconst bodyFill =\n (schema: StandardSchemaV1): Fill =>\n (draft) => {\n const media = mediaTypeOf(draft.req);\n const parse = parserFor(media);\n\n if (parse === undefined) {\n throw new HttpError(\n HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,\n `Unsupported content type \"${media}\". Declared bodies accept ` +\n 'application/json, application/x-www-form-urlencoded, multipart/form-data or text/*.',\n );\n }\n\n // Both handlers on one `then`, so the parse costs a single promise link. A\n // `ValidationError` from the success handler is deliberately not visible to the\n // rejection handler - only an unreadable or mangled body is a parse failure.\n return parse(draft.req).then(\n (value) => fillWith(draft, 'body', schema, value),\n (error: unknown) => {\n // A body the caller mangled is a 400. Only an unreadable stream would be ours.\n throw new HttpError(\n HttpStatusCode.BAD_REQUEST,\n `Malformed ${media} body`,\n { cause: error },\n );\n },\n );\n };\n\n/**\n * The query string, without parsing the whole URL to reach it. `new URL(req.url)`\n * resolves scheme, host, port, path and fragment to hand back a `searchParams`, and\n * measured **~1,000 ns of the ~1,500 ns** a `query` route used to cost - more than\n * the entire body reader. `RequestLoggingMiddleware` took the same slice for the\n * same reason.\n *\n * The fragment is stripped even though a client is not supposed to send one, because\n * `new URL` stripped it and a hostile request-target should not change what a schema\n * sees.\n */\nconst searchOf = (url: string): string => {\n const start = url.indexOf('?');\n if (start === -1) return '';\n const end = url.indexOf('#', start + 1);\n return end === -1 ? url.slice(start + 1) : url.slice(start + 1, end);\n};\n\nconst queryFill =\n (schema: StandardSchemaV1): Fill =>\n (draft) => {\n const params = new URLSearchParams(searchOf(draft.req.url));\n return fillWith(draft, 'query', schema, grouped(params));\n };\n\nconst paramsFill =\n (schema: StandardSchemaV1): Fill =>\n (draft) =>\n fillWith(draft, 'params', schema, draft.req.params);\n\n/** Sequential, and stays sequential without a promise unless one is produced. */\nconst then =\n (first: Fill, second: Fill): Fill =>\n (draft) => {\n const started = first(draft);\n return started instanceof Promise ? started.then(second) : second(started);\n };\n\n/**\n * Folds the declared schemas into a single closure, the way `compose` folds\n * middleware: which parsers and validators run is decided here, at boot, so per\n * request there is no metadata to read and no branch left to take.\n */\nexport const buildInputReader = (\n options: RouteSchemas | undefined,\n): InputReader => {\n const fills: Fill[] = [];\n if (options?.body !== undefined) fills.push(bodyFill(options.body));\n if (options?.query !== undefined) fills.push(queryFill(options.query));\n if (options?.params !== undefined) fills.push(paramsFill(options.params));\n\n if (fills.length === 0) return (req) => ({ req });\n\n const fill = fills.reduce(then);\n return (req) => fill({ req });\n};\n",
|
|
25
25
|
"import type { BunRequest } from 'bun';\nimport type { RouteContext } from './context.js';\n\nexport type Next = () => Promise<Response>;\n\n/**\n * The single extension point. A guard is middleware that throws, an interceptor\n * wraps `next()`, a filter is the error mapper. `ctx` names the route and carries\n * what its decorators declared, resolved at boot - so a guard costs a Map lookup.\n */\nexport interface Middleware {\n handle(req: BunRequest, ctx: RouteContext, next: Next): Promise<Response>;\n}\n\nexport type RouteHandler = (req: BunRequest) => Promise<Response>;\n\n/**\n * What goes into the `Bun.serve` route table. Wider than `RouteHandler` because\n * Bun accepts a plain `Response`, which is what lets a route with nothing to\n * await skip promises altogether - see `buildRoutes`.\n */\nexport type ServedHandler = (req: BunRequest) => Response | Promise<Response>;\n\n/** Folded into one closure per route at boot - no per-request array iteration. */\nexport const compose = (\n middleware: readonly Middleware[],\n ctx: RouteContext,\n handler: RouteHandler,\n): RouteHandler =>\n middleware.reduceRight<RouteHandler>(\n (next, current) => (req) => current.handle(req, ctx, () => next(req)),\n handler,\n );\n",
|
|
26
26
|
"/**\n * The settings `app.set()` accepts. A key has to be declared here to be settable,\n * so the map is checked at compile time instead of being a string bag - a typo is\n * a type error, not a setting that silently never applies.\n */\nexport interface AppSettings {\n /**\n * Resolve the client address from `X-Forwarded-For` rather than the socket. Only\n * turn it on behind a proxy that rewrites the header: a direct client can send\n * whatever it likes.\n */\n 'trust proxy': boolean;\n}\n\nexport const defaultSettings = (): AppSettings => ({ 'trust proxy': false });\n",
|
|
27
27
|
"import { HandlerKind, markGateway, markHandler } from './marker.js';\n\ntype GatewayTarget = abstract new (...args: never[]) => object;\n// never[] is what makes an arbitrary method signature assignable, so a handler\n// may declare the payload type it expects. See the README, \"Typed payloads\".\ntype HandlerMethod = (...args: never[]) => unknown;\n\nexport const Gateway =\n (path = '/') =>\n <T extends GatewayTarget>(target: T): T => {\n markGateway(target, path);\n return target;\n };\n\nconst lifecycle =\n (kind: HandlerKind) =>\n () =>\n <T extends HandlerMethod>(value: T): T => {\n markHandler(value, { kind, event: undefined });\n return value;\n };\n\n/** Runs before the socket exists. Return a `Response` to refuse the upgrade. */\nexport const OnUpgrade = lifecycle(HandlerKind.UPGRADE);\nexport const OnOpen = lifecycle(HandlerKind.OPEN);\nexport const OnClose = lifecycle(HandlerKind.CLOSE);\nexport const OnDrain = lifecycle(HandlerKind.DRAIN);\nexport const OnPing = lifecycle(HandlerKind.PING);\nexport const OnPong = lifecycle(HandlerKind.PONG);\n\n/**\n * With an event name, the handler is routed the `data` of any\n * `{\"event\":\"<name>\",\"data\":...}` frame. With none, it is the raw catch-all and\n * receives every frame no named handler claimed.\n */\nexport const OnMessage =\n (event?: string) =>\n <T extends HandlerMethod>(value: T): T => {\n markHandler(value, { kind: HandlerKind.MESSAGE, event });\n return value;\n };\n",
|
|
28
28
|
"import { AppError } from '@dunx/core';\nimport type { PubSubRelay } from './relay.js';\n\n/**\n * The schemes `Bun.RedisClient` accepts. Checked here because Bun takes any string\n * and only fails later, at connect time, as an opaque `Connection closed` - which\n * an absence-tolerant relay would swallow, turning a typo into silent single-node\n * fan-out.\n */\nconst PROTOCOLS: readonly string[] = [\n 'redis:',\n 'rediss:',\n 'valkey:',\n 'valkeys:',\n 'redis+tls:',\n 'redis+unix:',\n 'redis+tls+unix:',\n];\n\n/** The same fallback chain `Bun.RedisClient` uses when given no URL. */\nexport const defaultRelayUrl = (): string =>\n process.env['VALKEY_URL'] ??\n process.env['REDIS_URL'] ??\n 'redis://localhost:6379';\n\nexport interface RedisRelayOptions {\n /** @default `$VALKEY_URL`, `$REDIS_URL`, then `redis://localhost:6379` */\n readonly url?: string;\n /**\n * Bun's reconnection budget.\n *\n * `0` by default, and that default is not a preference: a `Bun.RedisClient` that\n * never connects keeps an internal retry timer alive past `close()`, and the\n * process then never exits. A relay is exactly the connection most likely to be\n * absent - a single-node deployment with `REDIS_URL` left over from staging -\n * so the default has to be the one that lets the app boot, degrade, and still\n * exit. Raise it when Redis is a hard requirement and you want Bun to reconnect\n * for you.\n *\n * @default 0\n */\n readonly maxRetries?: number;\n /** @default 10000 */\n readonly connectionTimeout?: number;\n readonly tls?: boolean | Bun.TLSOptions;\n}\n\nconst assertUrl = (url: string): string => {\n let parsed: URL;\n try {\n parsed = new URL(url);\n } catch {\n throw new AppError(\n `${JSON.stringify(url)} is not a valid URL for the websocket relay. ` +\n 'Expected something like redis://localhost:6379.',\n );\n }\n if (!PROTOCOLS.includes(parsed.protocol)) {\n throw new AppError(\n `Unsupported protocol ${JSON.stringify(parsed.protocol)} in ` +\n `${JSON.stringify(url)}. Expected one of ${PROTOCOLS.join(', ')}.`,\n );\n }\n return url;\n};\n\n/**\n * A {@link PubSubRelay} on `Bun.RedisClient` - a Bun global, so this costs\n * `@dunx/http` no dependency at all.\n *\n * **Two connections, not one.** A client in subscriber mode rejects every data\n * command, and throws synchronously doing it, so the subscription cannot share the\n * socket that publishes. This is the same split the socket.io Redis adapter makes\n * with its `pubClient` / `subClient`.\n *\n * Both are opened lazily, on the first call that needs them, and a failed one is\n * discarded so the next call builds a fresh connection rather than reusing a dead\n * one.\n */\nexport class RedisRelay implements PubSubRelay {\n readonly #url: string;\n readonly #options: Bun.RedisOptions;\n #pub: Bun.RedisClient | undefined;\n #sub: Bun.RedisClient | undefined;\n /** Remembered only so `close()` can leave subscriber mode. See `close()`. */\n #channel: string | undefined;\n\n constructor(options: RedisRelayOptions = {}) {\n this.#url = assertUrl(options.url ?? defaultRelayUrl());\n this.#options = {\n maxRetries: options.maxRetries ?? 0,\n ...(options.connectionTimeout !== undefined && {\n connectionTimeout: options.connectionTimeout,\n }),\n ...(options.tls !== undefined && { tls: options.tls }),\n };\n }\n\n /** The URL with any password removed, for logs and error messages. */\n get url(): string {\n const parsed = new URL(this.#url);\n if (parsed.password) parsed.password = '***';\n return parsed.toString();\n }\n\n async publish(channel: string, message: string): Promise<number> {\n const client = (this.#pub ??= new Bun.RedisClient(\n this.#url,\n this.#options,\n ));\n try {\n return await client.publish(channel, message);\n } catch (error) {\n if (this.#pub === client) {\n this.#pub = undefined;\n client.close();\n }\n throw error;\n }\n }\n\n async subscribe(\n channel: string,\n listener: (message: string) => void,\n ): Promise<void> {\n const client = (this.#sub ??= new Bun.RedisClient(\n this.#url,\n this.#options,\n ));\n try {\n // `connect()` before `subscribe()`, and that order is load-bearing too:\n // measured on Bun 1.3.14, a `subscribe()` that cannot reach the server\n // leaves the client holding the event loop open even after `close()` and\n // even with `maxRetries: 0`, so an app pointed at an absent broker would\n // never exit. Failing at `connect()` instead releases cleanly, and says\n // `Connection closed` rather than `Max reconnection attempts reached`.\n await client.connect();\n await client.subscribe(channel, listener);\n this.#channel = channel;\n } catch (error) {\n if (this.#sub === client) {\n this.#sub = undefined;\n client.close();\n }\n throw error;\n }\n }\n\n /**\n * `UNSUBSCRIBE` before `close()`, and that order is load-bearing: measured on\n * Bun 1.3.14, a `Bun.RedisClient` left in subscriber mode keeps the process\n * alive after `close()`, so an app that shut down cleanly would never exit.\n * Leaving subscriber mode first fixes it. Recorded in docs/bun-apis.md.\n */\n async close(): Promise<void> {\n const sub = this.#sub;\n const channel = this.#channel;\n this.#pub?.close();\n this.#pub = undefined;\n this.#sub = undefined;\n this.#channel = undefined;\n if (!sub) return;\n if (channel !== undefined) {\n try {\n await sub.unsubscribe(channel);\n } catch {\n // A socket that is already gone is not in subscriber mode either, and\n // throwing here would leave the connection below unclosed.\n }\n }\n sub.close();\n }\n}\nObject.defineProperty(RedisRelay, Symbol.for('dunx.deps'), {\n value: () => [{ unresolved: \"options: RedisRelayOptions = {}\" }],\n});\n"
|
|
29
29
|
],
|
|
30
|
-
"mappings": ";;;;;;AAMA,IAAM,QAAQ,OAAO,IAAI,YAAY;AACrC,IAAM,aAAa,OAAO,IAAI,iBAAiB;AAuBxC,IAAM,cAAc,CAAC,SAC1B,OAAO,SAAS,aAAa,KAAK,IAAI;AAUjC,IAAM,YAAY,CAAC,QAAgB,SAA0B;AAAA,EAClE,OAAO,eAAe,QAAQ,OAAO,EAAE,OAAO,MAAM,cAAc,KAAK,CAAC;AAAA;AAGnE,IAA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AAK,GAAkB;AAAA,IAC3B,MAAM,MAAM,KAAK;AAAA,IACjB,MAAM,UAAU,KAAK;AAAA,IACrB,KAAK,MAAM,MAAM;AAAA,IACjB,KAAK,OAAO;AAAA,IACZ,KAAK,OAAO;AAAA,IACZ,KAAK,WAAW;AAAA,IAChB,IAAI,CAAC;AAAA,MAAK;AAAA,IACV,IAAI,YAAY,WAAW;AAAA,MACzB,IAAI;AAAA,QACF,MAAM,IAAI,YAAY,OAAO;AAAA,QAC7B,MAAM;AAAA,IAIV;AAAA,IACA,IAAI,MAAM;AAAA;AAEd;AACA,OAAO,eAAe,YAAY,OAAO,IAAI,WAAW,GAAG;AAAA,EACzD,OAAO,MAAM,CAAC,EAAE,YAAY,kCAAkC,CAAC;AACjE,CAAC;",
|
|
31
|
+
"debugId": "F88308694CAB730E64756E2164756E21",
|
|
32
32
|
"names": []
|
|
33
33
|
}
|
package/dist/route/discover.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Ctor } from '@dunx/core';
|
|
1
|
+
import type { Ctor, ModuleRef } from '@dunx/core';
|
|
2
2
|
import type { Middleware } from '../server/middleware.js';
|
|
3
3
|
import { type HttpMethod } from './marker.js';
|
|
4
4
|
import { type MetaRecord } from './metadata.js';
|
|
@@ -23,6 +23,17 @@ export interface DiscoveredRoute {
|
|
|
23
23
|
readonly classMeta?: MetaRecord | undefined;
|
|
24
24
|
/** Class-level `@UseGuards` first, then method-level. `buildRoutes` resolves them. */
|
|
25
25
|
readonly guards?: readonly Ctor<Middleware>[] | undefined;
|
|
26
|
+
/**
|
|
27
|
+
* The module that declared this route's controller, and the middleware that module
|
|
28
|
+
* declared - applied to these routes and to nothing else.
|
|
29
|
+
*
|
|
30
|
+
* Filled by `HttpFactory`, which is the only place that knows the module graph.
|
|
31
|
+
* `module` is carried alongside so each entry resolves from **that module's scope**,
|
|
32
|
+
* which is the whole point: module middleware can inject providers the module keeps
|
|
33
|
+
* private.
|
|
34
|
+
*/
|
|
35
|
+
readonly module?: ModuleRef | undefined;
|
|
36
|
+
readonly moduleMiddleware?: readonly Ctor<Middleware>[] | undefined;
|
|
26
37
|
}
|
|
27
38
|
export declare const joinPath: (prefix: string, path: string) => string;
|
|
28
39
|
/**
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
import type { BunRequest } from 'bun';
|
|
2
|
-
import { type App, type AppOptions, type Ctor, type InjectionToken, type ShutdownSignal } from '@dunx/core';
|
|
2
|
+
import { type App, type AppOptions, type Ctor, type InjectionToken, type ModuleRef, type ShutdownSignal } from '@dunx/core';
|
|
3
3
|
import { type DiscoveredRoute } from '../route/discover.js';
|
|
4
4
|
import type { WebSocketRuntime } from '../ws/adapter.js';
|
|
5
5
|
import type { PubSubRelay, RelayOptions } from '../ws/relay.js';
|
|
6
6
|
import type { SocketOptions } from '../ws/socket.js';
|
|
7
7
|
import type { CorsOptions } from './cors.js';
|
|
8
|
-
import { type
|
|
8
|
+
import { type ErrorHandler } from './errors.js';
|
|
9
9
|
import type { Middleware } from './middleware.js';
|
|
10
10
|
import { type RequestLoggingOptions } from './request-logging.js';
|
|
11
11
|
import { type AppSettings } from './settings.js';
|
|
@@ -13,7 +13,18 @@ export interface HttpOptions extends AppOptions {
|
|
|
13
13
|
readonly port?: number;
|
|
14
14
|
/** Resolved from the container, so middleware can inject(). */
|
|
15
15
|
readonly middleware?: readonly Ctor<Middleware>[];
|
|
16
|
-
|
|
16
|
+
/**
|
|
17
|
+
* Replaces the default mapper.
|
|
18
|
+
*
|
|
19
|
+
* A bare `ErrorMapper` function, or an `ErrorFilter` **class** - which is the one
|
|
20
|
+
* to prefer, because a class is resolved from the container and can therefore
|
|
21
|
+
* inject the `Logger` or the config a real filter needs. A mapper cannot; dunx's
|
|
22
|
+
* own default has to be curried over its logger for exactly that reason.
|
|
23
|
+
*
|
|
24
|
+
* A filter with dependencies needs them bindable, the same rule `middleware`
|
|
25
|
+
* entries follow; one with none self-binds and needs no `providers` entry.
|
|
26
|
+
*/
|
|
27
|
+
readonly onError?: ErrorHandler;
|
|
17
28
|
/**
|
|
18
29
|
* One structured entry per request, on by default. `false` removes it; an
|
|
19
30
|
* options object tunes what it records. See {@link RequestLoggingMiddleware}.
|
|
@@ -92,9 +103,11 @@ export interface HttpApp extends App {
|
|
|
92
103
|
}
|
|
93
104
|
export declare class HttpApplication implements HttpApp {
|
|
94
105
|
#private;
|
|
106
|
+
/** Forwarded from the container so an app can log scope warnings at boot. */
|
|
107
|
+
readonly warnings: readonly string[];
|
|
95
108
|
readonly closed: Promise<void>;
|
|
96
109
|
readonly gatewayPaths: readonly string[];
|
|
97
|
-
constructor(app: App, discovered: readonly DiscoveredRoute[], options: HttpOptions, websocket?: WebSocketRuntime);
|
|
110
|
+
constructor(app: App, discovered: readonly DiscoveredRoute[], options: HttpOptions, root: ModuleRef, websocket?: WebSocketRuntime);
|
|
98
111
|
get<T>(token: InjectionToken<T>): T;
|
|
99
112
|
setGlobalPrefix(prefix: string): this;
|
|
100
113
|
use(...middleware: readonly Ctor<Middleware>[]): this;
|
package/dist/server/errors.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { AppError, type Logger } from '@dunx/core';
|
|
1
|
+
import { AppError, type Ctor, type Logger } from '@dunx/core';
|
|
2
2
|
export declare class HttpError extends AppError {
|
|
3
3
|
readonly status: number;
|
|
4
4
|
name: string;
|
|
@@ -22,6 +22,70 @@ export declare class ValidationError extends HttpError {
|
|
|
22
22
|
constructor(source: InputSource, issues: readonly ValidationIssue[]);
|
|
23
23
|
}
|
|
24
24
|
export type ErrorMapper = (error: unknown, req: Request) => Response;
|
|
25
|
+
/**
|
|
26
|
+
* The class form of {@link ErrorMapper}, and the one to reach for in an app.
|
|
27
|
+
*
|
|
28
|
+
* A mapper is a function, which means it cannot inject: the interesting ones need
|
|
29
|
+
* the app's config to decide how much of an error to reveal, or its `Logger` to
|
|
30
|
+
* record the ones that became a 500. dunx's own default proves the point - it is
|
|
31
|
+
* `errorMapper(logger)`, a curried factory, because currying was the only way to
|
|
32
|
+
* hand a function a dependency.
|
|
33
|
+
*
|
|
34
|
+
* A filter is resolved **from the container**, exactly as `HttpOptions.middleware`
|
|
35
|
+
* entries are, so it takes whatever it needs as constructor parameters:
|
|
36
|
+
*
|
|
37
|
+
* ```ts
|
|
38
|
+
* export class AppErrorFilter extends ErrorFilter {
|
|
39
|
+
* constructor(
|
|
40
|
+
* private readonly logger: Logger,
|
|
41
|
+
* private readonly config: AppConfigService,
|
|
42
|
+
* ) {}
|
|
43
|
+
*
|
|
44
|
+
* catch(error: unknown, req: Request): Response {
|
|
45
|
+
* ...
|
|
46
|
+
* }
|
|
47
|
+
* }
|
|
48
|
+
*
|
|
49
|
+
* // It is a provider like any other, so it goes in a module:
|
|
50
|
+
* @Module({ providers: [AppErrorFilter] })
|
|
51
|
+
* // and then:
|
|
52
|
+
* HttpFactory.create(root, { onError: AppErrorFilter });
|
|
53
|
+
* ```
|
|
54
|
+
*
|
|
55
|
+
* `abstract class` rather than an interface, so it is a runtime value and therefore
|
|
56
|
+
* usable as an injection token - an app that wants to swap filters by binding one
|
|
57
|
+
* can. Extending it is optional: `onError` accepts any class with a matching
|
|
58
|
+
* `catch`, because the check is structural.
|
|
59
|
+
*
|
|
60
|
+
* The method is `catch` to match the vocabulary of the thing it replaces, NestJS's
|
|
61
|
+
* `ExceptionFilter.catch`. A filter that cannot handle an error should rethrow it,
|
|
62
|
+
* or delegate to `defaultErrorMapper`.
|
|
63
|
+
*/
|
|
64
|
+
export declare abstract class ErrorFilter {
|
|
65
|
+
abstract catch(error: unknown, req: Request): Response;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* What `onError` accepts. A bare mapper still works and is the cheaper thing for a
|
|
69
|
+
* filter with no dependencies; a class is what an app that needs one uses.
|
|
70
|
+
*/
|
|
71
|
+
export type ErrorHandler = ErrorMapper | Ctor<ErrorFilter>;
|
|
72
|
+
/**
|
|
73
|
+
* Whether `onError` was given a class rather than a mapper.
|
|
74
|
+
*
|
|
75
|
+
* Both are `typeof === 'function'`, so the discriminator is the prototype carrying
|
|
76
|
+
* a `catch`: a class declaration always has one, and neither an arrow function nor
|
|
77
|
+
* a `function` expression ever does. Checking `prototype` alone would be wrong -
|
|
78
|
+
* `function mapper() {}` has an empty one.
|
|
79
|
+
*/
|
|
80
|
+
export declare const isErrorFilter: (handler: ErrorHandler) => handler is Ctor<ErrorFilter>;
|
|
81
|
+
/**
|
|
82
|
+
* Narrows an `ErrorHandler` to the mapper the request path actually calls.
|
|
83
|
+
*
|
|
84
|
+
* `resolve` is typed for this one token rather than generically: the only thing ever
|
|
85
|
+
* looked up here is the filter, and a `<T>(token: Ctor<T>) => T` signature makes
|
|
86
|
+
* every caller - a test included - satisfy a polymorphic contract it does not need.
|
|
87
|
+
*/
|
|
88
|
+
export declare const toErrorMapper: (handler: ErrorHandler, resolve: (token: Ctor<ErrorFilter>) => ErrorFilter) => ErrorMapper;
|
|
25
89
|
/**
|
|
26
90
|
* The mapper `HttpFactory` installs unless `onError` replaces it, built from the
|
|
27
91
|
* app's **bound** `Logger` - so a service that imported `@dunx/infra/logger` gets
|
package/dist/server/routes.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type Ctor } from '@dunx/core';
|
|
1
|
+
import { type Ctor, type ModuleRef } from '@dunx/core';
|
|
2
2
|
import type { DiscoveredRoute } from '../route/discover.js';
|
|
3
3
|
import type { HttpMethod } from '../route/marker.js';
|
|
4
4
|
import type { UpgradeHandler } from '../ws/adapter.js';
|
|
@@ -6,7 +6,14 @@ import { type CorsOptions } from './cors.js';
|
|
|
6
6
|
import { type ErrorMapper } from './errors.js';
|
|
7
7
|
import { type Middleware, type RouteHandler, type ServedHandler } from './middleware.js';
|
|
8
8
|
/** How a `@UseGuards` class becomes an instance. `listen()` passes `app.get`. */
|
|
9
|
-
|
|
9
|
+
/**
|
|
10
|
+
* How a guard or a module's middleware becomes an instance.
|
|
11
|
+
*
|
|
12
|
+
* `from` names the module whose scope it resolves in - module middleware has to be
|
|
13
|
+
* built from the module that declared it, or it could not inject that module's private
|
|
14
|
+
* providers, which is the point of declaring it there.
|
|
15
|
+
*/
|
|
16
|
+
export type GuardResolver = (guard: Ctor<Middleware>, from?: ModuleRef) => Middleware;
|
|
10
17
|
/** `OPTIONS` is never a `@Get`-style route - only CORS mounts one. */
|
|
11
18
|
export type RouteMethod = HttpMethod | 'OPTIONS';
|
|
12
19
|
export type BunRoutes = Record<string, Partial<Record<RouteMethod, ServedHandler>>>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dunx/http",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "1.0.0",
|
|
4
4
|
"description": "Bun.serve adapter for the dunx framework: controllers, middleware and WebSocket gateways",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"bun",
|
|
@@ -58,7 +58,7 @@
|
|
|
58
58
|
"@dunx/core": "workspace:*"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
|
-
"@dunx/core": "^0.
|
|
61
|
+
"@dunx/core": "^1.0.0",
|
|
62
62
|
"@types/bun": ">=1.3.0"
|
|
63
63
|
},
|
|
64
64
|
"peerDependenciesMeta": {
|