@ontrails/http 1.0.0-beta.14 → 1.0.0-beta.16

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.
@@ -1,340 +0,0 @@
1
- /**
2
- * Hono connector 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 trailhead(app, { port: 3000 });
10
- * ```
11
- */
12
-
13
- import { isTrailsError, statusCodeMap } from '@ontrails/core';
14
- import type {
15
- Gate,
16
- ProvisionOverrideMap,
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 TrailheadHttpOptions {
33
- readonly basePath?: string | undefined;
34
- /** Config values for provisions that declare a `config` schema, keyed by provision 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 gates?: readonly Gate[] | undefined;
43
- readonly name?: string | undefined;
44
- readonly port?: number | undefined;
45
- readonly provisions?: ProvisionOverrideMap | 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: abortSignal } = c.req.raw;
237
-
238
- try {
239
- const result = await route.execute(rawInput, requestId, abortSignal);
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
- // trailhead
299
- // ---------------------------------------------------------------------------
300
-
301
- /**
302
- * Build HTTP routes from a topo, create a Hono app, and optionally start serving.
303
- *
304
- * Topo validation runs before route construction — pass `validate: false`
305
- * to skip it (e.g. during hot-reload or progressive startup).
306
- */
307
- // oxlint-disable-next-line require-await -- async for consistency with other trailhead() entrypoints
308
- export const trailhead = async (
309
- app: Topo,
310
- options: TrailheadHttpOptions = {}
311
- ): Promise<Hono> => {
312
- const hono = new Hono();
313
-
314
- registerErrorHandler(hono);
315
-
316
- const routesResult = buildHttpRoutes(app, {
317
- basePath: options.basePath,
318
- configValues: options.configValues,
319
- createContext: options.createContext,
320
- gates: options.gates,
321
- provisions: options.provisions,
322
- validate: options.validate,
323
- });
324
-
325
- if (routesResult.isErr()) {
326
- throw routesResult.error;
327
- }
328
-
329
- registerRoutes(hono, routesResult.value);
330
-
331
- if (options.serve !== false) {
332
- Bun.serve({
333
- fetch: hono.fetch,
334
- hostname: options.hostname ?? '0.0.0.0',
335
- port: options.port ?? 3000,
336
- });
337
- }
338
-
339
- return hono;
340
- };
package/tsconfig.json DELETED
@@ -1,9 +0,0 @@
1
- {
2
- "extends": "../../tsconfig.json",
3
- "compilerOptions": {
4
- "outDir": "dist",
5
- "rootDir": "src"
6
- },
7
- "include": ["src"],
8
- "exclude": ["**/__tests__/**", "**/*.test.ts", "dist"]
9
- }
@@ -1 +0,0 @@
1
- {"root":["./src/build.ts","./src/index.ts","./src/hono/index.ts","./src/hono/trailhead.ts"],"version":"5.9.3"}