@nifrajs/workers 0.1.0-alpha.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.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -0
  3. package/package.json +43 -0
  4. package/src/index.ts +114 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nifra Authors
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,18 @@
1
+ # @nifrajs/workers
2
+
3
+ Cloudflare Workers helpers for nifra — a Durable Object hub for cross-connection WebSocket broadcast.
4
+
5
+ Part of the **[nifra](https://nifra.dev)** full-stack TypeScript framework — one core, five UI libraries, every runtime. Scaffold a new app with `bun create nifra`.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ bun add @nifrajs/workers
11
+ ```
12
+
13
+ ## Docs
14
+
15
+ - Reference: <https://nifra.dev/docs>
16
+ - AI-readable: <https://nifra.dev/llms.txt>
17
+
18
+ MIT
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@nifrajs/workers",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Cloudflare Workers helpers for nifra — a Durable Object hub for cross-connection WebSocket broadcast.",
5
+ "keywords": [
6
+ "bun",
7
+ "typescript",
8
+ "nifra",
9
+ "web-framework",
10
+ "full-stack",
11
+ "edge",
12
+ "ssr"
13
+ ],
14
+ "type": "module",
15
+ "types": "./src/index.ts",
16
+ "exports": {
17
+ ".": {
18
+ "workerd": "./src/index.ts",
19
+ "types": "./src/index.ts",
20
+ "default": "./src/index.ts"
21
+ }
22
+ },
23
+ "files": [
24
+ "src"
25
+ ],
26
+ "sideEffects": false,
27
+ "license": "MIT",
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "dependencies": {
32
+ "@nifrajs/core": "workspace:*"
33
+ },
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/nifrajs/nifra.git",
37
+ "directory": "packages/workers"
38
+ },
39
+ "bugs": {
40
+ "url": "https://github.com/nifrajs/nifra/issues"
41
+ },
42
+ "homepage": "https://github.com/nifrajs/nifra#readme"
43
+ }
package/src/index.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Cloudflare Workers helpers for nifra.
3
+ *
4
+ * On Workers, a WebSocket lives in a single isolate, so a stateless `fetch` can't broadcast across
5
+ * connections — `app.publish(topic, data)` only reaches sockets in the same long-lived process. A
6
+ * **Durable Object** is that long-lived process: {@link createWebSocketHub} builds a DO class that
7
+ * holds every connection and runs the app's pub/sub registry, so `ws.subscribe` / `app.publish` work
8
+ * with their normal nifra semantics. Route upgrades to it with `toFetchHandler(app, { webSocketHub })`.
9
+ *
10
+ * // worker.ts
11
+ * import { server } from "@nifrajs/core"
12
+ * import { toFetchHandler } from "@nifrajs/core"
13
+ * import { createWebSocketHub } from "@nifrajs/workers"
14
+ *
15
+ * const app = server().ws("/chat", {
16
+ * open: (ws) => ws.subscribe("room"),
17
+ * message: (ws, text) => app.publish("room", text),
18
+ * })
19
+ *
20
+ * export const NifraWebSocketHub = createWebSocketHub(app) // bind as NIFRA_WS_HUB in wrangler.toml
21
+ * export default toFetchHandler(app, { webSocketHub: (env) => env.NIFRA_WS_HUB })
22
+ *
23
+ * # wrangler.toml
24
+ * # [[durable_objects.bindings]]
25
+ * # name = "NIFRA_WS_HUB"
26
+ * # class_name = "NifraWebSocketHub"
27
+ * # [[migrations]]
28
+ * # tag = "v1"
29
+ * # new_sqlite_classes = ["NifraWebSocketHub"]
30
+ */
31
+ // The `/ws` subpath registers core's WebSocket runtime as a side effect — so importing the hub is
32
+ // enough to enable `app.ws()`; worker entries don't need a separate `import "@nifrajs/core/ws"`.
33
+
34
+ import type { StandardWebSocket, WebSocketUpgradeOutcome } from "@nifrajs/core"
35
+ import { attachWebSocket } from "@nifrajs/core/ws"
36
+
37
+ /** The nifra-app surface the hub needs — every `server()` app satisfies it. */
38
+ export interface WebSocketHubApp<Env = unknown> {
39
+ resolveWebSocketUpgrade(
40
+ request: Request,
41
+ platform?: { readonly env: Env; readonly waitUntil: (promise: Promise<unknown>) => void },
42
+ ): WebSocketUpgradeOutcome | Promise<WebSocketUpgradeOutcome>
43
+ }
44
+
45
+ /** Structural view of a Durable Object's state (only `waitUntil` is used). */
46
+ interface DurableObjectStateLike {
47
+ waitUntil?(promise: Promise<unknown>): void
48
+ }
49
+
50
+ /** Cloudflare's `WebSocketPair` (a Workers global) — structurally typed to avoid a CF types dependency. */
51
+ type WebSocketPairCtor = new () => {
52
+ readonly 0: unknown
53
+ readonly 1: StandardWebSocket & { accept(): void }
54
+ }
55
+
56
+ /** The Durable Object class shape `createWebSocketHub` returns. */
57
+ export type WebSocketHubClass<Env> = new (
58
+ state: DurableObjectStateLike,
59
+ env: Env,
60
+ ) => { fetch(request: Request): Promise<Response> }
61
+
62
+ /**
63
+ * Build a Durable Object class that serves an app's `app.ws()` routes with **cross-connection
64
+ * broadcast**. Every WebSocket accepted here lives in the DO's isolate, and the app's `TopicRegistry`
65
+ * lives there too — so `ws.subscribe(topic)` and `app.publish(topic, data)` (called from the WS
66
+ * lifecycle) reach every connected client. Route upgrades to it via
67
+ * `toFetchHandler(app, { webSocketHub: (env) => env.YOUR_BINDING })`.
68
+ *
69
+ * Single hub: all connections route to one DO instance, so topics are app-global (matching nifra's
70
+ * in-process semantics). Shard by room later by giving the hub a room-derived id.
71
+ */
72
+ export function createWebSocketHub<Env = unknown>(
73
+ app: WebSocketHubApp<Env>,
74
+ ): WebSocketHubClass<Env> {
75
+ return class NifraWebSocketHub {
76
+ readonly #env: Env
77
+ readonly #state: DurableObjectStateLike
78
+
79
+ constructor(state: DurableObjectStateLike, env: Env) {
80
+ this.#state = state
81
+ this.#env = env
82
+ }
83
+
84
+ async fetch(request: Request): Promise<Response> {
85
+ const platform = {
86
+ env: this.#env,
87
+ waitUntil: (promise: Promise<unknown>) => {
88
+ this.#state.waitUntil?.(promise)
89
+ },
90
+ }
91
+ const outcome = await app.resolveWebSocketUpgrade(request, platform)
92
+ if (outcome.kind === "reject") return outcome.response
93
+ if (outcome.kind !== "upgrade") {
94
+ // Not a registered WS route (or not an upgrade) — nothing for the hub to do.
95
+ return new Response("Upgrade Required", { status: 426 })
96
+ }
97
+ const Pair = (globalThis as { WebSocketPair?: WebSocketPairCtor }).WebSocketPair
98
+ if (Pair === undefined) {
99
+ return new Response("WebSocketPair unavailable (not a Workers runtime)", { status: 500 })
100
+ }
101
+ const pair = new Pair()
102
+ const server = pair[1]
103
+ server.accept()
104
+ // The socket + the app's pub/sub registry both live in this DO isolate, so a broadcast from any
105
+ // connection's `message`/`open` (via `app.publish`) reaches every client held here.
106
+ attachWebSocket(server, outcome.handler, outcome.data, {
107
+ openNow: true,
108
+ pubsub: outcome.pubsub,
109
+ })
110
+ // `webSocket` is a Workers-only `ResponseInit` field, and 101 is only valid on Workers.
111
+ return new Response(null, { status: 101, webSocket: pair[0] } as unknown as ResponseInit)
112
+ }
113
+ }
114
+ }