@protorip/connect-hono 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,190 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ Copyright 2026 Strange Computer (Marc Porciuncula)
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,10 @@
1
+ connect-hono
2
+ Copyright 2026 Strange Computer (Marc Porciuncula)
3
+
4
+ "Protorip", "protos.rip", and the Protorip logo are trademarks of
5
+ Strange Computer (Marc Porciuncula). Under Section 6 of the Apache-2.0
6
+ License, no trademark rights are granted except as required for
7
+ reasonable and customary use in describing the origin of the Work and
8
+ reproducing this NOTICE file.
9
+
10
+ See LICENSE for the Apache-2.0 license text.
package/README.md CHANGED
@@ -1,3 +1,146 @@
1
- # Temporary Holding Version
1
+ # @protorip/connect-hono
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Hono and Web Fetch adapter for [ConnectRPC](https://connectrpc.com/).
4
+
5
+ `@protorip/connect-hono` mounts a `@connectrpc/connect` `ConnectRouter` onto a [Hono](https://hono.dev/) application or any Web Fetch runtime (Cloudflare Workers, Deno, Bun, or Node.js) with typed `ContextValues` bridging, path prefix stripping, lazy router initialization, and optional request-body buffering.
6
+
7
+ ## Requirements
8
+
9
+ - `@connectrpc/connect` `^2.0.0`
10
+ - `hono` `^4.0.0` (optional if you only import `@protorip/connect-hono/fetch`)
11
+ - Node.js `>=20`, Cloudflare Workers, Bun, or Deno
12
+
13
+ ## Installation
14
+
15
+ ```sh
16
+ npm install @protorip/connect-hono @connectrpc/connect hono
17
+ ```
18
+
19
+ If you only need the framework-agnostic Fetch handler (`@protorip/connect-hono/fetch`), you do not need to install `hono`.
20
+
21
+ ## Usage
22
+
23
+ ### Hono middleware
24
+
25
+ Assemble a `ConnectRouter` with `createConnectRouter` and pass it to `connectMiddleware`. Non-matching requests fall through to `next()`.
26
+
27
+ ```ts
28
+ import {
29
+ createConnectRouter,
30
+ createContextKey,
31
+ createContextValues,
32
+ type ServiceImpl,
33
+ } from "@connectrpc/connect";
34
+ import { Hono } from "hono";
35
+ import { cors } from "hono/cors";
36
+ import { connectMiddleware, honoContextKey } from "@protorip/connect-hono";
37
+ import { ElizaService } from "./gen/eliza_pb.js";
38
+
39
+ type AppEnv = {
40
+ Bindings: { ENVIRONMENT: string };
41
+ Variables: { userId: string };
42
+ };
43
+
44
+ const userIdKey = createContextKey<string | undefined>(undefined);
45
+
46
+ const elizaService: ServiceImpl<typeof ElizaService> = {
47
+ say(req, ctx) {
48
+ const userId = ctx.values.get(userIdKey);
49
+ const c = ctx.values.get(honoContextKey);
50
+ return { sentence: `[${userId ?? "anon"}:${c?.env.ENVIRONMENT}] ${req.sentence}` };
51
+ },
52
+ };
53
+
54
+ const connectRouter = createConnectRouter().service(ElizaService, elizaService);
55
+
56
+ const app = new Hono<AppEnv>();
57
+
58
+ app.use("/*", cors());
59
+ app.use(
60
+ "/*",
61
+ connectMiddleware<AppEnv>(connectRouter, {
62
+ bufferRequestBody: true,
63
+ contextValues: (c) => createContextValues().set(userIdKey, c.get("userId")),
64
+ }),
65
+ );
66
+
67
+ app.get("/health", (c) => c.text("ok"));
68
+
69
+ export default app;
70
+ ```
71
+
72
+ ### Lazy router initialization
73
+
74
+ Pass a zero-argument factory `() => ConnectRouter` to defer router construction until the first incoming request. The router and handler map are created once and cached for subsequent requests.
75
+
76
+ ```ts
77
+ app.use(
78
+ "/*",
79
+ connectMiddleware(() => createConnectRouter().service(ElizaService, elizaService)),
80
+ );
81
+ ```
82
+
83
+ ### Nested Hono sub-routers and mount prefixes
84
+
85
+ When mounting Connect routes under a static or parameterized path, pass `requestPathPrefix` so the adapter strips the mount prefix before matching Connect service paths.
86
+
87
+ ```ts
88
+ import { createConnectRouter } from "@connectrpc/connect";
89
+ import { Hono } from "hono";
90
+ import { connectMiddleware } from "@protorip/connect-hono";
91
+ import { ElizaService } from "./gen/eliza_pb.js";
92
+
93
+ const connectRouter = createConnectRouter().service(ElizaService, elizaService);
94
+
95
+ const tenantApp = new Hono();
96
+ tenantApp.use(
97
+ "/*",
98
+ connectMiddleware(connectRouter, {
99
+ requestPathPrefix: (c) => `/tenants/${c.req.param("tenantId")}`,
100
+ }),
101
+ );
102
+
103
+ const app = new Hono();
104
+ app.route("/tenants/:tenantId", tenantApp);
105
+ ```
106
+
107
+ ### Framework-agnostic Fetch handler
108
+
109
+ Import `createConnectFetchHandler` from `@protorip/connect-hono/fetch` when running directly on Cloudflare Workers, `Deno.serve`, `Bun.serve`, or `@hono/node-server` without Hono.
110
+
111
+ ```ts
112
+ import { createConnectRouter } from "@connectrpc/connect";
113
+ import { createConnectFetchHandler } from "@protorip/connect-hono/fetch";
114
+ import { ElizaService } from "./gen/eliza_pb.js";
115
+
116
+ const connectRouter = createConnectRouter().service(ElizaService, elizaService);
117
+
118
+ const handleConnect = createConnectFetchHandler(connectRouter, {
119
+ requestPathPrefix: "/rpc",
120
+ bufferRequestBody: true,
121
+ });
122
+
123
+ export default {
124
+ async fetch(request: Request): Promise<Response> {
125
+ const rpcResponse = await handleConnect(request);
126
+ if (rpcResponse) return rpcResponse;
127
+ return new Response("Not found", { status: 404 });
128
+ },
129
+ };
130
+ ```
131
+
132
+ ## Options
133
+
134
+ Configure Connect router behavior (such as `interceptors`, `readMaxBytes`, `writeMaxBytes`, `grpc`, `grpcWeb`, and `acceptCompression`) directly on `createConnectRouter(...)`.
135
+
136
+ Both `connectMiddleware(router, options?)` and `createConnectFetchHandler(router, options?)` accept:
137
+
138
+ | Option | Type | Default | Description |
139
+ | ------------------- | ---------------------------------------------------------------------------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
140
+ | `requestPathPrefix` | `string \| ((c: Context<E>) => string)` (`string` only for `@protorip/connect-hono/fetch`) | `""` | Path prefix stripped before matching Connect handler paths. Trailing slashes are normalized. |
141
+ | `bufferRequestBody` | `boolean` | `false` | Buffers non-`GET`/`HEAD` request bodies with `request.arrayBuffer()` before passing the request to Connect. Recommended on Cloudflare Workers and Wrangler to avoid body-drain errors on rejected or unimplemented RPCs. |
142
+ | `contextValues` | `(c: Context<E>) => ContextValues \| Promise<ContextValues>` (or `(request: Request) => ...` for `@protorip/connect-hono/fetch`) | `undefined` | Builds Connect `ContextValues` per matched request. In Hono middleware, `honoContextKey` is attached automatically unless set explicitly. |
143
+
144
+ ## License
145
+
146
+ Apache-2.0. Maintained by [protos.rip](https://protos.rip).
@@ -0,0 +1,43 @@
1
+ import type { ConnectRouter, ContextValues } from "@connectrpc/connect";
2
+ import { type UniversalHandler } from "@connectrpc/connect/protocol";
3
+ /**
4
+ * A prebuilt `ConnectRouter` or a zero-argument factory invoked lazily once on
5
+ * the first request and cached for subsequent requests.
6
+ */
7
+ export type ConnectRouterSource = ConnectRouter | (() => ConnectRouter);
8
+ export interface ConnectFetchOptions {
9
+ /**
10
+ * Optional mount path prefix to strip before matching Connect handler paths
11
+ * (for example `"/rpc"` or `"/api/v1"`). Trailing slashes are normalized.
12
+ */
13
+ requestPathPrefix?: string;
14
+ /**
15
+ * Buffer non-GET/HEAD request bodies with `request.arrayBuffer()` before
16
+ * passing them to Connect. Defaults to `false`.
17
+ *
18
+ * Enable on runtimes such as Cloudflare Workers / Wrangler where an
19
+ * unconsumed `ReadableStream` reader (for example on an unimplemented RPC)
20
+ * can trigger body-drain errors.
21
+ */
22
+ bufferRequestBody?: boolean;
23
+ /** Produce Connect `ContextValues` for each matched request. */
24
+ contextValues?: (request: Request) => ContextValues | Promise<ContextValues>;
25
+ }
26
+ export type ConnectFetchHandler = (request: Request, contextValues?: ContextValues) => Promise<Response | null>;
27
+ /** @internal */
28
+ export declare function normalizePathPrefix(prefix: string | undefined): string;
29
+ /** @internal */
30
+ export declare function stripPathPrefix(pathname: string, prefix: string): string | null;
31
+ /** @internal */
32
+ export interface ConnectDispatcher {
33
+ match(pathname: string, prefix?: string): UniversalHandler | undefined;
34
+ invoke(handler: UniversalHandler, request: Request, contextValues?: ContextValues): Promise<Response>;
35
+ }
36
+ /** @internal */
37
+ export declare function createConnectDispatcher(routerSource: ConnectRouterSource, bufferRequestBody?: boolean): ConnectDispatcher;
38
+ /**
39
+ * Create a Web Fetch handler that dispatches matching Connect RPC requests and
40
+ * returns `null` when the request path does not match any registered service.
41
+ */
42
+ export declare function createConnectFetchHandler(router: ConnectRouterSource, options?: ConnectFetchOptions): ConnectFetchHandler;
43
+ //# sourceMappingURL=fetch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.d.ts","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACxE,OAAO,EAGL,KAAK,gBAAgB,EACtB,MAAM,8BAA8B,CAAC;AAEtC;;;GAGG;AACH,MAAM,MAAM,mBAAmB,GAAG,aAAa,GAAG,CAAC,MAAM,aAAa,CAAC,CAAC;AAExE,MAAM,WAAW,mBAAmB;IAClC;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;;;;OAOG;IACH,iBAAiB,CAAC,EAAE,OAAO,CAAC;IAC5B,gEAAgE;IAChE,aAAa,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CAC9E;AAED,MAAM,MAAM,mBAAmB,GAAG,CAChC,OAAO,EAAE,OAAO,EAChB,aAAa,CAAC,EAAE,aAAa,KAC1B,OAAO,CAAC,QAAQ,GAAG,IAAI,CAAC,CAAC;AAE9B,gBAAgB;AAChB,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAKtE;AAED,gBAAgB;AAChB,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAI/E;AAED,gBAAgB;AAChB,MAAM,WAAW,iBAAiB;IAChC,KAAK,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,gBAAgB,GAAG,SAAS,CAAC;IACvE,MAAM,CACJ,OAAO,EAAE,gBAAgB,EACzB,OAAO,EAAE,OAAO,EAChB,aAAa,CAAC,EAAE,aAAa,GAC5B,OAAO,CAAC,QAAQ,CAAC,CAAC;CACtB;AAMD,gBAAgB;AAChB,wBAAgB,uBAAuB,CACrC,YAAY,EAAE,mBAAmB,EACjC,iBAAiB,UAAQ,GACxB,iBAAiB,CAuCnB;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,mBAAmB,EAC3B,OAAO,GAAE,mBAAwB,GAChC,mBAAmB,CAarB"}
package/dist/fetch.js ADDED
@@ -0,0 +1,75 @@
1
+ import { universalServerRequestFromFetch, universalServerResponseToFetch, } from "@connectrpc/connect/protocol";
2
+ /** @internal */
3
+ export function normalizePathPrefix(prefix) {
4
+ if (!prefix)
5
+ return "";
6
+ const trimmed = prefix.replace(/\/+$/, "");
7
+ if (!trimmed)
8
+ return "";
9
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
10
+ }
11
+ /** @internal */
12
+ export function stripPathPrefix(pathname, prefix) {
13
+ if (!prefix)
14
+ return pathname;
15
+ if (!pathname.startsWith(`${prefix}/`))
16
+ return null;
17
+ return pathname.slice(prefix.length);
18
+ }
19
+ function buildHandlerMap(router) {
20
+ return new Map(router.handlers.map((handler) => [handler.requestPath, handler]));
21
+ }
22
+ /** @internal */
23
+ export function createConnectDispatcher(routerSource, bufferRequestBody = false) {
24
+ let handlers = typeof routerSource === "function" ? undefined : buildHandlerMap(routerSource);
25
+ const getHandlers = () => {
26
+ if (!handlers) {
27
+ handlers = buildHandlerMap(routerSource());
28
+ }
29
+ return handlers;
30
+ };
31
+ return {
32
+ match(pathname, prefix = "") {
33
+ const stripped = stripPathPrefix(pathname, prefix);
34
+ if (stripped === null)
35
+ return undefined;
36
+ return getHandlers().get(stripped);
37
+ },
38
+ async invoke(handler, request, contextValues) {
39
+ let effectiveRequest = request;
40
+ if (bufferRequestBody && request.method !== "GET" && request.method !== "HEAD") {
41
+ const body = await request.arrayBuffer();
42
+ effectiveRequest = new Request(request.url, {
43
+ method: request.method,
44
+ headers: request.headers,
45
+ body,
46
+ signal: request.signal,
47
+ });
48
+ }
49
+ const universalRequest = universalServerRequestFromFetch(effectiveRequest, {});
50
+ if (contextValues) {
51
+ universalRequest.contextValues = contextValues;
52
+ }
53
+ const universalResponse = await handler(universalRequest);
54
+ return universalServerResponseToFetch(universalResponse);
55
+ },
56
+ };
57
+ }
58
+ /**
59
+ * Create a Web Fetch handler that dispatches matching Connect RPC requests and
60
+ * returns `null` when the request path does not match any registered service.
61
+ */
62
+ export function createConnectFetchHandler(router, options = {}) {
63
+ const { requestPathPrefix, bufferRequestBody = false, contextValues } = options;
64
+ const prefix = normalizePathPrefix(requestPathPrefix);
65
+ const dispatcher = createConnectDispatcher(router, bufferRequestBody);
66
+ return async (request, contextValuesOverride) => {
67
+ const pathname = new URL(request.url).pathname;
68
+ const handler = dispatcher.match(pathname, prefix);
69
+ if (!handler)
70
+ return null;
71
+ const values = contextValuesOverride ?? (contextValues ? await contextValues(request) : undefined);
72
+ return dispatcher.invoke(handler, request, values);
73
+ };
74
+ }
75
+ //# sourceMappingURL=fetch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fetch.js","sourceRoot":"","sources":["../src/fetch.ts"],"names":[],"mappings":"AACA,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,GAE/B,MAAM,8BAA8B,CAAC;AAgCtC,gBAAgB;AAChB,MAAM,UAAU,mBAAmB,CAAC,MAA0B;IAC5D,IAAI,CAAC,MAAM;QAAE,OAAO,EAAE,CAAC;IACvB,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC;IAC3C,IAAI,CAAC,OAAO;QAAE,OAAO,EAAE,CAAC;IACxB,OAAO,OAAO,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,EAAE,CAAC;AAC3D,CAAC;AAED,gBAAgB;AAChB,MAAM,UAAU,eAAe,CAAC,QAAgB,EAAE,MAA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qBAAqB,IAAI,CAAC,aAAa,CAAC,CAAC,CAAC,MAAM,aAAa,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;QACtF,OAAO,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,CAAC;IACrD,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,29 @@
1
+ import { type ContextValues } from "@connectrpc/connect";
2
+ import type { Context, Env, MiddlewareHandler } from "hono";
3
+ import { type ConnectFetchOptions, type ConnectRouterSource } from "./fetch.js";
4
+ export { createConnectFetchHandler, type ConnectFetchHandler, type ConnectFetchOptions, type ConnectRouterSource, } from "./fetch.js";
5
+ /**
6
+ * Connect context key holding the active Hono `Context` for requests dispatched
7
+ * through `connectMiddleware`.
8
+ */
9
+ export declare const honoContextKey: import("@connectrpc/connect").ContextKey<Context<any, any, {}> | undefined>;
10
+ export interface ConnectHonoOptions<E extends Env = Env> extends Omit<ConnectFetchOptions, "requestPathPrefix" | "contextValues"> {
11
+ /**
12
+ * Optional mount path prefix to strip before matching Connect handler paths.
13
+ * Pass a static string (for example `"/rpc"`) or a function that derives the
14
+ * prefix from the Hono context (for example
15
+ * `(c) => \`/instances/${c.req.param("id")}\``).
16
+ */
17
+ requestPathPrefix?: string | ((c: Context<E>) => string);
18
+ /**
19
+ * Produce Connect `ContextValues` for each matched Hono request.
20
+ * `honoContextKey` is populated automatically unless set explicitly.
21
+ */
22
+ contextValues?: (c: Context<E>) => ContextValues | Promise<ContextValues>;
23
+ }
24
+ /**
25
+ * Create a Hono middleware that dispatches matching Connect RPC requests and
26
+ * falls through to `next()` for non-matching paths.
27
+ */
28
+ export declare function connectMiddleware<E extends Env = Env>(router: ConnectRouterSource, options?: ConnectHonoOptions<E>): MiddlewareHandler<E>;
29
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAyC,KAAK,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAChG,OAAO,KAAK,EAAE,OAAO,EAAE,GAAG,EAAE,iBAAiB,EAAE,MAAM,MAAM,CAAC;AAC5D,OAAO,EAGL,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACzB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,yBAAyB,EACzB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,GACzB,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,eAAO,MAAM,cAAc,6EAAmD,CAAC;AAE/E,MAAM,WAAW,kBAAkB,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG,CAAE,SAAQ,IAAI,CACnE,mBAAmB,EACnB,mBAAmB,GAAG,eAAe,CACtC;IACC;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,GAAG,CAAC,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,MAAM,CAAC,CAAC;IACzD;;;OAGG;IACH,aAAa,CAAC,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,aAAa,GAAG,OAAO,CAAC,aAAa,CAAC,CAAC;CAC3E;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG,EACnD,MAAM,EAAE,mBAAmB,EAC3B,OAAO,GAAE,kBAAkB,CAAC,CAAC,CAAM,GAClC,iBAAiB,CAAC,CAAC,CAAC,CAoBtB"}
package/dist/index.js ADDED
@@ -0,0 +1,31 @@
1
+ import { createContextKey, createContextValues } from "@connectrpc/connect";
2
+ import { createConnectDispatcher, normalizePathPrefix, } from "./fetch.js";
3
+ export { createConnectFetchHandler, } from "./fetch.js";
4
+ /**
5
+ * Connect context key holding the active Hono `Context` for requests dispatched
6
+ * through `connectMiddleware`.
7
+ */
8
+ export const honoContextKey = createContextKey(undefined);
9
+ /**
10
+ * Create a Hono middleware that dispatches matching Connect RPC requests and
11
+ * falls through to `next()` for non-matching paths.
12
+ */
13
+ export function connectMiddleware(router, options = {}) {
14
+ const { requestPathPrefix, bufferRequestBody = false, contextValues } = options;
15
+ const staticPrefix = typeof requestPathPrefix === "string" ? normalizePathPrefix(requestPathPrefix) : undefined;
16
+ const dispatcher = createConnectDispatcher(router, bufferRequestBody);
17
+ return async (c, next) => {
18
+ const prefix = typeof requestPathPrefix === "function"
19
+ ? normalizePathPrefix(requestPathPrefix(c))
20
+ : (staticPrefix ?? "");
21
+ const handler = dispatcher.match(c.req.path, prefix);
22
+ if (!handler)
23
+ return next();
24
+ const values = contextValues ? await contextValues(c) : createContextValues();
25
+ if (values.get(honoContextKey) === undefined) {
26
+ values.set(honoContextKey, c);
27
+ }
28
+ return dispatcher.invoke(handler, c.req.raw, values);
29
+ };
30
+ }
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,mBAAmB,EAAsB,MAAM,qBAAqB,CAAC;AAEhG,OAAO,EACL,uBAAuB,EACvB,mBAAmB,GAGpB,MAAM,YAAY,CAAC;AAEpB,OAAO,EACL,yBAAyB,GAI1B,MAAM,YAAY,CAAC;AAEpB;;;GAGG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG,gBAAgB,CAAsB,SAAS,CAAC,CAAC;AAoB/E;;;GAGG;AACH,MAAM,UAAU,iBAAiB,CAC/B,MAA2B,EAC3B,UAAiC,EAAE;IAEnC,MAAM,EAAE,iBAAiB,EAAE,iBAAiB,GAAG,KAAK,EAAE,aAAa,EAAE,GAAG,OAAO,CAAC;IAChF,MAAM,YAAY,GAChB,OAAO,iBAAiB,KAAK,QAAQ,CAAC,CAAC,CAAC,mBAAmB,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC7F,MAAM,UAAU,GAAG,uBAAuB,CAAC,MAAM,EAAE,iBAAiB,CAAC,CAAC;IAEtE,OAAO,KAAK,EAAE,CAAC,EAAE,IAAI,EAAE,EAAE;QACvB,MAAM,MAAM,GACV,OAAO,iBAAiB,KAAK,UAAU;YACrC,CAAC,CAAC,mBAAmB,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC;YAC3C,CAAC,CAAC,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC;QAC3B,MAAM,OAAO,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QACrD,IAAI,CAAC,OAAO;YAAE,OAAO,IAAI,EAAE,CAAC;QAE5B,MAAM,MAAM,GAAG,aAAa,CAAC,CAAC,CAAC,MAAM,aAAa,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,mBAAmB,EAAE,CAAC;QAC9E,IAAI,MAAM,CAAC,GAAG,CAAC,cAAc,CAAC,KAAK,SAAS,EAAE,CAAC;YAC7C,MAAM,CAAC,GAAG,CAAC,cAAc,EAAE,CAAuB,CAAC,CAAC;QACtD,CAAC;QACD,OAAO,UAAU,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IACvD,CAAC,CAAC;AACJ,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@protorip/connect-hono",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Hono and Web Fetch adapter for ConnectRPC",
5
+ "author": "Strange Computer (Marc Porciuncula)",
6
+ "license": "Apache-2.0",
7
+ "publishConfig": {
8
+ "access": "public"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/Protorip/connect-hono.git"
13
+ },
14
+ "homepage": "https://github.com/Protorip/connect-hono#readme",
15
+ "bugs": {
16
+ "url": "https://github.com/Protorip/connect-hono/issues"
17
+ },
18
+ "keywords": [
19
+ "connect",
20
+ "connectrpc",
21
+ "hono",
22
+ "protobuf",
23
+ "rpc",
24
+ "cloudflare-workers",
25
+ "fetch"
26
+ ],
27
+ "type": "module",
28
+ "engines": {
29
+ "node": ">=20"
30
+ },
31
+ "exports": {
32
+ ".": {
33
+ "types": "./dist/index.d.ts",
34
+ "default": "./dist/index.js"
35
+ },
36
+ "./fetch": {
37
+ "types": "./dist/fetch.d.ts",
38
+ "default": "./dist/fetch.js"
39
+ }
40
+ },
41
+ "files": [
42
+ "dist",
43
+ "LICENSE",
44
+ "NOTICE",
45
+ "README.md"
46
+ ],
47
+ "scripts": {
48
+ "build": "tsc",
49
+ "typecheck": "tsc --noEmit",
50
+ "test": "vitest run"
51
+ },
52
+ "peerDependencies": {
53
+ "@connectrpc/connect": "^2.0.0",
54
+ "hono": "^4.0.0"
55
+ },
56
+ "peerDependenciesMeta": {
57
+ "hono": {
58
+ "optional": true
59
+ }
60
+ },
61
+ "devDependencies": {
62
+ "@bufbuild/protobuf": "^2.11.0",
63
+ "@connectrpc/connect": "^2.1.1",
64
+ "@types/node": "^24.0.0",
65
+ "hono": "^4.7.0",
66
+ "typescript": "^5.8.3",
67
+ "vitest": "^3.1.4"
68
+ },
69
+ "packageManager": "pnpm@12.8.1"
70
+ }