rivetkit 2.0.5 → 2.0.6

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 (116) hide show
  1. package/dist/tsup/actor-router-consts-BK6arfy8.d.cts +17 -0
  2. package/dist/tsup/actor-router-consts-BK6arfy8.d.ts +17 -0
  3. package/dist/tsup/chunk-2K3JMDAN.js +232 -0
  4. package/dist/tsup/chunk-2K3JMDAN.js.map +1 -0
  5. package/dist/tsup/chunk-42I3OZ3Q.js +15 -0
  6. package/dist/tsup/chunk-42I3OZ3Q.js.map +1 -0
  7. package/dist/tsup/{chunk-L7QRXNWP.js → chunk-4CKHQRXG.js} +1642 -4408
  8. package/dist/tsup/chunk-4CKHQRXG.js.map +1 -0
  9. package/dist/tsup/{chunk-WADSS5X4.cjs → chunk-5JBFVV4C.cjs} +2 -2
  10. package/dist/tsup/{chunk-WADSS5X4.cjs.map → chunk-5JBFVV4C.cjs.map} +1 -1
  11. package/dist/tsup/{chunk-FGFT4FVX.cjs → chunk-6P6RA47N.cjs} +9 -9
  12. package/dist/tsup/{chunk-FGFT4FVX.cjs.map → chunk-6P6RA47N.cjs.map} +1 -1
  13. package/dist/tsup/chunk-7OUKNSTU.js +1043 -0
  14. package/dist/tsup/chunk-7OUKNSTU.js.map +1 -0
  15. package/dist/tsup/{chunk-LZIBTLEY.cjs → chunk-DIAYNQTE.cjs} +13 -25
  16. package/dist/tsup/chunk-DIAYNQTE.cjs.map +1 -0
  17. package/dist/tsup/{chunk-YW6Y6VNE.js → chunk-G75SVQON.js} +4 -4
  18. package/dist/tsup/{chunk-PHSQJ6QI.cjs → chunk-KG3C7MKR.cjs} +3 -3
  19. package/dist/tsup/{chunk-PHSQJ6QI.cjs.map → chunk-KG3C7MKR.cjs.map} +1 -1
  20. package/dist/tsup/chunk-KUPQZYUQ.cjs +15 -0
  21. package/dist/tsup/chunk-KUPQZYUQ.cjs.map +1 -0
  22. package/dist/tsup/{chunk-5YTI25C3.cjs → chunk-MRRT2CZD.cjs} +7 -7
  23. package/dist/tsup/{chunk-5YTI25C3.cjs.map → chunk-MRRT2CZD.cjs.map} +1 -1
  24. package/dist/tsup/chunk-NTCUGYSD.cjs +1043 -0
  25. package/dist/tsup/chunk-NTCUGYSD.cjs.map +1 -0
  26. package/dist/tsup/{chunk-CFFKMUYH.js → chunk-RGQR2J7S.js} +2 -2
  27. package/dist/tsup/{chunk-CFFKMUYH.js.map → chunk-RGQR2J7S.js.map} +1 -1
  28. package/dist/tsup/chunk-TCUI5JFE.cjs +232 -0
  29. package/dist/tsup/chunk-TCUI5JFE.cjs.map +1 -0
  30. package/dist/tsup/chunk-TWGATZ3X.cjs +3676 -0
  31. package/dist/tsup/chunk-TWGATZ3X.cjs.map +1 -0
  32. package/dist/tsup/chunk-UFWAK3X2.cjs +3796 -0
  33. package/dist/tsup/chunk-UFWAK3X2.cjs.map +1 -0
  34. package/dist/tsup/{chunk-D7NWUCRK.cjs → chunk-UTI5NCES.cjs} +6 -6
  35. package/dist/tsup/{chunk-D7NWUCRK.cjs.map → chunk-UTI5NCES.cjs.map} +1 -1
  36. package/dist/tsup/{chunk-PG3K2LI7.js → chunk-VCEHU56K.js} +2 -2
  37. package/dist/tsup/{chunk-I5VTWPHW.js → chunk-VPV4MWXR.js} +3 -3
  38. package/dist/tsup/chunk-W6LN7AF5.js +3676 -0
  39. package/dist/tsup/chunk-W6LN7AF5.js.map +1 -0
  40. package/dist/tsup/{chunk-WNGOBAA7.js → chunk-WC2PSJWN.js} +2 -2
  41. package/dist/tsup/{chunk-CKA54YQN.js → chunk-ZYLTS2EM.js} +3 -15
  42. package/dist/tsup/chunk-ZYLTS2EM.js.map +1 -0
  43. package/dist/tsup/client/mod.cjs +9 -9
  44. package/dist/tsup/client/mod.d.cts +2 -2
  45. package/dist/tsup/client/mod.d.ts +2 -2
  46. package/dist/tsup/client/mod.js +8 -8
  47. package/dist/tsup/common/log.cjs +3 -3
  48. package/dist/tsup/common/log.js +2 -2
  49. package/dist/tsup/common/websocket.cjs +4 -4
  50. package/dist/tsup/common/websocket.js +3 -3
  51. package/dist/tsup/{connection-BvE-Oq7t.d.ts → connection-BLemxi4f.d.ts} +1 -1
  52. package/dist/tsup/{connection-DTzmWwU5.d.cts → connection-CpDIydXf.d.cts} +1 -1
  53. package/dist/tsup/driver-helpers/mod.cjs +5 -5
  54. package/dist/tsup/driver-helpers/mod.d.cts +2 -2
  55. package/dist/tsup/driver-helpers/mod.d.ts +2 -2
  56. package/dist/tsup/driver-helpers/mod.js +4 -4
  57. package/dist/tsup/driver-test-suite/mod.cjs +66 -58
  58. package/dist/tsup/driver-test-suite/mod.cjs.map +1 -1
  59. package/dist/tsup/driver-test-suite/mod.d.cts +1 -1
  60. package/dist/tsup/driver-test-suite/mod.d.ts +1 -1
  61. package/dist/tsup/driver-test-suite/mod.js +24 -16
  62. package/dist/tsup/driver-test-suite/mod.js.map +1 -1
  63. package/dist/tsup/inspector/mod.cjs +7 -5
  64. package/dist/tsup/inspector/mod.cjs.map +1 -1
  65. package/dist/tsup/inspector/mod.js +9 -7
  66. package/dist/tsup/mod.cjs +11 -8
  67. package/dist/tsup/mod.cjs.map +1 -1
  68. package/dist/tsup/mod.d.cts +52 -7
  69. package/dist/tsup/mod.d.ts +52 -7
  70. package/dist/tsup/mod.js +17 -14
  71. package/dist/tsup/test/mod.cjs +11 -9
  72. package/dist/tsup/test/mod.cjs.map +1 -1
  73. package/dist/tsup/test/mod.d.cts +1 -1
  74. package/dist/tsup/test/mod.d.ts +1 -1
  75. package/dist/tsup/test/mod.js +10 -8
  76. package/dist/tsup/utils.cjs +2 -2
  77. package/dist/tsup/utils.js +1 -1
  78. package/package.json +1 -1
  79. package/src/actor/mod.ts +5 -3
  80. package/src/actor/router-endpoints.ts +5 -32
  81. package/src/actor/router.ts +9 -8
  82. package/src/client/actor-conn.ts +9 -8
  83. package/src/client/actor-handle.ts +0 -1
  84. package/src/client/client.ts +1 -1
  85. package/src/client/raw-utils.ts +1 -1
  86. package/src/client/utils.ts +1 -1
  87. package/src/common/actor-router-consts.ts +38 -0
  88. package/src/driver-helpers/mod.ts +1 -1
  89. package/src/driver-test-suite/test-inline-client-driver.ts +4 -4
  90. package/src/driver-test-suite/utils.ts +7 -2
  91. package/src/drivers/engine/actor-driver.ts +18 -17
  92. package/src/manager/driver.ts +1 -1
  93. package/src/manager/protocol/query.ts +1 -1
  94. package/src/registry/mod.ts +7 -2
  95. package/src/registry/serve.ts +8 -3
  96. package/src/remote-manager-driver/actor-websocket-client.ts +2 -2
  97. package/src/remote-manager-driver/mod.ts +2 -5
  98. package/dist/tsup/chunk-2MD57QF4.js +0 -1794
  99. package/dist/tsup/chunk-2MD57QF4.js.map +0 -1
  100. package/dist/tsup/chunk-B2QGJGZQ.js +0 -338
  101. package/dist/tsup/chunk-B2QGJGZQ.js.map +0 -1
  102. package/dist/tsup/chunk-CKA54YQN.js.map +0 -1
  103. package/dist/tsup/chunk-IRMBWX36.cjs +0 -1794
  104. package/dist/tsup/chunk-IRMBWX36.cjs.map +0 -1
  105. package/dist/tsup/chunk-L7QRXNWP.js.map +0 -1
  106. package/dist/tsup/chunk-LZIBTLEY.cjs.map +0 -1
  107. package/dist/tsup/chunk-MRZS2J4X.cjs +0 -6562
  108. package/dist/tsup/chunk-MRZS2J4X.cjs.map +0 -1
  109. package/dist/tsup/chunk-RM2SVURR.cjs +0 -338
  110. package/dist/tsup/chunk-RM2SVURR.cjs.map +0 -1
  111. package/dist/tsup/router-endpoints-CctffZNL.d.cts +0 -65
  112. package/dist/tsup/router-endpoints-DFm1BglJ.d.ts +0 -65
  113. /package/dist/tsup/{chunk-YW6Y6VNE.js.map → chunk-G75SVQON.js.map} +0 -0
  114. /package/dist/tsup/{chunk-PG3K2LI7.js.map → chunk-VCEHU56K.js.map} +0 -0
  115. /package/dist/tsup/{chunk-I5VTWPHW.js.map → chunk-VPV4MWXR.js.map} +0 -0
  116. /package/dist/tsup/{chunk-WNGOBAA7.js.map → chunk-WC2PSJWN.js.map} +0 -0
@@ -0,0 +1,3796 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } var _class; var _class2; var _class3; var _class4;
2
+
3
+
4
+
5
+
6
+ var _chunkDIAYNQTEcjs = require('./chunk-DIAYNQTE.cjs');
7
+
8
+
9
+
10
+ var _chunkKG3C7MKRcjs = require('./chunk-KG3C7MKR.cjs');
11
+
12
+
13
+
14
+
15
+
16
+
17
+
18
+
19
+
20
+ var _chunkNTCUGYSDcjs = require('./chunk-NTCUGYSD.cjs');
21
+
22
+
23
+
24
+
25
+
26
+
27
+
28
+
29
+
30
+
31
+
32
+
33
+
34
+
35
+
36
+
37
+
38
+
39
+ var _chunkTCUI5JFEcjs = require('./chunk-TCUI5JFE.cjs');
40
+
41
+
42
+
43
+
44
+ var _chunkMRRT2CZDcjs = require('./chunk-MRRT2CZD.cjs');
45
+
46
+
47
+
48
+
49
+
50
+
51
+
52
+
53
+
54
+
55
+
56
+ var _chunk5JBFVV4Ccjs = require('./chunk-5JBFVV4C.cjs');
57
+
58
+
59
+
60
+
61
+
62
+
63
+
64
+
65
+
66
+
67
+
68
+
69
+
70
+ var _chunk5QGQK44Lcjs = require('./chunk-5QGQK44L.cjs');
71
+
72
+ // src/actor/connection.ts
73
+ var _cborx = require('cbor-x'); var cbor = _interopRequireWildcard(_cborx); var cbor2 = _interopRequireWildcard(_cborx); var cbor5 = _interopRequireWildcard(_cborx); var cbor4 = _interopRequireWildcard(_cborx); var cbor3 = _interopRequireWildcard(_cborx); var cbor6 = _interopRequireWildcard(_cborx);
74
+ function generateConnId() {
75
+ return crypto.randomUUID();
76
+ }
77
+ function generateConnToken() {
78
+ return _chunkTCUI5JFEcjs.generateSecureToken.call(void 0, 32);
79
+ }
80
+ var CONNECTION_DRIVER_WEBSOCKET = "webSocket";
81
+ var CONNECTION_DRIVER_SSE = "sse";
82
+ var CONNECTION_DRIVER_HTTP = "http";
83
+ var CONNECTION_CHECK_LIVENESS_SYMBOL = Symbol("checkLiveness");
84
+ var Conn = (_class = class {
85
+ __init() {this.subscriptions = /* @__PURE__ */ new Set()}
86
+ #stateEnabled;
87
+ // TODO: Remove this cyclical reference
88
+ #actor;
89
+ #status = "connected";
90
+ /**
91
+ * The proxied state that notifies of changes automatically.
92
+ *
93
+ * Any data that should be stored indefinitely should be held within this object.
94
+ */
95
+
96
+ /**
97
+ * Driver used to manage realtime connection communication.
98
+ *
99
+ * @protected
100
+ */
101
+ #driver;
102
+ get params() {
103
+ return this.__persist.params;
104
+ }
105
+ get driver() {
106
+ return this.__persist.connDriver;
107
+ }
108
+ get _stateEnabled() {
109
+ return this.#stateEnabled;
110
+ }
111
+ /**
112
+ * Gets the current state of the connection.
113
+ *
114
+ * Throws an error if the state is not enabled.
115
+ */
116
+ get state() {
117
+ this.#validateStateEnabled();
118
+ if (!this.__persist.state) throw new Error("state should exists");
119
+ return this.__persist.state;
120
+ }
121
+ /**
122
+ * Sets the state of the connection.
123
+ *
124
+ * Throws an error if the state is not enabled.
125
+ */
126
+ set state(value) {
127
+ this.#validateStateEnabled();
128
+ this.__persist.state = value;
129
+ }
130
+ /**
131
+ * Unique identifier for the connection.
132
+ */
133
+ get id() {
134
+ return this.__persist.connId;
135
+ }
136
+ /**
137
+ * Token used to authenticate this request.
138
+ */
139
+ get _token() {
140
+ return this.__persist.token;
141
+ }
142
+ /**
143
+ * Status of the connection.
144
+ */
145
+ get status() {
146
+ return this.#status;
147
+ }
148
+ /**
149
+ * Timestamp of the last time the connection was seen, i.e. the last time the connection was active and checked for liveness.
150
+ */
151
+ get lastSeen() {
152
+ return this.__persist.lastSeen;
153
+ }
154
+ /**
155
+ * Initializes a new instance of the Connection class.
156
+ *
157
+ * This should only be constructed by {@link Actor}.
158
+ *
159
+ * @protected
160
+ */
161
+ constructor(actor, persist, driver, stateEnabled) {;_class.prototype.__init.call(this);
162
+ this.#actor = actor;
163
+ this.__persist = persist;
164
+ this.#driver = driver;
165
+ this.#stateEnabled = stateEnabled;
166
+ }
167
+ #validateStateEnabled() {
168
+ if (!this.#stateEnabled) {
169
+ throw new (0, _chunk5QGQK44Lcjs.ConnStateNotEnabled)();
170
+ }
171
+ }
172
+ /**
173
+ * Sends a WebSocket message to the client.
174
+ *
175
+ * @param message - The message to send.
176
+ *
177
+ * @protected
178
+ */
179
+ _sendMessage(message) {
180
+ var _a, _b;
181
+ (_b = (_a = this.#driver).sendMessage) == null ? void 0 : _b.call(
182
+ _a,
183
+ this.#actor,
184
+ this,
185
+ this.__persist.connDriverState,
186
+ message
187
+ );
188
+ }
189
+ /**
190
+ * Sends an event with arguments to the client.
191
+ *
192
+ * @param eventName - The name of the event.
193
+ * @param args - The arguments for the event.
194
+ * @see {@link https://rivet.dev/docs/events|Events Documentation}
195
+ */
196
+ send(eventName, ...args) {
197
+ this.#actor.inspector.emitter.emit("eventFired", {
198
+ type: "event",
199
+ eventName,
200
+ args,
201
+ connId: this.id
202
+ });
203
+ this._sendMessage(
204
+ new (0, _chunkTCUI5JFEcjs.CachedSerializer)(
205
+ {
206
+ body: {
207
+ tag: "Event",
208
+ val: {
209
+ name: eventName,
210
+ args: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor.encode(args))
211
+ }
212
+ }
213
+ },
214
+ _chunkNTCUGYSDcjs.TO_CLIENT_VERSIONED
215
+ )
216
+ );
217
+ }
218
+ /**
219
+ * Disconnects the client with an optional reason.
220
+ *
221
+ * @param reason - The reason for disconnection.
222
+ */
223
+ async disconnect(reason) {
224
+ this.#status = "reconnecting";
225
+ await this.#driver.disconnect(
226
+ this.#actor,
227
+ this,
228
+ this.__persist.connDriverState,
229
+ reason
230
+ );
231
+ }
232
+ /**
233
+ * This method checks the connection's liveness by querying the driver for its ready state.
234
+ * If the connection is not closed, it updates the last liveness timestamp and returns `true`.
235
+ * Otherwise, it returns `false`.
236
+ * @internal
237
+ */
238
+ [CONNECTION_CHECK_LIVENESS_SYMBOL]() {
239
+ const readyState = this.#driver.getConnectionReadyState(this.#actor, this);
240
+ const isConnectionClosed = readyState === 3 /* CLOSED */ || readyState === 2 /* CLOSING */ || readyState === void 0;
241
+ const newLastSeen = Date.now();
242
+ const newStatus = isConnectionClosed ? "reconnecting" : "connected";
243
+ this.#actor.rLog.debug({
244
+ msg: "liveness probe for connection",
245
+ connId: this.id,
246
+ actorId: this.#actor.id,
247
+ readyState,
248
+ status: this.#status,
249
+ newStatus,
250
+ lastSeen: this.__persist.lastSeen,
251
+ currentTs: newLastSeen
252
+ });
253
+ if (!isConnectionClosed) {
254
+ this.__persist.lastSeen = newLastSeen;
255
+ }
256
+ this.#status = newStatus;
257
+ return {
258
+ status: this.#status,
259
+ lastSeen: this.__persist.lastSeen
260
+ };
261
+ }
262
+ }, _class);
263
+
264
+ // src/actor/instance.ts
265
+
266
+ var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant);
267
+ var _onchange = require('on-change'); var _onchange2 = _interopRequireDefault(_onchange);
268
+
269
+ // src/inspector/actor.ts
270
+ var _standardvalidator = require('@hono/standard-validator');
271
+ var _fastjsonpatch = require('@rivetkit/fast-json-patch'); var _fastjsonpatch2 = _interopRequireDefault(_fastjsonpatch);
272
+ var _hono = require('hono');
273
+ var _streaming = require('hono/streaming');
274
+ var _nanoevents = require('nanoevents');
275
+ var _v4 = require('zod/v4'); var _v42 = _interopRequireDefault(_v4);
276
+ function createActorInspectorRouter() {
277
+ return new (0, _hono.Hono)().get("/ping", (c) => {
278
+ return c.json({ message: "pong" }, 200);
279
+ }).get("/state", async (c) => {
280
+ if (await c.var.inspector.accessors.isStateEnabled()) {
281
+ return c.json(
282
+ {
283
+ enabled: true,
284
+ state: await c.var.inspector.accessors.getState()
285
+ },
286
+ 200
287
+ );
288
+ }
289
+ return c.json({ enabled: false, state: null }, 200);
290
+ }).patch(
291
+ "/state",
292
+ _standardvalidator.sValidator.call(void 0,
293
+ "json",
294
+ _v42.default.object({ patch: _chunkDIAYNQTEcjs.PatchSchema }).or(_v42.default.object({ replace: _v42.default.any() }))
295
+ ),
296
+ async (c) => {
297
+ if (!await c.var.inspector.accessors.isStateEnabled()) {
298
+ return c.json({ enabled: false }, 200);
299
+ }
300
+ const body = c.req.valid("json");
301
+ if ("replace" in body) {
302
+ await c.var.inspector.accessors.setState(body.replace);
303
+ return c.json(
304
+ {
305
+ enabled: true,
306
+ state: await c.var.inspector.accessors.getState()
307
+ },
308
+ 200
309
+ );
310
+ }
311
+ const state = await c.var.inspector.accessors.getState();
312
+ const { newDocument: newState } = _fastjsonpatch2.default.applyPatch(
313
+ state,
314
+ body.patch
315
+ );
316
+ await c.var.inspector.accessors.setState(newState);
317
+ return c.json(
318
+ { enabled: true, state: await c.var.inspector.accessors.getState() },
319
+ 200
320
+ );
321
+ }
322
+ ).get("/state/stream", async (c) => {
323
+ if (!await c.var.inspector.accessors.isStateEnabled()) {
324
+ return c.json({ enabled: false }, 200);
325
+ }
326
+ let id = 0;
327
+ let unsub;
328
+ return _streaming.streamSSE.call(void 0,
329
+ c,
330
+ async (stream) => {
331
+ unsub = c.var.inspector.emitter.on("stateUpdated", async (state) => {
332
+ stream.writeSSE({
333
+ data: JSON.stringify(state) || "",
334
+ event: "state-update",
335
+ id: String(id++)
336
+ });
337
+ });
338
+ const { promise } = Promise.withResolvers();
339
+ return promise;
340
+ },
341
+ async () => {
342
+ unsub == null ? void 0 : unsub();
343
+ }
344
+ );
345
+ }).get("/connections", async (c) => {
346
+ const connections = await c.var.inspector.accessors.getConnections();
347
+ return c.json({ connections }, 200);
348
+ }).get("/connections/stream", async (c) => {
349
+ let id = 0;
350
+ let unsub;
351
+ return _streaming.streamSSE.call(void 0,
352
+ c,
353
+ async (stream) => {
354
+ unsub = c.var.inspector.emitter.on("connectionUpdated", async () => {
355
+ stream.writeSSE({
356
+ data: JSON.stringify(
357
+ await c.var.inspector.accessors.getConnections()
358
+ ),
359
+ event: "connection-update",
360
+ id: String(id++)
361
+ });
362
+ });
363
+ const { promise } = Promise.withResolvers();
364
+ return promise;
365
+ },
366
+ async () => {
367
+ unsub == null ? void 0 : unsub();
368
+ }
369
+ );
370
+ }).get("/events", async (c) => {
371
+ const events = c.var.inspector.lastRealtimeEvents;
372
+ return c.json({ events }, 200);
373
+ }).post("/events/clear", async (c) => {
374
+ c.var.inspector.lastRealtimeEvents.length = 0;
375
+ return c.json({ message: "Events cleared" }, 200);
376
+ }).get("/events/stream", async (c) => {
377
+ let id = 0;
378
+ let unsub;
379
+ return _streaming.streamSSE.call(void 0,
380
+ c,
381
+ async (stream) => {
382
+ unsub = c.var.inspector.emitter.on("eventFired", () => {
383
+ stream.writeSSE({
384
+ data: JSON.stringify(c.var.inspector.lastRealtimeEvents),
385
+ event: "realtime-event",
386
+ id: String(id++)
387
+ });
388
+ });
389
+ const { promise } = Promise.withResolvers();
390
+ return promise;
391
+ },
392
+ async () => {
393
+ unsub == null ? void 0 : unsub();
394
+ }
395
+ );
396
+ }).get("/rpcs", async (c) => {
397
+ const rpcs = await c.var.inspector.accessors.getRpcs();
398
+ return c.json({ rpcs }, 200);
399
+ }).get("/db", async (c) => {
400
+ if (!await c.var.inspector.accessors.isDbEnabled()) {
401
+ return c.json({ enabled: false, db: null }, 200);
402
+ }
403
+ const db = await c.var.inspector.accessors.getDb();
404
+ const rows = await db.execute(`PRAGMA table_list`);
405
+ const tables = _chunkDIAYNQTEcjs.TablesSchema.parse(rows).filter(
406
+ (table) => table.schema !== "temp" && !table.name.startsWith("sqlite_")
407
+ );
408
+ const tablesInfo = await Promise.all(
409
+ tables.map((table) => db.execute(`PRAGMA table_info(${table.name})`))
410
+ );
411
+ const columns = tablesInfo.map((def) => _chunkDIAYNQTEcjs.ColumnsSchema.parse(def));
412
+ const foreignKeysList = await Promise.all(
413
+ tables.map(
414
+ (table) => db.execute(`PRAGMA foreign_key_list(${table.name})`)
415
+ )
416
+ );
417
+ const foreignKeys = foreignKeysList.map(
418
+ (def) => _chunkDIAYNQTEcjs.ForeignKeysSchema.parse(def)
419
+ );
420
+ const countInfo = await Promise.all(
421
+ tables.map(
422
+ (table) => db.execute(`SELECT COUNT(*) as count FROM ${table.name}`)
423
+ )
424
+ );
425
+ const counts = countInfo.map((def) => {
426
+ return def[0].count || 0;
427
+ });
428
+ return c.json(
429
+ {
430
+ enabled: true,
431
+ db: tablesInfo.map((_, index) => {
432
+ return {
433
+ table: tables[index],
434
+ columns: columns[index],
435
+ foreignKeys: foreignKeys[index],
436
+ records: counts[index]
437
+ };
438
+ })
439
+ },
440
+ 200
441
+ );
442
+ }).post(
443
+ "/db",
444
+ _standardvalidator.sValidator.call(void 0,
445
+ "json",
446
+ _v42.default.object({ query: _v42.default.string(), params: _v42.default.array(_v42.default.any()).optional() })
447
+ ),
448
+ async (c) => {
449
+ if (!await c.var.inspector.accessors.isDbEnabled()) {
450
+ return c.json({ enabled: false }, 200);
451
+ }
452
+ const db = await c.var.inspector.accessors.getDb();
453
+ try {
454
+ const result = await db.execute(
455
+ c.req.valid("json").query,
456
+ ...c.req.valid("json").params || []
457
+ );
458
+ return c.json({ result }, 200);
459
+ } catch (error) {
460
+ c;
461
+ return c.json({ error: error.message }, 500);
462
+ }
463
+ }
464
+ );
465
+ }
466
+ var ActorInspector = (_class2 = class {
467
+
468
+ __init2() {this.emitter = _nanoevents.createNanoEvents.call(void 0, )}
469
+ #lastRealtimeEvents = [];
470
+ get lastRealtimeEvents() {
471
+ return this.#lastRealtimeEvents;
472
+ }
473
+ constructor(accessors) {;_class2.prototype.__init2.call(this);
474
+ this.accessors = accessors();
475
+ this.emitter.on("eventFired", (event) => {
476
+ this.#lastRealtimeEvents.push({
477
+ id: crypto.randomUUID(),
478
+ timestamp: Date.now(),
479
+ ...event
480
+ });
481
+ if (this.#lastRealtimeEvents.length > 100) {
482
+ this.#lastRealtimeEvents = this.#lastRealtimeEvents.slice(-100);
483
+ }
484
+ });
485
+ }
486
+ }, _class2);
487
+
488
+ // src/actor/context.ts
489
+ var ActorContext = class {
490
+ #actor;
491
+ constructor(actor) {
492
+ this.#actor = actor;
493
+ }
494
+ /**
495
+ * Get the actor state
496
+ */
497
+ get state() {
498
+ return this.#actor.state;
499
+ }
500
+ /**
501
+ * Get the actor variables
502
+ */
503
+ get vars() {
504
+ return this.#actor.vars;
505
+ }
506
+ /**
507
+ * Broadcasts an event to all connected clients.
508
+ * @param name - The name of the event.
509
+ * @param args - The arguments to send with the event.
510
+ */
511
+ broadcast(name, ...args) {
512
+ this.#actor._broadcast(name, ...args);
513
+ return;
514
+ }
515
+ /**
516
+ * Gets the logger instance.
517
+ */
518
+ get log() {
519
+ return this.#actor.log;
520
+ }
521
+ /**
522
+ * Gets actor ID.
523
+ */
524
+ get actorId() {
525
+ return this.#actor.id;
526
+ }
527
+ /**
528
+ * Gets the actor name.
529
+ */
530
+ get name() {
531
+ return this.#actor.name;
532
+ }
533
+ /**
534
+ * Gets the actor key.
535
+ */
536
+ get key() {
537
+ return this.#actor.key;
538
+ }
539
+ /**
540
+ * Gets the region.
541
+ */
542
+ get region() {
543
+ return this.#actor.region;
544
+ }
545
+ /**
546
+ * Gets the scheduler.
547
+ */
548
+ get schedule() {
549
+ return this.#actor.schedule;
550
+ }
551
+ /**
552
+ * Gets the map of connections.
553
+ */
554
+ get conns() {
555
+ return this.#actor.conns;
556
+ }
557
+ /**
558
+ * Returns the client for the given registry.
559
+ */
560
+ client() {
561
+ return this.#actor.inlineClient;
562
+ }
563
+ /**
564
+ * Gets the database.
565
+ * @experimental
566
+ * @throws {DatabaseNotEnabled} If the database is not enabled.
567
+ */
568
+ get db() {
569
+ return this.#actor.db;
570
+ }
571
+ /**
572
+ * Forces the state to get saved.
573
+ *
574
+ * @param opts - Options for saving the state.
575
+ */
576
+ async saveState(opts) {
577
+ return this.#actor.saveState(opts);
578
+ }
579
+ /**
580
+ * Prevents the actor from sleeping until promise is complete.
581
+ */
582
+ waitUntil(promise) {
583
+ this.#actor._waitUntil(promise);
584
+ }
585
+ /**
586
+ * AbortSignal that fires when the actor is stopping.
587
+ */
588
+ get abortSignal() {
589
+ return this.#actor.abortSignal;
590
+ }
591
+ /**
592
+ * Forces the actor to sleep.
593
+ *
594
+ * Not supported on all drivers.
595
+ *
596
+ * @experimental
597
+ */
598
+ sleep() {
599
+ this.#actor._sleep();
600
+ }
601
+ };
602
+
603
+ // src/actor/keys.ts
604
+ var EMPTY_KEY = "/";
605
+ var KEY_SEPARATOR = "/";
606
+ function serializeActorKey(key) {
607
+ if (key.length === 0) {
608
+ return EMPTY_KEY;
609
+ }
610
+ const escapedParts = key.map((part) => {
611
+ if (part === "") {
612
+ return "\\0";
613
+ }
614
+ let escaped = part.replace(/\\/g, "\\\\");
615
+ escaped = escaped.replace(/\//g, `\\${KEY_SEPARATOR}`);
616
+ return escaped;
617
+ });
618
+ return escapedParts.join(KEY_SEPARATOR);
619
+ }
620
+ function deserializeActorKey(keyString) {
621
+ if (keyString === void 0 || keyString === null || keyString === EMPTY_KEY) {
622
+ return [];
623
+ }
624
+ const parts = [];
625
+ let currentPart = "";
626
+ let escaping = false;
627
+ let isEmptyStringMarker = false;
628
+ for (let i = 0; i < keyString.length; i++) {
629
+ const char = keyString[i];
630
+ if (escaping) {
631
+ if (char === "0") {
632
+ isEmptyStringMarker = true;
633
+ } else {
634
+ currentPart += char;
635
+ }
636
+ escaping = false;
637
+ } else if (char === "\\") {
638
+ escaping = true;
639
+ } else if (char === KEY_SEPARATOR) {
640
+ if (isEmptyStringMarker) {
641
+ parts.push("");
642
+ isEmptyStringMarker = false;
643
+ } else {
644
+ parts.push(currentPart);
645
+ }
646
+ currentPart = "";
647
+ } else {
648
+ currentPart += char;
649
+ }
650
+ }
651
+ if (escaping) {
652
+ parts.push(currentPart + "\\");
653
+ } else if (isEmptyStringMarker) {
654
+ parts.push("");
655
+ } else if (currentPart !== "" || parts.length > 0) {
656
+ parts.push(currentPart);
657
+ }
658
+ return parts;
659
+ }
660
+
661
+ // src/actor/schedule.ts
662
+ var Schedule = class {
663
+ #actor;
664
+ constructor(actor) {
665
+ this.#actor = actor;
666
+ }
667
+ async after(duration, fn, ...args) {
668
+ await this.#actor.scheduleEvent(Date.now() + duration, fn, args);
669
+ }
670
+ async at(timestamp, fn, ...args) {
671
+ await this.#actor.scheduleEvent(timestamp, fn, args);
672
+ }
673
+ };
674
+
675
+ // src/actor/instance.ts
676
+ var ActorInstance = class {
677
+ // Shared actor context for this instance
678
+
679
+ /** Actor log, intended for the user to call */
680
+ #log;
681
+ /** Runtime log, intended for internal actor logs */
682
+ #rLog;
683
+ #sleepCalled = false;
684
+ #stopCalled = false;
685
+ get isStopping() {
686
+ return this.#stopCalled || this.#sleepCalled;
687
+ }
688
+ #persistChanged = false;
689
+ #isInOnStateChange = false;
690
+ /**
691
+ * The proxied state that notifies of changes automatically.
692
+ *
693
+ * Any data that should be stored indefinitely should be held within this object.
694
+ */
695
+ #persist;
696
+ /** Raw state without the proxy wrapper */
697
+ #persistRaw;
698
+ #persistWriteQueue = new (0, _chunk5JBFVV4Ccjs.SinglePromiseQueue)();
699
+ #alarmWriteQueue = new (0, _chunk5JBFVV4Ccjs.SinglePromiseQueue)();
700
+ #lastSaveTime = 0;
701
+ #pendingSaveTimeout;
702
+ #vars;
703
+ #backgroundPromises = [];
704
+ #abortController = new AbortController();
705
+ #config;
706
+ #connectionDrivers;
707
+ #actorDriver;
708
+ #inlineClient;
709
+ #actorId;
710
+ #name;
711
+ #key;
712
+ #region;
713
+ #ready = false;
714
+ #connections = /* @__PURE__ */ new Map();
715
+ #subscriptionIndex = /* @__PURE__ */ new Map();
716
+ #checkConnLivenessInterval;
717
+ #sleepTimeout;
718
+ // Track active raw requests so sleep logic can account for them
719
+ #activeRawFetchCount = 0;
720
+ #activeRawWebSockets = /* @__PURE__ */ new Set();
721
+ #schedule;
722
+ #db;
723
+ #inspector = new ActorInspector(() => {
724
+ return {
725
+ isDbEnabled: async () => {
726
+ return this.#db !== void 0;
727
+ },
728
+ getDb: async () => {
729
+ return this.db;
730
+ },
731
+ isStateEnabled: async () => {
732
+ return this.stateEnabled;
733
+ },
734
+ getState: async () => {
735
+ this.#validateStateEnabled();
736
+ return this.#persistRaw.state;
737
+ },
738
+ getRpcs: async () => {
739
+ return Object.keys(this.#config.actions);
740
+ },
741
+ getConnections: async () => {
742
+ return Array.from(this.#connections.entries()).map(([id, conn]) => ({
743
+ id,
744
+ stateEnabled: conn._stateEnabled,
745
+ params: conn.params,
746
+ state: conn._stateEnabled ? conn.state : void 0
747
+ }));
748
+ },
749
+ setState: async (state) => {
750
+ this.#validateStateEnabled();
751
+ this.#persist.state = { ...state };
752
+ await this.saveState({ immediate: true });
753
+ }
754
+ };
755
+ });
756
+ get id() {
757
+ return this.#actorId;
758
+ }
759
+ get inlineClient() {
760
+ return this.#inlineClient;
761
+ }
762
+ get inspector() {
763
+ return this.#inspector;
764
+ }
765
+ get #sleepingSupported() {
766
+ return this.#actorDriver.sleep !== void 0;
767
+ }
768
+ /**
769
+ * This constructor should never be used directly.
770
+ *
771
+ * Constructed in {@link ActorInstance.start}.
772
+ *
773
+ * @private
774
+ */
775
+ constructor(config) {
776
+ this.#config = config;
777
+ this.actorContext = new ActorContext(this);
778
+ }
779
+ async start(connectionDrivers, actorDriver, inlineClient, actorId, name, key, region) {
780
+ var _a, _b;
781
+ const logParams = {
782
+ actor: name,
783
+ key: serializeActorKey(key),
784
+ actorId
785
+ };
786
+ this.#log = _chunkMRRT2CZDcjs.getBaseLogger.call(void 0, ).child(
787
+ Object.assign(_chunkMRRT2CZDcjs.getIncludeTarget.call(void 0, ) ? { target: "actor" } : {}, logParams)
788
+ );
789
+ this.#rLog = _chunkMRRT2CZDcjs.getBaseLogger.call(void 0, ).child(
790
+ Object.assign(
791
+ _chunkMRRT2CZDcjs.getIncludeTarget.call(void 0, ) ? { target: "actor-runtime" } : {},
792
+ logParams
793
+ )
794
+ );
795
+ this.#connectionDrivers = connectionDrivers;
796
+ this.#actorDriver = actorDriver;
797
+ this.#inlineClient = inlineClient;
798
+ this.#actorId = actorId;
799
+ this.#name = name;
800
+ this.#key = key;
801
+ this.#region = region;
802
+ this.#schedule = new Schedule(this);
803
+ await this.#initialize();
804
+ if (this.#varsEnabled) {
805
+ let vars;
806
+ if ("createVars" in this.#config) {
807
+ const dataOrPromise = this.#config.createVars(
808
+ this.actorContext,
809
+ this.#actorDriver.getContext(this.#actorId)
810
+ );
811
+ if (dataOrPromise instanceof Promise) {
812
+ vars = await _chunkTCUI5JFEcjs.deadline.call(void 0,
813
+ dataOrPromise,
814
+ this.#config.options.createVarsTimeout
815
+ );
816
+ } else {
817
+ vars = dataOrPromise;
818
+ }
819
+ } else if ("vars" in this.#config) {
820
+ vars = structuredClone(this.#config.vars);
821
+ } else {
822
+ throw new Error("Could not variables from 'createVars' or 'vars'");
823
+ }
824
+ this.#vars = vars;
825
+ }
826
+ this.#rLog.info({ msg: "actor starting" });
827
+ if (this.#config.onStart) {
828
+ const result = this.#config.onStart(this.actorContext);
829
+ if (result instanceof Promise) {
830
+ await result;
831
+ }
832
+ }
833
+ if ("db" in this.#config && this.#config.db) {
834
+ const client = await this.#config.db.createClient({
835
+ getDatabase: () => actorDriver.getDatabase(this.#actorId)
836
+ });
837
+ this.#rLog.info({ msg: "database migration starting" });
838
+ await ((_b = (_a = this.#config.db).onMigrate) == null ? void 0 : _b.call(_a, client));
839
+ this.#rLog.info({ msg: "database migration complete" });
840
+ this.#db = client;
841
+ }
842
+ if (this.#persist.scheduledEvents.length > 0) {
843
+ await this.#queueSetAlarm(this.#persist.scheduledEvents[0].timestamp);
844
+ }
845
+ this.#rLog.info({ msg: "actor ready" });
846
+ this.#ready = true;
847
+ this.#resetSleepTimer();
848
+ this.#checkConnLivenessInterval = setInterval(
849
+ this.#checkConnectionsLiveness.bind(this),
850
+ this.#config.options.connectionLivenessInterval
851
+ );
852
+ this.#checkConnectionsLiveness();
853
+ }
854
+ async #scheduleEventInner(newEvent) {
855
+ this.actorContext.log.info({ msg: "scheduling event", ...newEvent });
856
+ const insertIndex = this.#persist.scheduledEvents.findIndex(
857
+ (x) => x.timestamp > newEvent.timestamp
858
+ );
859
+ if (insertIndex === -1) {
860
+ this.#persist.scheduledEvents.push(newEvent);
861
+ } else {
862
+ this.#persist.scheduledEvents.splice(insertIndex, 0, newEvent);
863
+ }
864
+ if (insertIndex === 0 || this.#persist.scheduledEvents.length === 1) {
865
+ this.actorContext.log.info({
866
+ msg: "setting alarm",
867
+ timestamp: newEvent.timestamp,
868
+ eventCount: this.#persist.scheduledEvents.length
869
+ });
870
+ await this.#queueSetAlarm(newEvent.timestamp);
871
+ }
872
+ }
873
+ async _onAlarm() {
874
+ const now = Date.now();
875
+ this.actorContext.log.debug({
876
+ msg: "alarm triggered",
877
+ now,
878
+ events: this.#persist.scheduledEvents.length
879
+ });
880
+ this.#resetSleepTimer();
881
+ const runIndex = this.#persist.scheduledEvents.findIndex(
882
+ (x) => x.timestamp <= now
883
+ );
884
+ if (runIndex === -1) {
885
+ this.#rLog.warn({ msg: "no events are due yet, time may have broken" });
886
+ if (this.#persist.scheduledEvents.length > 0) {
887
+ const nextTs = this.#persist.scheduledEvents[0].timestamp;
888
+ this.actorContext.log.warn({
889
+ msg: "alarm fired early, rescheduling for next event",
890
+ now,
891
+ nextTs,
892
+ delta: nextTs - now
893
+ });
894
+ await this.#queueSetAlarm(nextTs);
895
+ }
896
+ this.actorContext.log.debug({ msg: "no events to run", now });
897
+ return;
898
+ }
899
+ const scheduleEvents = this.#persist.scheduledEvents.splice(
900
+ 0,
901
+ runIndex + 1
902
+ );
903
+ this.actorContext.log.debug({
904
+ msg: "running events",
905
+ count: scheduleEvents.length
906
+ });
907
+ if (this.#persist.scheduledEvents.length > 0) {
908
+ const nextTs = this.#persist.scheduledEvents[0].timestamp;
909
+ this.actorContext.log.info({
910
+ msg: "setting next alarm",
911
+ nextTs,
912
+ remainingEvents: this.#persist.scheduledEvents.length
913
+ });
914
+ await this.#queueSetAlarm(nextTs);
915
+ }
916
+ for (const event of scheduleEvents) {
917
+ try {
918
+ this.actorContext.log.info({
919
+ msg: "running action for event",
920
+ event: event.eventId,
921
+ timestamp: event.timestamp,
922
+ action: event.kind.generic.actionName
923
+ });
924
+ const fn = this.#config.actions[event.kind.generic.actionName];
925
+ if (!fn)
926
+ throw new Error(
927
+ `Missing action for alarm ${event.kind.generic.actionName}`
928
+ );
929
+ if (typeof fn !== "function")
930
+ throw new Error(
931
+ `Alarm function lookup for ${event.kind.generic.actionName} returned ${typeof fn}`
932
+ );
933
+ try {
934
+ const args = event.kind.generic.args ? cbor2.decode(new Uint8Array(event.kind.generic.args)) : [];
935
+ await fn.call(void 0, this.actorContext, ...args);
936
+ } catch (error) {
937
+ this.actorContext.log.error({
938
+ msg: "error while running event",
939
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error),
940
+ event: event.eventId,
941
+ timestamp: event.timestamp,
942
+ action: event.kind.generic.actionName
943
+ });
944
+ }
945
+ } catch (error) {
946
+ this.actorContext.log.error({
947
+ msg: "internal error while running event",
948
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error),
949
+ ...event
950
+ });
951
+ }
952
+ }
953
+ }
954
+ async scheduleEvent(timestamp, action, args) {
955
+ return this.#scheduleEventInner({
956
+ eventId: crypto.randomUUID(),
957
+ timestamp,
958
+ kind: {
959
+ generic: {
960
+ actionName: action,
961
+ args: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor2.encode(args))
962
+ }
963
+ }
964
+ });
965
+ }
966
+ get stateEnabled() {
967
+ return "createState" in this.#config || "state" in this.#config;
968
+ }
969
+ #validateStateEnabled() {
970
+ if (!this.stateEnabled) {
971
+ throw new (0, _chunk5QGQK44Lcjs.StateNotEnabled)();
972
+ }
973
+ }
974
+ get #connStateEnabled() {
975
+ return "createConnState" in this.#config || "connState" in this.#config;
976
+ }
977
+ get #varsEnabled() {
978
+ return "createVars" in this.#config || "vars" in this.#config;
979
+ }
980
+ #validateVarsEnabled() {
981
+ if (!this.#varsEnabled) {
982
+ throw new (0, _chunk5QGQK44Lcjs.VarsNotEnabled)();
983
+ }
984
+ }
985
+ /** Promise used to wait for a save to complete. This is required since you cannot await `#saveStateThrottled`. */
986
+ #onPersistSavedPromise;
987
+ /** Throttled save state method. Used to write to KV at a reasonable cadence. */
988
+ #savePersistThrottled() {
989
+ const now = Date.now();
990
+ const timeSinceLastSave = now - this.#lastSaveTime;
991
+ const saveInterval = this.#config.options.stateSaveInterval;
992
+ if (timeSinceLastSave < saveInterval) {
993
+ if (this.#pendingSaveTimeout === void 0) {
994
+ this.#pendingSaveTimeout = setTimeout(() => {
995
+ this.#pendingSaveTimeout = void 0;
996
+ this.#savePersistInner();
997
+ }, saveInterval - timeSinceLastSave);
998
+ }
999
+ } else {
1000
+ this.#savePersistInner();
1001
+ }
1002
+ }
1003
+ /** Saves the state to KV. You probably want to use #saveStateThrottled instead except for a few edge cases. */
1004
+ async #savePersistInner() {
1005
+ var _a, _b;
1006
+ try {
1007
+ this.#lastSaveTime = Date.now();
1008
+ if (this.#persistChanged) {
1009
+ const finished = this.#persistWriteQueue.enqueue(async () => {
1010
+ this.#rLog.debug({ msg: "saving persist" });
1011
+ this.#persistChanged = false;
1012
+ const bareData = this.#convertToBarePersisted(this.#persistRaw);
1013
+ await this.#actorDriver.writePersistedData(
1014
+ this.#actorId,
1015
+ _chunkNTCUGYSDcjs.PERSISTED_ACTOR_VERSIONED.serializeWithEmbeddedVersion(bareData)
1016
+ );
1017
+ this.#rLog.debug({ msg: "persist saved" });
1018
+ });
1019
+ await finished;
1020
+ }
1021
+ (_a = this.#onPersistSavedPromise) == null ? void 0 : _a.resolve();
1022
+ } catch (error) {
1023
+ (_b = this.#onPersistSavedPromise) == null ? void 0 : _b.reject(error);
1024
+ throw error;
1025
+ }
1026
+ }
1027
+ async #queueSetAlarm(timestamp) {
1028
+ await this.#alarmWriteQueue.enqueue(async () => {
1029
+ await this.#actorDriver.setAlarm(this, timestamp);
1030
+ });
1031
+ }
1032
+ /**
1033
+ * Creates proxy for `#persist` that handles automatically flagging when state needs to be updated.
1034
+ */
1035
+ #setPersist(target) {
1036
+ this.#persistRaw = target;
1037
+ if (target === null || typeof target !== "object") {
1038
+ let invalidPath = "";
1039
+ if (!_chunk5JBFVV4Ccjs.isCborSerializable.call(void 0,
1040
+ target,
1041
+ (path) => {
1042
+ invalidPath = path;
1043
+ },
1044
+ ""
1045
+ )) {
1046
+ throw new (0, _chunk5QGQK44Lcjs.InvalidStateType)({ path: invalidPath });
1047
+ }
1048
+ return target;
1049
+ }
1050
+ if (this.#persist) {
1051
+ _onchange2.default.unsubscribe(this.#persist);
1052
+ }
1053
+ this.#persist = _onchange2.default.call(void 0,
1054
+ target,
1055
+ // biome-ignore lint/suspicious/noExplicitAny: Don't know types in proxy
1056
+ (path, value, _previousValue, _applyData) => {
1057
+ if (path !== "state" && !path.startsWith("state.")) {
1058
+ return;
1059
+ }
1060
+ let invalidPath = "";
1061
+ if (!_chunk5JBFVV4Ccjs.isCborSerializable.call(void 0,
1062
+ value,
1063
+ (invalidPathPart) => {
1064
+ invalidPath = invalidPathPart;
1065
+ },
1066
+ ""
1067
+ )) {
1068
+ throw new (0, _chunk5QGQK44Lcjs.InvalidStateType)({
1069
+ path: path + (invalidPath ? `.${invalidPath}` : "")
1070
+ });
1071
+ }
1072
+ this.#persistChanged = true;
1073
+ this.inspector.emitter.emit("stateUpdated", this.#persist.state);
1074
+ if (this.#config.onStateChange && this.#ready && !this.#isInOnStateChange) {
1075
+ try {
1076
+ this.#isInOnStateChange = true;
1077
+ this.#config.onStateChange(
1078
+ this.actorContext,
1079
+ this.#persistRaw.state
1080
+ );
1081
+ } catch (error) {
1082
+ this.#rLog.error({
1083
+ msg: "error in `_onStateChange`",
1084
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1085
+ });
1086
+ } finally {
1087
+ this.#isInOnStateChange = false;
1088
+ }
1089
+ }
1090
+ },
1091
+ { ignoreDetached: true }
1092
+ );
1093
+ }
1094
+ async #initialize() {
1095
+ const persistDataBuffer = await this.#actorDriver.readPersistedData(
1096
+ this.#actorId
1097
+ );
1098
+ _invariant2.default.call(void 0,
1099
+ persistDataBuffer !== void 0,
1100
+ "persist data has not been set, it should be set when initialized"
1101
+ );
1102
+ const bareData = _chunkNTCUGYSDcjs.PERSISTED_ACTOR_VERSIONED.deserializeWithEmbeddedVersion(
1103
+ persistDataBuffer
1104
+ );
1105
+ const persistData = this.#convertFromBarePersisted(bareData);
1106
+ if (persistData.hasInitiated) {
1107
+ this.#rLog.info({
1108
+ msg: "actor restoring",
1109
+ connections: persistData.connections.length
1110
+ });
1111
+ this.#setPersist(persistData);
1112
+ for (const connPersist of this.#persist.connections) {
1113
+ const driver = this.__getConnDriver(connPersist.connDriver);
1114
+ const conn = new Conn(
1115
+ this,
1116
+ connPersist,
1117
+ driver,
1118
+ this.#connStateEnabled
1119
+ );
1120
+ this.#connections.set(conn.id, conn);
1121
+ for (const sub of connPersist.subscriptions) {
1122
+ this.#addSubscription(sub.eventName, conn, true);
1123
+ }
1124
+ }
1125
+ } else {
1126
+ this.#rLog.info({ msg: "actor creating" });
1127
+ let stateData;
1128
+ if (this.stateEnabled) {
1129
+ this.#rLog.info({ msg: "actor state initializing" });
1130
+ if ("createState" in this.#config) {
1131
+ this.#config.createState;
1132
+ stateData = await this.#config.createState(
1133
+ this.actorContext,
1134
+ persistData.input
1135
+ );
1136
+ } else if ("state" in this.#config) {
1137
+ stateData = structuredClone(this.#config.state);
1138
+ } else {
1139
+ throw new Error("Both 'createState' or 'state' were not defined");
1140
+ }
1141
+ } else {
1142
+ this.#rLog.debug({ msg: "state not enabled" });
1143
+ }
1144
+ persistData.state = stateData;
1145
+ persistData.hasInitiated = true;
1146
+ this.#rLog.debug({ msg: "writing state" });
1147
+ const bareData2 = this.#convertToBarePersisted(persistData);
1148
+ await this.#actorDriver.writePersistedData(
1149
+ this.#actorId,
1150
+ _chunkNTCUGYSDcjs.PERSISTED_ACTOR_VERSIONED.serializeWithEmbeddedVersion(bareData2)
1151
+ );
1152
+ this.#setPersist(persistData);
1153
+ if (this.#config.onCreate) {
1154
+ await this.#config.onCreate(this.actorContext, persistData.input);
1155
+ }
1156
+ }
1157
+ }
1158
+ __getConnForId(id) {
1159
+ return this.#connections.get(id);
1160
+ }
1161
+ /**
1162
+ * Removes a connection and cleans up its resources.
1163
+ */
1164
+ __removeConn(conn) {
1165
+ if (!conn) {
1166
+ this.#rLog.warn({ msg: "`conn` does not exist" });
1167
+ return;
1168
+ }
1169
+ const connIdx = this.#persist.connections.findIndex(
1170
+ (c) => c.connId === conn.id
1171
+ );
1172
+ if (connIdx !== -1) {
1173
+ this.#persist.connections.splice(connIdx, 1);
1174
+ this.saveState({ immediate: true, allowStoppingState: true });
1175
+ } else {
1176
+ this.#rLog.warn({
1177
+ msg: "could not find persisted connection to remove",
1178
+ connId: conn.id
1179
+ });
1180
+ }
1181
+ this.#connections.delete(conn.id);
1182
+ for (const eventName of [...conn.subscriptions.values()]) {
1183
+ this.#removeSubscription(eventName, conn, true);
1184
+ }
1185
+ this.inspector.emitter.emit("connectionUpdated");
1186
+ if (this.#config.onDisconnect) {
1187
+ try {
1188
+ const result = this.#config.onDisconnect(this.actorContext, conn);
1189
+ if (result instanceof Promise) {
1190
+ result.catch((error) => {
1191
+ this.#rLog.error({
1192
+ msg: "error in `onDisconnect`",
1193
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1194
+ });
1195
+ });
1196
+ }
1197
+ } catch (error) {
1198
+ this.#rLog.error({
1199
+ msg: "error in `onDisconnect`",
1200
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1201
+ });
1202
+ }
1203
+ }
1204
+ this.#resetSleepTimer();
1205
+ }
1206
+ async prepareConn(params, request) {
1207
+ let connState;
1208
+ const onBeforeConnectOpts = {
1209
+ request
1210
+ };
1211
+ if (this.#config.onBeforeConnect) {
1212
+ await this.#config.onBeforeConnect(
1213
+ this.actorContext,
1214
+ onBeforeConnectOpts,
1215
+ params
1216
+ );
1217
+ }
1218
+ if (this.#connStateEnabled) {
1219
+ if ("createConnState" in this.#config) {
1220
+ const dataOrPromise = this.#config.createConnState(
1221
+ this.actorContext,
1222
+ onBeforeConnectOpts,
1223
+ params
1224
+ );
1225
+ if (dataOrPromise instanceof Promise) {
1226
+ connState = await _chunkTCUI5JFEcjs.deadline.call(void 0,
1227
+ dataOrPromise,
1228
+ this.#config.options.createConnStateTimeout
1229
+ );
1230
+ } else {
1231
+ connState = dataOrPromise;
1232
+ }
1233
+ } else if ("connState" in this.#config) {
1234
+ connState = structuredClone(this.#config.connState);
1235
+ } else {
1236
+ throw new Error(
1237
+ "Could not create connection state from 'createConnState' or 'connState'"
1238
+ );
1239
+ }
1240
+ }
1241
+ return connState;
1242
+ }
1243
+ __getConnDriver(driverId) {
1244
+ const driver = this.#connectionDrivers[driverId];
1245
+ if (!driver) throw new Error(`No connection driver: ${driverId}`);
1246
+ return driver;
1247
+ }
1248
+ /**
1249
+ * Called after establishing a connection handshake.
1250
+ */
1251
+ async createConn(connectionId, connectionToken, params, state, driverId, driverState, authData) {
1252
+ this.#assertReady();
1253
+ if (this.#connections.has(connectionId)) {
1254
+ throw new Error(`Connection already exists: ${connectionId}`);
1255
+ }
1256
+ const driver = this.__getConnDriver(driverId);
1257
+ const persist = {
1258
+ connId: connectionId,
1259
+ token: connectionToken,
1260
+ connDriver: driverId,
1261
+ connDriverState: driverState,
1262
+ params,
1263
+ state,
1264
+ authData,
1265
+ lastSeen: Date.now(),
1266
+ subscriptions: []
1267
+ };
1268
+ const conn = new Conn(
1269
+ this,
1270
+ persist,
1271
+ driver,
1272
+ this.#connStateEnabled
1273
+ );
1274
+ this.#connections.set(conn.id, conn);
1275
+ this.#resetSleepTimer();
1276
+ this.#persist.connections.push(persist);
1277
+ this.saveState({ immediate: true });
1278
+ if (this.#config.onConnect) {
1279
+ try {
1280
+ const result = this.#config.onConnect(this.actorContext, conn);
1281
+ if (result instanceof Promise) {
1282
+ _chunkTCUI5JFEcjs.deadline.call(void 0, result, this.#config.options.onConnectTimeout).catch(
1283
+ (error) => {
1284
+ this.#rLog.error({
1285
+ msg: "error in `onConnect`, closing socket",
1286
+ error
1287
+ });
1288
+ conn == null ? void 0 : conn.disconnect("`onConnect` failed");
1289
+ }
1290
+ );
1291
+ }
1292
+ } catch (error) {
1293
+ this.#rLog.error({
1294
+ msg: "error in `onConnect`",
1295
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1296
+ });
1297
+ conn == null ? void 0 : conn.disconnect("`onConnect` failed");
1298
+ }
1299
+ }
1300
+ this.inspector.emitter.emit("connectionUpdated");
1301
+ conn._sendMessage(
1302
+ new (0, _chunkTCUI5JFEcjs.CachedSerializer)(
1303
+ {
1304
+ body: {
1305
+ tag: "Init",
1306
+ val: {
1307
+ actorId: this.id,
1308
+ connectionId: conn.id,
1309
+ connectionToken: conn._token
1310
+ }
1311
+ }
1312
+ },
1313
+ _chunkNTCUGYSDcjs.TO_CLIENT_VERSIONED
1314
+ )
1315
+ );
1316
+ return conn;
1317
+ }
1318
+ // MARK: Messages
1319
+ async processMessage(message, conn) {
1320
+ await _chunkNTCUGYSDcjs.processMessage.call(void 0, message, this, conn, {
1321
+ onExecuteAction: async (ctx, name, args) => {
1322
+ this.inspector.emitter.emit("eventFired", {
1323
+ type: "action",
1324
+ name,
1325
+ args,
1326
+ connId: conn.id
1327
+ });
1328
+ return await this.executeAction(ctx, name, args);
1329
+ },
1330
+ onSubscribe: async (eventName, conn2) => {
1331
+ this.inspector.emitter.emit("eventFired", {
1332
+ type: "subscribe",
1333
+ eventName,
1334
+ connId: conn2.id
1335
+ });
1336
+ this.#addSubscription(eventName, conn2, false);
1337
+ },
1338
+ onUnsubscribe: async (eventName, conn2) => {
1339
+ this.inspector.emitter.emit("eventFired", {
1340
+ type: "unsubscribe",
1341
+ eventName,
1342
+ connId: conn2.id
1343
+ });
1344
+ this.#removeSubscription(eventName, conn2, false);
1345
+ }
1346
+ });
1347
+ }
1348
+ // MARK: Events
1349
+ #addSubscription(eventName, connection, fromPersist) {
1350
+ if (connection.subscriptions.has(eventName)) {
1351
+ this.#rLog.debug({
1352
+ msg: "connection already has subscription",
1353
+ eventName
1354
+ });
1355
+ return;
1356
+ }
1357
+ if (!fromPersist) {
1358
+ connection.__persist.subscriptions.push({ eventName });
1359
+ this.saveState({ immediate: true });
1360
+ }
1361
+ connection.subscriptions.add(eventName);
1362
+ let subscribers = this.#subscriptionIndex.get(eventName);
1363
+ if (!subscribers) {
1364
+ subscribers = /* @__PURE__ */ new Set();
1365
+ this.#subscriptionIndex.set(eventName, subscribers);
1366
+ }
1367
+ subscribers.add(connection);
1368
+ }
1369
+ #removeSubscription(eventName, connection, fromRemoveConn) {
1370
+ if (!connection.subscriptions.has(eventName)) {
1371
+ this.#rLog.warn({
1372
+ msg: "connection does not have subscription",
1373
+ eventName
1374
+ });
1375
+ return;
1376
+ }
1377
+ if (!fromRemoveConn) {
1378
+ connection.subscriptions.delete(eventName);
1379
+ const subIdx = connection.__persist.subscriptions.findIndex(
1380
+ (s) => s.eventName === eventName
1381
+ );
1382
+ if (subIdx !== -1) {
1383
+ connection.__persist.subscriptions.splice(subIdx, 1);
1384
+ } else {
1385
+ this.#rLog.warn({
1386
+ msg: "subscription does not exist with name",
1387
+ eventName
1388
+ });
1389
+ }
1390
+ this.saveState({ immediate: true });
1391
+ }
1392
+ const subscribers = this.#subscriptionIndex.get(eventName);
1393
+ if (subscribers) {
1394
+ subscribers.delete(connection);
1395
+ if (subscribers.size === 0) {
1396
+ this.#subscriptionIndex.delete(eventName);
1397
+ }
1398
+ }
1399
+ }
1400
+ #assertReady(allowStoppingState = false) {
1401
+ if (!this.#ready) throw new (0, _chunk5QGQK44Lcjs.InternalError)("Actor not ready");
1402
+ if (!allowStoppingState && this.#sleepCalled)
1403
+ throw new (0, _chunk5QGQK44Lcjs.InternalError)("Actor is going to sleep");
1404
+ if (!allowStoppingState && this.#stopCalled)
1405
+ throw new (0, _chunk5QGQK44Lcjs.InternalError)("Actor is stopping");
1406
+ }
1407
+ /**
1408
+ * Check the liveness of all connections.
1409
+ * Sets up a recurring check based on the configured interval.
1410
+ */
1411
+ #checkConnectionsLiveness() {
1412
+ this.#rLog.debug({ msg: "checking connections liveness" });
1413
+ for (const conn of this.#connections.values()) {
1414
+ const liveness = conn[CONNECTION_CHECK_LIVENESS_SYMBOL]();
1415
+ if (liveness.status === "connected") {
1416
+ this.#rLog.debug({ msg: "connection is alive", connId: conn.id });
1417
+ } else {
1418
+ const lastSeen = liveness.lastSeen;
1419
+ const sinceLastSeen = Date.now() - lastSeen;
1420
+ if (sinceLastSeen < this.#config.options.connectionLivenessTimeout) {
1421
+ this.#rLog.debug({
1422
+ msg: "connection might be alive, will check later",
1423
+ connId: conn.id,
1424
+ lastSeen,
1425
+ sinceLastSeen
1426
+ });
1427
+ continue;
1428
+ }
1429
+ this.#rLog.warn({
1430
+ msg: "connection is dead, removing",
1431
+ connId: conn.id,
1432
+ lastSeen
1433
+ });
1434
+ this.__removeConn(conn);
1435
+ }
1436
+ }
1437
+ }
1438
+ /**
1439
+ * Check if the actor is ready to handle requests.
1440
+ */
1441
+ isReady() {
1442
+ return this.#ready;
1443
+ }
1444
+ /**
1445
+ * Execute an action call from a client.
1446
+ *
1447
+ * This method handles:
1448
+ * 1. Validating the action name
1449
+ * 2. Executing the action function
1450
+ * 3. Processing the result through onBeforeActionResponse (if configured)
1451
+ * 4. Handling timeouts and errors
1452
+ * 5. Saving state changes
1453
+ *
1454
+ * @param ctx The action context
1455
+ * @param actionName The name of the action being called
1456
+ * @param args The arguments passed to the action
1457
+ * @returns The result of the action call
1458
+ * @throws {ActionNotFound} If the action doesn't exist
1459
+ * @throws {ActionTimedOut} If the action times out
1460
+ * @internal
1461
+ */
1462
+ async executeAction(ctx, actionName, args) {
1463
+ _invariant2.default.call(void 0, this.#ready, "executing action before ready");
1464
+ if (!(actionName in this.#config.actions)) {
1465
+ this.#rLog.warn({ msg: "action does not exist", actionName });
1466
+ throw new (0, _chunk5QGQK44Lcjs.ActionNotFound)(actionName);
1467
+ }
1468
+ const actionFunction = this.#config.actions[actionName];
1469
+ if (typeof actionFunction !== "function") {
1470
+ this.#rLog.warn({
1471
+ msg: "action is not a function",
1472
+ actionName,
1473
+ type: typeof actionFunction
1474
+ });
1475
+ throw new (0, _chunk5QGQK44Lcjs.ActionNotFound)(actionName);
1476
+ }
1477
+ try {
1478
+ this.#rLog.debug({
1479
+ msg: "executing action",
1480
+ actionName,
1481
+ args
1482
+ });
1483
+ const outputOrPromise = actionFunction.call(void 0, ctx, ...args);
1484
+ let output;
1485
+ if (outputOrPromise instanceof Promise) {
1486
+ this.#rLog.debug({
1487
+ msg: "awaiting async action",
1488
+ actionName
1489
+ });
1490
+ output = await _chunkTCUI5JFEcjs.deadline.call(void 0,
1491
+ outputOrPromise,
1492
+ this.#config.options.actionTimeout
1493
+ );
1494
+ this.#rLog.debug({
1495
+ msg: "async action completed",
1496
+ actionName
1497
+ });
1498
+ } else {
1499
+ output = outputOrPromise;
1500
+ }
1501
+ if (this.#config.onBeforeActionResponse) {
1502
+ try {
1503
+ const processedOutput = this.#config.onBeforeActionResponse(
1504
+ this.actorContext,
1505
+ actionName,
1506
+ args,
1507
+ output
1508
+ );
1509
+ if (processedOutput instanceof Promise) {
1510
+ this.#rLog.debug({
1511
+ msg: "awaiting onBeforeActionResponse",
1512
+ actionName
1513
+ });
1514
+ output = await processedOutput;
1515
+ this.#rLog.debug({
1516
+ msg: "onBeforeActionResponse completed",
1517
+ actionName
1518
+ });
1519
+ } else {
1520
+ output = processedOutput;
1521
+ }
1522
+ } catch (error) {
1523
+ this.#rLog.error({
1524
+ msg: "error in `onBeforeActionResponse`",
1525
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1526
+ });
1527
+ }
1528
+ }
1529
+ this.#rLog.debug({
1530
+ msg: "action completed",
1531
+ actionName,
1532
+ outputType: typeof output,
1533
+ isPromise: output instanceof Promise
1534
+ });
1535
+ return output;
1536
+ } catch (error) {
1537
+ if (error instanceof _chunkTCUI5JFEcjs.DeadlineError) {
1538
+ throw new (0, _chunk5QGQK44Lcjs.ActionTimedOut)();
1539
+ }
1540
+ this.#rLog.error({
1541
+ msg: "action error",
1542
+ actionName,
1543
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1544
+ });
1545
+ throw error;
1546
+ } finally {
1547
+ this.#savePersistThrottled();
1548
+ }
1549
+ }
1550
+ /**
1551
+ * Returns a list of action methods available on this actor.
1552
+ */
1553
+ get actions() {
1554
+ return Object.keys(this.#config.actions);
1555
+ }
1556
+ /**
1557
+ * Handles raw HTTP requests to the actor.
1558
+ */
1559
+ async handleFetch(request, opts) {
1560
+ this.#assertReady();
1561
+ if (!this.#config.onFetch) {
1562
+ throw new (0, _chunk5QGQK44Lcjs.FetchHandlerNotDefined)();
1563
+ }
1564
+ this.#activeRawFetchCount++;
1565
+ this.#resetSleepTimer();
1566
+ try {
1567
+ const response = await this.#config.onFetch(
1568
+ this.actorContext,
1569
+ request,
1570
+ opts
1571
+ );
1572
+ if (!response) {
1573
+ throw new (0, _chunk5QGQK44Lcjs.InvalidFetchResponse)();
1574
+ }
1575
+ return response;
1576
+ } catch (error) {
1577
+ this.#rLog.error({ msg: "onFetch error", error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error) });
1578
+ throw error;
1579
+ } finally {
1580
+ this.#activeRawFetchCount = Math.max(0, this.#activeRawFetchCount - 1);
1581
+ this.#resetSleepTimer();
1582
+ this.#savePersistThrottled();
1583
+ }
1584
+ }
1585
+ /**
1586
+ * Handles raw WebSocket connections to the actor.
1587
+ */
1588
+ async handleWebSocket(websocket, opts) {
1589
+ this.#assertReady();
1590
+ if (!this.#config.onWebSocket) {
1591
+ throw new (0, _chunk5QGQK44Lcjs.InternalError)("onWebSocket handler not defined");
1592
+ }
1593
+ try {
1594
+ const stateBeforeHandler = this.#persistChanged;
1595
+ this.#activeRawWebSockets.add(websocket);
1596
+ this.#resetSleepTimer();
1597
+ const onSocketClosed = () => {
1598
+ try {
1599
+ websocket.removeEventListener("close", onSocketClosed);
1600
+ websocket.removeEventListener("error", onSocketClosed);
1601
+ } catch (e) {
1602
+ }
1603
+ this.#activeRawWebSockets.delete(websocket);
1604
+ this.#resetSleepTimer();
1605
+ };
1606
+ try {
1607
+ websocket.addEventListener("close", onSocketClosed);
1608
+ websocket.addEventListener("error", onSocketClosed);
1609
+ } catch (e2) {
1610
+ }
1611
+ await this.#config.onWebSocket(this.actorContext, websocket, opts);
1612
+ if (this.#persistChanged && !stateBeforeHandler) {
1613
+ await this.saveState({ immediate: true });
1614
+ }
1615
+ } catch (error) {
1616
+ this.#rLog.error({
1617
+ msg: "onWebSocket error",
1618
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1619
+ });
1620
+ throw error;
1621
+ } finally {
1622
+ this.#savePersistThrottled();
1623
+ }
1624
+ }
1625
+ // MARK: Lifecycle hooks
1626
+ // MARK: Exposed methods
1627
+ get log() {
1628
+ _invariant2.default.call(void 0, this.#log, "log not configured");
1629
+ return this.#log;
1630
+ }
1631
+ get rLog() {
1632
+ _invariant2.default.call(void 0, this.#rLog, "log not configured");
1633
+ return this.#rLog;
1634
+ }
1635
+ /**
1636
+ * Gets the name.
1637
+ */
1638
+ get name() {
1639
+ return this.#name;
1640
+ }
1641
+ /**
1642
+ * Gets the key.
1643
+ */
1644
+ get key() {
1645
+ return this.#key;
1646
+ }
1647
+ /**
1648
+ * Gets the region.
1649
+ */
1650
+ get region() {
1651
+ return this.#region;
1652
+ }
1653
+ /**
1654
+ * Gets the scheduler.
1655
+ */
1656
+ get schedule() {
1657
+ return this.#schedule;
1658
+ }
1659
+ /**
1660
+ * Gets the map of connections.
1661
+ */
1662
+ get conns() {
1663
+ return this.#connections;
1664
+ }
1665
+ /**
1666
+ * Gets the current state.
1667
+ *
1668
+ * Changing properties of this value will automatically be persisted.
1669
+ */
1670
+ get state() {
1671
+ this.#validateStateEnabled();
1672
+ return this.#persist.state;
1673
+ }
1674
+ /**
1675
+ * Gets the database.
1676
+ * @experimental
1677
+ * @throws {DatabaseNotEnabled} If the database is not enabled.
1678
+ */
1679
+ get db() {
1680
+ if (!this.#db) {
1681
+ throw new (0, _chunk5QGQK44Lcjs.DatabaseNotEnabled)();
1682
+ }
1683
+ return this.#db;
1684
+ }
1685
+ /**
1686
+ * Sets the current state.
1687
+ *
1688
+ * This property will automatically be persisted.
1689
+ */
1690
+ set state(value) {
1691
+ this.#validateStateEnabled();
1692
+ this.#persist.state = value;
1693
+ }
1694
+ get vars() {
1695
+ this.#validateVarsEnabled();
1696
+ _invariant2.default.call(void 0, this.#vars !== void 0, "vars not enabled");
1697
+ return this.#vars;
1698
+ }
1699
+ /**
1700
+ * Broadcasts an event to all connected clients.
1701
+ * @param name - The name of the event.
1702
+ * @param args - The arguments to send with the event.
1703
+ */
1704
+ _broadcast(name, ...args) {
1705
+ this.#assertReady();
1706
+ this.inspector.emitter.emit("eventFired", {
1707
+ type: "broadcast",
1708
+ eventName: name,
1709
+ args
1710
+ });
1711
+ const subscriptions = this.#subscriptionIndex.get(name);
1712
+ if (!subscriptions) return;
1713
+ const toClientSerializer = new (0, _chunkTCUI5JFEcjs.CachedSerializer)(
1714
+ {
1715
+ body: {
1716
+ tag: "Event",
1717
+ val: {
1718
+ name,
1719
+ args: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor2.encode(args))
1720
+ }
1721
+ }
1722
+ },
1723
+ _chunkNTCUGYSDcjs.TO_CLIENT_VERSIONED
1724
+ );
1725
+ for (const connection of subscriptions) {
1726
+ connection._sendMessage(toClientSerializer);
1727
+ }
1728
+ }
1729
+ /**
1730
+ * Prevents the actor from sleeping until promise is complete.
1731
+ *
1732
+ * This allows the actor runtime to ensure that a promise completes while
1733
+ * returning from an action request early.
1734
+ *
1735
+ * @param promise - The promise to run in the background.
1736
+ */
1737
+ _waitUntil(promise) {
1738
+ this.#assertReady();
1739
+ const nonfailablePromise = promise.then(() => {
1740
+ this.#rLog.debug({ msg: "wait until promise complete" });
1741
+ }).catch((error) => {
1742
+ this.#rLog.error({
1743
+ msg: "wait until promise failed",
1744
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1745
+ });
1746
+ });
1747
+ this.#backgroundPromises.push(nonfailablePromise);
1748
+ }
1749
+ /**
1750
+ * Forces the state to get saved.
1751
+ *
1752
+ * This is helpful if running a long task that may fail later or when
1753
+ * running a background job that updates the state.
1754
+ *
1755
+ * @param opts - Options for saving the state.
1756
+ */
1757
+ async saveState(opts) {
1758
+ this.#assertReady(opts.allowStoppingState);
1759
+ if (this.#persistChanged) {
1760
+ if (opts.immediate) {
1761
+ await this.#savePersistInner();
1762
+ } else {
1763
+ if (!this.#onPersistSavedPromise) {
1764
+ this.#onPersistSavedPromise = Promise.withResolvers();
1765
+ }
1766
+ this.#savePersistThrottled();
1767
+ await this.#onPersistSavedPromise.promise;
1768
+ }
1769
+ }
1770
+ }
1771
+ // MARK: Sleep
1772
+ /**
1773
+ * Reset timer from the last actor interaction that allows it to be put to sleep.
1774
+ *
1775
+ * This should be called any time a sleep-related event happens:
1776
+ * - Connection opens (will clear timer)
1777
+ * - Connection closes (will schedule timer if there are no open connections)
1778
+ * - Alarm triggers (will reset timer)
1779
+ *
1780
+ * We don't need to call this on events like individual action calls, since there will always be a connection open for these.
1781
+ **/
1782
+ #resetSleepTimer() {
1783
+ if (this.#config.options.noSleep || !this.#sleepingSupported) return;
1784
+ const canSleep = this.#canSleep();
1785
+ this.#rLog.debug({
1786
+ msg: "resetting sleep timer",
1787
+ canSleep,
1788
+ existingTimeout: !!this.#sleepTimeout
1789
+ });
1790
+ if (this.#sleepTimeout) {
1791
+ clearTimeout(this.#sleepTimeout);
1792
+ this.#sleepTimeout = void 0;
1793
+ }
1794
+ if (this.#sleepCalled) return;
1795
+ if (canSleep) {
1796
+ this.#sleepTimeout = setTimeout(() => {
1797
+ this._sleep().catch((error) => {
1798
+ this.#rLog.error({
1799
+ msg: "error during sleep",
1800
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1801
+ });
1802
+ });
1803
+ }, this.#config.options.sleepTimeout);
1804
+ }
1805
+ }
1806
+ /** If this actor can be put in a sleeping state. */
1807
+ #canSleep() {
1808
+ if (!this.#ready) return false;
1809
+ for (const conn of this.#connections.values()) {
1810
+ if (conn.status === "connected") return false;
1811
+ }
1812
+ if (this.#activeRawFetchCount > 0) return false;
1813
+ if (this.#activeRawWebSockets.size > 0) return false;
1814
+ return true;
1815
+ }
1816
+ /** Puts an actor to sleep. This should just start the sleep sequence, most shutdown logic should be in _stop (which is called by the ActorDriver when sleeping). */
1817
+ async _sleep() {
1818
+ var _a;
1819
+ const sleep = (_a = this.#actorDriver.sleep) == null ? void 0 : _a.bind(
1820
+ this.#actorDriver,
1821
+ this.#actorId
1822
+ );
1823
+ _invariant2.default.call(void 0, this.#sleepingSupported, "sleeping not supported");
1824
+ _invariant2.default.call(void 0, sleep, "no sleep on driver");
1825
+ if (this.#sleepCalled) {
1826
+ this.#rLog.warn({ msg: "already sleeping actor" });
1827
+ return;
1828
+ }
1829
+ this.#sleepCalled = true;
1830
+ this.#rLog.info({ msg: "actor sleeping" });
1831
+ setImmediate(async () => {
1832
+ await sleep();
1833
+ });
1834
+ }
1835
+ // MARK: Stop
1836
+ async _stop() {
1837
+ if (this.#stopCalled) {
1838
+ this.#rLog.warn({ msg: "already stopping actor" });
1839
+ return;
1840
+ }
1841
+ this.#stopCalled = true;
1842
+ this.#rLog.info({ msg: "actor stopping" });
1843
+ try {
1844
+ this.#abortController.abort();
1845
+ } catch (e3) {
1846
+ }
1847
+ if (this.#config.onStop) {
1848
+ try {
1849
+ this.#rLog.debug({ msg: "calling onStop" });
1850
+ const result = this.#config.onStop(this.actorContext);
1851
+ if (result instanceof Promise) {
1852
+ await _chunkTCUI5JFEcjs.deadline.call(void 0, result, this.#config.options.onStopTimeout);
1853
+ }
1854
+ this.#rLog.debug({ msg: "onStop completed" });
1855
+ } catch (error) {
1856
+ if (error instanceof _chunkTCUI5JFEcjs.DeadlineError) {
1857
+ this.#rLog.error({ msg: "onStop timed out" });
1858
+ } else {
1859
+ this.#rLog.error({
1860
+ msg: "error in onStop",
1861
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
1862
+ });
1863
+ }
1864
+ }
1865
+ }
1866
+ const promises = [];
1867
+ for (const connection of this.#connections.values()) {
1868
+ promises.push(connection.disconnect());
1869
+ }
1870
+ await this.#waitBackgroundPromises(this.#config.options.waitUntilTimeout);
1871
+ if (this.#pendingSaveTimeout) clearTimeout(this.#pendingSaveTimeout);
1872
+ if (this.#sleepTimeout) clearTimeout(this.#sleepTimeout);
1873
+ if (this.#checkConnLivenessInterval)
1874
+ clearInterval(this.#checkConnLivenessInterval);
1875
+ await this.saveState({ immediate: true, allowStoppingState: true });
1876
+ const res = Promise.race([
1877
+ Promise.all(promises).then(() => false),
1878
+ new Promise(
1879
+ (res2) => globalThis.setTimeout(() => res2(true), 1500)
1880
+ )
1881
+ ]);
1882
+ if (await res) {
1883
+ this.#rLog.warn({
1884
+ msg: "timed out waiting for connections to close, shutting down anyway"
1885
+ });
1886
+ }
1887
+ if (this.#persistWriteQueue.runningDrainLoop)
1888
+ await this.#persistWriteQueue.runningDrainLoop;
1889
+ if (this.#alarmWriteQueue.runningDrainLoop)
1890
+ await this.#alarmWriteQueue.runningDrainLoop;
1891
+ }
1892
+ /** Abort signal that fires when the actor is stopping. */
1893
+ get abortSignal() {
1894
+ return this.#abortController.signal;
1895
+ }
1896
+ /** Wait for background waitUntil promises with a timeout. */
1897
+ async #waitBackgroundPromises(timeoutMs) {
1898
+ const pending = this.#backgroundPromises;
1899
+ if (pending.length === 0) {
1900
+ this.#rLog.debug({ msg: "no background promises" });
1901
+ return;
1902
+ }
1903
+ const timedOut = await Promise.race([
1904
+ Promise.allSettled(pending).then(() => false),
1905
+ new Promise(
1906
+ (resolve) => setTimeout(() => resolve(true), timeoutMs)
1907
+ )
1908
+ ]);
1909
+ if (timedOut) {
1910
+ this.#rLog.error({
1911
+ msg: "timed out waiting for background tasks, background promises may have leaked",
1912
+ count: pending.length,
1913
+ timeoutMs
1914
+ });
1915
+ } else {
1916
+ this.#rLog.debug({ msg: "background promises finished" });
1917
+ }
1918
+ }
1919
+ // MARK: BARE Conversion Helpers
1920
+ #convertToBarePersisted(persist) {
1921
+ return {
1922
+ input: persist.input !== void 0 ? _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor2.encode(persist.input)) : null,
1923
+ hasInitialized: persist.hasInitiated,
1924
+ state: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor2.encode(persist.state)),
1925
+ connections: persist.connections.map((conn) => ({
1926
+ id: conn.connId,
1927
+ token: conn.token,
1928
+ driver: conn.connDriver,
1929
+ driverState: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0,
1930
+ cbor2.encode(conn.connDriverState || {})
1931
+ ),
1932
+ parameters: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor2.encode(conn.params || {})),
1933
+ state: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor2.encode(conn.state || {})),
1934
+ subscriptions: conn.subscriptions.map((sub) => ({
1935
+ eventName: sub.eventName
1936
+ })),
1937
+ lastSeen: BigInt(conn.lastSeen)
1938
+ })),
1939
+ scheduledEvents: persist.scheduledEvents.map((event) => ({
1940
+ eventId: event.eventId,
1941
+ timestamp: BigInt(event.timestamp),
1942
+ kind: {
1943
+ tag: "GenericPersistedScheduleEvent",
1944
+ val: {
1945
+ action: event.kind.generic.actionName,
1946
+ args: _nullishCoalesce(event.kind.generic.args, () => ( null))
1947
+ }
1948
+ }
1949
+ }))
1950
+ };
1951
+ }
1952
+ #convertFromBarePersisted(bareData) {
1953
+ return {
1954
+ input: bareData.input ? cbor2.decode(new Uint8Array(bareData.input)) : void 0,
1955
+ hasInitiated: bareData.hasInitialized,
1956
+ state: cbor2.decode(new Uint8Array(bareData.state)),
1957
+ connections: bareData.connections.map((conn) => ({
1958
+ connId: conn.id,
1959
+ token: conn.token,
1960
+ connDriver: conn.driver,
1961
+ connDriverState: cbor2.decode(new Uint8Array(conn.driverState)),
1962
+ params: cbor2.decode(new Uint8Array(conn.parameters)),
1963
+ state: cbor2.decode(new Uint8Array(conn.state)),
1964
+ subscriptions: conn.subscriptions.map((sub) => ({
1965
+ eventName: sub.eventName
1966
+ })),
1967
+ lastSeen: Number(conn.lastSeen)
1968
+ })),
1969
+ scheduledEvents: bareData.scheduledEvents.map((event) => ({
1970
+ eventId: event.eventId,
1971
+ timestamp: Number(event.timestamp),
1972
+ kind: {
1973
+ generic: {
1974
+ actionName: event.kind.val.action,
1975
+ args: event.kind.val.args
1976
+ }
1977
+ }
1978
+ }))
1979
+ };
1980
+ }
1981
+ };
1982
+
1983
+ // src/actor/definition.ts
1984
+ var ActorDefinition = class {
1985
+ #config;
1986
+ constructor(config) {
1987
+ this.#config = config;
1988
+ }
1989
+ get config() {
1990
+ return this.#config;
1991
+ }
1992
+ instantiate() {
1993
+ return new ActorInstance(this.#config);
1994
+ }
1995
+ };
1996
+ function lookupInRegistry(registryConfig, name) {
1997
+ const definition = registryConfig.use[name];
1998
+ if (!definition) throw new Error(`no actor in registry for name ${name}`);
1999
+ return definition;
2000
+ }
2001
+
2002
+ // src/client/errors.ts
2003
+ var ActorClientError = class extends Error {
2004
+ };
2005
+ var InternalError2 = class extends ActorClientError {
2006
+ };
2007
+ var ManagerError = class extends ActorClientError {
2008
+ constructor(error, opts) {
2009
+ super(`Manager error: ${error}`, opts);
2010
+ }
2011
+ };
2012
+ var MalformedResponseMessage = class extends ActorClientError {
2013
+ constructor(cause) {
2014
+ super(`Malformed response message: ${cause}`, { cause });
2015
+ }
2016
+ };
2017
+ var ActorError = (_class3 = class extends ActorClientError {
2018
+ constructor(group, code, message, metadata) {
2019
+ super(message);_class3.prototype.__init3.call(this);;
2020
+ this.group = group;
2021
+ this.code = code;
2022
+ this.metadata = metadata;
2023
+ }
2024
+ __init3() {this.__type = "ActorError"}
2025
+ }, _class3);
2026
+ var HttpRequestError = class extends ActorClientError {
2027
+ constructor(message, opts) {
2028
+ super(`HTTP request error: ${message}`, { cause: opts == null ? void 0 : opts.cause });
2029
+ }
2030
+ };
2031
+ var ActorConnDisposed = class extends ActorClientError {
2032
+ constructor() {
2033
+ super("Attempting to interact with a disposed actor connection.");
2034
+ }
2035
+ };
2036
+
2037
+ // src/client/actor-conn.ts
2038
+
2039
+
2040
+ var _pretry = require('p-retry'); var _pretry2 = _interopRequireDefault(_pretry);
2041
+
2042
+ // src/common/eventsource.ts
2043
+ var eventSourcePromise = null;
2044
+ async function importEventSource() {
2045
+ if (eventSourcePromise !== null) {
2046
+ return eventSourcePromise;
2047
+ }
2048
+ eventSourcePromise = (async () => {
2049
+ let _EventSource;
2050
+ try {
2051
+ const es = await Promise.resolve().then(() => _interopRequireWildcard(require("eventsource")));
2052
+ _EventSource = es.EventSource;
2053
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug("using eventsource from npm");
2054
+ } catch (err) {
2055
+ _EventSource = class MockEventSource {
2056
+ constructor() {
2057
+ throw new Error(
2058
+ 'EventSource support requires installing the "eventsource" peer dependency.'
2059
+ );
2060
+ }
2061
+ };
2062
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug("using mock eventsource");
2063
+ }
2064
+ return _EventSource;
2065
+ })();
2066
+ return eventSourcePromise;
2067
+ }
2068
+
2069
+ // src/client/actor-query.ts
2070
+ async function queryActor(c, query, managerDriver) {
2071
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "querying actor", query: JSON.stringify(query) });
2072
+ let actorOutput;
2073
+ if ("getForId" in query) {
2074
+ const output = await managerDriver.getForId({
2075
+ c,
2076
+ name: query.getForId.name,
2077
+ actorId: query.getForId.actorId
2078
+ });
2079
+ if (!output) throw new (0, _chunk5QGQK44Lcjs.ActorNotFound)(query.getForId.actorId);
2080
+ actorOutput = output;
2081
+ } else if ("getForKey" in query) {
2082
+ const existingActor = await managerDriver.getWithKey({
2083
+ c,
2084
+ name: query.getForKey.name,
2085
+ key: query.getForKey.key
2086
+ });
2087
+ if (!existingActor) {
2088
+ throw new (0, _chunk5QGQK44Lcjs.ActorNotFound)(
2089
+ `${query.getForKey.name}:${JSON.stringify(query.getForKey.key)}`
2090
+ );
2091
+ }
2092
+ actorOutput = existingActor;
2093
+ } else if ("getOrCreateForKey" in query) {
2094
+ const getOrCreateOutput = await managerDriver.getOrCreateWithKey({
2095
+ c,
2096
+ name: query.getOrCreateForKey.name,
2097
+ key: query.getOrCreateForKey.key,
2098
+ input: query.getOrCreateForKey.input,
2099
+ region: query.getOrCreateForKey.region
2100
+ });
2101
+ actorOutput = {
2102
+ actorId: getOrCreateOutput.actorId
2103
+ };
2104
+ } else if ("create" in query) {
2105
+ const createOutput = await managerDriver.createActor({
2106
+ c,
2107
+ name: query.create.name,
2108
+ key: query.create.key,
2109
+ input: query.create.input,
2110
+ region: query.create.region
2111
+ });
2112
+ actorOutput = {
2113
+ actorId: createOutput.actorId
2114
+ };
2115
+ } else {
2116
+ throw new (0, _chunk5QGQK44Lcjs.InvalidRequest)("Invalid query format");
2117
+ }
2118
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "actor query result", actorId: actorOutput.actorId });
2119
+ return { actorId: actorOutput.actorId };
2120
+ }
2121
+
2122
+ // src/client/actor-handle.ts
2123
+
2124
+
2125
+
2126
+ // src/client/raw-utils.ts
2127
+
2128
+ async function rawHttpFetch(driver, actorQuery, params, input, init) {
2129
+ let path;
2130
+ let mergedInit = init || {};
2131
+ if (typeof input === "string") {
2132
+ path = input;
2133
+ } else if (input instanceof URL) {
2134
+ path = input.pathname + input.search;
2135
+ } else if (input instanceof Request) {
2136
+ const url = new URL(input.url);
2137
+ path = url.pathname + url.search;
2138
+ const requestHeaders = new Headers(input.headers);
2139
+ const initHeaders = new Headers((init == null ? void 0 : init.headers) || {});
2140
+ const mergedHeaders = new Headers(requestHeaders);
2141
+ for (const [key, value] of initHeaders) {
2142
+ mergedHeaders.set(key, value);
2143
+ }
2144
+ mergedInit = {
2145
+ method: input.method,
2146
+ body: input.body,
2147
+ mode: input.mode,
2148
+ credentials: input.credentials,
2149
+ redirect: input.redirect,
2150
+ referrer: input.referrer,
2151
+ referrerPolicy: input.referrerPolicy,
2152
+ integrity: input.integrity,
2153
+ keepalive: input.keepalive,
2154
+ signal: input.signal,
2155
+ ...mergedInit,
2156
+ // init overrides Request properties
2157
+ headers: mergedHeaders
2158
+ // headers must be set after spread to ensure proper merge
2159
+ };
2160
+ if (mergedInit.body) {
2161
+ mergedInit.duplex = "half";
2162
+ }
2163
+ } else {
2164
+ throw new TypeError("Invalid input type for fetch");
2165
+ }
2166
+ try {
2167
+ const { actorId } = await queryActor(void 0, actorQuery, driver);
2168
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "found actor for raw http", actorId });
2169
+ _invariant2.default.call(void 0, actorId, "Missing actor ID");
2170
+ const normalizedPath = path.startsWith("/") ? path.slice(1) : path;
2171
+ const url = new URL(`http://actor/raw/http/${normalizedPath}`);
2172
+ const proxyRequestHeaders = new Headers(mergedInit.headers);
2173
+ if (params) {
2174
+ proxyRequestHeaders.set(_chunkTCUI5JFEcjs.HEADER_CONN_PARAMS, JSON.stringify(params));
2175
+ }
2176
+ const proxyRequest = new Request(url, {
2177
+ ...mergedInit,
2178
+ headers: proxyRequestHeaders
2179
+ });
2180
+ return driver.sendRequest(actorId, proxyRequest);
2181
+ } catch (err) {
2182
+ const { group, code, message, metadata } = _chunk5JBFVV4Ccjs.deconstructError.call(void 0,
2183
+ err,
2184
+ _chunkKG3C7MKRcjs.logger.call(void 0, ),
2185
+ {},
2186
+ true
2187
+ );
2188
+ throw new ActorError(group, code, message, metadata);
2189
+ }
2190
+ }
2191
+ async function rawWebSocket(driver, actorQuery, params, path, protocols) {
2192
+ const encoding = "bare";
2193
+ const { actorId } = await queryActor(void 0, actorQuery, driver);
2194
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "found actor for action", actorId });
2195
+ _invariant2.default.call(void 0, actorId, "Missing actor ID");
2196
+ let pathPortion = "";
2197
+ let queryPortion = "";
2198
+ if (path) {
2199
+ const queryIndex = path.indexOf("?");
2200
+ if (queryIndex !== -1) {
2201
+ pathPortion = path.substring(0, queryIndex);
2202
+ queryPortion = path.substring(queryIndex);
2203
+ } else {
2204
+ pathPortion = path;
2205
+ }
2206
+ if (pathPortion.startsWith("/")) {
2207
+ pathPortion = pathPortion.slice(1);
2208
+ }
2209
+ }
2210
+ const fullPath = `${_chunkTCUI5JFEcjs.PATH_RAW_WEBSOCKET_PREFIX}${pathPortion}${queryPortion}`;
2211
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2212
+ msg: "opening websocket",
2213
+ actorId,
2214
+ encoding,
2215
+ path: fullPath
2216
+ });
2217
+ const ws = await driver.openWebSocket(fullPath, actorId, encoding, params);
2218
+ return ws;
2219
+ }
2220
+
2221
+ // src/client/utils.ts
2222
+
2223
+
2224
+ function messageLength(message) {
2225
+ if (message instanceof Blob) {
2226
+ return message.size;
2227
+ }
2228
+ if (message instanceof ArrayBuffer) {
2229
+ return message.byteLength;
2230
+ }
2231
+ if (message instanceof Uint8Array) {
2232
+ return message.byteLength;
2233
+ }
2234
+ if (typeof message === "string") {
2235
+ return message.length;
2236
+ }
2237
+ _chunk5JBFVV4Ccjs.assertUnreachable.call(void 0, message);
2238
+ }
2239
+ async function sendHttpRequest(opts) {
2240
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2241
+ msg: "sending http request",
2242
+ url: opts.url,
2243
+ encoding: opts.encoding
2244
+ });
2245
+ let contentType;
2246
+ let bodyData;
2247
+ if (opts.method === "POST" || opts.method === "PUT") {
2248
+ _invariant2.default.call(void 0, opts.body !== void 0, "missing body");
2249
+ contentType = _chunkTCUI5JFEcjs.contentTypeForEncoding.call(void 0, opts.encoding);
2250
+ bodyData = _chunkTCUI5JFEcjs.serializeWithEncoding.call(void 0,
2251
+ opts.encoding,
2252
+ opts.body,
2253
+ opts.requestVersionedDataHandler
2254
+ );
2255
+ }
2256
+ let response;
2257
+ try {
2258
+ response = await (_nullishCoalesce(opts.customFetch, () => ( fetch)))(
2259
+ new Request(opts.url, {
2260
+ method: opts.method,
2261
+ headers: {
2262
+ ...opts.headers,
2263
+ ...contentType ? {
2264
+ "Content-Type": contentType
2265
+ } : {},
2266
+ "User-Agent": _chunk5JBFVV4Ccjs.httpUserAgent.call(void 0, )
2267
+ },
2268
+ body: bodyData,
2269
+ credentials: "include",
2270
+ signal: opts.signal
2271
+ })
2272
+ );
2273
+ } catch (error) {
2274
+ throw new HttpRequestError(`Request failed: ${error}`, {
2275
+ cause: error
2276
+ });
2277
+ }
2278
+ if (!response.ok) {
2279
+ const bufferResponse = await response.arrayBuffer();
2280
+ let responseData;
2281
+ try {
2282
+ responseData = _chunkTCUI5JFEcjs.deserializeWithEncoding.call(void 0,
2283
+ opts.encoding,
2284
+ new Uint8Array(bufferResponse),
2285
+ _chunkNTCUGYSDcjs.HTTP_RESPONSE_ERROR_VERSIONED
2286
+ );
2287
+ } catch (error) {
2288
+ const textResponse = new TextDecoder("utf-8", { fatal: false }).decode(
2289
+ bufferResponse
2290
+ );
2291
+ throw new HttpRequestError(
2292
+ `${response.statusText} (${response.status}):
2293
+ ${textResponse}`
2294
+ );
2295
+ }
2296
+ throw new ActorError(
2297
+ responseData.group,
2298
+ responseData.code,
2299
+ responseData.message,
2300
+ responseData.metadata ? cbor3.decode(new Uint8Array(responseData.metadata)) : void 0
2301
+ );
2302
+ }
2303
+ if (opts.skipParseResponse) {
2304
+ return void 0;
2305
+ }
2306
+ try {
2307
+ const buffer = new Uint8Array(await response.arrayBuffer());
2308
+ return _chunkTCUI5JFEcjs.deserializeWithEncoding.call(void 0,
2309
+ opts.encoding,
2310
+ buffer,
2311
+ opts.responseVersionedDataHandler
2312
+ );
2313
+ } catch (error) {
2314
+ throw new HttpRequestError(`Failed to parse response: ${error}`, {
2315
+ cause: error
2316
+ });
2317
+ }
2318
+ }
2319
+
2320
+ // src/client/actor-handle.ts
2321
+ var ActorHandleRaw = class {
2322
+ #client;
2323
+ #driver;
2324
+ #encoding;
2325
+ #actorQuery;
2326
+ #params;
2327
+ /**
2328
+ * Do not call this directly.
2329
+ *
2330
+ * Creates an instance of ActorHandleRaw.
2331
+ *
2332
+ * @protected
2333
+ */
2334
+ constructor(client, driver, params, encoding, actorQuery) {
2335
+ this.#client = client;
2336
+ this.#driver = driver;
2337
+ this.#encoding = encoding;
2338
+ this.#actorQuery = actorQuery;
2339
+ this.#params = params;
2340
+ }
2341
+ /**
2342
+ * Call a raw action. This method sends an HTTP request to invoke the named action.
2343
+ *
2344
+ * @see {@link ActorHandle}
2345
+ * @template Args - The type of arguments to pass to the action function.
2346
+ * @template Response - The type of the response returned by the action function.
2347
+ */
2348
+ async action(opts) {
2349
+ try {
2350
+ const { actorId } = await queryActor(
2351
+ void 0,
2352
+ this.#actorQuery,
2353
+ this.#driver
2354
+ );
2355
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "found actor for action", actorId });
2356
+ _invariant2.default.call(void 0, actorId, "Missing actor ID");
2357
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2358
+ msg: "handling action",
2359
+ name: opts.name,
2360
+ encoding: this.#encoding
2361
+ });
2362
+ const responseData = await sendHttpRequest({
2363
+ url: `http://actor/action/${encodeURIComponent(opts.name)}`,
2364
+ method: "POST",
2365
+ headers: {
2366
+ [_chunkTCUI5JFEcjs.HEADER_ENCODING]: this.#encoding,
2367
+ ...this.#params !== void 0 ? { [_chunkTCUI5JFEcjs.HEADER_CONN_PARAMS]: JSON.stringify(this.#params) } : {}
2368
+ },
2369
+ body: {
2370
+ args: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor4.encode(opts.args))
2371
+ },
2372
+ encoding: this.#encoding,
2373
+ customFetch: this.#driver.sendRequest.bind(this.#driver, actorId),
2374
+ signal: opts == null ? void 0 : opts.signal,
2375
+ requestVersionedDataHandler: _chunkNTCUGYSDcjs.HTTP_ACTION_REQUEST_VERSIONED,
2376
+ responseVersionedDataHandler: _chunkNTCUGYSDcjs.HTTP_ACTION_RESPONSE_VERSIONED
2377
+ });
2378
+ return cbor4.decode(new Uint8Array(responseData.output));
2379
+ } catch (err) {
2380
+ const { group, code, message, metadata } = _chunk5JBFVV4Ccjs.deconstructError.call(void 0,
2381
+ err,
2382
+ _chunkKG3C7MKRcjs.logger.call(void 0, ),
2383
+ {},
2384
+ true
2385
+ );
2386
+ throw new ActorError(group, code, message, metadata);
2387
+ }
2388
+ }
2389
+ /**
2390
+ * Establishes a persistent connection to the actor.
2391
+ *
2392
+ * @template AD The actor class that this connection is for.
2393
+ * @returns {ActorConn<AD>} A connection to the actor.
2394
+ */
2395
+ connect() {
2396
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2397
+ msg: "establishing connection from handle",
2398
+ query: this.#actorQuery
2399
+ });
2400
+ const conn = new ActorConnRaw(
2401
+ this.#client,
2402
+ this.#driver,
2403
+ this.#params,
2404
+ this.#encoding,
2405
+ this.#actorQuery
2406
+ );
2407
+ return this.#client[CREATE_ACTOR_CONN_PROXY](
2408
+ conn
2409
+ );
2410
+ }
2411
+ /**
2412
+ * Makes a raw HTTP request to the actor.
2413
+ *
2414
+ * @param input - The URL, path, or Request object
2415
+ * @param init - Standard fetch RequestInit options
2416
+ * @returns Promise<Response> - The raw HTTP response
2417
+ */
2418
+ async fetch(input, init) {
2419
+ return rawHttpFetch(
2420
+ this.#driver,
2421
+ this.#actorQuery,
2422
+ this.#params,
2423
+ input,
2424
+ init
2425
+ );
2426
+ }
2427
+ /**
2428
+ * Creates a raw WebSocket connection to the actor.
2429
+ *
2430
+ * @param path - The path for the WebSocket connection (e.g., "stream")
2431
+ * @param protocols - Optional WebSocket subprotocols
2432
+ * @returns WebSocket - A raw WebSocket connection
2433
+ */
2434
+ async websocket(path, protocols) {
2435
+ return rawWebSocket(
2436
+ this.#driver,
2437
+ this.#actorQuery,
2438
+ this.#params,
2439
+ path,
2440
+ protocols
2441
+ );
2442
+ }
2443
+ /**
2444
+ * Resolves the actor to get its unique actor ID
2445
+ *
2446
+ * @returns {Promise<string>} - A promise that resolves to the actor's ID
2447
+ */
2448
+ async resolve({ signal } = {}) {
2449
+ if ("getForKey" in this.#actorQuery || "getOrCreateForKey" in this.#actorQuery) {
2450
+ let name;
2451
+ if ("getForKey" in this.#actorQuery) {
2452
+ name = this.#actorQuery.getForKey.name;
2453
+ } else if ("getOrCreateForKey" in this.#actorQuery) {
2454
+ name = this.#actorQuery.getOrCreateForKey.name;
2455
+ } else {
2456
+ _chunkTCUI5JFEcjs.assertUnreachable.call(void 0, this.#actorQuery);
2457
+ }
2458
+ const { actorId } = await queryActor(
2459
+ void 0,
2460
+ this.#actorQuery,
2461
+ this.#driver
2462
+ );
2463
+ this.#actorQuery = { getForId: { actorId, name } };
2464
+ return actorId;
2465
+ } else if ("getForId" in this.#actorQuery) {
2466
+ return this.#actorQuery.getForId.actorId;
2467
+ } else if ("create" in this.#actorQuery) {
2468
+ _invariant2.default.call(void 0, false, "actorQuery cannot be create");
2469
+ } else {
2470
+ _chunkTCUI5JFEcjs.assertUnreachable.call(void 0, this.#actorQuery);
2471
+ }
2472
+ }
2473
+ };
2474
+
2475
+ // src/client/client.ts
2476
+ var ACTOR_CONNS_SYMBOL = Symbol("actorConns");
2477
+ var CREATE_ACTOR_CONN_PROXY = Symbol("createActorConnProxy");
2478
+ var TRANSPORT_SYMBOL = Symbol("transport");
2479
+ var ClientRaw = (_class4 = class {
2480
+ #disposed = false;
2481
+ __init4() {this[ACTOR_CONNS_SYMBOL] = /* @__PURE__ */ new Set()}
2482
+ #driver;
2483
+ #encodingKind;
2484
+
2485
+ /**
2486
+ * Creates an instance of Client.
2487
+ *
2488
+ * @param {string} managerEndpoint - The manager endpoint. See {@link https://rivet.dev/docs/setup|Initial Setup} for instructions on getting the manager endpoint.
2489
+ * @param {ClientConfig} [opts] - Options for configuring the client.
2490
+ * @see {@link https://rivet.dev/docs/setup|Initial Setup}
2491
+ */
2492
+ constructor(driver, opts) {;_class4.prototype.__init4.call(this);
2493
+ this.#driver = driver;
2494
+ this.#encodingKind = _nullishCoalesce((opts == null ? void 0 : opts.encoding), () => ( "bare"));
2495
+ this[TRANSPORT_SYMBOL] = _nullishCoalesce((opts == null ? void 0 : opts.transport), () => ( "websocket"));
2496
+ }
2497
+ /**
2498
+ * Gets a stateless handle to a actor by its ID.
2499
+ *
2500
+ * @template AD The actor class that this handle is for.
2501
+ * @param {string} name - The name of the actor.
2502
+ * @param {string} actorId - The ID of the actor.
2503
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
2504
+ * @returns {ActorHandle<AD>} - A handle to the actor.
2505
+ */
2506
+ getForId(name, actorId, opts) {
2507
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2508
+ msg: "get handle to actor with id",
2509
+ name,
2510
+ actorId,
2511
+ params: opts == null ? void 0 : opts.params
2512
+ });
2513
+ const actorQuery = {
2514
+ getForId: {
2515
+ name,
2516
+ actorId
2517
+ }
2518
+ };
2519
+ const handle = this.#createHandle(opts == null ? void 0 : opts.params, actorQuery);
2520
+ return createActorProxy(handle);
2521
+ }
2522
+ /**
2523
+ * Gets a stateless handle to a actor by its key, but does not create the actor if it doesn't exist.
2524
+ *
2525
+ * @template AD The actor class that this handle is for.
2526
+ * @param {string} name - The name of the actor.
2527
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
2528
+ * @param {GetWithIdOptions} [opts] - Options for getting the actor.
2529
+ * @returns {ActorHandle<AD>} - A handle to the actor.
2530
+ */
2531
+ get(name, key, opts) {
2532
+ const keyArray = typeof key === "string" ? [key] : key || [];
2533
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2534
+ msg: "get handle to actor",
2535
+ name,
2536
+ key: keyArray,
2537
+ parameters: opts == null ? void 0 : opts.params
2538
+ });
2539
+ const actorQuery = {
2540
+ getForKey: {
2541
+ name,
2542
+ key: keyArray
2543
+ }
2544
+ };
2545
+ const handle = this.#createHandle(opts == null ? void 0 : opts.params, actorQuery);
2546
+ return createActorProxy(handle);
2547
+ }
2548
+ /**
2549
+ * Gets a stateless handle to a actor by its key, creating it if necessary.
2550
+ *
2551
+ * @template AD The actor class that this handle is for.
2552
+ * @param {string} name - The name of the actor.
2553
+ * @param {string | string[]} [key=[]] - The key to identify the actor. Can be a single string or an array of strings.
2554
+ * @param {GetOptions} [opts] - Options for getting the actor.
2555
+ * @returns {ActorHandle<AD>} - A handle to the actor.
2556
+ */
2557
+ getOrCreate(name, key, opts) {
2558
+ const keyArray = typeof key === "string" ? [key] : key || [];
2559
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2560
+ msg: "get or create handle to actor",
2561
+ name,
2562
+ key: keyArray,
2563
+ parameters: opts == null ? void 0 : opts.params,
2564
+ createInRegion: opts == null ? void 0 : opts.createInRegion
2565
+ });
2566
+ const actorQuery = {
2567
+ getOrCreateForKey: {
2568
+ name,
2569
+ key: keyArray,
2570
+ input: opts == null ? void 0 : opts.createWithInput,
2571
+ region: opts == null ? void 0 : opts.createInRegion
2572
+ }
2573
+ };
2574
+ const handle = this.#createHandle(opts == null ? void 0 : opts.params, actorQuery);
2575
+ return createActorProxy(handle);
2576
+ }
2577
+ /**
2578
+ * Creates a new actor with the provided key and returns a stateless handle to it.
2579
+ * Resolves the actor ID and returns a handle with getForId query.
2580
+ *
2581
+ * @template AD The actor class that this handle is for.
2582
+ * @param {string} name - The name of the actor.
2583
+ * @param {string | string[]} key - The key to identify the actor. Can be a single string or an array of strings.
2584
+ * @param {CreateOptions} [opts] - Options for creating the actor (excluding name and key).
2585
+ * @returns {Promise<ActorHandle<AD>>} - A promise that resolves to a handle to the actor.
2586
+ */
2587
+ async create(name, key, opts) {
2588
+ const keyArray = typeof key === "string" ? [key] : key || [];
2589
+ const createQuery = {
2590
+ create: {
2591
+ ...opts,
2592
+ // Do these last to override `opts`
2593
+ name,
2594
+ key: keyArray
2595
+ }
2596
+ };
2597
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2598
+ msg: "create actor handle",
2599
+ name,
2600
+ key: keyArray,
2601
+ parameters: opts == null ? void 0 : opts.params,
2602
+ create: createQuery.create
2603
+ });
2604
+ const { actorId } = await queryActor(void 0, createQuery, this.#driver);
2605
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2606
+ msg: "created actor with ID",
2607
+ name,
2608
+ key: keyArray,
2609
+ actorId
2610
+ });
2611
+ const getForIdQuery = {
2612
+ getForId: {
2613
+ name,
2614
+ actorId
2615
+ }
2616
+ };
2617
+ const handle = this.#createHandle(opts == null ? void 0 : opts.params, getForIdQuery);
2618
+ const proxy = createActorProxy(handle);
2619
+ return proxy;
2620
+ }
2621
+ #createHandle(params, actorQuery) {
2622
+ return new ActorHandleRaw(
2623
+ this,
2624
+ this.#driver,
2625
+ params,
2626
+ this.#encodingKind,
2627
+ actorQuery
2628
+ );
2629
+ }
2630
+ [CREATE_ACTOR_CONN_PROXY](conn) {
2631
+ this[ACTOR_CONNS_SYMBOL].add(conn);
2632
+ conn[CONNECT_SYMBOL]();
2633
+ return createActorProxy(conn);
2634
+ }
2635
+ /**
2636
+ * Disconnects from all actors.
2637
+ *
2638
+ * @returns {Promise<void>} A promise that resolves when all connections are closed.
2639
+ */
2640
+ async dispose() {
2641
+ if (this.#disposed) {
2642
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({ msg: "client already disconnected" });
2643
+ return;
2644
+ }
2645
+ this.#disposed = true;
2646
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "disposing client" });
2647
+ const disposePromises = [];
2648
+ for (const conn of this[ACTOR_CONNS_SYMBOL].values()) {
2649
+ disposePromises.push(conn.dispose());
2650
+ }
2651
+ await Promise.all(disposePromises);
2652
+ }
2653
+ }, _class4);
2654
+ function createClientWithDriver(driver, config) {
2655
+ const client = new ClientRaw(driver, config);
2656
+ return new Proxy(client, {
2657
+ get: (target, prop, receiver) => {
2658
+ if (typeof prop === "symbol" || prop in target) {
2659
+ const value = Reflect.get(target, prop, receiver);
2660
+ if (typeof value === "function") {
2661
+ return value.bind(target);
2662
+ }
2663
+ return value;
2664
+ }
2665
+ if (typeof prop === "string") {
2666
+ return {
2667
+ // Handle methods (stateless action)
2668
+ get: (key, opts) => {
2669
+ return target.get(
2670
+ prop,
2671
+ key,
2672
+ opts
2673
+ );
2674
+ },
2675
+ getOrCreate: (key, opts) => {
2676
+ return target.getOrCreate(prop, key, opts);
2677
+ },
2678
+ getForId: (actorId, opts) => {
2679
+ return target.getForId(
2680
+ prop,
2681
+ actorId,
2682
+ opts
2683
+ );
2684
+ },
2685
+ create: async (key, opts = {}) => {
2686
+ return await target.create(prop, key, opts);
2687
+ }
2688
+ };
2689
+ }
2690
+ return void 0;
2691
+ }
2692
+ });
2693
+ }
2694
+ function createActorProxy(handle) {
2695
+ const methodCache = /* @__PURE__ */ new Map();
2696
+ return new Proxy(handle, {
2697
+ get(target, prop, receiver) {
2698
+ if (typeof prop === "symbol") {
2699
+ return Reflect.get(target, prop, receiver);
2700
+ }
2701
+ if (prop === "constructor" || prop in target) {
2702
+ const value = Reflect.get(target, prop, receiver);
2703
+ if (typeof value === "function") {
2704
+ return value.bind(target);
2705
+ }
2706
+ return value;
2707
+ }
2708
+ if (typeof prop === "string") {
2709
+ if (prop === "then") return void 0;
2710
+ let method = methodCache.get(prop);
2711
+ if (!method) {
2712
+ method = (...args) => target.action({ name: prop, args });
2713
+ methodCache.set(prop, method);
2714
+ }
2715
+ return method;
2716
+ }
2717
+ },
2718
+ // Support for 'in' operator
2719
+ has(target, prop) {
2720
+ if (typeof prop === "string") {
2721
+ return true;
2722
+ }
2723
+ return Reflect.has(target, prop);
2724
+ },
2725
+ // Support instanceof checks
2726
+ getPrototypeOf(target) {
2727
+ return Reflect.getPrototypeOf(target);
2728
+ },
2729
+ // Prevent property enumeration of non-existent action methods
2730
+ ownKeys(target) {
2731
+ return Reflect.ownKeys(target);
2732
+ },
2733
+ // Support proper property descriptors
2734
+ getOwnPropertyDescriptor(target, prop) {
2735
+ const targetDescriptor = Reflect.getOwnPropertyDescriptor(target, prop);
2736
+ if (targetDescriptor) {
2737
+ return targetDescriptor;
2738
+ }
2739
+ if (typeof prop === "string") {
2740
+ return {
2741
+ configurable: true,
2742
+ enumerable: false,
2743
+ writable: false,
2744
+ value: (...args) => target.action({ name: prop, args })
2745
+ };
2746
+ }
2747
+ return void 0;
2748
+ }
2749
+ });
2750
+ }
2751
+
2752
+ // src/client/actor-conn.ts
2753
+ var CONNECT_SYMBOL = Symbol("connect");
2754
+ var ActorConnRaw = class {
2755
+ #disposed = false;
2756
+ /* Will be aborted on dispose. */
2757
+ #abortController = new AbortController();
2758
+ /** If attempting to connect. Helpful for knowing if in a retry loop when reconnecting. */
2759
+ #connecting = false;
2760
+ // These will only be set on SSE driver
2761
+ #actorId;
2762
+ #connectionId;
2763
+ #connectionToken;
2764
+ #transport;
2765
+ #messageQueue = [];
2766
+ #actionsInFlight = /* @__PURE__ */ new Map();
2767
+ // biome-ignore lint/suspicious/noExplicitAny: Unknown subscription type
2768
+ #eventSubscriptions = /* @__PURE__ */ new Map();
2769
+ #errorHandlers = /* @__PURE__ */ new Set();
2770
+ #actionIdCounter = 0;
2771
+ /**
2772
+ * Interval that keeps the NodeJS process alive if this is the only thing running.
2773
+ *
2774
+ * See ttps://github.com/nodejs/node/issues/22088
2775
+ */
2776
+ #keepNodeAliveInterval;
2777
+ /** Promise used to indicate the socket has connected successfully. This will be rejected if the connection fails. */
2778
+ #onOpenPromise;
2779
+ #client;
2780
+ #driver;
2781
+ #params;
2782
+ #encoding;
2783
+ #actorQuery;
2784
+ // TODO: ws message queue
2785
+ /**
2786
+ * Do not call this directly.
2787
+ *
2788
+ * Creates an instance of ActorConnRaw.
2789
+ *
2790
+ * @protected
2791
+ */
2792
+ constructor(client, driver, params, encoding, actorQuery) {
2793
+ this.#client = client;
2794
+ this.#driver = driver;
2795
+ this.#params = params;
2796
+ this.#encoding = encoding;
2797
+ this.#actorQuery = actorQuery;
2798
+ this.#keepNodeAliveInterval = setInterval(() => 6e4);
2799
+ }
2800
+ /**
2801
+ * Call a raw action connection. See {@link ActorConn} for type-safe action calls.
2802
+ *
2803
+ * @see {@link ActorConn}
2804
+ * @template Args - The type of arguments to pass to the action function.
2805
+ * @template Response - The type of the response returned by the action function.
2806
+ * @param {string} name - The name of the action function to call.
2807
+ * @param {...Args} args - The arguments to pass to the action function.
2808
+ * @returns {Promise<Response>} - A promise that resolves to the response of the action function.
2809
+ */
2810
+ async action(opts) {
2811
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "action", name: opts.name, args: opts.args });
2812
+ const actionId = this.#actionIdCounter;
2813
+ this.#actionIdCounter += 1;
2814
+ const { promise, resolve, reject } = Promise.withResolvers();
2815
+ this.#actionsInFlight.set(actionId, { name: opts.name, resolve, reject });
2816
+ this.#sendMessage({
2817
+ body: {
2818
+ tag: "ActionRequest",
2819
+ val: {
2820
+ id: BigInt(actionId),
2821
+ name: opts.name,
2822
+ args: _chunk5JBFVV4Ccjs.bufferToArrayBuffer.call(void 0, cbor5.encode(opts.args))
2823
+ }
2824
+ }
2825
+ });
2826
+ const { id: responseId, output } = await promise;
2827
+ if (responseId !== BigInt(actionId))
2828
+ throw new Error(
2829
+ `Request ID ${actionId} does not match response ID ${responseId}`
2830
+ );
2831
+ return cbor5.decode(new Uint8Array(output));
2832
+ }
2833
+ /**
2834
+ * Do not call this directly.
2835
+ enc
2836
+ * Establishes a connection to the server using the specified endpoint & encoding & driver.
2837
+ *
2838
+ * @protected
2839
+ */
2840
+ [CONNECT_SYMBOL]() {
2841
+ this.#connectWithRetry();
2842
+ }
2843
+ async #connectWithRetry() {
2844
+ this.#connecting = true;
2845
+ try {
2846
+ await _pretry2.default.call(void 0, this.#connectAndWait.bind(this), {
2847
+ forever: true,
2848
+ minTimeout: 250,
2849
+ maxTimeout: 3e4,
2850
+ onFailedAttempt: (error) => {
2851
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({
2852
+ msg: "failed to reconnect",
2853
+ attempt: error.attemptNumber,
2854
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
2855
+ });
2856
+ },
2857
+ // Cancel retry if aborted
2858
+ signal: this.#abortController.signal
2859
+ });
2860
+ } catch (err) {
2861
+ if (err.name === "AbortError") {
2862
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).info({ msg: "connection retry aborted" });
2863
+ return;
2864
+ } else {
2865
+ throw err;
2866
+ }
2867
+ }
2868
+ this.#connecting = false;
2869
+ }
2870
+ async #connectAndWait() {
2871
+ try {
2872
+ if (this.#onOpenPromise)
2873
+ throw new Error("#onOpenPromise already defined");
2874
+ this.#onOpenPromise = Promise.withResolvers();
2875
+ if (this.#client[TRANSPORT_SYMBOL] === "websocket") {
2876
+ await this.#connectWebSocket();
2877
+ } else if (this.#client[TRANSPORT_SYMBOL] === "sse") {
2878
+ await this.#connectSse();
2879
+ } else {
2880
+ _chunk5JBFVV4Ccjs.assertUnreachable.call(void 0, this.#client[TRANSPORT_SYMBOL]);
2881
+ }
2882
+ await this.#onOpenPromise.promise;
2883
+ } finally {
2884
+ this.#onOpenPromise = void 0;
2885
+ }
2886
+ }
2887
+ async #connectWebSocket() {
2888
+ const { actorId } = await queryActor(
2889
+ void 0,
2890
+ this.#actorQuery,
2891
+ this.#driver
2892
+ );
2893
+ const ws = await this.#driver.openWebSocket(
2894
+ _chunkTCUI5JFEcjs.PATH_CONNECT_WEBSOCKET,
2895
+ actorId,
2896
+ this.#encoding,
2897
+ this.#params
2898
+ );
2899
+ this.#transport = { websocket: ws };
2900
+ ws.addEventListener("open", () => {
2901
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "websocket open" });
2902
+ });
2903
+ ws.addEventListener("message", async (ev) => {
2904
+ this.#handleOnMessage(ev.data);
2905
+ });
2906
+ ws.addEventListener("close", (ev) => {
2907
+ this.#handleOnClose(ev);
2908
+ });
2909
+ ws.addEventListener("error", (_ev) => {
2910
+ this.#handleOnError();
2911
+ });
2912
+ }
2913
+ async #connectSse() {
2914
+ const EventSource = await importEventSource();
2915
+ const { actorId } = await queryActor(
2916
+ void 0,
2917
+ this.#actorQuery,
2918
+ this.#driver
2919
+ );
2920
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "found actor for sse connection", actorId });
2921
+ _invariant2.default.call(void 0, actorId, "Missing actor ID");
2922
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2923
+ msg: "opening sse connection",
2924
+ actorId,
2925
+ encoding: this.#encoding
2926
+ });
2927
+ const eventSource = new EventSource("http://actor/connect/sse", {
2928
+ fetch: (input, init) => {
2929
+ return this.#driver.sendRequest(
2930
+ actorId,
2931
+ new Request(input, {
2932
+ ...init,
2933
+ headers: {
2934
+ ...init == null ? void 0 : init.headers,
2935
+ "User-Agent": _chunk5JBFVV4Ccjs.httpUserAgent.call(void 0, ),
2936
+ [_chunkTCUI5JFEcjs.HEADER_ENCODING]: this.#encoding,
2937
+ ...this.#params !== void 0 ? { [_chunkTCUI5JFEcjs.HEADER_CONN_PARAMS]: JSON.stringify(this.#params) } : {}
2938
+ }
2939
+ })
2940
+ );
2941
+ }
2942
+ });
2943
+ this.#transport = { sse: eventSource };
2944
+ eventSource.addEventListener("message", (ev) => {
2945
+ this.#handleOnMessage(ev.data);
2946
+ });
2947
+ eventSource.addEventListener("error", (ev) => {
2948
+ this.#handleOnError();
2949
+ });
2950
+ }
2951
+ /** Called by the onopen event from drivers. */
2952
+ #handleOnOpen() {
2953
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
2954
+ msg: "socket open",
2955
+ messageQueueLength: this.#messageQueue.length
2956
+ });
2957
+ if (this.#onOpenPromise) {
2958
+ this.#onOpenPromise.resolve(void 0);
2959
+ } else {
2960
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({ msg: "#onOpenPromise is undefined" });
2961
+ }
2962
+ for (const eventName of this.#eventSubscriptions.keys()) {
2963
+ this.#sendSubscription(eventName, true);
2964
+ }
2965
+ const queue = this.#messageQueue;
2966
+ this.#messageQueue = [];
2967
+ for (const msg of queue) {
2968
+ this.#sendMessage(msg);
2969
+ }
2970
+ }
2971
+ /** Called by the onmessage event from drivers. */
2972
+ async #handleOnMessage(data) {
2973
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace({
2974
+ msg: "received message",
2975
+ dataType: typeof data,
2976
+ isBlob: data instanceof Blob,
2977
+ isArrayBuffer: data instanceof ArrayBuffer
2978
+ });
2979
+ const response = await this.#parseMessage(data);
2980
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace(
2981
+ _chunk5JBFVV4Ccjs.getEnvUniversal.call(void 0, "_RIVETKIT_LOG_MESSAGE") ? {
2982
+ msg: "parsed message",
2983
+ message: _chunkTCUI5JFEcjs.jsonStringifyCompat.call(void 0, response).substring(0, 100) + "..."
2984
+ } : { msg: "parsed message" }
2985
+ );
2986
+ if (response.body.tag === "Init") {
2987
+ this.#actorId = response.body.val.actorId;
2988
+ this.#connectionId = response.body.val.connectionId;
2989
+ this.#connectionToken = response.body.val.connectionToken;
2990
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace({
2991
+ msg: "received init message",
2992
+ actorId: this.#actorId,
2993
+ connectionId: this.#connectionId
2994
+ });
2995
+ this.#handleOnOpen();
2996
+ } else if (response.body.tag === "Error") {
2997
+ const { group, code, message, metadata, actionId } = response.body.val;
2998
+ if (actionId) {
2999
+ const inFlight = this.#takeActionInFlight(Number(actionId));
3000
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({
3001
+ msg: "action error",
3002
+ actionId,
3003
+ actionName: inFlight == null ? void 0 : inFlight.name,
3004
+ group,
3005
+ code,
3006
+ message,
3007
+ metadata
3008
+ });
3009
+ inFlight.reject(new ActorError(group, code, message, metadata));
3010
+ } else {
3011
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({
3012
+ msg: "connection error",
3013
+ group,
3014
+ code,
3015
+ message,
3016
+ metadata
3017
+ });
3018
+ const actorError = new ActorError(
3019
+ group,
3020
+ code,
3021
+ message,
3022
+ metadata
3023
+ );
3024
+ if (this.#onOpenPromise) {
3025
+ this.#onOpenPromise.reject(actorError);
3026
+ }
3027
+ for (const [id, inFlight] of this.#actionsInFlight.entries()) {
3028
+ inFlight.reject(actorError);
3029
+ this.#actionsInFlight.delete(id);
3030
+ }
3031
+ this.#dispatchActorError(actorError);
3032
+ }
3033
+ } else if (response.body.tag === "ActionResponse") {
3034
+ const { id: actionId } = response.body.val;
3035
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace({
3036
+ msg: "received action response",
3037
+ actionId
3038
+ });
3039
+ const inFlight = this.#takeActionInFlight(Number(actionId));
3040
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace({
3041
+ msg: "resolving action promise",
3042
+ actionId,
3043
+ actionName: inFlight == null ? void 0 : inFlight.name
3044
+ });
3045
+ inFlight.resolve(response.body.val);
3046
+ } else if (response.body.tag === "Event") {
3047
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace({ msg: "received event", name: response.body.val.name });
3048
+ this.#dispatchEvent(response.body.val);
3049
+ } else {
3050
+ _chunk5JBFVV4Ccjs.assertUnreachable.call(void 0, response.body);
3051
+ }
3052
+ }
3053
+ /** Called by the onclose event from drivers. */
3054
+ #handleOnClose(event) {
3055
+ if (this.#onOpenPromise) {
3056
+ this.#onOpenPromise.reject(new Error("Closed"));
3057
+ }
3058
+ const closeEvent = event;
3059
+ if (closeEvent.wasClean) {
3060
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).info({
3061
+ msg: "socket closed",
3062
+ code: closeEvent.code,
3063
+ reason: closeEvent.reason,
3064
+ wasClean: closeEvent.wasClean
3065
+ });
3066
+ } else {
3067
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({
3068
+ msg: "socket closed",
3069
+ code: closeEvent.code,
3070
+ reason: closeEvent.reason,
3071
+ wasClean: closeEvent.wasClean
3072
+ });
3073
+ }
3074
+ this.#transport = void 0;
3075
+ if (!this.#disposed && !this.#connecting) {
3076
+ this.#connectWithRetry();
3077
+ }
3078
+ }
3079
+ /** Called by the onerror event from drivers. */
3080
+ #handleOnError() {
3081
+ if (this.#disposed) return;
3082
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn("socket error");
3083
+ }
3084
+ #takeActionInFlight(id) {
3085
+ const inFlight = this.#actionsInFlight.get(id);
3086
+ if (!inFlight) {
3087
+ throw new InternalError2(`No in flight response for ${id}`);
3088
+ }
3089
+ this.#actionsInFlight.delete(id);
3090
+ return inFlight;
3091
+ }
3092
+ #dispatchEvent(event) {
3093
+ const { name, args: argsRaw } = event;
3094
+ const args = cbor5.decode(new Uint8Array(argsRaw));
3095
+ const listeners = this.#eventSubscriptions.get(name);
3096
+ if (!listeners) return;
3097
+ for (const listener of [...listeners]) {
3098
+ listener.callback(...args);
3099
+ if (listener.once) {
3100
+ listeners.delete(listener);
3101
+ }
3102
+ }
3103
+ if (listeners.size === 0) {
3104
+ this.#eventSubscriptions.delete(name);
3105
+ }
3106
+ }
3107
+ #dispatchActorError(error) {
3108
+ for (const handler of [...this.#errorHandlers]) {
3109
+ try {
3110
+ handler(error);
3111
+ } catch (err) {
3112
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).error({
3113
+ msg: "error in connection error handler",
3114
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, err)
3115
+ });
3116
+ }
3117
+ }
3118
+ }
3119
+ #addEventSubscription(eventName, callback, once) {
3120
+ const listener = {
3121
+ callback,
3122
+ once
3123
+ };
3124
+ let subscriptionSet = this.#eventSubscriptions.get(eventName);
3125
+ if (subscriptionSet === void 0) {
3126
+ subscriptionSet = /* @__PURE__ */ new Set();
3127
+ this.#eventSubscriptions.set(eventName, subscriptionSet);
3128
+ this.#sendSubscription(eventName, true);
3129
+ }
3130
+ subscriptionSet.add(listener);
3131
+ return () => {
3132
+ const listeners = this.#eventSubscriptions.get(eventName);
3133
+ if (listeners) {
3134
+ listeners.delete(listener);
3135
+ if (listeners.size === 0) {
3136
+ this.#eventSubscriptions.delete(eventName);
3137
+ this.#sendSubscription(eventName, false);
3138
+ }
3139
+ }
3140
+ };
3141
+ }
3142
+ /**
3143
+ * Subscribes to an event that will happen repeatedly.
3144
+ *
3145
+ * @template Args - The type of arguments the event callback will receive.
3146
+ * @param {string} eventName - The name of the event to subscribe to.
3147
+ * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
3148
+ * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
3149
+ * @see {@link https://rivet.dev/docs/events|Events Documentation}
3150
+ */
3151
+ on(eventName, callback) {
3152
+ return this.#addEventSubscription(eventName, callback, false);
3153
+ }
3154
+ /**
3155
+ * Subscribes to an event that will be triggered only once.
3156
+ *
3157
+ * @template Args - The type of arguments the event callback will receive.
3158
+ * @param {string} eventName - The name of the event to subscribe to.
3159
+ * @param {(...args: Args) => void} callback - The callback function to execute when the event is triggered.
3160
+ * @returns {EventUnsubscribe} - A function to unsubscribe from the event.
3161
+ * @see {@link https://rivet.dev/docs/events|Events Documentation}
3162
+ */
3163
+ once(eventName, callback) {
3164
+ return this.#addEventSubscription(eventName, callback, true);
3165
+ }
3166
+ /**
3167
+ * Subscribes to connection errors.
3168
+ *
3169
+ * @param {ActorErrorCallback} callback - The callback function to execute when a connection error occurs.
3170
+ * @returns {() => void} - A function to unsubscribe from the error handler.
3171
+ */
3172
+ onError(callback) {
3173
+ this.#errorHandlers.add(callback);
3174
+ return () => {
3175
+ this.#errorHandlers.delete(callback);
3176
+ };
3177
+ }
3178
+ #sendMessage(message, opts) {
3179
+ if (this.#disposed) {
3180
+ throw new ActorConnDisposed();
3181
+ }
3182
+ let queueMessage = false;
3183
+ if (!this.#transport) {
3184
+ queueMessage = true;
3185
+ } else if ("websocket" in this.#transport) {
3186
+ if (this.#transport.websocket.readyState === 1) {
3187
+ try {
3188
+ const messageSerialized = _chunkTCUI5JFEcjs.serializeWithEncoding.call(void 0,
3189
+ this.#encoding,
3190
+ message,
3191
+ _chunkNTCUGYSDcjs.TO_SERVER_VERSIONED
3192
+ );
3193
+ this.#transport.websocket.send(messageSerialized);
3194
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace({
3195
+ msg: "sent websocket message",
3196
+ len: messageLength(messageSerialized)
3197
+ });
3198
+ } catch (error) {
3199
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({
3200
+ msg: "failed to send message, added to queue",
3201
+ error
3202
+ });
3203
+ queueMessage = true;
3204
+ }
3205
+ } else {
3206
+ queueMessage = true;
3207
+ }
3208
+ } else if ("sse" in this.#transport) {
3209
+ if (this.#transport.sse.readyState === 1) {
3210
+ this.#sendHttpMessage(message, opts);
3211
+ } else {
3212
+ queueMessage = true;
3213
+ }
3214
+ } else {
3215
+ _chunk5JBFVV4Ccjs.assertUnreachable.call(void 0, this.#transport);
3216
+ }
3217
+ if (!(opts == null ? void 0 : opts.ephemeral) && queueMessage) {
3218
+ this.#messageQueue.push(message);
3219
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "queued connection message" });
3220
+ }
3221
+ }
3222
+ async #sendHttpMessage(message, opts) {
3223
+ try {
3224
+ if (!this.#actorId || !this.#connectionId || !this.#connectionToken)
3225
+ throw new InternalError2("Missing connection ID or token.");
3226
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).trace(
3227
+ _chunk5JBFVV4Ccjs.getEnvUniversal.call(void 0, "_RIVETKIT_LOG_MESSAGE") ? {
3228
+ msg: "sent http message",
3229
+ message: `${_chunkTCUI5JFEcjs.jsonStringifyCompat.call(void 0, message).substring(0, 100)}...`
3230
+ } : { msg: "sent http message" }
3231
+ );
3232
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({
3233
+ msg: "sending http message",
3234
+ actorId: this.#actorId,
3235
+ connectionId: this.#connectionId
3236
+ });
3237
+ await sendHttpRequest({
3238
+ url: "http://actor/connections/message",
3239
+ method: "POST",
3240
+ headers: {
3241
+ [_chunkTCUI5JFEcjs.HEADER_ENCODING]: this.#encoding,
3242
+ [_chunkTCUI5JFEcjs.HEADER_CONN_ID]: this.#connectionId,
3243
+ [_chunkTCUI5JFEcjs.HEADER_CONN_TOKEN]: this.#connectionToken
3244
+ },
3245
+ body: message,
3246
+ encoding: this.#encoding,
3247
+ skipParseResponse: true,
3248
+ customFetch: this.#driver.sendRequest.bind(this.#driver, this.#actorId),
3249
+ requestVersionedDataHandler: _chunkNTCUGYSDcjs.TO_SERVER_VERSIONED,
3250
+ responseVersionedDataHandler: _chunkNTCUGYSDcjs.TO_CLIENT_VERSIONED
3251
+ });
3252
+ } catch (error) {
3253
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({ msg: "failed to send message, added to queue", error });
3254
+ if (!(opts == null ? void 0 : opts.ephemeral)) {
3255
+ this.#messageQueue.unshift(message);
3256
+ }
3257
+ }
3258
+ }
3259
+ async #parseMessage(data) {
3260
+ _invariant2.default.call(void 0, this.#transport, "transport must be defined");
3261
+ if (_chunkTCUI5JFEcjs.encodingIsBinary.call(void 0, this.#encoding) && "sse" in this.#transport) {
3262
+ if (typeof data === "string") {
3263
+ const binaryString = atob(data);
3264
+ data = new Uint8Array(
3265
+ [...binaryString].map((char) => char.charCodeAt(0))
3266
+ );
3267
+ } else {
3268
+ throw new InternalError2(
3269
+ `Expected data to be a string for SSE, got ${data}.`
3270
+ );
3271
+ }
3272
+ }
3273
+ const buffer = await _chunkNTCUGYSDcjs.inputDataToBuffer.call(void 0, data);
3274
+ return _chunkTCUI5JFEcjs.deserializeWithEncoding.call(void 0, this.#encoding, buffer, _chunkNTCUGYSDcjs.TO_CLIENT_VERSIONED);
3275
+ }
3276
+ /**
3277
+ * Disconnects from the actor.
3278
+ *
3279
+ * @returns {Promise<void>} A promise that resolves when the socket is gracefully closed.
3280
+ */
3281
+ async dispose() {
3282
+ if (this.#disposed) {
3283
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).warn({ msg: "connection already disconnected" });
3284
+ return;
3285
+ }
3286
+ this.#disposed = true;
3287
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "disposing actor conn" });
3288
+ clearInterval(this.#keepNodeAliveInterval);
3289
+ this.#abortController.abort();
3290
+ this.#client[ACTOR_CONNS_SYMBOL].delete(this);
3291
+ if (!this.#transport) {
3292
+ } else if ("websocket" in this.#transport) {
3293
+ const ws = this.#transport.websocket;
3294
+ if (ws.readyState === 2 || ws.readyState === 3) {
3295
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "ws already closed or closing" });
3296
+ } else {
3297
+ const { promise, resolve } = Promise.withResolvers();
3298
+ ws.addEventListener("close", () => {
3299
+ _chunkKG3C7MKRcjs.logger.call(void 0, ).debug({ msg: "ws closed" });
3300
+ resolve(void 0);
3301
+ });
3302
+ ws.close();
3303
+ await promise;
3304
+ }
3305
+ } else if ("sse" in this.#transport) {
3306
+ this.#transport.sse.close();
3307
+ } else {
3308
+ _chunk5JBFVV4Ccjs.assertUnreachable.call(void 0, this.#transport);
3309
+ }
3310
+ this.#transport = void 0;
3311
+ }
3312
+ #sendSubscription(eventName, subscribe) {
3313
+ this.#sendMessage(
3314
+ {
3315
+ body: {
3316
+ tag: "SubscriptionRequest",
3317
+ val: {
3318
+ eventName,
3319
+ subscribe
3320
+ }
3321
+ }
3322
+ },
3323
+ { ephemeral: true }
3324
+ );
3325
+ }
3326
+ };
3327
+
3328
+ // src/remote-manager-driver/mod.ts
3329
+
3330
+
3331
+
3332
+ // src/remote-manager-driver/log.ts
3333
+ function logger2() {
3334
+ return _chunkMRRT2CZDcjs.getLogger.call(void 0, "remote-manager-driver");
3335
+ }
3336
+
3337
+ // src/remote-manager-driver/api-utils.ts
3338
+ var EngineApiError = class extends Error {
3339
+ constructor(group, code, message) {
3340
+ super(message || `Engine API error: ${group}/${code}`);
3341
+ this.group = group;
3342
+ this.code = code;
3343
+ this.name = "EngineApiError";
3344
+ }
3345
+ };
3346
+ function getEndpoint(config) {
3347
+ return _nullishCoalesce(config.endpoint, () => ( "http://127.0.0.1:6420"));
3348
+ }
3349
+ async function apiCall(config, method, path, body) {
3350
+ const endpoint = getEndpoint(config);
3351
+ const url = _chunk5JBFVV4Ccjs.combineUrlPath.call(void 0, endpoint, path, {
3352
+ namespace: config.namespace
3353
+ });
3354
+ logger2().debug({ msg: "making api call", method, url });
3355
+ return await sendHttpRequest({
3356
+ method,
3357
+ url,
3358
+ headers: {},
3359
+ body,
3360
+ encoding: "json",
3361
+ skipParseResponse: false,
3362
+ requestVersionedDataHandler: void 0,
3363
+ responseVersionedDataHandler: void 0
3364
+ });
3365
+ }
3366
+
3367
+ // src/remote-manager-driver/actor-http-client.ts
3368
+ async function sendHttpRequestToActor(runConfig, actorId, actorRequest) {
3369
+ const url = new URL(actorRequest.url);
3370
+ const endpoint = getEndpoint(runConfig);
3371
+ const guardUrl = _chunk5JBFVV4Ccjs.combineUrlPath.call(void 0, endpoint, url.pathname + url.search);
3372
+ let bodyToSend = null;
3373
+ const guardHeaders = buildGuardHeadersForHttp(actorRequest, actorId);
3374
+ if (actorRequest.body && actorRequest.method !== "GET" && actorRequest.method !== "HEAD") {
3375
+ if (actorRequest.bodyUsed) {
3376
+ throw new Error("Request body has already been consumed");
3377
+ }
3378
+ const clonedRequest = actorRequest.clone();
3379
+ bodyToSend = await clonedRequest.arrayBuffer();
3380
+ guardHeaders.delete("transfer-encoding");
3381
+ guardHeaders.set(
3382
+ "content-length",
3383
+ String(bodyToSend.byteLength)
3384
+ );
3385
+ }
3386
+ const guardRequest = new Request(guardUrl, {
3387
+ method: actorRequest.method,
3388
+ headers: guardHeaders,
3389
+ body: bodyToSend,
3390
+ signal: actorRequest.signal
3391
+ });
3392
+ return mutableResponse(await fetch(guardRequest));
3393
+ }
3394
+ function mutableResponse(fetchRes) {
3395
+ return new Response(fetchRes.body, fetchRes);
3396
+ }
3397
+ function buildGuardHeadersForHttp(actorRequest, actorId) {
3398
+ const headers = new Headers();
3399
+ for (const [key, value] of actorRequest.headers.entries()) {
3400
+ headers.set(key, value);
3401
+ }
3402
+ headers.set("x-rivet-target", "actor");
3403
+ headers.set("x-rivet-actor", actorId);
3404
+ headers.set("x-rivet-port", "main");
3405
+ return headers;
3406
+ }
3407
+
3408
+ // src/remote-manager-driver/actor-websocket-client.ts
3409
+ async function openWebSocketToActor(runConfig, path, actorId, encoding, params) {
3410
+ const WebSocket2 = await _chunkKG3C7MKRcjs.importWebSocket.call(void 0, );
3411
+ const endpoint = getEndpoint(runConfig);
3412
+ const guardUrl = _chunk5JBFVV4Ccjs.combineUrlPath.call(void 0, endpoint, path);
3413
+ logger2().debug({
3414
+ msg: "opening websocket to actor via guard",
3415
+ actorId,
3416
+ path,
3417
+ guardUrl
3418
+ });
3419
+ const ws = new WebSocket2(guardUrl, {
3420
+ headers: buildGuardHeadersForWebSocket(actorId, encoding, params)
3421
+ });
3422
+ ws.binaryType = "arraybuffer";
3423
+ logger2().debug({ msg: "websocket connection opened", actorId });
3424
+ return ws;
3425
+ }
3426
+ function buildGuardHeadersForWebSocket(actorId, encoding, params, authData) {
3427
+ const headers = {};
3428
+ headers["x-rivet-target"] = "actor";
3429
+ headers["x-rivet-actor"] = actorId;
3430
+ headers["x-rivet-port"] = "main";
3431
+ headers[_chunkTCUI5JFEcjs.HEADER_ENCODING] = encoding;
3432
+ if (params) {
3433
+ headers[_chunkTCUI5JFEcjs.HEADER_CONN_PARAMS] = JSON.stringify(params);
3434
+ }
3435
+ if (authData) {
3436
+ headers[_chunkTCUI5JFEcjs.HEADER_AUTH_DATA] = JSON.stringify(authData);
3437
+ }
3438
+ return headers;
3439
+ }
3440
+
3441
+ // src/remote-manager-driver/api-endpoints.ts
3442
+ async function getActor(config, actorId) {
3443
+ return apiCall(
3444
+ config,
3445
+ "GET",
3446
+ `/actors/${encodeURIComponent(actorId)}`
3447
+ );
3448
+ }
3449
+ async function getActorById(config, name, key) {
3450
+ const serializedKey = serializeActorKey(key);
3451
+ return apiCall(
3452
+ config,
3453
+ "GET",
3454
+ `/actors/by-id?name=${encodeURIComponent(name)}&key=${encodeURIComponent(serializedKey)}`
3455
+ );
3456
+ }
3457
+ async function getOrCreateActorById(config, request) {
3458
+ return apiCall(
3459
+ config,
3460
+ "PUT",
3461
+ `/actors/by-id`,
3462
+ request
3463
+ );
3464
+ }
3465
+ async function createActor(config, request) {
3466
+ return apiCall(
3467
+ config,
3468
+ "POST",
3469
+ `/actors`,
3470
+ request
3471
+ );
3472
+ }
3473
+ async function destroyActor(config, actorId) {
3474
+ return apiCall(
3475
+ config,
3476
+ "DELETE",
3477
+ `/actors/${encodeURIComponent(actorId)}`
3478
+ );
3479
+ }
3480
+
3481
+ // src/remote-manager-driver/ws-proxy.ts
3482
+ async function createWebSocketProxy(c, targetUrl, headers) {
3483
+ const WebSocket2 = await _chunkKG3C7MKRcjs.importWebSocket.call(void 0, );
3484
+ for (const [k, v] of c.req.raw.headers.entries()) {
3485
+ if (!k.startsWith("sec-") && k !== "connection" && k !== "upgrade") {
3486
+ headers[k] = v;
3487
+ }
3488
+ }
3489
+ const state = {};
3490
+ return {
3491
+ onOpen: async (event, clientWs) => {
3492
+ logger2().debug({ msg: "client websocket connected", targetUrl });
3493
+ if (clientWs.readyState !== 1) {
3494
+ logger2().warn({
3495
+ msg: "client websocket not open on connection",
3496
+ targetUrl,
3497
+ readyState: clientWs.readyState
3498
+ });
3499
+ return;
3500
+ }
3501
+ const targetWs = new WebSocket2(targetUrl, { headers });
3502
+ state.targetWs = targetWs;
3503
+ state.connectPromise = new Promise((resolve, reject) => {
3504
+ targetWs.addEventListener("open", () => {
3505
+ logger2().debug({ msg: "target websocket connected", targetUrl });
3506
+ if (clientWs.readyState !== 1) {
3507
+ logger2().warn({
3508
+ msg: "client websocket closed before target connected",
3509
+ targetUrl,
3510
+ clientReadyState: clientWs.readyState
3511
+ });
3512
+ targetWs.close(1001, "Client disconnected");
3513
+ reject(new Error("Client disconnected"));
3514
+ return;
3515
+ }
3516
+ resolve();
3517
+ });
3518
+ targetWs.addEventListener("error", (error) => {
3519
+ logger2().warn({
3520
+ msg: "target websocket error during connection",
3521
+ targetUrl
3522
+ });
3523
+ reject(error);
3524
+ });
3525
+ });
3526
+ state.targetWs.addEventListener("message", (event2) => {
3527
+ if (typeof event2.data === "string" || event2.data instanceof ArrayBuffer) {
3528
+ clientWs.send(event2.data);
3529
+ } else if (event2.data instanceof Blob) {
3530
+ event2.data.arrayBuffer().then((buffer) => {
3531
+ clientWs.send(buffer);
3532
+ });
3533
+ }
3534
+ });
3535
+ state.targetWs.addEventListener("close", (event2) => {
3536
+ logger2().debug({
3537
+ msg: "target websocket closed",
3538
+ targetUrl,
3539
+ code: event2.code,
3540
+ reason: event2.reason
3541
+ });
3542
+ closeWebSocketIfOpen(clientWs, event2.code, event2.reason);
3543
+ });
3544
+ state.targetWs.addEventListener("error", (error) => {
3545
+ logger2().error({
3546
+ msg: "target websocket error",
3547
+ targetUrl,
3548
+ error: _chunk5JBFVV4Ccjs.stringifyError.call(void 0, error)
3549
+ });
3550
+ closeWebSocketIfOpen(clientWs, 1011, "Target WebSocket error");
3551
+ });
3552
+ },
3553
+ onMessage: async (event, clientWs) => {
3554
+ if (!state.targetWs || !state.connectPromise) {
3555
+ logger2().error({ msg: "websocket state not initialized", targetUrl });
3556
+ return;
3557
+ }
3558
+ try {
3559
+ await state.connectPromise;
3560
+ if (state.targetWs.readyState === WebSocket2.OPEN) {
3561
+ state.targetWs.send(event.data);
3562
+ } else {
3563
+ logger2().warn({
3564
+ msg: "target websocket not open",
3565
+ targetUrl,
3566
+ readyState: state.targetWs.readyState
3567
+ });
3568
+ }
3569
+ } catch (error) {
3570
+ logger2().error({
3571
+ msg: "failed to connect to target websocket",
3572
+ targetUrl,
3573
+ error
3574
+ });
3575
+ closeWebSocketIfOpen(clientWs, 1011, "Failed to connect to target");
3576
+ }
3577
+ },
3578
+ onClose: (event, clientWs) => {
3579
+ logger2().debug({
3580
+ msg: "client websocket closed",
3581
+ targetUrl,
3582
+ code: event.code,
3583
+ reason: event.reason,
3584
+ wasClean: event.wasClean
3585
+ });
3586
+ if (state.targetWs) {
3587
+ if (state.targetWs.readyState === WebSocket2.OPEN || state.targetWs.readyState === WebSocket2.CONNECTING) {
3588
+ state.targetWs.close(1e3, event.reason || "Client disconnected");
3589
+ }
3590
+ }
3591
+ },
3592
+ onError: (event, clientWs) => {
3593
+ logger2().error({ msg: "client websocket error", targetUrl, event });
3594
+ if (state.targetWs) {
3595
+ if (state.targetWs.readyState === WebSocket2.OPEN) {
3596
+ state.targetWs.close(1011, "Client WebSocket error");
3597
+ } else if (state.targetWs.readyState === WebSocket2.CONNECTING) {
3598
+ state.targetWs.close();
3599
+ }
3600
+ }
3601
+ }
3602
+ };
3603
+ }
3604
+ function closeWebSocketIfOpen(ws, code, reason) {
3605
+ if (ws.readyState === 1) {
3606
+ ws.close(code, reason);
3607
+ } else if ("close" in ws && ws.readyState === WebSocket.OPEN) {
3608
+ ws.close(code, reason);
3609
+ }
3610
+ }
3611
+
3612
+ // src/remote-manager-driver/mod.ts
3613
+ var RemoteManagerDriver = class {
3614
+ #config;
3615
+ constructor(runConfig) {
3616
+ this.#config = runConfig;
3617
+ }
3618
+ async getForId({
3619
+ c,
3620
+ name,
3621
+ actorId
3622
+ }) {
3623
+ try {
3624
+ const response = await getActor(this.#config, actorId);
3625
+ if (response.actor.name !== name) {
3626
+ logger2().debug({
3627
+ msg: "actor name mismatch from api",
3628
+ actorId,
3629
+ apiName: response.actor.name,
3630
+ requestedName: name
3631
+ });
3632
+ return void 0;
3633
+ }
3634
+ const keyRaw = response.actor.key;
3635
+ _invariant2.default.call(void 0, keyRaw, `actor ${actorId} should have key`);
3636
+ const key = deserializeActorKey(keyRaw);
3637
+ return {
3638
+ actorId,
3639
+ name,
3640
+ key
3641
+ };
3642
+ } catch (error) {
3643
+ if (error instanceof EngineApiError && error.group === "actor" && error.code === "not_found") {
3644
+ return void 0;
3645
+ }
3646
+ throw error;
3647
+ }
3648
+ }
3649
+ async getWithKey({
3650
+ c,
3651
+ name,
3652
+ key
3653
+ }) {
3654
+ logger2().debug({ msg: "getWithKey: searching for actor", name, key });
3655
+ try {
3656
+ const response = await getActorById(this.#config, name, key);
3657
+ if (!response.actor_id) {
3658
+ return void 0;
3659
+ }
3660
+ const actorId = response.actor_id;
3661
+ logger2().debug({
3662
+ msg: "getWithKey: found actor via api",
3663
+ actorId,
3664
+ name,
3665
+ key
3666
+ });
3667
+ return {
3668
+ actorId,
3669
+ name,
3670
+ key
3671
+ };
3672
+ } catch (error) {
3673
+ if (error instanceof EngineApiError && error.group === "actor" && error.code === "not_found") {
3674
+ return void 0;
3675
+ }
3676
+ throw error;
3677
+ }
3678
+ }
3679
+ async getOrCreateWithKey(input) {
3680
+ const { c, name, key, input: actorInput, region } = input;
3681
+ logger2().info({
3682
+ msg: "getOrCreateWithKey: getting or creating actor via engine api",
3683
+ name,
3684
+ key
3685
+ });
3686
+ const response = await getOrCreateActorById(this.#config, {
3687
+ name,
3688
+ key: serializeActorKey(key),
3689
+ runner_name_selector: this.#config.runnerName,
3690
+ input: input ? cbor6.encode(actorInput).toString("base64") : void 0,
3691
+ crash_policy: "sleep"
3692
+ });
3693
+ const actorId = response.actor_id;
3694
+ logger2().info({
3695
+ msg: "getOrCreateWithKey: actor ready",
3696
+ actorId,
3697
+ name,
3698
+ key,
3699
+ created: response.created
3700
+ });
3701
+ return {
3702
+ actorId,
3703
+ name,
3704
+ key
3705
+ };
3706
+ }
3707
+ async createActor({
3708
+ c,
3709
+ name,
3710
+ key,
3711
+ input
3712
+ }) {
3713
+ logger2().info({ msg: "creating actor via engine api", name, key });
3714
+ const result = await createActor(this.#config, {
3715
+ name,
3716
+ runner_name_selector: this.#config.runnerName,
3717
+ key: serializeActorKey(key),
3718
+ input: input ? cbor6.encode(input).toString("base64") : null,
3719
+ crash_policy: "sleep"
3720
+ });
3721
+ const actorId = result.actor.actor_id;
3722
+ logger2().info({ msg: "actor created", actorId, name, key });
3723
+ return {
3724
+ actorId,
3725
+ name,
3726
+ key
3727
+ };
3728
+ }
3729
+ async destroyActor(actorId) {
3730
+ logger2().info({ msg: "destroying actor via engine api", actorId });
3731
+ await destroyActor(this.#config, actorId);
3732
+ logger2().info({ msg: "actor destroyed", actorId });
3733
+ }
3734
+ async sendRequest(actorId, actorRequest) {
3735
+ return await sendHttpRequestToActor(this.#config, actorId, actorRequest);
3736
+ }
3737
+ async openWebSocket(path, actorId, encoding, params) {
3738
+ return await openWebSocketToActor(
3739
+ this.#config,
3740
+ path,
3741
+ actorId,
3742
+ encoding,
3743
+ params
3744
+ );
3745
+ }
3746
+ async proxyRequest(_c, actorRequest, actorId) {
3747
+ return await sendHttpRequestToActor(this.#config, actorId, actorRequest);
3748
+ }
3749
+ async proxyWebSocket(c, path, actorId, encoding, params, authData) {
3750
+ var _a, _b;
3751
+ const upgradeWebSocket = (_b = (_a = this.#config).getUpgradeWebSocket) == null ? void 0 : _b.call(_a);
3752
+ _invariant2.default.call(void 0, upgradeWebSocket, "missing getUpgradeWebSocket");
3753
+ const endpoint = getEndpoint(this.#config);
3754
+ const guardUrl = _chunk5JBFVV4Ccjs.combineUrlPath.call(void 0, endpoint, path);
3755
+ const wsGuardUrl = guardUrl.replace("http://", "ws://");
3756
+ logger2().debug({
3757
+ msg: "forwarding websocket to actor via guard",
3758
+ actorId,
3759
+ path,
3760
+ guardUrl
3761
+ });
3762
+ const headers = buildGuardHeadersForWebSocket(
3763
+ actorId,
3764
+ encoding,
3765
+ params,
3766
+ authData
3767
+ );
3768
+ const args = await createWebSocketProxy(c, wsGuardUrl, headers);
3769
+ return await upgradeWebSocket(() => args)(c, _chunk5JBFVV4Ccjs.noopNext.call(void 0, ));
3770
+ }
3771
+ displayInformation() {
3772
+ return { name: "Remote", properties: {} };
3773
+ }
3774
+ };
3775
+
3776
+
3777
+
3778
+
3779
+
3780
+
3781
+
3782
+
3783
+
3784
+
3785
+
3786
+
3787
+
3788
+
3789
+
3790
+
3791
+
3792
+
3793
+
3794
+
3795
+ exports.generateConnId = generateConnId; exports.generateConnToken = generateConnToken; exports.CONNECTION_DRIVER_WEBSOCKET = CONNECTION_DRIVER_WEBSOCKET; exports.CONNECTION_DRIVER_SSE = CONNECTION_DRIVER_SSE; exports.CONNECTION_DRIVER_HTTP = CONNECTION_DRIVER_HTTP; exports.createActorInspectorRouter = createActorInspectorRouter; exports.deserializeActorKey = deserializeActorKey; exports.ActorDefinition = ActorDefinition; exports.lookupInRegistry = lookupInRegistry; exports.ActorClientError = ActorClientError; exports.InternalError = InternalError2; exports.ManagerError = ManagerError; exports.MalformedResponseMessage = MalformedResponseMessage; exports.ActorError = ActorError; exports.ActorConnRaw = ActorConnRaw; exports.ActorHandleRaw = ActorHandleRaw; exports.createClientWithDriver = createClientWithDriver; exports.RemoteManagerDriver = RemoteManagerDriver;
3796
+ //# sourceMappingURL=chunk-UFWAK3X2.cjs.map