trpc-bun-adapter
Advanced tools
Comparing version 1.1.1 to 1.1.2
@@ -1,3 +0,43 @@ | ||
export * from "./createBunHttpHandler"; | ||
export * from "./createBunWSHandler"; | ||
export * from "./createBunServeHandler"; | ||
import * as bun from 'bun'; | ||
import { Server, ServerWebSocket, WebSocketHandler, ServeOptions } from 'bun'; | ||
import { AnyRouter, inferRouterContext } from '@trpc/server'; | ||
import { FetchCreateContextFnOptions, FetchHandlerRequestOptions } from '@trpc/server/adapters/fetch'; | ||
import { TRPCClientOutgoingMessage } from '@trpc/server/rpc'; | ||
import { BaseHandlerOptions } from '@trpc/server/src/@trpc/server/http'; | ||
import { CreateContextCallback } from '@trpc/server/src/@trpc/server'; | ||
import { MaybePromise } from '@trpc/server/src/unstable-core-do-not-import'; | ||
import { NodeHTTPCreateContextFnOptions } from '@trpc/server/src/adapters/node-http'; | ||
type CreateBunContextOptions = FetchCreateContextFnOptions; | ||
type BunHttpHandlerOptions<TRouter extends AnyRouter> = Omit<FetchHandlerRequestOptions<TRouter>, "req"> & { | ||
endpoint?: string; | ||
createContext?: (opts: CreateBunContextOptions) => inferRouterContext<TRouter> | Promise<inferRouterContext<TRouter>>; | ||
}; | ||
declare function createBunHttpHandler<TRouter extends AnyRouter>(opts: BunHttpHandlerOptions<TRouter> & { | ||
emitWsUpgrades?: boolean; | ||
}): (request: Request, server: Server) => Response | Promise<Response> | undefined; | ||
type CreateBunWSSContextFnOptions = Omit<NodeHTTPCreateContextFnOptions<Request, ServerWebSocket<BunWSClientCtx>>, "info">; | ||
type BunWSAdapterOptions<TRouter extends AnyRouter> = BaseHandlerOptions<TRouter, Request> & CreateContextCallback<inferRouterContext<TRouter>, (opts: CreateBunWSSContextFnOptions) => MaybePromise<inferRouterContext<TRouter>>>; | ||
type BunWSClientCtx = { | ||
req: Request; | ||
handleRequest: (msg: TRPCClientOutgoingMessage) => Promise<void>; | ||
unsubscribe(): void; | ||
}; | ||
declare function createBunWSHandler<TRouter extends AnyRouter>(opts: BunWSAdapterOptions<TRouter>): WebSocketHandler<BunWSClientCtx>; | ||
type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>; | ||
declare function createBunServeHandler<TRouter extends AnyRouter>(opts: BunHttpHandlerOptions<TRouter> & BunWSAdapterOptions<TRouter>, serveOptions?: Optional<ServeOptions, "fetch">): { | ||
fetch(req: Request, server: Server): Promise<Response | undefined>; | ||
websocket: bun.WebSocketHandler<BunWSClientCtx>; | ||
error?: (this: Server, request: bun.ErrorLike) => Response | Promise<Response> | undefined | Promise<undefined>; | ||
id?: string | null; | ||
port?: string | number; | ||
reusePort?: boolean; | ||
hostname?: string; | ||
unix?: never; | ||
maxRequestBodySize?: number; | ||
development?: boolean; | ||
}; | ||
export { type BunHttpHandlerOptions, type BunWSAdapterOptions, type BunWSClientCtx, type CreateBunContextOptions, type CreateBunWSSContextFnOptions, createBunHttpHandler, createBunServeHandler, createBunWSHandler }; |
@@ -7,20 +7,14 @@ "use strict"; | ||
var __export = (target, all) => { | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
for (var name in all) | ||
__defProp(target, name, { get: all[name], enumerable: true }); | ||
}; | ||
var __copyProps = (to, from, except, desc) => { | ||
if ((from && typeof from === "object") || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { | ||
get: () => from[key], | ||
enumerable: | ||
!(desc = __getOwnPropDesc(from, key)) || | ||
desc.enumerable, | ||
}); | ||
} | ||
return to; | ||
if (from && typeof from === "object" || typeof from === "function") { | ||
for (let key of __getOwnPropNames(from)) | ||
if (!__hasOwnProp.call(to, key) && key !== except) | ||
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); | ||
} | ||
return to; | ||
}; | ||
var __toCommonJS = (mod) => | ||
__copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); | ||
@@ -30,5 +24,5 @@ // src/index.ts | ||
__export(src_exports, { | ||
createBunHttpHandler: () => createBunHttpHandler, | ||
createBunServeHandler: () => createBunServeHandler, | ||
createBunWSHandler: () => createBunWSHandler, | ||
createBunHttpHandler: () => createBunHttpHandler, | ||
createBunServeHandler: () => createBunServeHandler, | ||
createBunWSHandler: () => createBunWSHandler | ||
}); | ||
@@ -40,20 +34,17 @@ module.exports = __toCommonJS(src_exports); | ||
function createBunHttpHandler(opts) { | ||
return (request, server) => { | ||
const url = new URL(request.url); | ||
if (opts.endpoint && !url.pathname.startsWith(opts.endpoint)) { | ||
return; | ||
} | ||
if ( | ||
opts.emitWsUpgrades && | ||
server.upgrade(request, { data: { req: request } }) | ||
) { | ||
return new Response(null, { status: 101 }); | ||
} | ||
return (0, import_fetch.fetchRequestHandler)({ | ||
endpoint: opts.endpoint ?? "", | ||
router: opts.router, | ||
req: request, | ||
createContext: opts.createContext, | ||
}); | ||
}; | ||
return (request, server) => { | ||
const url = new URL(request.url); | ||
if (opts.endpoint && !url.pathname.startsWith(opts.endpoint)) { | ||
return; | ||
} | ||
if (opts.emitWsUpgrades && server.upgrade(request, { data: { req: request } })) { | ||
return new Response(null, { status: 101 }); | ||
} | ||
return (0, import_fetch.fetchRequestHandler)({ | ||
createContext: () => ({}), | ||
...opts, | ||
req: request, | ||
endpoint: opts.endpoint ?? "" | ||
}); | ||
}; | ||
} | ||
@@ -66,230 +57,226 @@ | ||
function createBunWSHandler(opts) { | ||
const { router, createContext } = opts; | ||
const respond = (client, untransformedJSON) => { | ||
client.send( | ||
JSON.stringify( | ||
(0, import_server.transformTRPCResponse)( | ||
opts.router._def._config, | ||
untransformedJSON, | ||
), | ||
), | ||
); | ||
}; | ||
return { | ||
async open(client) { | ||
const { req } = client.data; | ||
const clientSubscriptions = /* @__PURE__ */ new Map(); | ||
const ctxPromise = createContext?.({ req, client }); | ||
let ctx = void 0; | ||
await (async () => { | ||
try { | ||
ctx = await ctxPromise; | ||
} catch (cause) { | ||
const error = (0, import_server.getTRPCErrorFromUnknown)( | ||
cause, | ||
); | ||
opts.onError?.({ | ||
error, | ||
path: void 0, | ||
type: "unknown", | ||
ctx, | ||
req, | ||
input: void 0, | ||
}); | ||
respond(client, { | ||
id: null, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type: "unknown", | ||
path: void 0, | ||
input: void 0, | ||
ctx, | ||
}), | ||
}); | ||
setImmediate(() => client.close()); | ||
const { router, createContext } = opts; | ||
const respond = (client, untransformedJSON) => { | ||
client.send( | ||
JSON.stringify( | ||
(0, import_server.transformTRPCResponse)( | ||
opts.router._def._config, | ||
untransformedJSON | ||
) | ||
) | ||
); | ||
}; | ||
return { | ||
async open(client) { | ||
const { req } = client.data; | ||
const clientSubscriptions = /* @__PURE__ */ new Map(); | ||
const ctxPromise = createContext?.({ | ||
req, | ||
res: client | ||
}); | ||
let ctx = void 0; | ||
await (async () => { | ||
try { | ||
ctx = await ctxPromise; | ||
} catch (cause) { | ||
const error = (0, import_server.getTRPCErrorFromUnknown)(cause); | ||
opts.onError?.({ | ||
error, | ||
path: void 0, | ||
type: "unknown", | ||
ctx, | ||
req, | ||
input: void 0 | ||
}); | ||
respond(client, { | ||
id: null, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type: "unknown", | ||
path: void 0, | ||
input: void 0, | ||
ctx | ||
}) | ||
}); | ||
setImmediate(() => client.close()); | ||
} | ||
})(); | ||
const stopSubscription = (subscription, { | ||
id, | ||
jsonrpc | ||
}) => { | ||
subscription.unsubscribe(); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "stopped" | ||
} | ||
}); | ||
}; | ||
client.data.handleRequest = async (msg) => { | ||
const { id, jsonrpc } = msg; | ||
if (id === null) { | ||
throw new import_server.TRPCError({ | ||
code: "BAD_REQUEST", | ||
message: "`id` is required" | ||
}); | ||
} | ||
if (msg.method === "subscription.stop") { | ||
const sub = clientSubscriptions.get(id); | ||
if (sub) { | ||
stopSubscription(sub, { id, jsonrpc }); | ||
} | ||
clientSubscriptions.delete(id); | ||
return; | ||
} | ||
const { path, input } = msg.params; | ||
const type = msg.method; | ||
try { | ||
await ctxPromise; | ||
const result = await (0, import_server.callProcedure)({ | ||
procedures: router._def.procedures, | ||
path, | ||
input, | ||
getRawInput: () => Promise.resolve(input), | ||
ctx, | ||
type | ||
}); | ||
if (type === "subscription") { | ||
if (!(0, import_observable.isObservable)(result)) { | ||
throw new import_server.TRPCError({ | ||
message: `Subscription ${path} did not return an observable`, | ||
code: "INTERNAL_SERVER_ERROR" | ||
}); | ||
} | ||
} else { | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "data", | ||
data: result | ||
} | ||
}); | ||
return; | ||
} | ||
const observable = result; | ||
const sub = observable.subscribe({ | ||
next(data) { | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "data", | ||
data | ||
} | ||
})(); | ||
const stopSubscription = (subscription, { id, jsonrpc }) => { | ||
subscription.unsubscribe(); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "stopped", | ||
}, | ||
}); | ||
}; | ||
client.data.handleRequest = async (msg) => { | ||
const { id, jsonrpc } = msg; | ||
if (id === null) { | ||
throw new import_server.TRPCError({ | ||
code: "BAD_REQUEST", | ||
message: "`id` is required", | ||
}); | ||
}); | ||
}, | ||
error(err) { | ||
const error = (0, import_server.getTRPCErrorFromUnknown)(err); | ||
opts.onError?.({ | ||
error, | ||
path, | ||
type, | ||
ctx, | ||
req, | ||
input | ||
}); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type, | ||
path, | ||
input, | ||
ctx | ||
}) | ||
}); | ||
}, | ||
complete() { | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "stopped" | ||
} | ||
if (msg.method === "subscription.stop") { | ||
const sub = clientSubscriptions.get(id); | ||
if (sub) { | ||
stopSubscription(sub, { id, jsonrpc }); | ||
} | ||
clientSubscriptions.delete(id); | ||
return; | ||
} | ||
const { path, input } = msg.params; | ||
const type = msg.method; | ||
try { | ||
await ctxPromise; | ||
const result = await (0, import_server.callProcedure)({ | ||
procedures: router._def.procedures, | ||
path, | ||
input, | ||
getRawInput: () => Promise.resolve(input), | ||
ctx, | ||
type, | ||
}); | ||
if (type === "subscription") { | ||
if (!(0, import_observable.isObservable)(result)) { | ||
throw new import_server.TRPCError({ | ||
message: `Subscription ${path} did not return an observable`, | ||
code: "INTERNAL_SERVER_ERROR", | ||
}); | ||
} | ||
} else { | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "data", | ||
data: result, | ||
}, | ||
}); | ||
return; | ||
} | ||
const observable = result; | ||
const sub = observable.subscribe({ | ||
next(data) { | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "data", | ||
data, | ||
}, | ||
}); | ||
}, | ||
error(err) { | ||
const error = (0, | ||
import_server.getTRPCErrorFromUnknown)(err); | ||
opts.onError?.({ | ||
error, | ||
path, | ||
type, | ||
ctx, | ||
req, | ||
input, | ||
}); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type, | ||
path, | ||
input, | ||
ctx, | ||
}), | ||
}); | ||
}, | ||
complete() { | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "stopped", | ||
}, | ||
}); | ||
}, | ||
}); | ||
if (client.readyState !== WebSocket.OPEN) { | ||
sub.unsubscribe(); | ||
return; | ||
} | ||
if (clientSubscriptions.has(id)) { | ||
stopSubscription(sub, { id, jsonrpc }); | ||
throw new import_server.TRPCError({ | ||
message: `Duplicate id ${id}`, | ||
code: "BAD_REQUEST", | ||
}); | ||
} | ||
clientSubscriptions.set(id, sub); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "started", | ||
}, | ||
}); | ||
} catch (cause) { | ||
const error = (0, import_server.getTRPCErrorFromUnknown)( | ||
cause, | ||
); | ||
opts.onError?.({ error, path, type, ctx, req, input }); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type, | ||
path, | ||
input, | ||
ctx, | ||
}), | ||
}); | ||
} | ||
}; | ||
client.data.unsubscribe = () => { | ||
for (const sub of clientSubscriptions.values()) { | ||
sub.unsubscribe(); | ||
} | ||
clientSubscriptions.clear(); | ||
}; | ||
}, | ||
async close(client) { | ||
client.data.unsubscribe?.(); | ||
}, | ||
async message(client, message) { | ||
try { | ||
const msgJSON = JSON.parse(message.toString()); | ||
const msgs = Array.isArray(msgJSON) ? msgJSON : [msgJSON]; | ||
const promises = msgs | ||
.map((raw) => | ||
(0, import_rpc.parseTRPCMessage)( | ||
raw, | ||
router._def._config.transformer, | ||
), | ||
) | ||
.map(client.data.handleRequest); | ||
await Promise.all(promises); | ||
} catch (cause) { | ||
const error = new import_server.TRPCError({ | ||
code: "PARSE_ERROR", | ||
cause, | ||
}); | ||
respond(client, { | ||
id: null, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type: "unknown", | ||
path: void 0, | ||
input: void 0, | ||
ctx: void 0, | ||
}), | ||
}); | ||
}); | ||
} | ||
}, | ||
}; | ||
}); | ||
if (client.readyState !== WebSocket.OPEN) { | ||
sub.unsubscribe(); | ||
return; | ||
} | ||
if (clientSubscriptions.has(id)) { | ||
stopSubscription(sub, { id, jsonrpc }); | ||
throw new import_server.TRPCError({ | ||
message: `Duplicate id ${id}`, | ||
code: "BAD_REQUEST" | ||
}); | ||
} | ||
clientSubscriptions.set(id, sub); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
result: { | ||
type: "started" | ||
} | ||
}); | ||
} catch (cause) { | ||
const error = (0, import_server.getTRPCErrorFromUnknown)(cause); | ||
opts.onError?.({ error, path, type, ctx, req, input }); | ||
respond(client, { | ||
id, | ||
jsonrpc, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type, | ||
path, | ||
input, | ||
ctx | ||
}) | ||
}); | ||
} | ||
}; | ||
client.data.unsubscribe = () => { | ||
for (const sub of clientSubscriptions.values()) { | ||
sub.unsubscribe(); | ||
} | ||
clientSubscriptions.clear(); | ||
}; | ||
}, | ||
async close(client) { | ||
client.data.unsubscribe?.(); | ||
}, | ||
async message(client, message) { | ||
try { | ||
const msgJSON = JSON.parse(message.toString()); | ||
const msgs = Array.isArray(msgJSON) ? msgJSON : [msgJSON]; | ||
const promises = msgs.map( | ||
(raw) => (0, import_rpc.parseTRPCMessage)(raw, router._def._config.transformer) | ||
).map(client.data.handleRequest); | ||
await Promise.all(promises); | ||
} catch (cause) { | ||
const error = new import_server.TRPCError({ | ||
code: "PARSE_ERROR", | ||
cause | ||
}); | ||
respond(client, { | ||
id: null, | ||
error: (0, import_server.getErrorShape)({ | ||
config: router._def._config, | ||
error, | ||
type: "unknown", | ||
path: void 0, | ||
input: void 0, | ||
ctx: void 0 | ||
}) | ||
}); | ||
} | ||
} | ||
}; | ||
} | ||
@@ -299,26 +286,25 @@ | ||
function createBunServeHandler(opts, serveOptions) { | ||
const trpcHandler = createBunHttpHandler({ | ||
...opts, | ||
emitWsUpgrades: true, | ||
}); | ||
return { | ||
...serveOptions, | ||
async fetch(req, server) { | ||
const trpcReponse = trpcHandler(req, server); | ||
if (trpcReponse) { | ||
return trpcReponse; | ||
} | ||
return serveOptions?.fetch?.call(server, req, server); | ||
}, | ||
websocket: createBunWSHandler(opts), | ||
}; | ||
const trpcHandler = createBunHttpHandler({ | ||
...opts, | ||
emitWsUpgrades: true | ||
}); | ||
return { | ||
...serveOptions, | ||
async fetch(req, server) { | ||
const trpcReponse = trpcHandler(req, server); | ||
if (trpcReponse) { | ||
return trpcReponse; | ||
} | ||
return serveOptions?.fetch?.call(server, req, server); | ||
}, | ||
websocket: createBunWSHandler(opts) | ||
}; | ||
} | ||
// Annotate the CommonJS export names for ESM import in node: | ||
0 && | ||
(module.exports = { | ||
createBunHttpHandler, | ||
createBunServeHandler, | ||
createBunWSHandler, | ||
}); | ||
0 && (module.exports = { | ||
createBunHttpHandler, | ||
createBunServeHandler, | ||
createBunWSHandler | ||
}); | ||
/* istanbul ignore next -- @preserve */ | ||
//# sourceMappingURL=index.js.map | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "trpc-bun-adapter", | ||
"version": "1.1.1", | ||
"version": "1.1.2", | ||
"description": "TRPC adapter for bun js runtime", | ||
@@ -32,7 +32,7 @@ "main": "dist/index.js", | ||
"tsup": "^8.0.1", | ||
"typescript": "^5.5.2" | ||
"typescript": "^5.5.4" | ||
}, | ||
"peerDependencies": { | ||
"@trpc/server": "^11.0.0-next-beta.228" | ||
"@trpc/server": "^11.0.0-rc.477" | ||
} | ||
} |
@@ -11,9 +11,11 @@ import { Server } from "bun"; | ||
export type BunHttpHandlerOptions<TRouter extends AnyRouter> = | ||
FetchHandlerRequestOptions<TRouter> & { | ||
endpoint?: string; | ||
createContext?: ( | ||
opts: CreateBunContextOptions, | ||
) => inferRouterContext<TRouter> | Promise<inferRouterContext<TRouter>>; | ||
}; | ||
export type BunHttpHandlerOptions<TRouter extends AnyRouter> = Omit< | ||
FetchHandlerRequestOptions<TRouter>, | ||
"req" | ||
> & { | ||
endpoint?: string; | ||
createContext?: ( | ||
opts: CreateBunContextOptions, | ||
) => inferRouterContext<TRouter> | Promise<inferRouterContext<TRouter>>; | ||
}; | ||
@@ -38,2 +40,3 @@ export function createBunHttpHandler<TRouter extends AnyRouter>( | ||
return fetchRequestHandler({ | ||
createContext: () => ({}) as never, | ||
...opts, | ||
@@ -40,0 +43,0 @@ req: request, |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
89630
15
1275