Skip to content

Commit 4f1c793

Browse files
committed
fix(examples): update hono example to remove transforms since StarlingMonkey takes care of it
Signed-off-by: Lachlan Heywood <[email protected]>
1 parent 7418e56 commit 4f1c793

File tree

20 files changed

+679
-152
lines changed

20 files changed

+679
-152
lines changed

examples/components/http-server-with-hono/README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,7 @@ The adapter in [`src/wasmcloud/hono-adapter`](https://github.com/wasmCloud/types
3535

3636
**How it works:**
3737

38-
- The adapter exposes a `serve(app)` function that takes a Hono app and returns a WASI-compatible handler function.
39-
- When a request comes in, it converts the WASI HTTP request into a standard Web `Request` object.
40-
- The Hono app processes the request and returns a standard Web `Response`.
41-
- The adapter reads the response status, headers, and streams the response body (if present) back to the WASI HTTP provider, ensuring compatibility with both text and binary responses.
38+
- The adapter exposes a `serve(app: Hono)` function that takes a Hono app and adds a 'fetch' event-listener onto the global context. JCO componentize-js supports this (through StarlingMonkey) by automatically adding the necessary imports.
4239
- Any errors in the request handling are caught and a 500 Internal Server Error is returned to the client.
4340

4441
## Logging Middleware
@@ -53,3 +50,7 @@ The logging middleware in [`src/wasmcloud/hono-middleware-wasi-logging`](https:/
5350
- Uses the WASI logging interface for compatibility with wasmCloud and other WASI hosts
5451

5552
This makes it easy to observe and debug your HTTP component's behavior in production or development environments.
53+
54+
## Environment Variables
55+
56+
The example uses the `wasi:config/runtime` interface to pass environment variables to the Hono app. The `env` object is available in the request context, allowing you to access configuration values in your routes and middleware.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
declare module 'wasi:cli/[email protected]' {
2+
/**
3+
* Get the POSIX-style environment variables.
4+
*
5+
* Each environment variable is provided as a pair of string variable names
6+
* and string value.
7+
*
8+
* Morally, these are a value import, but until value imports are available
9+
* in the component model, this import function should return the same
10+
* values each time it is called.
11+
*/
12+
export function getEnvironment(): Array<[string, string]>;
13+
/**
14+
* Get the POSIX-style arguments to the program.
15+
*/
16+
export function getArguments(): Array<string>;
17+
/**
18+
* Return a path that programs should use as their initial current working
19+
* directory, interpreting `.` as shorthand for this.
20+
*/
21+
export function initialCwd(): string | undefined;
22+
}

examples/components/http-server-with-hono/generated/types/wit.d.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
/// <reference path="./interfaces/wasi-cli-environment.d.ts" />
12
/// <reference path="./interfaces/wasi-clocks-monotonic-clock.d.ts" />
23
/// <reference path="./interfaces/wasi-config-runtime.d.ts" />
34
/// <reference path="./interfaces/wasi-http-incoming-handler.d.ts" />
@@ -7,6 +8,7 @@
78
/// <reference path="./interfaces/wasi-io-streams.d.ts" />
89
/// <reference path="./interfaces/wasi-logging-logging.d.ts" />
910
declare module 'wasmcloud:hello/hello' {
11+
export type * as WasiCliEnvironment023 from 'wasi:cli/[email protected]'; // import wasi:cli/[email protected]
1012
export type * as WasiClocksMonotonicClock023 from 'wasi:clocks/[email protected]'; // import wasi:clocks/[email protected]
1113
export type * as WasiConfigRuntime020Draft from 'wasi:config/[email protected]'; // import wasi:config/[email protected]
1214
export type * as WasiHttpTypes023 from 'wasi:http/[email protected]'; // import wasi:http/[email protected]

examples/components/http-server-with-hono/package-lock.json

Lines changed: 11 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples/components/http-server-with-hono/package.json

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,7 @@
2222
"hono": "^4.4.13"
2323
},
2424
"devDependencies": {
25-
"@bytecodealliance/jco": "^1.10.2",
26-
"@rollup/plugin-commonjs": "^28.0.3",
25+
"@bytecodealliance/jco": "^1.11.1",
2726
"@rollup/plugin-node-resolve": "^16.0.1",
2827
"@rollup/plugin-typescript": "^12.1.2",
2928
"@types/node": "^22.7.6",

examples/components/http-server-with-hono/rollup.config.mjs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
// rollup.config.mjs
22
import resolve from '@rollup/plugin-node-resolve';
3-
import commonjs from '@rollup/plugin-commonjs';
43
import typescript from '@rollup/plugin-typescript';
54

65
export default {
@@ -10,7 +9,7 @@ export default {
109
format: 'esm', // Output format as ES Module
1110
sourcemap: true,
1211
},
13-
external: [/wasi:.*/],
12+
external: [/wasi:.*/], // Exclude WASI imports from bundling
1413
plugins: [
1514
typescript({
1615
// Compile TypeScript first
@@ -23,6 +22,5 @@ export default {
2322
preferBuiltins: false, // Important for WASI environment
2423
browser: true, // Treat as browser environment for dependencies
2524
}),
26-
commonjs(), // Convert CommonJS modules to ES modules
2725
],
2826
};

examples/components/http-server-with-hono/src/app.ts

Lines changed: 0 additions & 20 deletions
This file was deleted.
Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,22 @@
1-
import app from './app';
2-
import {serve} from './wasmcloud/hono-adapter';
1+
import {Hono, Context} from 'hono';
32

4-
export const incomingHandler = {
5-
handle: serve(app),
6-
};
3+
import {serve, type WasiEnv} from './wasmcloud/hono-adapter';
4+
import {wasiLog} from './wasmcloud/hono-middleware-wasi-logging';
5+
6+
// Initialize Hono app
7+
const app = new Hono<WasiEnv>();
8+
9+
// Middleware for logging
10+
app.use(wasiLog());
11+
12+
// Define routes
13+
app.get('/', (c: Context) => c.text('Welcome to the Hono HTTP Router Example!'));
14+
app.get('/hello', (c: Context) => c.text('Hello, World!'));
15+
app.get('/api/data', (c: Context) => c.json({message: 'This is some JSON data.'}));
16+
17+
// handle missing routes
18+
app.notFound((c: Context) => {
19+
return c.json({error: '404 Not Found'}, 404);
20+
});
21+
22+
serve(app);
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,3 @@
1+
export type {WasiEnv} from './types';
2+
13
export {serve} from './server';
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
import {logging as rootLogger} from '../logging';
22

33
export const logging = rootLogger.createLogger('hono-adapter');
4+
export type Logger = typeof logging;
Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,28 @@
1+
/// <reference lib="WebWorker" />
2+
// The ServiceWorker scope isn't currently exported from the TS lib; only the "WebWorker" scope. StarlingMonkey executes
3+
// in a ServiceWorker context, so we need to override the type of `self` to be ServiceWorkerGlobalScope.
4+
// See https://github.com/microsoft/TypeScript-DOM-lib-generator/issues/1498
5+
declare const self: ServiceWorkerGlobalScope;
6+
17
import type {Env, Hono, Schema} from 'hono';
2-
import type {IncomingRequest, ResponseOutparam} from 'wasi:http/[email protected]';
38
import type {BlankSchema} from 'hono/types';
49

510
import {getAll as getConfig} from 'wasi:config/[email protected]';
611

7-
import {logging} from './logging';
8-
import {createRequest, createResponse} from './transformers';
912
import {handleError} from './errorHandling';
10-
11-
const logger = logging.createLogger('serve');
13+
import {createLogger} from '../logging';
1214

1315
function serve<E extends Env = Env, S extends Schema = BlankSchema, BasePath extends string = '/'>(
1416
app: Hono<E, S, BasePath>,
15-
): (request: IncomingRequest, response: ResponseOutparam) => Promise<void> {
16-
return async (request, response) => {
17-
logger.info(`Received request: ${request.pathWithQuery()}`);
18-
app.onError(handleError);
17+
): void {
18+
const logger = createLogger('serve()');
19+
app.onError(handleError);
20+
self.addEventListener('fetch', (event): void => {
21+
logger.debug('Request:', event.request.url);
1922

2023
const env = Object.fromEntries(getConfig());
21-
const res = await app.fetch(createRequest(request), env);
22-
await createResponse(res, response);
23-
};
24+
event.respondWith(app.fetch(event.request, env));
25+
});
2426
}
2527

2628
export {serve};

examples/components/http-server-with-hono/src/wasmcloud/hono-adapter/transformers.ts

Lines changed: 0 additions & 93 deletions
This file was deleted.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import type {Env} from 'hono';
2+
import type {Logger} from './logging';
3+
4+
export interface WasiEnv extends Env {
5+
config: Record<string, string>;
6+
logger: Logger;
7+
}

examples/components/http-server-with-hono/wasmcloud.lock

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,15 @@
22
# It is not intended for manual editing.
33
version = 1
44

5+
[[packages]]
6+
name = "wasi:cli"
7+
registry = "wasi.dev"
8+
9+
[[packages.versions]]
10+
requirement = "=0.2.3"
11+
version = "0.2.3"
12+
digest = "sha256:8f97d837e1f856a225422869d5c34752204d1befb5a04d0cd80541aec17a20c1"
13+
514
[[packages]]
615
name = "wasi:config"
716
registry = "wasi.dev"

0 commit comments

Comments
 (0)