shardwire 0.0.1

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,141 @@
1
+ # shardwire
2
+
3
+ Lightweight TypeScript library that turns a Discord bot host into a WebSocket command/event bridge.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add shardwire
9
+ ```
10
+
11
+ ## Host mode
12
+
13
+ ```ts
14
+ import { createShardwire } from "shardwire";
15
+
16
+ type Commands = {
17
+ "ban-user": { userId: string };
18
+ };
19
+
20
+ type Events = {
21
+ "member-joined": { userId: string; guildId: string };
22
+ };
23
+
24
+ const wire = createShardwire<Commands, Events>({
25
+ client: discordClient,
26
+ server: {
27
+ port: 3001,
28
+ secret: process.env.SHARDWIRE_SECRET!,
29
+ },
30
+ });
31
+
32
+ wire.onCommand("ban-user", async ({ userId }) => {
33
+ await guild.members.ban(userId);
34
+ return { banned: true };
35
+ });
36
+
37
+ wire.emitEvent("member-joined", { userId: "123", guildId: "456" });
38
+ ```
39
+
40
+ ## Consumer mode
41
+
42
+ ```ts
43
+ import { createShardwire } from "shardwire";
44
+
45
+ type Commands = {
46
+ "ban-user": { userId: string };
47
+ };
48
+
49
+ type Events = {
50
+ "member-joined": { userId: string; guildId: string };
51
+ };
52
+
53
+ const wire = createShardwire<Commands, Events>({
54
+ url: "ws://localhost:3001/shardwire",
55
+ secret: process.env.SHARDWIRE_SECRET!,
56
+ });
57
+
58
+ const result = await wire.send("ban-user", { userId: "123" });
59
+
60
+ wire.on("member-joined", (payload) => {
61
+ console.log(payload.guildId);
62
+ });
63
+ ```
64
+
65
+ ## Local examples
66
+
67
+ Run a local host and consumer in two terminals:
68
+
69
+ 1. Start host:
70
+ - `pnpm example:host`
71
+ 2. Start consumer:
72
+ - `pnpm example:consumer`
73
+
74
+ Environment overrides:
75
+
76
+ - `SHARDWIRE_SECRET` (default: `local-dev-secret`)
77
+ - `SHARDWIRE_PORT` for host (default: `3001`)
78
+ - `SHARDWIRE_URL` for consumer (default: `ws://localhost:3001/shardwire`)
79
+
80
+ ## API quick reference
81
+
82
+ ### Host
83
+
84
+ - `wire.onCommand(name, handler)` register a command handler.
85
+ - `wire.emitEvent(name, payload)` emit an event to all connected consumers.
86
+ - `wire.broadcast(name, payload)` alias of `emitEvent`.
87
+ - `wire.close()` stop websocket server and close connections.
88
+
89
+ ### Consumer
90
+
91
+ - `wire.send(name, payload, options?)` send command request and await typed result.
92
+ - `wire.on(name, handler)` subscribe to events.
93
+ - `wire.off(name, handler)` remove specific event handler.
94
+ - `wire.connected()` check authenticated connection state.
95
+ - `wire.close()` close socket and stop reconnect attempts.
96
+
97
+ ### Command result shape
98
+
99
+ `send()` resolves to:
100
+
101
+ - success: `{ ok: true, requestId, ts, data }`
102
+ - failure: `{ ok: false, requestId, ts, error: { code, message, details? } }`
103
+
104
+ Error codes: `AUTH_ERROR`, `TIMEOUT`, `COMMAND_NOT_FOUND`, `VALIDATION_ERROR`, `INTERNAL_ERROR`.
105
+
106
+ ## Runtime validation behavior
107
+
108
+ - Host config requires a valid `server` block (`port`, `secret`, and positive numeric limits).
109
+ - Consumer config requires non-empty `url` and `secret`.
110
+ - Command/event names must be non-empty strings.
111
+ - Command/event payloads must be JSON-serializable.
112
+
113
+ Invalid input throws synchronously with a descriptive `Error`.
114
+
115
+ ## Compatibility matrix
116
+
117
+ - Node.js: `>=18.18`
118
+ - TypeScript: `>=5.x` (consumer project)
119
+ - discord.js: `^14` (optional peer dependency)
120
+ - Module support: ESM + CJS exports
121
+
122
+ ## Security and operations notes
123
+
124
+ - Keep `secret` in environment variables, never commit it.
125
+ - v1 uses static shared secret (restart host to rotate).
126
+ - Use `server.corsOrigins` when browser clients connect.
127
+ - Set `server.maxPayloadBytes` and `requestTimeoutMs` for your workload profile.
128
+
129
+ ## CI and release workflow
130
+
131
+ - CI runs `pnpm verify` (`test`, `typecheck`, `build`) on pushes and pull requests.
132
+ - Local verification: `pnpm verify`
133
+ - Release guide: see `RELEASING.md`
134
+ - Change history: see `CHANGELOG.md`
135
+
136
+ ## v1 constraints
137
+
138
+ - Single package, no external services required.
139
+ - Single host process only (no cross-host sharding in v1).
140
+ - Shared-secret auth for host/consumer handshake.
141
+ - In-memory command dedupe and pending request tracking.
@@ -0,0 +1,101 @@
1
+ type CommandMap = Record<string, unknown>;
2
+ type EventMap = Record<string, unknown>;
3
+ type Unsubscribe = () => void;
4
+ interface ShardwireLogger {
5
+ debug?: (message: string, meta?: Record<string, unknown>) => void;
6
+ info?: (message: string, meta?: Record<string, unknown>) => void;
7
+ warn?: (message: string, meta?: Record<string, unknown>) => void;
8
+ error?: (message: string, meta?: Record<string, unknown>) => void;
9
+ }
10
+ interface DiscordClientLike {
11
+ login(token: string): Promise<string>;
12
+ destroy(): void;
13
+ once(event: "ready", listener: () => void): void;
14
+ on(event: "ready", listener: () => void): void;
15
+ off(event: "ready", listener: () => void): void;
16
+ }
17
+ interface CommandContext {
18
+ requestId: string;
19
+ receivedAt: number;
20
+ connectionId: string;
21
+ source?: string;
22
+ }
23
+ interface EventMeta {
24
+ ts: number;
25
+ source?: string;
26
+ }
27
+ interface CommandSuccess<T = unknown> {
28
+ ok: true;
29
+ requestId: string;
30
+ ts: number;
31
+ data: T;
32
+ }
33
+ interface CommandFailure {
34
+ ok: false;
35
+ requestId: string;
36
+ ts: number;
37
+ error: {
38
+ code: "AUTH_ERROR" | "TIMEOUT" | "COMMAND_NOT_FOUND" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
39
+ message: string;
40
+ details?: unknown;
41
+ };
42
+ }
43
+ type CommandResult<T = unknown> = CommandSuccess<T> | CommandFailure;
44
+ interface HostOptions<C extends CommandMap, E extends EventMap> {
45
+ client?: DiscordClientLike;
46
+ token?: string;
47
+ server: {
48
+ port: number;
49
+ host?: string;
50
+ secret: string;
51
+ path?: string;
52
+ heartbeatMs?: number;
53
+ commandTimeoutMs?: number;
54
+ maxPayloadBytes?: number;
55
+ corsOrigins?: string[];
56
+ };
57
+ name?: string;
58
+ logger?: ShardwireLogger;
59
+ }
60
+ interface ConsumerOptions<C extends CommandMap, E extends EventMap> {
61
+ url: string;
62
+ secret: string;
63
+ webSocketFactory?: (url: string) => {
64
+ readyState: number;
65
+ send(data: string): void;
66
+ close(code?: number, reason?: string): void;
67
+ on(event: "open" | "message" | "close" | "error", listener: (...args: any[]) => void): void;
68
+ once(event: "close", listener: () => void): void;
69
+ };
70
+ reconnect?: {
71
+ enabled?: boolean;
72
+ initialDelayMs?: number;
73
+ maxDelayMs?: number;
74
+ jitter?: boolean;
75
+ };
76
+ requestTimeoutMs?: number;
77
+ logger?: ShardwireLogger;
78
+ }
79
+ interface HostShardwire<C extends CommandMap, E extends EventMap> {
80
+ mode: "host";
81
+ onCommand<K extends keyof C & string>(name: K, handler: (payload: C[K], ctx: CommandContext) => Promise<unknown> | unknown): Unsubscribe;
82
+ emitEvent<K extends keyof E & string>(name: K, payload: E[K]): void;
83
+ broadcast<K extends keyof E & string>(name: K, payload: E[K]): void;
84
+ close(): Promise<void>;
85
+ }
86
+ interface ConsumerShardwire<C extends CommandMap, E extends EventMap> {
87
+ mode: "consumer";
88
+ send<K extends keyof C & string>(name: K, payload: C[K], options?: {
89
+ timeoutMs?: number;
90
+ requestId?: string;
91
+ }): Promise<CommandResult>;
92
+ on<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): Unsubscribe;
93
+ off<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): void;
94
+ connected(): boolean;
95
+ close(): Promise<void>;
96
+ }
97
+
98
+ declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: HostOptions<C, E>): HostShardwire<C, E>;
99
+ declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: ConsumerOptions<C, E>): ConsumerShardwire<C, E>;
100
+
101
+ export { type CommandContext, type CommandFailure, type CommandMap, type CommandResult, type CommandSuccess, type ConsumerOptions, type ConsumerShardwire, type DiscordClientLike, type EventMap, type EventMeta, type HostOptions, type HostShardwire, type ShardwireLogger, type Unsubscribe, createShardwire };
@@ -0,0 +1,101 @@
1
+ type CommandMap = Record<string, unknown>;
2
+ type EventMap = Record<string, unknown>;
3
+ type Unsubscribe = () => void;
4
+ interface ShardwireLogger {
5
+ debug?: (message: string, meta?: Record<string, unknown>) => void;
6
+ info?: (message: string, meta?: Record<string, unknown>) => void;
7
+ warn?: (message: string, meta?: Record<string, unknown>) => void;
8
+ error?: (message: string, meta?: Record<string, unknown>) => void;
9
+ }
10
+ interface DiscordClientLike {
11
+ login(token: string): Promise<string>;
12
+ destroy(): void;
13
+ once(event: "ready", listener: () => void): void;
14
+ on(event: "ready", listener: () => void): void;
15
+ off(event: "ready", listener: () => void): void;
16
+ }
17
+ interface CommandContext {
18
+ requestId: string;
19
+ receivedAt: number;
20
+ connectionId: string;
21
+ source?: string;
22
+ }
23
+ interface EventMeta {
24
+ ts: number;
25
+ source?: string;
26
+ }
27
+ interface CommandSuccess<T = unknown> {
28
+ ok: true;
29
+ requestId: string;
30
+ ts: number;
31
+ data: T;
32
+ }
33
+ interface CommandFailure {
34
+ ok: false;
35
+ requestId: string;
36
+ ts: number;
37
+ error: {
38
+ code: "AUTH_ERROR" | "TIMEOUT" | "COMMAND_NOT_FOUND" | "VALIDATION_ERROR" | "INTERNAL_ERROR";
39
+ message: string;
40
+ details?: unknown;
41
+ };
42
+ }
43
+ type CommandResult<T = unknown> = CommandSuccess<T> | CommandFailure;
44
+ interface HostOptions<C extends CommandMap, E extends EventMap> {
45
+ client?: DiscordClientLike;
46
+ token?: string;
47
+ server: {
48
+ port: number;
49
+ host?: string;
50
+ secret: string;
51
+ path?: string;
52
+ heartbeatMs?: number;
53
+ commandTimeoutMs?: number;
54
+ maxPayloadBytes?: number;
55
+ corsOrigins?: string[];
56
+ };
57
+ name?: string;
58
+ logger?: ShardwireLogger;
59
+ }
60
+ interface ConsumerOptions<C extends CommandMap, E extends EventMap> {
61
+ url: string;
62
+ secret: string;
63
+ webSocketFactory?: (url: string) => {
64
+ readyState: number;
65
+ send(data: string): void;
66
+ close(code?: number, reason?: string): void;
67
+ on(event: "open" | "message" | "close" | "error", listener: (...args: any[]) => void): void;
68
+ once(event: "close", listener: () => void): void;
69
+ };
70
+ reconnect?: {
71
+ enabled?: boolean;
72
+ initialDelayMs?: number;
73
+ maxDelayMs?: number;
74
+ jitter?: boolean;
75
+ };
76
+ requestTimeoutMs?: number;
77
+ logger?: ShardwireLogger;
78
+ }
79
+ interface HostShardwire<C extends CommandMap, E extends EventMap> {
80
+ mode: "host";
81
+ onCommand<K extends keyof C & string>(name: K, handler: (payload: C[K], ctx: CommandContext) => Promise<unknown> | unknown): Unsubscribe;
82
+ emitEvent<K extends keyof E & string>(name: K, payload: E[K]): void;
83
+ broadcast<K extends keyof E & string>(name: K, payload: E[K]): void;
84
+ close(): Promise<void>;
85
+ }
86
+ interface ConsumerShardwire<C extends CommandMap, E extends EventMap> {
87
+ mode: "consumer";
88
+ send<K extends keyof C & string>(name: K, payload: C[K], options?: {
89
+ timeoutMs?: number;
90
+ requestId?: string;
91
+ }): Promise<CommandResult>;
92
+ on<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): Unsubscribe;
93
+ off<K extends keyof E & string>(name: K, handler: (payload: E[K], meta: EventMeta) => void): void;
94
+ connected(): boolean;
95
+ close(): Promise<void>;
96
+ }
97
+
98
+ declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: HostOptions<C, E>): HostShardwire<C, E>;
99
+ declare function createShardwire<C extends CommandMap = {}, E extends EventMap = {}>(options: ConsumerOptions<C, E>): ConsumerShardwire<C, E>;
100
+
101
+ export { type CommandContext, type CommandFailure, type CommandMap, type CommandResult, type CommandSuccess, type ConsumerOptions, type ConsumerShardwire, type DiscordClientLike, type EventMap, type EventMeta, type HostOptions, type HostShardwire, type ShardwireLogger, type Unsubscribe, createShardwire };