@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.
- package/LICENSE.md +7 -0
- package/README.md +2042 -0
- package/dist/browser.d.ts +384 -0
- package/dist/browser.js +2 -0
- package/dist/browser.js.map +1 -0
- package/dist/index.d.ts +644 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/react.d.ts +416 -0
- package/dist/react.js +2 -0
- package/dist/react.js.map +1 -0
- package/dist/src/alarms.d.ts +47 -0
- package/dist/src/alarms.d.ts.map +1 -0
- package/dist/src/browser.d.ts +2 -0
- package/dist/src/browser.d.ts.map +1 -0
- package/dist/src/constants.d.ts +12 -0
- package/dist/src/constants.d.ts.map +1 -0
- package/dist/src/createAccessToken.d.ts +9 -0
- package/dist/src/createAccessToken.d.ts.map +1 -0
- package/dist/src/createActorFetch.d.ts +18 -0
- package/dist/src/createActorFetch.d.ts.map +1 -0
- package/dist/src/createActorKitClient.d.ts +13 -0
- package/dist/src/createActorKitClient.d.ts.map +1 -0
- package/dist/src/createActorKitContext.d.ts +29 -0
- package/dist/src/createActorKitContext.d.ts.map +1 -0
- package/dist/src/createActorKitMockClient.d.ts +11 -0
- package/dist/src/createActorKitMockClient.d.ts.map +1 -0
- package/dist/src/createActorKitRouter.d.ts +4 -0
- package/dist/src/createActorKitRouter.d.ts.map +1 -0
- package/dist/src/createMachineServer.d.ts +20 -0
- package/dist/src/createMachineServer.d.ts.map +1 -0
- package/dist/src/durable-object-system.d.ts +36 -0
- package/dist/src/durable-object-system.d.ts.map +1 -0
- package/dist/src/index.d.ts +7 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/react.d.ts +2 -0
- package/dist/src/react.d.ts.map +1 -0
- package/dist/src/schemas.d.ts +312 -0
- package/dist/src/schemas.d.ts.map +1 -0
- package/dist/src/server.d.ts +3 -0
- package/dist/src/server.d.ts.map +1 -0
- package/dist/src/storage.d.ts +64 -0
- package/dist/src/storage.d.ts.map +1 -0
- package/dist/src/storybook.d.ts +13 -0
- package/dist/src/storybook.d.ts.map +1 -0
- package/dist/src/test.d.ts +2 -0
- package/dist/src/test.d.ts.map +1 -0
- package/dist/src/types.d.ts +181 -0
- package/dist/src/types.d.ts.map +1 -0
- package/dist/src/utils.d.ts +30 -0
- package/dist/src/utils.d.ts.map +1 -0
- package/dist/src/withActorKit.d.ts +9 -0
- package/dist/src/withActorKit.d.ts.map +1 -0
- package/dist/src/worker.d.ts +3 -0
- package/dist/src/worker.d.ts.map +1 -0
- package/package.json +87 -0
- package/src/alarms.ts +237 -0
- package/src/browser.ts +1 -0
- package/src/constants.ts +31 -0
- package/src/createAccessToken.ts +29 -0
- package/src/createActorFetch.ts +111 -0
- package/src/createActorKitClient.ts +224 -0
- package/src/createActorKitContext.tsx +228 -0
- package/src/createActorKitMockClient.ts +138 -0
- package/src/createActorKitRouter.ts +149 -0
- package/src/createMachineServer.ts +844 -0
- package/src/durable-object-system.ts +212 -0
- package/src/global.d.ts +7 -0
- package/src/index.ts +6 -0
- package/src/react.ts +1 -0
- package/src/schemas.ts +95 -0
- package/src/server.ts +3 -0
- package/src/storage.ts +404 -0
- package/src/storybook.ts +42 -0
- package/src/test.ts +1 -0
- package/src/types.ts +334 -0
- package/src/utils.ts +171 -0
- package/src/withActorKit.tsx +103 -0
- package/src/worker.ts +2 -0
|
@@ -0,0 +1,384 @@
|
|
|
1
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
2
|
+
import { AnyEventObject, StateMachine, StateValueFrom, AnyStateMachine, SnapshotFrom } from 'xstate';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
|
|
5
|
+
declare const RequestInfoSchema: z.ZodObject<{
|
|
6
|
+
longitude: z.ZodString;
|
|
7
|
+
latitude: z.ZodString;
|
|
8
|
+
continent: z.ZodString;
|
|
9
|
+
country: z.ZodString;
|
|
10
|
+
city: z.ZodString;
|
|
11
|
+
timezone: z.ZodString;
|
|
12
|
+
postalCode: z.ZodString;
|
|
13
|
+
region: z.ZodString;
|
|
14
|
+
regionCode: z.ZodString;
|
|
15
|
+
metroCode: z.ZodString;
|
|
16
|
+
botManagement: z.ZodObject<{
|
|
17
|
+
corporateProxy: z.ZodBoolean;
|
|
18
|
+
verifiedBot: z.ZodBoolean;
|
|
19
|
+
jsDetection: z.ZodObject<{
|
|
20
|
+
passed: z.ZodBoolean;
|
|
21
|
+
}, "strip", z.ZodTypeAny, {
|
|
22
|
+
passed: boolean;
|
|
23
|
+
}, {
|
|
24
|
+
passed: boolean;
|
|
25
|
+
}>;
|
|
26
|
+
staticResource: z.ZodBoolean;
|
|
27
|
+
detectionIds: z.ZodRecord<z.ZodString, z.ZodAny>;
|
|
28
|
+
score: z.ZodNumber;
|
|
29
|
+
}, "strip", z.ZodTypeAny, {
|
|
30
|
+
corporateProxy: boolean;
|
|
31
|
+
verifiedBot: boolean;
|
|
32
|
+
jsDetection: {
|
|
33
|
+
passed: boolean;
|
|
34
|
+
};
|
|
35
|
+
staticResource: boolean;
|
|
36
|
+
detectionIds: Record<string, any>;
|
|
37
|
+
score: number;
|
|
38
|
+
}, {
|
|
39
|
+
corporateProxy: boolean;
|
|
40
|
+
verifiedBot: boolean;
|
|
41
|
+
jsDetection: {
|
|
42
|
+
passed: boolean;
|
|
43
|
+
};
|
|
44
|
+
staticResource: boolean;
|
|
45
|
+
detectionIds: Record<string, any>;
|
|
46
|
+
score: number;
|
|
47
|
+
}>;
|
|
48
|
+
}, "strip", z.ZodTypeAny, {
|
|
49
|
+
longitude: string;
|
|
50
|
+
latitude: string;
|
|
51
|
+
continent: string;
|
|
52
|
+
country: string;
|
|
53
|
+
city: string;
|
|
54
|
+
timezone: string;
|
|
55
|
+
postalCode: string;
|
|
56
|
+
region: string;
|
|
57
|
+
regionCode: string;
|
|
58
|
+
metroCode: string;
|
|
59
|
+
botManagement: {
|
|
60
|
+
corporateProxy: boolean;
|
|
61
|
+
verifiedBot: boolean;
|
|
62
|
+
jsDetection: {
|
|
63
|
+
passed: boolean;
|
|
64
|
+
};
|
|
65
|
+
staticResource: boolean;
|
|
66
|
+
detectionIds: Record<string, any>;
|
|
67
|
+
score: number;
|
|
68
|
+
};
|
|
69
|
+
}, {
|
|
70
|
+
longitude: string;
|
|
71
|
+
latitude: string;
|
|
72
|
+
continent: string;
|
|
73
|
+
country: string;
|
|
74
|
+
city: string;
|
|
75
|
+
timezone: string;
|
|
76
|
+
postalCode: string;
|
|
77
|
+
region: string;
|
|
78
|
+
regionCode: string;
|
|
79
|
+
metroCode: string;
|
|
80
|
+
botManagement: {
|
|
81
|
+
corporateProxy: boolean;
|
|
82
|
+
verifiedBot: boolean;
|
|
83
|
+
jsDetection: {
|
|
84
|
+
passed: boolean;
|
|
85
|
+
};
|
|
86
|
+
staticResource: boolean;
|
|
87
|
+
detectionIds: Record<string, any>;
|
|
88
|
+
score: number;
|
|
89
|
+
};
|
|
90
|
+
}>;
|
|
91
|
+
declare const CallerSchema: z.ZodObject<{
|
|
92
|
+
id: z.ZodString;
|
|
93
|
+
type: z.ZodEnum<["client", "system", "service"]>;
|
|
94
|
+
}, "strip", z.ZodTypeAny, {
|
|
95
|
+
type: "client" | "system" | "service";
|
|
96
|
+
id: string;
|
|
97
|
+
}, {
|
|
98
|
+
type: "client" | "system" | "service";
|
|
99
|
+
id: string;
|
|
100
|
+
}>;
|
|
101
|
+
declare const SystemEventSchema: z.ZodDiscriminatedUnion<"type", [z.ZodObject<{
|
|
102
|
+
type: z.ZodLiteral<"INITIALIZE">;
|
|
103
|
+
caller: z.ZodObject<{
|
|
104
|
+
type: z.ZodLiteral<"system">;
|
|
105
|
+
id: z.ZodString;
|
|
106
|
+
}, "strip", z.ZodTypeAny, {
|
|
107
|
+
type: "system";
|
|
108
|
+
id: string;
|
|
109
|
+
}, {
|
|
110
|
+
type: "system";
|
|
111
|
+
id: string;
|
|
112
|
+
}>;
|
|
113
|
+
}, "strip", z.ZodTypeAny, {
|
|
114
|
+
type: "INITIALIZE";
|
|
115
|
+
caller: {
|
|
116
|
+
type: "system";
|
|
117
|
+
id: string;
|
|
118
|
+
};
|
|
119
|
+
}, {
|
|
120
|
+
type: "INITIALIZE";
|
|
121
|
+
caller: {
|
|
122
|
+
type: "system";
|
|
123
|
+
id: string;
|
|
124
|
+
};
|
|
125
|
+
}>, z.ZodObject<{
|
|
126
|
+
type: z.ZodLiteral<"CONNECT">;
|
|
127
|
+
caller: z.ZodObject<{
|
|
128
|
+
type: z.ZodLiteral<"system">;
|
|
129
|
+
id: z.ZodString;
|
|
130
|
+
}, "strip", z.ZodTypeAny, {
|
|
131
|
+
type: "system";
|
|
132
|
+
id: string;
|
|
133
|
+
}, {
|
|
134
|
+
type: "system";
|
|
135
|
+
id: string;
|
|
136
|
+
}>;
|
|
137
|
+
connectingCaller: z.ZodObject<{
|
|
138
|
+
id: z.ZodString;
|
|
139
|
+
type: z.ZodEnum<["client", "system", "service"]>;
|
|
140
|
+
}, "strip", z.ZodTypeAny, {
|
|
141
|
+
type: "client" | "system" | "service";
|
|
142
|
+
id: string;
|
|
143
|
+
}, {
|
|
144
|
+
type: "client" | "system" | "service";
|
|
145
|
+
id: string;
|
|
146
|
+
}>;
|
|
147
|
+
}, "strip", z.ZodTypeAny, {
|
|
148
|
+
type: "CONNECT";
|
|
149
|
+
caller: {
|
|
150
|
+
type: "system";
|
|
151
|
+
id: string;
|
|
152
|
+
};
|
|
153
|
+
connectingCaller: {
|
|
154
|
+
type: "client" | "system" | "service";
|
|
155
|
+
id: string;
|
|
156
|
+
};
|
|
157
|
+
}, {
|
|
158
|
+
type: "CONNECT";
|
|
159
|
+
caller: {
|
|
160
|
+
type: "system";
|
|
161
|
+
id: string;
|
|
162
|
+
};
|
|
163
|
+
connectingCaller: {
|
|
164
|
+
type: "client" | "system" | "service";
|
|
165
|
+
id: string;
|
|
166
|
+
};
|
|
167
|
+
}>, z.ZodObject<{
|
|
168
|
+
type: z.ZodLiteral<"DISCONNECT">;
|
|
169
|
+
caller: z.ZodObject<{
|
|
170
|
+
type: z.ZodLiteral<"system">;
|
|
171
|
+
id: z.ZodString;
|
|
172
|
+
}, "strip", z.ZodTypeAny, {
|
|
173
|
+
type: "system";
|
|
174
|
+
id: string;
|
|
175
|
+
}, {
|
|
176
|
+
type: "system";
|
|
177
|
+
id: string;
|
|
178
|
+
}>;
|
|
179
|
+
disconnectingCaller: z.ZodObject<{
|
|
180
|
+
id: z.ZodString;
|
|
181
|
+
type: z.ZodEnum<["client", "system", "service"]>;
|
|
182
|
+
}, "strip", z.ZodTypeAny, {
|
|
183
|
+
type: "client" | "system" | "service";
|
|
184
|
+
id: string;
|
|
185
|
+
}, {
|
|
186
|
+
type: "client" | "system" | "service";
|
|
187
|
+
id: string;
|
|
188
|
+
}>;
|
|
189
|
+
}, "strip", z.ZodTypeAny, {
|
|
190
|
+
type: "DISCONNECT";
|
|
191
|
+
caller: {
|
|
192
|
+
type: "system";
|
|
193
|
+
id: string;
|
|
194
|
+
};
|
|
195
|
+
disconnectingCaller: {
|
|
196
|
+
type: "client" | "system" | "service";
|
|
197
|
+
id: string;
|
|
198
|
+
};
|
|
199
|
+
}, {
|
|
200
|
+
type: "DISCONNECT";
|
|
201
|
+
caller: {
|
|
202
|
+
type: "system";
|
|
203
|
+
id: string;
|
|
204
|
+
};
|
|
205
|
+
disconnectingCaller: {
|
|
206
|
+
type: "client" | "system" | "service";
|
|
207
|
+
id: string;
|
|
208
|
+
};
|
|
209
|
+
}>, z.ZodObject<{
|
|
210
|
+
type: z.ZodLiteral<"RESUME">;
|
|
211
|
+
caller: z.ZodObject<{
|
|
212
|
+
type: z.ZodLiteral<"system">;
|
|
213
|
+
id: z.ZodString;
|
|
214
|
+
}, "strip", z.ZodTypeAny, {
|
|
215
|
+
type: "system";
|
|
216
|
+
id: string;
|
|
217
|
+
}, {
|
|
218
|
+
type: "system";
|
|
219
|
+
id: string;
|
|
220
|
+
}>;
|
|
221
|
+
}, "strip", z.ZodTypeAny, {
|
|
222
|
+
type: "RESUME";
|
|
223
|
+
caller: {
|
|
224
|
+
type: "system";
|
|
225
|
+
id: string;
|
|
226
|
+
};
|
|
227
|
+
}, {
|
|
228
|
+
type: "RESUME";
|
|
229
|
+
caller: {
|
|
230
|
+
type: "system";
|
|
231
|
+
id: string;
|
|
232
|
+
};
|
|
233
|
+
}>, z.ZodObject<{
|
|
234
|
+
type: z.ZodLiteral<"MIGRATE">;
|
|
235
|
+
caller: z.ZodObject<{
|
|
236
|
+
type: z.ZodLiteral<"system">;
|
|
237
|
+
id: z.ZodString;
|
|
238
|
+
}, "strip", z.ZodTypeAny, {
|
|
239
|
+
type: "system";
|
|
240
|
+
id: string;
|
|
241
|
+
}, {
|
|
242
|
+
type: "system";
|
|
243
|
+
id: string;
|
|
244
|
+
}>;
|
|
245
|
+
operations: z.ZodArray<z.ZodAny, "many">;
|
|
246
|
+
}, "strip", z.ZodTypeAny, {
|
|
247
|
+
type: "MIGRATE";
|
|
248
|
+
caller: {
|
|
249
|
+
type: "system";
|
|
250
|
+
id: string;
|
|
251
|
+
};
|
|
252
|
+
operations: any[];
|
|
253
|
+
}, {
|
|
254
|
+
type: "MIGRATE";
|
|
255
|
+
caller: {
|
|
256
|
+
type: "system";
|
|
257
|
+
id: string;
|
|
258
|
+
};
|
|
259
|
+
operations: any[];
|
|
260
|
+
}>]>;
|
|
261
|
+
|
|
262
|
+
type EnvWithDurableObjects = {
|
|
263
|
+
ACTOR_KIT_SECRET: string;
|
|
264
|
+
[key: string]: DurableObjectNamespace<ActorServer<any>> | unknown;
|
|
265
|
+
};
|
|
266
|
+
interface ActorServerMethods<TMachine extends BaseActorKitStateMachine> {
|
|
267
|
+
fetch(request: Request): Promise<Response>;
|
|
268
|
+
spawn(props: {
|
|
269
|
+
actorType: string;
|
|
270
|
+
actorId: string;
|
|
271
|
+
caller: Caller;
|
|
272
|
+
input: Record<string, unknown>;
|
|
273
|
+
}): void;
|
|
274
|
+
send(event: ClientEventFrom<TMachine> | ServiceEventFrom<TMachine>): void;
|
|
275
|
+
getSnapshot(caller: Caller, options?: {
|
|
276
|
+
waitForEvent?: ClientEventFrom<TMachine>;
|
|
277
|
+
waitForState?: StateValueFrom<TMachine>;
|
|
278
|
+
timeout?: number;
|
|
279
|
+
errorOnWaitTimeout?: boolean;
|
|
280
|
+
}): Promise<{
|
|
281
|
+
checksum: string;
|
|
282
|
+
snapshot: CallerSnapshotFrom<TMachine>;
|
|
283
|
+
}>;
|
|
284
|
+
}
|
|
285
|
+
type ActorServer<TMachine extends AnyActorKitStateMachine> = DurableObject & ActorServerMethods<TMachine>;
|
|
286
|
+
type Caller = z.infer<typeof CallerSchema>;
|
|
287
|
+
type RequestInfo = z.infer<typeof RequestInfoSchema>;
|
|
288
|
+
type CallerType = "client" | "system" | "service";
|
|
289
|
+
type EventObject = {
|
|
290
|
+
type: string;
|
|
291
|
+
};
|
|
292
|
+
type BaseActorKitContext<TPublicProps extends {
|
|
293
|
+
[key: string]: unknown;
|
|
294
|
+
}, TPrivateProps extends {
|
|
295
|
+
[key: string]: unknown;
|
|
296
|
+
}> = {
|
|
297
|
+
public: TPublicProps;
|
|
298
|
+
private: Record<string, TPrivateProps>;
|
|
299
|
+
};
|
|
300
|
+
type ActorKitStateMachine<TEvent extends BaseActorKitEvent<EnvWithDurableObjects>, TInput extends {
|
|
301
|
+
id: string;
|
|
302
|
+
caller: Caller;
|
|
303
|
+
storage: DurableObjectStorage;
|
|
304
|
+
}, TContext extends BaseActorKitContext<any, any> & {
|
|
305
|
+
[key: string]: unknown;
|
|
306
|
+
}> = StateMachine<TContext, TEvent & EventObject, any, any, any, any, any, any, any, TInput, any, any, any, any>;
|
|
307
|
+
type BaseActorKitInput<TEnv = EnvWithDurableObjects> = {
|
|
308
|
+
id: string;
|
|
309
|
+
caller: Caller;
|
|
310
|
+
env: TEnv;
|
|
311
|
+
storage: DurableObjectStorage;
|
|
312
|
+
};
|
|
313
|
+
type WithActorKitInput<TInputProps extends {
|
|
314
|
+
[key: string]: unknown;
|
|
315
|
+
}, TEnv extends EnvWithDurableObjects> = TInputProps & BaseActorKitInput<TEnv>;
|
|
316
|
+
type AnyActorKitStateMachine = ActorKitStateMachine<any, any, any>;
|
|
317
|
+
type AnyActorKitEvent = (WithActorKitEvent<AnyEventObject, "client"> | WithActorKitEvent<AnyEventObject, "service"> | ActorKitSystemEvent) & BaseActorKitEvent<EnvWithDurableObjects>;
|
|
318
|
+
type AnyActorKitInput = WithActorKitInput<{
|
|
319
|
+
[key: string]: unknown;
|
|
320
|
+
}, EnvWithDurableObjects> & {
|
|
321
|
+
storage: DurableObjectStorage;
|
|
322
|
+
};
|
|
323
|
+
type AnyActorKitContext = {
|
|
324
|
+
public: {
|
|
325
|
+
[key: string]: unknown;
|
|
326
|
+
};
|
|
327
|
+
private: Record<string, {
|
|
328
|
+
[key: string]: unknown;
|
|
329
|
+
}>;
|
|
330
|
+
};
|
|
331
|
+
type BaseActorKitStateMachine = ActorKitStateMachine<AnyActorKitEvent, AnyActorKitInput, AnyActorKitContext>;
|
|
332
|
+
interface BaseActorKitEvent<TEnv extends EnvWithDurableObjects> {
|
|
333
|
+
caller: Caller;
|
|
334
|
+
storage: DurableObjectStorage;
|
|
335
|
+
requestInfo?: RequestInfo;
|
|
336
|
+
env: TEnv;
|
|
337
|
+
}
|
|
338
|
+
type ActorKitSystemEvent = z.infer<typeof SystemEventSchema>;
|
|
339
|
+
type WithActorKitEvent<T extends {
|
|
340
|
+
type: string;
|
|
341
|
+
}, C extends CallerType> = T & BaseActorKitEvent<EnvWithDurableObjects> & {
|
|
342
|
+
caller: {
|
|
343
|
+
type: C;
|
|
344
|
+
};
|
|
345
|
+
};
|
|
346
|
+
type CallerSnapshotFrom<TMachine extends AnyStateMachine> = {
|
|
347
|
+
public: SnapshotFrom<TMachine> extends {
|
|
348
|
+
context: {
|
|
349
|
+
public: infer P;
|
|
350
|
+
};
|
|
351
|
+
} ? P : unknown;
|
|
352
|
+
private: SnapshotFrom<TMachine> extends {
|
|
353
|
+
context: {
|
|
354
|
+
private: Partial<Record<string, infer PR>>;
|
|
355
|
+
};
|
|
356
|
+
} ? PR : unknown;
|
|
357
|
+
value: SnapshotFrom<TMachine> extends {
|
|
358
|
+
value: infer V;
|
|
359
|
+
} ? V : unknown;
|
|
360
|
+
};
|
|
361
|
+
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;
|
|
362
|
+
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;
|
|
363
|
+
type ActorKitClient<TMachine extends AnyActorKitStateMachine> = {
|
|
364
|
+
connect: () => Promise<void>;
|
|
365
|
+
disconnect: () => void;
|
|
366
|
+
send: (event: ClientEventFrom<TMachine>) => void;
|
|
367
|
+
getState: () => CallerSnapshotFrom<TMachine>;
|
|
368
|
+
subscribe: (listener: (state: CallerSnapshotFrom<TMachine>) => void) => () => void;
|
|
369
|
+
waitFor: (predicateFn: (state: CallerSnapshotFrom<TMachine>) => boolean, timeoutMs?: number) => Promise<void>;
|
|
370
|
+
};
|
|
371
|
+
|
|
372
|
+
type ActorKitClientProps<TMachine extends AnyActorKitStateMachine> = {
|
|
373
|
+
host: string;
|
|
374
|
+
actorType: string;
|
|
375
|
+
actorId: string;
|
|
376
|
+
checksum: string;
|
|
377
|
+
accessToken: string;
|
|
378
|
+
initialSnapshot: CallerSnapshotFrom<TMachine>;
|
|
379
|
+
onStateChange?: (newState: CallerSnapshotFrom<TMachine>) => void;
|
|
380
|
+
onError?: (error: Error) => void;
|
|
381
|
+
};
|
|
382
|
+
declare function createActorKitClient<TMachine extends AnyActorKitStateMachine>(props: ActorKitClientProps<TMachine>): ActorKitClient<TMachine>;
|
|
383
|
+
|
|
384
|
+
export { createActorKitClient };
|
package/dist/browser.js
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{applyPatch as e}from"fast-json-patch";import{produce as t}from"immer";function r(r){let o=r.initialSnapshot,n=null;const s=new Set;let c=0;const a=async()=>{const i=function(e){const{host:t,actorId:r,actorType:o,accessToken:n,checksum:s}=e,c=`${/^(localhost|127\.0\.0\.1|192\.168\.|10\.|172\.(1[6-9]|2[0-9]|3[0-1])\.)/.test(t)?"ws":"wss"}://${t}/api/${o}/${r}`,a=new URLSearchParams({accessToken:n});s&&a.append("checksum",s);return`${c}?${a.toString()}`}(r);return n=new WebSocket(i),n.addEventListener("open",()=>{c=0}),n.addEventListener("message",n=>{try{const c=JSON.parse("string"==typeof n.data?n.data:(new TextDecoder).decode(n.data));o=t(o,t=>{e(t,c.operations)}),r.onStateChange?.(o),s.forEach(e=>e(o))}catch(e){console.error("[ActorKitClient] Error processing message:",e),r.onError?.(e)}}),n.addEventListener("error",e=>{console.error("[ActorKitClient] WebSocket error:",e),console.error("[ActorKitClient] Error details:",{message:e.message,type:e.type,target:e.target,eventPhase:e.eventPhase}),r.onError?.(new Error(`WebSocket error: ${JSON.stringify(e)}`))}),n.addEventListener("close",e=>{if(c<5){c++;const e=Math.min(1e3*Math.pow(2,c),3e4);setTimeout(a,e)}else console.error("[ActorKitClient] Max reconnection attempts reached")}),new Promise(e=>{n.addEventListener("open",()=>e())})},i=e=>(s.add(e),()=>{s.delete(e)});return{connect:a,disconnect:()=>{n&&(n.close(),n=null)},send:e=>{n&&n.readyState===WebSocket.OPEN?n.send(JSON.stringify(e)):r.onError?.(new Error("Cannot send event: WebSocket is not connected"))},getState:()=>o,subscribe:i,waitFor:async(e,t=5e3)=>e(o)?Promise.resolve():new Promise((r,o)=>{let n=null;t>0&&(n=setTimeout(()=>{s(),o(new Error(`Timeout waiting for condition after ${t}ms`))},t));const s=i(t=>{e(t)&&(n&&clearTimeout(n),s(),r())})})}}export{r as createActorKitClient};
|
|
2
|
+
//# sourceMappingURL=browser.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"browser.js","sources":["../src/createActorKitClient.ts"],"sourcesContent":["import { applyPatch } from \"fast-json-patch\";\nimport { produce } from \"immer\";\n\nimport {\n ActorKitClient,\n ActorKitEmittedEvent,\n AnyActorKitStateMachine,\n CallerSnapshotFrom,\n ClientEventFrom,\n} from \"./types\";\n\nexport type ActorKitClientProps<TMachine extends AnyActorKitStateMachine> = {\n host: string;\n actorType: string;\n actorId: string;\n checksum: string;\n accessToken: string;\n initialSnapshot: CallerSnapshotFrom<TMachine>;\n onStateChange?: (newState: CallerSnapshotFrom<TMachine>) => void;\n onError?: (error: Error) => void;\n};\n\ntype Listener<T> = (state: T) => void;\n\n/**\n * Creates an Actor Kit client for managing state and communication with the server.\n *\n * @template TMachine - The type of the state machine.\n * @param {ActorKitClientProps<TMachine>} props - Configuration options for the client.\n * @returns {ActorKitClient<TMachine>} An object with methods to interact with the actor.\n */\nexport function createActorKitClient<TMachine extends AnyActorKitStateMachine>(\n props: ActorKitClientProps<TMachine>\n): ActorKitClient<TMachine> {\n let currentSnapshot = props.initialSnapshot;\n let socket: WebSocket | null = null;\n const listeners: Set<Listener<CallerSnapshotFrom<TMachine>>> = new Set();\n let reconnectAttempts = 0;\n const maxReconnectAttempts = 5;\n\n /**\n * Notifies all registered listeners with the current state.\n */\n const notifyListeners = () => {\n listeners.forEach((listener) => listener(currentSnapshot));\n };\n\n /**\n * Establishes a WebSocket connection to the Actor Kit server.\n * @returns {Promise<void>} A promise that resolves when the connection is established.\n */\n const connect = async () => {\n const url = getWebSocketUrl(props);\n\n socket = new WebSocket(url);\n\n socket.addEventListener(\"open\", () => {\n reconnectAttempts = 0;\n });\n\n socket.addEventListener(\"message\", (event: MessageEvent) => {\n try {\n const data = JSON.parse(\n typeof event.data === \"string\"\n ? event.data\n : new TextDecoder().decode(event.data)\n ) as ActorKitEmittedEvent;\n\n currentSnapshot = produce(currentSnapshot, (draft) => {\n applyPatch(draft, data.operations);\n });\n\n props.onStateChange?.(currentSnapshot);\n notifyListeners();\n } catch (error) {\n console.error(`[ActorKitClient] Error processing message:`, error);\n props.onError?.(error as Error);\n }\n });\n\n socket.addEventListener(\"error\", (error: any) => {\n console.error(`[ActorKitClient] WebSocket error:`, error);\n console.error(`[ActorKitClient] Error details:`, {\n message: error.message,\n type: error.type,\n target: error.target,\n eventPhase: error.eventPhase,\n });\n props.onError?.(new Error(`WebSocket error: ${JSON.stringify(error)}`));\n });\n\n // todo, how do we reconnect when a user returns to the tab\n // later after it's disconnected\n\n socket.addEventListener(\"close\", (event) => {\n // Implement reconnection logic\n if (reconnectAttempts < maxReconnectAttempts) {\n reconnectAttempts++;\n const delay = Math.min(1000 * Math.pow(2, reconnectAttempts), 30000);\n setTimeout(connect, delay);\n } else {\n console.error(`[ActorKitClient] Max reconnection attempts reached`);\n }\n });\n\n return new Promise<void>((resolve) => {\n socket!.addEventListener(\"open\", () => resolve());\n });\n };\n\n /**\n * Closes the WebSocket connection to the Actor Kit server.\n */\n const disconnect = () => {\n if (socket) {\n socket.close();\n socket = null;\n }\n };\n\n /**\n * Sends an event to the Actor Kit server.\n * @param {ClientEventFrom<TMachine>} event - The event to send.\n */\n const send = (event: ClientEventFrom<TMachine>) => {\n if (socket && socket.readyState === WebSocket.OPEN) {\n socket.send(JSON.stringify(event));\n } else {\n props.onError?.(\n new Error(\"Cannot send event: WebSocket is not connected\")\n );\n }\n };\n\n /**\n * Retrieves the current state of the actor.\n * @returns {CallerSnapshotFrom<TMachine>} The current state.\n */\n const getState = () => currentSnapshot;\n\n /**\n * Subscribes a listener to state changes.\n * @param {Listener<CallerSnapshotFrom<TMachine>>} listener - The listener function to be called on state changes.\n * @returns {() => void} A function to unsubscribe the listener.\n */\n const subscribe = (listener: Listener<CallerSnapshotFrom<TMachine>>) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n };\n\n /**\n * Waits for a state condition to be met.\n * @param {(state: CallerSnapshotFrom<TMachine>) => boolean} predicateFn - Function that returns true when condition is met\n * @param {number} [timeoutMs=5000] - Maximum time to wait in milliseconds\n * @returns {Promise<void>} Resolves when condition is met, rejects on timeout\n */\n const waitFor = async (\n predicateFn: (state: CallerSnapshotFrom<TMachine>) => boolean,\n timeoutMs: number = 5000\n ): Promise<void> => {\n // Check if condition is already met\n if (predicateFn(currentSnapshot)) {\n return Promise.resolve();\n }\n return new Promise((resolve, reject) => {\n let timeoutId: number | null = null;\n\n // Set up timeout to reject if condition isn't met in time\n if (timeoutMs > 0) {\n timeoutId = setTimeout(() => {\n unsubscribe();\n reject(\n new Error(`Timeout waiting for condition after ${timeoutMs}ms`)\n );\n }, timeoutMs);\n }\n\n // Subscribe to state changes\n const unsubscribe = subscribe((state) => {\n if (predicateFn(state)) {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n unsubscribe();\n resolve();\n }\n });\n });\n };\n\n return {\n connect,\n disconnect,\n send,\n getState,\n subscribe,\n waitFor,\n };\n}\n\nfunction getWebSocketUrl(props: ActorKitClientProps<any>): string {\n const { host, actorId, actorType, accessToken, checksum } = props;\n\n // Determine protocol (ws or wss)\n const protocol =\n /^(localhost|127\\.0\\.0\\.1|192\\.168\\.|10\\.|172\\.(1[6-9]|2[0-9]|3[0-1])\\.)/.test(\n host\n )\n ? \"ws\"\n : \"wss\";\n\n // Construct base URL\n const baseUrl = `${protocol}://${host}/api/${actorType}/${actorId}`;\n\n // Add query parameters\n const params = new URLSearchParams({ accessToken });\n if (checksum) params.append(\"checksum\", checksum);\n\n const finalUrl = `${baseUrl}?${params.toString()}`;\n\n return finalUrl;\n}\n"],"names":["createActorKitClient","props","currentSnapshot","initialSnapshot","socket","listeners","Set","reconnectAttempts","connect","async","url","host","actorId","actorType","accessToken","checksum","baseUrl","test","params","URLSearchParams","append","toString","getWebSocketUrl","WebSocket","addEventListener","event","data","JSON","parse","TextDecoder","decode","produce","draft","applyPatch","operations","onStateChange","forEach","listener","error","console","onError","message","type","target","eventPhase","Error","stringify","delay","Math","min","pow","setTimeout","Promise","resolve","subscribe","add","delete","disconnect","close","send","readyState","OPEN","getState","waitFor","predicateFn","timeoutMs","reject","timeoutId","unsubscribe","state","clearTimeout"],"mappings":"6EA+BM,SAAUA,EACdC,GAEA,IAAIC,EAAkBD,EAAME,gBACxBC,EAA2B,KAC/B,MAAMC,EAAyD,IAAIC,IACnE,IAAIC,EAAoB,EACxB,MAaMC,EAAUC,UACd,MAAMC,EAsJV,SAAyBT,GACvB,MAAMU,KAAEA,EAAIC,QAAEA,EAAOC,UAAEA,EAASC,YAAEA,EAAWC,SAAEA,GAAad,EAWtDe,EAAU,GAPd,0EAA0EC,KACxEN,GAEE,KACA,WAG2BA,SAAYE,KAAaD,IAGpDM,EAAS,IAAIC,gBAAgB,CAAEL,gBACjCC,GAAUG,EAAOE,OAAO,WAAYL,GAIxC,MAFiB,GAAGC,KAAWE,EAAOG,YAGxC,CA3KgBC,CAAgBrB,GAqD5B,OAnDAG,EAAS,IAAImB,UAAUb,GAEvBN,EAAOoB,iBAAiB,OAAQ,KAC9BjB,EAAoB,IAGtBH,EAAOoB,iBAAiB,UAAYC,IAClC,IACE,MAAMC,EAAOC,KAAKC,MACM,iBAAfH,EAAMC,KACTD,EAAMC,MACN,IAAIG,aAAcC,OAAOL,EAAMC,OAGrCxB,EAAkB6B,EAAQ7B,EAAkB8B,IAC1CC,EAAWD,EAAON,EAAKQ,cAGzBjC,EAAMkC,gBAAgBjC,GA5B1BG,EAAU+B,QAASC,GAAaA,EAASnC,GA8BvC,CAAE,MAAOoC,GACPC,QAAQD,MAAM,6CAA8CA,GAC5DrC,EAAMuC,UAAUF,EAClB,IAGFlC,EAAOoB,iBAAiB,QAAUc,IAChCC,QAAQD,MAAM,oCAAqCA,GACnDC,QAAQD,MAAM,kCAAmC,CAC/CG,QAASH,EAAMG,QACfC,KAAMJ,EAAMI,KACZC,OAAQL,EAAMK,OACdC,WAAYN,EAAMM,aAEpB3C,EAAMuC,UAAU,IAAIK,MAAM,oBAAoBlB,KAAKmB,UAAUR,SAM/DlC,EAAOoB,iBAAiB,QAAUC,IAEhC,GAAIlB,EA1DqB,EA0DqB,CAC5CA,IACA,MAAMwC,EAAQC,KAAKC,IAAI,IAAOD,KAAKE,IAAI,EAAG3C,GAAoB,KAC9D4C,WAAW3C,EAASuC,EACtB,MACER,QAAQD,MAAM,wDAIX,IAAIc,QAAeC,IACxBjD,EAAQoB,iBAAiB,OAAQ,IAAM6B,QAuCrCC,EAAajB,IACjBhC,EAAUkD,IAAIlB,GACP,KACLhC,EAAUmD,OAAOnB,KA4CrB,MAAO,CACL7B,UACAiD,WAjFiB,KACbrD,IACFA,EAAOsD,QACPtD,EAAS,OA+EXuD,KAvEYlC,IACRrB,GAAUA,EAAOwD,aAAerC,UAAUsC,KAC5CzD,EAAOuD,KAAKhC,KAAKmB,UAAUrB,IAE3BxB,EAAMuC,UACJ,IAAIK,MAAM,mDAmEdiB,SA1De,IAAM5D,EA2DrBoD,YACAS,QAxCctD,MACduD,EACAC,EAAoB,MAGhBD,EAAY9D,GACPkD,QAAQC,UAEV,IAAID,QAAQ,CAACC,EAASa,KAC3B,IAAIC,EAA2B,KAG3BF,EAAY,IACdE,EAAYhB,WAAW,KACrBiB,IACAF,EACE,IAAIrB,MAAM,uCAAuCoB,SAElDA,IAIL,MAAMG,EAAcd,EAAWe,IACzBL,EAAYK,KACVF,GACFG,aAAaH,GAEfC,IACAf,SAcV"}
|