rivetkit 0.0.0-pr.4701.ff93012 → 0.0.0-pr.4702.d108c6a

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 (80) hide show
  1. package/dist/browser/client.d.ts +1265 -1249
  2. package/dist/browser/client.js +49 -4
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/tsup/agent-os/index.cjs.map +1 -1
  5. package/dist/tsup/agent-os/index.d.cts +948 -99
  6. package/dist/tsup/agent-os/index.d.ts +948 -99
  7. package/dist/tsup/agent-os/index.js.map +1 -1
  8. package/dist/tsup/chunk-2NDZ7JCR.cjs +70 -0
  9. package/dist/tsup/chunk-2NDZ7JCR.cjs.map +1 -0
  10. package/dist/tsup/{chunk-62AHO6WC.cjs → chunk-AEW4SZ55.cjs} +4 -4
  11. package/dist/tsup/chunk-AEW4SZ55.cjs.map +1 -0
  12. package/dist/tsup/{chunk-ZNUG56LA.cjs → chunk-D4ZZ76AG.cjs} +310 -285
  13. package/dist/tsup/chunk-D4ZZ76AG.cjs.map +1 -0
  14. package/dist/tsup/{chunk-LAI5BDJE.cjs → chunk-D5XMQ2SX.cjs} +24 -4
  15. package/dist/tsup/chunk-D5XMQ2SX.cjs.map +1 -0
  16. package/dist/tsup/{chunk-P34PD3YC.js → chunk-KSLTRFN4.js} +2 -2
  17. package/dist/tsup/chunk-PCBNKI2J.js +70 -0
  18. package/dist/tsup/chunk-PCBNKI2J.js.map +1 -0
  19. package/dist/tsup/{chunk-KHGQOO7K.js → chunk-T3TVXCFT.js} +257 -232
  20. package/dist/tsup/chunk-T3TVXCFT.js.map +1 -0
  21. package/dist/tsup/{chunk-V5TKDR7T.cjs → chunk-TJTWPXJO.cjs} +3 -3
  22. package/dist/tsup/{chunk-V5TKDR7T.cjs.map → chunk-TJTWPXJO.cjs.map} +1 -1
  23. package/dist/tsup/{chunk-JG2DVWPX.js → chunk-TRTGGEVI.js} +24 -4
  24. package/dist/tsup/chunk-TRTGGEVI.js.map +1 -0
  25. package/dist/tsup/{chunk-TDPKDZIH.js → chunk-VXVC6BLC.js} +2 -2
  26. package/dist/tsup/chunk-VXVC6BLC.js.map +1 -0
  27. package/dist/tsup/client/mod.cjs +9 -9
  28. package/dist/tsup/client/mod.d.cts +4 -3
  29. package/dist/tsup/client/mod.d.ts +4 -3
  30. package/dist/tsup/client/mod.js +3 -3
  31. package/dist/tsup/common/log.cjs +2 -2
  32. package/dist/tsup/common/log.d.cts +2 -2
  33. package/dist/tsup/common/log.d.ts +2 -2
  34. package/dist/tsup/common/log.js +1 -1
  35. package/dist/tsup/common/websocket.cjs +3 -3
  36. package/dist/tsup/common/websocket.js +2 -2
  37. package/dist/tsup/{client-4UdAN2cG.d.cts → config-BXRnHP3F.d.cts} +1104 -1206
  38. package/dist/tsup/{client-Y4oSOZvn.d.ts → config-D3OQoOIz.d.ts} +1104 -1206
  39. package/dist/tsup/config-DUAq1NBZ.d.cts +120 -0
  40. package/dist/tsup/config-DUAq1NBZ.d.ts +120 -0
  41. package/dist/tsup/{context-T7mBRFd1.d.ts → context-CV8PK6wM.d.cts} +2 -1
  42. package/dist/tsup/{context-DCaX6PAI.d.cts → context-CvwJmFo9.d.ts} +2 -1
  43. package/dist/tsup/db/drizzle.cjs +264 -0
  44. package/dist/tsup/db/drizzle.cjs.map +1 -0
  45. package/dist/tsup/db/drizzle.d.cts +27 -0
  46. package/dist/tsup/db/drizzle.d.ts +27 -0
  47. package/dist/tsup/db/drizzle.js +264 -0
  48. package/dist/tsup/db/drizzle.js.map +1 -0
  49. package/dist/tsup/db/mod.cjs +182 -0
  50. package/dist/tsup/db/mod.cjs.map +1 -0
  51. package/dist/tsup/db/mod.d.cts +9 -0
  52. package/dist/tsup/db/mod.d.ts +9 -0
  53. package/dist/tsup/db/mod.js +182 -0
  54. package/dist/tsup/db/mod.js.map +1 -0
  55. package/dist/tsup/mod.cjs +65 -62
  56. package/dist/tsup/mod.cjs.map +1 -1
  57. package/dist/tsup/mod.d.cts +4 -3
  58. package/dist/tsup/mod.d.ts +4 -3
  59. package/dist/tsup/mod.js +22 -19
  60. package/dist/tsup/mod.js.map +1 -1
  61. package/dist/tsup/utils.cjs +2 -2
  62. package/dist/tsup/utils.js +1 -1
  63. package/dist/tsup/workflow/mod.cjs +12 -12
  64. package/dist/tsup/workflow/mod.d.cts +6 -5
  65. package/dist/tsup/workflow/mod.d.ts +6 -5
  66. package/dist/tsup/workflow/mod.js +2 -2
  67. package/package.json +29 -9
  68. package/src/actor/config.ts +57 -12
  69. package/src/client/actor-conn.ts +38 -9
  70. package/src/db/drizzle.ts +349 -0
  71. package/src/db/mod.ts +11 -0
  72. package/src/registry/config/index.ts +2 -1
  73. package/src/registry/native.ts +28 -11
  74. package/dist/tsup/chunk-62AHO6WC.cjs.map +0 -1
  75. package/dist/tsup/chunk-JG2DVWPX.js.map +0 -1
  76. package/dist/tsup/chunk-KHGQOO7K.js.map +0 -1
  77. package/dist/tsup/chunk-LAI5BDJE.cjs.map +0 -1
  78. package/dist/tsup/chunk-TDPKDZIH.js.map +0 -1
  79. package/dist/tsup/chunk-ZNUG56LA.cjs.map +0 -1
  80. /package/dist/tsup/{chunk-P34PD3YC.js.map → chunk-KSLTRFN4.js.map} +0 -0
@@ -1,10 +1,10 @@
1
- import { z as z$1 } from 'zod';
2
- import z$2, { z } from 'zod/v4';
1
+ import { z as z$2 } from 'zod';
2
+ import z$1, { z } from 'zod/v4';
3
3
  import { UniversalWebSocket } from '@rivetkit/virtual-websocket';
4
- import { StandardSchemaV1 } from '@standard-schema/spec';
5
- import { Logger } from 'pino';
6
4
  import { Context, Handler, Hono } from 'hono';
5
+ import { StandardSchemaV1 } from '@standard-schema/spec';
7
6
  import { ContentfulStatusCode } from 'hono/utils/http-status';
7
+ import { Logger } from 'pino';
8
8
 
9
9
  interface SqliteVfsMetrics {
10
10
  requestBuildNs: number;
@@ -125,6 +125,114 @@ type RawAccess = {
125
125
  close: () => Promise<void>;
126
126
  };
127
127
 
128
+ declare const EncodingSchema: z.ZodEnum<{
129
+ json: "json";
130
+ cbor: "cbor";
131
+ bare: "bare";
132
+ }>;
133
+ /**
134
+ * Encoding used to communicate between the client & actor.
135
+ */
136
+ type Encoding = z.infer<typeof EncodingSchema>;
137
+
138
+ declare const ActorKeySchema: z.ZodArray<z.ZodString>;
139
+ type ActorKey = z.infer<typeof ActorKeySchema>;
140
+ /**
141
+ * Crash policy for actor lifecycle management.
142
+ *
143
+ * This schema is only used by the engine driver for actor creation. The manager
144
+ * driver ignores crash policy and passes it through to the engine unchanged.
145
+ */
146
+ declare const CrashPolicySchema: z.ZodEnum<{
147
+ restart: "restart";
148
+ sleep: "sleep";
149
+ destroy: "destroy";
150
+ }>;
151
+ type CrashPolicy = z.infer<typeof CrashPolicySchema>;
152
+ declare const CreateRequestSchema: z.ZodObject<{
153
+ name: z.ZodString;
154
+ key: z.ZodArray<z.ZodString>;
155
+ input: z.ZodOptional<z.ZodUnknown>;
156
+ region: z.ZodOptional<z.ZodString>;
157
+ }, z.core.$strip>;
158
+ declare const ActorQuerySchema: z.ZodUnion<readonly [z.ZodObject<{
159
+ getForId: z.ZodObject<{
160
+ name: z.ZodString;
161
+ actorId: z.ZodString;
162
+ }, z.core.$strip>;
163
+ }, z.core.$strip>, z.ZodObject<{
164
+ getForKey: z.ZodObject<{
165
+ name: z.ZodString;
166
+ key: z.ZodArray<z.ZodString>;
167
+ }, z.core.$strip>;
168
+ }, z.core.$strip>, z.ZodObject<{
169
+ getOrCreateForKey: z.ZodObject<{
170
+ name: z.ZodString;
171
+ key: z.ZodArray<z.ZodString>;
172
+ input: z.ZodOptional<z.ZodUnknown>;
173
+ region: z.ZodOptional<z.ZodString>;
174
+ }, z.core.$strip>;
175
+ }, z.core.$strip>, z.ZodObject<{
176
+ create: z.ZodObject<{
177
+ name: z.ZodString;
178
+ key: z.ZodArray<z.ZodString>;
179
+ input: z.ZodOptional<z.ZodUnknown>;
180
+ region: z.ZodOptional<z.ZodString>;
181
+ }, z.core.$strip>;
182
+ }, z.core.$strip>]>;
183
+ type ActorQuery = z.infer<typeof ActorQuerySchema>;
184
+ /**
185
+ * Interface representing a request to create a actor.
186
+ */
187
+ type CreateRequest = z.infer<typeof CreateRequestSchema>;
188
+
189
+ interface DeconstructedError {
190
+ __type: "ActorError";
191
+ statusCode: ContentfulStatusCode;
192
+ public: boolean;
193
+ group: string;
194
+ code: string;
195
+ message: string;
196
+ metadata?: unknown;
197
+ }
198
+
199
+ interface RivetErrorOptions extends ErrorOptions {
200
+ /** Error data can safely be serialized in a response to the client. */
201
+ public?: boolean;
202
+ /** Metadata associated with this error. */
203
+ metadata?: unknown;
204
+ /** Explicit HTTP status override for router responses. */
205
+ statusCode?: number;
206
+ }
207
+ interface UserErrorOptions extends ErrorOptions {
208
+ /**
209
+ * Machine readable code for this error. Useful for catching different types of
210
+ * errors in try-catch.
211
+ */
212
+ code?: string;
213
+ /**
214
+ * Additional metadata related to the error. Useful for understanding context
215
+ * about the error.
216
+ */
217
+ metadata?: unknown;
218
+ }
219
+ declare class RivetError extends Error {
220
+ __type: "RivetError";
221
+ public: boolean;
222
+ metadata?: unknown;
223
+ statusCode: number;
224
+ readonly group: string;
225
+ readonly code: string;
226
+ static isRivetError(error: unknown): error is RivetError | DeconstructedError;
227
+ static isActorError(error: unknown): error is RivetError | DeconstructedError;
228
+ constructor(group: string, code: string, message: string, options?: RivetErrorOptions | unknown);
229
+ toString(): string;
230
+ }
231
+
232
+ declare class UserError extends RivetError {
233
+ constructor(message: string, options?: UserErrorOptions);
234
+ }
235
+
128
236
  type SchemaHookResult = boolean | Promise<boolean>;
129
237
  type SchemaHook<TContext = any> = (ctx: TContext) => SchemaHookResult;
130
238
  interface EventTypeToken<T, TContext = any> {
@@ -163,1386 +271,1294 @@ type InferQueueCompleteMap<T extends QueueSchemaConfig> = {
163
271
  };
164
272
  type InferEventArgs<T> = T extends readonly unknown[] ? number extends T["length"] ? [T] : T : [T];
165
273
 
166
- declare const ACTOR_CONTEXT_INTERNAL_SYMBOL: unique symbol;
167
- interface ActorLogger {
168
- level: any;
169
- fatal: any;
170
- trace: any;
171
- silent: any;
172
- msgPrefix: any;
173
- debug: any;
174
- info: any;
175
- warn: any;
176
- error: any;
177
- [key: string]: any;
274
+ type UpgradeWebSocket = (createEvents: (c: Context) => any) => Handler;
275
+ type GetUpgradeWebSocket = () => UpgradeWebSocket;
276
+
277
+ type GatewayTarget = {
278
+ directId: string;
279
+ } | ActorQuery;
280
+ interface EngineControlClient {
281
+ getForId(input: GetForIdInput): Promise<ActorOutput | undefined>;
282
+ getWithKey(input: GetWithKeyInput): Promise<ActorOutput | undefined>;
283
+ getOrCreateWithKey(input: GetOrCreateWithKeyInput): Promise<ActorOutput>;
284
+ createActor(input: CreateInput): Promise<ActorOutput>;
285
+ listActors(input: ListActorsInput): Promise<ActorOutput[]>;
286
+ sendRequest(target: GatewayTarget, actorRequest: Request): Promise<Response>;
287
+ openWebSocket(path: string, target: GatewayTarget, encoding: Encoding, params: unknown): Promise<UniversalWebSocket>;
288
+ proxyRequest(c: Context, actorRequest: Request, actorId: string): Promise<Response>;
289
+ proxyWebSocket(c: Context, path: string, actorId: string, encoding: Encoding, params: unknown): Promise<Response>;
290
+ buildGatewayUrl(target: GatewayTarget): Promise<string>;
291
+ displayInformation(): RuntimeDisplayInformation;
292
+ extraStartupLog?: () => Record<string, unknown>;
293
+ modifyRuntimeRouter?: (config: RegistryConfig, router: Hono) => void;
294
+ setGetUpgradeWebSocket(getUpgradeWebSocket: GetUpgradeWebSocket): void;
295
+ shutdown?(): void;
296
+ /**
297
+ * Test-only helper that simulates an abrupt actor crash.
298
+ */
299
+ hardCrashActor?(actorId: string): Promise<void>;
300
+ kvGet(actorId: string, key: Uint8Array): Promise<string | null>;
301
+ kvBatchGet(actorId: string, keys: Uint8Array[]): Promise<(Uint8Array | null)[]>;
302
+ kvBatchPut(actorId: string, entries: [Uint8Array, Uint8Array][]): Promise<void>;
303
+ kvBatchDelete(actorId: string, keys: Uint8Array[]): Promise<void>;
304
+ kvDeleteRange(actorId: string, start: Uint8Array, end: Uint8Array): Promise<void>;
178
305
  }
179
- interface ActorKv {
180
- get(key: Uint8Array | string): Promise<Uint8Array | null>;
181
- put(key: Uint8Array | string, value: Uint8Array | string): Promise<void>;
182
- delete(key: Uint8Array | string): Promise<void>;
183
- batchPut(entries: [Uint8Array, Uint8Array][]): Promise<void>;
184
- batchGet(keys: Uint8Array[]): Promise<(Uint8Array | null)[]>;
185
- batchDelete(keys: Uint8Array[]): Promise<void>;
186
- deleteRange(start: Uint8Array, end: Uint8Array): Promise<void>;
187
- listPrefix(prefix: Uint8Array, options?: {
188
- reverse?: boolean;
189
- limit?: number;
190
- }): Promise<[Uint8Array, Uint8Array][]>;
191
- listRange(start: Uint8Array, end: Uint8Array, options?: {
192
- reverse?: boolean;
193
- limit?: number;
194
- }): Promise<[Uint8Array, Uint8Array][]>;
195
- [key: string]: any;
306
+ interface RuntimeDisplayInformation {
307
+ properties: Record<string, string>;
196
308
  }
197
- interface ActorSql {
198
- exec(sql: string, callback?: (row: unknown[], columns: string[]) => void): Promise<void>;
199
- run(sql: string, params?: unknown[] | Record<string, unknown>): Promise<void>;
200
- query(sql: string, params?: unknown[] | Record<string, unknown>): Promise<{
201
- columns: string[];
202
- rows: unknown[][];
203
- }>;
204
- [key: string]: any;
309
+ interface GetForIdInput {
310
+ c?: Context | undefined;
311
+ name: string;
312
+ actorId: string;
205
313
  }
206
- interface ActorSchedule {
207
- after(duration: number, action: string, ...args: unknown[]): Promise<void>;
208
- at(timestamp: number, action: string, ...args: unknown[]): Promise<void>;
209
- [key: string]: any;
314
+ interface GetWithKeyInput {
315
+ c?: Context | undefined;
316
+ name: string;
317
+ key: ActorKey;
210
318
  }
211
- type QueueMessageOf<Name extends string, Body> = {
212
- id: number | bigint;
213
- name: Name;
214
- body: Body;
215
- createdAt: number;
216
- [key: string]: unknown;
217
- };
218
- type QueueName<TQueues extends QueueSchemaConfig> = keyof TQueues & string;
219
- type QueueFilterName<TQueues extends QueueSchemaConfig> = keyof TQueues extends never ? string : QueueName<TQueues>;
220
- type QueueMessageForName<TQueues extends QueueSchemaConfig, TName extends QueueFilterName<TQueues>> = keyof TQueues extends never ? QueueMessageOf<string, unknown> : TName extends QueueName<TQueues> ? QueueMessageOf<TName, InferSchemaMap<TQueues>[TName]> : never;
221
- type QueueCompletionResultForName<TQueues extends QueueSchemaConfig, TName extends QueueFilterName<TQueues>> = keyof TQueues extends never ? unknown | undefined : TName extends QueueName<TQueues> ? InferQueueCompleteMap<TQueues>[TName] | undefined : unknown | undefined;
222
- interface QueueNextOptions<TName extends string = string, TCompletable extends boolean = boolean> {
223
- names?: readonly TName[];
224
- timeout?: number;
225
- signal?: AbortSignal;
226
- completable?: TCompletable;
319
+ interface GetOrCreateWithKeyInput {
320
+ c?: Context | undefined;
321
+ name: string;
322
+ key: ActorKey;
323
+ input?: unknown;
324
+ region?: string;
325
+ crashPolicy?: CrashPolicy;
227
326
  }
228
- interface QueueNextBatchOptions<TName extends string = string, TCompletable extends boolean = boolean> {
229
- names?: readonly TName[];
230
- count?: number;
231
- timeout?: number;
232
- signal?: AbortSignal;
233
- completable?: TCompletable;
327
+ interface CreateInput {
328
+ c?: Context | undefined;
329
+ name: string;
330
+ key: ActorKey;
331
+ input?: unknown;
332
+ region?: string;
333
+ crashPolicy?: CrashPolicy;
234
334
  }
235
- interface QueueWaitOptions<TCompletable extends boolean = boolean> {
335
+ interface ListActorsInput {
336
+ c?: Context | undefined;
337
+ name: string;
338
+ key?: string;
339
+ includeDestroyed?: boolean;
340
+ }
341
+ interface ActorOutput {
342
+ actorId: string;
343
+ name: string;
344
+ key: ActorKey;
345
+ createTs?: number;
346
+ startTs?: number | null;
347
+ connectableTs?: number | null;
348
+ sleepTs?: number | null;
349
+ destroyTs?: number | null;
350
+ error?: unknown;
351
+ }
352
+
353
+ interface QueueSendWaitOptions {
354
+ wait: true;
236
355
  timeout?: number;
237
356
  signal?: AbortSignal;
238
- completable?: TCompletable;
239
357
  }
240
- interface QueueEnqueueAndWaitOptions {
241
- timeout?: number;
358
+ interface QueueSendNoWaitOptions {
359
+ wait?: false;
360
+ timeout?: never;
242
361
  signal?: AbortSignal;
243
362
  }
244
- interface QueueTryNextOptions<TName extends string = string, TCompletable extends boolean = boolean> {
245
- names?: readonly TName[];
246
- completable?: TCompletable;
363
+ interface QueueSendResult<TResponse = unknown> {
364
+ status: "completed" | "timedOut";
365
+ response?: TResponse;
247
366
  }
248
- interface QueueTryNextBatchOptions<TName extends string = string, TCompletable extends boolean = boolean> {
249
- names?: readonly TName[];
250
- count?: number;
251
- completable?: TCompletable;
252
- }
253
- interface QueueIterOptions<TName extends string = string, TCompletable extends boolean = boolean> {
254
- names?: readonly TName[];
255
- signal?: AbortSignal;
256
- completable?: TCompletable;
257
- }
258
- interface ActorQueue<TQueues extends QueueSchemaConfig = Record<never, never>> {
259
- send<TName extends QueueFilterName<TQueues>>(name: TName, body: QueueMessageForName<TQueues, TName>["body"]): Promise<any>;
260
- next<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueNextOptions<TName, TCompletable>): Promise<any>;
261
- nextBatch<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueNextBatchOptions<TName, TCompletable>): Promise<any[]>;
262
- waitForNames<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(names: readonly TName[], opts?: QueueWaitOptions<TCompletable>): Promise<any>;
263
- enqueueAndWait<const TName extends QueueFilterName<TQueues>>(name: TName, body: QueueMessageForName<TQueues, TName>["body"], opts?: QueueEnqueueAndWaitOptions): Promise<QueueCompletionResultForName<TQueues, TName>>;
264
- tryNext<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueTryNextOptions<TName, TCompletable>): Promise<any>;
265
- tryNextBatch<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueTryNextBatchOptions<TName, TCompletable>): Promise<any[]>;
266
- iter<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueIterOptions<TName, TCompletable>): AsyncIterable<any>;
267
- [key: string]: any;
268
- }
269
- interface Conn<TState = unknown, TConnParams = unknown, TConnState = unknown, TVars = unknown, TInput = unknown, TDatabase extends AnyDatabaseProvider = AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
270
- id: string;
271
- params: TConnParams;
272
- state: TConnState;
273
- isHibernatable: boolean;
274
- send(name: string, ...args: any[]): void;
275
- disconnect(reason?: string): Promise<void>;
276
- [key: string]: any;
277
- }
278
- interface ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
279
- [ACTOR_CONTEXT_INTERNAL_SYMBOL]?: unknown;
280
- state: TState;
281
- vars: TVars;
282
- readonly kv: ActorKv;
283
- readonly sql: ActorSql;
284
- readonly db: InferDatabaseClient<TDatabase>;
285
- readonly schedule: ActorSchedule;
286
- readonly queue: ActorQueue<TQueues>;
287
- readonly actorId: string;
288
- readonly name: string;
289
- readonly key: Array<string | number>;
290
- readonly region: string;
291
- readonly conns: Map<string, Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>>;
292
- readonly log: ActorLogger;
293
- readonly abortSignal: AbortSignal;
294
- readonly aborted: boolean;
295
- readonly preventSleep: boolean;
296
- broadcast(name: string, ...args: any[]): void;
297
- saveState(opts?: {
298
- immediate?: boolean;
299
- maxWait?: number;
300
- }): Promise<void>;
301
- keepAwake<T>(promise: Promise<T>): Promise<T>;
302
- waitUntil(promise: Promise<unknown>): void;
303
- setPreventSleep(preventSleep: boolean): void;
304
- sleep(): void;
305
- destroy(): void;
306
- client<T = any>(): T;
307
- [key: string]: any;
308
- }
309
- type ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & {
310
- conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
311
- };
312
- type BeforeActionResponseContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
313
- type BeforeConnectContext<TState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, TVars, TInput, TDatabase, TEvents, TQueues>;
314
- type ConnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
315
- type CreateConnStateContext<TState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, TVars, TInput, TDatabase, TEvents, TQueues>;
316
- type CreateContext<TState, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, unknown, TInput, TDatabase, TEvents, TQueues>;
317
- type CreateVarsContext<TState, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = CreateContext<TState, TInput, TDatabase, TEvents, TQueues>;
318
- type DestroyContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
319
- type DisconnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
320
- type RequestContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
321
- type RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
322
- type SleepContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
323
- type StateChangeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
324
- type WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
325
- type MigrateContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
326
- type WebSocketContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
327
- type InspectorUnsubscribe = () => void;
328
- declare const RunConfigSchema: z.ZodObject<{
329
- name: z.ZodOptional<z.ZodString>;
330
- icon: z.ZodOptional<z.ZodString>;
331
- run: z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>;
332
- inspector: z.ZodOptional<z.ZodOptional<z.ZodObject<{
333
- workflow: z.ZodOptional<z.ZodObject<{
334
- getHistory: z.ZodCustom<() => unknown, () => unknown>;
335
- onHistoryUpdated: z.ZodOptional<z.ZodCustom<(listener: (history: unknown) => void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>;
336
- replayFromStep: z.ZodOptional<z.ZodCustom<(entryId?: string) => Promise<unknown>, (entryId?: string) => Promise<unknown>>>;
337
- }, z.core.$strip>>;
338
- }, z.core.$strip>>>;
339
- }, z.core.$strip>;
340
- type RunConfigRuntime = z.infer<typeof RunConfigSchema>;
341
- type RunConfig<TState = unknown, TConnParams = unknown, TConnState = unknown, TVars = unknown, TInput = unknown, TDatabase extends AnyDatabaseProvider = AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = Omit<RunConfigRuntime, "run"> & {
342
- run: (c: RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
343
- };
344
- declare const ActorConfigSchema: z.ZodObject<{
345
- onCreate: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
346
- onDestroy: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
347
- onMigrate: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
348
- onWake: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
349
- onSleep: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
350
- run: z.ZodOptional<z.ZodUnion<readonly [z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>, z.ZodObject<{
351
- name: z.ZodOptional<z.ZodString>;
352
- icon: z.ZodOptional<z.ZodString>;
353
- run: z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>;
354
- inspector: z.ZodOptional<z.ZodOptional<z.ZodObject<{
355
- workflow: z.ZodOptional<z.ZodObject<{
356
- getHistory: z.ZodCustom<() => unknown, () => unknown>;
357
- onHistoryUpdated: z.ZodOptional<z.ZodCustom<(listener: (history: unknown) => void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>;
358
- replayFromStep: z.ZodOptional<z.ZodCustom<(entryId?: string) => Promise<unknown>, (entryId?: string) => Promise<unknown>>>;
359
- }, z.core.$strip>>;
360
- }, z.core.$strip>>>;
361
- }, z.core.$strip>]>>;
362
- onStateChange: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
363
- onBeforeConnect: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
364
- onConnect: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
365
- onDisconnect: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
366
- onBeforeActionResponse: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
367
- onRequest: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
368
- onWebSocket: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
369
- actions: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>>;
370
- actionInputSchemas: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
371
- connParamsSchema: z.ZodOptional<z.ZodAny>;
372
- events: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
373
- queues: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
374
- state: z.ZodOptional<z.ZodAny>;
375
- createState: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
376
- connState: z.ZodOptional<z.ZodAny>;
377
- createConnState: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
378
- vars: z.ZodOptional<z.ZodAny>;
379
- db: z.ZodOptional<z.ZodAny>;
380
- createVars: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
381
- options: z.ZodPrefault<z.ZodObject<{
382
- name: z.ZodOptional<z.ZodString>;
383
- icon: z.ZodOptional<z.ZodString>;
384
- canHibernateWebSocket: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<(request: Request) => boolean, (request: Request) => boolean>]>>;
385
- createVarsTimeout: z.ZodDefault<z.ZodNumber>;
386
- createConnStateTimeout: z.ZodDefault<z.ZodNumber>;
387
- onBeforeConnectTimeout: z.ZodDefault<z.ZodNumber>;
388
- onConnectTimeout: z.ZodDefault<z.ZodNumber>;
389
- onMigrateTimeout: z.ZodDefault<z.ZodNumber>;
390
- sleepGracePeriod: z.ZodOptional<z.ZodNumber>;
391
- onDestroyTimeout: z.ZodDefault<z.ZodNumber>;
392
- stateSaveInterval: z.ZodDefault<z.ZodNumber>;
393
- actionTimeout: z.ZodDefault<z.ZodNumber>;
394
- waitUntilTimeout: z.ZodDefault<z.ZodNumber>;
395
- connectionLivenessTimeout: z.ZodDefault<z.ZodNumber>;
396
- connectionLivenessInterval: z.ZodDefault<z.ZodNumber>;
397
- noSleep: z.ZodDefault<z.ZodBoolean>;
398
- sleepTimeout: z.ZodDefault<z.ZodNumber>;
399
- maxQueueSize: z.ZodDefault<z.ZodNumber>;
400
- maxQueueMessageSize: z.ZodDefault<z.ZodNumber>;
401
- preloadMaxWorkflowBytes: z.ZodOptional<z.ZodNumber>;
402
- preloadMaxConnectionsBytes: z.ZodOptional<z.ZodNumber>;
403
- }, z.core.$strict>>;
404
- }, z.core.$strict>;
405
- type CreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
406
- state: TState;
407
- } | {
408
- createState: (c: CreateContext<TState, TInput, TDatabase, TEvents, TQueues>, input: TInput) => TState | Promise<TState>;
409
- } | Record<never, never>;
410
- type CreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
411
- connState: TConnState;
412
- } | {
413
- createConnState: (c: CreateConnStateContext<TState, TVars, TInput, TDatabase, TEvents, TQueues>, params: TConnParams) => TConnState | Promise<TConnState>;
414
- } | Record<never, never>;
415
- /**
416
- * @experimental
417
- */
418
- type CreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
419
- /**
420
- * @experimental
421
- */
422
- vars: TVars;
423
- } | {
424
- /**
425
- * @experimental
426
- */
427
- createVars: (c: CreateVarsContext<TState, TInput, TDatabase, TEvents, TQueues>, driverCtx: any) => TVars | Promise<TVars>;
428
- } | Record<never, never>;
429
- interface Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
430
- [Action: string]: (c: ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, ...args: any[]) => any;
431
- }
432
- interface BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig, TActions extends Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>> {
433
- /**
434
- * Called when the actor is first initialized.
435
- *
436
- * Use this hook to initialize your actor's state.
437
- * This is called before any other lifecycle hooks.
438
- */
439
- onCreate?: (c: CreateContext<TState, TInput, TDatabase, TEvents, TQueues>, input: TInput) => void | Promise<void>;
440
- /**
441
- * Called when the actor is destroyed.
442
- */
443
- onDestroy?: (c: DestroyContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
444
- /**
445
- * Called on every actor start after persisted state loads and before onWake.
446
- *
447
- * Use this hook for repeatable schema migrations or other startup work that
448
- * must run on both first boot and wake.
449
- */
450
- onMigrate?: (c: MigrateContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, isNew: boolean) => void | Promise<void>;
451
- /**
452
- * Called when the actor is started and ready to receive connections and action.
453
- *
454
- * Use this hook to initialize resources needed for the actor's operation
455
- * (timers, external connections, etc.)
456
- *
457
- * @returns Void or a Promise that resolves when startup is complete
458
- */
459
- onWake?: (c: WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
460
- /**
461
- * Called when the actor is stopping or sleeping.
462
- *
463
- * Use this hook to clean up resources, save state, or perform
464
- * any shutdown operations before the actor sleeps or stops.
465
- *
466
- * Not supported on all platforms.
467
- *
468
- * @returns Void or a Promise that resolves when shutdown is complete
469
- */
470
- onSleep?: (c: SleepContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
471
- /**
472
- * Called after the actor starts up. Does not block actor startup.
473
- *
474
- * Use this for background tasks like:
475
- * - Reading from queues in a loop
476
- * - Tick loops for periodic work
477
- * - Custom workflow logic
478
- *
479
- * **Important:** The actor may go to sleep at any time during the `run`
480
- * handler. Use `c.setPreventSleep(true)` while work is active, then clear
481
- * it with `c.setPreventSleep(false)` once the actor can sleep again.
482
- * `setPreventSleep` blocks idle sleep until it is cleared. If shutdown has
483
- * already started, RivetKit waits for `preventSleep` to clear within the
484
- * same graceful shutdown window controlled by `sleepGracePeriod`.
485
- *
486
- * The handler receives an abort signal via `c.abortSignal` and a
487
- * `c.aborted` alias for loop checks. Use these to gracefully exit.
488
- *
489
- * If this handler exits, the actor will follow the normal idle sleep timeout
490
- * once it becomes idle.
491
- * If this handler throws, the actor logs the error and then sleeps once it
492
- * becomes idle.
493
- * Call `c.destroy()` explicitly if a run handler should destroy the actor.
494
- *
495
- * Can be either a function or a RunConfig object with optional name/icon metadata.
496
- *
497
- * @returns Void or a Promise.
498
- */
499
- run?: ((c: RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>) | RunConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
500
- /**
501
- * Called when the actor's state changes.
502
- *
503
- * Use this hook to react to state changes, such as updating
504
- * external systems or triggering events.
505
- *
506
- * State changes made within this hook will NOT trigger
507
- * another onStateChange call, preventing infinite recursion.
508
- *
509
- * @param newState The updated state
510
- */
511
- onStateChange?: (c: StateChangeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, newState: TState) => void;
512
- /**
513
- * Called before a client connects to the actor.
514
- *
515
- * Use this hook to determine if a connection should be accepted
516
- * and to initialize connection-specific state.
517
- *
518
- * @param opts Connection parameters including client-provided data
519
- * @returns The initial connection state or a Promise that resolves to it
520
- * @throws Throw an error to reject the connection
521
- */
522
- onBeforeConnect?: (c: BeforeConnectContext<TState, TVars, TInput, TDatabase, TEvents, TQueues>, params: TConnParams) => void | Promise<void>;
523
- /**
524
- * Called when a client successfully connects to the actor.
525
- *
526
- * Use this hook to perform actions when a connection is established,
527
- * such as sending initial data or updating the actor's state.
528
- *
529
- * @param conn The connection object
530
- * @returns Void or a Promise that resolves when connection handling is complete
531
- */
532
- onConnect?: (c: ConnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
533
- /**
534
- * Called when a client disconnects from the actor.
535
- *
536
- * Use this hook to clean up resources associated with the connection
537
- * or update the actor's state.
538
- *
539
- * @param conn The connection that is being closed
540
- * @returns Void or a Promise that resolves when disconnect handling is complete
541
- */
542
- onDisconnect?: (c: DisconnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
543
- /**
544
- * Called before sending an action response to the client.
545
- *
546
- * Use this hook to modify or transform the output of an action before it's sent
547
- * to the client. This is useful for formatting responses, adding metadata,
548
- * or applying transformations to the output.
549
- *
550
- * @param name The name of the action that was called
551
- * @param args The arguments that were passed to the action
552
- * @param output The output that will be sent to the client
553
- * @returns The modified output to send to the client
554
- */
555
- onBeforeActionResponse?: <Out>(c: BeforeActionResponseContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, name: string, args: unknown[], output: Out) => Out | Promise<Out>;
556
- /**
557
- * Called when a raw HTTP request is made to the actor.
558
- *
559
- * This handler receives raw HTTP requests made to `/actors/{actorName}/http/*` endpoints.
560
- * Use this hook to handle custom HTTP patterns, REST APIs, or other HTTP-based protocols.
561
- *
562
- * @param c The request context with access to the connection
563
- * @param request The raw HTTP request object
564
- * @param opts Additional options
565
- * @returns A Response object to send back, or void to continue with default routing
566
- */
567
- onRequest?: (c: RequestContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, request: Request) => Response | Promise<Response>;
568
- /**
569
- * Called when a raw WebSocket connection is established to the actor.
570
- *
571
- * This handler receives WebSocket connections made to `/actors/{actorName}/websocket/*` endpoints.
572
- * Use this hook to handle custom WebSocket protocols, binary streams, or other WebSocket-based communication.
573
- *
574
- * @param c The WebSocket context with access to the connection
575
- * @param websocket The actor-facing raw WebSocket connection
576
- * @param opts Additional options including the original HTTP upgrade request
577
- */
578
- onWebSocket?: (c: WebSocketContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, websocket: UniversalWebSocket) => void | Promise<void>;
579
- actions?: TActions;
580
- /**
581
- * Optional schema map for validating action argument tuples in native runtimes.
582
- */
583
- actionInputSchemas?: Record<string, PrimitiveSchema>;
584
- /**
585
- * Optional schema for validating connection params in native runtimes.
586
- */
587
- connParamsSchema?: PrimitiveSchema;
588
- /**
589
- * Schema map for events broadcasted by this actor.
590
- */
591
- events?: TEvents;
592
- /**
593
- * Schema map for queue payloads sent by this actor.
594
- */
595
- queues?: TQueues;
596
- }
597
- type ActorDatabaseConfig<TDatabase extends AnyDatabaseProvider> = {
598
- /**
599
- * @experimental
600
- */
601
- db: TDatabase;
602
- } | Record<never, never>;
603
- type ActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = Omit<z.infer<typeof ActorConfigSchema>, "actions" | "events" | "queues" | "onCreate" | "onDestroy" | "onMigrate" | "onWake" | "onSleep" | "run" | "onStateChange" | "onBeforeConnect" | "onConnect" | "onDisconnect" | "onBeforeActionResponse" | "onRequest" | "onWebSocket" | "state" | "createState" | "connState" | "createConnState" | "vars" | "createVars" | "db"> & BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues, Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>> & CreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & CreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & CreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & ActorDatabaseConfig<TDatabase>;
604
367
 
605
- interface BaseActorDefinition<S, CP, CS, V, I, DB extends AnyDatabaseProvider, E extends EventSchemaConfig = Record<never, never>, Q extends QueueSchemaConfig = Record<never, never>, R extends Actions<S, CP, CS, V, I, DB, E, Q> = Actions<S, CP, CS, V, I, DB, E, Q>> {
606
- readonly config: ActorConfig<S, CP, CS, V, I, DB, E, Q>;
368
+ /**
369
+ * Action function returned by Actor connections and handles.
370
+ *
371
+ * @typedef {Function} ActorActionFunction
372
+ * @template Args
373
+ * @template Response
374
+ * @param {...Args} args - Arguments for the action function.
375
+ * @returns {Promise<Response>}
376
+ */
377
+ type ActorActionFunction<Args extends Array<unknown> = unknown[], Response = unknown> = (...args: Args extends [unknown, ...infer Rest] ? Rest : Args) => Promise<Response>;
378
+ /**
379
+ * Maps action methods from actor definition to typed function signatures.
380
+ */
381
+ type ActorDefinitionActions<AD extends AnyActorDefinition> = AD extends BaseActorDefinition<any, any, any, any, any, any, any, any, infer R> ? {
382
+ [K in keyof R]: R[K] extends (...args: infer Args) => infer Return ? ActorActionFunction<Args, Return> : never;
383
+ } : never;
384
+ type ActorQueueSend<TQueues extends QueueSchemaConfig> = {
385
+ <K extends keyof TQueues & string>(name: K, body: InferSchemaMap<TQueues>[K], options: QueueSendWaitOptions): Promise<QueueSendResult<InferQueueCompleteMap<TQueues>[K]>>;
386
+ <K extends keyof TQueues & string>(name: K, body: InferSchemaMap<TQueues>[K], options?: QueueSendNoWaitOptions): Promise<void>;
387
+ (name: keyof TQueues extends never ? string : never, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
388
+ (name: keyof TQueues extends never ? string : never, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
389
+ };
390
+ type ActorEventSubscribe<TEvents extends EventSchemaConfig> = {
391
+ <K extends keyof TEvents & string>(eventName: K, callback: (...args: InferEventArgs<InferSchemaMap<TEvents>[K]>) => void): () => void;
392
+ (eventName: keyof TEvents extends never ? string : never, callback: (...args: any[]) => void): () => void;
393
+ };
394
+ type ActorDefinitionQueueSend<AD extends AnyActorDefinition> = AD extends BaseActorDefinition<any, any, any, any, any, any, any, infer Q, any> ? Q extends QueueSchemaConfig ? {
395
+ send: ActorQueueSend<Q>;
396
+ } : never : never;
397
+ type ActorDefinitionEventSubscriptions<AD extends AnyActorDefinition> = AD extends BaseActorDefinition<any, any, any, any, any, any, infer E, any, any> ? E extends EventSchemaConfig ? {
398
+ on: ActorEventSubscribe<E>;
399
+ once: ActorEventSubscribe<E>;
400
+ } : never : never;
401
+
402
+ declare class ActorClientError extends Error {
607
403
  }
608
- type AnyActorDefinition = BaseActorDefinition<any, any, any, any, any, any, any, any, any>;
609
- declare class ActorDefinition<S, CP, CS, V, I, DB extends AnyDatabaseProvider, E extends EventSchemaConfig = Record<never, never>, Q extends QueueSchemaConfig = Record<never, never>, R extends Actions<S, CP, CS, V, I, DB, E, Q> = Actions<S, CP, CS, V, I, DB, E, Q>> implements BaseActorDefinition<S, CP, CS, V, I, DB, E, Q, R> {
610
- #private;
611
- constructor(config: ActorConfig<S, CP, CS, V, I, DB, E, Q>);
612
- get config(): ActorConfig<S, CP, CS, V, I, DB, E, Q>;
404
+ declare class ManagerError extends ActorClientError {
405
+ constructor(error: string, opts?: ErrorOptions);
406
+ }
407
+ declare class MalformedResponseMessage extends ActorClientError {
408
+ constructor(cause?: unknown);
613
409
  }
614
410
 
615
- declare const ActorsSchema: z$1.ZodRecord<z$1.ZodString, z$1.ZodCustom<BaseActorDefinition<any, any, any, any, any, any, any, any, any>, BaseActorDefinition<any, any, any, any, any, any, any, any, any>>>;
616
- type RegistryActors = z$1.infer<typeof ActorsSchema>;
617
- declare const RegistryConfigSchema: z$1.ZodPipe<z$1.ZodObject<{
618
- use: z$1.ZodRecord<z$1.ZodString, z$1.ZodCustom<AnyActorDefinition, AnyActorDefinition>>;
619
- test: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodObject<{
620
- enabled: z$1.ZodBoolean;
621
- }, z$1.core.$strip>>>;
622
- maxIncomingMessageSize: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodNumber>>;
623
- maxOutgoingMessageSize: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodNumber>>;
624
- noWelcome: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
625
- logging: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodObject<{
626
- baseLogger: z$1.ZodOptional<z$1.ZodCustom<Logger, Logger>>;
627
- level: z$1.ZodOptional<z$1.ZodEnum<{
628
- error: "error";
629
- trace: "trace";
630
- fatal: "fatal";
631
- warn: "warn";
632
- info: "info";
633
- debug: "debug";
634
- silent: "silent";
635
- }>>;
636
- }, z$1.core.$strip>>>;
637
- endpoint: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string | undefined, string | undefined>>;
638
- token: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string | undefined, string | undefined>>;
639
- namespace: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string | undefined, string | undefined>>;
640
- headers: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodString>>>;
641
- staticDir: z$1.ZodOptional<z$1.ZodString>;
642
- httpBasePath: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodString>>;
643
- httpPort: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodNumber>>;
644
- httpHost: z$1.ZodOptional<z$1.ZodString>;
645
- startEngine: z$1.ZodDefault<z$1.ZodBoolean>;
646
- engineVersion: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodString>>;
647
- configurePool: z$1.ZodOptional<z$1.ZodOptional<z$1.ZodObject<{
648
- name: z$1.ZodOptional<z$1.ZodString>;
649
- url: z$1.ZodString;
650
- headers: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodString>>;
651
- requestLifespan: z$1.ZodOptional<z$1.ZodNumber>;
652
- metadata: z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodUnknown>>;
653
- metadataPollInterval: z$1.ZodOptional<z$1.ZodNumber>;
654
- drainOnVersionUpgrade: z$1.ZodOptional<z$1.ZodBoolean>;
655
- }, z$1.core.$strip>>>;
656
- serverless: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodObject<{
657
- basePath: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodString>>;
658
- publicEndpoint: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string | undefined, string | undefined>>;
659
- publicToken: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string | undefined, string | undefined>>;
660
- }, z$1.core.$strip>>>;
661
- envoy: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodObject<{
662
- poolName: z$1.ZodDefault<z$1.ZodString>;
663
- version: z$1.ZodDefault<z$1.ZodNumber>;
664
- totalSlots: z$1.ZodDefault<z$1.ZodNumber>;
665
- envoyKey: z$1.ZodOptional<z$1.ZodString>;
666
- }, z$1.core.$strip>>>;
667
- }, z$1.core.$strip>, z$1.ZodTransform<{
668
- endpoint: string | undefined;
669
- namespace: string;
670
- token: string | undefined;
671
- publicEndpoint: string | undefined;
672
- publicNamespace: string | undefined;
673
- publicToken: string | undefined;
674
- serverless: {
675
- publicEndpoint: string | undefined;
676
- basePath: string;
677
- publicToken: string | undefined;
678
- };
679
- use: Record<string, AnyActorDefinition>;
680
- test: {
681
- enabled: boolean;
682
- };
683
- maxIncomingMessageSize: number;
684
- maxOutgoingMessageSize: number;
685
- noWelcome: boolean;
686
- logging: {
687
- baseLogger?: Logger | undefined;
688
- level?: "error" | "trace" | "fatal" | "warn" | "info" | "debug" | "silent" | undefined;
689
- };
690
- headers: Record<string, string>;
691
- httpBasePath: string;
692
- httpPort: number;
693
- startEngine: boolean;
694
- engineVersion: string;
695
- envoy: {
696
- poolName: string;
697
- version: number;
698
- totalSlots: number;
699
- envoyKey?: string | undefined;
700
- };
701
- staticDir?: string | undefined;
702
- httpHost?: string | undefined;
703
- configurePool?: {
704
- url: string;
705
- name?: string | undefined;
706
- headers?: Record<string, string> | undefined;
707
- requestLifespan?: number | undefined;
708
- metadata?: Record<string, unknown> | undefined;
709
- metadataPollInterval?: number | undefined;
710
- drainOnVersionUpgrade?: boolean | undefined;
711
- } | undefined;
712
- }, {
713
- use: Record<string, AnyActorDefinition>;
714
- test: {
715
- enabled: boolean;
716
- };
717
- maxIncomingMessageSize: number;
718
- maxOutgoingMessageSize: number;
719
- noWelcome: boolean;
720
- logging: {
721
- baseLogger?: Logger | undefined;
722
- level?: "error" | "trace" | "fatal" | "warn" | "info" | "debug" | "silent" | undefined;
723
- };
724
- endpoint: string | undefined;
725
- token: string | undefined;
726
- namespace: string | undefined;
727
- headers: Record<string, string>;
728
- httpBasePath: string;
729
- httpPort: number;
730
- startEngine: boolean;
731
- engineVersion: string;
732
- serverless: {
733
- basePath: string;
734
- publicEndpoint: string | undefined;
735
- publicToken: string | undefined;
736
- };
737
- envoy: {
738
- poolName: string;
739
- version: number;
740
- totalSlots: number;
741
- envoyKey?: string | undefined;
742
- };
743
- staticDir?: string | undefined;
744
- httpHost?: string | undefined;
745
- configurePool?: {
746
- url: string;
747
- name?: string | undefined;
748
- headers?: Record<string, string> | undefined;
749
- requestLifespan?: number | undefined;
750
- metadata?: Record<string, unknown> | undefined;
751
- metadataPollInterval?: number | undefined;
752
- drainOnVersionUpgrade?: boolean | undefined;
753
- } | undefined;
754
- }>>;
755
- type RegistryConfig = z$1.infer<typeof RegistryConfigSchema>;
756
- type RegistryConfigInput<A extends RegistryActors> = Omit<z$1.input<typeof RegistryConfigSchema>, "use"> & {
757
- use: A;
758
- };
759
-
760
- type FetchHandler = (request: Request, ...args: any) => Response | Promise<Response>;
761
- interface ServerlessHandler {
762
- fetch: FetchHandler;
411
+ declare class ActorConnDisposed extends ActorClientError {
412
+ constructor();
763
413
  }
764
- declare class Registry<A extends RegistryActors> {
414
+
415
+ type ActorResolutionState = ActorQuery;
416
+
417
+ /**
418
+ * Connection status for an actor connection.
419
+ *
420
+ * - `"idle"`: Not connected, no auto-reconnect (initial state, after dispose, or disabled)
421
+ * - `"connecting"`: Attempting to establish connection
422
+ * - `"connected"`: Connection is active
423
+ * - `"disconnected"`: Connection was lost, will auto-reconnect
424
+ */
425
+ type ActorConnStatus = "idle" | "connecting" | "connected" | "disconnected";
426
+ /**
427
+ * A function that unsubscribes from an event.
428
+ *
429
+ * @typedef {Function} EventUnsubscribe
430
+ */
431
+ type EventUnsubscribe = () => void;
432
+ /**
433
+ * A function that handles connection errors.
434
+ *
435
+ * @typedef {Function} ActorErrorCallback
436
+ */
437
+ type ActorErrorCallback = (error: RivetError) => void;
438
+ /**
439
+ * A callback for connection state changes.
440
+ *
441
+ * @typedef {Function} ConnectionStateCallback
442
+ */
443
+ type ConnectionStateCallback = () => void;
444
+ /**
445
+ * A callback for connection status changes.
446
+ *
447
+ * @typedef {Function} StatusChangeCallback
448
+ */
449
+ type StatusChangeCallback = (status: ActorConnStatus) => void;
450
+ declare const CONNECT_SYMBOL: unique symbol;
451
+ /**
452
+ * Provides underlying functions for {@link ActorConn}. See {@link ActorConn} for using type-safe remote procedure calls.
453
+ *
454
+ * @see {@link ActorConn}
455
+ */
456
+ declare class ActorConnRaw {
765
457
  #private;
766
- get config(): RegistryConfigInput<A>;
767
- parseConfig(): RegistryConfig;
768
- constructor(config: RegistryConfigInput<A>);
769
458
  /**
770
- * Handle an incoming HTTP request for serverless deployments.
459
+ * Do not call this directly.
771
460
  *
772
- * @example
773
- * ```ts
774
- * const app = new Hono();
775
- * app.all("/api/rivet/*", (c) => registry.handler(c.req.raw));
776
- * export default app;
777
- * ```
461
+ * Creates an instance of ActorConnRaw.
462
+ *
463
+ * @protected
778
464
  */
779
- handler(request: Request): Promise<Response>;
465
+ constructor(client: ClientRaw, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState);
466
+ send(name: string, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
467
+ send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
468
+ /**
469
+ * Call a raw action connection. See {@link ActorConn} for type-safe action calls.
470
+ *
471
+ * @see {@link ActorConn}
472
+ * @template Args - The type of arguments to pass to the action function.
473
+ * @template Response - The type of the response returned by the action function.
474
+ * @param {string} name - The name of the action function to call.
475
+ * @param {...Args} args - The arguments to pass to the action function.
476
+ * @returns {Promise<Response>} - A promise that resolves to the response of the action function.
477
+ */
478
+ action<Args extends Array<unknown> = unknown[], Response = unknown>(opts: {
479
+ name: string;
480
+ args: Args;
481
+ signal?: AbortSignal;
482
+ }): Promise<Response>;
780
483
  /**
781
- * Returns a fetch handler for serverless deployments.
484
+ * Do not call this directly.
485
+ * Establishes a connection to the server using the specified endpoint & encoding & driver.
782
486
  *
783
- * @example
784
- * ```ts
785
- * export default registry.serve();
786
- * ```
487
+ * @protected
787
488
  */
788
- serve(): ServerlessHandler;
489
+ [CONNECT_SYMBOL](): void;
789
490
  /**
790
- * Starts an actor envoy for standalone server deployments.
491
+ * Subscribes to an event that will happen repeatedly.
492
+ *
493
+ * @template Args - The type of arguments the event callback will receive.
494
+ * @param {string} eventName - The name of the event to subscribe to.
495
+ * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
496
+ * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
497
+ * @see {@link https://rivet.dev/docs/events|Events Documentation}
791
498
  */
792
- startEnvoy(): void;
499
+ on<Args extends Array<unknown> = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe;
793
500
  /**
794
- * Starts the server, serving both the actor API and static files.
795
- *
796
- * This is the simplest way to run RivetKit. It starts a local runtime
797
- * server, serves static files from the configured `staticDir` (default
798
- * `"public"`), and starts the actor envoy.
799
- *
800
- * When an endpoint is configured (via config or RIVET_ENDPOINT env var),
801
- * operates in serverless mode connected to the remote engine instead.
501
+ * Subscribes to an event that will be triggered only once.
802
502
  *
803
- * @example
804
- * ```ts
805
- * const registry = setup({ use: { counter } });
806
- * registry.start();
807
- * ```
503
+ * @template Args - The type of arguments the event callback will receive.
504
+ * @param {string} eventName - The name of the event to subscribe to.
505
+ * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
506
+ * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
507
+ * @see {@link https://rivet.dev/docs/events|Events Documentation}
808
508
  */
809
- start(): void;
810
- }
811
-
812
- declare const EncodingSchema: z.ZodEnum<{
813
- json: "json";
814
- cbor: "cbor";
815
- bare: "bare";
816
- }>;
817
- /**
818
- * Encoding used to communicate between the client & actor.
819
- */
820
- type Encoding = z.infer<typeof EncodingSchema>;
821
-
822
- declare const ActorKeySchema: z.ZodArray<z.ZodString>;
823
- type ActorKey = z.infer<typeof ActorKeySchema>;
824
- /**
825
- * Crash policy for actor lifecycle management.
826
- *
827
- * This schema is only used by the engine driver for actor creation. The manager
828
- * driver ignores crash policy and passes it through to the engine unchanged.
829
- */
830
- declare const CrashPolicySchema: z.ZodEnum<{
831
- sleep: "sleep";
832
- destroy: "destroy";
833
- restart: "restart";
834
- }>;
835
- type CrashPolicy = z.infer<typeof CrashPolicySchema>;
836
- declare const CreateRequestSchema: z.ZodObject<{
837
- name: z.ZodString;
838
- key: z.ZodArray<z.ZodString>;
839
- input: z.ZodOptional<z.ZodUnknown>;
840
- region: z.ZodOptional<z.ZodString>;
841
- }, z.core.$strip>;
842
- declare const ActorQuerySchema: z.ZodUnion<readonly [z.ZodObject<{
843
- getForId: z.ZodObject<{
844
- name: z.ZodString;
845
- actorId: z.ZodString;
846
- }, z.core.$strip>;
847
- }, z.core.$strip>, z.ZodObject<{
848
- getForKey: z.ZodObject<{
849
- name: z.ZodString;
850
- key: z.ZodArray<z.ZodString>;
851
- }, z.core.$strip>;
852
- }, z.core.$strip>, z.ZodObject<{
853
- getOrCreateForKey: z.ZodObject<{
854
- name: z.ZodString;
855
- key: z.ZodArray<z.ZodString>;
856
- input: z.ZodOptional<z.ZodUnknown>;
857
- region: z.ZodOptional<z.ZodString>;
858
- }, z.core.$strip>;
859
- }, z.core.$strip>, z.ZodObject<{
860
- create: z.ZodObject<{
861
- name: z.ZodString;
862
- key: z.ZodArray<z.ZodString>;
863
- input: z.ZodOptional<z.ZodUnknown>;
864
- region: z.ZodOptional<z.ZodString>;
865
- }, z.core.$strip>;
866
- }, z.core.$strip>]>;
867
- type ActorQuery = z.infer<typeof ActorQuerySchema>;
868
- /**
869
- * Interface representing a request to create a actor.
870
- */
871
- type CreateRequest = z.infer<typeof CreateRequestSchema>;
872
-
873
- interface DeconstructedError {
874
- __type: "ActorError";
875
- statusCode: ContentfulStatusCode;
876
- public: boolean;
877
- group: string;
878
- code: string;
879
- message: string;
880
- metadata?: unknown;
881
- }
882
-
883
- interface RivetErrorOptions extends ErrorOptions {
884
- /** Error data can safely be serialized in a response to the client. */
885
- public?: boolean;
886
- /** Metadata associated with this error. */
887
- metadata?: unknown;
888
- /** Explicit HTTP status override for router responses. */
889
- statusCode?: number;
890
- }
891
- interface UserErrorOptions extends ErrorOptions {
509
+ once<Args extends Array<unknown> = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe;
892
510
  /**
893
- * Machine readable code for this error. Useful for catching different types of
894
- * errors in try-catch.
511
+ * Subscribes to connection errors.
512
+ *
513
+ * @param {ActorErrorCallback} callback - The callback function to execute when a connection error occurs.
514
+ * @returns {() => void} - A function to unsubscribe from the error handler.
895
515
  */
896
- code?: string;
516
+ onError(callback: ActorErrorCallback): () => void;
897
517
  /**
898
- * Additional metadata related to the error. Useful for understanding context
899
- * about the error.
518
+ * Returns the current connection status.
519
+ *
520
+ * @returns {ActorConnStatus} - The current connection status.
900
521
  */
901
- metadata?: unknown;
902
- }
903
- declare class RivetError extends Error {
904
- __type: "RivetError";
905
- public: boolean;
906
- metadata?: unknown;
907
- statusCode: number;
908
- readonly group: string;
909
- readonly code: string;
910
- static isRivetError(error: unknown): error is RivetError | DeconstructedError;
911
- static isActorError(error: unknown): error is RivetError | DeconstructedError;
912
- constructor(group: string, code: string, message: string, options?: RivetErrorOptions | unknown);
913
- toString(): string;
914
- }
915
-
916
- declare class UserError extends RivetError {
917
- constructor(message: string, options?: UserErrorOptions);
918
- }
919
-
920
- type UpgradeWebSocket = (createEvents: (c: Context) => any) => Handler;
921
- type GetUpgradeWebSocket = () => UpgradeWebSocket;
922
-
923
- type GatewayTarget = {
924
- directId: string;
925
- } | ActorQuery;
926
- interface EngineControlClient {
927
- getForId(input: GetForIdInput): Promise<ActorOutput | undefined>;
928
- getWithKey(input: GetWithKeyInput): Promise<ActorOutput | undefined>;
929
- getOrCreateWithKey(input: GetOrCreateWithKeyInput): Promise<ActorOutput>;
930
- createActor(input: CreateInput): Promise<ActorOutput>;
931
- listActors(input: ListActorsInput): Promise<ActorOutput[]>;
932
- sendRequest(target: GatewayTarget, actorRequest: Request): Promise<Response>;
933
- openWebSocket(path: string, target: GatewayTarget, encoding: Encoding, params: unknown): Promise<UniversalWebSocket>;
934
- proxyRequest(c: Context, actorRequest: Request, actorId: string): Promise<Response>;
935
- proxyWebSocket(c: Context, path: string, actorId: string, encoding: Encoding, params: unknown): Promise<Response>;
936
- buildGatewayUrl(target: GatewayTarget): Promise<string>;
937
- displayInformation(): RuntimeDisplayInformation;
938
- extraStartupLog?: () => Record<string, unknown>;
939
- modifyRuntimeRouter?: (config: RegistryConfig, router: Hono) => void;
940
- setGetUpgradeWebSocket(getUpgradeWebSocket: GetUpgradeWebSocket): void;
941
- shutdown?(): void;
522
+ get connStatus(): ActorConnStatus;
942
523
  /**
943
- * Test-only helper that simulates an abrupt actor crash.
524
+ * Returns whether the connection is currently open.
525
+ *
526
+ * @deprecated Use `connStatus` instead.
527
+ * @returns {boolean} - True if the connection is open, false otherwise.
944
528
  */
945
- hardCrashActor?(actorId: string): Promise<void>;
946
- kvGet(actorId: string, key: Uint8Array): Promise<string | null>;
947
- kvBatchGet(actorId: string, keys: Uint8Array[]): Promise<(Uint8Array | null)[]>;
948
- kvBatchPut(actorId: string, entries: [Uint8Array, Uint8Array][]): Promise<void>;
949
- kvBatchDelete(actorId: string, keys: Uint8Array[]): Promise<void>;
950
- kvDeleteRange(actorId: string, start: Uint8Array, end: Uint8Array): Promise<void>;
951
- }
952
- interface RuntimeDisplayInformation {
953
- properties: Record<string, string>;
954
- }
955
- interface GetForIdInput {
956
- c?: Context | undefined;
957
- name: string;
958
- actorId: string;
959
- }
960
- interface GetWithKeyInput {
961
- c?: Context | undefined;
962
- name: string;
963
- key: ActorKey;
964
- }
965
- interface GetOrCreateWithKeyInput {
966
- c?: Context | undefined;
967
- name: string;
968
- key: ActorKey;
969
- input?: unknown;
970
- region?: string;
971
- crashPolicy?: CrashPolicy;
972
- }
973
- interface CreateInput {
974
- c?: Context | undefined;
975
- name: string;
976
- key: ActorKey;
977
- input?: unknown;
978
- region?: string;
979
- crashPolicy?: CrashPolicy;
980
- }
981
- interface ListActorsInput {
982
- c?: Context | undefined;
983
- name: string;
984
- key?: string;
985
- includeDestroyed?: boolean;
986
- }
987
- interface ActorOutput {
988
- actorId: string;
989
- name: string;
990
- key: ActorKey;
991
- createTs?: number;
992
- startTs?: number | null;
993
- connectableTs?: number | null;
994
- sleepTs?: number | null;
995
- destroyTs?: number | null;
996
- error?: unknown;
997
- }
998
-
999
- interface QueueSendWaitOptions {
1000
- wait: true;
1001
- timeout?: number;
1002
- signal?: AbortSignal;
1003
- }
1004
- interface QueueSendNoWaitOptions {
1005
- wait?: false;
1006
- timeout?: never;
1007
- signal?: AbortSignal;
1008
- }
1009
- interface QueueSendResult<TResponse = unknown> {
1010
- status: "completed" | "timedOut";
1011
- response?: TResponse;
529
+ get isConnected(): boolean;
530
+ /**
531
+ * Subscribes to connection open events.
532
+ *
533
+ * This is called when the WebSocket connection is established and the Init message is received.
534
+ *
535
+ * @param {ConnectionStateCallback} callback - The callback function to execute when the connection opens.
536
+ * @returns {() => void} - A function to unsubscribe from the open handler.
537
+ */
538
+ onOpen(callback: ConnectionStateCallback): () => void;
539
+ /**
540
+ * Subscribes to connection close events.
541
+ *
542
+ * This is called when the WebSocket connection is closed. The connection will automatically
543
+ * attempt to reconnect unless disposed.
544
+ *
545
+ * @param {ConnectionStateCallback} callback - The callback function to execute when the connection closes.
546
+ * @returns {() => void} - A function to unsubscribe from the close handler.
547
+ */
548
+ onClose(callback: ConnectionStateCallback): () => void;
549
+ /**
550
+ * Subscribes to connection status changes.
551
+ *
552
+ * This is called whenever the connection status changes between Disconnected, Connecting, and Connected.
553
+ *
554
+ * @param {StatusChangeCallback} callback - The callback function to execute when the status changes.
555
+ * @returns {() => void} - A function to unsubscribe from the status change handler.
556
+ */
557
+ onStatusChange(callback: StatusChangeCallback): () => void;
558
+ /**
559
+ * Disconnects from the actor.
560
+ *
561
+ * @returns {Promise<void>} A promise that resolves when the socket is gracefully closed.
562
+ */
563
+ dispose(): Promise<void>;
1012
564
  }
565
+ /**
566
+ * Connection to a actor. Allows calling actor's remote procedure calls with inferred types. See {@link ActorConnRaw} for underlying methods.
567
+ *
568
+ * @example
569
+ * ```
570
+ * const room = client.connect<ChatRoom>(...etc...);
571
+ * // This calls the action named `sendMessage` on the `ChatRoom` actor.
572
+ * await room.sendMessage('Hello, world!');
573
+ * ```
574
+ *
575
+ * Private methods (e.g. those starting with `_`) are automatically excluded.
576
+ *
577
+ * @template AD The actor class that this connection is for.
578
+ * @see {@link ActorConnRaw}
579
+ */
580
+ type ActorConn<AD extends AnyActorDefinition> = Omit<ActorConnRaw, "send" | "on" | "once"> & ActorDefinitionQueueSend<AD> & ActorDefinitionEventSubscriptions<AD> & ActorDefinitionActions<AD>;
1013
581
 
1014
582
  /**
1015
- * Action function returned by Actor connections and handles.
583
+ * Provides underlying functions for stateless {@link ActorHandle} for action calls.
584
+ * Similar to ActorConnRaw but doesn't maintain a connection.
1016
585
  *
1017
- * @typedef {Function} ActorActionFunction
1018
- * @template Args
1019
- * @template Response
1020
- * @param {...Args} args - Arguments for the action function.
1021
- * @returns {Promise<Response>}
586
+ * @see {@link ActorHandle}
1022
587
  */
1023
- type ActorActionFunction<Args extends Array<unknown> = unknown[], Response = unknown> = (...args: Args extends [unknown, ...infer Rest] ? Rest : Args) => Promise<Response>;
588
+ declare class ActorHandleRaw {
589
+ #private;
590
+ /**
591
+ * Do not call this directly.
592
+ *
593
+ * Creates an instance of ActorHandleRaw.
594
+ *
595
+ * @protected
596
+ */
597
+ constructor(client: any, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState);
598
+ send(name: string, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
599
+ send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
600
+ /**
601
+ * Call a raw action. This method sends an HTTP request to invoke the named action.
602
+ *
603
+ * @see {@link ActorHandle}
604
+ * @template Args - The type of arguments to pass to the action function.
605
+ * @template Response - The type of the response returned by the action function.
606
+ */
607
+ action<Args extends Array<unknown> = unknown[], Response = unknown>(opts: {
608
+ name: string;
609
+ args: Args;
610
+ signal?: AbortSignal;
611
+ }): Promise<Response>;
612
+ /**
613
+ * Establishes a persistent connection to the actor.
614
+ *
615
+ * @template AD The actor class that this connection is for.
616
+ * @returns {ActorConn<AD>} A connection to the actor.
617
+ */
618
+ connect(params?: unknown): ActorConn<AnyActorDefinition>;
619
+ /**
620
+ * Fetches a resource from this actor via the /request endpoint. This is a
621
+ * convenience wrapper around the raw HTTP API.
622
+ */
623
+ fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
624
+ /**
625
+ * Opens a raw WebSocket connection to this actor.
626
+ */
627
+ webSocket(path?: string, protocols?: string | string[]): Promise<any>;
628
+ /**
629
+ * Resolves the actor to get its unique actor ID.
630
+ */
631
+ resolve(): Promise<string>;
632
+ /**
633
+ * Returns the raw URL for routing traffic to the actor.
634
+ */
635
+ getGatewayUrl(): Promise<string>;
636
+ reload(): Promise<void>;
637
+ }
1024
638
  /**
1025
- * Maps action methods from actor definition to typed function signatures.
639
+ * Stateless handle to a actor. Allows calling actor's remote procedure calls with inferred types
640
+ * without establishing a persistent connection.
641
+ *
642
+ * @example
643
+ * ```
644
+ * const room = client.get<ChatRoom>(...etc...);
645
+ * // This calls the action named `sendMessage` on the `ChatRoom` actor without a connection.
646
+ * await room.sendMessage('Hello, world!');
647
+ * ```
648
+ *
649
+ * Private methods (e.g. those starting with `_`) are automatically excluded.
650
+ *
651
+ * @template AD The actor class that this handle is for.
652
+ * @see {@link ActorHandleRaw}
1026
653
  */
1027
- type ActorDefinitionActions<AD extends AnyActorDefinition> = AD extends BaseActorDefinition<any, any, any, any, any, any, any, any, infer R> ? {
1028
- [K in keyof R]: R[K] extends (...args: infer Args) => infer Return ? ActorActionFunction<Args, Return> : never;
1029
- } : never;
1030
- type ActorQueueSend<TQueues extends QueueSchemaConfig> = {
1031
- <K extends keyof TQueues & string>(name: K, body: InferSchemaMap<TQueues>[K], options: QueueSendWaitOptions): Promise<QueueSendResult<InferQueueCompleteMap<TQueues>[K]>>;
1032
- <K extends keyof TQueues & string>(name: K, body: InferSchemaMap<TQueues>[K], options?: QueueSendNoWaitOptions): Promise<void>;
1033
- (name: keyof TQueues extends never ? string : never, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
1034
- (name: keyof TQueues extends never ? string : never, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
1035
- };
1036
- type ActorEventSubscribe<TEvents extends EventSchemaConfig> = {
1037
- <K extends keyof TEvents & string>(eventName: K, callback: (...args: InferEventArgs<InferSchemaMap<TEvents>[K]>) => void): () => void;
1038
- (eventName: keyof TEvents extends never ? string : never, callback: (...args: any[]) => void): () => void;
1039
- };
1040
- type ActorDefinitionQueueSend<AD extends AnyActorDefinition> = AD extends BaseActorDefinition<any, any, any, any, any, any, any, infer Q, any> ? Q extends QueueSchemaConfig ? {
1041
- send: ActorQueueSend<Q>;
1042
- } : never : never;
1043
- type ActorDefinitionEventSubscriptions<AD extends AnyActorDefinition> = AD extends BaseActorDefinition<any, any, any, any, any, any, infer E, any, any> ? E extends EventSchemaConfig ? {
1044
- on: ActorEventSubscribe<E>;
1045
- once: ActorEventSubscribe<E>;
1046
- } : never : never;
654
+ type ActorHandle<AD extends AnyActorDefinition> = Omit<ActorHandleRaw, "connect" | "send"> & {
655
+ connect(params?: unknown): ActorConn<AD>;
656
+ resolve(): Promise<string>;
657
+ } & ActorDefinitionQueueSend<AD> & ActorDefinitionActions<AD>;
1047
658
 
1048
- declare class ActorClientError extends Error {
1049
- }
1050
- declare class ManagerError extends ActorClientError {
1051
- constructor(error: string, opts?: ErrorOptions);
1052
- }
1053
- declare class MalformedResponseMessage extends ActorClientError {
1054
- constructor(cause?: unknown);
1055
- }
659
+ declare const ClientConfigSchema: z$1.ZodPipe<z$1.ZodObject<{
660
+ endpoint: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string, string | undefined>>;
661
+ token: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string | undefined, string | undefined>>;
662
+ namespace: z$1.ZodPipe<z$1.ZodOptional<z$1.ZodString>, z$1.ZodTransform<string | undefined, string | undefined>>;
663
+ poolName: z$1.ZodDefault<z$1.ZodString>;
664
+ encoding: z$1.ZodDefault<z$1.ZodEnum<{
665
+ json: "json";
666
+ cbor: "cbor";
667
+ bare: "bare";
668
+ }>>;
669
+ headers: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodRecord<z$1.ZodString, z$1.ZodString>>>;
670
+ getUpgradeWebSocket: z$1.ZodOptional<z$1.ZodCustom<GetUpgradeWebSocket, GetUpgradeWebSocket>>;
671
+ disableMetadataLookup: z$1.ZodDefault<z$1.ZodOptional<z$1.ZodBoolean>>;
672
+ maxInputSize: z$1.ZodDefault<z$1.ZodNumber>;
673
+ devtools: z$1.ZodDefault<z$1.ZodBoolean>;
674
+ }, z$1.core.$strip>, z$1.ZodTransform<{
675
+ endpoint: string | undefined;
676
+ namespace: string;
677
+ token: string | undefined;
678
+ poolName: string;
679
+ encoding: "json" | "cbor" | "bare";
680
+ headers: Record<string, string>;
681
+ disableMetadataLookup: boolean;
682
+ maxInputSize: number;
683
+ devtools: boolean;
684
+ getUpgradeWebSocket?: GetUpgradeWebSocket | undefined;
685
+ }, {
686
+ endpoint: string;
687
+ token: string | undefined;
688
+ namespace: string | undefined;
689
+ poolName: string;
690
+ encoding: "json" | "cbor" | "bare";
691
+ headers: Record<string, string>;
692
+ disableMetadataLookup: boolean;
693
+ maxInputSize: number;
694
+ devtools: boolean;
695
+ getUpgradeWebSocket?: GetUpgradeWebSocket | undefined;
696
+ }>>;
697
+ type ClientConfigInput = z$1.input<typeof ClientConfigSchema>;
1056
698
 
1057
- declare class ActorConnDisposed extends ActorClientError {
1058
- constructor();
699
+ /** Extract the actor registry from the registry definition. */
700
+ type ExtractActorsFromRegistry<A extends Registry<any>> = A extends Registry<infer Actors> ? Actors : never;
701
+ /** Extract the registry definition from the client. */
702
+ type ExtractRegistryFromClient<C extends Client<Registry<{}>>> = C extends Client<infer A> ? A : never;
703
+ /**
704
+ * Represents a actor accessor that provides methods to interact with a specific actor.
705
+ */
706
+ interface ActorAccessor<AD extends AnyActorDefinition> {
707
+ /**
708
+ * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
709
+ * The actor name is automatically injected from the property accessor.
710
+ *
711
+ * Each operation resolves the current actor for the key before sending the
712
+ * request.
713
+ *
714
+ * @template AD The actor class that this handle is for.
715
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
716
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
717
+ * @returns {ActorHandle<AD>} - A handle to the actor.
718
+ */
719
+ get(key?: string | string[], opts?: GetWithIdOptions): ActorHandle<AD>;
720
+ /**
721
+ * Gets a stateless handle to a actor by its key, creating it if necessary.
722
+ * The actor name is automatically injected from the property accessor.
723
+ *
724
+ * Each operation resolves the current actor for the key before sending the
725
+ * request.
726
+ *
727
+ * @template AD The actor class that this handle is for.
728
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
729
+ * @param {GetOptions} [opts] - Options for getting the actor.
730
+ * @returns {ActorHandle<AD>} - A handle to the actor.
731
+ */
732
+ getOrCreate(key?: string | string[], opts?: GetOrCreateOptions): ActorHandle<AD>;
733
+ /**
734
+ * Gets a stateless handle to a actor by its ID.
735
+ *
736
+ * If the actor is destroyed, operations will throw without retrying since
737
+ * there is no key to re-resolve.
738
+ *
739
+ * @template AD The actor class that this handle is for.
740
+ * @param {string} actorId - The ID of the actor.
741
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
742
+ * @returns {ActorHandle<AD>} - A handle to the actor.
743
+ */
744
+ getForId(actorId: string, opts?: GetWithIdOptions): ActorHandle<AD>;
745
+ /**
746
+ * Creates a new actor with the name automatically injected from the property accessor,
747
+ * and returns a stateless handle to it with the actor ID resolved.
748
+ *
749
+ * If the actor is destroyed, operations will throw without retrying since
750
+ * creation is a one-shot operation.
751
+ *
752
+ * @template AD The actor class that this handle is for.
753
+ * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
754
+ * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
755
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
756
+ */
757
+ create(key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
1059
758
  }
1060
-
1061
- type ActorResolutionState = ActorQuery;
1062
-
1063
759
  /**
1064
- * Connection status for an actor connection.
1065
- *
1066
- * - `"idle"`: Not connected, no auto-reconnect (initial state, after dispose, or disabled)
1067
- * - `"connecting"`: Attempting to establish connection
1068
- * - `"connected"`: Connection is active
1069
- * - `"disconnected"`: Connection was lost, will auto-reconnect
760
+ * Options for querying actors.
761
+ * @typedef {Object} QueryOptions
762
+ * @property {unknown} [parameters] - Parameters to pass to the connection.
1070
763
  */
1071
- type ActorConnStatus = "idle" | "connecting" | "connected" | "disconnected";
764
+ interface QueryOptions {
765
+ /** Parameters to pass to the connection. */
766
+ params?: unknown;
767
+ /**
768
+ * Lazily resolves connection parameters for `.connect()` and `.webSocket()`.
769
+ * This is called each time a new connection is opened.
770
+ */
771
+ getParams?: () => Promise<unknown>;
772
+ /** Signal to abort the request. */
773
+ signal?: AbortSignal;
774
+ }
1072
775
  /**
1073
- * A function that unsubscribes from an event.
1074
- *
1075
- * @typedef {Function} EventUnsubscribe
776
+ * Options for getting a actor by ID.
777
+ * @typedef {QueryOptions} GetWithIdOptions
1076
778
  */
1077
- type EventUnsubscribe = () => void;
779
+ interface GetWithIdOptions extends QueryOptions {
780
+ }
1078
781
  /**
1079
- * A function that handles connection errors.
1080
- *
1081
- * @typedef {Function} ActorErrorCallback
782
+ * Options for getting a actor.
783
+ * @typedef {QueryOptions} GetOptions
1082
784
  */
1083
- type ActorErrorCallback = (error: RivetError) => void;
785
+ interface GetOptions extends QueryOptions {
786
+ }
1084
787
  /**
1085
- * A callback for connection state changes.
1086
- *
1087
- * @typedef {Function} ConnectionStateCallback
788
+ * Options for getting or creating a actor.
789
+ * @typedef {QueryOptions} GetOrCreateOptions
790
+ * @property {string} [createInRegion] - Region to create the actor in if it doesn't exist.
1088
791
  */
1089
- type ConnectionStateCallback = () => void;
792
+ interface GetOrCreateOptions extends QueryOptions {
793
+ /** Region to create the actor in if it doesn't exist. */
794
+ createInRegion?: string;
795
+ /** Input data to pass to the actor. */
796
+ createWithInput?: unknown;
797
+ }
1090
798
  /**
1091
- * A callback for connection status changes.
1092
- *
1093
- * @typedef {Function} StatusChangeCallback
799
+ * Options for creating a actor.
800
+ * @typedef {QueryOptions} CreateOptions
801
+ * @property {string} [region] - The region to create the actor in.
1094
802
  */
1095
- type StatusChangeCallback = (status: ActorConnStatus) => void;
1096
- declare const CONNECT_SYMBOL: unique symbol;
803
+ interface CreateOptions extends QueryOptions {
804
+ /** The region to create the actor in. */
805
+ region?: string;
806
+ /** Input data to pass to the actor. */
807
+ input?: unknown;
808
+ }
1097
809
  /**
1098
- * Provides underlying functions for {@link ActorConn}. See {@link ActorConn} for using type-safe remote procedure calls.
1099
- *
1100
- * @see {@link ActorConn}
810
+ * Represents a region to connect to.
811
+ * @typedef {Object} Region
812
+ * @property {string} id - The region ID.
813
+ * @property {string} name - The region name.
814
+ * @see {@link https://rivet.dev/docs/edge|Edge Networking}
815
+ * @see {@link https://rivet.dev/docs/regions|Available Regions}
1101
816
  */
1102
- declare class ActorConnRaw {
1103
- #private;
1104
- /**
1105
- * Do not call this directly.
1106
- *
1107
- * Creates an instance of ActorConnRaw.
1108
- *
1109
- * @protected
1110
- */
1111
- constructor(client: ClientRaw, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState);
1112
- send(name: string, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
1113
- send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
1114
- /**
1115
- * Call a raw action connection. See {@link ActorConn} for type-safe action calls.
1116
- *
1117
- * @see {@link ActorConn}
1118
- * @template Args - The type of arguments to pass to the action function.
1119
- * @template Response - The type of the response returned by the action function.
1120
- * @param {string} name - The name of the action function to call.
1121
- * @param {...Args} args - The arguments to pass to the action function.
1122
- * @returns {Promise<Response>} - A promise that resolves to the response of the action function.
1123
- */
1124
- action<Args extends Array<unknown> = unknown[], Response = unknown>(opts: {
1125
- name: string;
1126
- args: Args;
1127
- signal?: AbortSignal;
1128
- }): Promise<Response>;
1129
- /**
1130
- * Do not call this directly.
1131
- * Establishes a connection to the server using the specified endpoint & encoding & driver.
1132
- *
1133
- * @protected
1134
- */
1135
- [CONNECT_SYMBOL](): void;
1136
- /**
1137
- * Subscribes to an event that will happen repeatedly.
1138
- *
1139
- * @template Args - The type of arguments the event callback will receive.
1140
- * @param {string} eventName - The name of the event to subscribe to.
1141
- * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
1142
- * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
1143
- * @see {@link https://rivet.dev/docs/events|Events Documentation}
1144
- */
1145
- on<Args extends Array<unknown> = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe;
817
+ interface Region {
1146
818
  /**
1147
- * Subscribes to an event that will be triggered only once.
1148
- *
1149
- * @template Args - The type of arguments the event callback will receive.
1150
- * @param {string} eventName - The name of the event to subscribe to.
1151
- * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
1152
- * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
1153
- * @see {@link https://rivet.dev/docs/events|Events Documentation}
819
+ * The region slug.
1154
820
  */
1155
- once<Args extends Array<unknown> = unknown[]>(eventName: string, callback: (...args: Args) => void): EventUnsubscribe;
821
+ id: string;
1156
822
  /**
1157
- * Subscribes to connection errors.
1158
- *
1159
- * @param {ActorErrorCallback} callback - The callback function to execute when a connection error occurs.
1160
- * @returns {() => void} - A function to unsubscribe from the error handler.
823
+ * The human-friendly region name.
1161
824
  */
1162
- onError(callback: ActorErrorCallback): () => void;
825
+ name: string;
826
+ }
827
+ declare const ACTOR_CONNS_SYMBOL: unique symbol;
828
+ declare const CREATE_ACTOR_CONN_PROXY: unique symbol;
829
+ /**
830
+ * Client for managing & connecting to actors.
831
+ *
832
+ * @template A The actors map type that defines the available actors.
833
+ * @see {@link https://rivet.dev/docs/manage|Create & Manage Actors}
834
+ */
835
+ declare class ClientRaw {
836
+ #private;
837
+ [ACTOR_CONNS_SYMBOL]: Set<ActorConnRaw>;
1163
838
  /**
1164
- * Returns the current connection status.
1165
- *
1166
- * @returns {ActorConnStatus} - The current connection status.
839
+ * Creates an instance of Client.
1167
840
  */
1168
- get connStatus(): ActorConnStatus;
841
+ constructor(driver: EngineControlClient, encoding: Encoding | undefined);
1169
842
  /**
1170
- * Returns whether the connection is currently open.
843
+ * Gets a stateless handle to a actor by its ID.
1171
844
  *
1172
- * @deprecated Use `connStatus` instead.
1173
- * @returns {boolean} - True if the connection is open, false otherwise.
845
+ * @template AD The actor class that this handle is for.
846
+ * @param {string} name - The name of the actor.
847
+ * @param {string} actorId - The ID of the actor.
848
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
849
+ * @returns {ActorHandle<AD>} - A handle to the actor.
1174
850
  */
1175
- get isConnected(): boolean;
851
+ getForId<AD extends AnyActorDefinition>(name: string, actorId: string, opts?: GetWithIdOptions): ActorHandle<AD>;
1176
852
  /**
1177
- * Subscribes to connection open events.
1178
- *
1179
- * This is called when the WebSocket connection is established and the Init message is received.
853
+ * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
1180
854
  *
1181
- * @param {ConnectionStateCallback} callback - The callback function to execute when the connection opens.
1182
- * @returns {() => void} - A function to unsubscribe from the open handler.
855
+ * @template AD The actor class that this handle is for.
856
+ * @param {string} name - The name of the actor.
857
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
858
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
859
+ * @returns {ActorHandle<AD>} - A handle to the actor.
1183
860
  */
1184
- onOpen(callback: ConnectionStateCallback): () => void;
861
+ get<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: GetWithIdOptions): ActorHandle<AD>;
1185
862
  /**
1186
- * Subscribes to connection close events.
1187
- *
1188
- * This is called when the WebSocket connection is closed. The connection will automatically
1189
- * attempt to reconnect unless disposed.
863
+ * Gets a stateless handle to a actor by its key, creating it if necessary.
1190
864
  *
1191
- * @param {ConnectionStateCallback} callback - The callback function to execute when the connection closes.
1192
- * @returns {() => void} - A function to unsubscribe from the close handler.
865
+ * @template AD The actor class that this handle is for.
866
+ * @param {string} name - The name of the actor.
867
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
868
+ * @param {GetOptions} [opts] - Options for getting the actor.
869
+ * @returns {ActorHandle<AD>} - A handle to the actor.
1193
870
  */
1194
- onClose(callback: ConnectionStateCallback): () => void;
871
+ getOrCreate<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: GetOrCreateOptions): ActorHandle<AD>;
1195
872
  /**
1196
- * Subscribes to connection status changes.
1197
- *
1198
- * This is called whenever the connection status changes between Disconnected, Connecting, and Connected.
873
+ * Creates a new actor with the provided key and returns a stateless handle to it.
874
+ * Resolves the actor ID and returns a handle with getForId query.
1199
875
  *
1200
- * @param {StatusChangeCallback} callback - The callback function to execute when the status changes.
1201
- * @returns {() => void} - A function to unsubscribe from the status change handler.
876
+ * @template AD The actor class that this handle is for.
877
+ * @param {string} name - The name of the actor.
878
+ * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
879
+ * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
880
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
1202
881
  */
1203
- onStatusChange(callback: StatusChangeCallback): () => void;
882
+ create<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
883
+ [CREATE_ACTOR_CONN_PROXY]<AD extends AnyActorDefinition>(conn: ActorConnRaw): ActorConn<AD>;
1204
884
  /**
1205
- * Disconnects from the actor.
885
+ * Disconnects from all actors.
1206
886
  *
1207
- * @returns {Promise<void>} A promise that resolves when the socket is gracefully closed.
887
+ * @returns {Promise<void>} A promise that resolves when all connections are closed.
1208
888
  */
1209
889
  dispose(): Promise<void>;
1210
890
  }
1211
891
  /**
1212
- * Connection to a actor. Allows calling actor's remote procedure calls with inferred types. See {@link ActorConnRaw} for underlying methods.
1213
- *
1214
- * @example
1215
- * ```
1216
- * const room = client.connect<ChatRoom>(...etc...);
1217
- * // This calls the action named `sendMessage` on the `ChatRoom` actor.
1218
- * await room.sendMessage('Hello, world!');
1219
- * ```
1220
- *
1221
- * Private methods (e.g. those starting with `_`) are automatically excluded.
1222
- *
1223
- * @template AD The actor class that this connection is for.
1224
- * @see {@link ActorConnRaw}
1225
- */
1226
- type ActorConn<AD extends AnyActorDefinition> = Omit<ActorConnRaw, "send" | "on" | "once"> & ActorDefinitionQueueSend<AD> & ActorDefinitionEventSubscriptions<AD> & ActorDefinitionActions<AD>;
1227
-
1228
- /**
1229
- * Provides underlying functions for stateless {@link ActorHandle} for action calls.
1230
- * Similar to ActorConnRaw but doesn't maintain a connection.
1231
- *
1232
- * @see {@link ActorHandle}
892
+ * Client type with actor accessors.
893
+ * This adds property accessors for actor names to the ClientRaw base class.
894
+ *
895
+ * @template A The actor registry type.
896
+ */
897
+ type Client<A extends Registry<any>> = ClientRaw & {
898
+ [K in keyof ExtractActorsFromRegistry<A>]: ActorAccessor<ExtractActorsFromRegistry<A>[K]>;
899
+ };
900
+
901
+ declare const ACTOR_CONTEXT_INTERNAL_SYMBOL: unique symbol;
902
+ interface ActorLogger {
903
+ level: any;
904
+ fatal: any;
905
+ trace: any;
906
+ silent: any;
907
+ msgPrefix: any;
908
+ debug: any;
909
+ info: any;
910
+ warn: any;
911
+ error: any;
912
+ [key: string]: any;
913
+ }
914
+ type ActorKvValueType = "text" | "arrayBuffer" | "binary";
915
+ type ActorKvKeyType = "text" | "binary";
916
+ type ActorKvValueTypeMap = {
917
+ text: string;
918
+ arrayBuffer: ArrayBuffer;
919
+ binary: Uint8Array;
920
+ };
921
+ type ActorKvKeyTypeMap = {
922
+ text: string;
923
+ binary: Uint8Array;
924
+ };
925
+ type ActorKvValueOptions<T extends ActorKvValueType = "text"> = {
926
+ type?: T;
927
+ };
928
+ type ActorKvListOptions<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text"> = ActorKvValueOptions<T> & {
929
+ keyType?: K;
930
+ reverse?: boolean;
931
+ limit?: number;
932
+ };
933
+ type ActorClientFor<T> = T extends Registry<any> ? Client<T> : T;
934
+ interface ActorKv {
935
+ get<T extends ActorKvValueType = "text">(key: Uint8Array | string, options?: ActorKvValueOptions<T>): Promise<ActorKvValueTypeMap[T] | null>;
936
+ put<T extends ActorKvValueType = "text">(key: Uint8Array | string, value: Uint8Array | string | ArrayBuffer, options?: ActorKvValueOptions<T>): Promise<void>;
937
+ delete(key: Uint8Array | string): Promise<void>;
938
+ batchPut(entries: [Uint8Array, Uint8Array][]): Promise<void>;
939
+ batchGet(keys: Uint8Array[]): Promise<(Uint8Array | null)[]>;
940
+ batchDelete(keys: Uint8Array[]): Promise<void>;
941
+ deleteRange(start: Uint8Array, end: Uint8Array): Promise<void>;
942
+ listPrefix<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text">(prefix: Uint8Array | string, options?: ActorKvListOptions<T, K>): Promise<Array<[ActorKvKeyTypeMap[K], ActorKvValueTypeMap[T]]>>;
943
+ listRange<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text">(start: Uint8Array | string, end: Uint8Array | string, options?: ActorKvListOptions<T, K>): Promise<Array<[ActorKvKeyTypeMap[K], ActorKvValueTypeMap[T]]>>;
944
+ list<T extends ActorKvValueType = "text", K extends ActorKvKeyType = "text">(prefix: Uint8Array | string, options?: ActorKvListOptions<T, K>): Promise<Array<[ActorKvKeyTypeMap[K], ActorKvValueTypeMap[T]]>>;
945
+ [key: string]: any;
946
+ }
947
+ interface ActorSql {
948
+ exec(sql: string, callback?: (row: unknown[], columns: string[]) => void): Promise<void>;
949
+ run(sql: string, params?: unknown[] | Record<string, unknown>): Promise<void>;
950
+ query(sql: string, params?: unknown[] | Record<string, unknown>): Promise<{
951
+ columns: string[];
952
+ rows: unknown[][];
953
+ }>;
954
+ [key: string]: any;
955
+ }
956
+ interface ActorSchedule {
957
+ after(duration: number, action: string, ...args: unknown[]): Promise<void>;
958
+ at(timestamp: number, action: string, ...args: unknown[]): Promise<void>;
959
+ [key: string]: any;
960
+ }
961
+ type QueueMessageOf<Name extends string, Body> = {
962
+ id: number | bigint;
963
+ name: Name;
964
+ body: Body;
965
+ createdAt: number;
966
+ [key: string]: unknown;
967
+ };
968
+ type QueueName<TQueues extends QueueSchemaConfig> = keyof TQueues & string;
969
+ type QueueFilterName<TQueues extends QueueSchemaConfig> = keyof TQueues extends never ? string : QueueName<TQueues>;
970
+ type QueueMessageForName<TQueues extends QueueSchemaConfig, TName extends QueueFilterName<TQueues>> = keyof TQueues extends never ? QueueMessageOf<string, unknown> : TName extends QueueName<TQueues> ? QueueMessageOf<TName, InferSchemaMap<TQueues>[TName]> : never;
971
+ type QueueCompletionResultForName<TQueues extends QueueSchemaConfig, TName extends QueueFilterName<TQueues>> = keyof TQueues extends never ? unknown | undefined : TName extends QueueName<TQueues> ? InferQueueCompleteMap<TQueues>[TName] | undefined : unknown | undefined;
972
+ interface QueueNextOptions<TName extends string = string, TCompletable extends boolean = boolean> {
973
+ names?: readonly TName[];
974
+ timeout?: number;
975
+ signal?: AbortSignal;
976
+ completable?: TCompletable;
977
+ }
978
+ interface QueueNextBatchOptions<TName extends string = string, TCompletable extends boolean = boolean> {
979
+ names?: readonly TName[];
980
+ count?: number;
981
+ timeout?: number;
982
+ signal?: AbortSignal;
983
+ completable?: TCompletable;
984
+ }
985
+ interface QueueWaitOptions<TCompletable extends boolean = boolean> {
986
+ timeout?: number;
987
+ signal?: AbortSignal;
988
+ completable?: TCompletable;
989
+ }
990
+ interface QueueEnqueueAndWaitOptions {
991
+ timeout?: number;
992
+ signal?: AbortSignal;
993
+ }
994
+ interface QueueTryNextOptions<TName extends string = string, TCompletable extends boolean = boolean> {
995
+ names?: readonly TName[];
996
+ completable?: TCompletable;
997
+ }
998
+ interface QueueTryNextBatchOptions<TName extends string = string, TCompletable extends boolean = boolean> {
999
+ names?: readonly TName[];
1000
+ count?: number;
1001
+ completable?: TCompletable;
1002
+ }
1003
+ interface QueueIterOptions<TName extends string = string, TCompletable extends boolean = boolean> {
1004
+ names?: readonly TName[];
1005
+ signal?: AbortSignal;
1006
+ completable?: TCompletable;
1007
+ }
1008
+ interface ActorQueue<TQueues extends QueueSchemaConfig = Record<never, never>> {
1009
+ send<TName extends QueueFilterName<TQueues>>(name: TName, body: QueueMessageForName<TQueues, TName>["body"]): Promise<any>;
1010
+ next<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueNextOptions<TName, TCompletable>): Promise<any>;
1011
+ nextBatch<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueNextBatchOptions<TName, TCompletable>): Promise<any[]>;
1012
+ waitForNames<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(names: readonly TName[], opts?: QueueWaitOptions<TCompletable>): Promise<any>;
1013
+ enqueueAndWait<const TName extends QueueFilterName<TQueues>>(name: TName, body: QueueMessageForName<TQueues, TName>["body"], opts?: QueueEnqueueAndWaitOptions): Promise<QueueCompletionResultForName<TQueues, TName>>;
1014
+ tryNext<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueTryNextOptions<TName, TCompletable>): Promise<any>;
1015
+ tryNextBatch<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueTryNextBatchOptions<TName, TCompletable>): Promise<any[]>;
1016
+ iter<const TName extends QueueFilterName<TQueues>, const TCompletable extends boolean = false>(opts?: QueueIterOptions<TName, TCompletable>): AsyncIterable<any>;
1017
+ [key: string]: any;
1018
+ }
1019
+ interface Conn<TState = unknown, TConnParams = unknown, TConnState = unknown, TVars = unknown, TInput = unknown, TDatabase extends AnyDatabaseProvider = AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
1020
+ id: string;
1021
+ params: TConnParams;
1022
+ state: TConnState;
1023
+ isHibernatable: boolean;
1024
+ send(name: string, ...args: any[]): void;
1025
+ disconnect(reason?: string): Promise<void>;
1026
+ [key: string]: any;
1027
+ }
1028
+ interface ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
1029
+ [ACTOR_CONTEXT_INTERNAL_SYMBOL]?: unknown;
1030
+ state: TState;
1031
+ vars: TVars;
1032
+ readonly kv: ActorKv;
1033
+ readonly sql: ActorSql;
1034
+ readonly db: InferDatabaseClient<TDatabase>;
1035
+ readonly schedule: ActorSchedule;
1036
+ readonly queue: ActorQueue<TQueues>;
1037
+ readonly actorId: string;
1038
+ readonly name: string;
1039
+ readonly key: Array<string | number>;
1040
+ readonly region: string;
1041
+ readonly conns: Map<string, Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>>;
1042
+ readonly log: ActorLogger;
1043
+ readonly abortSignal: AbortSignal;
1044
+ readonly aborted: boolean;
1045
+ readonly request?: Request;
1046
+ readonly preventSleep: boolean;
1047
+ broadcast(name: string, ...args: any[]): void;
1048
+ saveState(opts?: {
1049
+ immediate?: boolean;
1050
+ maxWait?: number;
1051
+ }): Promise<void>;
1052
+ keepAwake<T>(promise: Promise<T>): Promise<T>;
1053
+ waitUntil(promise: Promise<unknown>): void;
1054
+ setPreventSleep(preventSleep: boolean): void;
1055
+ sleep(): void;
1056
+ destroy(): void;
1057
+ client<T = any>(): ActorClientFor<T>;
1058
+ [key: string]: any;
1059
+ }
1060
+ type ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & {
1061
+ conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1062
+ };
1063
+ type BeforeActionResponseContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1064
+ type BeforeConnectContext<TState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, TVars, TInput, TDatabase, TEvents, TQueues>;
1065
+ type ConnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1066
+ type CreateConnStateContext<TState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, TVars, TInput, TDatabase, TEvents, TQueues>;
1067
+ type CreateContext<TState, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, unknown, unknown, unknown, TInput, TDatabase, TEvents, TQueues>;
1068
+ type CreateVarsContext<TState, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = CreateContext<TState, TInput, TDatabase, TEvents, TQueues>;
1069
+ type DestroyContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1070
+ type DisconnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1071
+ type RequestContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1072
+ type RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActorContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1073
+ type SleepContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1074
+ type StateChangeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1075
+ type WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1076
+ type MigrateContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1077
+ type WebSocketContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1078
+ type InspectorUnsubscribe = () => void;
1079
+ declare const RunConfigSchema: z.ZodObject<{
1080
+ name: z.ZodOptional<z.ZodString>;
1081
+ icon: z.ZodOptional<z.ZodString>;
1082
+ run: z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>;
1083
+ inspector: z.ZodOptional<z.ZodOptional<z.ZodObject<{
1084
+ workflow: z.ZodOptional<z.ZodObject<{
1085
+ getHistory: z.ZodCustom<() => unknown, () => unknown>;
1086
+ onHistoryUpdated: z.ZodOptional<z.ZodCustom<(listener: (history: unknown) => void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>;
1087
+ replayFromStep: z.ZodOptional<z.ZodCustom<(entryId?: string) => Promise<unknown>, (entryId?: string) => Promise<unknown>>>;
1088
+ }, z.core.$strip>>;
1089
+ }, z.core.$strip>>>;
1090
+ }, z.core.$strip>;
1091
+ type RunConfigRuntime = z.infer<typeof RunConfigSchema>;
1092
+ type RunConfig<TState = unknown, TConnParams = unknown, TConnState = unknown, TVars = unknown, TInput = unknown, TDatabase extends AnyDatabaseProvider = AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = Omit<RunConfigRuntime, "run"> & {
1093
+ run: (c: RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
1094
+ };
1095
+ declare const ActorConfigSchema: z.ZodObject<{
1096
+ onCreate: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1097
+ onDestroy: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1098
+ onMigrate: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1099
+ onWake: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1100
+ onSleep: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1101
+ run: z.ZodOptional<z.ZodUnion<readonly [z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>, z.ZodObject<{
1102
+ name: z.ZodOptional<z.ZodString>;
1103
+ icon: z.ZodOptional<z.ZodString>;
1104
+ run: z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>;
1105
+ inspector: z.ZodOptional<z.ZodOptional<z.ZodObject<{
1106
+ workflow: z.ZodOptional<z.ZodObject<{
1107
+ getHistory: z.ZodCustom<() => unknown, () => unknown>;
1108
+ onHistoryUpdated: z.ZodOptional<z.ZodCustom<(listener: (history: unknown) => void) => InspectorUnsubscribe, (listener: (history: unknown) => void) => InspectorUnsubscribe>>;
1109
+ replayFromStep: z.ZodOptional<z.ZodCustom<(entryId?: string) => Promise<unknown>, (entryId?: string) => Promise<unknown>>>;
1110
+ }, z.core.$strip>>;
1111
+ }, z.core.$strip>>>;
1112
+ }, z.core.$strip>]>>;
1113
+ onStateChange: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1114
+ onBeforeConnect: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1115
+ onConnect: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1116
+ onDisconnect: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1117
+ onBeforeActionResponse: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1118
+ onRequest: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1119
+ onWebSocket: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1120
+ actions: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>>;
1121
+ actionInputSchemas: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
1122
+ connParamsSchema: z.ZodOptional<z.ZodAny>;
1123
+ events: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
1124
+ queues: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
1125
+ state: z.ZodOptional<z.ZodAny>;
1126
+ createState: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1127
+ connState: z.ZodOptional<z.ZodAny>;
1128
+ createConnState: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1129
+ vars: z.ZodOptional<z.ZodAny>;
1130
+ db: z.ZodOptional<z.ZodAny>;
1131
+ createVars: z.ZodOptional<z.ZodCustom<(...args: unknown[]) => unknown, (...args: unknown[]) => unknown>>;
1132
+ options: z.ZodPrefault<z.ZodObject<{
1133
+ name: z.ZodOptional<z.ZodString>;
1134
+ icon: z.ZodOptional<z.ZodString>;
1135
+ canHibernateWebSocket: z.ZodDefault<z.ZodUnion<readonly [z.ZodBoolean, z.ZodCustom<(request: Request) => boolean, (request: Request) => boolean>]>>;
1136
+ createVarsTimeout: z.ZodDefault<z.ZodNumber>;
1137
+ createConnStateTimeout: z.ZodDefault<z.ZodNumber>;
1138
+ onBeforeConnectTimeout: z.ZodDefault<z.ZodNumber>;
1139
+ onConnectTimeout: z.ZodDefault<z.ZodNumber>;
1140
+ onMigrateTimeout: z.ZodDefault<z.ZodNumber>;
1141
+ sleepGracePeriod: z.ZodOptional<z.ZodNumber>;
1142
+ onDestroyTimeout: z.ZodDefault<z.ZodNumber>;
1143
+ stateSaveInterval: z.ZodDefault<z.ZodNumber>;
1144
+ actionTimeout: z.ZodDefault<z.ZodNumber>;
1145
+ waitUntilTimeout: z.ZodDefault<z.ZodNumber>;
1146
+ connectionLivenessTimeout: z.ZodDefault<z.ZodNumber>;
1147
+ connectionLivenessInterval: z.ZodDefault<z.ZodNumber>;
1148
+ noSleep: z.ZodDefault<z.ZodBoolean>;
1149
+ sleepTimeout: z.ZodDefault<z.ZodNumber>;
1150
+ maxQueueSize: z.ZodDefault<z.ZodNumber>;
1151
+ maxQueueMessageSize: z.ZodDefault<z.ZodNumber>;
1152
+ preloadMaxWorkflowBytes: z.ZodOptional<z.ZodNumber>;
1153
+ preloadMaxConnectionsBytes: z.ZodOptional<z.ZodNumber>;
1154
+ }, z.core.$strict>>;
1155
+ }, z.core.$strict>;
1156
+ type CreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
1157
+ state: TState;
1158
+ } | {
1159
+ createState: (c: CreateContext<TState, TInput, TDatabase, TEvents, TQueues>, input: TInput) => TState | Promise<TState>;
1160
+ } | Record<never, never>;
1161
+ type CreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
1162
+ connState: TConnState;
1163
+ } | {
1164
+ createConnState: (c: CreateConnStateContext<TState, TVars, TInput, TDatabase, TEvents, TQueues>, params: TConnParams) => TConnState | Promise<TConnState>;
1165
+ } | Record<never, never>;
1166
+ /**
1167
+ * @experimental
1233
1168
  */
1234
- declare class ActorHandleRaw {
1235
- #private;
1169
+ type CreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig> = {
1236
1170
  /**
1237
- * Do not call this directly.
1238
- *
1239
- * Creates an instance of ActorHandleRaw.
1240
- *
1241
- * @protected
1171
+ * @experimental
1242
1172
  */
1243
- constructor(client: any, driver: EngineControlClient, params: unknown, getParams: (() => Promise<unknown>) | undefined, encoding: Encoding, actorResolutionState: ActorResolutionState);
1244
- send(name: string, body: unknown, options: QueueSendWaitOptions): Promise<QueueSendResult>;
1245
- send(name: string, body: unknown, options?: QueueSendNoWaitOptions): Promise<void>;
1173
+ vars: TVars;
1174
+ } | {
1246
1175
  /**
1247
- * Call a raw action. This method sends an HTTP request to invoke the named action.
1248
- *
1249
- * @see {@link ActorHandle}
1250
- * @template Args - The type of arguments to pass to the action function.
1251
- * @template Response - The type of the response returned by the action function.
1176
+ * @experimental
1252
1177
  */
1253
- action<Args extends Array<unknown> = unknown[], Response = unknown>(opts: {
1254
- name: string;
1255
- args: Args;
1256
- signal?: AbortSignal;
1257
- }): Promise<Response>;
1178
+ createVars: (c: CreateVarsContext<TState, TInput, TDatabase, TEvents, TQueues>, driverCtx: any) => TVars | Promise<TVars>;
1179
+ } | Record<never, never>;
1180
+ interface Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> {
1181
+ [Action: string]: (c: ActionContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, ...args: any[]) => any;
1182
+ }
1183
+ interface BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig, TQueues extends QueueSchemaConfig, TActions extends Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>> {
1258
1184
  /**
1259
- * Establishes a persistent connection to the actor.
1185
+ * Called when the actor is first initialized.
1260
1186
  *
1261
- * @template AD The actor class that this connection is for.
1262
- * @returns {ActorConn<AD>} A connection to the actor.
1187
+ * Use this hook to initialize your actor's state.
1188
+ * This is called before any other lifecycle hooks.
1263
1189
  */
1264
- connect(params?: unknown): ActorConn<AnyActorDefinition>;
1190
+ onCreate?: (c: CreateContext<TState, TInput, TDatabase, TEvents, TQueues>, input: TInput) => void | Promise<void>;
1265
1191
  /**
1266
- * Fetches a resource from this actor via the /request endpoint. This is a
1267
- * convenience wrapper around the raw HTTP API.
1192
+ * Called when the actor is destroyed.
1268
1193
  */
1269
- fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
1194
+ onDestroy?: (c: DestroyContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
1270
1195
  /**
1271
- * Opens a raw WebSocket connection to this actor.
1196
+ * Called on every actor start after persisted state loads and before onWake.
1197
+ *
1198
+ * Use this hook for repeatable schema migrations or other startup work that
1199
+ * must run on both first boot and wake.
1272
1200
  */
1273
- webSocket(path?: string, protocols?: string | string[]): Promise<any>;
1201
+ onMigrate?: (c: MigrateContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, isNew: boolean) => void | Promise<void>;
1274
1202
  /**
1275
- * Resolves the actor to get its unique actor ID.
1203
+ * Called when the actor is started and ready to receive connections and action.
1204
+ *
1205
+ * Use this hook to initialize resources needed for the actor's operation
1206
+ * (timers, external connections, etc.)
1207
+ *
1208
+ * @returns Void or a Promise that resolves when startup is complete
1276
1209
  */
1277
- resolve(): Promise<string>;
1210
+ onWake?: (c: WakeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
1278
1211
  /**
1279
- * Returns the raw URL for routing traffic to the actor.
1212
+ * Called when the actor is stopping or sleeping.
1213
+ *
1214
+ * Use this hook to clean up resources, save state, or perform
1215
+ * any shutdown operations before the actor sleeps or stops.
1216
+ *
1217
+ * Not supported on all platforms.
1218
+ *
1219
+ * @returns Void or a Promise that resolves when shutdown is complete
1280
1220
  */
1281
- getGatewayUrl(): Promise<string>;
1282
- reload(): Promise<void>;
1283
- }
1284
- /**
1285
- * Stateless handle to a actor. Allows calling actor's remote procedure calls with inferred types
1286
- * without establishing a persistent connection.
1287
- *
1288
- * @example
1289
- * ```
1290
- * const room = client.get<ChatRoom>(...etc...);
1291
- * // This calls the action named `sendMessage` on the `ChatRoom` actor without a connection.
1292
- * await room.sendMessage('Hello, world!');
1293
- * ```
1294
- *
1295
- * Private methods (e.g. those starting with `_`) are automatically excluded.
1296
- *
1297
- * @template AD The actor class that this handle is for.
1298
- * @see {@link ActorHandleRaw}
1299
- */
1300
- type ActorHandle<AD extends AnyActorDefinition> = Omit<ActorHandleRaw, "connect" | "send"> & {
1301
- connect(params?: unknown): ActorConn<AD>;
1302
- resolve(): Promise<string>;
1303
- } & ActorDefinitionQueueSend<AD> & ActorDefinitionActions<AD>;
1304
-
1305
- declare const ClientConfigSchema: z$2.ZodPipe<z$2.ZodObject<{
1306
- endpoint: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string, string | undefined>>;
1307
- token: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
1308
- namespace: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
1309
- poolName: z$2.ZodDefault<z$2.ZodString>;
1310
- encoding: z$2.ZodDefault<z$2.ZodEnum<{
1311
- json: "json";
1312
- cbor: "cbor";
1313
- bare: "bare";
1314
- }>>;
1315
- headers: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodRecord<z$2.ZodString, z$2.ZodString>>>;
1316
- getUpgradeWebSocket: z$2.ZodOptional<z$2.ZodCustom<GetUpgradeWebSocket, GetUpgradeWebSocket>>;
1317
- disableMetadataLookup: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodBoolean>>;
1318
- maxInputSize: z$2.ZodDefault<z$2.ZodNumber>;
1319
- devtools: z$2.ZodDefault<z$2.ZodBoolean>;
1320
- }, z$2.core.$strip>, z$2.ZodTransform<{
1321
- endpoint: string | undefined;
1322
- namespace: string;
1323
- token: string | undefined;
1324
- poolName: string;
1325
- encoding: "json" | "cbor" | "bare";
1326
- headers: Record<string, string>;
1327
- disableMetadataLookup: boolean;
1328
- maxInputSize: number;
1329
- devtools: boolean;
1330
- getUpgradeWebSocket?: GetUpgradeWebSocket | undefined;
1331
- }, {
1332
- endpoint: string;
1333
- token: string | undefined;
1334
- namespace: string | undefined;
1335
- poolName: string;
1336
- encoding: "json" | "cbor" | "bare";
1337
- headers: Record<string, string>;
1338
- disableMetadataLookup: boolean;
1339
- maxInputSize: number;
1340
- devtools: boolean;
1341
- getUpgradeWebSocket?: GetUpgradeWebSocket | undefined;
1342
- }>>;
1343
- type ClientConfigInput = z$2.input<typeof ClientConfigSchema>;
1344
-
1345
- /** Extract the actor registry from the registry definition. */
1346
- type ExtractActorsFromRegistry<A extends Registry<any>> = A extends Registry<infer Actors> ? Actors : never;
1347
- /** Extract the registry definition from the client. */
1348
- type ExtractRegistryFromClient<C extends Client<Registry<{}>>> = C extends Client<infer A> ? A : never;
1349
- /**
1350
- * Represents a actor accessor that provides methods to interact with a specific actor.
1351
- */
1352
- interface ActorAccessor<AD extends AnyActorDefinition> {
1221
+ onSleep?: (c: SleepContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
1353
1222
  /**
1354
- * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
1355
- * The actor name is automatically injected from the property accessor.
1223
+ * Called after the actor starts up. Does not block actor startup.
1356
1224
  *
1357
- * Each operation resolves the current actor for the key before sending the
1358
- * request.
1225
+ * Use this for background tasks like:
1226
+ * - Reading from queues in a loop
1227
+ * - Tick loops for periodic work
1228
+ * - Custom workflow logic
1359
1229
  *
1360
- * @template AD The actor class that this handle is for.
1361
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1362
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1363
- * @returns {ActorHandle<AD>} - A handle to the actor.
1230
+ * **Important:** The actor may go to sleep at any time during the `run`
1231
+ * handler. Use `c.setPreventSleep(true)` while work is active, then clear
1232
+ * it with `c.setPreventSleep(false)` once the actor can sleep again.
1233
+ * `setPreventSleep` blocks idle sleep until it is cleared. If shutdown has
1234
+ * already started, RivetKit waits for `preventSleep` to clear within the
1235
+ * same graceful shutdown window controlled by `sleepGracePeriod`.
1236
+ *
1237
+ * The handler receives an abort signal via `c.abortSignal` and a
1238
+ * `c.aborted` alias for loop checks. Use these to gracefully exit.
1239
+ *
1240
+ * If this handler exits, the actor will follow the normal idle sleep timeout
1241
+ * once it becomes idle.
1242
+ * If this handler throws, the actor logs the error and then sleeps once it
1243
+ * becomes idle.
1244
+ * Call `c.destroy()` explicitly if a run handler should destroy the actor.
1245
+ *
1246
+ * Can be either a function or a RunConfig object with optional name/icon metadata.
1247
+ *
1248
+ * @returns Void or a Promise.
1364
1249
  */
1365
- get(key?: string | string[], opts?: GetWithIdOptions): ActorHandle<AD>;
1250
+ run?: ((c: RunContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>) | RunConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>;
1366
1251
  /**
1367
- * Gets a stateless handle to a actor by its key, creating it if necessary.
1368
- * The actor name is automatically injected from the property accessor.
1252
+ * Called when the actor's state changes.
1369
1253
  *
1370
- * Each operation resolves the current actor for the key before sending the
1371
- * request.
1254
+ * Use this hook to react to state changes, such as updating
1255
+ * external systems or triggering events.
1372
1256
  *
1373
- * @template AD The actor class that this handle is for.
1374
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1375
- * @param {GetOptions} [opts] - Options for getting the actor.
1376
- * @returns {ActorHandle<AD>} - A handle to the actor.
1257
+ * State changes made within this hook will NOT trigger
1258
+ * another onStateChange call, preventing infinite recursion.
1259
+ *
1260
+ * @param newState The updated state
1377
1261
  */
1378
- getOrCreate(key?: string | string[], opts?: GetOrCreateOptions): ActorHandle<AD>;
1262
+ onStateChange?: (c: StateChangeContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, newState: TState) => void;
1379
1263
  /**
1380
- * Gets a stateless handle to a actor by its ID.
1264
+ * Called before a client connects to the actor.
1381
1265
  *
1382
- * If the actor is destroyed, operations will throw without retrying since
1383
- * there is no key to re-resolve.
1266
+ * Use this hook to determine if a connection should be accepted
1267
+ * and to initialize connection-specific state.
1384
1268
  *
1385
- * @template AD The actor class that this handle is for.
1386
- * @param {string} actorId - The ID of the actor.
1387
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1388
- * @returns {ActorHandle<AD>} - A handle to the actor.
1269
+ * @param opts Connection parameters including client-provided data
1270
+ * @returns The initial connection state or a Promise that resolves to it
1271
+ * @throws Throw an error to reject the connection
1389
1272
  */
1390
- getForId(actorId: string, opts?: GetWithIdOptions): ActorHandle<AD>;
1273
+ onBeforeConnect?: (c: BeforeConnectContext<TState, TVars, TInput, TDatabase, TEvents, TQueues>, params: TConnParams) => void | Promise<void>;
1391
1274
  /**
1392
- * Creates a new actor with the name automatically injected from the property accessor,
1393
- * and returns a stateless handle to it with the actor ID resolved.
1275
+ * Called when a client successfully connects to the actor.
1394
1276
  *
1395
- * If the actor is destroyed, operations will throw without retrying since
1396
- * creation is a one-shot operation.
1277
+ * Use this hook to perform actions when a connection is established,
1278
+ * such as sending initial data or updating the actor's state.
1397
1279
  *
1398
- * @template AD The actor class that this handle is for.
1399
- * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
1400
- * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
1401
- * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
1280
+ * @param conn The connection object
1281
+ * @returns Void or a Promise that resolves when connection handling is complete
1402
1282
  */
1403
- create(key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
1404
- }
1405
- /**
1406
- * Options for querying actors.
1407
- * @typedef {Object} QueryOptions
1408
- * @property {unknown} [parameters] - Parameters to pass to the connection.
1409
- */
1410
- interface QueryOptions {
1411
- /** Parameters to pass to the connection. */
1412
- params?: unknown;
1283
+ onConnect?: (c: ConnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
1413
1284
  /**
1414
- * Lazily resolves connection parameters for `.connect()` and `.webSocket()`.
1415
- * This is called each time a new connection is opened.
1285
+ * Called when a client disconnects from the actor.
1286
+ *
1287
+ * Use this hook to clean up resources associated with the connection
1288
+ * or update the actor's state.
1289
+ *
1290
+ * @param conn The connection that is being closed
1291
+ * @returns Void or a Promise that resolves when disconnect handling is complete
1416
1292
  */
1417
- getParams?: () => Promise<unknown>;
1418
- /** Signal to abort the request. */
1419
- signal?: AbortSignal;
1420
- }
1421
- /**
1422
- * Options for getting a actor by ID.
1423
- * @typedef {QueryOptions} GetWithIdOptions
1424
- */
1425
- interface GetWithIdOptions extends QueryOptions {
1426
- }
1427
- /**
1428
- * Options for getting a actor.
1429
- * @typedef {QueryOptions} GetOptions
1430
- */
1431
- interface GetOptions extends QueryOptions {
1432
- }
1433
- /**
1434
- * Options for getting or creating a actor.
1435
- * @typedef {QueryOptions} GetOrCreateOptions
1436
- * @property {string} [createInRegion] - Region to create the actor in if it doesn't exist.
1437
- */
1438
- interface GetOrCreateOptions extends QueryOptions {
1439
- /** Region to create the actor in if it doesn't exist. */
1440
- createInRegion?: string;
1441
- /** Input data to pass to the actor. */
1442
- createWithInput?: unknown;
1443
- }
1444
- /**
1445
- * Options for creating a actor.
1446
- * @typedef {QueryOptions} CreateOptions
1447
- * @property {string} [region] - The region to create the actor in.
1448
- */
1449
- interface CreateOptions extends QueryOptions {
1450
- /** The region to create the actor in. */
1451
- region?: string;
1452
- /** Input data to pass to the actor. */
1453
- input?: unknown;
1454
- }
1455
- /**
1456
- * Represents a region to connect to.
1457
- * @typedef {Object} Region
1458
- * @property {string} id - The region ID.
1459
- * @property {string} name - The region name.
1460
- * @see {@link https://rivet.dev/docs/edge|Edge Networking}
1461
- * @see {@link https://rivet.dev/docs/regions|Available Regions}
1462
- */
1463
- interface Region {
1293
+ onDisconnect?: (c: DisconnectContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, conn: Conn<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>) => void | Promise<void>;
1294
+ /**
1295
+ * Called before sending an action response to the client.
1296
+ *
1297
+ * Use this hook to modify or transform the output of an action before it's sent
1298
+ * to the client. This is useful for formatting responses, adding metadata,
1299
+ * or applying transformations to the output.
1300
+ *
1301
+ * @param name The name of the action that was called
1302
+ * @param args The arguments that were passed to the action
1303
+ * @param output The output that will be sent to the client
1304
+ * @returns The modified output to send to the client
1305
+ */
1306
+ onBeforeActionResponse?: <Out>(c: BeforeActionResponseContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, name: string, args: unknown[], output: Out) => Out | Promise<Out>;
1464
1307
  /**
1465
- * The region slug.
1308
+ * Called when a raw HTTP request is made to the actor.
1309
+ *
1310
+ * This handler receives raw HTTP requests made to `/actors/{actorName}/http/*` endpoints.
1311
+ * Use this hook to handle custom HTTP patterns, REST APIs, or other HTTP-based protocols.
1312
+ *
1313
+ * @param c The request context with access to the connection
1314
+ * @param request The raw HTTP request object
1315
+ * @param opts Additional options
1316
+ * @returns A Response object to send back, or void to continue with default routing
1466
1317
  */
1467
- id: string;
1318
+ onRequest?: (c: RequestContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, request: Request) => Response | Promise<Response>;
1468
1319
  /**
1469
- * The human-friendly region name.
1320
+ * Called when a raw WebSocket connection is established to the actor.
1321
+ *
1322
+ * This handler receives WebSocket connections made to `/actors/{actorName}/websocket/*` endpoints.
1323
+ * Use this hook to handle custom WebSocket protocols, binary streams, or other WebSocket-based communication.
1324
+ *
1325
+ * @param c The WebSocket context with access to the connection
1326
+ * @param websocket The actor-facing raw WebSocket connection
1327
+ * @param opts Additional options including the original HTTP upgrade request
1470
1328
  */
1471
- name: string;
1472
- }
1473
- declare const ACTOR_CONNS_SYMBOL: unique symbol;
1474
- declare const CREATE_ACTOR_CONN_PROXY: unique symbol;
1475
- /**
1476
- * Client for managing & connecting to actors.
1477
- *
1478
- * @template A The actors map type that defines the available actors.
1479
- * @see {@link https://rivet.dev/docs/manage|Create & Manage Actors}
1480
- */
1481
- declare class ClientRaw {
1482
- #private;
1483
- [ACTOR_CONNS_SYMBOL]: Set<ActorConnRaw>;
1329
+ onWebSocket?: (c: WebSocketContext<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>, websocket: UniversalWebSocket) => void | Promise<void>;
1330
+ actions?: TActions;
1484
1331
  /**
1485
- * Creates an instance of Client.
1332
+ * Optional schema map for validating action argument tuples in native runtimes.
1486
1333
  */
1487
- constructor(driver: EngineControlClient, encoding: Encoding | undefined);
1334
+ actionInputSchemas?: Record<string, PrimitiveSchema>;
1488
1335
  /**
1489
- * Gets a stateless handle to a actor by its ID.
1490
- *
1491
- * @template AD The actor class that this handle is for.
1492
- * @param {string} name - The name of the actor.
1493
- * @param {string} actorId - The ID of the actor.
1494
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1495
- * @returns {ActorHandle<AD>} - A handle to the actor.
1336
+ * Optional schema for validating connection params in native runtimes.
1496
1337
  */
1497
- getForId<AD extends AnyActorDefinition>(name: string, actorId: string, opts?: GetWithIdOptions): ActorHandle<AD>;
1338
+ connParamsSchema?: PrimitiveSchema;
1498
1339
  /**
1499
- * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
1500
- *
1501
- * @template AD The actor class that this handle is for.
1502
- * @param {string} name - The name of the actor.
1503
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1504
- * @param {GetWithIdOptions} [opts] - Options for getting the actor.
1505
- * @returns {ActorHandle<AD>} - A handle to the actor.
1340
+ * Schema map for events broadcasted by this actor.
1506
1341
  */
1507
- get<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: GetWithIdOptions): ActorHandle<AD>;
1342
+ events?: TEvents;
1508
1343
  /**
1509
- * Gets a stateless handle to a actor by its key, creating it if necessary.
1344
+ * Schema map for queue payloads sent by this actor.
1345
+ */
1346
+ queues?: TQueues;
1347
+ }
1348
+ type ActorDatabaseConfig<TDatabase extends AnyDatabaseProvider> = {
1349
+ /**
1350
+ * @experimental
1351
+ */
1352
+ db: TDatabase;
1353
+ } | Record<never, never>;
1354
+ type ActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase extends AnyDatabaseProvider, TEvents extends EventSchemaConfig = Record<never, never>, TQueues extends QueueSchemaConfig = Record<never, never>> = Omit<z.infer<typeof ActorConfigSchema>, "actions" | "events" | "queues" | "onCreate" | "onDestroy" | "onMigrate" | "onWake" | "onSleep" | "run" | "onStateChange" | "onBeforeConnect" | "onConnect" | "onDisconnect" | "onBeforeActionResponse" | "onRequest" | "onWebSocket" | "state" | "createState" | "connState" | "createConnState" | "vars" | "createVars" | "db"> & BaseActorConfig<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues, Actions<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues>> & CreateState<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & CreateConnState<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & CreateVars<TState, TConnParams, TConnState, TVars, TInput, TDatabase, TEvents, TQueues> & ActorDatabaseConfig<TDatabase>;
1355
+
1356
+ interface BaseActorDefinition<S, CP, CS, V, I, DB extends AnyDatabaseProvider, E extends EventSchemaConfig = Record<never, never>, Q extends QueueSchemaConfig = Record<never, never>, R extends Actions<S, CP, CS, V, I, DB, E, Q> = Actions<S, CP, CS, V, I, DB, E, Q>> {
1357
+ readonly config: ActorConfig<S, CP, CS, V, I, DB, E, Q>;
1358
+ }
1359
+ type AnyActorDefinition = BaseActorDefinition<any, any, any, any, any, any, any, any, any>;
1360
+ declare class ActorDefinition<S, CP, CS, V, I, DB extends AnyDatabaseProvider, E extends EventSchemaConfig = Record<never, never>, Q extends QueueSchemaConfig = Record<never, never>, R extends Actions<S, CP, CS, V, I, DB, E, Q> = Actions<S, CP, CS, V, I, DB, E, Q>> implements BaseActorDefinition<S, CP, CS, V, I, DB, E, Q, R> {
1361
+ #private;
1362
+ constructor(config: ActorConfig<S, CP, CS, V, I, DB, E, Q>);
1363
+ get config(): ActorConfig<S, CP, CS, V, I, DB, E, Q>;
1364
+ }
1365
+
1366
+ declare const ActorsSchema: z$2.ZodRecord<z$2.ZodString, z$2.ZodCustom<BaseActorDefinition<any, any, any, any, any, any, any, any, any>, BaseActorDefinition<any, any, any, any, any, any, any, any, any>>>;
1367
+ type RegistryActors = z$2.infer<typeof ActorsSchema>;
1368
+ declare const RegistryConfigSchema: z$2.ZodPipe<z$2.ZodObject<{
1369
+ use: z$2.ZodRecord<z$2.ZodString, z$2.ZodCustom<AnyActorDefinition, AnyActorDefinition>>;
1370
+ test: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodObject<{
1371
+ enabled: z$2.ZodBoolean;
1372
+ }, z$2.core.$strip>>>;
1373
+ maxIncomingMessageSize: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodNumber>>;
1374
+ maxOutgoingMessageSize: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodNumber>>;
1375
+ noWelcome: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodBoolean>>;
1376
+ logging: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodObject<{
1377
+ baseLogger: z$2.ZodOptional<z$2.ZodCustom<Logger, Logger>>;
1378
+ level: z$2.ZodOptional<z$2.ZodEnum<{
1379
+ error: "error";
1380
+ trace: "trace";
1381
+ fatal: "fatal";
1382
+ warn: "warn";
1383
+ info: "info";
1384
+ debug: "debug";
1385
+ silent: "silent";
1386
+ }>>;
1387
+ }, z$2.core.$strip>>>;
1388
+ endpoint: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
1389
+ token: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
1390
+ namespace: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
1391
+ headers: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodRecord<z$2.ZodString, z$2.ZodString>>>;
1392
+ staticDir: z$2.ZodOptional<z$2.ZodString>;
1393
+ httpBasePath: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodString>>;
1394
+ httpPort: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodNumber>>;
1395
+ httpHost: z$2.ZodOptional<z$2.ZodString>;
1396
+ startEngine: z$2.ZodDefault<z$2.ZodBoolean>;
1397
+ engineVersion: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodString>>;
1398
+ configurePool: z$2.ZodOptional<z$2.ZodOptional<z$2.ZodObject<{
1399
+ name: z$2.ZodOptional<z$2.ZodString>;
1400
+ url: z$2.ZodString;
1401
+ headers: z$2.ZodOptional<z$2.ZodRecord<z$2.ZodString, z$2.ZodString>>;
1402
+ requestLifespan: z$2.ZodOptional<z$2.ZodNumber>;
1403
+ metadata: z$2.ZodOptional<z$2.ZodRecord<z$2.ZodString, z$2.ZodUnknown>>;
1404
+ metadataPollInterval: z$2.ZodOptional<z$2.ZodNumber>;
1405
+ drainOnVersionUpgrade: z$2.ZodOptional<z$2.ZodBoolean>;
1406
+ }, z$2.core.$strip>>>;
1407
+ serverless: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodObject<{
1408
+ basePath: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodString>>;
1409
+ publicEndpoint: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
1410
+ publicToken: z$2.ZodPipe<z$2.ZodOptional<z$2.ZodString>, z$2.ZodTransform<string | undefined, string | undefined>>;
1411
+ }, z$2.core.$strip>>>;
1412
+ envoy: z$2.ZodDefault<z$2.ZodOptional<z$2.ZodObject<{
1413
+ poolName: z$2.ZodDefault<z$2.ZodString>;
1414
+ version: z$2.ZodDefault<z$2.ZodNumber>;
1415
+ totalSlots: z$2.ZodDefault<z$2.ZodNumber>;
1416
+ envoyKey: z$2.ZodOptional<z$2.ZodString>;
1417
+ }, z$2.core.$strip>>>;
1418
+ }, z$2.core.$strip>, z$2.ZodTransform<{
1419
+ endpoint: string | undefined;
1420
+ namespace: string;
1421
+ token: string | undefined;
1422
+ publicEndpoint: string | undefined;
1423
+ publicNamespace: string | undefined;
1424
+ publicToken: string | undefined;
1425
+ serverless: {
1426
+ publicEndpoint: string | undefined;
1427
+ basePath: string;
1428
+ publicToken: string | undefined;
1429
+ };
1430
+ use: Record<string, AnyActorDefinition>;
1431
+ test: {
1432
+ enabled: boolean;
1433
+ };
1434
+ maxIncomingMessageSize: number;
1435
+ maxOutgoingMessageSize: number;
1436
+ noWelcome: boolean;
1437
+ logging: {
1438
+ baseLogger?: Logger | undefined;
1439
+ level?: "error" | "trace" | "fatal" | "warn" | "info" | "debug" | "silent" | undefined;
1440
+ };
1441
+ headers: Record<string, string>;
1442
+ httpBasePath: string;
1443
+ httpPort: number;
1444
+ startEngine: boolean;
1445
+ engineVersion: string;
1446
+ envoy: {
1447
+ poolName: string;
1448
+ version: number;
1449
+ totalSlots: number;
1450
+ envoyKey?: string | undefined;
1451
+ };
1452
+ staticDir?: string | undefined;
1453
+ httpHost?: string | undefined;
1454
+ configurePool?: {
1455
+ url: string;
1456
+ name?: string | undefined;
1457
+ headers?: Record<string, string> | undefined;
1458
+ requestLifespan?: number | undefined;
1459
+ metadata?: Record<string, unknown> | undefined;
1460
+ metadataPollInterval?: number | undefined;
1461
+ drainOnVersionUpgrade?: boolean | undefined;
1462
+ } | undefined;
1463
+ }, {
1464
+ use: Record<string, AnyActorDefinition>;
1465
+ test: {
1466
+ enabled: boolean;
1467
+ };
1468
+ maxIncomingMessageSize: number;
1469
+ maxOutgoingMessageSize: number;
1470
+ noWelcome: boolean;
1471
+ logging: {
1472
+ baseLogger?: Logger | undefined;
1473
+ level?: "error" | "trace" | "fatal" | "warn" | "info" | "debug" | "silent" | undefined;
1474
+ };
1475
+ endpoint: string | undefined;
1476
+ token: string | undefined;
1477
+ namespace: string | undefined;
1478
+ headers: Record<string, string>;
1479
+ httpBasePath: string;
1480
+ httpPort: number;
1481
+ startEngine: boolean;
1482
+ engineVersion: string;
1483
+ serverless: {
1484
+ basePath: string;
1485
+ publicEndpoint: string | undefined;
1486
+ publicToken: string | undefined;
1487
+ };
1488
+ envoy: {
1489
+ poolName: string;
1490
+ version: number;
1491
+ totalSlots: number;
1492
+ envoyKey?: string | undefined;
1493
+ };
1494
+ staticDir?: string | undefined;
1495
+ httpHost?: string | undefined;
1496
+ configurePool?: {
1497
+ url: string;
1498
+ name?: string | undefined;
1499
+ headers?: Record<string, string> | undefined;
1500
+ requestLifespan?: number | undefined;
1501
+ metadata?: Record<string, unknown> | undefined;
1502
+ metadataPollInterval?: number | undefined;
1503
+ drainOnVersionUpgrade?: boolean | undefined;
1504
+ } | undefined;
1505
+ }>>;
1506
+ type RegistryConfig = z$2.infer<typeof RegistryConfigSchema>;
1507
+ type RegistryConfigInput<A extends RegistryActors> = Omit<z$2.input<typeof RegistryConfigSchema>, "use"> & {
1508
+ use: A;
1509
+ };
1510
+
1511
+ type FetchHandler = (request: Request, ...args: any) => Response | Promise<Response>;
1512
+ interface ServerlessHandler {
1513
+ fetch: FetchHandler;
1514
+ }
1515
+ declare class Registry<A extends RegistryActors> {
1516
+ #private;
1517
+ get config(): RegistryConfigInput<A>;
1518
+ parseConfig(): RegistryConfig;
1519
+ constructor(config: RegistryConfigInput<A>);
1520
+ /**
1521
+ * Handle an incoming HTTP request for serverless deployments.
1510
1522
  *
1511
- * @template AD The actor class that this handle is for.
1512
- * @param {string} name - The name of the actor.
1513
- * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
1514
- * @param {GetOptions} [opts] - Options for getting the actor.
1515
- * @returns {ActorHandle<AD>} - A handle to the actor.
1523
+ * @example
1524
+ * ```ts
1525
+ * const app = new Hono();
1526
+ * app.all("/api/rivet/*", (c) => registry.handler(c.req.raw));
1527
+ * export default app;
1528
+ * ```
1516
1529
  */
1517
- getOrCreate<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: GetOrCreateOptions): ActorHandle<AD>;
1530
+ handler(request: Request): Promise<Response>;
1518
1531
  /**
1519
- * Creates a new actor with the provided key and returns a stateless handle to it.
1520
- * Resolves the actor ID and returns a handle with getForId query.
1532
+ * Returns a fetch handler for serverless deployments.
1521
1533
  *
1522
- * @template AD The actor class that this handle is for.
1523
- * @param {string} name - The name of the actor.
1524
- * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
1525
- * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
1526
- * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
1534
+ * @example
1535
+ * ```ts
1536
+ * export default registry.serve();
1537
+ * ```
1527
1538
  */
1528
- create<AD extends AnyActorDefinition>(name: string, key?: string | string[], opts?: CreateOptions): Promise<ActorHandle<AD>>;
1529
- [CREATE_ACTOR_CONN_PROXY]<AD extends AnyActorDefinition>(conn: ActorConnRaw): ActorConn<AD>;
1539
+ serve(): ServerlessHandler;
1530
1540
  /**
1531
- * Disconnects from all actors.
1541
+ * Starts an actor envoy for standalone server deployments.
1542
+ */
1543
+ startEnvoy(): void;
1544
+ /**
1545
+ * Starts the server, serving both the actor API and static files.
1532
1546
  *
1533
- * @returns {Promise<void>} A promise that resolves when all connections are closed.
1547
+ * This is the simplest way to run RivetKit. It starts a local runtime
1548
+ * server, serves static files from the configured `staticDir` (default
1549
+ * `"public"`), and starts the actor envoy.
1550
+ *
1551
+ * When an endpoint is configured (via config or RIVET_ENDPOINT env var),
1552
+ * operates in serverless mode connected to the remote engine instead.
1553
+ *
1554
+ * @example
1555
+ * ```ts
1556
+ * const registry = setup({ use: { counter } });
1557
+ * registry.start();
1558
+ * ```
1534
1559
  */
1535
- dispose(): Promise<void>;
1560
+ start(): void;
1536
1561
  }
1537
- /**
1538
- * Client type with actor accessors.
1539
- * This adds property accessors for actor names to the ClientRaw base class.
1540
- *
1541
- * @template A The actor registry type.
1542
- */
1543
- type Client<A extends Registry<any>> = ClientRaw & {
1544
- [K in keyof ExtractActorsFromRegistry<A>]: ActorAccessor<ExtractActorsFromRegistry<A>[K]>;
1545
- };
1546
1562
 
1547
1563
  /**
1548
1564
  * Creates a client with the actor accessor proxy.