@methodacting/actor-kit 0.47.0 → 0.47.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.ts +15 -284
- package/dist/index.d.ts +57 -263
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/react.d.ts +18 -286
- package/dist/react.js.map +1 -1
- package/dist/src/createActorFetch.d.ts +3 -3
- package/dist/src/createActorFetch.d.ts.map +1 -1
- package/dist/src/createActorKitContext.d.ts +3 -3
- package/dist/src/createActorKitContext.d.ts.map +1 -1
- package/dist/src/createActorKitRouter.d.ts.map +1 -1
- package/dist/src/createMachineServer.d.ts +21 -14
- package/dist/src/createMachineServer.d.ts.map +1 -1
- package/dist/src/react.d.ts +1 -0
- package/dist/src/react.d.ts.map +1 -1
- package/dist/src/schemas.d.ts +44 -250
- package/dist/src/schemas.d.ts.map +1 -1
- package/dist/src/storage.d.ts +1 -1
- package/dist/src/storage.d.ts.map +1 -1
- package/dist/src/types.d.ts +12 -12
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/worker.d.ts +1 -0
- package/dist/src/worker.d.ts.map +1 -1
- package/package.json +18 -15
- package/src/createActorFetch.ts +4 -4
- package/src/createActorKitContext.tsx +2 -3
- package/src/createActorKitRouter.ts +7 -4
- package/src/createMachineServer.ts +20 -30
- package/src/react.ts +8 -0
- package/src/schemas.ts +5 -2
- package/src/storage.ts +45 -31
- package/src/types.ts +35 -44
- package/src/worker.ts +11 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,50 +1,22 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { DurableObject } from 'cloudflare:workers';
|
|
3
3
|
import { Operation } from 'fast-json-patch';
|
|
4
|
-
import {
|
|
4
|
+
import { AnyStateMachine, EventFromLogic, StateValueFrom, SnapshotFrom, StateMachine, AnyEventObject, AnyActorRef } from 'xstate';
|
|
5
5
|
|
|
6
6
|
declare const BotManagementSchema: z.ZodObject<{
|
|
7
7
|
corporateProxy: z.ZodBoolean;
|
|
8
8
|
verifiedBot: z.ZodBoolean;
|
|
9
9
|
jsDetection: z.ZodObject<{
|
|
10
10
|
passed: z.ZodBoolean;
|
|
11
|
-
},
|
|
12
|
-
passed: boolean;
|
|
13
|
-
}, {
|
|
14
|
-
passed: boolean;
|
|
15
|
-
}>;
|
|
11
|
+
}, z.core.$strip>;
|
|
16
12
|
staticResource: z.ZodBoolean;
|
|
17
13
|
detectionIds: z.ZodRecord<z.ZodString, z.ZodAny>;
|
|
18
14
|
score: z.ZodNumber;
|
|
19
|
-
},
|
|
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
|
-
}>;
|
|
15
|
+
}, z.core.$strip>;
|
|
38
16
|
declare const EnvironmentSchema: z.ZodObject<{
|
|
39
17
|
ACTOR_KIT_SECRET: z.ZodString;
|
|
40
18
|
ACTOR_KIT_HOST: z.ZodString;
|
|
41
|
-
},
|
|
42
|
-
ACTOR_KIT_SECRET: string;
|
|
43
|
-
ACTOR_KIT_HOST: string;
|
|
44
|
-
}, {
|
|
45
|
-
ACTOR_KIT_SECRET: string;
|
|
46
|
-
ACTOR_KIT_HOST: string;
|
|
47
|
-
}>;
|
|
19
|
+
}, z.core.$strip>;
|
|
48
20
|
declare const RequestInfoSchema: z.ZodObject<{
|
|
49
21
|
longitude: z.ZodString;
|
|
50
22
|
latitude: z.ZodString;
|
|
@@ -61,258 +33,80 @@ declare const RequestInfoSchema: z.ZodObject<{
|
|
|
61
33
|
verifiedBot: z.ZodBoolean;
|
|
62
34
|
jsDetection: z.ZodObject<{
|
|
63
35
|
passed: z.ZodBoolean;
|
|
64
|
-
},
|
|
65
|
-
passed: boolean;
|
|
66
|
-
}, {
|
|
67
|
-
passed: boolean;
|
|
68
|
-
}>;
|
|
36
|
+
}, z.core.$strip>;
|
|
69
37
|
staticResource: z.ZodBoolean;
|
|
70
38
|
detectionIds: z.ZodRecord<z.ZodString, z.ZodAny>;
|
|
71
39
|
score: z.ZodNumber;
|
|
72
|
-
},
|
|
73
|
-
|
|
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
|
-
}>;
|
|
40
|
+
}, z.core.$strip>;
|
|
41
|
+
}, z.core.$strip>;
|
|
134
42
|
declare const CallerSchema: z.ZodObject<{
|
|
135
43
|
id: z.ZodString;
|
|
136
|
-
type: z.ZodEnum<
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
id: string;
|
|
143
|
-
}>;
|
|
44
|
+
type: z.ZodEnum<{
|
|
45
|
+
client: "client";
|
|
46
|
+
system: "system";
|
|
47
|
+
service: "service";
|
|
48
|
+
}>;
|
|
49
|
+
}, z.core.$strip>;
|
|
144
50
|
declare const AnyEventSchema: z.ZodObject<{
|
|
145
51
|
type: z.ZodString;
|
|
146
|
-
},
|
|
147
|
-
|
|
148
|
-
}, {
|
|
149
|
-
type: string;
|
|
150
|
-
}>;
|
|
151
|
-
declare const SystemEventSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
|
|
52
|
+
}, z.core.$strip>;
|
|
53
|
+
declare const SystemEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
152
54
|
type: z.ZodLiteral<"INITIALIZE">;
|
|
153
55
|
caller: z.ZodObject<{
|
|
154
56
|
type: z.ZodLiteral<"system">;
|
|
155
57
|
id: z.ZodString;
|
|
156
|
-
},
|
|
157
|
-
|
|
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<{
|
|
58
|
+
}, z.core.$strip>;
|
|
59
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
176
60
|
type: z.ZodLiteral<"CONNECT">;
|
|
177
61
|
caller: z.ZodObject<{
|
|
178
62
|
type: z.ZodLiteral<"system">;
|
|
179
63
|
id: z.ZodString;
|
|
180
|
-
},
|
|
181
|
-
type: "system";
|
|
182
|
-
id: string;
|
|
183
|
-
}, {
|
|
184
|
-
type: "system";
|
|
185
|
-
id: string;
|
|
186
|
-
}>;
|
|
64
|
+
}, z.core.$strip>;
|
|
187
65
|
connectingCaller: z.ZodObject<{
|
|
188
66
|
id: z.ZodString;
|
|
189
|
-
type: z.ZodEnum<
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
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<{
|
|
67
|
+
type: z.ZodEnum<{
|
|
68
|
+
client: "client";
|
|
69
|
+
system: "system";
|
|
70
|
+
service: "service";
|
|
71
|
+
}>;
|
|
72
|
+
}, z.core.$strip>;
|
|
73
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
218
74
|
type: z.ZodLiteral<"DISCONNECT">;
|
|
219
75
|
caller: z.ZodObject<{
|
|
220
76
|
type: z.ZodLiteral<"system">;
|
|
221
77
|
id: z.ZodString;
|
|
222
|
-
},
|
|
223
|
-
type: "system";
|
|
224
|
-
id: string;
|
|
225
|
-
}, {
|
|
226
|
-
type: "system";
|
|
227
|
-
id: string;
|
|
228
|
-
}>;
|
|
78
|
+
}, z.core.$strip>;
|
|
229
79
|
disconnectingCaller: z.ZodObject<{
|
|
230
80
|
id: z.ZodString;
|
|
231
|
-
type: z.ZodEnum<
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
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<{
|
|
81
|
+
type: z.ZodEnum<{
|
|
82
|
+
client: "client";
|
|
83
|
+
system: "system";
|
|
84
|
+
service: "service";
|
|
85
|
+
}>;
|
|
86
|
+
}, z.core.$strip>;
|
|
87
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
260
88
|
type: z.ZodLiteral<"RESUME">;
|
|
261
89
|
caller: z.ZodObject<{
|
|
262
90
|
type: z.ZodLiteral<"system">;
|
|
263
91
|
id: z.ZodString;
|
|
264
|
-
},
|
|
265
|
-
|
|
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<{
|
|
92
|
+
}, z.core.$strip>;
|
|
93
|
+
}, z.core.$strip>, z.ZodObject<{
|
|
284
94
|
type: z.ZodLiteral<"MIGRATE">;
|
|
285
95
|
caller: z.ZodObject<{
|
|
286
96
|
type: z.ZodLiteral<"system">;
|
|
287
97
|
id: z.ZodString;
|
|
288
|
-
},
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
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, {
|
|
98
|
+
}, z.core.$strip>;
|
|
99
|
+
operations: z.ZodArray<z.ZodAny>;
|
|
100
|
+
}, z.core.$strip>], "type">;
|
|
101
|
+
declare const CallerIdTypeSchema: z.ZodEnum<{
|
|
102
|
+
client: "client";
|
|
103
|
+
system: "system";
|
|
104
|
+
service: "service";
|
|
105
|
+
}>;
|
|
106
|
+
declare const CallerStringSchema: z.ZodPipe<z.ZodString, z.ZodTransform<{
|
|
313
107
|
type: "client" | "system" | "service";
|
|
314
108
|
id: string;
|
|
315
|
-
}, string
|
|
109
|
+
}, string>>;
|
|
316
110
|
|
|
317
111
|
interface AlarmRecord {
|
|
318
112
|
id: string;
|
|
@@ -355,7 +149,7 @@ interface Snapshot {
|
|
|
355
149
|
checksum?: string;
|
|
356
150
|
}
|
|
357
151
|
declare class ActorKitStorage {
|
|
358
|
-
private storage;
|
|
152
|
+
private readonly storage;
|
|
359
153
|
private initialized;
|
|
360
154
|
private sql;
|
|
361
155
|
constructor(storage: DurableObjectStorage);
|
|
@@ -428,7 +222,7 @@ type EnvWithDurableObjects = {
|
|
|
428
222
|
[key: string]: DurableObjectNamespace<ActorServer<any>> | unknown;
|
|
429
223
|
};
|
|
430
224
|
type AnyEvent = z.infer<typeof AnyEventSchema>;
|
|
431
|
-
interface ActorServerMethods<TMachine extends
|
|
225
|
+
interface ActorServerMethods<TMachine extends AnyStateMachine> {
|
|
432
226
|
fetch(request: Request): Promise<Response>;
|
|
433
227
|
spawn(props: {
|
|
434
228
|
actorType: string;
|
|
@@ -447,7 +241,7 @@ interface ActorServerMethods<TMachine extends BaseActorKitStateMachine> {
|
|
|
447
241
|
snapshot: CallerSnapshotFrom<TMachine>;
|
|
448
242
|
}>;
|
|
449
243
|
}
|
|
450
|
-
type ActorServer<TMachine extends
|
|
244
|
+
type ActorServer<TMachine extends AnyStateMachine> = DurableObject & ActorServerMethods<TMachine>;
|
|
451
245
|
type AnyActorServer = ActorServer<any>;
|
|
452
246
|
type Caller = z.infer<typeof CallerSchema>;
|
|
453
247
|
type RequestInfo = z.infer<typeof RequestInfoSchema>;
|
|
@@ -461,14 +255,14 @@ type CallerType = "client" | "system" | "service";
|
|
|
461
255
|
type EventObject = {
|
|
462
256
|
type: string;
|
|
463
257
|
};
|
|
464
|
-
type EventSchemaUnion = z.ZodDiscriminatedUnion<
|
|
258
|
+
type EventSchemaUnion = z.ZodDiscriminatedUnion<[
|
|
465
259
|
z.ZodObject<z.ZodRawShape & {
|
|
466
260
|
type: z.ZodString;
|
|
467
261
|
}>,
|
|
468
262
|
...z.ZodObject<z.ZodRawShape & {
|
|
469
263
|
type: z.ZodString;
|
|
470
264
|
}>[]
|
|
471
|
-
]>;
|
|
265
|
+
], "type">;
|
|
472
266
|
type EventSchemas = {
|
|
473
267
|
client: EventSchemaUnion;
|
|
474
268
|
service: EventSchemaUnion;
|
|
@@ -497,7 +291,7 @@ type BaseActorKitInput<TEnv = EnvWithDurableObjects> = {
|
|
|
497
291
|
type WithActorKitInput<TInputProps extends {
|
|
498
292
|
[key: string]: unknown;
|
|
499
293
|
}, TEnv extends EnvWithDurableObjects> = TInputProps & BaseActorKitInput<TEnv>;
|
|
500
|
-
type AnyActorKitStateMachine =
|
|
294
|
+
type AnyActorKitStateMachine = AnyStateMachine;
|
|
501
295
|
type AnyActorKitEvent = (WithActorKitEvent<AnyEventObject, "client"> | WithActorKitEvent<AnyEventObject, "service"> | ActorKitSystemEvent) & BaseActorKitEvent<EnvWithDurableObjects>;
|
|
502
296
|
type AnyActorKitInput = WithActorKitInput<{
|
|
503
297
|
[key: string]: unknown;
|
|
@@ -555,14 +349,14 @@ type CallerSnapshotFrom<TMachine extends AnyStateMachine> = {
|
|
|
555
349
|
value: infer V;
|
|
556
350
|
} ? V : unknown;
|
|
557
351
|
};
|
|
558
|
-
type ClientEventFrom<T extends
|
|
559
|
-
type ServiceEventFrom<T extends
|
|
352
|
+
type ClientEventFrom<T extends AnyStateMachine> = EventFromLogic<T> extends infer TEvent ? TEvent extends WithActorKitEvent<infer E, "client"> ? Omit<E, keyof BaseActorKitEvent<EnvWithDurableObjects>> : Omit<TEvent, keyof BaseActorKitEvent<EnvWithDurableObjects>> : never;
|
|
353
|
+
type ServiceEventFrom<T extends AnyStateMachine> = EventFromLogic<T> extends infer TEvent ? TEvent extends WithActorKitEvent<infer E, "service"> ? Omit<E, keyof BaseActorKitEvent<EnvWithDurableObjects>> : never : never;
|
|
560
354
|
type ScreamingSnakeToKebab<S extends string> = S extends `${infer T}_${infer U}` ? `${Lowercase<T>}-${ScreamingSnakeToKebab<U>}` : Lowercase<S>;
|
|
561
|
-
type DurableObjectActor<TMachine extends
|
|
355
|
+
type DurableObjectActor<TMachine extends AnyStateMachine> = ActorServer<TMachine>;
|
|
562
356
|
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
357
|
type KebabToCamelCase<S extends string> = S extends `${infer T}-${infer U}` ? `${T}${Capitalize<KebabToCamelCase<U>>}` : S;
|
|
564
358
|
type KebabToScreamingSnake<S extends string> = Uppercase<CamelToSnakeCase<KebabToCamelCase<S>>>;
|
|
565
|
-
interface MatchesProps<TMachine extends
|
|
359
|
+
interface MatchesProps<TMachine extends AnyStateMachine> {
|
|
566
360
|
state: StateValueFrom<TMachine>;
|
|
567
361
|
and?: StateValueFrom<TMachine>;
|
|
568
362
|
or?: StateValueFrom<TMachine>;
|
|
@@ -574,7 +368,7 @@ type ActorKitEmittedEvent = {
|
|
|
574
368
|
operations: Operation[];
|
|
575
369
|
checksum: string;
|
|
576
370
|
};
|
|
577
|
-
type ActorKitClient<TMachine extends
|
|
371
|
+
type ActorKitClient<TMachine extends AnyStateMachine> = {
|
|
578
372
|
connect: () => Promise<void>;
|
|
579
373
|
disconnect: () => void;
|
|
580
374
|
send: (event: ClientEventFrom<TMachine>) => void;
|
|
@@ -586,7 +380,7 @@ type ExtractEventType<TMachine> = TMachine extends ActorKitStateMachine<infer TE
|
|
|
586
380
|
type ExtractEnvType<TEvent> = TEvent extends {
|
|
587
381
|
env: infer TEnv;
|
|
588
382
|
} ? TEnv : never;
|
|
589
|
-
type EnvFromMachine<TMachine extends
|
|
383
|
+
type EnvFromMachine<TMachine extends AnyStateMachine> = ExtractEnvType<ExtractEventType<TMachine>> extends never ? EnvWithDurableObjects : ExtractEnvType<ExtractEventType<TMachine>> & EnvWithDurableObjects;
|
|
590
384
|
interface MachineServerOptions {
|
|
591
385
|
persisted?: boolean;
|
|
592
386
|
enableAlarms?: boolean;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +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};
|
|
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.string(),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 a.addIssue({code:e.ZodIssueCode.custom,message:`Invalid caller type: ${t.split("-")[0]}`}),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=null;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}const t=Array.isArray(e)?e:e?[e]:[];if(0===t.length)return[];const a=t[0],s=a?.columns??a?.columnNames??[],r=a?.rows??a?.results??[];return s.length&&r.length?r.map(e=>{const t={};return s.forEach((a,s)=>{t[a]=e[s]}),t}):[]}}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
2
|
//# sourceMappingURL=index.js.map
|