@methodacting/actor-kit 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/LICENSE.md +7 -0
  2. package/README.md +2042 -0
  3. package/dist/browser.d.ts +384 -0
  4. package/dist/browser.js +2 -0
  5. package/dist/browser.js.map +1 -0
  6. package/dist/index.d.ts +644 -0
  7. package/dist/index.js +2 -0
  8. package/dist/index.js.map +1 -0
  9. package/dist/react.d.ts +416 -0
  10. package/dist/react.js +2 -0
  11. package/dist/react.js.map +1 -0
  12. package/dist/src/alarms.d.ts +47 -0
  13. package/dist/src/alarms.d.ts.map +1 -0
  14. package/dist/src/browser.d.ts +2 -0
  15. package/dist/src/browser.d.ts.map +1 -0
  16. package/dist/src/constants.d.ts +12 -0
  17. package/dist/src/constants.d.ts.map +1 -0
  18. package/dist/src/createAccessToken.d.ts +9 -0
  19. package/dist/src/createAccessToken.d.ts.map +1 -0
  20. package/dist/src/createActorFetch.d.ts +18 -0
  21. package/dist/src/createActorFetch.d.ts.map +1 -0
  22. package/dist/src/createActorKitClient.d.ts +13 -0
  23. package/dist/src/createActorKitClient.d.ts.map +1 -0
  24. package/dist/src/createActorKitContext.d.ts +29 -0
  25. package/dist/src/createActorKitContext.d.ts.map +1 -0
  26. package/dist/src/createActorKitMockClient.d.ts +11 -0
  27. package/dist/src/createActorKitMockClient.d.ts.map +1 -0
  28. package/dist/src/createActorKitRouter.d.ts +4 -0
  29. package/dist/src/createActorKitRouter.d.ts.map +1 -0
  30. package/dist/src/createMachineServer.d.ts +20 -0
  31. package/dist/src/createMachineServer.d.ts.map +1 -0
  32. package/dist/src/durable-object-system.d.ts +36 -0
  33. package/dist/src/durable-object-system.d.ts.map +1 -0
  34. package/dist/src/index.d.ts +7 -0
  35. package/dist/src/index.d.ts.map +1 -0
  36. package/dist/src/react.d.ts +2 -0
  37. package/dist/src/react.d.ts.map +1 -0
  38. package/dist/src/schemas.d.ts +312 -0
  39. package/dist/src/schemas.d.ts.map +1 -0
  40. package/dist/src/server.d.ts +3 -0
  41. package/dist/src/server.d.ts.map +1 -0
  42. package/dist/src/storage.d.ts +64 -0
  43. package/dist/src/storage.d.ts.map +1 -0
  44. package/dist/src/storybook.d.ts +13 -0
  45. package/dist/src/storybook.d.ts.map +1 -0
  46. package/dist/src/test.d.ts +2 -0
  47. package/dist/src/test.d.ts.map +1 -0
  48. package/dist/src/types.d.ts +181 -0
  49. package/dist/src/types.d.ts.map +1 -0
  50. package/dist/src/utils.d.ts +30 -0
  51. package/dist/src/utils.d.ts.map +1 -0
  52. package/dist/src/withActorKit.d.ts +9 -0
  53. package/dist/src/withActorKit.d.ts.map +1 -0
  54. package/dist/src/worker.d.ts +3 -0
  55. package/dist/src/worker.d.ts.map +1 -0
  56. package/package.json +87 -0
  57. package/src/alarms.ts +237 -0
  58. package/src/browser.ts +1 -0
  59. package/src/constants.ts +31 -0
  60. package/src/createAccessToken.ts +29 -0
  61. package/src/createActorFetch.ts +111 -0
  62. package/src/createActorKitClient.ts +224 -0
  63. package/src/createActorKitContext.tsx +228 -0
  64. package/src/createActorKitMockClient.ts +138 -0
  65. package/src/createActorKitRouter.ts +149 -0
  66. package/src/createMachineServer.ts +844 -0
  67. package/src/durable-object-system.ts +212 -0
  68. package/src/global.d.ts +7 -0
  69. package/src/index.ts +6 -0
  70. package/src/react.ts +1 -0
  71. package/src/schemas.ts +95 -0
  72. package/src/server.ts +3 -0
  73. package/src/storage.ts +404 -0
  74. package/src/storybook.ts +42 -0
  75. package/src/test.ts +1 -0
  76. package/src/types.ts +334 -0
  77. package/src/utils.ts +171 -0
  78. package/src/withActorKit.tsx +103 -0
  79. package/src/worker.ts +2 -0
@@ -0,0 +1,644 @@
1
+ import { z } from 'zod';
2
+ import { DurableObject } from 'cloudflare:workers';
3
+ import { Operation } from 'fast-json-patch';
4
+ import { StateMachine, AnyEventObject, StateValueFrom, AnyStateMachine, SnapshotFrom, AnyActorRef } from 'xstate';
5
+
6
+ declare const BotManagementSchema: z.ZodObject<{
7
+ corporateProxy: z.ZodBoolean;
8
+ verifiedBot: z.ZodBoolean;
9
+ jsDetection: z.ZodObject<{
10
+ passed: z.ZodBoolean;
11
+ }, "strip", z.ZodTypeAny, {
12
+ passed: boolean;
13
+ }, {
14
+ passed: boolean;
15
+ }>;
16
+ staticResource: z.ZodBoolean;
17
+ detectionIds: z.ZodRecord<z.ZodString, z.ZodAny>;
18
+ score: z.ZodNumber;
19
+ }, "strip", z.ZodTypeAny, {
20
+ corporateProxy: boolean;
21
+ verifiedBot: boolean;
22
+ jsDetection: {
23
+ passed: boolean;
24
+ };
25
+ staticResource: boolean;
26
+ detectionIds: Record<string, any>;
27
+ score: number;
28
+ }, {
29
+ corporateProxy: boolean;
30
+ verifiedBot: boolean;
31
+ jsDetection: {
32
+ passed: boolean;
33
+ };
34
+ staticResource: boolean;
35
+ detectionIds: Record<string, any>;
36
+ score: number;
37
+ }>;
38
+ declare const EnvironmentSchema: z.ZodObject<{
39
+ ACTOR_KIT_SECRET: z.ZodString;
40
+ ACTOR_KIT_HOST: z.ZodString;
41
+ }, "strip", z.ZodTypeAny, {
42
+ ACTOR_KIT_SECRET: string;
43
+ ACTOR_KIT_HOST: string;
44
+ }, {
45
+ ACTOR_KIT_SECRET: string;
46
+ ACTOR_KIT_HOST: string;
47
+ }>;
48
+ declare const RequestInfoSchema: z.ZodObject<{
49
+ longitude: z.ZodString;
50
+ latitude: z.ZodString;
51
+ continent: z.ZodString;
52
+ country: z.ZodString;
53
+ city: z.ZodString;
54
+ timezone: z.ZodString;
55
+ postalCode: z.ZodString;
56
+ region: z.ZodString;
57
+ regionCode: z.ZodString;
58
+ metroCode: z.ZodString;
59
+ botManagement: z.ZodObject<{
60
+ corporateProxy: z.ZodBoolean;
61
+ verifiedBot: z.ZodBoolean;
62
+ jsDetection: z.ZodObject<{
63
+ passed: z.ZodBoolean;
64
+ }, "strip", z.ZodTypeAny, {
65
+ passed: boolean;
66
+ }, {
67
+ passed: boolean;
68
+ }>;
69
+ staticResource: z.ZodBoolean;
70
+ detectionIds: z.ZodRecord<z.ZodString, z.ZodAny>;
71
+ score: z.ZodNumber;
72
+ }, "strip", z.ZodTypeAny, {
73
+ corporateProxy: boolean;
74
+ verifiedBot: boolean;
75
+ jsDetection: {
76
+ passed: boolean;
77
+ };
78
+ staticResource: boolean;
79
+ detectionIds: Record<string, any>;
80
+ score: number;
81
+ }, {
82
+ corporateProxy: boolean;
83
+ verifiedBot: boolean;
84
+ jsDetection: {
85
+ passed: boolean;
86
+ };
87
+ staticResource: boolean;
88
+ detectionIds: Record<string, any>;
89
+ score: number;
90
+ }>;
91
+ }, "strip", z.ZodTypeAny, {
92
+ longitude: string;
93
+ latitude: string;
94
+ continent: string;
95
+ country: string;
96
+ city: string;
97
+ timezone: string;
98
+ postalCode: string;
99
+ region: string;
100
+ regionCode: string;
101
+ metroCode: string;
102
+ botManagement: {
103
+ corporateProxy: boolean;
104
+ verifiedBot: boolean;
105
+ jsDetection: {
106
+ passed: boolean;
107
+ };
108
+ staticResource: boolean;
109
+ detectionIds: Record<string, any>;
110
+ score: number;
111
+ };
112
+ }, {
113
+ longitude: string;
114
+ latitude: string;
115
+ continent: string;
116
+ country: string;
117
+ city: string;
118
+ timezone: string;
119
+ postalCode: string;
120
+ region: string;
121
+ regionCode: string;
122
+ metroCode: string;
123
+ botManagement: {
124
+ corporateProxy: boolean;
125
+ verifiedBot: boolean;
126
+ jsDetection: {
127
+ passed: boolean;
128
+ };
129
+ staticResource: boolean;
130
+ detectionIds: Record<string, any>;
131
+ score: number;
132
+ };
133
+ }>;
134
+ declare const CallerSchema: z.ZodObject<{
135
+ id: z.ZodString;
136
+ type: z.ZodEnum<["client", "system", "service"]>;
137
+ }, "strip", z.ZodTypeAny, {
138
+ type: "client" | "system" | "service";
139
+ id: string;
140
+ }, {
141
+ type: "client" | "system" | "service";
142
+ id: string;
143
+ }>;
144
+ declare const AnyEventSchema: z.ZodObject<{
145
+ type: z.ZodString;
146
+ }, "strip", z.ZodTypeAny, {
147
+ type: string;
148
+ }, {
149
+ type: string;
150
+ }>;
151
+ declare const SystemEventSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
152
+ type: z.ZodLiteral<"INITIALIZE">;
153
+ caller: z.ZodObject<{
154
+ type: z.ZodLiteral<"system">;
155
+ id: z.ZodString;
156
+ }, "strip", z.ZodTypeAny, {
157
+ type: "system";
158
+ id: string;
159
+ }, {
160
+ type: "system";
161
+ id: string;
162
+ }>;
163
+ }, "strip", z.ZodTypeAny, {
164
+ type: "INITIALIZE";
165
+ caller: {
166
+ type: "system";
167
+ id: string;
168
+ };
169
+ }, {
170
+ type: "INITIALIZE";
171
+ caller: {
172
+ type: "system";
173
+ id: string;
174
+ };
175
+ }>, z.ZodObject<{
176
+ type: z.ZodLiteral<"CONNECT">;
177
+ caller: z.ZodObject<{
178
+ type: z.ZodLiteral<"system">;
179
+ id: z.ZodString;
180
+ }, "strip", z.ZodTypeAny, {
181
+ type: "system";
182
+ id: string;
183
+ }, {
184
+ type: "system";
185
+ id: string;
186
+ }>;
187
+ connectingCaller: z.ZodObject<{
188
+ id: z.ZodString;
189
+ type: z.ZodEnum<["client", "system", "service"]>;
190
+ }, "strip", z.ZodTypeAny, {
191
+ type: "client" | "system" | "service";
192
+ id: string;
193
+ }, {
194
+ type: "client" | "system" | "service";
195
+ id: string;
196
+ }>;
197
+ }, "strip", z.ZodTypeAny, {
198
+ type: "CONNECT";
199
+ caller: {
200
+ type: "system";
201
+ id: string;
202
+ };
203
+ connectingCaller: {
204
+ type: "client" | "system" | "service";
205
+ id: string;
206
+ };
207
+ }, {
208
+ type: "CONNECT";
209
+ caller: {
210
+ type: "system";
211
+ id: string;
212
+ };
213
+ connectingCaller: {
214
+ type: "client" | "system" | "service";
215
+ id: string;
216
+ };
217
+ }>, z.ZodObject<{
218
+ type: z.ZodLiteral<"DISCONNECT">;
219
+ caller: z.ZodObject<{
220
+ type: z.ZodLiteral<"system">;
221
+ id: z.ZodString;
222
+ }, "strip", z.ZodTypeAny, {
223
+ type: "system";
224
+ id: string;
225
+ }, {
226
+ type: "system";
227
+ id: string;
228
+ }>;
229
+ disconnectingCaller: z.ZodObject<{
230
+ id: z.ZodString;
231
+ type: z.ZodEnum<["client", "system", "service"]>;
232
+ }, "strip", z.ZodTypeAny, {
233
+ type: "client" | "system" | "service";
234
+ id: string;
235
+ }, {
236
+ type: "client" | "system" | "service";
237
+ id: string;
238
+ }>;
239
+ }, "strip", z.ZodTypeAny, {
240
+ type: "DISCONNECT";
241
+ caller: {
242
+ type: "system";
243
+ id: string;
244
+ };
245
+ disconnectingCaller: {
246
+ type: "client" | "system" | "service";
247
+ id: string;
248
+ };
249
+ }, {
250
+ type: "DISCONNECT";
251
+ caller: {
252
+ type: "system";
253
+ id: string;
254
+ };
255
+ disconnectingCaller: {
256
+ type: "client" | "system" | "service";
257
+ id: string;
258
+ };
259
+ }>, z.ZodObject<{
260
+ type: z.ZodLiteral<"RESUME">;
261
+ caller: z.ZodObject<{
262
+ type: z.ZodLiteral<"system">;
263
+ id: z.ZodString;
264
+ }, "strip", z.ZodTypeAny, {
265
+ type: "system";
266
+ id: string;
267
+ }, {
268
+ type: "system";
269
+ id: string;
270
+ }>;
271
+ }, "strip", z.ZodTypeAny, {
272
+ type: "RESUME";
273
+ caller: {
274
+ type: "system";
275
+ id: string;
276
+ };
277
+ }, {
278
+ type: "RESUME";
279
+ caller: {
280
+ type: "system";
281
+ id: string;
282
+ };
283
+ }>, z.ZodObject<{
284
+ type: z.ZodLiteral<"MIGRATE">;
285
+ caller: z.ZodObject<{
286
+ type: z.ZodLiteral<"system">;
287
+ id: z.ZodString;
288
+ }, "strip", z.ZodTypeAny, {
289
+ type: "system";
290
+ id: string;
291
+ }, {
292
+ type: "system";
293
+ id: string;
294
+ }>;
295
+ operations: z.ZodArray<z.ZodAny, "many">;
296
+ }, "strip", z.ZodTypeAny, {
297
+ type: "MIGRATE";
298
+ caller: {
299
+ type: "system";
300
+ id: string;
301
+ };
302
+ operations: any[];
303
+ }, {
304
+ type: "MIGRATE";
305
+ caller: {
306
+ type: "system";
307
+ id: string;
308
+ };
309
+ operations: any[];
310
+ }>]>;
311
+ declare const CallerIdTypeSchema: z.ZodEnum<["client", "service", "system"]>;
312
+ declare const CallerStringSchema: z.ZodEffects<z.ZodString, {
313
+ type: "client" | "system" | "service";
314
+ id: string;
315
+ }, string>;
316
+
317
+ interface AlarmRecord {
318
+ id: string;
319
+ type: string;
320
+ scheduled_at: number;
321
+ repeat_interval: number | null;
322
+ payload: string | null;
323
+ created_at: number;
324
+ }
325
+ interface AlarmScheduleOptions {
326
+ id: string;
327
+ type: string;
328
+ scheduledAt: number;
329
+ repeatInterval?: number;
330
+ payload: Record<string, unknown>;
331
+ }
332
+ interface ActorMetaRecord {
333
+ actor_id: string;
334
+ actor_type: string;
335
+ initial_caller: string;
336
+ input: string;
337
+ created_at: number;
338
+ updated_at: number;
339
+ }
340
+ interface ActorMeta {
341
+ actorId: string;
342
+ actorType: string;
343
+ initialCaller: Caller;
344
+ input: Record<string, unknown>;
345
+ }
346
+ interface SnapshotRecord {
347
+ actor_id: string;
348
+ snapshot: string;
349
+ checksum: string | null;
350
+ updated_at: number;
351
+ }
352
+ interface Snapshot {
353
+ actorId: string;
354
+ snapshot: unknown;
355
+ checksum?: string;
356
+ }
357
+ declare class ActorKitStorage {
358
+ private storage;
359
+ private initialized;
360
+ private sql;
361
+ constructor(storage: DurableObjectStorage);
362
+ ensureInitialized(): Promise<void>;
363
+ getAlarms(): Promise<AlarmRecord[]>;
364
+ getDueAlarms(before: number): Promise<AlarmRecord[]>;
365
+ getEarliestAlarm(): Promise<AlarmRecord | null>;
366
+ insertAlarm(options: AlarmScheduleOptions): Promise<void>;
367
+ updateAlarm(options: AlarmScheduleOptions): Promise<void>;
368
+ deleteAlarm(id: string): Promise<void>;
369
+ deleteAlarmsByType(type: string): Promise<void>;
370
+ getActorMeta(actorId?: string): Promise<ActorMeta | null>;
371
+ setActorMeta(meta: ActorMeta): Promise<void>;
372
+ deleteActorMeta(actorId: string): Promise<void>;
373
+ getSnapshot(actorId: string): Promise<Snapshot | null>;
374
+ setSnapshot(actorId: string, snapshot: unknown, checksum?: string): Promise<void>;
375
+ deleteSnapshot(actorId: string): Promise<void>;
376
+ migrateFromKV(storage: DurableObjectStorage): Promise<void>;
377
+ private parseRows;
378
+ }
379
+
380
+ type AlarmType = "xstate-delay" | "cache-cleanup" | "custom";
381
+ interface Alarm {
382
+ id: string;
383
+ type: AlarmType;
384
+ scheduledAt: number;
385
+ repeatInterval?: number;
386
+ payload: Record<string, unknown>;
387
+ createdAt: number;
388
+ }
389
+ interface ScheduleAlarmOptions {
390
+ id: string;
391
+ type: AlarmType;
392
+ scheduledAt: number;
393
+ repeatInterval?: number;
394
+ payload: Record<string, unknown>;
395
+ }
396
+ interface AlarmHandleResult {
397
+ id: string;
398
+ type: AlarmType;
399
+ rescheduled?: boolean;
400
+ deleted: boolean;
401
+ }
402
+ declare class AlarmManager {
403
+ private storage;
404
+ private state;
405
+ private currentAlarmId;
406
+ private currentAlarmTime;
407
+ constructor(storage: ActorKitStorage, state: DurableObjectState);
408
+ schedule(options: ScheduleAlarmOptions): Promise<void>;
409
+ cancel(id: string): Promise<void>;
410
+ cancelByType(type: AlarmType): Promise<void>;
411
+ getPendingAlarms(): Promise<Alarm[]>;
412
+ getDueAlarms(before?: number): Promise<Alarm[]>;
413
+ deleteAlarm(id: string): Promise<void>;
414
+ updateAlarm(options: ScheduleAlarmOptions): Promise<void>;
415
+ rescheduleNextAlarm(): Promise<void>;
416
+ handleDueAlarms(handler: (alarm: Alarm) => Promise<boolean>): Promise<AlarmHandleResult[]>;
417
+ getCurrentAlarm(): {
418
+ id: string | null;
419
+ time: number | null;
420
+ };
421
+ private parseAlarmRecord;
422
+ }
423
+ declare function generateAlarmId(): string;
424
+ declare function calculateNextRecurringAlarm(baseTime: number, interval: number, now?: number): number;
425
+
426
+ type EnvWithDurableObjects = {
427
+ ACTOR_KIT_SECRET: string;
428
+ [key: string]: DurableObjectNamespace<ActorServer<any>> | unknown;
429
+ };
430
+ type AnyEvent = z.infer<typeof AnyEventSchema>;
431
+ interface ActorServerMethods<TMachine extends BaseActorKitStateMachine> {
432
+ fetch(request: Request): Promise<Response>;
433
+ spawn(props: {
434
+ actorType: string;
435
+ actorId: string;
436
+ caller: Caller;
437
+ input: Record<string, unknown>;
438
+ }): void;
439
+ send(event: ClientEventFrom<TMachine> | ServiceEventFrom<TMachine>): void;
440
+ getSnapshot(caller: Caller, options?: {
441
+ waitForEvent?: ClientEventFrom<TMachine>;
442
+ waitForState?: StateValueFrom<TMachine>;
443
+ timeout?: number;
444
+ errorOnWaitTimeout?: boolean;
445
+ }): Promise<{
446
+ checksum: string;
447
+ snapshot: CallerSnapshotFrom<TMachine>;
448
+ }>;
449
+ }
450
+ type ActorServer<TMachine extends AnyActorKitStateMachine> = DurableObject & ActorServerMethods<TMachine>;
451
+ type AnyActorServer = ActorServer<any>;
452
+ type Caller = z.infer<typeof CallerSchema>;
453
+ type RequestInfo = z.infer<typeof RequestInfoSchema>;
454
+ type ActorKitInputProps = {
455
+ id: string;
456
+ caller: Caller;
457
+ storage: DurableObjectStorage;
458
+ [key: string]: unknown;
459
+ };
460
+ type CallerType = "client" | "system" | "service";
461
+ type EventObject = {
462
+ type: string;
463
+ };
464
+ type EventSchemaUnion = z.ZodDiscriminatedUnion<"type", [
465
+ z.ZodObject<z.ZodRawShape & {
466
+ type: z.ZodString;
467
+ }>,
468
+ ...z.ZodObject<z.ZodRawShape & {
469
+ type: z.ZodString;
470
+ }>[]
471
+ ]>;
472
+ type EventSchemas = {
473
+ client: EventSchemaUnion;
474
+ service: EventSchemaUnion;
475
+ };
476
+ type BaseActorKitContext<TPublicProps extends {
477
+ [key: string]: unknown;
478
+ }, TPrivateProps extends {
479
+ [key: string]: unknown;
480
+ }> = {
481
+ public: TPublicProps;
482
+ private: Record<string, TPrivateProps>;
483
+ };
484
+ type ActorKitStateMachine<TEvent extends BaseActorKitEvent<EnvWithDurableObjects>, TInput extends {
485
+ id: string;
486
+ caller: Caller;
487
+ storage: DurableObjectStorage;
488
+ }, TContext extends BaseActorKitContext<any, any> & {
489
+ [key: string]: unknown;
490
+ }> = StateMachine<TContext, TEvent & EventObject, any, any, any, any, any, any, any, TInput, any, any, any, any>;
491
+ type BaseActorKitInput<TEnv = EnvWithDurableObjects> = {
492
+ id: string;
493
+ caller: Caller;
494
+ env: TEnv;
495
+ storage: DurableObjectStorage;
496
+ };
497
+ type WithActorKitInput<TInputProps extends {
498
+ [key: string]: unknown;
499
+ }, TEnv extends EnvWithDurableObjects> = TInputProps & BaseActorKitInput<TEnv>;
500
+ type AnyActorKitStateMachine = ActorKitStateMachine<any, any, any>;
501
+ type AnyActorKitEvent = (WithActorKitEvent<AnyEventObject, "client"> | WithActorKitEvent<AnyEventObject, "service"> | ActorKitSystemEvent) & BaseActorKitEvent<EnvWithDurableObjects>;
502
+ type AnyActorKitInput = WithActorKitInput<{
503
+ [key: string]: unknown;
504
+ }, EnvWithDurableObjects> & {
505
+ storage: DurableObjectStorage;
506
+ };
507
+ type AnyActorKitContext = {
508
+ public: {
509
+ [key: string]: unknown;
510
+ };
511
+ private: Record<string, {
512
+ [key: string]: unknown;
513
+ }>;
514
+ };
515
+ type BaseActorKitStateMachine = ActorKitStateMachine<AnyActorKitEvent, AnyActorKitInput, AnyActorKitContext>;
516
+ type ExtraContext = {
517
+ requestId: string;
518
+ };
519
+ interface BaseActorKitEvent<TEnv extends EnvWithDurableObjects> {
520
+ caller: Caller;
521
+ storage: DurableObjectStorage;
522
+ requestInfo?: RequestInfo;
523
+ env: TEnv;
524
+ }
525
+ type ActorKitSystemEvent = z.infer<typeof SystemEventSchema>;
526
+ type WithActorKitEvent<T extends {
527
+ type: string;
528
+ }, C extends CallerType> = T & BaseActorKitEvent<EnvWithDurableObjects> & {
529
+ caller: {
530
+ type: C;
531
+ };
532
+ };
533
+ type WithActorKitContext<TExtraProps extends {
534
+ [key: string]: unknown;
535
+ }, TPrivateProps extends {
536
+ [key: string]: unknown;
537
+ }, TPublicProps extends {
538
+ [key: string]: unknown;
539
+ }> = TExtraProps & {
540
+ public: TPublicProps;
541
+ private: Record<string, TPrivateProps>;
542
+ };
543
+ type CallerSnapshotFrom<TMachine extends AnyStateMachine> = {
544
+ public: SnapshotFrom<TMachine> extends {
545
+ context: {
546
+ public: infer P;
547
+ };
548
+ } ? P : unknown;
549
+ private: SnapshotFrom<TMachine> extends {
550
+ context: {
551
+ private: Partial<Record<string, infer PR>>;
552
+ };
553
+ } ? PR : unknown;
554
+ value: SnapshotFrom<TMachine> extends {
555
+ value: infer V;
556
+ } ? V : unknown;
557
+ };
558
+ type ClientEventFrom<T extends AnyActorKitStateMachine> = T extends StateMachine<any, infer TEvent, any, any, any, any, any, any, any, any, any, any, any, any> ? TEvent extends WithActorKitEvent<infer E, "client"> ? Omit<E, keyof BaseActorKitEvent<EnvWithDurableObjects>> : never : never;
559
+ type ServiceEventFrom<T extends AnyActorKitStateMachine> = T extends StateMachine<any, infer TEvent, any, any, any, any, any, any, any, any, any, any, any, any> ? TEvent extends WithActorKitEvent<infer E, "service"> ? Omit<E, keyof BaseActorKitEvent<EnvWithDurableObjects>> : never : never;
560
+ type ScreamingSnakeToKebab<S extends string> = S extends `${infer T}_${infer U}` ? `${Lowercase<T>}-${ScreamingSnakeToKebab<U>}` : Lowercase<S>;
561
+ type DurableObjectActor<TMachine extends AnyActorKitStateMachine> = ActorServer<TMachine>;
562
+ type CamelToSnakeCase<S extends string> = S extends `${infer T}${infer U}` ? U extends Uncapitalize<U> ? `${Lowercase<T>}${CamelToSnakeCase<U>}` : `${Lowercase<T>}_${CamelToSnakeCase<U>}` : S;
563
+ type KebabToCamelCase<S extends string> = S extends `${infer T}-${infer U}` ? `${T}${Capitalize<KebabToCamelCase<U>>}` : S;
564
+ type KebabToScreamingSnake<S extends string> = Uppercase<CamelToSnakeCase<KebabToCamelCase<S>>>;
565
+ interface MatchesProps<TMachine extends AnyActorKitStateMachine> {
566
+ state: StateValueFrom<TMachine>;
567
+ and?: StateValueFrom<TMachine>;
568
+ or?: StateValueFrom<TMachine>;
569
+ not?: boolean;
570
+ initialValueOverride?: boolean;
571
+ }
572
+ type MachineFromServer<T> = T extends ActorServer<infer M> ? M : never;
573
+ type ActorKitEmittedEvent = {
574
+ operations: Operation[];
575
+ checksum: string;
576
+ };
577
+ type ActorKitClient<TMachine extends AnyActorKitStateMachine> = {
578
+ connect: () => Promise<void>;
579
+ disconnect: () => void;
580
+ send: (event: ClientEventFrom<TMachine>) => void;
581
+ getState: () => CallerSnapshotFrom<TMachine>;
582
+ subscribe: (listener: (state: CallerSnapshotFrom<TMachine>) => void) => () => void;
583
+ waitFor: (predicateFn: (state: CallerSnapshotFrom<TMachine>) => boolean, timeoutMs?: number) => Promise<void>;
584
+ };
585
+ type ExtractEventType<TMachine> = TMachine extends ActorKitStateMachine<infer TEvent, any, any> ? TEvent : never;
586
+ type ExtractEnvType<TEvent> = TEvent extends {
587
+ env: infer TEnv;
588
+ } ? TEnv : never;
589
+ type EnvFromMachine<TMachine extends AnyActorKitStateMachine> = ExtractEnvType<ExtractEventType<TMachine>> extends never ? EnvWithDurableObjects : ExtractEnvType<ExtractEventType<TMachine>> & EnvWithDurableObjects;
590
+ interface MachineServerOptions {
591
+ persisted?: boolean;
592
+ enableAlarms?: boolean;
593
+ }
594
+ interface MachineServerServices {
595
+ storage: ActorKitStorage;
596
+ alarmManager: AlarmManager | null;
597
+ }
598
+
599
+ declare const HEADERS: {
600
+ X_CALLER_ID: string;
601
+ X_CALLER_TYPE: string;
602
+ X_ACTOR_ID: string;
603
+ X_ACTOR_TYPE: string;
604
+ };
605
+ declare const CallerTypes: Record<CallerType, CallerType>;
606
+ declare const AlarmTypes: Record<AlarmType, AlarmType>;
607
+ declare const PERSISTED_SNAPSHOT_KEY = "persistedSnapshot";
608
+
609
+ interface XStateAlarmData {
610
+ type: "xstate-delay";
611
+ sourceSessionId: string;
612
+ targetSessionId: string;
613
+ event: AnyEventObject;
614
+ scheduledEventId: string;
615
+ alarmId: string;
616
+ [key: string]: unknown;
617
+ }
618
+ interface ScheduledEventSnapshot {
619
+ sourceSessionId: string;
620
+ targetSessionId: string;
621
+ event: AnyEventObject;
622
+ delay: number;
623
+ id: string;
624
+ startedAt: number;
625
+ }
626
+ interface Clock {
627
+ setTimeout: (fn: () => void, delay: number) => unknown;
628
+ clearTimeout: (id: unknown) => void;
629
+ }
630
+ declare const NOOP_CLOCK: Clock;
631
+ declare function createAlarmScheduler(alarmManager: AlarmManager, system: any): {
632
+ schedule: (source: AnyActorRef, target: AnyActorRef, event: AnyEventObject, delay: number, id?: string) => void;
633
+ cancel: (source: AnyActorRef, id: string) => void;
634
+ cancelAll: (actorRef: AnyActorRef) => void;
635
+ };
636
+ declare function handleXStateAlarm(alarmData: XStateAlarmData, actor: any): Promise<void>;
637
+ declare function getScheduledEvents(): Map<string, ScheduledEventSnapshot>;
638
+ declare function restoreScheduledEvents(alarms: Array<{
639
+ payload: XStateAlarmData;
640
+ scheduledAt: number;
641
+ }>): void;
642
+
643
+ export { ActorKitStorage, AlarmManager, AlarmTypes, AnyEventSchema, BotManagementSchema, CallerIdTypeSchema, CallerSchema, CallerStringSchema, CallerTypes, EnvironmentSchema, HEADERS, NOOP_CLOCK, PERSISTED_SNAPSHOT_KEY, RequestInfoSchema, SystemEventSchema, calculateNextRecurringAlarm, createAlarmScheduler, generateAlarmId, getScheduledEvents, handleXStateAlarm, restoreScheduledEvents };
644
+ export type { ActorKitClient, ActorKitEmittedEvent, ActorKitInputProps, ActorKitStateMachine, ActorKitSystemEvent, ActorMeta, ActorMetaRecord, ActorServer, ActorServerMethods, Alarm, AlarmHandleResult, AlarmRecord, AlarmScheduleOptions, AlarmType, AnyActorKitStateMachine, AnyActorServer, AnyEvent, BaseActorKitContext, BaseActorKitEvent, BaseActorKitInput, BaseActorKitStateMachine, Caller, CallerSnapshotFrom, CallerType, ClientEventFrom, Clock, DurableObjectActor, EnvFromMachine, EnvWithDurableObjects, EventSchemas, ExtraContext, KebabToScreamingSnake, MachineFromServer, MachineServerOptions, MachineServerServices, MatchesProps, RequestInfo, ScheduleAlarmOptions, ScheduledEventSnapshot, ScreamingSnakeToKebab, ServiceEventFrom, Snapshot, SnapshotRecord, WithActorKitContext, WithActorKitEvent, WithActorKitInput, XStateAlarmData };
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import{z as e}from"zod";const t=e.object({corporateProxy:e.boolean(),verifiedBot:e.boolean(),jsDetection:e.object({passed:e.boolean()}),staticResource:e.boolean(),detectionIds:e.record(e.any()),score:e.number()}),a=e.object({ACTOR_KIT_SECRET:e.string(),ACTOR_KIT_HOST:e.string()}),s=e.object({longitude:e.string(),latitude:e.string(),continent:e.string(),country:e.string(),city:e.string(),timezone:e.string(),postalCode:e.string(),region:e.string(),regionCode:e.string(),metroCode:e.string(),botManagement:t}),r=e.object({id:e.string(),type:e.enum(["client","system","service"])}),i=e.object({type:e.string()}),n=e.discriminatedUnion("type",[e.object({type:e.literal("INITIALIZE"),caller:e.object({type:e.literal("system"),id:e.string()})}),e.object({type:e.literal("CONNECT"),caller:e.object({type:e.literal("system"),id:e.string()}),connectingCaller:r}),e.object({type:e.literal("DISCONNECT"),caller:e.object({type:e.literal("system"),id:e.string()}),disconnectingCaller:r}),e.object({type:e.literal("RESUME"),caller:e.object({type:e.literal("system"),id:e.string()})}),e.object({type:e.literal("MIGRATE"),caller:e.object({type:e.literal("system"),id:e.string()}),operations:e.array(e.any())})]),l=e.enum(["client","service","system"]),c=e.string().transform((t,a)=>{if("anonymous"===t)return{type:"client",id:"anonymous"};const s=l.safeParse(t.split("-")[0]);if(!s.success)return s.error.issues.forEach(a.addIssue),e.NEVER;const r=s.data,i=t.substring(t.indexOf("-")+1);return e.string().uuid().safeParse(i).success?{type:r,id:i}:(a.addIssue({code:e.ZodIssueCode.custom,message:`Must be a valid uuid or 'anonymous'. Received '${i}' on value '${t}'.`}),e.NEVER)}),o={X_CALLER_ID:"X-Caller-ID",X_CALLER_TYPE:"X-Caller-Type",X_ACTOR_ID:"X-Actor-ID",X_ACTOR_TYPE:"X-Actor-Type"},d={client:"client",system:"system",service:"service"},u={"xstate-delay":"xstate-delay","cache-cleanup":"cache-cleanup",custom:"custom"},p="persistedSnapshot";class h{storage;initialized=!1;sql;constructor(e){this.storage=e,this.sql=e.sql}async ensureInitialized(){if(!this.initialized)try{await this.sql.exec("\n-- Alarms table - supports one-time and recurring alarms\nCREATE TABLE IF NOT EXISTS alarms (\n id TEXT PRIMARY KEY,\n type TEXT NOT NULL,\n scheduled_at INTEGER NOT NULL,\n repeat_interval INTEGER,\n payload TEXT,\n created_at INTEGER NOT NULL\n);\n\n-- Index for efficient due alarm queries\nCREATE INDEX IF NOT EXISTS idx_alarms_scheduled_at ON alarms(scheduled_at);\n\n-- Actor metadata (replaces KV keys: actorType, actorId, initialCaller, input)\nCREATE TABLE IF NOT EXISTS actor_meta (\n actor_id TEXT PRIMARY KEY,\n actor_type TEXT NOT NULL,\n initial_caller TEXT NOT NULL,\n input TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n);\n\n-- Snapshots table (replaces PERSISTED_SNAPSHOT_KEY)\nCREATE TABLE IF NOT EXISTS snapshots (\n actor_id TEXT PRIMARY KEY,\n snapshot TEXT NOT NULL,\n checksum TEXT,\n updated_at INTEGER NOT NULL\n);\n"),this.initialized=!0}catch(e){throw console.error("Failed to initialize database schema:",e),e}}async getAlarms(){await this.ensureInitialized();const e=await this.sql.exec("SELECT id, type, scheduled_at, repeat_interval, payload, created_at FROM alarms ORDER BY scheduled_at ASC");return await this.parseRows(e)}async getDueAlarms(e){await this.ensureInitialized();const t=await this.sql.exec("SELECT id, type, scheduled_at, repeat_interval, payload, created_at FROM alarms WHERE scheduled_at <= ? ORDER BY scheduled_at ASC",[e]);return await this.parseRows(t)}async getEarliestAlarm(){await this.ensureInitialized();const e=await this.sql.exec("SELECT id, type, scheduled_at, repeat_interval, payload, created_at FROM alarms ORDER BY scheduled_at ASC LIMIT 1");return(await this.parseRows(e))[0]||null}async insertAlarm(e){await this.ensureInitialized(),await this.sql.exec("INSERT INTO alarms (id, type, scheduled_at, repeat_interval, payload, created_at) VALUES (?, ?, ?, ?, ?, ?)",[e.id,e.type,e.scheduledAt,e.repeatInterval??null,JSON.stringify(e.payload),Date.now()])}async updateAlarm(e){await this.ensureInitialized(),await this.sql.exec("UPDATE alarms SET scheduled_at = ?, repeat_interval = ?, payload = ? WHERE id = ?",[e.scheduledAt,e.repeatInterval??null,JSON.stringify(e.payload),e.id])}async deleteAlarm(e){await this.ensureInitialized(),await this.sql.exec("DELETE FROM alarms WHERE id = ?",[e])}async deleteAlarmsByType(e){await this.ensureInitialized(),await this.sql.exec("DELETE FROM alarms WHERE type = ?",[e])}async getActorMeta(e){if(await this.ensureInitialized(),!e){const e=await this.sql.exec("SELECT actor_id, actor_type, initial_caller, input, created_at, updated_at FROM actor_meta LIMIT 1"),t=await this.parseRows(e);if(0===t.length)return null;const a=t[0];return{actorId:a.actor_id,actorType:a.actor_type,initialCaller:JSON.parse(a.initial_caller),input:JSON.parse(a.input)}}const t=await this.sql.exec("SELECT actor_id, actor_type, initial_caller, input, created_at, updated_at FROM actor_meta WHERE actor_id = ?",[e]),a=await this.parseRows(t);if(0===a.length)return null;const s=a[0];return{actorId:s.actor_id,actorType:s.actor_type,initialCaller:JSON.parse(s.initial_caller),input:JSON.parse(s.input)}}async setActorMeta(e){await this.ensureInitialized();const t=Date.now();await this.sql.exec("INSERT INTO actor_meta (actor_id, actor_type, initial_caller, input, created_at, updated_at)\n VALUES (?, ?, ?, ?, ?, ?)\n ON CONFLICT(actor_id) DO UPDATE SET\n actor_type = excluded.actor_type,\n initial_caller = excluded.initial_caller,\n input = excluded.input,\n updated_at = excluded.updated_at",[e.actorId,e.actorType,JSON.stringify(e.initialCaller),JSON.stringify(e.input),t,t])}async deleteActorMeta(e){await this.ensureInitialized(),await this.sql.exec("DELETE FROM actor_meta WHERE actor_id = ?",[e])}async getSnapshot(e){await this.ensureInitialized();const t=await this.sql.exec("SELECT actor_id, snapshot, checksum, updated_at FROM snapshots WHERE actor_id = ?",[e]),a=await this.parseRows(t);if(0===a.length)return null;const s=a[0];return{actorId:s.actor_id,snapshot:JSON.parse(s.snapshot),checksum:s.checksum??void 0}}async setSnapshot(e,t,a){await this.ensureInitialized(),await this.sql.exec("INSERT INTO snapshots (actor_id, snapshot, checksum, updated_at)\n VALUES (?, ?, ?, ?)\n ON CONFLICT(actor_id) DO UPDATE SET\n snapshot = excluded.snapshot,\n checksum = excluded.checksum,\n updated_at = excluded.updated_at",[e,JSON.stringify(t),a??null,Date.now()])}async deleteSnapshot(e){await this.ensureInitialized(),await this.sql.exec("DELETE FROM snapshots WHERE actor_id = ?",[e])}async migrateFromKV(e){await this.ensureInitialized();const[t,a,s,r]=await Promise.all([e.get("actorType"),e.get("actorId"),e.get("initialCaller"),e.get("input")]);t&&a&&s&&r&&await this.setActorMeta({actorId:a,actorType:t,initialCaller:JSON.parse(s),input:JSON.parse(r)});const i=await e.get(p);if(i){const e=JSON.parse(i);await this.setSnapshot(a,e)}}async parseRows(e){if(e&&"function"==typeof e[Symbol.asyncIterator]){const t=e,a=[];let s=[];for await(const e of t){s||(s=e.columns);for(const t of e.results){const e={};s.forEach((a,s)=>{e[a]=t[s]}),a.push(e)}}return a}if(Array.isArray(e)&&0===e.length)return[];const{columns:t,rows:a}=e[0];return a.map(e=>{const a={};return t.forEach((t,s)=>{a[t]=e[s]}),a})}}class y{storage;state;currentAlarmId=null;currentAlarmTime=null;constructor(e,t){this.storage=e,this.state=t}async schedule(e){await this.storage.insertAlarm(e),await this.rescheduleNextAlarm()}async cancel(e){await this.storage.deleteAlarm(e),this.currentAlarmId===e&&await this.rescheduleNextAlarm()}async cancelByType(e){await this.storage.deleteAlarmsByType(e),await this.rescheduleNextAlarm()}async getPendingAlarms(){return(await this.storage.getAlarms()).map(this.parseAlarmRecord)}async getDueAlarms(e=Date.now()){return(await this.storage.getDueAlarms(e)).map(this.parseAlarmRecord)}async deleteAlarm(e){await this.storage.deleteAlarm(e)}async updateAlarm(e){await this.storage.updateAlarm(e)}async rescheduleNextAlarm(){const e=await this.storage.getEarliestAlarm();if(!e)return this.currentAlarmId=null,void(this.currentAlarmTime=null);this.currentAlarmId===e.id&&this.currentAlarmTime===e.scheduled_at||(this.currentAlarmId=e.id,this.currentAlarmTime=e.scheduled_at,await this.state.storage.setAlarm(e.scheduled_at))}async handleDueAlarms(e){const t=Date.now(),a=await this.getDueAlarms(t),s=[];for(const r of a){let a=!1,i=!0;if(r.repeatInterval){const e=t+r.repeatInterval;await this.updateAlarm({id:r.id,type:r.type,scheduledAt:e,repeatInterval:r.repeatInterval,payload:r.payload}),a=!0,i=!1}else await this.deleteAlarm(r.id);try{await e(r)}catch(e){console.error(`Error handling alarm ${r.id}:`,e)}s.push({id:r.id,type:r.type,rescheduled:a,deleted:i})}return await this.rescheduleNextAlarm(),s}getCurrentAlarm(){return{id:this.currentAlarmId,time:this.currentAlarmTime}}parseAlarmRecord(e){return{id:e.id,type:e.type,scheduledAt:e.scheduled_at,repeatInterval:e.repeat_interval??void 0,payload:e.payload?JSON.parse(e.payload):{},createdAt:e.created_at}}}function m(){return`alarm-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function E(e,t,a=Date.now()){let s=e;for(;s<a;)s+=t;return s}const T={setTimeout:()=>Math.random(),clearTimeout:()=>{}},I=new Map;function _(e,t){return{schedule:(t,a,s,r,i=Math.random().toString(36).slice(2))=>{const n=`${t.sessionId}.${i}`,l={sourceSessionId:t.sessionId,targetSessionId:a.sessionId,event:s,delay:r,id:i,startedAt:Date.now()};I.set(n,l);const c=`xstate-${n}`;e.schedule({id:c,type:"xstate-delay",scheduledAt:Date.now()+r,payload:{type:"xstate-delay",sourceSessionId:t.sessionId,targetSessionId:a.sessionId,event:s,scheduledEventId:n,alarmId:c}}).catch(e=>{console.error("[AlarmScheduler] Error scheduling alarm:",e),I.delete(n)})},cancel:(t,a)=>{const s=`${t.sessionId}.${a}`;I.delete(s),e.cancel(`xstate-${s}`).catch(e=>{console.error("[AlarmScheduler] Error canceling alarm:",e)})},cancelAll:t=>{const a=[];for(const[e,s]of I.entries())s.sourceSessionId===t.sessionId&&a.push(e);for(const t of a)I.delete(t),e.cancel(`xstate-${t}`).catch(e=>{console.error("[AlarmScheduler] Error canceling alarm:",e)})}}}async function A(e,t){const{scheduledEventId:a,event:s}=e;I.delete(a);try{t.system&&t.system._relay?t.system._relay(t,t,s):t.send(s)}catch(e){console.error("[AlarmScheduler] Error handling XState alarm:",e)}}function g(){return new Map(I)}function w(e){for(const t of e)if("xstate-delay"===t.payload.type){const{sourceSessionId:e,targetSessionId:a,event:s,scheduledEventId:r}=t.payload,i=t.scheduledAt-Date.now();i>0&&I.set(r,{sourceSessionId:e,targetSessionId:a,event:s,delay:i,id:r.split(".").pop()||r,startedAt:t.scheduledAt-i})}}export{h as ActorKitStorage,y as AlarmManager,u as AlarmTypes,i as AnyEventSchema,t as BotManagementSchema,l as CallerIdTypeSchema,r as CallerSchema,c as CallerStringSchema,d as CallerTypes,a as EnvironmentSchema,o as HEADERS,T as NOOP_CLOCK,p as PERSISTED_SNAPSHOT_KEY,s as RequestInfoSchema,n as SystemEventSchema,E as calculateNextRecurringAlarm,_ as createAlarmScheduler,m as generateAlarmId,g as getScheduledEvents,A as handleXStateAlarm,w as restoreScheduledEvents};
2
+ //# sourceMappingURL=index.js.map