Repository navigation
Expand file tree
/
Copy pathindex.d.ts
More file actions
709 lines (637 loc) · 24 KB
/
Copy pathindex.d.ts
File metadata and controls
709 lines (637 loc) · 24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
// Type definitions for api-ape
// Project: https://github.com/codemeasandwich/api-ape
import { Server as HttpServer } from 'http'
import { IncomingMessage } from 'http'
/**
* WebSocket instance type (compatible with ws library and native implementations)
*/
export interface ApeWebSocket {
send(data: string | Buffer): void
close(code?: number, reason?: string): void
on(event: 'message', handler: (data: Buffer) => void): this
on(event: 'close', handler: () => void): this
on(event: 'error', handler: (err: Error) => void): this
readonly readyState: number
readonly CONNECTING: 0
readonly OPEN: 1
readonly CLOSING: 2
readonly CLOSED: 3
}
// =============================================================================
// SERVER TYPES
// =============================================================================
/**
* Controller context available as `this` inside controller functions
*/
export interface ControllerContext {
/** Publish to channel subscribers */
publish(channel: string, data: any): void
/** Forget a channel's retained last message (the next subscriber gets nothing) */
clearLastMessage(channel: string): void
/** Push `type` to every connected client */
broadcast(type: string, data: any): void
/** Push `type` to every connected client except the caller */
broadcastOthers(type: string, data: any): void
/** Push `type` to the calling client only */
send(type: string, data: any): void
/**
* Restart the caller's 10 s timer during slow work. The call is not resolved.
* Per call: concurrent calls each keepalive on their own queryId.
*/
keepalive(): void
/** Read-only Map of connected clients (`clients.size` is the online count) */
clients: ReadonlyMap<string, ClientWrapper>
/** Auth state: always false / 0 / null (the auth options are not wired, see server/README.md) */
isAuthenticated: boolean
authTier: number
principal: any
/** Unique ID of the calling client (generated by api-ape) */
clientId: string
/** Session ID from cookie (set by outer framework, may be null) */
sessionId: string | null
/** Original HTTP request */
req: IncomingMessage
/** WebSocket instance */
socket: ApeWebSocket
/** Parsed user-agent info */
agent: {
browser: { name?: string; version?: string }
os: { name?: string; version?: string }
device: { type?: string; vendor?: string; model?: string }
}
/** Custom embedded values from onConnect */
[key: string]: any
}
/**
* Controller function type
*/
export type ControllerFunction<T = any, R = any> = (
this: ControllerContext,
data: T
) => R | Promise<R>
/**
* Send function provided to onConnect
*/
export type SendFunction = {
(type: string, data: any): void
toString(): string
}
/**
* After hook returned from onReceive/onSend
*/
export type AfterHook = (err: Error | null, result: any) => void
/**
* Connection lifecycle hooks returned from onConnect
*/
export interface ConnectionHandlers {
/** Values to embed into controller context */
embed?: Record<string, any>
/** Called before processing incoming message, return after hook */
onReceive?: (queryId: string, data: any, type: string) => AfterHook | void
/** Called before sending message, return after hook */
onSend?: (data: any, type: string) => AfterHook | void
/** Called on error */
onError?: (errorString: string) => void
/** Called when client disconnects */
onDisconnect?: () => void
}
/**
* onConnect callback signature
*/
export type OnConnectCallback = (
socket: ApeWebSocket,
req: IncomingMessage,
send: SendFunction
) => ConnectionHandlers | void
/**
* Optional sinks for api-ape internal diagnostics (merge with `console` for omitted levels).
*/
export interface ApeLoggingHandlers {
log?: (...args: any[]) => void
warn?: (...args: any[]) => void
error?: (...args: any[]) => void
info?: (...args: any[]) => void
debug?: (...args: any[]) => void
}
/**
* `false` silences framework logs; `true` uses `console`; an object overrides per level.
*/
export type ApeLoggingOption = boolean | ApeLoggingHandlers
/**
* Set the process-wide / tab-wide api-ape log sink (browser or Node client).
*/
export declare function configureApeLogging(logging: ApeLoggingOption): void
/**
* WebSocket Origin policy. See server/README.md "Origin check".
*/
export interface ApeOriginPolicy {
/**
* `root-domain` compares root domains and ignores ports (Node default).
* `exact` compares scheme-normalised host and port (Bun default).
*/
mode?: 'root-domain' | 'exact'
/** Extra exact origins to admit, e.g. `['http://localhost:5173']` */
allowedOrigins?: string[]
/** When non-empty, refuse any request whose Host is not listed (DNS-rebinding guard) */
allowedHosts?: string[]
}
/**
* Opt-in controller hot reload. `true` watches the controller directory;
* the object form also evicts and watches the listed service directories.
*/
export type ApeWatchOption = boolean | {
/** Extra directories whose modules are reloaded together with the controllers */
paths?: string[]
/** Quiet period before a reload, in ms (default 50) */
debounceMs?: number
/** `false` forces one watcher per directory instead of one recursive watcher (default: by platform) */
recursive?: boolean
}
/**
* A map from endpoint path to controller, for the `controllers` option.
* A value is the function, or a module namespace whose `default` is the function.
*/
export type ApeControllerMap = {
[path: string]: ControllerFunction | { default: ControllerFunction }
}
/**
* What `onSubscribe` is told about the connection that asks to subscribe.
*/
export interface ApeSubscribeContext {
/** The connection's client id (what controllers see as `this.clientId`) */
clientId: string
/**
* The session id from the `sessionId` cookie / `x-ape-session-id` header, or null (what
* controllers see as `this.sessionId`). The CLIENT supplies it, so it can be forged:
* authorise on `embed`, which `onConnect` sets after it has really authenticated.
*/
sessionId: string | null
/** What `onConnect` returned as `embed` (`{}` when it returned none) */
embed: Record<string, any>
}
/**
* Subscribe authorisation. Return exactly `true` (or a Promise of `true`) to allow the
* subscription; anything else, a throw or a rejection refuses it (fail closed).
*/
export type OnSubscribeCallback = (
channel: string,
context: ApeSubscribeContext
) => boolean | Promise<boolean>
/**
* Options shared by both ways of providing controllers
*/
export interface ApeServerOptionsBase {
/**
* Public URL segment for the api-ape routes (`/${urlPrefix}/ape`). Defaults to `where`
* (relative) or its basename (absolute). The browser client dials `/api/ape`.
*/
urlPrefix?: string
/** Controller file extensions to load, default `['js']` (`['js', 'ts']` under Bun) */
selector?: string[]
/** Binary transfer settings (Node only) */
fileTransferOptions?: { startTimeout?: number; completeTimeout?: number }
/** HTTP long-poll fallback settings (Node only) */
longPollingOptions?: { heartbeatInterval?: number; recycleTimeout?: number }
/**
* Most bytes one inbound WebSocket message, or one long-poll POST body, may hold
* (default 16 MiB). Larger ones close the socket (1009) or get HTTP 413. Uploads are
* separate HTTP PUTs and are not limited by this.
*/
maxMessageBytes?: number
/**
* How far ahead of the server's clock (ms) a call's `createdAt` may be before the call is
* refused (default 5000). Calls older than 10 s are still refused, and a repeated call is
* still a replay. The bundled clients read the server's time from the `__connected__`
* frame (`serverTime`) and stamp calls in the server's clock.
*/
maxClockSkewMs?: number
/** Connection lifecycle hook */
onConnect?: OnConnectCallback
/**
* Decide who may subscribe to a channel. Asked before a subscription is recorded and
* before the channel's retained message is sent. A refused client gets a
* `__subscribe_refused__` error frame (its `api.channel(callback, onError)` calls
* `onError`). Absent: every client may subscribe to any channel (as before 4.5.0).
* WebSocket only: the HTTP streaming path cannot subscribe.
*/
onSubscribe?: OnSubscribeCallback
/** Origin policy for WebSocket upgrades (default: `root-domain` on Node, `exact` on Bun) */
origin?: ApeOriginPolicy
/** Hot-reload controllers on change. Off by default. */
watch?: ApeWatchOption
/** Bun only: Bun.serve websocket tuning (idleTimeout, sendPings, maxPayloadLength, ...) */
websocketOptions?: {
idleTimeout?: number
sendPings?: boolean
maxPayloadLength?: number
backpressureLimit?: number
closeOnBackpressureLimit?: boolean
perMessageDeflate?: boolean | object
publishToSelf?: boolean
}
/**
* Internal framework logging: `false` silences api-ape diagnostics; omit or `true` keeps `console`.
*/
logging?: ApeLoggingOption
/**
* Not supported. `ape()` and `apeBun()` throw if these are passed (4.3.0 accepted and
* ignored them, leaving endpoints unauthenticated). Authenticate in `onConnect`.
*/
authFramework?: never
authMiddleware?: never
}
/**
* Server options for `ape()` and `apeBun()`: controllers come from a folder (`where`) or
* from a map (`controllers`), never both. `watch` and `selector` concern a folder only.
*/
export type ApeServerOptions = ApeServerOptionsBase &
(
| {
/** Directory containing controller files (scanned at start-up; hot reload with `watch`) */
where: string
controllers?: never
}
| {
/**
* Endpoint path to controller, for a `bun build --compile` executable (no folder
* to scan): `{ 'cards/move': move }`. Same naming rules as files: `index` maps
* to the parent; a `_private` segment, a bare `index` or a `.test` name is
* refused. Public URL prefix defaults to `api`. See server/README.md.
*/
controllers: ApeControllerMap
where?: never
/** Not applicable to a map; ignored with a warning */
watch?: never
/** Not applicable to a map; ignored with a warning */
selector?: never
}
)
/**
* What `apeBun()` returns, for `Bun.serve({ fetch, websocket })`.
*/
export interface ApeBunHandlers {
/** Answers the api-ape paths; returns null for anything else so your routes can follow */
fetch(req: Request, server: any): Response | null | undefined
/** Pass as `Bun.serve({ websocket })` */
websocket: Record<string, any>
/** The WebSocket server adapter */
wss: any
/** Stop the hot-reload watcher started by `watch` (no-op when off) */
close(): void
}
// =============================================================================
// 🌲 FOREST - DISTRIBUTED MESH TYPES
// =============================================================================
/**
* Supported database client types for Forest adapters
*/
export type ForestDatabaseClient =
| RedisClient
| MongoClient
| PostgresPool
| SupabaseClient
| FirebaseDatabase
| ForestCustomAdapter
/** Redis client (node-redis or ioredis) */
export interface RedisClient {
duplicate(): RedisClient
publish(channel: string, message: string): Promise<number>
subscribe(channel: string): Promise<void>
on(event: string, handler: (...args: any[]) => void): void
}
/** MongoDB client */
export interface MongoClient {
db(name?: string): any
}
/** PostgreSQL pool (pg) */
export interface PostgresPool {
query(text: string, values?: any[]): Promise<any>
connect(): Promise<any>
}
/** Supabase client */
export interface SupabaseClient {
from(table: string): any
channel(name: string): any
removeChannel(channel: any): Promise<void>
}
/** Firebase Realtime Database */
export interface FirebaseDatabase {
ref(path: string): any
goOnline?(): void
app?: any
}
/**
* Forest adapter instance interface
*/
export interface ForestAdapterInstance {
/** This server's unique ID */
readonly serverId: string
/** Join the distributed mesh */
join(serverId?: string): Promise<void>
/** Leave the mesh and cleanup */
leave(): Promise<void>
/** Client-to-server lookup operations */
lookup: {
/** Register a client on this server */
add(clientId: string): Promise<void>
/** Find which server owns a client */
read(clientId: string): Promise<string | null>
/** Remove a client mapping (must own it) */
remove(clientId: string): Promise<void>
}
/** Inter-server channel operations */
channels: {
/** Push message to a server's channel (empty string = broadcast) */
push(serverId: string, message: any): Promise<void>
/** Subscribe to a server's channel, returns unsubscribe function */
pull(serverId: string, handler: (message: any, senderServerId: string) => void): Promise<() => Promise<void>>
}
}
/**
* Custom adapter interface for implementing your own Forest adapter
*/
export interface ForestCustomAdapter {
join(serverId: string): Promise<void>
leave(): Promise<void>
lookup: {
add(clientId: string): Promise<void>
read(clientId: string): Promise<string | null>
remove(clientId: string): Promise<void>
}
channels: {
push(serverId: string, message: any): Promise<void>
pull(serverId: string, handler: (message: any, senderServerId: string) => void): Promise<() => Promise<void>>
}
}
/**
* Options for joinVia()
*/
export interface ForestOptions {
/** Prefix for keys/tables (default: 'apes') */
namespace?: string
/** Custom server ID (default: auto-generated) */
serverId?: string
}
/**
* Initialize api-ape on a Node.js HTTP/HTTPS server
*
* V3 Breaking Change:
* Old: const ape = require('api-ape')
* New: const { ape } = require('api-ape')
*/
declare function ape(server: HttpServer, options: ApeServerOptions): void
declare namespace ape {
/**
* Publish to channel subscribers
* Supports chained syntax: ape.publish.channel.name(data)
* Or direct call: ape.publish('/channel', data)
*/
export const publish: {
(channel: string, data: any): void
[key: string]: any
}
/**
* Forget a channel's retained last message so the next subscriber is sent nothing.
* Current subscribers are unaffected; the next publish is retained again.
* (A function of its own: `ape.publish.clearLastMessage` would be a channel.)
*/
export function clearLastMessage(channel: string): void
/**
* Read-only Map of connected clients
* Each ClientWrapper provides: clientId, sessionId (Phase 1 pairing scope — often minted server-side), embed, agent, send(type, data)
*/
export const clients: ReadonlyMap<string, ClientWrapper>
// =========================================================================
// 🌲 FOREST - DISTRIBUTED MESH
// =========================================================================
/**
* Join the distributed mesh for multi-server coordination.
* Pass any supported database client - APE auto-detects the type.
*
* @example
* // Redis
* ape.joinVia(redisClient);
*
* // With options
* ape.joinVia(mongoClient, { namespace: 'myapp', serverId: 'srv-1' });
*
* // Custom adapter
* ape.joinVia({ join, leave, lookup, channels });
*/
export function joinVia(client: ForestDatabaseClient, options?: ForestOptions): Promise<ForestAdapterInstance>
/**
* Leave the distributed mesh gracefully.
* Removes all client mappings and unsubscribes from channels.
*/
export function leaveCluster(): Promise<void>
/**
* Current Forest adapter instance (null if not joined)
*/
export const cluster: ForestAdapterInstance | null
/**
* This server's ID in the cluster (null if not joined)
*/
export const serverId: string | null
// Browser client methods (available when imported in browser context)
/** Subscribe to broadcasts from the server */
export function on<T = any>(type: string, handler: (message: { err?: Error; type: string; data: T }) => void): void
/** Subscribe to connection state changes. Returns unsubscribe function. */
export function onConnectionChange(handler: (state: 'offline' | 'walled' | 'disconnected' | 'connecting' | 'connected') => void): () => void
/** Current transport type (read-only) */
export const transport: 'websocket' | 'polling' | null
/** Call any server function dynamically (browser only) */
export function message<T = any, R = any>(data?: T): Promise<R>
}
// =============================================================================
// SERVER-SIDE CLIENT (api - same interface as browser)
// =============================================================================
/**
* Server-side client for connecting to other api-ape servers
* 100% identical interface to the browser client
*
* @example
* import api from 'api-ape'
*
* // Configure connection (or set APE_SERVER env)
* api.connect('other-server', 3000) // → ws://other-server:3000/api/ape
*
* // Same usage as browser
* const result = await api.hello('World')
* api.on('message', (data) => console.log(data))
*/
export interface ApeServerClient extends ApeSender {
/** Subscribe to broadcasts from the remote server */
on<T = any>(type: string, handler: MessageHandler<T>): void
on(handler: MessageHandler): void
/** Subscribe to connection state changes */
onConnectionChange(handler: (state: ConnectionState) => void): () => void
/** Configure internal api-ape logging for this Node client */
configureLogging(logging: ApeLoggingOption): void
/** Connect to a server using host and port */
connect(host: string, port: number, options?: { logging?: ApeLoggingOption }): void
/** Close the connection */
close(): void
/** Current transport type (read-only) */
readonly transport: 'websocket' | null
}
/**
* The api client - works identically on browser and server
*/
declare const api: ApeServerClient
// Named export for V3 (Server usage: const { ape } = require('api-ape'))
export { ape, api }
// Default export: api client (same interface on browser and server)
export default api
// =============================================================================
// BROWSER CLIENT (Default export in browser context)
// =============================================================================
/**
* Unified browser client - auto-initializing Proxy that buffers calls until ready.
*
* In browser context (via bundler or direct import), `import api from 'api-ape'`
* returns this client instead of the server function.
*
* Usage:
* import api from 'api-ape'
* api.message({ text: 'Hello!' }) // Buffered until connected
* api.on('message', (data) => {}) // Listen for broadcasts
* api.onConnectionChange((state) => {}) // Connection state updates
*/
export interface ApeBrowserClient extends ApeSender {
/** Subscribe to broadcasts from the server */
on<T = any>(type: string, handler: MessageHandler<T>): void
/** Subscribe to connection state changes. Returns unsubscribe function. */
onConnectionChange(handler: (state: ConnectionState) => void): () => void
/** Configure internal api-ape logging (prefer calling before first RPC) */
configureLogging(logging: ApeLoggingOption): void
/** Current transport type (read-only) */
readonly transport: TransportType | null
}
// =============================================================================
// CLIENT TYPES
// =============================================================================
/**
* Connection state enum values
*/
export type ConnectionState = 'offline' | 'walled' | 'disconnected' | 'connecting' | 'connected' | 'closing'
/**
* Connection state enum object
*/
export declare const ConnectionState: {
Offline: 'offline'
Walled: 'walled'
Disconnected: 'disconnected'
Connecting: 'connecting'
Connected: 'connected'
Closing: 'closing'
}
/**
* Message received from server
*/
export interface ReceivedMessage<T = any> {
err?: Error | string
type: string
data: T
}
/**
* Message handler callback
*/
export type MessageHandler<T = any> = (message: ReceivedMessage<T>) => void
/**
* Proxy-based sender - any property access creates a callable path
* Example: sender.users.list() calls type="/users/list"
*/
export interface ApeSender {
[key: string]: ApeSender &
// Subscribe: a function argument. `onError` runs if the server refuses the
// subscription (its `onSubscribe`): `err.code === 'SUBSCRIBE_REFUSED'`, `err.data.channel`.
((callback: (data: any) => void, onError?: (err: Error & { code?: string; data?: any }) => void) => () => void) &
// Call: any other argument
(<T = any, R = any>(data?: T) => Promise<R>)
}
/**
* Set receiver for specific message type or all messages
*/
export type SetOnReceiver = {
(type: string, handler: MessageHandler): void
(handler: MessageHandler): void
}
/**
* Connected client interface
*/
export interface ApeClient {
sender: ApeSender
setOnReceiver: SetOnReceiver
/** Subscribe to connection state changes. Returns unsubscribe function. */
onConnectionChange: (handler: (state: ConnectionState) => void) => () => void
/** Current transport type (read-only) */
readonly transport: TransportType | null
}
/**
* Transport type for connection
*/
export type TransportType = 'websocket' | 'polling'
/**
* Connect socket function with configuration methods
*/
export interface ConnectSocket {
(options?: { logging?: ApeLoggingOption }): ApeClient
/** Enable auto-reconnection on disconnect */
autoReconnect(): void
/** Connection state enum */
ConnectionState: typeof ConnectionState
/** Same as {@link configureApeLogging} */
configureLogging(logging: ApeLoggingOption): void
}
/**
* Client module default export
*/
declare const connectSocket: ConnectSocket
export { connectSocket }
// =============================================================================
// CLIENTS MODULE
// =============================================================================
export declare const clients: ReadonlyMap<string, ClientWrapper>
/**
* Forget a channel's retained last message (same as `ape.clearLastMessage`)
*/
export declare function clearLastMessage(channel: string): void
/**
* Chainable send function for client.send
* Supports both direct and chained syntax:
* - client.send('news/banking', data)
* - client.send.news.banking(data)
*/
export interface ClientSendFunction {
/** Direct call: send(type, data) */
(type: string, data: any): void
/** Chained access for path building */
[key: string]: ClientSendFunction & ((data?: any) => void)
}
/**
* Client wrapper providing client info and send function
*/
export interface ClientWrapper {
/** Unique client identifier */
readonly clientId: string
/**
* Parent session scope for Phase 1 `(sessionId, clientId)` pairing.
* From cookie/header when provided; WebSocket and LP handlers otherwise mint an id and echo it in `__connected__` — often non-null even without app-set cookies.
*/
readonly sessionId: string | null
/** Embedded values from onConnect */
readonly embed: Record<string, any>
/** Parsed user-agent info */
readonly agent: {
browser: { name?: string; version?: string }
os: { name?: string; version?: string }
device: { type?: string; vendor?: string; model?: string }
}
/**
* Send a message to this specific client
* Supports both direct and chained syntax:
* - client.send('news/banking', data)
* - client.send.news.banking(data)
*/
send: ClientSendFunction
}