bun-ws-router
Version:
Lightweight client/server WebSocket router for Bun with type-safe Zod/Valibot validation.
110 lines • 3.99 kB
JavaScript
// SPDX-FileCopyrightText: 2025-present Kriasoft
// SPDX-License-Identifier: MIT
import { validateMetaSchema } from "../shared/normalize.js";
/**
* Factory function to create messageSchema using the consumer's Zod instance.
*
* CRITICAL: This factory pattern is required to fix discriminated union support.
* Without it, the library and consumer use different Zod instances, causing
* instanceof checks to fail and discriminatedUnion to throw runtime errors.
*
* The factory pattern ensures:
* - Both library and app use the same Zod instance (no dual package hazard)
* - Discriminated unions work correctly with proper instanceof checks
* - Type inference flows through without manual type assertions
* - Schemas are composable and can be used in unions
*
* @param zod - The Zod instance from the consuming application
* @returns Object with messageSchema function and related utilities
*
* @example Basic usage:
* ```typescript
* import { z } from "zod";
* import { createMessageSchema } from "bun-ws-router/zod";
*
* const { messageSchema } = createMessageSchema(z);
* const PingSchema = messageSchema("PING");
* ```
*
* @example Singleton pattern (recommended for apps):
* ```typescript
* // schemas/factory.ts
* export const { messageSchema, createMessage } = createMessageSchema(z);
*
* // schemas/messages.ts
* import { messageSchema } from "./factory";
* const LoginSchema = messageSchema("LOGIN", { username: z.string() });
* ```
*
* @example With discriminated unions:
* ```typescript
* const PingSchema = messageSchema("PING");
* const PongSchema = messageSchema("PONG");
*
* // This now works correctly!
* const MessageUnion = z.discriminatedUnion("type", [PingSchema, PongSchema]);
* ```
*/
export function createMessageSchema(zod) {
// Create base schemas using the provided Zod instance
const MessageMetadataSchema = zod.object({
timestamp: zod.number().int().positive().optional(),
correlationId: zod.string().optional(),
});
const ErrorCode = zod.enum([
"INVALID_MESSAGE_FORMAT",
"VALIDATION_FAILED",
"UNSUPPORTED_MESSAGE_TYPE",
"AUTHENTICATION_FAILED",
"AUTHORIZATION_FAILED",
"RESOURCE_NOT_FOUND",
"RATE_LIMIT_EXCEEDED",
"INTERNAL_SERVER_ERROR",
]);
function messageSchema(messageType, payload, meta) {
// Validate that extended meta doesn't use reserved keys (fail-fast at schema creation)
validateMetaSchema(meta);
// Meta schema must be strict (reject unknown keys)
const metaSchema = (meta ? MessageMetadataSchema.extend(meta) : MessageMetadataSchema).strict();
const baseSchema = {
type: zod.literal(messageType),
meta: metaSchema,
};
if (payload === undefined) {
return zod.object(baseSchema).strict();
}
// Payloads can be a Zod object or a raw shape
const payloadSchema = (payload._def
? payload
: zod.object(payload)).strict(); // Payload must also be strict
return zod
.object({
...baseSchema,
payload: payloadSchema,
})
.strict();
}
// Standard schemas used across most WebSocket applications
const ErrorMessage = messageSchema("ERROR", {
code: ErrorCode,
message: zod.string().optional(),
context: zod.record(zod.string(), zod.any()).optional(),
});
// Client-side helper: validates and creates messages for sending
function createMessage(schema, payload, meta) {
const messageData = {
type: schema.shape.type.value,
...(payload !== undefined && { payload }),
meta: meta || {},
};
return schema.safeParse(messageData);
}
return {
messageSchema,
MessageMetadataSchema,
ErrorCode,
ErrorMessage,
createMessage,
};
}
//# sourceMappingURL=schema.js.map