rivetkit 2.0.41 → 2.0.43-rc.1

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 (115) hide show
  1. package/dist/tsup/actor/errors.cjs +2 -2
  2. package/dist/tsup/actor/errors.cjs.map +1 -1
  3. package/dist/tsup/actor/errors.js +1 -1
  4. package/dist/tsup/{chunk-LMG4QMDO.js → chunk-2NJQ3DJ5.js} +15 -5
  5. package/dist/tsup/{chunk-LMG4QMDO.js.map → chunk-2NJQ3DJ5.js.map} +1 -1
  6. package/dist/tsup/{chunk-SNAUKDDK.cjs → chunk-2XQS746M.cjs} +4 -4
  7. package/dist/tsup/chunk-2XQS746M.cjs.map +1 -0
  8. package/dist/tsup/{chunk-DSNSFYDL.cjs → chunk-3HKN5HQ7.cjs} +3 -3
  9. package/dist/tsup/chunk-3HKN5HQ7.cjs.map +1 -0
  10. package/dist/tsup/{chunk-B5UXC4QV.cjs → chunk-BEMEUFS2.cjs} +78 -78
  11. package/dist/tsup/chunk-BEMEUFS2.cjs.map +1 -0
  12. package/dist/tsup/chunk-CKBPIXRM.js +278 -0
  13. package/dist/tsup/chunk-CKBPIXRM.js.map +1 -0
  14. package/dist/tsup/{chunk-GTQKDCM4.cjs → chunk-ETNL2HZL.cjs} +49 -49
  15. package/dist/tsup/chunk-ETNL2HZL.cjs.map +1 -0
  16. package/dist/tsup/{chunk-OXN6EZUB.js → chunk-F7ZL4T63.js} +3 -3
  17. package/dist/tsup/chunk-GBENOENJ.cjs.map +1 -1
  18. package/dist/tsup/chunk-KDFWJKMJ.cjs.map +1 -1
  19. package/dist/tsup/{chunk-2YHR67M4.js → chunk-LFVF5SCU.js} +4 -4
  20. package/dist/tsup/chunk-LFVF5SCU.js.map +1 -0
  21. package/dist/tsup/{chunk-4UHJ3ADW.cjs → chunk-MQ3PTGWH.cjs} +115 -99
  22. package/dist/tsup/chunk-MQ3PTGWH.cjs.map +1 -0
  23. package/dist/tsup/{chunk-Y7ZDTLD2.js → chunk-NENM5PQN.js} +2 -2
  24. package/dist/tsup/chunk-R33VIC3W.cjs +278 -0
  25. package/dist/tsup/chunk-R33VIC3W.cjs.map +1 -0
  26. package/dist/tsup/{chunk-QDVKDX7G.cjs → chunk-ROVVTBUE.cjs} +9 -9
  27. package/dist/tsup/chunk-ROVVTBUE.cjs.map +1 -0
  28. package/dist/tsup/{chunk-7KIR3QLO.js → chunk-S22E2HUH.js} +24 -8
  29. package/dist/tsup/chunk-S22E2HUH.js.map +1 -0
  30. package/dist/tsup/{chunk-UGOCTUBG.js → chunk-TFMRMA5S.js} +5 -5
  31. package/dist/tsup/{chunk-WYZLRPQM.cjs → chunk-YR6H6STI.cjs} +269 -269
  32. package/dist/tsup/chunk-YR6H6STI.cjs.map +1 -0
  33. package/dist/tsup/{chunk-S6F7EKC7.cjs → chunk-YZZF7DES.cjs} +20 -10
  34. package/dist/tsup/chunk-YZZF7DES.cjs.map +1 -0
  35. package/dist/tsup/{chunk-4J5EFV3E.js → chunk-Z3BORZE2.js} +5 -5
  36. package/dist/tsup/{chunk-NRP2OHSW.js → chunk-ZKCVZA7Z.js} +5 -5
  37. package/dist/tsup/client/mod.cjs +6 -6
  38. package/dist/tsup/client/mod.cjs.map +1 -1
  39. package/dist/tsup/client/mod.d.cts +2 -2
  40. package/dist/tsup/client/mod.d.ts +2 -2
  41. package/dist/tsup/client/mod.js +5 -5
  42. package/dist/tsup/common/log.cjs +3 -3
  43. package/dist/tsup/common/log.cjs.map +1 -1
  44. package/dist/tsup/common/log.d.cts +2 -2
  45. package/dist/tsup/common/log.d.ts +2 -2
  46. package/dist/tsup/common/log.js +2 -2
  47. package/dist/tsup/common/websocket.cjs +4 -4
  48. package/dist/tsup/common/websocket.cjs.map +1 -1
  49. package/dist/tsup/common/websocket.js +3 -3
  50. package/dist/tsup/{config-D43N-CFi.d.ts → config-CLnylLYY.d.ts} +10 -10
  51. package/dist/tsup/{config-COyis_uH.d.cts → config-CZB2-W8x.d.cts} +10 -10
  52. package/dist/tsup/{driver-KyM2v645.d.ts → driver-D0QX9M11.d.ts} +1 -1
  53. package/dist/tsup/driver-helpers/mod.cjs +4 -4
  54. package/dist/tsup/driver-helpers/mod.cjs.map +1 -1
  55. package/dist/tsup/driver-helpers/mod.d.cts +2 -2
  56. package/dist/tsup/driver-helpers/mod.d.ts +2 -2
  57. package/dist/tsup/driver-helpers/mod.js +3 -3
  58. package/dist/tsup/{driver-Bt7B-qMd.d.cts → driver-q-zqG7fc.d.cts} +1 -1
  59. package/dist/tsup/driver-test-suite/mod.cjs +323 -448
  60. package/dist/tsup/driver-test-suite/mod.cjs.map +1 -1
  61. package/dist/tsup/driver-test-suite/mod.d.cts +2 -2
  62. package/dist/tsup/driver-test-suite/mod.d.ts +2 -2
  63. package/dist/tsup/driver-test-suite/mod.js +916 -1041
  64. package/dist/tsup/driver-test-suite/mod.js.map +1 -1
  65. package/dist/tsup/inspector/mod.cjs.map +1 -1
  66. package/dist/tsup/mod.cjs +8 -8
  67. package/dist/tsup/mod.cjs.map +1 -1
  68. package/dist/tsup/mod.d.cts +4 -4
  69. package/dist/tsup/mod.d.ts +4 -4
  70. package/dist/tsup/mod.js +7 -7
  71. package/dist/tsup/serve-test-suite/mod.cjs +1581 -0
  72. package/dist/tsup/serve-test-suite/mod.cjs.map +1 -0
  73. package/dist/tsup/serve-test-suite/mod.d.cts +9 -0
  74. package/dist/tsup/serve-test-suite/mod.d.ts +9 -0
  75. package/dist/tsup/serve-test-suite/mod.js +1578 -0
  76. package/dist/tsup/serve-test-suite/mod.js.map +1 -0
  77. package/dist/tsup/test/mod.cjs +8 -8
  78. package/dist/tsup/test/mod.cjs.map +1 -1
  79. package/dist/tsup/test/mod.d.cts +1 -1
  80. package/dist/tsup/test/mod.d.ts +1 -1
  81. package/dist/tsup/test/mod.js +7 -7
  82. package/dist/tsup/utils.cjs +3 -3
  83. package/dist/tsup/utils.cjs.map +1 -1
  84. package/dist/tsup/utils.js +2 -2
  85. package/package.json +14 -4
  86. package/src/actor/errors.ts +4 -4
  87. package/src/driver-test-suite/mod.ts +3 -0
  88. package/src/driver-test-suite/tests/actor-driver.ts +4 -0
  89. package/src/driver-test-suite/tests/actor-lifecycle.ts +157 -0
  90. package/src/driver-test-suite/tests/conn-error-serialization.ts +64 -0
  91. package/src/drivers/engine/actor-driver.ts +24 -4
  92. package/src/serve-test-suite/mod.ts +147 -0
  93. package/dist/schemas/actor-persist/v1.js +0 -167
  94. package/dist/schemas/actor-persist/v2.js +0 -200
  95. package/dist/schemas/actor-persist/v3.js +0 -200
  96. package/dist/schemas/client-protocol/v1.js +0 -301
  97. package/dist/schemas/client-protocol/v2.js +0 -299
  98. package/dist/schemas/file-system-driver/v1.js +0 -76
  99. package/dist/schemas/file-system-driver/v2.js +0 -103
  100. package/dist/schemas/file-system-driver/v3.js +0 -122
  101. package/dist/tsup/chunk-2YHR67M4.js.map +0 -1
  102. package/dist/tsup/chunk-4UHJ3ADW.cjs.map +0 -1
  103. package/dist/tsup/chunk-7KIR3QLO.js.map +0 -1
  104. package/dist/tsup/chunk-B5UXC4QV.cjs.map +0 -1
  105. package/dist/tsup/chunk-DSNSFYDL.cjs.map +0 -1
  106. package/dist/tsup/chunk-GTQKDCM4.cjs.map +0 -1
  107. package/dist/tsup/chunk-QDVKDX7G.cjs.map +0 -1
  108. package/dist/tsup/chunk-S6F7EKC7.cjs.map +0 -1
  109. package/dist/tsup/chunk-SNAUKDDK.cjs.map +0 -1
  110. package/dist/tsup/chunk-WYZLRPQM.cjs.map +0 -1
  111. /package/dist/tsup/{chunk-OXN6EZUB.js.map → chunk-F7ZL4T63.js.map} +0 -0
  112. /package/dist/tsup/{chunk-Y7ZDTLD2.js.map → chunk-NENM5PQN.js.map} +0 -0
  113. /package/dist/tsup/{chunk-UGOCTUBG.js.map → chunk-TFMRMA5S.js.map} +0 -0
  114. /package/dist/tsup/{chunk-4J5EFV3E.js.map → chunk-Z3BORZE2.js.map} +0 -0
  115. /package/dist/tsup/{chunk-NRP2OHSW.js.map → chunk-ZKCVZA7Z.js.map} +0 -0
@@ -0,0 +1,1578 @@
1
+ import {
2
+ hibernationActor,
3
+ logger,
4
+ sleep,
5
+ sleepWithLongRpc,
6
+ sleepWithNoSleepOption,
7
+ sleepWithRawHttp,
8
+ sleepWithRawWebSocket
9
+ } from "../chunk-CKBPIXRM.js";
10
+ import {
11
+ actor,
12
+ setup
13
+ } from "../chunk-S22E2HUH.js";
14
+ import {
15
+ createFileSystemOrMemoryDriver
16
+ } from "../chunk-ZKCVZA7Z.js";
17
+ import "../chunk-TFMRMA5S.js";
18
+ import "../chunk-NENM5PQN.js";
19
+ import {
20
+ buildManagerRouter
21
+ } from "../chunk-F7ZL4T63.js";
22
+ import "../chunk-E6ZE2YEA.js";
23
+ import "../chunk-2NJQ3DJ5.js";
24
+ import {
25
+ ActorError,
26
+ UserError
27
+ } from "../chunk-LFVF5SCU.js";
28
+
29
+ // src/serve-test-suite/mod.ts
30
+ import { serve as honoServe } from "@hono/node-server";
31
+ import { createNodeWebSocket } from "@hono/node-ws";
32
+ import { createServer } from "net";
33
+ import { fileURLToPath } from "url";
34
+ import invariant from "invariant";
35
+
36
+ // fixtures/driver-test-suite/action-inputs.ts
37
+ var inputActor = actor({
38
+ createState: (c, input) => {
39
+ return {
40
+ initialInput: input,
41
+ onCreateInput: void 0
42
+ };
43
+ },
44
+ onCreate: (c, input) => {
45
+ c.state.onCreateInput = input;
46
+ },
47
+ actions: {
48
+ getInputs: (c) => {
49
+ return {
50
+ initialInput: c.state.initialInput,
51
+ onCreateInput: c.state.onCreateInput
52
+ };
53
+ }
54
+ }
55
+ });
56
+
57
+ // fixtures/driver-test-suite/action-timeout.ts
58
+ var shortTimeoutActor = actor({
59
+ state: { value: 0 },
60
+ options: {
61
+ actionTimeout: 50
62
+ // 50ms timeout
63
+ },
64
+ actions: {
65
+ quickAction: async (c) => {
66
+ return "quick response";
67
+ },
68
+ slowAction: async (c) => {
69
+ await new Promise((resolve) => setTimeout(resolve, 100));
70
+ return "slow response";
71
+ }
72
+ }
73
+ });
74
+ var longTimeoutActor = actor({
75
+ state: { value: 0 },
76
+ options: {
77
+ actionTimeout: 200
78
+ // 200ms timeout
79
+ },
80
+ actions: {
81
+ delayedAction: async (c) => {
82
+ await new Promise((resolve) => setTimeout(resolve, 100));
83
+ return "delayed response";
84
+ }
85
+ }
86
+ });
87
+ var defaultTimeoutActor = actor({
88
+ state: { value: 0 },
89
+ actions: {
90
+ normalAction: async (c) => {
91
+ await new Promise((resolve) => setTimeout(resolve, 50));
92
+ return "normal response";
93
+ }
94
+ }
95
+ });
96
+ var syncTimeoutActor = actor({
97
+ state: { value: 0 },
98
+ options: {
99
+ actionTimeout: 50
100
+ // 50ms timeout
101
+ },
102
+ actions: {
103
+ syncAction: (c) => {
104
+ return "sync response";
105
+ }
106
+ }
107
+ });
108
+
109
+ // fixtures/driver-test-suite/action-types.ts
110
+ var syncActionActor = actor({
111
+ state: { value: 0 },
112
+ actions: {
113
+ // Simple synchronous action that returns a value directly
114
+ increment: (c, amount = 1) => {
115
+ c.state.value += amount;
116
+ return c.state.value;
117
+ },
118
+ // Synchronous action that returns an object
119
+ getInfo: (c) => {
120
+ return {
121
+ currentValue: c.state.value,
122
+ timestamp: Date.now()
123
+ };
124
+ },
125
+ // Synchronous action with no return value (void)
126
+ reset: (c) => {
127
+ c.state.value = 0;
128
+ }
129
+ }
130
+ });
131
+ var asyncActionActor = actor({
132
+ state: { value: 0, data: null },
133
+ actions: {
134
+ // Async action with a delay
135
+ delayedIncrement: async (c, amount = 1) => {
136
+ await Promise.resolve();
137
+ c.state.value += amount;
138
+ return c.state.value;
139
+ },
140
+ // Async action that simulates an API call
141
+ fetchData: async (c, id) => {
142
+ await Promise.resolve();
143
+ const data = { id, timestamp: Date.now() };
144
+ c.state.data = data;
145
+ return data;
146
+ },
147
+ // Async action with error handling
148
+ asyncWithError: async (c, shouldError) => {
149
+ await Promise.resolve();
150
+ if (shouldError) {
151
+ throw new UserError("Intentional error");
152
+ }
153
+ return "Success";
154
+ }
155
+ }
156
+ });
157
+ var promiseActor = actor({
158
+ state: { results: [] },
159
+ actions: {
160
+ // Action that returns a resolved promise
161
+ resolvedPromise: (c) => {
162
+ return Promise.resolve("resolved value");
163
+ },
164
+ // Action that returns a promise that resolves after a delay
165
+ delayedPromise: (c) => {
166
+ return new Promise((resolve) => {
167
+ c.state.results.push("delayed");
168
+ resolve("delayed value");
169
+ });
170
+ },
171
+ // Action that returns a rejected promise
172
+ rejectedPromise: (c) => {
173
+ return Promise.reject(new UserError("promised rejection"));
174
+ },
175
+ // Action to check the collected results
176
+ getResults: (c) => {
177
+ return c.state.results;
178
+ }
179
+ }
180
+ });
181
+
182
+ // fixtures/driver-test-suite/actor-onstatechange.ts
183
+ var onStateChangeActor = actor({
184
+ state: {
185
+ value: 0,
186
+ changeCount: 0
187
+ },
188
+ actions: {
189
+ // Action that modifies state - should trigger onStateChange
190
+ setValue: (c, newValue) => {
191
+ c.state.value = newValue;
192
+ return c.state.value;
193
+ },
194
+ // Action that modifies state multiple times - should trigger onStateChange for each change
195
+ incrementMultiple: (c, times) => {
196
+ for (let i = 0; i < times; i++) {
197
+ c.state.value++;
198
+ }
199
+ return c.state.value;
200
+ },
201
+ // Action that doesn't modify state - should NOT trigger onStateChange
202
+ getValue: (c) => {
203
+ return c.state.value;
204
+ },
205
+ // Action that reads and returns without modifying - should NOT trigger onStateChange
206
+ getDoubled: (c) => {
207
+ const doubled = c.state.value * 2;
208
+ return doubled;
209
+ },
210
+ // Get the count of how many times onStateChange was called
211
+ getChangeCount: (c) => {
212
+ return c.state.changeCount;
213
+ },
214
+ // Reset change counter for testing
215
+ resetChangeCount: (c) => {
216
+ c.state.changeCount = 0;
217
+ }
218
+ },
219
+ // Track onStateChange calls
220
+ onStateChange: (c) => {
221
+ c.state.changeCount++;
222
+ }
223
+ });
224
+
225
+ // fixtures/driver-test-suite/conn-params.ts
226
+ var counterWithParams = actor({
227
+ state: { count: 0, initializers: [] },
228
+ createConnState: (c, params) => {
229
+ return {
230
+ name: params.name || "anonymous"
231
+ };
232
+ },
233
+ onConnect: (c, conn) => {
234
+ c.state.initializers.push(conn.state.name);
235
+ },
236
+ actions: {
237
+ increment: (c, x) => {
238
+ c.state.count += x;
239
+ c.broadcast("newCount", {
240
+ count: c.state.count,
241
+ by: c.conn.state.name
242
+ });
243
+ return c.state.count;
244
+ },
245
+ getInitializers: (c) => {
246
+ return c.state.initializers;
247
+ }
248
+ }
249
+ });
250
+
251
+ // fixtures/driver-test-suite/conn-state.ts
252
+ var connStateActor = actor({
253
+ state: {
254
+ sharedCounter: 0,
255
+ disconnectionCount: 0
256
+ },
257
+ // Define connection state
258
+ createConnState: (c, params) => {
259
+ return {
260
+ username: (params == null ? void 0 : params.username) || "anonymous",
261
+ role: (params == null ? void 0 : params.role) || "user",
262
+ counter: 0,
263
+ createdAt: Date.now(),
264
+ noCount: (params == null ? void 0 : params.noCount) ?? false
265
+ };
266
+ },
267
+ // Lifecycle hook when a connection is established
268
+ onConnect: (c, conn) => {
269
+ c.broadcast("userConnected", {
270
+ id: conn.id,
271
+ username: "anonymous",
272
+ role: "user"
273
+ });
274
+ },
275
+ // Lifecycle hook when a connection is closed
276
+ onDisconnect: (c, conn) => {
277
+ var _a;
278
+ if (!((_a = conn.state) == null ? void 0 : _a.noCount)) {
279
+ c.state.disconnectionCount += 1;
280
+ c.broadcast("userDisconnected", {
281
+ id: conn.id
282
+ });
283
+ }
284
+ },
285
+ actions: {
286
+ // Action to increment the connection's counter
287
+ incrementConnCounter: (c, amount = 1) => {
288
+ c.conn.state.counter += amount;
289
+ },
290
+ // Action to increment the shared counter
291
+ incrementSharedCounter: (c, amount = 1) => {
292
+ c.state.sharedCounter += amount;
293
+ return c.state.sharedCounter;
294
+ },
295
+ // Get the connection state
296
+ getConnectionState: (c) => {
297
+ return { id: c.conn.id, ...c.conn.state };
298
+ },
299
+ // Check all active connections
300
+ getConnectionIds: (c) => {
301
+ return c.conns.entries().filter((c2) => {
302
+ var _a;
303
+ return !((_a = c2[1].state) == null ? void 0 : _a.noCount);
304
+ }).map((x) => x[0]).toArray();
305
+ },
306
+ // Get disconnection count
307
+ getDisconnectionCount: (c) => {
308
+ return c.state.disconnectionCount;
309
+ },
310
+ // Get all active connection states
311
+ getAllConnectionStates: (c) => {
312
+ return c.conns.entries().map(([id, conn]) => ({ id, ...conn.state })).toArray();
313
+ },
314
+ // Send message to a specific connection with matching ID
315
+ sendToConnection: (c, targetId, message) => {
316
+ if (c.conns.has(targetId)) {
317
+ c.conns.get(targetId).send("directMessage", { from: c.conn.id, message });
318
+ return true;
319
+ } else {
320
+ return false;
321
+ }
322
+ },
323
+ // Update connection state (simulated for tests)
324
+ updateConnection: (c, updates) => {
325
+ if (updates.username) c.conn.state.username = updates.username;
326
+ if (updates.role) c.conn.state.role = updates.role;
327
+ return c.conn.state;
328
+ },
329
+ disconnectSelf: (c, reason) => {
330
+ c.conn.disconnect(reason ?? "test.disconnect");
331
+ return true;
332
+ }
333
+ }
334
+ });
335
+
336
+ // fixtures/driver-test-suite/counter.ts
337
+ var counter = actor({
338
+ state: { count: 0 },
339
+ actions: {
340
+ increment: (c, x) => {
341
+ c.state.count += x;
342
+ c.broadcast("newCount", c.state.count);
343
+ return c.state.count;
344
+ },
345
+ setCount: (c, x) => {
346
+ c.state.count = x;
347
+ c.broadcast("newCount", x);
348
+ return c.state.count;
349
+ },
350
+ getCount: (c) => {
351
+ return c.state.count;
352
+ }
353
+ }
354
+ });
355
+
356
+ // fixtures/driver-test-suite/counter-conn.ts
357
+ var counterConn = actor({
358
+ state: {
359
+ connectionCount: 0
360
+ },
361
+ connState: { count: 0 },
362
+ onConnect: (c, conn) => {
363
+ c.state.connectionCount += 1;
364
+ },
365
+ onDisconnect: (c, conn) => {
366
+ c.state.connectionCount -= 1;
367
+ },
368
+ actions: {
369
+ increment: (c, x) => {
370
+ c.conn.state.count += x;
371
+ c.broadcast("newCount", c.conn.state.count);
372
+ },
373
+ setCount: (c, x) => {
374
+ c.conn.state.count = x;
375
+ c.broadcast("newCount", x);
376
+ },
377
+ getCount: (c) => {
378
+ return c.conn.state.count;
379
+ },
380
+ getConnectionCount: (c) => {
381
+ return c.state.connectionCount;
382
+ }
383
+ }
384
+ });
385
+
386
+ // fixtures/driver-test-suite/destroy.ts
387
+ var destroyObserver = actor({
388
+ state: { destroyedActors: [] },
389
+ actions: {
390
+ notifyDestroyed: (c, actorKey) => {
391
+ c.state.destroyedActors.push(actorKey);
392
+ },
393
+ wasDestroyed: (c, actorKey) => {
394
+ return c.state.destroyedActors.includes(actorKey);
395
+ },
396
+ reset: (c) => {
397
+ c.state.destroyedActors = [];
398
+ }
399
+ }
400
+ });
401
+ var destroyActor = actor({
402
+ state: { value: 0, key: "" },
403
+ onWake: (c) => {
404
+ c.state.key = c.key.join("/");
405
+ },
406
+ onDestroy: async (c) => {
407
+ const client = c.client();
408
+ const observer = client.destroyObserver.getOrCreate(["observer"]);
409
+ await observer.notifyDestroyed(c.state.key);
410
+ },
411
+ actions: {
412
+ setValue: async (c, newValue) => {
413
+ c.state.value = newValue;
414
+ await c.saveState({ immediate: true });
415
+ return c.state.value;
416
+ },
417
+ getValue: (c) => {
418
+ return c.state.value;
419
+ },
420
+ destroy: (c) => {
421
+ c.destroy();
422
+ }
423
+ }
424
+ });
425
+
426
+ // fixtures/driver-test-suite/error-handling.ts
427
+ var errorHandlingActor = actor({
428
+ state: {
429
+ errorLog: []
430
+ },
431
+ actions: {
432
+ // Action that throws a UserError with just a message
433
+ throwSimpleError: () => {
434
+ throw new UserError("Simple error message");
435
+ },
436
+ // Action that throws a UserError with code and metadata
437
+ throwDetailedError: () => {
438
+ throw new UserError("Detailed error message", {
439
+ code: "detailed_error",
440
+ metadata: {
441
+ reason: "test",
442
+ timestamp: Date.now()
443
+ }
444
+ });
445
+ },
446
+ // Action that throws an internal error
447
+ throwInternalError: () => {
448
+ throw new Error("This is an internal error");
449
+ },
450
+ // Action that returns successfully
451
+ successfulAction: () => {
452
+ return "success";
453
+ },
454
+ // Action that times out (simulated with a long delay)
455
+ timeoutAction: async (c) => {
456
+ return new Promise((resolve) => {
457
+ setTimeout(() => {
458
+ resolve("This should not be reached if timeout works");
459
+ }, 1e4);
460
+ });
461
+ },
462
+ // Action with configurable delay to test timeout edge cases
463
+ delayedAction: async (c, delayMs) => {
464
+ return new Promise((resolve) => {
465
+ setTimeout(() => {
466
+ resolve(`Completed after ${delayMs}ms`);
467
+ }, delayMs);
468
+ });
469
+ },
470
+ // Log an error for inspection
471
+ logError: (c, error) => {
472
+ c.state.errorLog.push(error);
473
+ return c.state.errorLog;
474
+ },
475
+ // Get the error log
476
+ getErrorLog: (c) => {
477
+ return c.state.errorLog;
478
+ },
479
+ // Clear the error log
480
+ clearErrorLog: (c) => {
481
+ c.state.errorLog = [];
482
+ return true;
483
+ }
484
+ },
485
+ options: {
486
+ actionTimeout: 500
487
+ // 500ms timeout for actions
488
+ }
489
+ });
490
+ var customTimeoutActor = actor({
491
+ state: {},
492
+ actions: {
493
+ quickAction: async () => {
494
+ await new Promise((resolve) => setTimeout(resolve, 50));
495
+ return "Quick action completed";
496
+ },
497
+ slowAction: async () => {
498
+ await new Promise((resolve) => setTimeout(resolve, 300));
499
+ return "Slow action completed";
500
+ }
501
+ },
502
+ options: {
503
+ actionTimeout: 200
504
+ // 200ms timeout
505
+ }
506
+ });
507
+
508
+ // fixtures/driver-test-suite/inline-client.ts
509
+ var inlineClientActor = actor({
510
+ state: { messages: [] },
511
+ actions: {
512
+ // Action that uses client to call another actor (stateless)
513
+ callCounterIncrement: async (c, amount) => {
514
+ const client = c.client();
515
+ const result = await client.counter.getOrCreate(["inline-test"]).increment(amount);
516
+ c.state.messages.push(
517
+ `Called counter.increment(${amount}), result: ${result}`
518
+ );
519
+ return result;
520
+ },
521
+ // Action that uses client to get counter state (stateless)
522
+ getCounterState: async (c) => {
523
+ const client = c.client();
524
+ const count = await client.counter.getOrCreate(["inline-test"]).getCount();
525
+ c.state.messages.push(`Got counter state: ${count}`);
526
+ return count;
527
+ },
528
+ // Action that uses client with .connect() for stateful communication
529
+ connectToCounterAndIncrement: async (c, amount) => {
530
+ const client = c.client();
531
+ const handle = client.counter.getOrCreate(["inline-test-stateful"]);
532
+ const connection = handle.connect();
533
+ const events = [];
534
+ connection.on("newCount", (count) => {
535
+ events.push(count);
536
+ });
537
+ const result1 = await connection.increment(amount);
538
+ const result2 = await connection.increment(amount * 2);
539
+ await connection.dispose();
540
+ c.state.messages.push(
541
+ `Connected to counter, incremented by ${amount} and ${amount * 2}, results: ${result1}, ${result2}, events: ${JSON.stringify(events)}`
542
+ );
543
+ return { result1, result2, events };
544
+ },
545
+ // Get all messages from this actor's state
546
+ getMessages: (c) => {
547
+ return c.state.messages;
548
+ },
549
+ // Clear messages
550
+ clearMessages: (c) => {
551
+ c.state.messages = [];
552
+ }
553
+ }
554
+ });
555
+
556
+ // fixtures/driver-test-suite/kv.ts
557
+ var kvActor = actor({
558
+ actions: {
559
+ putText: async (c, key, value) => {
560
+ await c.kv.put(key, value);
561
+ return true;
562
+ },
563
+ getText: async (c, key) => {
564
+ return await c.kv.get(key);
565
+ },
566
+ listText: async (c, prefix) => {
567
+ const results = await c.kv.list(prefix, { keyType: "text" });
568
+ return results.map(([key, value]) => ({
569
+ key,
570
+ value
571
+ }));
572
+ },
573
+ roundtripArrayBuffer: async (c, key, values) => {
574
+ const buffer = new Uint8Array(values).buffer;
575
+ await c.kv.put(key, buffer, { type: "arrayBuffer" });
576
+ const result = await c.kv.get(key, { type: "arrayBuffer" });
577
+ if (!result) {
578
+ return null;
579
+ }
580
+ return Array.from(new Uint8Array(result));
581
+ }
582
+ }
583
+ });
584
+
585
+ // fixtures/driver-test-suite/large-payloads.ts
586
+ var largePayloadActor = actor({
587
+ state: {},
588
+ actions: {
589
+ /**
590
+ * Accepts a large request payload and returns its size
591
+ */
592
+ processLargeRequest: (c, data) => {
593
+ return {
594
+ itemCount: data.items.length,
595
+ firstItem: data.items[0],
596
+ lastItem: data.items[data.items.length - 1]
597
+ };
598
+ },
599
+ /**
600
+ * Returns a large response payload
601
+ */
602
+ getLargeResponse: (c, itemCount) => {
603
+ const items = [];
604
+ for (let i = 0; i < itemCount; i++) {
605
+ items.push(`Item ${i} with some additional text to increase size`);
606
+ }
607
+ return { items };
608
+ },
609
+ /**
610
+ * Echo back the request data
611
+ */
612
+ echo: (c, data) => {
613
+ return data;
614
+ }
615
+ }
616
+ });
617
+ var largePayloadConnActor = actor({
618
+ state: {},
619
+ connState: {
620
+ lastRequestSize: 0
621
+ },
622
+ actions: {
623
+ /**
624
+ * Accepts a large request payload and returns its size
625
+ */
626
+ processLargeRequest: (c, data) => {
627
+ c.conn.state.lastRequestSize = data.items.length;
628
+ return {
629
+ itemCount: data.items.length,
630
+ firstItem: data.items[0],
631
+ lastItem: data.items[data.items.length - 1]
632
+ };
633
+ },
634
+ /**
635
+ * Returns a large response payload
636
+ */
637
+ getLargeResponse: (c, itemCount) => {
638
+ const items = [];
639
+ for (let i = 0; i < itemCount; i++) {
640
+ items.push(`Item ${i} with some additional text to increase size`);
641
+ }
642
+ return { items };
643
+ },
644
+ /**
645
+ * Echo back the request data
646
+ */
647
+ echo: (c, data) => {
648
+ return data;
649
+ },
650
+ /**
651
+ * Get the last request size
652
+ */
653
+ getLastRequestSize: (c) => {
654
+ return c.conn.state.lastRequestSize;
655
+ }
656
+ }
657
+ });
658
+
659
+ // fixtures/driver-test-suite/lifecycle.ts
660
+ var counterWithLifecycle = actor({
661
+ state: {
662
+ count: 0,
663
+ events: []
664
+ },
665
+ createConnState: (c, params) => ({
666
+ joinTime: Date.now()
667
+ }),
668
+ onWake: (c) => {
669
+ c.state.events.push("onWake");
670
+ },
671
+ onBeforeConnect: (c, params) => {
672
+ if (params == null ? void 0 : params.trackLifecycle) c.state.events.push("onBeforeConnect");
673
+ },
674
+ onConnect: (c, conn) => {
675
+ var _a;
676
+ if ((_a = conn.params) == null ? void 0 : _a.trackLifecycle) c.state.events.push("onConnect");
677
+ },
678
+ onDisconnect: (c, conn) => {
679
+ var _a;
680
+ if ((_a = conn.params) == null ? void 0 : _a.trackLifecycle) c.state.events.push("onDisconnect");
681
+ },
682
+ actions: {
683
+ getEvents: (c) => {
684
+ return c.state.events;
685
+ },
686
+ increment: (c, x) => {
687
+ c.state.count += x;
688
+ return c.state.count;
689
+ }
690
+ }
691
+ });
692
+
693
+ // fixtures/driver-test-suite/metadata.ts
694
+ var metadataActor = actor({
695
+ state: {
696
+ lastMetadata: null,
697
+ actorName: "",
698
+ // Store tags and region in state for testing since they may not be
699
+ // available in the context in all environments
700
+ storedTags: {},
701
+ storedRegion: null
702
+ },
703
+ onWake: (c) => {
704
+ c.state.actorName = c.name;
705
+ },
706
+ actions: {
707
+ // Set up test tags - this will be called by tests to simulate tags
708
+ setupTestTags: (c, tags) => {
709
+ c.state.storedTags = tags;
710
+ return tags;
711
+ },
712
+ // Set up test region - this will be called by tests to simulate region
713
+ setupTestRegion: (c, region) => {
714
+ c.state.storedRegion = region;
715
+ return region;
716
+ },
717
+ // Get all available metadata
718
+ getMetadata: (c) => {
719
+ const metadata = {
720
+ name: c.name,
721
+ tags: c.state.storedTags,
722
+ region: c.state.storedRegion
723
+ };
724
+ c.state.lastMetadata = metadata;
725
+ return metadata;
726
+ },
727
+ // Get the actor name
728
+ getActorName: (c) => {
729
+ return c.name;
730
+ },
731
+ // Get a specific tag by key
732
+ getTag: (c, key) => {
733
+ return c.state.storedTags[key] || null;
734
+ },
735
+ // Get all tags
736
+ getTags: (c) => {
737
+ return c.state.storedTags;
738
+ },
739
+ // Get the region
740
+ getRegion: (c) => {
741
+ return c.state.storedRegion;
742
+ },
743
+ // Get the stored actor name (from onWake)
744
+ getStoredActorName: (c) => {
745
+ return c.state.actorName;
746
+ },
747
+ // Get last retrieved metadata
748
+ getLastMetadata: (c) => {
749
+ return c.state.lastMetadata;
750
+ }
751
+ }
752
+ });
753
+
754
+ // fixtures/driver-test-suite/raw-http.ts
755
+ import { Hono } from "hono";
756
+ var rawHttpActor = actor({
757
+ state: {
758
+ requestCount: 0
759
+ },
760
+ onRequest(ctx, request) {
761
+ const url = new URL(request.url);
762
+ const method = request.method;
763
+ ctx.state.requestCount++;
764
+ if (url.pathname === "/api/hello") {
765
+ return new Response(
766
+ JSON.stringify({ message: "Hello from actor!" }),
767
+ {
768
+ headers: { "Content-Type": "application/json" }
769
+ }
770
+ );
771
+ }
772
+ if (url.pathname === "/api/echo" && method === "POST") {
773
+ return new Response(request.body, {
774
+ headers: request.headers
775
+ });
776
+ }
777
+ if (url.pathname === "/api/state") {
778
+ return new Response(
779
+ JSON.stringify({
780
+ requestCount: ctx.state.requestCount
781
+ }),
782
+ {
783
+ headers: { "Content-Type": "application/json" }
784
+ }
785
+ );
786
+ }
787
+ if (url.pathname === "/api/headers") {
788
+ const headers = {};
789
+ request.headers.forEach((value, key) => {
790
+ headers[key] = value;
791
+ });
792
+ return new Response(JSON.stringify(headers), {
793
+ headers: { "Content-Type": "application/json" }
794
+ });
795
+ }
796
+ return new Response("Not Found", { status: 404 });
797
+ },
798
+ actions: {}
799
+ });
800
+ var rawHttpNoHandlerActor = actor({
801
+ actions: {}
802
+ });
803
+ var rawHttpVoidReturnActor = actor({
804
+ onRequest(ctx, request) {
805
+ return void 0;
806
+ },
807
+ actions: {}
808
+ });
809
+ var rawHttpHonoActor = actor({
810
+ createVars() {
811
+ const router = new Hono();
812
+ router.get(
813
+ "/",
814
+ (c) => c.json({ message: "Welcome to Hono actor!" })
815
+ );
816
+ router.get(
817
+ "/users",
818
+ (c) => c.json([
819
+ { id: 1, name: "Alice" },
820
+ { id: 2, name: "Bob" }
821
+ ])
822
+ );
823
+ router.get("/users/:id", (c) => {
824
+ const id = c.req.param("id");
825
+ return c.json({
826
+ id: parseInt(id),
827
+ name: id === "1" ? "Alice" : "Bob"
828
+ });
829
+ });
830
+ router.post("/users", async (c) => {
831
+ const body = await c.req.json();
832
+ return c.json({ id: 3, ...body }, 201);
833
+ });
834
+ router.put("/users/:id", async (c) => {
835
+ const id = c.req.param("id");
836
+ const body = await c.req.json();
837
+ return c.json({ id: parseInt(id), ...body });
838
+ });
839
+ router.delete("/users/:id", (c) => {
840
+ const id = c.req.param("id");
841
+ return c.json({ message: `User ${id} deleted` });
842
+ });
843
+ return { router };
844
+ },
845
+ onRequest(ctx, request) {
846
+ return ctx.vars.router.fetch(request);
847
+ },
848
+ actions: {}
849
+ });
850
+
851
+ // fixtures/driver-test-suite/raw-http-request-properties.ts
852
+ var rawHttpRequestPropertiesActor = actor({
853
+ actions: {},
854
+ onRequest(ctx, request) {
855
+ const url = new URL(request.url);
856
+ const method = request.method;
857
+ const headers = {};
858
+ request.headers.forEach((value, key) => {
859
+ headers[key] = value;
860
+ });
861
+ const handleBody = async () => {
862
+ if (!request.body) {
863
+ return null;
864
+ }
865
+ const contentType = request.headers.get("content-type") || "";
866
+ try {
867
+ if (contentType.includes("application/json")) {
868
+ const text = await request.text();
869
+ return text ? JSON.parse(text) : null;
870
+ } else {
871
+ const text = await request.text();
872
+ return text || null;
873
+ }
874
+ } catch (error) {
875
+ return null;
876
+ }
877
+ };
878
+ if (method === "HEAD") {
879
+ return new Response(null, {
880
+ status: 200
881
+ });
882
+ }
883
+ if (method === "OPTIONS") {
884
+ return new Response(null, {
885
+ status: 204
886
+ });
887
+ }
888
+ return handleBody().then((body) => {
889
+ const responseData = {
890
+ // URL properties
891
+ url: request.url,
892
+ pathname: url.pathname,
893
+ search: url.search,
894
+ searchParams: Object.fromEntries(url.searchParams.entries()),
895
+ hash: url.hash,
896
+ // Method
897
+ method: request.method,
898
+ // Headers
899
+ headers,
900
+ // Body
901
+ body,
902
+ bodyText: typeof body === "string" ? body : body === null && request.body !== null ? "" : null,
903
+ // Additional properties that might be available
904
+ // Note: Some properties like cache, credentials, mode, etc.
905
+ // might not be available in all environments
906
+ cache: request.cache || null,
907
+ credentials: request.credentials || null,
908
+ mode: request.mode || null,
909
+ redirect: request.redirect || null,
910
+ referrer: request.referrer || null
911
+ };
912
+ return new Response(JSON.stringify(responseData), {
913
+ headers: { "Content-Type": "application/json" }
914
+ });
915
+ });
916
+ }
917
+ });
918
+
919
+ // fixtures/driver-test-suite/raw-websocket.ts
920
+ var rawWebSocketActor = actor({
921
+ state: {
922
+ connectionCount: 0,
923
+ messageCount: 0
924
+ },
925
+ onWebSocket(ctx, websocket) {
926
+ ctx.state.connectionCount = ctx.state.connectionCount + 1;
927
+ console.log(
928
+ `[ACTOR] New connection, count: ${ctx.state.connectionCount}`
929
+ );
930
+ websocket.send(
931
+ JSON.stringify({
932
+ type: "welcome",
933
+ connectionCount: ctx.state.connectionCount
934
+ })
935
+ );
936
+ console.log("[ACTOR] Sent welcome message");
937
+ websocket.addEventListener("message", (event) => {
938
+ var _a;
939
+ ctx.state.messageCount = ctx.state.messageCount + 1;
940
+ console.log(
941
+ `[ACTOR] Message received, total count: ${ctx.state.messageCount}, data:`,
942
+ event.data
943
+ );
944
+ const data = event.data;
945
+ if (typeof data === "string") {
946
+ try {
947
+ const parsed = JSON.parse(data);
948
+ if (parsed.type === "ping") {
949
+ websocket.send(
950
+ JSON.stringify({
951
+ type: "pong",
952
+ timestamp: Date.now()
953
+ })
954
+ );
955
+ } else if (parsed.type === "getStats") {
956
+ console.log(
957
+ `[ACTOR] Sending stats - connections: ${ctx.state.connectionCount}, messages: ${ctx.state.messageCount}`
958
+ );
959
+ websocket.send(
960
+ JSON.stringify({
961
+ type: "stats",
962
+ connectionCount: ctx.state.connectionCount,
963
+ messageCount: ctx.state.messageCount
964
+ })
965
+ );
966
+ } else if (parsed.type === "getRequestInfo") {
967
+ const url = ((_a = ctx.request) == null ? void 0 : _a.url) || "ws://actor/websocket";
968
+ const urlObj = new URL(url);
969
+ websocket.send(
970
+ JSON.stringify({
971
+ type: "requestInfo",
972
+ url,
973
+ pathname: urlObj.pathname,
974
+ search: urlObj.search
975
+ })
976
+ );
977
+ } else {
978
+ websocket.send(data);
979
+ }
980
+ } catch {
981
+ websocket.send(data);
982
+ }
983
+ } else {
984
+ websocket.send(data);
985
+ }
986
+ });
987
+ websocket.addEventListener("close", () => {
988
+ ctx.state.connectionCount = ctx.state.connectionCount - 1;
989
+ console.log(
990
+ `[ACTOR] Connection closed, count: ${ctx.state.connectionCount}`
991
+ );
992
+ });
993
+ },
994
+ actions: {
995
+ getStats(ctx) {
996
+ return {
997
+ connectionCount: ctx.state.connectionCount,
998
+ messageCount: ctx.state.messageCount
999
+ };
1000
+ }
1001
+ }
1002
+ });
1003
+ var rawWebSocketBinaryActor = actor({
1004
+ onWebSocket(ctx, websocket) {
1005
+ websocket.addEventListener("message", (event) => {
1006
+ const data = event.data;
1007
+ if (data instanceof ArrayBuffer || data instanceof Uint8Array) {
1008
+ const bytes = new Uint8Array(data);
1009
+ const reversed = new Uint8Array(bytes.length);
1010
+ for (let i = 0; i < bytes.length; i++) {
1011
+ reversed[i] = bytes[bytes.length - 1 - i];
1012
+ }
1013
+ websocket.send(reversed);
1014
+ }
1015
+ });
1016
+ },
1017
+ actions: {}
1018
+ });
1019
+
1020
+ // fixtures/driver-test-suite/request-access.ts
1021
+ var requestAccessActor = actor({
1022
+ state: {
1023
+ // Track request info from different hooks
1024
+ onBeforeConnectRequest: {
1025
+ hasRequest: false,
1026
+ requestUrl: null,
1027
+ requestMethod: null,
1028
+ requestHeaders: {}
1029
+ },
1030
+ createConnStateRequest: {
1031
+ hasRequest: false,
1032
+ requestUrl: null,
1033
+ requestMethod: null,
1034
+ requestHeaders: {}
1035
+ },
1036
+ onRequestRequest: {
1037
+ hasRequest: false,
1038
+ requestUrl: null,
1039
+ requestMethod: null,
1040
+ requestHeaders: {}
1041
+ },
1042
+ onWebSocketRequest: {
1043
+ hasRequest: false,
1044
+ requestUrl: null,
1045
+ requestMethod: null,
1046
+ requestHeaders: {}
1047
+ }
1048
+ },
1049
+ createConnState: (c, params) => {
1050
+ let requestInfo = null;
1051
+ if ((params == null ? void 0 : params.trackRequest) && c.request) {
1052
+ const headers = {};
1053
+ c.request.headers.forEach((value, key) => {
1054
+ headers[key] = value;
1055
+ });
1056
+ requestInfo = {
1057
+ hasRequest: true,
1058
+ requestUrl: c.request.url,
1059
+ requestMethod: c.request.method,
1060
+ requestHeaders: headers
1061
+ };
1062
+ }
1063
+ return {
1064
+ trackRequest: (params == null ? void 0 : params.trackRequest) || false,
1065
+ requestInfo
1066
+ };
1067
+ },
1068
+ onConnect: (c, conn) => {
1069
+ if (conn.state.requestInfo) {
1070
+ c.state.createConnStateRequest = conn.state.requestInfo;
1071
+ }
1072
+ },
1073
+ onBeforeConnect: (c, params) => {
1074
+ if (params == null ? void 0 : params.trackRequest) {
1075
+ if (c.request) {
1076
+ c.state.onBeforeConnectRequest.hasRequest = true;
1077
+ c.state.onBeforeConnectRequest.requestUrl = c.request.url;
1078
+ c.state.onBeforeConnectRequest.requestMethod = c.request.method;
1079
+ const headers = {};
1080
+ c.request.headers.forEach((value, key) => {
1081
+ headers[key] = value;
1082
+ });
1083
+ c.state.onBeforeConnectRequest.requestHeaders = headers;
1084
+ } else {
1085
+ c.state.onBeforeConnectRequest.hasRequest = false;
1086
+ }
1087
+ }
1088
+ },
1089
+ onRequest: (c, request) => {
1090
+ c.state.onRequestRequest.hasRequest = true;
1091
+ c.state.onRequestRequest.requestUrl = request.url;
1092
+ c.state.onRequestRequest.requestMethod = request.method;
1093
+ const headers = {};
1094
+ request.headers.forEach((value, key) => {
1095
+ headers[key] = value;
1096
+ });
1097
+ c.state.onRequestRequest.requestHeaders = headers;
1098
+ return new Response(
1099
+ JSON.stringify({
1100
+ hasRequest: true,
1101
+ requestUrl: request.url,
1102
+ requestMethod: request.method,
1103
+ requestHeaders: headers
1104
+ }),
1105
+ {
1106
+ status: 200,
1107
+ headers: { "Content-Type": "application/json" }
1108
+ }
1109
+ );
1110
+ },
1111
+ onWebSocket: (c, websocket) => {
1112
+ if (!c.request) throw "Missing request";
1113
+ c.state.onWebSocketRequest.hasRequest = true;
1114
+ c.state.onWebSocketRequest.requestUrl = c.request.url;
1115
+ c.state.onWebSocketRequest.requestMethod = c.request.method;
1116
+ const headers = {};
1117
+ c.request.headers.forEach((value, key) => {
1118
+ headers[key] = value;
1119
+ });
1120
+ c.state.onWebSocketRequest.requestHeaders = headers;
1121
+ websocket.send(
1122
+ JSON.stringify({
1123
+ hasRequest: true,
1124
+ requestUrl: c.request.url,
1125
+ requestMethod: c.request.method,
1126
+ requestHeaders: headers
1127
+ })
1128
+ );
1129
+ websocket.addEventListener("message", (event) => {
1130
+ websocket.send(event.data);
1131
+ });
1132
+ },
1133
+ actions: {
1134
+ getRequestInfo: (c) => {
1135
+ return {
1136
+ onBeforeConnect: c.state.onBeforeConnectRequest,
1137
+ createConnState: c.state.createConnStateRequest,
1138
+ onRequest: c.state.onRequestRequest,
1139
+ onWebSocket: c.state.onWebSocketRequest
1140
+ };
1141
+ }
1142
+ }
1143
+ });
1144
+
1145
+ // fixtures/driver-test-suite/reject-connection.ts
1146
+ var rejectConnectionActor = actor({
1147
+ onBeforeConnect: async (_c, params) => {
1148
+ if (params == null ? void 0 : params.reject) {
1149
+ await new Promise((resolve) => setTimeout(resolve, 500));
1150
+ throw new UserError("Rejected connection", {
1151
+ code: "rejected"
1152
+ });
1153
+ }
1154
+ },
1155
+ actions: {
1156
+ ping: () => "pong"
1157
+ }
1158
+ });
1159
+
1160
+ // fixtures/driver-test-suite/scheduled.ts
1161
+ var scheduled = actor({
1162
+ state: {
1163
+ lastRun: 0,
1164
+ scheduledCount: 0,
1165
+ taskHistory: []
1166
+ },
1167
+ actions: {
1168
+ // Schedule using 'at' with specific timestamp
1169
+ scheduleTaskAt: (c, timestamp) => {
1170
+ c.schedule.at(timestamp, "onScheduledTask");
1171
+ return timestamp;
1172
+ },
1173
+ // Schedule using 'after' with delay
1174
+ scheduleTaskAfter: (c, delayMs) => {
1175
+ c.schedule.after(delayMs, "onScheduledTask");
1176
+ return Date.now() + delayMs;
1177
+ },
1178
+ // Schedule with a task ID for ordering tests
1179
+ scheduleTaskAfterWithId: (c, taskId, delayMs) => {
1180
+ c.schedule.after(delayMs, "onScheduledTaskWithId", taskId);
1181
+ return { taskId, scheduledFor: Date.now() + delayMs };
1182
+ },
1183
+ // Original method for backward compatibility
1184
+ scheduleTask: (c, delayMs) => {
1185
+ const timestamp = Date.now() + delayMs;
1186
+ c.schedule.at(timestamp, "onScheduledTask");
1187
+ return timestamp;
1188
+ },
1189
+ // Getters for state
1190
+ getLastRun: (c) => {
1191
+ return c.state.lastRun;
1192
+ },
1193
+ getScheduledCount: (c) => {
1194
+ return c.state.scheduledCount;
1195
+ },
1196
+ getTaskHistory: (c) => {
1197
+ return c.state.taskHistory;
1198
+ },
1199
+ clearHistory: (c) => {
1200
+ c.state.taskHistory = [];
1201
+ c.state.scheduledCount = 0;
1202
+ c.state.lastRun = 0;
1203
+ return true;
1204
+ },
1205
+ // Scheduled task handlers
1206
+ onScheduledTask: (c) => {
1207
+ c.state.lastRun = Date.now();
1208
+ c.state.scheduledCount++;
1209
+ c.broadcast("scheduled", {
1210
+ time: c.state.lastRun,
1211
+ count: c.state.scheduledCount
1212
+ });
1213
+ },
1214
+ onScheduledTaskWithId: (c, taskId) => {
1215
+ c.state.lastRun = Date.now();
1216
+ c.state.scheduledCount++;
1217
+ c.state.taskHistory.push(taskId);
1218
+ c.broadcast("scheduledWithId", {
1219
+ taskId,
1220
+ time: c.state.lastRun,
1221
+ count: c.state.scheduledCount
1222
+ });
1223
+ }
1224
+ }
1225
+ });
1226
+
1227
+ // fixtures/driver-test-suite/vars.ts
1228
+ var staticVarActor = actor({
1229
+ state: { value: 0 },
1230
+ connState: { hello: "world" },
1231
+ vars: { counter: 42, name: "test-actor" },
1232
+ actions: {
1233
+ getVars: (c) => {
1234
+ return c.vars;
1235
+ },
1236
+ getName: (c) => {
1237
+ return c.vars.name;
1238
+ }
1239
+ }
1240
+ });
1241
+ var nestedVarActor = actor({
1242
+ state: { value: 0 },
1243
+ connState: { hello: "world" },
1244
+ vars: {
1245
+ counter: 42,
1246
+ nested: {
1247
+ value: "original",
1248
+ array: [1, 2, 3],
1249
+ obj: { key: "value" }
1250
+ }
1251
+ },
1252
+ actions: {
1253
+ getVars: (c) => {
1254
+ return c.vars;
1255
+ },
1256
+ modifyNested: (c) => {
1257
+ c.vars.nested.value = "modified";
1258
+ c.vars.nested.array.push(4);
1259
+ c.vars.nested.obj.key = "new-value";
1260
+ return c.vars;
1261
+ }
1262
+ }
1263
+ });
1264
+ var dynamicVarActor = actor({
1265
+ state: { value: 0 },
1266
+ connState: { hello: "world" },
1267
+ createVars: () => {
1268
+ return {
1269
+ random: Math.random(),
1270
+ computed: `Actor-${Math.floor(Math.random() * 1e3)}`
1271
+ };
1272
+ },
1273
+ actions: {
1274
+ getVars: (c) => {
1275
+ return c.vars;
1276
+ }
1277
+ }
1278
+ });
1279
+ var uniqueVarActor = actor({
1280
+ state: { value: 0 },
1281
+ connState: { hello: "world" },
1282
+ createVars: () => {
1283
+ return {
1284
+ id: Math.floor(Math.random() * 1e6)
1285
+ };
1286
+ },
1287
+ actions: {
1288
+ getVars: (c) => {
1289
+ return c.vars;
1290
+ }
1291
+ }
1292
+ });
1293
+ var driverCtxActor = actor({
1294
+ state: { value: 0 },
1295
+ connState: { hello: "world" },
1296
+ createVars: (c, driverCtx) => {
1297
+ return {
1298
+ hasDriverCtx: Boolean(driverCtx == null ? void 0 : driverCtx.isTest)
1299
+ };
1300
+ },
1301
+ actions: {
1302
+ getVars: (c) => {
1303
+ return c.vars;
1304
+ }
1305
+ }
1306
+ });
1307
+
1308
+ // fixtures/driver-test-suite/start-stop-race.ts
1309
+ var startStopRaceActor = actor({
1310
+ state: {
1311
+ initialized: false,
1312
+ startTime: 0,
1313
+ destroyCalled: false,
1314
+ startCompleted: false
1315
+ },
1316
+ onWake: async (c) => {
1317
+ c.state.startTime = Date.now();
1318
+ await new Promise((resolve) => setTimeout(resolve, 100));
1319
+ c.state.initialized = true;
1320
+ c.state.startCompleted = true;
1321
+ },
1322
+ onDestroy: (c) => {
1323
+ c.state.destroyCalled = true;
1324
+ },
1325
+ actions: {
1326
+ getState: (c) => {
1327
+ return {
1328
+ initialized: c.state.initialized,
1329
+ startTime: c.state.startTime,
1330
+ destroyCalled: c.state.destroyCalled,
1331
+ startCompleted: c.state.startCompleted
1332
+ };
1333
+ },
1334
+ ping: (c) => {
1335
+ return "pong";
1336
+ },
1337
+ destroy: (c) => {
1338
+ c.destroy();
1339
+ }
1340
+ }
1341
+ });
1342
+ var lifecycleObserver = actor({
1343
+ state: {
1344
+ events: []
1345
+ },
1346
+ actions: {
1347
+ recordEvent: (c, params) => {
1348
+ c.state.events.push({
1349
+ actorKey: params.actorKey,
1350
+ event: params.event,
1351
+ timestamp: Date.now()
1352
+ });
1353
+ },
1354
+ getEvents: (c) => {
1355
+ return c.state.events;
1356
+ },
1357
+ clearEvents: (c) => {
1358
+ c.state.events = [];
1359
+ }
1360
+ }
1361
+ });
1362
+
1363
+ // fixtures/driver-test-suite/conn-error-serialization.ts
1364
+ var CustomConnectionError = class extends ActorError {
1365
+ constructor(message) {
1366
+ super("connection", "custom_error", message, { public: true });
1367
+ }
1368
+ };
1369
+ var connErrorSerializationActor = actor({
1370
+ state: {
1371
+ value: 0
1372
+ },
1373
+ createConnState: (_c, params) => {
1374
+ if (params.shouldThrow) {
1375
+ throw new CustomConnectionError("Test error from createConnState");
1376
+ }
1377
+ return { initialized: true };
1378
+ },
1379
+ actions: {
1380
+ getValue: (c) => c.state.value
1381
+ }
1382
+ });
1383
+
1384
+ // fixtures/driver-test-suite/registry.ts
1385
+ var registry = setup({
1386
+ use: {
1387
+ // From counter.ts
1388
+ counter,
1389
+ // From counter-conn.ts
1390
+ counterConn,
1391
+ // From lifecycle.ts
1392
+ counterWithLifecycle,
1393
+ // From scheduled.ts
1394
+ scheduled,
1395
+ // From sleep.ts
1396
+ sleep,
1397
+ sleepWithLongRpc,
1398
+ sleepWithRawHttp,
1399
+ sleepWithRawWebSocket,
1400
+ sleepWithNoSleepOption,
1401
+ // From error-handling.ts
1402
+ errorHandlingActor,
1403
+ customTimeoutActor,
1404
+ // From inline-client.ts
1405
+ inlineClientActor,
1406
+ // From kv.ts
1407
+ kvActor,
1408
+ // From action-inputs.ts
1409
+ inputActor,
1410
+ // From action-timeout.ts
1411
+ shortTimeoutActor,
1412
+ longTimeoutActor,
1413
+ defaultTimeoutActor,
1414
+ syncTimeoutActor,
1415
+ // From action-types.ts
1416
+ syncActionActor,
1417
+ asyncActionActor,
1418
+ promiseActor,
1419
+ // From conn-params.ts
1420
+ counterWithParams,
1421
+ // From conn-state.ts
1422
+ connStateActor,
1423
+ // From metadata.ts
1424
+ metadataActor,
1425
+ // From vars.ts
1426
+ staticVarActor,
1427
+ nestedVarActor,
1428
+ dynamicVarActor,
1429
+ uniqueVarActor,
1430
+ driverCtxActor,
1431
+ // From raw-http.ts
1432
+ rawHttpActor,
1433
+ rawHttpNoHandlerActor,
1434
+ rawHttpVoidReturnActor,
1435
+ rawHttpHonoActor,
1436
+ // From raw-http-request-properties.ts
1437
+ rawHttpRequestPropertiesActor,
1438
+ // From raw-websocket.ts
1439
+ rawWebSocketActor,
1440
+ rawWebSocketBinaryActor,
1441
+ // From reject-connection.ts
1442
+ rejectConnectionActor,
1443
+ // From request-access.ts
1444
+ requestAccessActor,
1445
+ // From actor-onstatechange.ts
1446
+ onStateChangeActor,
1447
+ // From destroy.ts
1448
+ destroyActor,
1449
+ destroyObserver,
1450
+ // From hibernation.ts
1451
+ hibernationActor,
1452
+ // From large-payloads.ts
1453
+ largePayloadActor,
1454
+ largePayloadConnActor,
1455
+ // From start-stop-race.ts
1456
+ startStopRaceActor,
1457
+ lifecycleObserver,
1458
+ // From conn-error-serialization.ts
1459
+ connErrorSerializationActor
1460
+ }
1461
+ });
1462
+
1463
+ // src/serve-test-suite/mod.ts
1464
+ async function getPort() {
1465
+ const MIN_PORT = 1e4;
1466
+ const MAX_PORT = 65535;
1467
+ const getRandomPort = () => Math.floor(Math.random() * (MAX_PORT - MIN_PORT + 1)) + MIN_PORT;
1468
+ let port = getRandomPort();
1469
+ let maxAttempts = 10;
1470
+ while (maxAttempts > 0) {
1471
+ try {
1472
+ const server = await new Promise((resolve, reject) => {
1473
+ const server2 = createServer();
1474
+ server2.once("error", (err) => {
1475
+ if (err.code === "EADDRINUSE") {
1476
+ reject(new Error(`Port ${port} is in use`));
1477
+ } else {
1478
+ reject(err);
1479
+ }
1480
+ });
1481
+ server2.once("listening", () => {
1482
+ resolve(server2);
1483
+ });
1484
+ server2.listen(port);
1485
+ });
1486
+ await new Promise((resolve) => {
1487
+ server.close(() => resolve());
1488
+ });
1489
+ return port;
1490
+ } catch {
1491
+ maxAttempts--;
1492
+ if (maxAttempts <= 0) {
1493
+ break;
1494
+ }
1495
+ port = getRandomPort();
1496
+ }
1497
+ }
1498
+ throw new Error("Could not find an available port after multiple attempts");
1499
+ }
1500
+ async function serveTestSuite() {
1501
+ var _a;
1502
+ registry.config.test = { ...registry.config.test, enabled: true };
1503
+ registry.config.inspector = {
1504
+ enabled: true,
1505
+ token: () => "token"
1506
+ };
1507
+ const port = await getPort();
1508
+ registry.config.managerPort = port;
1509
+ registry.config.serverless = {
1510
+ ...registry.config.serverless,
1511
+ publicEndpoint: `http://127.0.0.1:${port}`
1512
+ };
1513
+ const driver = await createFileSystemOrMemoryDriver(
1514
+ true,
1515
+ `/tmp/rivetkit-test-suite-${crypto.randomUUID()}`
1516
+ );
1517
+ registry.config.driver = driver;
1518
+ let upgradeWebSocket;
1519
+ const parsedConfig = registry.parseConfig();
1520
+ const managerDriver = (_a = driver.manager) == null ? void 0 : _a.call(driver, parsedConfig);
1521
+ invariant(managerDriver, "missing manager driver");
1522
+ const { router } = buildManagerRouter(
1523
+ parsedConfig,
1524
+ managerDriver,
1525
+ () => upgradeWebSocket
1526
+ );
1527
+ const nodeWebSocket = createNodeWebSocket({ app: router });
1528
+ upgradeWebSocket = nodeWebSocket.upgradeWebSocket;
1529
+ managerDriver.setGetUpgradeWebSocket(() => upgradeWebSocket);
1530
+ const server = honoServe({
1531
+ fetch: router.fetch,
1532
+ hostname: "127.0.0.1",
1533
+ port
1534
+ });
1535
+ invariant(
1536
+ nodeWebSocket.injectWebSocket !== void 0,
1537
+ "should have injectWebSocket"
1538
+ );
1539
+ nodeWebSocket.injectWebSocket(server);
1540
+ const endpoint = `http://127.0.0.1:${port}`;
1541
+ logger().info({ msg: "test suite server listening", port });
1542
+ return {
1543
+ endpoint,
1544
+ namespace: "default",
1545
+ runnerName: "default",
1546
+ close: async () => {
1547
+ await new Promise((resolve) => server.close(() => resolve(void 0)));
1548
+ }
1549
+ };
1550
+ }
1551
+ async function runCli() {
1552
+ const result = await serveTestSuite();
1553
+ process.stdout.write(
1554
+ `${JSON.stringify({
1555
+ endpoint: result.endpoint,
1556
+ namespace: result.namespace,
1557
+ runnerName: result.runnerName
1558
+ })}
1559
+ `
1560
+ );
1561
+ const shutdown = async () => {
1562
+ await result.close();
1563
+ process.exit(0);
1564
+ };
1565
+ process.on("SIGINT", shutdown);
1566
+ process.on("SIGTERM", shutdown);
1567
+ }
1568
+ var mainPath = process.argv[1];
1569
+ if (mainPath && mainPath === fileURLToPath(import.meta.url)) {
1570
+ runCli().catch((err) => {
1571
+ logger().error({ msg: "serve-test-suite failed", error: err });
1572
+ process.exit(1);
1573
+ });
1574
+ }
1575
+ export {
1576
+ serveTestSuite
1577
+ };
1578
+ //# sourceMappingURL=mod.js.map