@spikard/node 0.13.0 → 0.15.2

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/index.d.ts CHANGED
@@ -1,378 +1,808 @@
1
1
  /* auto-generated by NAPI-RS */
2
2
  /* eslint-disable */
3
3
  /**
4
- * JavaScript-side gRPC message stream for client streaming RPC
4
+ * Configuration for GraphQL routes
5
5
  *
6
- * Wraps a Rust MessageStream and exposes JavaScript async iterator protocol
7
- * so JavaScript handlers can consume incoming messages as an async iterable.
6
+ * Provides a builder pattern for configuring GraphQL route parameters
7
+ * for the Spikard HTTP server's routing system.
8
+ *
9
+ * # Example
8
10
  */
9
- export declare class GrpcMessageStream {
11
+ export declare class GraphQLRouteConfig {
12
+ /**
13
+ * Set the HTTP path for the GraphQL endpoint
14
+ *
15
+ * # Arguments
16
+ *
17
+ * * `path` - The URL path (e.g., "/graphql", "/api/graphql")
18
+ */
19
+ path(path: string): GraphQLRouteConfig
20
+ /**
21
+ * Set the HTTP method for the GraphQL endpoint
22
+ *
23
+ * # Arguments
24
+ *
25
+ * * `method` - The HTTP method (typically "POST")
26
+ */
27
+ method(method: string): GraphQLRouteConfig
28
+ /**
29
+ * Enable or disable the GraphQL Playground UI
30
+ *
31
+ * # Arguments
32
+ *
33
+ * * `enable` - Whether to enable playground
34
+ */
35
+ enablePlayground(enable: boolean): GraphQLRouteConfig
10
36
  /**
11
- * Get the next message from the stream
37
+ * Set a custom description for documentation
38
+ *
39
+ * # Arguments
12
40
  *
13
- * Returns a Promise that resolves to the next message Buffer or null if stream is done.
14
- * Throws an error if the stream encounters an error.
41
+ * * `description` - Documentation string
15
42
  */
16
- next(): Promise<Buffer | null>
43
+ description(description: string): GraphQLRouteConfig
44
+ /** Get the configured path */
45
+ getPath(): string
46
+ /** Get the configured method */
47
+ getMethod(): string
48
+ /** Check if playground is enabled */
49
+ isPlaygroundEnabled(): boolean
50
+ /** Get the description if set */
51
+ getDescription(): string | null
52
+ static default(): GraphQLRouteConfig
17
53
  }
54
+ export type JsGraphQLRouteConfig = GraphQLRouteConfig
18
55
 
19
- /** Node.js wrapper for SSE event */
20
- export declare class SseEvent {
56
+ export declare class JsGraphQlErrorInfo {
57
+ statusCode: number
58
+ isTransient: boolean
59
+ errorType: string
60
+ /** HTTP status code for this error (0 means no associated status). */
61
+ statusCode(): number
62
+ /** Returns `true` if the error is transient and a retry may succeed. */
63
+ isTransient(): boolean
64
+ /** Machine-readable error category string for matching and logging. */
65
+ errorType(): string
66
+ }
67
+ export type JsGraphQLErrorInfo = JsGraphQlErrorInfo
21
68
 
69
+ /**
70
+ * Core test client for making HTTP requests to a Spikard application.
71
+ *
72
+ * This struct wraps axum-test's TestServer and provides a language-agnostic
73
+ * interface for making HTTP requests, sending WebSocket connections, and
74
+ * handling Server-Sent Events. Language bindings wrap this to provide
75
+ * native API surfaces.
76
+ */
77
+ export declare class TestClient {
78
+ /** a GraphQL query/mutation to a custom endpoint */
79
+ graphqlAt(endpoint: string, query: string, variables?: any | undefined | null, operationName?: string | undefined | null): Promise<ResponseSnapshot>
80
+ /** a GraphQL query/mutation */
81
+ graphql(query: string, variables?: any | undefined | null, operationName?: string | undefined | null): Promise<ResponseSnapshot>
82
+ /**
83
+ * a GraphQL subscription (WebSocket) to a custom endpoint.
84
+ *
85
+ * Uses the `graphql-transport-ws` protocol and captures the first `next` payload.
86
+ * After the first payload is received, this client sends `complete` to unsubscribe.
87
+ */
88
+ graphqlSubscriptionAt(endpoint: string, query: string, variables?: any | undefined | null, operationName?: string | undefined | null): Promise<GraphQLSubscriptionSnapshot>
89
+ /**
90
+ * a GraphQL subscription (WebSocket).
91
+ *
92
+ * Uses `/graphql` as the default subscription endpoint.
93
+ */
94
+ graphqlSubscription(query: string, variables?: any | undefined | null, operationName?: string | undefined | null): Promise<GraphQLSubscriptionSnapshot>
22
95
  }
96
+ export type JsTestClient = TestClient
23
97
 
24
- /** Node.js wrapper for SSE event */
25
- export declare class SseEvent {
26
- /** Get the data field of the event */
27
- getData(): string
28
- /** Parse the event data as JSON */
29
- asJson(): any
30
- /** Get the data field of the event */
31
- getData(): string
32
- /** Parse the event data as JSON */
33
- asJson(): any
98
+ /** API Key authentication configuration */
99
+ export interface ApiKeyConfig {
100
+ /** Valid API keys */
101
+ keys: Array<string>
102
+ /** Header name to check (e.g., "X-API-Key") */
103
+ headerName: string
34
104
  }
35
105
 
36
- /** Node.js wrapper for SSE stream */
37
- export declare class SseStream {
106
+ /** AsyncAPI HTTP endpoint configuration */
107
+ export interface AsyncApiConfig {
108
+ /** Enable AsyncAPI endpoints (default: false) */
109
+ enabled?: boolean
110
+ /** Pre-registered AsyncAPI spec to serve from GET /asyncapi.json */
111
+ spec?: any
112
+ }
38
113
 
114
+ export interface BackgroundJobMetadata {
115
+ name?: string
116
+ requestId?: string
39
117
  }
40
118
 
41
- /** Node.js wrapper for SSE stream */
42
- export declare class SseStream {
43
- /** Get the raw body of the SSE response */
44
- body(): string
45
- /** Get all events from the stream */
46
- events(): Array<SseEvent>
47
- /** Get events as JSON values */
48
- eventsAsJson(): Array<any>
49
- /** Get the raw body of the SSE response */
50
- body(): string
51
- /** Get all events from the stream */
52
- events(): Array<SseEvent>
53
- /** Get events as JSON values */
54
- eventsAsJson(): Array<any>
119
+ export declare function backgroundJobMetadataDefault(): BackgroundJobMetadata
120
+
121
+ /** Configuration for in-process background task execution. */
122
+ export interface BackgroundTaskConfig {
123
+ maxQueueSize?: number
124
+ maxConcurrentTasks?: number
125
+ drainTimeoutSecs?: number
55
126
  }
56
127
 
57
- /** Test client for making HTTP requests to a Spikard application */
58
- export declare class TestClient {
59
- /** Create a new test client from routes and handlers */
60
- constructor(routesJson: string, websocketRoutesJson: string | undefined | null, handlersMap: object, websocketHandlers?: object | undefined | null, dependencies?: object | undefined | null, lifecycleHooks?: object | undefined | null, config?: object | undefined | null)
61
- /** Make a GET request. */
62
- get(path: string, headers?: any | undefined | null): Promise<TestResponse>
63
- /** Make a POST request with an optional JSON body. */
64
- post(path: string, headers?: any | undefined | null, json?: any | undefined | null): Promise<TestResponse>
65
- /** Make a PUT request with an optional JSON body. */
66
- put(path: string, headers?: any | undefined | null, json?: any | undefined | null): Promise<TestResponse>
67
- /** Make a DELETE request. */
68
- delete(path: string, headers?: any | undefined | null): Promise<TestResponse>
69
- /** Make a PATCH request with an optional JSON body. */
70
- patch(path: string, headers?: any | undefined | null, json?: any | undefined | null): Promise<TestResponse>
71
- /** Make a HEAD request. */
72
- head(path: string, headers?: any | undefined | null): Promise<TestResponse>
73
- /** Make an OPTIONS request. */
74
- options(path: string, headers?: any | undefined | null): Promise<TestResponse>
75
- /** Make a TRACE request. */
76
- trace(path: string, headers?: any | undefined | null): Promise<TestResponse>
77
- /** Connect to a Server-Sent Events endpoint */
78
- sse(path: string): Promise<SseStream>
79
- /** Connect to a WebSocket endpoint */
80
- websocket(path: string): Promise<WebSocketTestConnection>
81
- }
82
-
83
- /** HTTP Response wrapper */
84
- export declare class TestResponse {
85
- /** Get the HTTP status code */
86
- get statusCode(): number
87
- /** Get response headers as JSON */
88
- headers(): any
89
- /** Get response body as text */
90
- text(): string
91
- /** Parse response body as JSON */
92
- json(): any
93
- /** Get raw response body bytes */
94
- bytes(): Buffer
95
- /** Extract GraphQL data from response */
96
- graphqlData(): any
97
- /** Extract GraphQL errors from response */
98
- graphqlErrors(): Array<any>
99
- }
100
-
101
- /** Node.js wrapper for WebSocket messages */
102
- export declare class WebSocketMessage {
103
-
104
- }
105
-
106
- /** Node.js wrapper for WebSocket messages */
107
- export declare class WebSocketMessage {
108
- /** Get message as text if it's a text message */
109
- asText(): string | null
110
- /** Get message as JSON if it's a text message containing JSON */
111
- asJson(): any | null
112
- /** Get message as binary if it's a binary message */
113
- asBinary(): Buffer | null
114
- /** Check if this is a close message */
115
- isClose(): boolean
116
- /** Get message as text if it's a text message */
117
- asText(): string | null
118
- /** Get message as JSON if it's a text message containing JSON */
119
- asJson(): any | null
120
- /** Get message as binary if it's a binary message */
121
- asBinary(): Buffer | null
122
- /** Check if this is a close message */
123
- isClose(): boolean
124
- }
125
-
126
- /** Node.js wrapper for WebSocket test client */
127
- export declare class WebSocketTestConnection {
128
-
129
- }
130
-
131
- /** Node.js wrapper for WebSocket test client */
132
- export declare class WebSocketTestConnection {
133
- /** Send a text message */
134
- sendText(text: string): Promise<void>
135
- /** Send a JSON message */
136
- sendJson(obj: any): Promise<void>
137
- /** Receive a text message */
138
- receiveText(): Promise<string>
139
- /** Receive and parse a JSON message */
140
- receiveJson(): Promise<any>
141
- /** Receive raw bytes */
142
- receiveBytes(): Promise<Buffer>
143
- /** Receive a message and return WebSocketMessage */
144
- receiveMessage(): Promise<WebSocketMessage>
145
- /** Close the WebSocket connection */
146
- close(): Promise<void>
147
- /** Send a text message */
148
- sendText(text: string): Promise<void>
149
- /** Send a JSON message */
150
- sendJson(obj: any): Promise<void>
151
- /** Receive a text message */
152
- receiveText(): Promise<string>
153
- /** Receive and parse a JSON message */
154
- receiveJson(): Promise<any>
155
- /** Receive raw bytes */
156
- receiveBytes(): Promise<Buffer>
157
- /** Receive a message and return WebSocketMessage */
158
- receiveMessage(): Promise<WebSocketMessage>
159
- /** Close the WebSocket connection */
160
- close(): Promise<void>
161
- }
162
-
163
- /** Run an async task on Spikard's background runtime. */
164
- export declare function backgroundRun(task: () => Promise<undefined>): void
128
+ export declare function backgroundTaskConfigDefault(): BackgroundTaskConfig
129
+
130
+ /** Compression configuration shared across runtimes */
131
+ export interface CompressionConfig {
132
+ /** Enable gzip compression */
133
+ gzip?: boolean
134
+ /** Enable brotli compression */
135
+ brotli?: boolean
136
+ /** Minimum response size to compress (bytes) */
137
+ minSize?: number
138
+ /** Compression quality (0-11 for brotli, 0-9 for gzip) */
139
+ quality?: number
140
+ }
141
+
142
+ export declare function compressionConfigDefault(): CompressionConfig
143
+
144
+ /** Contact information */
145
+ export interface ContactInfo {
146
+ /** Name of the contact person or organisation. */
147
+ name?: string
148
+ /** Contact email address. */
149
+ email?: string
150
+ /** URL pointing to the contact information page. */
151
+ url?: string
152
+ }
153
+
154
+ /** CORS configuration for a route */
155
+ export interface CorsConfig {
156
+ allowedOrigins?: Array<string>
157
+ allowedMethods?: Array<string>
158
+ allowedHeaders?: Array<string>
159
+ exposeHeaders?: Array<string>
160
+ maxAge?: number
161
+ allowCredentials?: boolean
162
+ }
163
+
164
+ export declare function corsConfigDefault(): CorsConfig
165
+
166
+ /** Configuration for fully-featured schemas with Query, Mutation, and Subscription types */
167
+ export interface FullSchemaConfig {
168
+ /** Enable introspection queries */
169
+ introspectionEnabled?: boolean
170
+ /** Maximum query complexity (None = unlimited) */
171
+ complexityLimit?: number
172
+ /** Maximum query depth (None = unlimited) */
173
+ depthLimit?: number
174
+ }
175
+
176
+ export declare function fullSchemaConfigDefault(): FullSchemaConfig
177
+
178
+ /** Snapshot of a GraphQL subscription exchange over WebSocket. */
179
+ export interface GraphQLSubscriptionSnapshot {
180
+ /** Operation id used for the subscription request. */
181
+ operationId: string
182
+ /** Whether the server acknowledged the GraphQL WebSocket connection. */
183
+ acknowledged: boolean
184
+ /** First `next.payload` received for this subscription, if any. */
185
+ event?: any
186
+ /** GraphQL protocol errors emitted by the server. */
187
+ errors: Array<any>
188
+ /** Whether a `complete` frame was observed for this operation. */
189
+ completeReceived: boolean
190
+ }
165
191
 
166
192
  /**
167
- * Creates a streaming handle from a JavaScript async iterator.
193
+ * Configuration for gRPC support
194
+ *
195
+ * Controls how the server handles gRPC requests, including compression,
196
+ * timeouts, and protocol settings.
197
+ *
198
+ * # Stream Limits
199
+ *
200
+ * This configuration enforces message-level size limits but delegates
201
+ * concurrent stream limiting to the HTTP/2 transport layer:
202
+ *
203
+ * - **Message Size Limits**: The `max_message_size` field is enforced per
204
+ * individual message (request or response) in both unary and streaming RPCs.
205
+ * When a single message exceeds this limit, the request is rejected with
206
+ * `PAYLOAD_TOO_LARGE` (HTTP 413).
207
+ *
208
+ * - **Concurrent Stream Limits**: The `max_concurrent_streams` is an advisory
209
+ * configuration passed to the HTTP/2 layer for connection-level stream
210
+ * negotiation. The HTTP/2 transport automatically enforces this limit and
211
+ * returns GOAWAY frames when exceeded. Applications should not rely on
212
+ * custom enforcement of this limit.
168
213
  *
169
- * This function is exposed to JavaScript via napi. It wraps async iterators
170
- * in a streaming handle structure that can be used to construct HTTP streaming responses.
214
+ * - **Stream Response Size Limits**: The `max_stream_response_bytes` field caps the
215
+ * total encoded bytes emitted across a server-streaming or bidi-streaming response.
216
+ * When the cumulative size exceeds the limit, the stream is terminated with
217
+ * `tonic.Status.resource_exhausted`. Defaults to `None` (unbounded).
171
218
  *
172
- * NOTE: Marked with #[allow(dead_code)] because the #[napi] macro generates
173
- * FFI bindings that aren't visible to the Rust dead code checker, though the
174
- * function is actually exported and callable from JavaScript.
219
+ * # Example
175
220
  */
176
- export declare function createStreamingHandle(iterator: object, init?: StreamingResponseInit | undefined | null): number
221
+ export interface GrpcConfig {
222
+ /** Enable gRPC support */
223
+ enabled?: boolean
224
+ /**
225
+ * Maximum message size in bytes (for both sending and receiving)
226
+ *
227
+ * This limit applies to individual messages in both unary and streaming RPCs.
228
+ * When a single message exceeds this size, the request is rejected with HTTP 413
229
+ * (Payload Too Large).
230
+ *
231
+ * Default: 4MB (4194304 bytes)
232
+ *
233
+ * # Note
234
+ * This limit does NOT apply to the total response size in streaming RPCs.
235
+ * For multi-message streams, the total response can exceed this limit as long
236
+ * as each individual message stays within the limit.
237
+ */
238
+ maxMessageSize?: number
239
+ /** Enable gzip compression for gRPC messages */
240
+ enableCompression?: boolean
241
+ /** Timeout for gRPC requests in seconds (None = no timeout) */
242
+ requestTimeout?: number
243
+ /**
244
+ * Maximum number of concurrent streams per connection (HTTP/2 advisory)
245
+ *
246
+ * This value is communicated to HTTP/2 clients as the server's flow control limit.
247
+ * The HTTP/2 transport layer enforces this limit automatically via SETTINGS frames
248
+ * and GOAWAY responses. Applications should NOT implement custom enforcement.
249
+ *
250
+ * Default: 100 streams per connection
251
+ *
252
+ * # Stream Limiting Strategy
253
+ * - **Per Connection**: This limit applies per HTTP/2 connection, not globally
254
+ * - **Transport Enforcement**: HTTP/2 handles all stream limiting; applications
255
+ * need not implement custom checks
256
+ * - **Streaming Requests**: In server streaming or bidi streaming, each logical
257
+ * RPC consumes one stream slot. Message ordering within a stream follows
258
+ * HTTP/2 frame ordering.
259
+ */
260
+ maxConcurrentStreams?: number
261
+ /** Enable HTTP/2 keepalive */
262
+ enableKeepalive?: boolean
263
+ /** HTTP/2 keepalive interval in seconds */
264
+ keepaliveInterval?: number
265
+ /** HTTP/2 keepalive timeout in seconds */
266
+ keepaliveTimeout?: number
267
+ /**
268
+ * Total byte cap across an entire streaming response.
269
+ *
270
+ * When `Some(n)`, the streaming adapter aborts the stream with
271
+ * `tonic::Status::resource_exhausted` once the cumulative encoded message
272
+ * bytes exceed `n`. The stream yields the error item and then terminates.
273
+ *
274
+ * Per-message cap remains `max_message_size`. This limit applies to
275
+ * server-streaming and bidirectional-streaming RPCs only; unary RPCs are
276
+ * governed solely by `max_message_size`.
277
+ *
278
+ * Default: `None` (unbounded total response size).
279
+ */
280
+ maxStreamResponseBytes?: number
281
+ }
282
+
283
+ export declare function grpcConfigDefault(): GrpcConfig
284
+
285
+ /** JSON-RPC server configuration */
286
+ export interface JsonRpcConfig {
287
+ /** Enable JSON-RPC endpoint */
288
+ enabled?: boolean
289
+ /** HTTP endpoint path for JSON-RPC requests (default: "/rpc") */
290
+ endpointPath?: string
291
+ /** Enable batch request processing (default: true) */
292
+ enableBatch?: boolean
293
+ /** Maximum number of requests in a batch (default: 100) */
294
+ maxBatchSize?: number
295
+ }
296
+
297
+ export declare function jsonRpcConfigDefault(): JsonRpcConfig
177
298
 
178
299
  /**
179
- * Bidirectional streaming request: request with collected input messages
300
+ * JSON-RPC method metadata for routes that support JSON-RPC
180
301
  *
181
- * Used when calling JavaScript bidirectional streaming handlers.
182
- * The handler receives all input messages and returns an array of response messages.
302
+ * This struct captures the metadata needed to expose HTTP routes as JSON-RPC methods,
303
+ * enabling discovery and documentation of RPC-compatible endpoints.
304
+ *
305
+ * # Examples
183
306
  */
184
- export interface GrpcBidiStreamRequest {
185
- /** Fully qualified service name (e.g., "mypackage.UserService") */
186
- serviceName: string
187
- /** Method name (e.g., "GetUser") */
307
+ export interface JsonRpcMethodInfo {
308
+ /** The JSON-RPC method name (e.g., "user.create") */
188
309
  methodName: string
189
- /** gRPC metadata as key-value pairs */
190
- metadata: Record<string, string>
191
- /** Collected stream messages as Buffers */
192
- messages: Buffer[]
310
+ /** Optional description of what the method does */
311
+ description?: string
312
+ /** Optional JSON Schema for method parameters */
313
+ paramsSchema?: any
314
+ /** Optional JSON Schema for the result */
315
+ resultSchema?: any
316
+ /** Whether this method is deprecated */
317
+ deprecated: boolean
318
+ /** Tags for categorizing and grouping methods */
319
+ tags: Array<string>
193
320
  }
194
321
 
195
- /**
196
- * Bidirectional streaming response: array of response messages
197
- *
198
- * Returned by JavaScript bidirectional streaming handlers.
199
- * Each message is converted back to a protobuf message in the response stream.
200
- */
201
- export interface GrpcBidiStreamResponse {
202
- /** Stream response messages as Buffers */
203
- messages: Buffer[]
204
- /** Optional gRPC metadata to include in response */
205
- metadata?: Record<string, string> | undefined
322
+ /** JWT authentication configuration */
323
+ export interface JwtConfig {
324
+ /** Secret key for JWT verification */
325
+ secret: string
326
+ /** Required algorithm (HS256, HS384, HS512, RS256, etc.) */
327
+ algorithm: string
328
+ /** Required audience claim */
329
+ audience?: Array<string>
330
+ /** Required issuer claim */
331
+ issuer?: string
332
+ /** Leeway for expiration checks (seconds) */
333
+ leeway: number
334
+ }
335
+
336
+ /** License information */
337
+ export interface LicenseInfo {
338
+ /** SPDX license identifier or display name (e.g. `"MIT"`). */
339
+ name: string
340
+ /** URL to the full license text. */
341
+ url?: string
342
+ }
343
+
344
+ /** HTTP method */
345
+ export declare const enum Method {
346
+ Get = 'Get',
347
+ Post = 'Post',
348
+ Put = 'Put',
349
+ Patch = 'Patch',
350
+ Delete = 'Delete',
351
+ Head = 'Head',
352
+ Options = 'Options',
353
+ Trace = 'Trace'
354
+ }
355
+
356
+ /** OpenAPI configuration */
357
+ export interface OpenApiConfig {
358
+ /** Enable OpenAPI generation (default: false for zero overhead) */
359
+ enabled?: boolean
360
+ /** API title */
361
+ title?: string
362
+ /** API version */
363
+ version?: string
364
+ /** API description (supports markdown) */
365
+ description?: string
366
+ /** Path to serve Swagger UI (default: "/docs") */
367
+ swaggerUiPath?: string
368
+ /** Path to serve Redoc (default: "/redoc") */
369
+ redocPath?: string
370
+ /** Path to serve OpenAPI JSON spec (default: "/openapi.json") */
371
+ openapiJsonPath?: string
372
+ /** Contact information */
373
+ contact?: JsContactInfo
374
+ /** License information */
375
+ license?: JsLicenseInfo
376
+ /** Server definitions */
377
+ servers?: Array<JsServerInfo>
378
+ /** Security schemes (auto-detected from middleware if not provided) */
379
+ securitySchemes?: Record<string, JsSecuritySchemeInfo>
380
+ }
381
+
382
+ export declare function openApiConfigDefault(): OpenApiConfig
383
+
384
+ /** A single channel extracted from an AsyncAPI spec */
385
+ export interface ParsedChannel {
386
+ /** Channel key from the spec (e.g. "chat/messages") */
387
+ name: string
388
+ /** Channel address / path */
389
+ address: string
390
+ /** Message names declared on this channel */
391
+ messages: Array<string>
392
+ /** Bindings (ws / http / amqp / …) as raw JSON for forward-compatibility */
393
+ bindings?: any
394
+ }
395
+
396
+ /** A resolved message (name + JSON Schema) */
397
+ export interface ParsedMessage {
398
+ /** Message name */
399
+ name: string
400
+ /** Resolved JSON Schema for the message payload, if available */
401
+ schema?: any
402
+ }
403
+
404
+ /** A single operation extracted from an AsyncAPI spec */
405
+ export interface ParsedOperation {
406
+ /** Operation name */
407
+ name: string
408
+ /** Operation action: "send" or "receive" */
409
+ action: string
410
+ /** Channel reference (resolved to the channel name) */
411
+ channel: string
412
+ }
413
+
414
+ /** Request body for `POST /asyncapi/parse` */
415
+ export interface ParseRequest {
416
+ spec: any
417
+ }
418
+
419
+ /** Full parse result returned by `POST /asyncapi/parse` */
420
+ export interface ParseResult {
421
+ specVersion: string
422
+ title: string
423
+ apiVersion: string
424
+ channels: Array<ParsedChannel>
425
+ operations: Array<ParsedOperation>
426
+ messages: Array<ParsedMessage>
206
427
  }
207
428
 
208
429
  /**
209
- * Client streaming request: unary request with collected stream messages
430
+ * RFC 9457 Problem Details for HTTP APIs
431
+ *
432
+ * A machine-readable format for specifying errors in HTTP API responses.
433
+ * Per RFC 9457, all fields are optional. The `type` field defaults to "about:blank"
434
+ * if not specified.
210
435
  *
211
- * Used when calling JavaScript client streaming handlers.
212
- * The handler receives all collected messages in a single call.
436
+ * # Content-Type
437
+ * Responses using this struct should set:
438
+ * ```text
439
+ * Content-Type: application/problem+json
440
+ * ```
441
+ *
442
+ * ```json
443
+ * {
444
+ * "type": "https://spikard.dev/errors/validation-error",
445
+ * "title": "Request Validation Failed",
446
+ * "status": 422,
447
+ * "detail": "2 validation errors in request body",
448
+ * "errors": [...]
449
+ * }
450
+ * ```
213
451
  */
214
- export interface GrpcClientStreamRequest {
215
- /** Fully qualified service name (e.g., "mypackage.UserService") */
216
- serviceName: string
217
- /** Method name (e.g., "GetUser") */
218
- methodName: string
219
- /** gRPC metadata as key-value pairs */
220
- metadata: Record<string, string>
221
- /** Collected stream messages as Buffers */
222
- messages: Buffer[]
452
+ export interface ProblemDetails {
453
+ /**
454
+ * A URI reference that identifies the problem type.
455
+ * Defaults to "about:blank" when absent.
456
+ * Should be a stable, human-readable identifier for the problem type.
457
+ */
458
+ type: string
459
+ /**
460
+ * A short, human-readable summary of the problem type.
461
+ * Should not change from occurrence to occurrence of the problem.
462
+ */
463
+ title: string
464
+ /**
465
+ * The HTTP status code generated by the origin server.
466
+ * This is advisory; the actual HTTP status code takes precedence.
467
+ */
468
+ status: number
469
+ /** A human-readable explanation specific to this occurrence of the problem. */
470
+ detail?: string
471
+ /**
472
+ * A URI reference that identifies the specific occurrence of the problem.
473
+ * It may or may not yield further information if dereferenced.
474
+ */
475
+ instance?: string
476
+ /**
477
+ * Extension members - problem-type-specific data.
478
+ * For validation errors, this typically contains an "errors" array.
479
+ */
480
+ extensions: Record<string, any>
481
+ }
482
+
483
+ /** Create a bad request error */
484
+ export declare function problemDetailsBadRequest(detail: string): ProblemDetails
485
+
486
+ /** Create an internal server error */
487
+ export declare function problemDetailsInternalServerError(detail: string): ProblemDetails
488
+
489
+ /** Create a method not allowed error */
490
+ export declare function problemDetailsMethodNotAllowed(detail: string): ProblemDetails
491
+
492
+ /** Create a not found error */
493
+ export declare function problemDetailsNotFound(detail: string): ProblemDetails
494
+
495
+ /** Set the detail field */
496
+ export declare function problemDetailsWithDetail(cfg: ProblemDetails, detail: string): ProblemDetails
497
+
498
+ /** Set the instance field */
499
+ export declare function problemDetailsWithInstance(cfg: ProblemDetails, instance: string): ProblemDetails
500
+
501
+ /** Configuration for schemas with Query and Mutation types */
502
+ export interface QueryMutationConfig {
503
+ /** Enable introspection queries */
504
+ introspectionEnabled?: boolean
505
+ /** Maximum query complexity (None = unlimited) */
506
+ complexityLimit?: number
507
+ /** Maximum query depth (None = unlimited) */
508
+ depthLimit?: number
509
+ }
510
+
511
+ export declare function queryMutationConfigDefault(): QueryMutationConfig
512
+
513
+ /** Configuration for schemas with only Query type */
514
+ export interface QueryOnlyConfig {
515
+ /** Enable introspection queries */
516
+ introspectionEnabled?: boolean
517
+ /** Maximum query complexity (None = unlimited) */
518
+ complexityLimit?: number
519
+ /** Maximum query depth (None = unlimited) */
520
+ depthLimit?: number
521
+ }
522
+
523
+ export declare function queryOnlyConfigDefault(): QueryOnlyConfig
524
+
525
+ /** Rate limiting configuration shared across runtimes */
526
+ export interface RateLimitConfig {
527
+ /** Requests per second */
528
+ perSecond?: number
529
+ /** Burst allowance */
530
+ burst?: number
531
+ /** Use IP-based rate limiting */
532
+ ipBased?: boolean
533
+ }
534
+
535
+ export declare function rateLimitConfigDefault(): RateLimitConfig
536
+
537
+ /** HTTP Response with custom status code, headers, and content */
538
+ export interface Response {
539
+ /** Response body content */
540
+ content?: any
541
+ /** HTTP status code (defaults to 200) */
542
+ statusCode?: number
543
+ /** Response headers */
544
+ headers?: Record<string, string>
545
+ }
546
+
547
+ export declare function responseDefault(): Response
548
+
549
+ /** Snapshot of an Axum response used by higher-level language bindings. */
550
+ export interface ResponseSnapshot {
551
+ /** HTTP status code. */
552
+ status: number
553
+ /** Response headers (lowercase keys for predictable lookups). */
554
+ headers: Record<string, string>
555
+ /** Response body bytes (decoded for supported encodings). */
556
+ body: Uint8Array | Buffer | Array<number>
223
557
  }
224
558
 
225
559
  /**
226
- * gRPC request object passed to JavaScript handlers
560
+ * Configuration for GraphQL schema building.
227
561
  *
228
- * Contains the parsed components of a gRPC request with all data
229
- * converted to JavaScript-friendly types.
562
+ * Encapsulates all schema-level configuration options including
563
+ * introspection control, complexity limits, and depth limits.
230
564
  */
231
- export interface GrpcRequest {
232
- /** Fully qualified service name (e.g., "mypackage.UserService") */
233
- serviceName: string
234
- /** Method name (e.g., "GetUser") */
235
- methodName: string
236
- /** Serialized protobuf message as Buffer */
237
- payload: Buffer
238
- /** gRPC metadata as key-value pairs */
239
- metadata: Record<string, string>
565
+ export interface SchemaConfig {
566
+ /** Enable introspection queries */
567
+ introspectionEnabled?: boolean
568
+ /** Maximum query complexity (None = unlimited) */
569
+ complexityLimit?: number
570
+ /** Maximum query depth (None = unlimited) */
571
+ depthLimit?: number
240
572
  }
241
573
 
574
+ export declare function schemaConfigDefault(): SchemaConfig
575
+
242
576
  /**
243
- * gRPC response object returned by JavaScript handlers
577
+ * Create a schema configuration with all three root types.
578
+ *
579
+ * This is a convenience function for fully-featured schemas.
580
+ *
581
+ * # Returns
244
582
  *
245
- * Contains the serialized protobuf response and optional metadata
246
- * to include in the response headers.
583
+ * A `FullSchemaConfig` with default settings
247
584
  */
248
- export interface GrpcResponse {
249
- /** Serialized protobuf message as Buffer */
250
- payload: Buffer
251
- /** Optional gRPC metadata to include in response */
252
- metadata?: Record<string, string> | undefined
253
- }
585
+ export declare function schemaFull(): FullSchemaConfig
254
586
 
255
587
  /**
256
- * Server-streaming response object returned by JavaScript handlers
588
+ * Create a schema configuration with Query and Mutation types.
589
+ *
590
+ * This is a convenience function for schemas with queries and mutations but no subscriptions.
257
591
  *
258
- * Contains all serialized protobuf messages to emit in order for a
259
- * server-streaming RPC.
592
+ * # Returns
593
+ *
594
+ * A `QueryMutationConfig` with default settings
260
595
  */
261
- export interface GrpcServerStreamResponse {
262
- /** Ordered server-stream response messages as Buffers */
263
- messages: Buffer[]
264
- }
596
+ export declare function schemaQueryMutation(): QueryMutationConfig
265
597
 
266
598
  /**
267
- * Structured handler input passed to JavaScript handlers
599
+ * Create a simple schema configuration with only Query type.
268
600
  *
269
- * This struct replaces JSON string passing, eliminating serialization overhead.
270
- * Fields are converted from `RequestData` using a direct `From` impl.
601
+ * This is a convenience function for schemas that only have queries.
271
602
  *
272
- * PERFORMANCE: `object_from_js = false` skips generating FromNapiValue since
273
- * HandlerInput only flows Rust→JS, never JS→Rust. This eliminates unnecessary
274
- * code generation and potential conversion overhead.
603
+ * # Returns
604
+ *
605
+ * A `QueryOnlyConfig` with default settings
275
606
  */
276
- export interface HandlerInput {
277
- /** HTTP method (GET, POST, etc.) */
278
- method: string
279
- /** Request path */
280
- path: string
281
- /** HTTP headers as a map */
282
- headers: Record<string, string>
283
- /** HTTP cookies as a map */
284
- cookies: Record<string, string>
285
- /** Parsed query parameters */
286
- queryParams: any
287
- /** Validated parameters (query/path/header/cookie combined) */
288
- validatedParams?: any
289
- /** Parsed request body */
290
- body: any
291
- /** Extracted path parameters */
292
- pathParams: Record<string, string>
607
+ export declare function schemaQueryOnly(): QueryOnlyConfig
608
+
609
+ /** Security scheme types */
610
+ export interface SecuritySchemeInfo {
611
+ type: string
612
+ scheme?: string
613
+ bearerFormat?: string
614
+ location?: string
615
+ name?: string
616
+ }
617
+
618
+ /** Server configuration */
619
+ export interface ServerConfig {
620
+ /** Host to bind to */
621
+ host?: string
622
+ /** Port to bind to */
623
+ port?: number
624
+ /** Number of Tokio runtime worker threads used by binding-managed server runtimes */
625
+ workers?: number
626
+ /** Enable request ID generation and propagation */
627
+ enableRequestId?: boolean
628
+ /** Maximum request body size in bytes (None = unlimited, not recommended) */
629
+ maxBodySize?: number
630
+ /** Request timeout in seconds (None = no timeout) */
631
+ requestTimeout?: number
632
+ /** Enable compression middleware */
633
+ compression?: CompressionConfig
634
+ /** Enable rate limiting */
635
+ rateLimit?: RateLimitConfig
636
+ /** JWT authentication configuration */
637
+ jwtAuth?: JwtConfig
638
+ /** API Key authentication configuration */
639
+ apiKeyAuth?: ApiKeyConfig
640
+ /** Static file serving configuration */
641
+ staticFiles?: Array<StaticFilesConfig>
642
+ /** Enable graceful shutdown on SIGTERM/SIGINT */
643
+ gracefulShutdown?: boolean
644
+ /** Graceful shutdown timeout (seconds) */
645
+ shutdownTimeout?: number
646
+ /** AsyncAPI HTTP endpoint configuration */
647
+ asyncapi?: AsyncApiConfig
648
+ /** OpenAPI documentation configuration */
649
+ openapi?: OpenApiConfig
650
+ /** JSON-RPC configuration */
651
+ jsonrpc?: JsonRpcConfig
652
+ /** gRPC configuration */
653
+ grpc?: GrpcConfig
654
+ /** Background task executor configuration */
655
+ backgroundTasks?: BackgroundTaskConfig
656
+ /** Enable per-request HTTP tracing (tower-http `TraceLayer`) */
657
+ enableHttpTrace?: boolean
658
+ }
659
+
660
+ export declare function serverConfigDefault(): ServerConfig
661
+
662
+ /** Server information */
663
+ export interface ServerInfo {
664
+ /** Base URL of the server (e.g. `"https://api.example.com/v1"`). */
665
+ url: string
666
+ /** Optional human-readable description of the server environment. */
667
+ description?: string
668
+ }
669
+
670
+ /** Possible errors while converting an Axum response into a snapshot. */
671
+ export declare const enum SnapshotError {
672
+ /** Response header could not be decoded to UTF-8. */
673
+ InvalidHeader = 'InvalidHeader',
674
+ /** Body decompression failed. */
675
+ Decompression = 'Decompression'
293
676
  }
294
677
 
295
678
  /**
296
- * Structured handler output returned from JavaScript handlers
679
+ * An individual SSE event
680
+ *
681
+ * Represents a single Server-Sent Event to be sent to a connected client.
682
+ * Events can have an optional type, ID, and retry timeout for advanced scenarios.
297
683
  *
298
- * This struct is returned directly from handlers without JSON serialization,
299
- * completing the zero-copy request/response pattern.
684
+ * # Fields
685
+ *
686
+ * * `event_type` - Optional event type string (used for client-side event filtering)
687
+ * * `data` - JSON data payload to send to the client
688
+ * * `id` - Optional event ID (clients can use this to resume after disconnect)
689
+ * * `retry` - Optional retry timeout in milliseconds (tells client when to reconnect)
690
+ *
691
+ * # SSE Format
692
+ *
693
+ * Events are serialized to the following text format:
694
+ * ```text
695
+ * event: event_type
696
+ * data: {"json":"value"}
697
+ * id: event-123
698
+ * retry: 3000
699
+ * ```
300
700
  */
301
- export interface HandlerOutput {
302
- /** HTTP status code (e.g., 200, 404, 500) */
303
- status: number
304
- /** Response headers as a map */
305
- headers?: Record<string, string>
306
- /** Response body as JSON value (used when `raw_body` is not set) */
307
- body?: any
308
- /**
309
- * Pre-serialized response body bytes. When set, this is used directly as
310
- * the response body, bypassing `serde_json::to_vec` on the `body` field.
311
- * JS handlers can pass `Buffer.from(JSON.stringify(obj))` here to avoid
312
- * a napi Value → serde_json::Value → bytes round-trip.
313
- */
314
- rawBody?: Buffer
701
+ export interface SseEvent {
702
+ /** Event type (optional) */
703
+ eventType?: string
704
+ /** Event data (JSON value) */
705
+ data: any
706
+ /** Event ID (optional, for client-side reconnection) */
707
+ id?: string
708
+ /** Retry timeout in milliseconds (optional) */
709
+ retry?: number
315
710
  }
316
711
 
317
712
  /**
318
- * Start the Spikard HTTP server from Node.js
713
+ * Set the event ID for client-side reconnection support
319
714
  *
320
- * Creates an Axum HTTP server in a dedicated background thread with its own Tokio runtime.
321
- * This ensures the Node.js event loop remains free to process ThreadsafeFunction calls.
715
+ * Sets an ID that clients can use to resume from this point if they disconnect.
716
+ * The client sends this ID back in the `Last-Event-ID` header when reconnecting.
322
717
  *
323
718
  * # Arguments
719
+ * * `id` - Unique identifier for this event
324
720
  *
325
- * * `app` - Application object containing routes and handler functions
326
- * * `config` - Optional ServerConfig with all middleware settings
327
- *
328
- * # Returns
329
- *
330
- * Returns `Ok(())` after the server thread is spawned. Note that this function
331
- * returns immediately - the server runs in the background.
721
+ * # Example
722
+ */
723
+ export declare function sseEventWithId(cfg: SseEvent, id: string): SseEvent
724
+
725
+ /**
726
+ * Set the retry timeout for client reconnection
332
727
  *
333
- * # Errors
728
+ * Sets the time in milliseconds clients should wait before attempting to reconnect
729
+ * if the connection is lost. The client browser will automatically handle reconnection.
334
730
  *
335
- * Returns an error if:
336
- * - Route metadata is invalid or missing required fields
337
- * - Handler functions cannot be converted to ThreadsafeFunctions
338
- * - Socket address is invalid
339
- * - Route creation fails
731
+ * # Arguments
732
+ * * `retry_ms` - Retry timeout in milliseconds
340
733
  *
341
734
  * # Example
342
- *
343
- * ```typescript
344
- * import { Spikard, ServerConfig } from 'spikard';
345
- *
346
- * const config: ServerConfig = {
347
- * host: '0.0.0.0',
348
- * port: 8000,
349
- * compression: { quality: 9 },
350
- * openapi: {
351
- * enabled: true,
352
- * title: 'My API',
353
- * version: '1.0.0'
354
- * }
355
- * };
356
- *
357
- * const app = new Spikard();
358
- * app.run(config);
359
- * ```
360
735
  */
361
- export declare function runServer(app: object, config?: object | undefined | null): void
736
+ export declare function sseEventWithRetry(cfg: SseEvent, retryMs: number): SseEvent
737
+
738
+ /** Static file serving configuration */
739
+ export interface StaticFilesConfig {
740
+ /** Directory path to serve */
741
+ directory: string
742
+ /** URL path prefix (e.g., "/static") */
743
+ routePrefix: string
744
+ /** Fallback to index.html for directories */
745
+ indexFile: boolean
746
+ /** Cache-Control header value */
747
+ cacheControl?: string
748
+ }
749
+
750
+ /** A single Server-Sent Event. */
751
+ export interface TestingSseEvent {
752
+ /** The data field of the event. */
753
+ data: string
754
+ }
362
755
 
363
756
  /**
364
- * Optional configuration for a streaming response.
757
+ * Represents an uploaded file from multipart/form-data requests.
365
758
  *
366
- * This struct is exposed to JavaScript via napi and provides configuration
367
- * options when creating streaming responses from async iterators.
759
+ * This struct provides efficient access to file content with automatic
760
+ * base64 decoding and implements standard I/O traits for compatibility.
368
761
  *
369
- * NOTE: Marked with #[allow(dead_code)] because the #[napi(object)] macro
370
- * generates access patterns that aren't visible to the Rust dead code checker,
371
- * though the struct is actually exposed to and used by JavaScript code.
762
+ * # Example
372
763
  */
373
- export interface StreamingResponseInit {
374
- /** HTTP status code for the streaming response (default 200). */
375
- statusCode?: number
376
- /** Headers to attach to the streaming response. */
377
- headers?: Record<string, string>
764
+ export interface UploadFile {
765
+ /** Original filename from the client */
766
+ filename: string
767
+ /** MIME type of the uploaded file */
768
+ contentType?: string
769
+ /** Size of the file in bytes */
770
+ size?: number
771
+ /** File content (may be base64 encoded) */
772
+ content: Uint8Array | Buffer | Array<number>
773
+ /** Content encoding type */
774
+ contentEncoding?: string
775
+ }
776
+
777
+ /** Request body for `POST /asyncapi/validate` */
778
+ export interface ValidateRequest {
779
+ spec: any
780
+ channel: string
781
+ message: string
782
+ payload: any
783
+ }
784
+
785
+ /** Response body for `POST /asyncapi/validate` */
786
+ export interface ValidationResponse {
787
+ valid: boolean
788
+ errors: Array<string>
789
+ }
790
+
791
+ /** A WebSocket message that can be text or binary. */
792
+ export declare const enum WebSocketMessage {
793
+ /** A text message. */
794
+ Text = 'Text',
795
+ /** A binary message. */
796
+ Binary = 'Binary',
797
+ /**
798
+ * A close message with a numeric close code (RFC 6455) and optional reason text.
799
+ *
800
+ * Common codes: 1000 Normal Closure, 1001 Going Away, 1005 No Status Received,
801
+ * 1006 Abnormal Closure.
802
+ */
803
+ Close = 'Close',
804
+ /** A ping message. */
805
+ Ping = 'Ping',
806
+ /** A pong message. */
807
+ Pong = 'Pong'
378
808
  }