@ontrails/http 1.0.0-beta.12

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.
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Hono adapter for Trails HTTP routes.
3
+ *
4
+ * Takes framework-agnostic HttpRouteDefinition[] and wires them into a
5
+ * Hono application, handling request parsing, response mapping, and errors.
6
+ *
7
+ * ```ts
8
+ * const app = topo("myapp", entity);
9
+ * await blaze(app, { port: 3000 });
10
+ * ```
11
+ */
12
+
13
+ import { isTrailsError, statusCodeMap, validateTopo } from '@ontrails/core';
14
+ import type {
15
+ Layer,
16
+ ServiceOverrideMap,
17
+ Topo,
18
+ TrailContextInit,
19
+ } from '@ontrails/core';
20
+ import { Hono } from 'hono';
21
+ import type { Context as HonoContext } from 'hono';
22
+ import type { ContentfulStatusCode } from 'hono/utils/http-status';
23
+ import type { z } from 'zod';
24
+
25
+ import type { HttpMethod, HttpRouteDefinition } from '../build.js';
26
+ import { buildHttpRoutes } from '../build.js';
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // Options
30
+ // ---------------------------------------------------------------------------
31
+
32
+ export interface BlazeHttpOptions {
33
+ readonly basePath?: string | undefined;
34
+ /** Config values for services that declare a `config` schema, keyed by service ID. */
35
+ readonly configValues?:
36
+ | Readonly<Record<string, Record<string, unknown>>>
37
+ | undefined;
38
+ readonly createContext?:
39
+ | (() => TrailContextInit | Promise<TrailContextInit>)
40
+ | undefined;
41
+ readonly hostname?: string | undefined;
42
+ readonly layers?: readonly Layer[] | undefined;
43
+ readonly name?: string | undefined;
44
+ readonly port?: number | undefined;
45
+ readonly services?: ServiceOverrideMap | undefined;
46
+ /** Set false to return the Hono app without starting a server. */
47
+ readonly serve?: boolean | undefined;
48
+ /** Set to `false` to skip topo validation at startup. Defaults to `true`. */
49
+ readonly validate?: boolean | undefined;
50
+ }
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Request parsing
54
+ // ---------------------------------------------------------------------------
55
+
56
+ /**
57
+ * Build a set of field names that the input schema expects as arrays.
58
+ *
59
+ * Inspects the Zod v4 `_zod.def` internals to find top-level array fields.
60
+ * Returns an empty set when the schema is not an object or cannot be inspected.
61
+ */
62
+ interface ZodDef {
63
+ _zod: { def: Record<string, unknown> };
64
+ }
65
+
66
+ /** Unwrap optional/default wrappers to reach the underlying Zod type name. */
67
+ const unwrapZodType = (node: ZodDef): string => {
68
+ let current = node;
69
+ while (
70
+ (current._zod.def['type'] as string) === 'optional' ||
71
+ (current._zod.def['type'] as string) === 'default'
72
+ ) {
73
+ current = current._zod.def['innerType'] as ZodDef;
74
+ }
75
+ return current._zod.def['type'] as string;
76
+ };
77
+
78
+ /** Extract the object shape from a Zod schema, or undefined if not an object. */
79
+ const extractShape = (
80
+ schema: z.ZodType
81
+ ): Record<string, ZodDef> | undefined => {
82
+ const s = schema as unknown as ZodDef;
83
+ if ((s._zod.def['type'] as string) !== 'object') {
84
+ return undefined;
85
+ }
86
+ return s._zod.def['shape'] as Record<string, ZodDef> | undefined;
87
+ };
88
+
89
+ /** Collect top-level field names whose underlying type is array. */
90
+ const collectArrayKeys = (
91
+ inputSchema: z.ZodType | undefined
92
+ ): ReadonlySet<string> => {
93
+ const shape = inputSchema ? extractShape(inputSchema) : undefined;
94
+ if (!shape) {
95
+ return new Set();
96
+ }
97
+ const keys = new Set<string>();
98
+ for (const [key, value] of Object.entries(shape)) {
99
+ if (unwrapZodType(value) === 'array') {
100
+ keys.add(key);
101
+ }
102
+ }
103
+ return keys;
104
+ };
105
+
106
+ /** Parse query params into a plain object, preserving raw strings for Zod. */
107
+ const parseQueryParams = (
108
+ c: HonoContext,
109
+ inputSchema?: z.ZodType | undefined
110
+ ): Record<string, unknown> => {
111
+ const result: Record<string, unknown> = {};
112
+ const url = new URL(c.req.url);
113
+ const arrayKeys = collectArrayKeys(inputSchema);
114
+
115
+ for (const key of url.searchParams.keys()) {
116
+ // Already collected via getAll
117
+ if (key in result) {
118
+ continue;
119
+ }
120
+ const all = url.searchParams.getAll(key);
121
+ result[key] = all.length > 1 || arrayKeys.has(key) ? all : all[0];
122
+ }
123
+
124
+ return result;
125
+ };
126
+
127
+ /** Sentinel indicating a JSON parse failure. */
128
+ const JSON_PARSE_ERROR = Symbol('JSON_PARSE_ERROR');
129
+
130
+ /** Return true when the request has no body content. */
131
+ const isEmptyBody = (c: HonoContext): boolean => {
132
+ const contentLength = c.req.header('Content-Length');
133
+ if (contentLength !== undefined) {
134
+ return Number.parseInt(contentLength, 10) === 0;
135
+ }
136
+ // No Content-Length header — treat as empty when Content-Type is also absent.
137
+ return c.req.header('Content-Type') === undefined;
138
+ };
139
+
140
+ /** Read input from request based on input source. */
141
+ const readInput = async (
142
+ c: HonoContext,
143
+ inputSource: 'query' | 'body',
144
+ inputSchema?: z.ZodType | undefined
145
+ ): Promise<unknown> => {
146
+ if (inputSource === 'query') {
147
+ return parseQueryParams(c, inputSchema);
148
+ }
149
+ if (isEmptyBody(c)) {
150
+ return {};
151
+ }
152
+ try {
153
+ return await c.req.json();
154
+ } catch {
155
+ return JSON_PARSE_ERROR;
156
+ }
157
+ };
158
+
159
+ // ---------------------------------------------------------------------------
160
+ // Response mapping
161
+ // ---------------------------------------------------------------------------
162
+
163
+ /** Map a TrailsError or generic Error to an HTTP error response. */
164
+ const mapErrorResponse = (
165
+ error: Error
166
+ ): { body: Record<string, unknown>; status: ContentfulStatusCode } => {
167
+ if (isTrailsError(error)) {
168
+ return {
169
+ body: {
170
+ error: {
171
+ category: error.category,
172
+ code: error.name,
173
+ message: error.message,
174
+ },
175
+ },
176
+ status: statusCodeMap[error.category] as ContentfulStatusCode,
177
+ };
178
+ }
179
+ return {
180
+ body: {
181
+ error: {
182
+ category: 'internal',
183
+ code: 'InternalError',
184
+ message: error.message,
185
+ },
186
+ },
187
+ status: 500,
188
+ };
189
+ };
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // Route registration
193
+ // ---------------------------------------------------------------------------
194
+
195
+ /** Map a Result to an HTTP response via Hono context. */
196
+ const mapResultToResponse = (
197
+ result: { isOk(): boolean; value?: unknown; error?: Error },
198
+ c: HonoContext
199
+ ): Response => {
200
+ if (result.isOk()) {
201
+ return c.json({ data: result.value }, 200);
202
+ }
203
+ const { body, status } = mapErrorResponse(
204
+ result.error ?? new Error('Unknown error')
205
+ );
206
+ return c.json(body, status);
207
+ };
208
+
209
+ /** Convert a caught unknown value to an error response. */
210
+ const handleCaughtError = (error: unknown, c: HonoContext): Response => {
211
+ const err = error instanceof Error ? error : new Error(String(error));
212
+ const { body, status } = mapErrorResponse(err);
213
+ return c.json(body, status);
214
+ };
215
+
216
+ /** Create a Hono handler from a route definition. */
217
+ const createHonoHandler =
218
+ (route: HttpRouteDefinition) =>
219
+ async (c: HonoContext): Promise<Response> => {
220
+ const rawInput = await readInput(c, route.inputSource, route.trail.input);
221
+
222
+ if (rawInput === JSON_PARSE_ERROR) {
223
+ return c.json(
224
+ {
225
+ error: {
226
+ category: 'validation',
227
+ code: 'ValidationError',
228
+ message: 'Invalid JSON in request body',
229
+ },
230
+ },
231
+ 400
232
+ );
233
+ }
234
+
235
+ const requestId = c.req.header('X-Request-ID') ?? undefined;
236
+ const { signal } = c.req.raw;
237
+
238
+ try {
239
+ const result = await route.execute(rawInput, requestId, signal);
240
+ return mapResultToResponse(result, c);
241
+ } catch (error: unknown) {
242
+ return handleCaughtError(error, c);
243
+ }
244
+ };
245
+
246
+ /** Route registration keyed by HTTP method. */
247
+ const routeRegistrars: Record<
248
+ HttpMethod,
249
+ (
250
+ hono: Hono,
251
+ path: string,
252
+ handler: (c: HonoContext) => Promise<Response>
253
+ ) => void
254
+ > = {
255
+ DELETE: (hono, path, handler) => {
256
+ hono.delete(path, handler);
257
+ },
258
+ GET: (hono, path, handler) => {
259
+ hono.get(path, handler);
260
+ },
261
+ POST: (hono, path, handler) => {
262
+ hono.post(path, handler);
263
+ },
264
+ };
265
+
266
+ const registerRoutes = (hono: Hono, routes: HttpRouteDefinition[]): void => {
267
+ for (const route of routes) {
268
+ const handler = createHonoHandler(route);
269
+ routeRegistrars[route.method](hono, route.path, handler);
270
+ }
271
+ };
272
+
273
+ // ---------------------------------------------------------------------------
274
+ // Global error handler
275
+ // ---------------------------------------------------------------------------
276
+
277
+ const registerErrorHandler = (hono: Hono): void => {
278
+ // oxlint-disable-next-line prefer-await-to-callbacks -- Hono's onError API requires a callback
279
+ hono.onError((err, c) =>
280
+ c.json(
281
+ {
282
+ error: {
283
+ category: 'internal',
284
+ code: 'InternalError',
285
+ message: err.message,
286
+ },
287
+ },
288
+ 500
289
+ )
290
+ );
291
+ };
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // Validation
295
+ // ---------------------------------------------------------------------------
296
+
297
+ /**
298
+ * Throw a ValidationError if the topo has structural issues.
299
+ * Pass `skip: true` to bypass validation (e.g. when `validate: false` is set).
300
+ */
301
+ const assertValidTopo = (app: Topo, skip = false): void => {
302
+ if (skip) {
303
+ return;
304
+ }
305
+ const validated = validateTopo(app);
306
+ if (validated.isErr()) {
307
+ throw validated.error;
308
+ }
309
+ };
310
+
311
+ // ---------------------------------------------------------------------------
312
+ // blaze
313
+ // ---------------------------------------------------------------------------
314
+
315
+ /**
316
+ * Build HTTP routes from a topo, create a Hono app, and optionally start serving.
317
+ */
318
+ // oxlint-disable-next-line require-await -- async for consistency with other blaze() surfaces
319
+ export const blaze = async (
320
+ app: Topo,
321
+ options: BlazeHttpOptions = {}
322
+ ): Promise<Hono> => {
323
+ assertValidTopo(app, options.validate === false);
324
+
325
+ const hono = new Hono();
326
+
327
+ registerErrorHandler(hono);
328
+
329
+ const routesResult = buildHttpRoutes(app, {
330
+ basePath: options.basePath,
331
+ configValues: options.configValues,
332
+ createContext: options.createContext,
333
+ layers: options.layers,
334
+ services: options.services,
335
+ });
336
+
337
+ if (routesResult.isErr()) {
338
+ throw routesResult.error;
339
+ }
340
+
341
+ registerRoutes(hono, routesResult.value);
342
+
343
+ if (options.serve !== false) {
344
+ Bun.serve({
345
+ fetch: hono.fetch,
346
+ hostname: options.hostname ?? '0.0.0.0',
347
+ port: options.port ?? 3000,
348
+ });
349
+ }
350
+
351
+ return hono;
352
+ };
@@ -0,0 +1 @@
1
+ export { blaze, type BlazeHttpOptions } from './blaze.js';
package/src/index.ts ADDED
@@ -0,0 +1,8 @@
1
+ // Build (framework-agnostic)
2
+ export {
3
+ buildHttpRoutes,
4
+ type BuildHttpRoutesOptions,
5
+ type HttpMethod,
6
+ type HttpRouteDefinition,
7
+ type InputSource,
8
+ } from './build.js';
package/tsconfig.json ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "extends": "../../tsconfig.json",
3
+ "compilerOptions": {
4
+ "outDir": "dist",
5
+ "rootDir": "src"
6
+ },
7
+ "include": ["src"],
8
+ "exclude": ["**/__tests__/**", "**/*.test.ts", "dist"]
9
+ }
@@ -0,0 +1 @@
1
+ {"root":["./src/build.ts","./src/index.ts","./src/hono/blaze.ts","./src/hono/index.ts"],"version":"5.9.3"}