skir-rpc 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.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +381 -2
  3. package/dist/cjs/base64.d.ts +9 -0
  4. package/dist/cjs/base64.d.ts.map +1 -0
  5. package/dist/cjs/base64.js +44 -0
  6. package/dist/cjs/base64.js.map +1 -0
  7. package/dist/cjs/client-types.d.ts +44 -0
  8. package/dist/cjs/client-types.d.ts.map +1 -0
  9. package/dist/cjs/client-types.js +3 -0
  10. package/dist/cjs/client-types.js.map +1 -0
  11. package/dist/cjs/client.d.ts +198 -0
  12. package/dist/cjs/client.d.ts.map +1 -0
  13. package/dist/cjs/client.js +1302 -0
  14. package/dist/cjs/client.js.map +1 -0
  15. package/dist/cjs/compression.d.ts +11 -0
  16. package/dist/cjs/compression.d.ts.map +1 -0
  17. package/dist/cjs/compression.js +92 -0
  18. package/dist/cjs/compression.js.map +1 -0
  19. package/dist/cjs/framing.d.ts +118 -0
  20. package/dist/cjs/framing.d.ts.map +1 -0
  21. package/dist/cjs/framing.js +423 -0
  22. package/dist/cjs/framing.js.map +1 -0
  23. package/dist/cjs/health.d.ts +25 -0
  24. package/dist/cjs/health.d.ts.map +1 -0
  25. package/dist/cjs/health.js +90 -0
  26. package/dist/cjs/health.js.map +1 -0
  27. package/dist/cjs/index.d.ts +13 -0
  28. package/dist/cjs/index.d.ts.map +1 -0
  29. package/dist/cjs/index.js +15 -0
  30. package/dist/cjs/index.js.map +1 -0
  31. package/dist/cjs/metadata.d.ts +53 -0
  32. package/dist/cjs/metadata.d.ts.map +1 -0
  33. package/dist/cjs/metadata.js +310 -0
  34. package/dist/cjs/metadata.js.map +1 -0
  35. package/dist/cjs/node-streams.d.ts +9 -0
  36. package/dist/cjs/node-streams.d.ts.map +1 -0
  37. package/dist/cjs/node-streams.js +55 -0
  38. package/dist/cjs/node-streams.js.map +1 -0
  39. package/dist/cjs/package.json +3 -0
  40. package/dist/cjs/server.d.ts +226 -0
  41. package/dist/cjs/server.d.ts.map +1 -0
  42. package/dist/cjs/server.js +1361 -0
  43. package/dist/cjs/server.js.map +1 -0
  44. package/dist/cjs/status.d.ts +88 -0
  45. package/dist/cjs/status.d.ts.map +1 -0
  46. package/dist/cjs/status.js +340 -0
  47. package/dist/cjs/status.js.map +1 -0
  48. package/dist/cjs/timeout.d.ts +21 -0
  49. package/dist/cjs/timeout.d.ts.map +1 -0
  50. package/dist/cjs/timeout.js +82 -0
  51. package/dist/cjs/timeout.js.map +1 -0
  52. package/dist/cjs/web-client.d.ts +92 -0
  53. package/dist/cjs/web-client.d.ts.map +1 -0
  54. package/dist/cjs/web-client.js +487 -0
  55. package/dist/cjs/web-client.js.map +1 -0
  56. package/dist/cjs/web-compression.d.ts +26 -0
  57. package/dist/cjs/web-compression.d.ts.map +1 -0
  58. package/dist/cjs/web-compression.js +157 -0
  59. package/dist/cjs/web-compression.js.map +1 -0
  60. package/dist/esm/base64.d.ts +9 -0
  61. package/dist/esm/base64.d.ts.map +1 -0
  62. package/dist/esm/base64.js +38 -0
  63. package/dist/esm/base64.js.map +1 -0
  64. package/dist/esm/client-types.d.ts +44 -0
  65. package/dist/esm/client-types.d.ts.map +1 -0
  66. package/dist/esm/client-types.js +2 -0
  67. package/dist/esm/client-types.js.map +1 -0
  68. package/dist/esm/client.d.ts +198 -0
  69. package/dist/esm/client.d.ts.map +1 -0
  70. package/dist/esm/client.js +1265 -0
  71. package/dist/esm/client.js.map +1 -0
  72. package/dist/esm/compression.d.ts +11 -0
  73. package/dist/esm/compression.d.ts.map +1 -0
  74. package/dist/esm/compression.js +88 -0
  75. package/dist/esm/compression.js.map +1 -0
  76. package/dist/esm/framing.d.ts +118 -0
  77. package/dist/esm/framing.d.ts.map +1 -0
  78. package/dist/esm/framing.js +412 -0
  79. package/dist/esm/framing.js.map +1 -0
  80. package/dist/esm/health.d.ts +25 -0
  81. package/dist/esm/health.d.ts.map +1 -0
  82. package/dist/esm/health.js +86 -0
  83. package/dist/esm/health.js.map +1 -0
  84. package/dist/esm/index.d.ts +13 -0
  85. package/dist/esm/index.d.ts.map +1 -0
  86. package/dist/esm/index.js +6 -0
  87. package/dist/esm/index.js.map +1 -0
  88. package/dist/esm/metadata.d.ts +53 -0
  89. package/dist/esm/metadata.d.ts.map +1 -0
  90. package/dist/esm/metadata.js +306 -0
  91. package/dist/esm/metadata.js.map +1 -0
  92. package/dist/esm/node-streams.d.ts +9 -0
  93. package/dist/esm/node-streams.d.ts.map +1 -0
  94. package/dist/esm/node-streams.js +52 -0
  95. package/dist/esm/node-streams.js.map +1 -0
  96. package/dist/esm/package.json +3 -0
  97. package/dist/esm/server.d.ts +226 -0
  98. package/dist/esm/server.d.ts.map +1 -0
  99. package/dist/esm/server.js +1324 -0
  100. package/dist/esm/server.js.map +1 -0
  101. package/dist/esm/status.d.ts +88 -0
  102. package/dist/esm/status.d.ts.map +1 -0
  103. package/dist/esm/status.js +321 -0
  104. package/dist/esm/status.js.map +1 -0
  105. package/dist/esm/timeout.d.ts +21 -0
  106. package/dist/esm/timeout.d.ts.map +1 -0
  107. package/dist/esm/timeout.js +76 -0
  108. package/dist/esm/timeout.js.map +1 -0
  109. package/dist/esm/web-client.d.ts +92 -0
  110. package/dist/esm/web-client.d.ts.map +1 -0
  111. package/dist/esm/web-client.js +481 -0
  112. package/dist/esm/web-client.js.map +1 -0
  113. package/dist/esm/web-compression.d.ts +26 -0
  114. package/dist/esm/web-compression.d.ts.map +1 -0
  115. package/dist/esm/web-compression.js +153 -0
  116. package/dist/esm/web-compression.js.map +1 -0
  117. package/package.json +84 -4
  118. package/src/base64.ts +43 -0
  119. package/src/client-types.ts +55 -0
  120. package/src/client.ts +2002 -0
  121. package/src/compression.ts +125 -0
  122. package/src/framing.ts +569 -0
  123. package/src/health.ts +114 -0
  124. package/src/index.ts +36 -0
  125. package/src/metadata.ts +353 -0
  126. package/src/node-streams.ts +71 -0
  127. package/src/server.ts +2008 -0
  128. package/src/status.ts +411 -0
  129. package/src/timeout.ts +88 -0
  130. package/src/web-client.ts +824 -0
  131. package/src/web-compression.ts +201 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tyler Fibonacci
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 CHANGED
@@ -1,3 +1,382 @@
1
- # Temporary Holding Version
1
+ [![npm](https://img.shields.io/npm/v/skir-rpc)](https://www.npmjs.com/package/skir-rpc)
2
+ [![build](https://github.com/gepheum/skir/actions/workflows/ci.yml/badge.svg)](https://github.com/gepheum/skir/actions)
2
3
 
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.
4
+ # SkirRPC 2.0 for TypeScript (`skir-rpc`)
5
+
6
+ Batteries-included HTTP/2 and Web RPC framework for [Skir](https://skir.build) — a full-featured alternative to gRPC with **zero third-party runtime dependencies**.
7
+
8
+ ## Features
9
+
10
+ - **All 4 RPC modes:** Unary, server-streaming, client-streaming, and full-duplex bidirectional streaming.
11
+ - **Opinionated self-hosted server (`RpcServer`):** Wraps `node:http2` and `node:http` on a single port (TLS/mTLS ALPN `h2` + `http/1.1`, or cleartext `h2c` prior knowledge + `http/1.1`) with graceful `GOAWAY` draining.
12
+ - **Native browser & edge streaming (`WebRpcClient`):** Unary and real-time server-streaming directly over `fetch()` + `ReadableStream` with zero `node:*` dependencies and **no Envoy / `grpc-web` proxy required**.
13
+ - **Fast dense JSON serialization + format-agnostic decoding:** Serializes payloads as compact dense JSON (`application/skir`) while decoding via `fromBytes()` (accepting both UTF-8 JSON and Skir binary frames transparently).
14
+ - **Rename-proof routing:** Routes by stable Skir method number (`/{MethodName}:{MethodNumber}`), so renaming a method in `.skir` never breaks deployed clients.
15
+ - **Rich status & typed error details:** All 17 canonical status codes (`RpcCode.OK` .. `RpcCode.UNAUTHENTICATED`), initial & trailing `Metadata` (including `-bin` binary values), and typed Skir error details (`err.withDetail` / `err.getDetail`).
16
+ - **Production client channel (`RpcClient`):** Multiplexed HTTP/2 connection pool, automatic multi-session scaling at `MAX_CONCURRENT_STREAMS`, `round_robin` / `pick_first` load balancing, dynamic `dns:///` re-resolution, `waitForReady`, HTTP/2 `PING` keepalives, deadlines, cascading `parentContext`, and unary retries.
17
+ - **Compression:** Built-in `gzip`, `deflate`, and `br` (Brotli) with decompression-bomb protection (`maxReceiveMessageBytes`), plus pluggable custom codecs.
18
+ - **Built-in operational services:** Health checking (`checkHealth`, streaming `watchHealth`, HTTP `GET /healthz`), `?list` reflection, and interactive Skir Studio (`?studio`).
19
+ - **100% SkirRPC 1.0 superset:** Existing SkirRPC 1.0 `ServiceClient`s (`GET` and `POST`) work seamlessly against any `RpcServer` on the same port.
20
+
21
+ ---
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install skir-rpc skir-client
27
+ ```
28
+
29
+ Requires **Node.js >= 20** on the server / Node client, or any modern browser / Edge runtime (`fetch` + `ReadableStream`) for `WebRpcClient`.
30
+
31
+ ### Package Entrypoints
32
+
33
+ | Import path | Environment | Contents |
34
+ |---|---|---|
35
+ | `"skir-rpc"` | Node.js *(maps to `./web` in browser bundlers)* | `RpcServer`, `RpcClient`, `WebRpcClient`, `Metadata`, `RpcError`, `RpcCode`, codecs, helpers |
36
+ | `"skir-rpc/server"` | Node.js | `RpcServer` and server handler types |
37
+ | `"skir-rpc/client"` | Node.js | `RpcClient` and HTTP/2 client types |
38
+ | `"skir-rpc/web"` | Browser, Cloudflare Workers, Deno, Bun, Edge | Zero-Node-dependency `WebRpcClient`, `Metadata`, `RpcError`, `RpcCode`, Web codecs |
39
+
40
+ ### `RpcClient` vs `WebRpcClient`
41
+
42
+ | Capability | `RpcClient` (Node.js) | `WebRpcClient` (Browser / Edge) |
43
+ |---|---|---|
44
+ | Underlying transport | `node:http2` (`h2` TLS & cleartext `h2c`) | Web `fetch()` + `ReadableStream` |
45
+ | Streaming modes | Unary, Server, Client, Full-Duplex Bidi | Unary & Server-Streaming |
46
+ | Client-side LB & `dns:///` | `round_robin`, `pick_first`, periodic DNS refresh, `waitForReady`, `PING` | Delegated to browser / L7 load balancer |
47
+ | TLS / Auth | Custom `ca`, mTLS client certs, metadata | Browser cookies (`credentials`), CORS, metadata |
48
+ | Built-in compression | `gzip`, `deflate`, `br` (Brotli) | `gzip`, `deflate` (`CompressionStream`) |
49
+
50
+ ---
51
+
52
+ ## Quick Start
53
+
54
+ ### 1. Start an `RpcServer`
55
+
56
+ ```typescript
57
+ import { RpcCode, RpcError, RpcServer } from "skir-rpc";
58
+ import { Chat, GetUser, UploadLogs, WatchUsers } from "./skirout/service.js";
59
+
60
+ interface AuthContext {
61
+ userId: string;
62
+ }
63
+
64
+ const server = new RpcServer<AuthContext>({
65
+ basePath: "/myapi",
66
+ responseCompression: "gzip",
67
+ authExtractor: async (metadata) => {
68
+ const token = metadata.get("authorization");
69
+ if (!token?.startsWith("Bearer ")) {
70
+ throw new RpcError(RpcCode.UNAUTHENTICATED, "Missing bearer token");
71
+ }
72
+ return { userId: token.slice("Bearer ".length) };
73
+ },
74
+ });
75
+
76
+ // 1. Unary RPC (Request -> Response)
77
+ server.addMethod(GetUser, async (req, ctx) => {
78
+ ctx.responseHeaders.set("x-served-by", "node-1");
79
+ ctx.responseTrailers.set("x-caller", ctx.auth.userId);
80
+ return findUser(req.userId);
81
+ });
82
+
83
+ // 2. Server-Streaming RPC (Request -> AsyncIterable<Response>)
84
+ server.addMethod(WatchUsers, async function* (req, ctx) {
85
+ // Flush initial headers immediately before waiting for the first event
86
+ ctx.flushResponseHeaders();
87
+ while (!ctx.signal.aborted) {
88
+ yield await nextUserEvent(req, ctx.signal);
89
+ }
90
+ });
91
+
92
+ // 3. Client-Streaming RPC (AsyncIterable<Request> -> Response)
93
+ server.addMethod(UploadLogs, async (requests, ctx) => {
94
+ let count = 0;
95
+ for await (const entry of requests) {
96
+ await saveLog(entry);
97
+ count++;
98
+ }
99
+ return UploadSummary.create({ acceptedCount: count });
100
+ });
101
+
102
+ // 4. Bidirectional-Streaming RPC (AsyncIterable<Request> -> AsyncIterable<Response>)
103
+ server.addMethod(Chat, async function* (requests, ctx) {
104
+ for await (const msg of requests) {
105
+ yield ChatReply.create({ text: `Echo: ${msg.text}` });
106
+ }
107
+ });
108
+
109
+ const address = await server.listen({ port: 8787 });
110
+ console.log(`Listening on ${address.url}`);
111
+ // Interactive Skir Studio UI is automatically served at http://127.0.0.1:8787/myapi?studio
112
+
113
+ process.on("SIGTERM", () => {
114
+ void server.shutdown({ gracePeriodMs: 10_000 });
115
+ });
116
+ ```
117
+
118
+ > **Push-writer alternative:** Prefer imperative `writer.write(msg)` over `async function*` generators (e.g. when pushing from event-listener callbacks)? Use `server.addMethodWithWriter(method, async (reqOrReqs, writer, ctx) => { ... })`.
119
+
120
+ ---
121
+
122
+ ### 2. Call Methods from Node.js (`RpcClient`)
123
+
124
+ ```typescript
125
+ import { RpcClient, RpcCode } from "skir-rpc";
126
+ import { Chat, GetUser, UploadLogs, WatchUsers } from "./skirout/service.js";
127
+
128
+ const client = new RpcClient("http://127.0.0.1:8787/myapi", {
129
+ metadata: () => ({ authorization: `Bearer ${getAccessToken()}` }),
130
+ requestCompression: "gzip",
131
+ defaultTimeoutMs: 5_000,
132
+ waitForReady: true,
133
+ keepaliveIntervalMs: 30_000,
134
+ retryPolicy: {
135
+ maxAttempts: 3,
136
+ initialBackoffMs: 50,
137
+ retryableStatusCodes: [RpcCode.UNAVAILABLE],
138
+ },
139
+ });
140
+
141
+ // 1. Unary call (optionally inspect response headers & trailers via callbacks)
142
+ const user = await client.invoke(GetUser, GetUserRequest.create({ userId: "42" }), {
143
+ onHeaders: (headers) => console.log("Request ID:", headers.get("x-request-id")),
144
+ onTrailers: (trailers) => console.log("Server timing:", trailers.get("server-timing")),
145
+ });
146
+
147
+ // 2. Server-streaming call
148
+ const userStream = client.invoke(WatchUsers, watchReq, {
149
+ timeoutMs: 60_000,
150
+ });
151
+ for await (const event of userStream) {
152
+ console.log("Event:", event);
153
+ if (shouldStop(event)) {
154
+ userStream.cancel("done watching"); // Sends HTTP/2 RST_STREAM -> aborts ctx.signal on server
155
+ }
156
+ }
157
+
158
+ // 3. Client-streaming call (pass an Array/AsyncIterable to invoke, or push via openStream)
159
+ const summary = await client.invoke(UploadLogs, [log1, log2, log3]);
160
+
161
+ const writable = client.openStream(UploadLogs);
162
+ await writable.write(log1);
163
+ await writable.write(log2);
164
+ writable.end();
165
+ const summary2 = await writable.response;
166
+
167
+ // 4. Full-duplex bidirectional streaming
168
+ const duplex = client.openStream(Chat);
169
+ await duplex.write(ChatMessage.create({ text: "hello" }));
170
+ for await (const reply of duplex) {
171
+ console.log("Reply:", reply.text);
172
+ duplex.end();
173
+ }
174
+
175
+ await client.close();
176
+ ```
177
+
178
+ ---
179
+
180
+ ### 3. Call Methods from the Browser or Edge (`WebRpcClient`)
181
+
182
+ ```typescript
183
+ import { WebRpcClient } from "skir-rpc/web";
184
+ import { GetUser, WatchUsers } from "./skirout/service.js";
185
+
186
+ const client = new WebRpcClient("https://api.example.com/myapi", {
187
+ metadata: { authorization: "Bearer browser-jwt" },
188
+ requestCompression: "gzip",
189
+ credentials: "include",
190
+ });
191
+
192
+ // Unary RPC
193
+ const response = await client.invoke(GetUser, req, {
194
+ onHeaders: (headers) => console.log("Headers:", headers),
195
+ onTrailers: (trailers) => console.log("Trailers:", trailers),
196
+ });
197
+
198
+ // Real-time server-streaming RPC over fetch() + ReadableStream
199
+ const stream = client.invoke(WatchUsers, watchReq);
200
+ for await (const event of stream) {
201
+ renderUpdate(event);
202
+ }
203
+ ```
204
+
205
+ ---
206
+
207
+ ## Errors & Typed Error Details
208
+
209
+ Throw `RpcError` inside handlers or interceptors with any of the 17 canonical `RpcCode`s, optional trailing `Metadata`, and zero or more typed Skir detail payloads:
210
+
211
+ ```typescript
212
+ import { RpcCode, RpcError } from "skir-rpc";
213
+ import { QuotaFailure } from "./skirout/errors.js";
214
+
215
+ // Server side:
216
+ throw new RpcError(RpcCode.RESOURCE_EXHAUSTED, "API quota exceeded", {
217
+ metadata: { "x-retry-after-ms": "1000" },
218
+ }).withDetail(
219
+ QuotaFailure.serializer,
220
+ QuotaFailure.create({ limit: 100, subject: "user:42" }),
221
+ );
222
+
223
+ // Client side (works identically in RpcClient and WebRpcClient):
224
+ try {
225
+ await client.invoke(GetUser, req);
226
+ } catch (err) {
227
+ if (err instanceof RpcError && err.code === RpcCode.RESOURCE_EXHAUSTED) {
228
+ const quota = err.getDetail(QuotaFailure.serializer);
229
+ const retryAfter = err.metadata.get("x-retry-after-ms");
230
+ console.error(err.codeName, err.message, quota, retryAfter);
231
+ }
232
+ }
233
+ ```
234
+
235
+ *(Note: throwing a SkirRPC 1.0 `ServiceError` inside a handler is also supported and automatically mapped to the matching `RpcCode`.)*
236
+
237
+ ---
238
+
239
+ ## Metadata (ASCII & Binary `-bin`)
240
+
241
+ `Metadata` is a case-insensitive multi-value map used for request headers, initial response headers, and response trailers. Keys ending in `"-bin"` carry binary `Uint8Array` payloads (automatically Base64-encoded on the wire):
242
+
243
+ ```typescript
244
+ import { Metadata } from "skir-rpc";
245
+
246
+ const meta = new Metadata({ "x-request-id": "req-123" });
247
+ meta.append("x-tag", "blue");
248
+ meta.append("x-tag", "green");
249
+ meta.setBinary("x-trace-context-bin", new Uint8Array([1, 2, 3, 4]));
250
+
251
+ await client.invoke(GetUser, req, { metadata: meta });
252
+ ```
253
+
254
+ ---
255
+
256
+ ## Deadlines & Cascading Cancellation
257
+
258
+ Set `timeoutMs` or `deadline` (`Date`, Skir `Timestamp`, or epoch ms) on any call. When calling downstream services from inside a server handler, pass `{ parentContext: ctx }` to automatically propagate both the **remaining deadline budget** and **cooperative cancellation** (`ctx.signal`):
259
+
260
+ ```typescript
261
+ server.addMethod(GetOrderDashboard, async (req, ctx) => {
262
+ const [user, orders] = await Promise.all([
263
+ userClient.invoke(GetUser, { userId: req.userId }, { parentContext: ctx }),
264
+ orderClient.invoke(ListOrders, { userId: req.userId }, { parentContext: ctx }),
265
+ ]);
266
+ return buildDashboard(user, orders);
267
+ });
268
+ ```
269
+
270
+ ---
271
+
272
+ ## Load Balancing, Dynamic DNS & Session Scaling (`RpcClient`)
273
+
274
+ - **Static multi-endpoint pool:**
275
+ ```typescript
276
+ const client = new RpcClient(
277
+ ["http://10.0.0.1:8787/myapi", "http://10.0.0.2:8787/myapi"],
278
+ {
279
+ loadBalancingPolicy: "round_robin", // or "pick_first"
280
+ },
281
+ );
282
+ ```
283
+ - **Headless Kubernetes / DNS service discovery (`dns:///` & `dns+https:///`):**
284
+ ```typescript
285
+ const client = new RpcClient("dns:///user-svc.prod.svc.cluster.local:8787/myapi", {
286
+ loadBalancingPolicy: "round_robin",
287
+ dnsRefreshIntervalMs: 30_000, // Periodically diffs pod IPs without dropping healthy sessions
288
+ maxSessionsPerEndpoint: 4, // Scales HTTP/2 sessions per pod when MAX_CONCURRENT_STREAMS fills
289
+ waitForReady: true, // Waits with backoff during pod rollouts up to call deadline
290
+ });
291
+ ```
292
+
293
+ ---
294
+
295
+ ## TLS & Mutual TLS (mTLS)
296
+
297
+ ```typescript
298
+ import * as fs from "node:fs";
299
+ import { RpcClient, RpcServer } from "skir-rpc";
300
+
301
+ const server = new RpcServer({
302
+ tls: {
303
+ key: fs.readFileSync("server-key.pem"),
304
+ cert: fs.readFileSync("server-cert.pem"),
305
+ ca: fs.readFileSync("client-ca.pem"),
306
+ requireClientCert: true, // Inspect verified cert via `ctx.tlsPeerCertificate`
307
+ },
308
+ });
309
+
310
+ const client = new RpcClient("https://rpc.example.com:8443", {
311
+ tls: {
312
+ ca: fs.readFileSync("server-ca.pem"),
313
+ key: fs.readFileSync("client-key.pem"),
314
+ cert: fs.readFileSync("client-cert.pem"),
315
+ },
316
+ });
317
+ ```
318
+
319
+ ---
320
+
321
+ ## Interceptors
322
+
323
+ Both `ServerInterceptor` and `ClientInterceptor` use a single unified streaming signature that wraps unary and streaming RPCs alike:
324
+
325
+ ```typescript
326
+ // Server logging & timing interceptor
327
+ server.use(async function* (call, next) {
328
+ const start = performance.now();
329
+ try {
330
+ yield* next(call.requests);
331
+ } finally {
332
+ const ms = (performance.now() - start).toFixed(1);
333
+ console.log(`${call.context.method.name} took ${ms}ms`);
334
+ }
335
+ });
336
+
337
+ // Client header-injection interceptor
338
+ client.use((call, requests, next) => {
339
+ call.metadata.set("x-correlation-id", crypto.randomUUID());
340
+ return next(call, requests);
341
+ });
342
+ ```
343
+
344
+ ---
345
+
346
+ ## Built-in Health Checking & Server Reflection
347
+
348
+ Built in on every `RpcServer` (health checking configurable via `enableHealthService`):
349
+
350
+ ```typescript
351
+ // Update overall ("") or per-service health on the server:
352
+ server.setHealthStatus("orders", "SERVING"); // "SERVING" | "NOT_SERVING" | "UNKNOWN"
353
+
354
+ // 1. Unary RPC health check:
355
+ const status = await client.checkHealth("orders");
356
+
357
+ // 2. Real-time streaming health watch:
358
+ for await (const nextStatus of client.watchHealth("orders")) {
359
+ console.log("Orders health:", nextStatus);
360
+ }
361
+
362
+ // 3. Plain HTTP probe for Kubernetes / ALB load balancers:
363
+ // GET http://127.0.0.1:8787/healthz?service=orders -> 200 "SERVING" or 503 "NOT_SERVING"
364
+
365
+ // 4. Schema discovery & interactive Skir Studio UI:
366
+ // GET http://127.0.0.1:8787/?list -> JSON method list + Skir TypeDescriptors
367
+ // GET http://127.0.0.1:8787/?studio -> Interactive Skir Studio web UI
368
+ ```
369
+
370
+ ---
371
+
372
+ ## Custom Compression Codecs
373
+
374
+ `gzip`, `deflate`, and `br` (Node) are built in. To register custom codecs (e.g. Zstandard), implement `CompressionCodec` (`{ name, compress, decompress }`) and pass `compressionCodecs: [zstdCodec]` to `RpcServer` and `RpcClient` / `WebRpcClient`.
375
+
376
+ ---
377
+
378
+ ## See Also
379
+
380
+ - [Skir Documentation](https://skir.build)
381
+ - [Skir GitHub Repository](https://github.com/gepheum/skir)
382
+ - [`skir-client` on npm](https://www.npmjs.com/package/skir-client)
@@ -0,0 +1,9 @@
1
+ export declare function encodeUtf8(str: string): Uint8Array;
2
+ export declare function decodeUtf8(bytes: Uint8Array): string;
3
+ export declare function bytesToBase64(bytes: Uint8Array): string;
4
+ /**
5
+ * Decodes standard, unpadded, or URL-safe Base64 into a `Uint8Array`
6
+ * (per gRPC HTTP/2 binary metadata rules).
7
+ */
8
+ export declare function base64ToBytes(b64: string): Uint8Array;
9
+ //# sourceMappingURL=base64.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64.d.ts","sourceRoot":"","sources":["../../src/base64.ts"],"names":[],"mappings":"AAAA,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAElD;AAED,wBAAgB,UAAU,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEpD;AAED,wBAAgB,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAMvD;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAmBrD"}
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.encodeUtf8 = encodeUtf8;
4
+ exports.decodeUtf8 = decodeUtf8;
5
+ exports.bytesToBase64 = bytesToBase64;
6
+ exports.base64ToBytes = base64ToBytes;
7
+ function encodeUtf8(str) {
8
+ return UTF8_ENCODER.encode(str);
9
+ }
10
+ function decodeUtf8(bytes) {
11
+ return UTF8_DECODER.decode(bytes);
12
+ }
13
+ function bytesToBase64(bytes) {
14
+ let binary = "";
15
+ for (let i = 0; i < bytes.byteLength; i++) {
16
+ binary += String.fromCharCode(bytes[i]);
17
+ }
18
+ return btoa(binary);
19
+ }
20
+ /**
21
+ * Decodes standard, unpadded, or URL-safe Base64 into a `Uint8Array`
22
+ * (per gRPC HTTP/2 binary metadata rules).
23
+ */
24
+ function base64ToBytes(b64) {
25
+ const normalized = b64
26
+ .replace(/[\r\n\s]/g, "")
27
+ .replace(/-/g, "+")
28
+ .replace(/_/g, "/");
29
+ let binary;
30
+ try {
31
+ binary = atob(normalized);
32
+ }
33
+ catch (err) {
34
+ throw new Error(`Invalid base64 binary payload: ${err instanceof Error ? err.message : String(err)}`, { cause: err });
35
+ }
36
+ const out = new Uint8Array(binary.length);
37
+ for (let i = 0; i < binary.length; i++) {
38
+ out[i] = binary.charCodeAt(i);
39
+ }
40
+ return out;
41
+ }
42
+ const UTF8_ENCODER = new TextEncoder();
43
+ const UTF8_DECODER = new TextDecoder();
44
+ //# sourceMappingURL=base64.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64.js","sourceRoot":"","sources":["../../src/base64.ts"],"names":[],"mappings":";;AAAA,gCAEC;AAED,gCAEC;AAED,sCAMC;AAMD,sCAmBC;AAvCD,SAAgB,UAAU,CAAC,GAAW;IACpC,OAAO,YAAY,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AAClC,CAAC;AAED,SAAgB,UAAU,CAAC,KAAiB;IAC1C,OAAO,YAAY,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AACpC,CAAC;AAED,SAAgB,aAAa,CAAC,KAAiB;IAC7C,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC,UAAU,EAAE,CAAC,EAAE,EAAE,CAAC;QAC1C,MAAM,IAAI,MAAM,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,CAAE,CAAC,CAAC;IAC3C,CAAC;IACD,OAAO,IAAI,CAAC,MAAM,CAAC,CAAC;AACtB,CAAC;AAED;;;GAGG;AACH,SAAgB,aAAa,CAAC,GAAW;IACvC,MAAM,UAAU,GAAG,GAAG;SACnB,OAAO,CAAC,WAAW,EAAE,EAAE,CAAC;SACxB,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC;SAClB,OAAO,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;IACtB,IAAI,MAAc,CAAC;IACnB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,UAAU,CAAC,CAAC;IAC5B,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CACb,kCAAkC,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EACpF,EAAE,KAAK,EAAE,GAAG,EAAE,CACf,CAAC;IACJ,CAAC;IACD,MAAM,GAAG,GAAG,IAAI,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IAC1C,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACvC,GAAG,CAAC,CAAC,CAAC,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IAChC,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC;AACvC,MAAM,YAAY,GAAG,IAAI,WAAW,EAAE,CAAC"}
@@ -0,0 +1,44 @@
1
+ import type { AnyMethod } from "skir-client";
2
+ import type { Metadata } from "./metadata.js";
3
+ import type { RpcCode } from "./status.js";
4
+ /** Automatic retry policy for unary RPCs. */
5
+ export interface RetryPolicy {
6
+ /** Maximum total attempts including the initial call (e.g. `3` = 1 call + up to 2 retries). */
7
+ readonly maxAttempts: number;
8
+ /** Initial backoff delay in milliseconds. Defaults to `50`. */
9
+ readonly initialBackoffMs?: number;
10
+ /** Maximum backoff cap in milliseconds. Defaults to `2000`. */
11
+ readonly maxBackoffMs?: number;
12
+ /** Exponential multiplier per attempt. Defaults to `2`. */
13
+ readonly backoffMultiplier?: number;
14
+ /** Whether to apply ±20% random jitter to backoff delays. Defaults to `true`. */
15
+ readonly jitter?: boolean;
16
+ /** Status codes eligible for retry. Defaults to `[RpcCode.UNAVAILABLE]`. */
17
+ readonly retryableStatusCodes?: readonly RpcCode[];
18
+ }
19
+ /** Streaming call handle returned by `invoke` for server-streaming and bidirectional-streaming methods. */
20
+ export interface ServerStreamingCall<Response> extends AsyncIterable<Response> {
21
+ readonly headers: Promise<Metadata>;
22
+ readonly trailers: Promise<Metadata>;
23
+ cancel(reason?: string): void;
24
+ }
25
+ /** Context visible to {@link ClientInterceptor}s. */
26
+ export interface ClientInterceptCall {
27
+ readonly method: AnyMethod<any, any>;
28
+ readonly metadata: Metadata;
29
+ readonly deadlineEpochMs: number | undefined;
30
+ readonly signal: AbortSignal | undefined;
31
+ }
32
+ /** Low-level transport result wrapped by {@link ClientInterceptor}s. */
33
+ export interface InterceptedClientStream {
34
+ readonly headers: Promise<Metadata>;
35
+ readonly trailers: Promise<Metadata>;
36
+ readonly responses: AsyncIterable<unknown>;
37
+ cancel(reason?: string): void;
38
+ }
39
+ /**
40
+ * Unified client interceptor supporting all 4 RPC cardinalities (logging, auth
41
+ * token injection, distributed tracing, metrics, client-side rate limiting).
42
+ */
43
+ export type ClientInterceptor = (call: ClientInterceptCall, requests: AsyncIterable<unknown>, next: (call: ClientInterceptCall, requests: AsyncIterable<unknown>) => InterceptedClientStream) => InterceptedClientStream;
44
+ //# sourceMappingURL=client-types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-types.d.ts","sourceRoot":"","sources":["../../src/client-types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAE3C,6CAA6C;AAC7C,MAAM,WAAW,WAAW;IAC1B,+FAA+F;IAC/F,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,+DAA+D;IAC/D,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,+DAA+D;IAC/D,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IAC/B,2DAA2D;IAC3D,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,iFAAiF;IACjF,QAAQ,CAAC,MAAM,CAAC,EAAE,OAAO,CAAC;IAC1B,4EAA4E;IAC5E,QAAQ,CAAC,oBAAoB,CAAC,EAAE,SAAS,OAAO,EAAE,CAAC;CACpD;AAED,2GAA2G;AAC3G,MAAM,WAAW,mBAAmB,CAAC,QAAQ,CAAE,SAAQ,aAAa,CAAC,QAAQ,CAAC;IAC5E,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IACpC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrC,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED,qDAAqD;AACrD,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACrC,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,eAAe,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7C,QAAQ,CAAC,MAAM,EAAE,WAAW,GAAG,SAAS,CAAC;CAC1C;AAED,wEAAwE;AACxE,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IACpC,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC;IACrC,QAAQ,CAAC,SAAS,EAAE,aAAa,CAAC,OAAO,CAAC,CAAC;IAC3C,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC/B;AAED;;;GAGG;AACH,MAAM,MAAM,iBAAiB,GAAG,CAC9B,IAAI,EAAE,mBAAmB,EACzB,QAAQ,EAAE,aAAa,CAAC,OAAO,CAAC,EAChC,IAAI,EAAE,CACJ,IAAI,EAAE,mBAAmB,EACzB,QAAQ,EAAE,aAAa,CAAC,OAAO,CAAC,KAC7B,uBAAuB,KACzB,uBAAuB,CAAC"}
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=client-types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client-types.js","sourceRoot":"","sources":["../../src/client-types.ts"],"names":[],"mappings":""}