rivetkit 2.0.18 → 2.0.20
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/tsup/{chunk-O7NI7QQW.cjs → chunk-2I6L3VRO.cjs} +14 -14
- package/dist/tsup/{chunk-O7NI7QQW.cjs.map → chunk-2I6L3VRO.cjs.map} +1 -1
- package/dist/tsup/{chunk-BGBEE6N2.cjs → chunk-2S7HJMMY.cjs} +240 -193
- package/dist/tsup/chunk-2S7HJMMY.cjs.map +1 -0
- package/dist/tsup/{chunk-JMSXK5ZO.js → chunk-5F6X4AFU.js} +6 -6
- package/dist/tsup/{chunk-2MUSMEMN.js → chunk-7ACKZS3T.js} +6 -5
- package/dist/tsup/chunk-7ACKZS3T.js.map +1 -0
- package/dist/tsup/{chunk-OPB45MKH.cjs → chunk-DUOTOMP7.cjs} +3 -3
- package/dist/tsup/{chunk-OPB45MKH.cjs.map → chunk-DUOTOMP7.cjs.map} +1 -1
- package/dist/tsup/{chunk-6JGEHV56.js → chunk-ER5OT3SQ.js} +2 -2
- package/dist/tsup/{chunk-4R5LOYEU.cjs → chunk-FYP3TZXD.cjs} +28 -27
- package/dist/tsup/chunk-FYP3TZXD.cjs.map +1 -0
- package/dist/tsup/{chunk-RFCYH6EC.cjs → chunk-G6JGHCG4.cjs} +6 -6
- package/dist/tsup/{chunk-RFCYH6EC.cjs.map → chunk-G6JGHCG4.cjs.map} +1 -1
- package/dist/tsup/{chunk-DZEQUURK.js → chunk-GQ5WTE64.js} +18 -10
- package/dist/tsup/chunk-GQ5WTE64.js.map +1 -0
- package/dist/tsup/{chunk-IXPZJCBE.cjs → chunk-JZD6FEOE.cjs} +219 -211
- package/dist/tsup/chunk-JZD6FEOE.cjs.map +1 -0
- package/dist/tsup/{chunk-F5VXILGA.cjs → chunk-KKRR7DSG.cjs} +8 -4
- package/dist/tsup/chunk-KKRR7DSG.cjs.map +1 -0
- package/dist/tsup/{chunk-FADDMRZP.cjs → chunk-KUZWEM23.cjs} +2 -2
- package/dist/tsup/{chunk-FADDMRZP.cjs.map → chunk-KUZWEM23.cjs.map} +1 -1
- package/dist/tsup/{chunk-S5K7CB2F.js → chunk-L3YPHXPE.js} +76 -29
- package/dist/tsup/{chunk-S5K7CB2F.js.map → chunk-L3YPHXPE.js.map} +1 -1
- package/dist/tsup/{chunk-IXPWBGXK.js → chunk-M6LIJ6BK.js} +3 -3
- package/dist/tsup/{chunk-2P4ENWQ6.js → chunk-MGHPBNWB.js} +7 -3
- package/dist/tsup/chunk-MGHPBNWB.js.map +1 -0
- package/dist/tsup/{chunk-SBBFWYNM.cjs → chunk-PV22ZBDE.cjs} +8 -8
- package/dist/tsup/{chunk-SBBFWYNM.cjs.map → chunk-PV22ZBDE.cjs.map} +1 -1
- package/dist/tsup/{chunk-42UD33X4.js → chunk-QMVCFQ37.js} +2 -2
- package/dist/tsup/{chunk-42UD33X4.js.map → chunk-QMVCFQ37.js.map} +1 -1
- package/dist/tsup/{chunk-YVK2XQNR.js → chunk-QRUGCDA5.js} +2 -2
- package/dist/tsup/{chunk-KPFRD7KN.js → chunk-RI4YHZZW.js} +2 -2
- package/dist/tsup/{chunk-QMF6X2E2.cjs → chunk-RJVSNJO7.cjs} +7 -7
- package/dist/tsup/{chunk-QMF6X2E2.cjs.map → chunk-RJVSNJO7.cjs.map} +1 -1
- package/dist/tsup/{chunk-AR5ZY563.js → chunk-YFFCPYHY.js} +3 -3
- package/dist/tsup/{chunk-ICPFPGOJ.cjs → chunk-ZODINJWN.cjs} +12 -12
- package/dist/tsup/{chunk-ICPFPGOJ.cjs.map → chunk-ZODINJWN.cjs.map} +1 -1
- package/dist/tsup/client/mod.cjs +9 -9
- package/dist/tsup/client/mod.d.cts +2 -2
- package/dist/tsup/client/mod.d.ts +2 -2
- package/dist/tsup/client/mod.js +8 -8
- package/dist/tsup/common/log.cjs +3 -3
- package/dist/tsup/common/log.js +2 -2
- package/dist/tsup/common/websocket.cjs +4 -4
- package/dist/tsup/common/websocket.js +3 -3
- package/dist/tsup/{conn-DhdZYlSX.d.ts → conn-CmPcqOCF.d.ts} +72 -67
- package/dist/tsup/{conn-CxCsTz2s.d.cts → conn-DU5EbfCu.d.cts} +72 -67
- package/dist/tsup/driver-helpers/mod.cjs +5 -5
- package/dist/tsup/driver-helpers/mod.d.cts +1 -1
- package/dist/tsup/driver-helpers/mod.d.ts +1 -1
- package/dist/tsup/driver-helpers/mod.js +4 -4
- package/dist/tsup/driver-test-suite/mod.cjs +71 -71
- package/dist/tsup/driver-test-suite/mod.d.cts +1 -1
- package/dist/tsup/driver-test-suite/mod.d.ts +1 -1
- package/dist/tsup/driver-test-suite/mod.js +11 -11
- package/dist/tsup/inspector/mod.cjs +6 -6
- package/dist/tsup/inspector/mod.d.cts +2 -2
- package/dist/tsup/inspector/mod.d.ts +2 -2
- package/dist/tsup/inspector/mod.js +5 -5
- package/dist/tsup/mod.cjs +10 -10
- package/dist/tsup/mod.d.cts +2 -2
- package/dist/tsup/mod.d.ts +2 -2
- package/dist/tsup/mod.js +9 -9
- package/dist/tsup/test/mod.cjs +11 -11
- package/dist/tsup/test/mod.d.cts +1 -1
- package/dist/tsup/test/mod.d.ts +1 -1
- package/dist/tsup/test/mod.js +10 -10
- package/dist/tsup/utils.cjs +2 -2
- package/dist/tsup/utils.js +1 -1
- package/package.json +1 -1
- package/src/common/eventsource.ts +7 -43
- package/src/common/websocket.ts +2 -1
- package/src/engine-process/mod.ts +66 -15
- package/src/registry/mod.ts +26 -2
- package/src/registry/run-config.ts +1 -0
- package/src/remote-manager-driver/mod.ts +12 -3
- package/dist/tsup/chunk-2MUSMEMN.js.map +0 -1
- package/dist/tsup/chunk-2P4ENWQ6.js.map +0 -1
- package/dist/tsup/chunk-4R5LOYEU.cjs.map +0 -1
- package/dist/tsup/chunk-BGBEE6N2.cjs.map +0 -1
- package/dist/tsup/chunk-DZEQUURK.js.map +0 -1
- package/dist/tsup/chunk-F5VXILGA.cjs.map +0 -1
- package/dist/tsup/chunk-IXPZJCBE.cjs.map +0 -1
- /package/dist/tsup/{chunk-JMSXK5ZO.js.map → chunk-5F6X4AFU.js.map} +0 -0
- /package/dist/tsup/{chunk-6JGEHV56.js.map → chunk-ER5OT3SQ.js.map} +0 -0
- /package/dist/tsup/{chunk-IXPWBGXK.js.map → chunk-M6LIJ6BK.js.map} +0 -0
- /package/dist/tsup/{chunk-YVK2XQNR.js.map → chunk-QRUGCDA5.js.map} +0 -0
- /package/dist/tsup/{chunk-KPFRD7KN.js.map → chunk-RI4YHZZW.js.map} +0 -0
- /package/dist/tsup/{chunk-AR5ZY563.js.map → chunk-YFFCPYHY.js.map} +0 -0
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
RemoteManagerDriver,
|
|
3
3
|
createClientWithDriver
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-GQ5WTE64.js";
|
|
5
5
|
import {
|
|
6
6
|
ClientConfigSchema
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-7ACKZS3T.js";
|
|
8
8
|
|
|
9
9
|
// src/client/mod.ts
|
|
10
10
|
function createClient(endpointOrConfig) {
|
|
@@ -17,4 +17,4 @@ function createClient(endpointOrConfig) {
|
|
|
17
17
|
export {
|
|
18
18
|
createClient
|
|
19
19
|
};
|
|
20
|
-
//# sourceMappingURL=chunk-
|
|
20
|
+
//# sourceMappingURL=chunk-M6LIJ6BK.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getLogger
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-ER5OT3SQ.js";
|
|
4
4
|
|
|
5
5
|
// src/client/log.ts
|
|
6
6
|
function logger() {
|
|
@@ -19,7 +19,11 @@ async function importWebSocket() {
|
|
|
19
19
|
_WebSocket = WebSocket;
|
|
20
20
|
} else {
|
|
21
21
|
try {
|
|
22
|
-
const
|
|
22
|
+
const moduleName = "ws";
|
|
23
|
+
const ws = await import(
|
|
24
|
+
/* webpackIgnore: true */
|
|
25
|
+
moduleName
|
|
26
|
+
);
|
|
23
27
|
_WebSocket = ws.default;
|
|
24
28
|
logger().debug("using websocket from npm");
|
|
25
29
|
} catch {
|
|
@@ -42,4 +46,4 @@ export {
|
|
|
42
46
|
logger,
|
|
43
47
|
importWebSocket
|
|
44
48
|
};
|
|
45
|
-
//# sourceMappingURL=chunk-
|
|
49
|
+
//# sourceMappingURL=chunk-MGHPBNWB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/client/log.ts","../../src/common/websocket.ts"],"sourcesContent":["import { getLogger } from \"@/common/log\";\n\nexport function logger() {\n\treturn getLogger(\"actor-client\");\n}\n","import { logger } from \"@/client/log\";\n\n// Global singleton promise that will be reused for subsequent calls\nlet webSocketPromise: Promise<typeof WebSocket> | null = null;\n\nexport async function importWebSocket(): Promise<typeof WebSocket> {\n\t// Return existing promise if we already started loading\n\tif (webSocketPromise !== null) {\n\t\treturn webSocketPromise;\n\t}\n\n\t// Create and store the promise\n\twebSocketPromise = (async () => {\n\t\tlet _WebSocket: typeof WebSocket;\n\n\t\tif (typeof WebSocket !== \"undefined\") {\n\t\t\t// Browser environment\n\t\t\t_WebSocket = WebSocket as unknown as typeof WebSocket;\n\t\t} else {\n\t\t\t// Node.js environment\n\t\t\ttry {\n\t\t\t\tconst moduleName = \"ws\";\n\t\t\t\tconst ws = await import(/* webpackIgnore: true */ moduleName);\n\t\t\t\t_WebSocket = ws.default as unknown as typeof WebSocket;\n\t\t\t\tlogger().debug(\"using websocket from npm\");\n\t\t\t} catch {\n\t\t\t\t// WS not available\n\t\t\t\t_WebSocket = class MockWebSocket {\n\t\t\t\t\tconstructor() {\n\t\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t\t'WebSocket support requires installing the \"ws\" peer dependency.',\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t} as unknown as typeof WebSocket;\n\t\t\t\tlogger().debug(\"using mock websocket\");\n\t\t\t}\n\t\t}\n\n\t\treturn _WebSocket;\n\t})();\n\n\treturn webSocketPromise;\n}\n"],"mappings":";;;;;AAEO,SAAS,SAAS;AACxB,SAAO,UAAU,cAAc;AAChC;;;ACDA,IAAI,mBAAqD;AAEzD,eAAsB,kBAA6C;AAElE,MAAI,qBAAqB,MAAM;AAC9B,WAAO;AAAA,EACR;AAGA,sBAAoB,YAAY;AAC/B,QAAI;AAEJ,QAAI,OAAO,cAAc,aAAa;AAErC,mBAAa;AAAA,IACd,OAAO;AAEN,UAAI;AACH,cAAM,aAAa;AACnB,cAAM,KAAK,MAAM;AAAA;AAAA,UAAiC;AAAA;AAClD,qBAAa,GAAG;AAChB,eAAO,EAAE,MAAM,0BAA0B;AAAA,MAC1C,QAAQ;AAEP,qBAAa,MAAM,cAAc;AAAA,UAChC,cAAc;AACb,kBAAM,IAAI;AAAA,cACT;AAAA,YACD;AAAA,UACD;AAAA,QACD;AACA,eAAO,EAAE,MAAM,sBAAsB;AAAA,MACtC;AAAA,IACD;AAEA,WAAO;AAAA,EACR,GAAG;AAEH,SAAO;AACR;","names":[]}
|
|
@@ -1,16 +1,16 @@
|
|
|
1
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 }; }
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkRJVSNJO7cjs = require('./chunk-RJVSNJO7.cjs');
|
|
4
4
|
|
|
5
5
|
|
|
6
|
-
var
|
|
6
|
+
var _chunkKUZWEM23cjs = require('./chunk-KUZWEM23.cjs');
|
|
7
7
|
|
|
8
8
|
|
|
9
9
|
var _chunkKSRXX3Z4cjs = require('./chunk-KSRXX3Z4.cjs');
|
|
10
10
|
|
|
11
11
|
// src/actor/log.ts
|
|
12
12
|
function loggerWithoutContext() {
|
|
13
|
-
return
|
|
13
|
+
return _chunkRJVSNJO7cjs.getLogger.call(void 0, "actor-runtime");
|
|
14
14
|
}
|
|
15
15
|
|
|
16
16
|
// src/actor/utils.ts
|
|
@@ -216,7 +216,7 @@ function encodingIsBinary(encoding) {
|
|
|
216
216
|
} else if (encoding === "cbor" || encoding === "bare") {
|
|
217
217
|
return true;
|
|
218
218
|
} else {
|
|
219
|
-
|
|
219
|
+
_chunkKUZWEM23cjs.assertUnreachable.call(void 0, encoding);
|
|
220
220
|
}
|
|
221
221
|
}
|
|
222
222
|
function contentTypeForEncoding(encoding) {
|
|
@@ -225,7 +225,7 @@ function contentTypeForEncoding(encoding) {
|
|
|
225
225
|
} else if (encoding === "cbor" || encoding === "bare") {
|
|
226
226
|
return "application/octet-stream";
|
|
227
227
|
} else {
|
|
228
|
-
|
|
228
|
+
_chunkKUZWEM23cjs.assertUnreachable.call(void 0, encoding);
|
|
229
229
|
}
|
|
230
230
|
}
|
|
231
231
|
function serializeWithEncoding(encoding, value, versionedDataHandler) {
|
|
@@ -239,7 +239,7 @@ function serializeWithEncoding(encoding, value, versionedDataHandler) {
|
|
|
239
239
|
}
|
|
240
240
|
return versionedDataHandler.serializeWithEmbeddedVersion(value);
|
|
241
241
|
} else {
|
|
242
|
-
|
|
242
|
+
_chunkKUZWEM23cjs.assertUnreachable.call(void 0, encoding);
|
|
243
243
|
}
|
|
244
244
|
}
|
|
245
245
|
function deserializeWithEncoding(encoding, buffer, versionedDataHandler) {
|
|
@@ -267,7 +267,7 @@ function deserializeWithEncoding(encoding, buffer, versionedDataHandler) {
|
|
|
267
267
|
}
|
|
268
268
|
return versionedDataHandler.deserializeWithEmbeddedVersion(buffer);
|
|
269
269
|
} else {
|
|
270
|
-
|
|
270
|
+
_chunkKUZWEM23cjs.assertUnreachable.call(void 0, encoding);
|
|
271
271
|
}
|
|
272
272
|
}
|
|
273
273
|
|
|
@@ -310,4 +310,4 @@ function deserializeWithEncoding(encoding, buffer, versionedDataHandler) {
|
|
|
310
310
|
|
|
311
311
|
|
|
312
312
|
exports.uint8ArrayToBase64 = uint8ArrayToBase64; exports.encodingIsBinary = encodingIsBinary; exports.contentTypeForEncoding = contentTypeForEncoding; exports.serializeWithEncoding = serializeWithEncoding; exports.deserializeWithEncoding = deserializeWithEncoding; exports.loggerWithoutContext = loggerWithoutContext; exports.assertUnreachable = assertUnreachable2; exports.DeadlineError = DeadlineError; exports.deadline = deadline; exports.generateSecureToken = generateSecureToken; exports.generateRandomString = generateRandomString; exports.EncodingSchema = EncodingSchema; exports.CachedSerializer = CachedSerializer; exports.encodeDataToString = encodeDataToString; exports.jsonStringifyCompat = jsonStringifyCompat; exports.PATH_CONNECT_WEBSOCKET = PATH_CONNECT_WEBSOCKET; exports.PATH_RAW_WEBSOCKET_PREFIX = PATH_RAW_WEBSOCKET_PREFIX; exports.HEADER_ACTOR_QUERY = HEADER_ACTOR_QUERY; exports.HEADER_ENCODING = HEADER_ENCODING; exports.HEADER_CONN_PARAMS = HEADER_CONN_PARAMS; exports.HEADER_ACTOR_ID = HEADER_ACTOR_ID; exports.HEADER_CONN_ID = HEADER_CONN_ID; exports.HEADER_CONN_TOKEN = HEADER_CONN_TOKEN; exports.HEADER_RIVET_TOKEN = HEADER_RIVET_TOKEN; exports.HEADER_RIVET_TARGET = HEADER_RIVET_TARGET; exports.HEADER_RIVET_ACTOR = HEADER_RIVET_ACTOR; exports.WS_PROTOCOL_STANDARD = WS_PROTOCOL_STANDARD; exports.WS_PROTOCOL_TARGET = WS_PROTOCOL_TARGET; exports.WS_PROTOCOL_ACTOR = WS_PROTOCOL_ACTOR; exports.WS_PROTOCOL_ENCODING = WS_PROTOCOL_ENCODING; exports.WS_PROTOCOL_CONN_PARAMS = WS_PROTOCOL_CONN_PARAMS; exports.WS_PROTOCOL_CONN_ID = WS_PROTOCOL_CONN_ID; exports.WS_PROTOCOL_CONN_TOKEN = WS_PROTOCOL_CONN_TOKEN; exports.WS_PROTOCOL_TOKEN = WS_PROTOCOL_TOKEN; exports.WS_PROTOCOL_TRANSPORT = WS_PROTOCOL_TRANSPORT; exports.WS_PROTOCOL_PATH = WS_PROTOCOL_PATH; exports.ALLOWED_PUBLIC_HEADERS = ALLOWED_PUBLIC_HEADERS;
|
|
313
|
-
//# sourceMappingURL=chunk-
|
|
313
|
+
//# sourceMappingURL=chunk-PV22ZBDE.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-SBBFWYNM.cjs","../../src/actor/log.ts","../../src/actor/utils.ts","../../src/common/actor-router-consts.ts","../../src/serde.ts","../../src/actor/protocol/serde.ts"],"names":["assertUnreachable"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACPO,SAAS,oBAAA,CAAA,EAAuB;AACtC,EAAA,OAAO,yCAAA,eAAyB,CAAA;AACjC;ADSA;AACA;AEZO,SAASA,kBAAAA,CAAkB,CAAA,EAAiB;AAClD,EAAA,oBAAA,CAAqB,CAAA,CAAE,KAAA,CAAM;AAAA,IAC5B,GAAA,EAAK,aAAA;AAAA,IACL,KAAA,EAAO,CAAA,EAAA;AACA,IAAA;AACP,EAAA;AACgB,EAAA;AAClB;AA+Ba;AACZ,EAAA;AACO,IAAA;AACP,EAAA;AACD;AAEgB;AACT,EAAA;AACA,EAAA;AAGA,EAAA;AAEC,EAAA;AACN,IAAA;AACI,IAAA;AACH,MAAA;AACA,IAAA;AACC,EAAA;AACF,IAAA;AACA,EAAA;AACF;AAwBgB;AACT,EAAA;AACC,EAAA;AAEA,EAAA;AAIR;AAEgB;AACT,EAAA;AAEF,EAAA;AACK,EAAA;AACF,IAAA;AACN,IAAA;AACD,EAAA;AACO,EAAA;AACR;AFjDY;AACA;AGtDC;AACA;AAGA;AAEA;AAG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AACD,MAAA;AACD,IAAA;AAEO,IAAA;AACP,EAAA;AACF;ALHY;AACA;AIjMI;AAEX,EAAA;AACI,IAAA;AACR,EAAA;AAGI,EAAA;AACE,EAAA;AACG,EAAA;AACR,IAAA;AACD,EAAA;AACO,EAAA;AACR;AAEgB;AACX,EAAA;AACI,IAAA;AACR,EAAA;AACQ,IAAA;AACD,EAAA;AACN,IAAA;AACD,EAAA;AACD;AAEgB;AACX,EAAA;AACI,IAAA;AACR,EAAA;AACQ,IAAA;AACD,EAAA;AACN,IAAA;AACD,EAAA;AACD;AAcgB;AAKX,EAAA;AACI,IAAA;AACR,EAAA;AACa,IAAA;AACb,EAAA;AACM,IAAA;AACE,MAAA;AACP,IAAA;AACO,IAAA;AACD,EAAA;AACN,IAAA;AACD,EAAA;AACD;AAEgB;AAKX,EAAA;AACC,IAAA;AACH,MAAA;AACM,IAAA;AACA,MAAA;AACA,MAAA;AACN,MAAA;AACD,IAAA;AACD,EAAA;AACC,IAAA;AACC,MAAA;AACA,MAAA;AACD,IAAA;AACY,IAAA;AACb,EAAA;AACC,IAAA;AACC,MAAA;AACA,MAAA;AACD,IAAA;AACK,IAAA;AACE,MAAA;AACP,IAAA;AACO,IAAA;AACD,EAAA;AACN,IAAA;AACD,EAAA;AACD;AJwKY;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-SBBFWYNM.cjs","sourcesContent":[null,"import { getLogger } from \"@/common/log\";\n\n/** Prever to use ActorInstance.rlog child logger. This does not provide context in the log, should only be used as a last resort if you cannot pass the actor's child logger. */\nexport function loggerWithoutContext() {\n\treturn getLogger(\"actor-runtime\");\n}\n","import * as errors from \"./errors\";\nimport { loggerWithoutContext } from \"./log\";\n\nexport function assertUnreachable(x: never): never {\n\tloggerWithoutContext().error({\n\t\tmsg: \"unreachable\",\n\t\tvalue: `${x}`,\n\t\tstack: new Error().stack,\n\t});\n\tthrow new errors.Unreachable(x);\n}\n\nexport const throttle = <\n\t// biome-ignore lint/suspicious/noExplicitAny: we want to allow any function\n\tFn extends (...args: any) => any,\n>(\n\tfn: Fn,\n\tdelay: number,\n) => {\n\tlet lastRan = false;\n\tlet lastArgs: Parameters<Fn> | null = null;\n\n\treturn (...args: Parameters<Fn>) => {\n\t\tif (!lastRan) {\n\t\t\tfn.apply(this, args);\n\t\t\tlastRan = true;\n\t\t\tconst timer = () =>\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tlastRan = false;\n\t\t\t\t\tif (lastArgs) {\n\t\t\t\t\t\tfn.apply(this, lastArgs);\n\t\t\t\t\t\tlastRan = true;\n\t\t\t\t\t\tlastArgs = null;\n\t\t\t\t\t\ttimer();\n\t\t\t\t\t}\n\t\t\t\t}, delay);\n\t\t\ttimer();\n\t\t} else lastArgs = args;\n\t};\n};\n\nexport class DeadlineError extends Error {\n\tconstructor() {\n\t\tsuper(\"Promise did not complete before deadline.\");\n\t}\n}\n\nexport function deadline<T>(promise: Promise<T>, timeout: number): Promise<T> {\n\tconst controller = new AbortController();\n\tconst signal = controller.signal;\n\n\t// Set a timeout to abort the operation\n\tconst timeoutId = setTimeout(() => controller.abort(), timeout);\n\n\treturn Promise.race<T>([\n\t\tpromise,\n\t\tnew Promise<T>((_, reject) => {\n\t\t\tsignal.addEventListener(\"abort\", () => reject(new DeadlineError()));\n\t\t}),\n\t]).finally(() => {\n\t\tclearTimeout(timeoutId);\n\t});\n}\n\nexport class Lock<T> {\n\tprivate _locked = false;\n\tprivate _waiting: Array<() => void> = [];\n\n\tconstructor(private _value: T) {}\n\n\tasync lock(fn: (value: T) => Promise<void>): Promise<void> {\n\t\tif (this._locked) {\n\t\t\tawait new Promise<void>((resolve) => this._waiting.push(resolve));\n\t\t}\n\t\tthis._locked = true;\n\n\t\ttry {\n\t\t\tawait fn(this._value);\n\t\t} finally {\n\t\t\tthis._locked = false;\n\t\t\tconst next = this._waiting.shift();\n\t\t\tif (next) next();\n\t\t}\n\t}\n}\n\nexport function generateSecureToken(length = 32) {\n\tconst array = new Uint8Array(length);\n\tcrypto.getRandomValues(array);\n\t// Replace base64 chars that are not URL safe with URL-safe chars and strip padding\n\treturn btoa(String.fromCharCode(...array))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nexport function generateRandomString(length = 32) {\n\tconst characters =\n\t\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\tlet result = \"\";\n\tfor (let i = 0; i < length; i++) {\n\t\tconst randomIndex = Math.floor(Math.random() * characters.length);\n\t\tresult += characters[randomIndex];\n\t}\n\treturn result;\n}\n","// NOTE: This is in a separate file from the router since it needs to be shared between the client & the server. If this was in the router file, the client would end up importing the *entire* actor router and tree shaking would not work.\n\n// MARK: Paths\nexport const PATH_CONNECT_WEBSOCKET = \"/connect/websocket\";\nexport const PATH_RAW_WEBSOCKET_PREFIX = \"/raw/websocket/\";\n\n// MARK: Headers\nexport const HEADER_ACTOR_QUERY = \"x-rivet-query\";\n\nexport const HEADER_ENCODING = \"x-rivet-encoding\";\n\n// IMPORTANT: Params must be in headers or in an E2EE part of the request (i.e. NOT the URL or query string) in order to ensure that tokens can be securely passed in params.\nexport const HEADER_CONN_PARAMS = \"x-rivet-conn-params\";\n\nexport const HEADER_ACTOR_ID = \"x-rivet-actor\";\n\nexport const HEADER_CONN_ID = \"x-rivet-conn\";\n\nexport const HEADER_CONN_TOKEN = \"x-rivet-conn-token\";\n\nexport const HEADER_RIVET_TOKEN = \"x-rivet-token\";\n\n// MARK: Manager Gateway Headers\nexport const HEADER_RIVET_TARGET = \"x-rivet-target\";\nexport const HEADER_RIVET_ACTOR = \"x-rivet-actor\";\n\n// MARK: WebSocket Protocol Prefixes\n/** Some servers (such as node-ws & Cloudflare) require explicitly match a certain WebSocket protocol. This gives us a static protocol to match against. */\nexport const WS_PROTOCOL_STANDARD = \"rivet\";\nexport const WS_PROTOCOL_TARGET = \"rivet_target.\";\nexport const WS_PROTOCOL_ACTOR = \"rivet_actor.\";\nexport const WS_PROTOCOL_ENCODING = \"rivet_encoding.\";\nexport const WS_PROTOCOL_CONN_PARAMS = \"rivet_conn_params.\";\nexport const WS_PROTOCOL_CONN_ID = \"rivet_conn.\";\nexport const WS_PROTOCOL_CONN_TOKEN = \"rivet_conn_token.\";\nexport const WS_PROTOCOL_TOKEN = \"rivet_token.\";\n\n// MARK: WebSocket Inline Test Protocol Prefixes\nexport const WS_PROTOCOL_TRANSPORT = \"test_transport.\";\nexport const WS_PROTOCOL_PATH = \"test_path.\";\n\n/**\n * Headers that publics can send from public clients.\n *\n * Used for CORS.\n **/\nexport const ALLOWED_PUBLIC_HEADERS = [\n\t\"Content-Type\",\n\t\"User-Agent\",\n\tHEADER_ACTOR_QUERY,\n\tHEADER_ENCODING,\n\tHEADER_CONN_PARAMS,\n\tHEADER_ACTOR_ID,\n\tHEADER_CONN_ID,\n\tHEADER_CONN_TOKEN,\n\tHEADER_RIVET_TARGET,\n\tHEADER_RIVET_ACTOR,\n\tHEADER_RIVET_TOKEN,\n];\n","import * as cbor from \"cbor-x\";\nimport invariant from \"invariant\";\nimport { assertUnreachable } from \"@/common/utils\";\nimport type { VersionedDataHandler } from \"@/common/versioned-data\";\nimport type { Encoding } from \"@/mod\";\nimport { jsonParseCompat, jsonStringifyCompat } from \"./actor/protocol/serde\";\n\nexport function uint8ArrayToBase64(uint8Array: Uint8Array): string {\n\t// Check if Buffer is available (Node.js)\n\tif (typeof Buffer !== \"undefined\") {\n\t\treturn Buffer.from(uint8Array).toString(\"base64\");\n\t}\n\n\t// Browser environment - use btoa\n\tlet binary = \"\";\n\tconst len = uint8Array.byteLength;\n\tfor (let i = 0; i < len; i++) {\n\t\tbinary += String.fromCharCode(uint8Array[i]);\n\t}\n\treturn btoa(binary);\n}\n\nexport function encodingIsBinary(encoding: Encoding): boolean {\n\tif (encoding === \"json\") {\n\t\treturn false;\n\t} else if (encoding === \"cbor\" || encoding === \"bare\") {\n\t\treturn true;\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function contentTypeForEncoding(encoding: Encoding): string {\n\tif (encoding === \"json\") {\n\t\treturn \"application/json\";\n\t} else if (encoding === \"cbor\" || encoding === \"bare\") {\n\t\treturn \"application/octet-stream\";\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function wsBinaryTypeForEncoding(\n\tencoding: Encoding,\n): \"arraybuffer\" | \"blob\" {\n\tif (encoding === \"json\") {\n\t\treturn \"blob\";\n\t} else if (encoding === \"cbor\" || encoding === \"bare\") {\n\t\treturn \"arraybuffer\";\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function serializeWithEncoding<T>(\n\tencoding: Encoding,\n\tvalue: T,\n\tversionedDataHandler: VersionedDataHandler<T> | undefined,\n): Uint8Array | string {\n\tif (encoding === \"json\") {\n\t\treturn jsonStringifyCompat(value);\n\t} else if (encoding === \"cbor\") {\n\t\treturn cbor.encode(value);\n\t} else if (encoding === \"bare\") {\n\t\tif (!versionedDataHandler) {\n\t\t\tthrow new Error(\"VersionedDataHandler is required for 'bare' encoding\");\n\t\t}\n\t\treturn versionedDataHandler.serializeWithEmbeddedVersion(value);\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function deserializeWithEncoding<T>(\n\tencoding: Encoding,\n\tbuffer: Uint8Array | string,\n\tversionedDataHandler: VersionedDataHandler<T> | undefined,\n): T {\n\tif (encoding === \"json\") {\n\t\tif (typeof buffer === \"string\") {\n\t\t\treturn jsonParseCompat(buffer);\n\t\t} else {\n\t\t\tconst decoder = new TextDecoder(\"utf-8\");\n\t\t\tconst jsonString = decoder.decode(buffer);\n\t\t\treturn jsonParseCompat(jsonString);\n\t\t}\n\t} else if (encoding === \"cbor\") {\n\t\tinvariant(\n\t\t\ttypeof buffer !== \"string\",\n\t\t\t\"buffer cannot be string for cbor encoding\",\n\t\t);\n\t\treturn cbor.decode(buffer);\n\t} else if (encoding === \"bare\") {\n\t\tinvariant(\n\t\t\ttypeof buffer !== \"string\",\n\t\t\t\"buffer cannot be string for bare encoding\",\n\t\t);\n\t\tif (!versionedDataHandler) {\n\t\t\tthrow new Error(\"VersionedDataHandler is required for 'bare' encoding\");\n\t\t}\n\t\treturn versionedDataHandler.deserializeWithEmbeddedVersion(buffer);\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n","import * as cbor from \"cbor-x\";\nimport { z } from \"zod\";\nimport * as errors from \"@/actor/errors\";\nimport type { VersionedDataHandler } from \"@/common/versioned-data\";\nimport { serializeWithEncoding } from \"@/serde\";\nimport { loggerWithoutContext } from \"../log\";\nimport { assertUnreachable } from \"../utils\";\n\n/** Data that can be deserialized. */\nexport type InputData = string | Buffer | Blob | ArrayBufferLike | Uint8Array;\n\n/** Data that's been serialized. */\nexport type OutputData = string | Uint8Array;\n\nexport const EncodingSchema = z.enum([\"json\", \"cbor\", \"bare\"]);\n\n/**\n * Encoding used to communicate between the client & actor.\n */\nexport type Encoding = z.infer<typeof EncodingSchema>;\n\n/**\n * Helper class that helps serialize data without re-serializing for the same encoding.\n */\nexport class CachedSerializer<T> {\n\t#data: T;\n\t#cache = new Map<Encoding, OutputData>();\n\t#versionedDataHandler: VersionedDataHandler<T>;\n\n\tconstructor(data: T, versionedDataHandler: VersionedDataHandler<T>) {\n\t\tthis.#data = data;\n\t\tthis.#versionedDataHandler = versionedDataHandler;\n\t}\n\n\tpublic get rawData(): T {\n\t\treturn this.#data;\n\t}\n\n\tpublic serialize(encoding: Encoding): OutputData {\n\t\tconst cached = this.#cache.get(encoding);\n\t\tif (cached) {\n\t\t\treturn cached;\n\t\t} else {\n\t\t\tconst serialized = serializeWithEncoding(\n\t\t\t\tencoding,\n\t\t\t\tthis.#data,\n\t\t\t\tthis.#versionedDataHandler,\n\t\t\t);\n\t\t\tthis.#cache.set(encoding, serialized);\n\t\t\treturn serialized;\n\t\t}\n\t}\n}\n\n///**\n// * Use `CachedSerializer` if serializing the same data repeatedly.\n// */\n//export function serialize<T>(value: T, encoding: Encoding): OutputData {\n//\tif (encoding === \"json\") {\n//\t\treturn JSON.stringify(value);\n//\t} else if (encoding === \"cbor\") {\n//\t\t// TODO: Remove this hack, but cbor-x can't handle anything extra in data structures\n//\t\tconst cleanValue = JSON.parse(JSON.stringify(value));\n//\t\treturn cbor.encode(cleanValue);\n//\t} else {\n//\t\tassertUnreachable(encoding);\n//\t}\n//}\n//\n//export async function deserialize(data: InputData, encoding: Encoding) {\n//\tif (encoding === \"json\") {\n//\t\tif (typeof data !== \"string\") {\n//\t\t\tlogger().warn(\"received non-string for json parse\");\n//\t\t\tthrow new errors.MalformedMessage();\n//\t\t} else {\n//\t\t\treturn JSON.parse(data);\n//\t\t}\n//\t} else if (encoding === \"cbor\") {\n//\t\tif (data instanceof Blob) {\n//\t\t\tconst arrayBuffer = await data.arrayBuffer();\n//\t\t\treturn cbor.decode(new Uint8Array(arrayBuffer));\n//\t\t} else if (data instanceof Uint8Array) {\n//\t\t\treturn cbor.decode(data);\n//\t\t} else if (\n//\t\t\tdata instanceof ArrayBuffer ||\n//\t\t\tdata instanceof SharedArrayBuffer\n//\t\t) {\n//\t\t\treturn cbor.decode(new Uint8Array(data));\n//\t\t} else {\n//\t\t\tlogger().warn(\"received non-binary type for cbor parse\");\n//\t\t\tthrow new errors.MalformedMessage();\n//\t\t}\n//\t} else {\n//\t\tassertUnreachable(encoding);\n//\t}\n//}\n\n// TODO: Encode base 128\nfunction base64EncodeUint8Array(uint8Array: Uint8Array): string {\n\tlet binary = \"\";\n\tconst len = uint8Array.byteLength;\n\tfor (let i = 0; i < len; i++) {\n\t\tbinary += String.fromCharCode(uint8Array[i]);\n\t}\n\treturn btoa(binary);\n}\n\nfunction base64EncodeArrayBuffer(arrayBuffer: ArrayBuffer): string {\n\tconst uint8Array = new Uint8Array(arrayBuffer);\n\treturn base64EncodeUint8Array(uint8Array);\n}\n\n/** Converts data that was encoded to a string. Some formats (like SSE) don't support raw binary data. */\nexport function encodeDataToString(message: OutputData): string {\n\tif (typeof message === \"string\") {\n\t\treturn message;\n\t} else if (message instanceof ArrayBuffer) {\n\t\treturn base64EncodeArrayBuffer(message);\n\t} else if (message instanceof Uint8Array) {\n\t\treturn base64EncodeUint8Array(message);\n\t} else {\n\t\tassertUnreachable(message);\n\t}\n}\n\nfunction base64DecodeToUint8Array(base64: string): Uint8Array {\n\t// Check if Buffer is available (Node.js)\n\tif (typeof Buffer !== \"undefined\") {\n\t\treturn new Uint8Array(Buffer.from(base64, \"base64\"));\n\t}\n\n\t// Browser environment - use atob\n\tconst binary = atob(base64);\n\tconst len = binary.length;\n\tconst bytes = new Uint8Array(len);\n\tfor (let i = 0; i < len; i++) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n\nfunction base64DecodeToArrayBuffer(base64: string): ArrayBuffer {\n\treturn base64DecodeToUint8Array(base64).buffer as ArrayBuffer;\n}\n\n/** Stringifies with compat for values that BARE & CBOR supports. */\nexport function jsonStringifyCompat(input: any): string {\n\treturn JSON.stringify(input, (_key, value) => {\n\t\tif (typeof value === \"bigint\") {\n\t\t\treturn [\"$BigInt\", value.toString()];\n\t\t} else if (value instanceof ArrayBuffer) {\n\t\t\treturn [\"$ArrayBuffer\", base64EncodeArrayBuffer(value)];\n\t\t} else if (value instanceof Uint8Array) {\n\t\t\treturn [\"$Uint8Array\", base64EncodeUint8Array(value)];\n\t\t}\n\n\t\t// Escape user arrays that start with $ by prepending another $\n\t\tif (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.length === 2 &&\n\t\t\ttypeof value[0] === \"string\" &&\n\t\t\tvalue[0].startsWith(\"$\")\n\t\t) {\n\t\t\treturn [\"$\" + value[0], value[1]];\n\t\t}\n\n\t\treturn value;\n\t});\n}\n\n/** Parses JSON with compat for values that BARE & CBOR supports. */\nexport function jsonParseCompat(input: string): any {\n\treturn JSON.parse(input, (_key, value) => {\n\t\t// Handle arrays with $ prefix\n\t\tif (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.length === 2 &&\n\t\t\ttypeof value[0] === \"string\" &&\n\t\t\tvalue[0].startsWith(\"$\")\n\t\t) {\n\t\t\t// Known special types\n\t\t\tif (value[0] === \"$BigInt\") {\n\t\t\t\treturn BigInt(value[1]);\n\t\t\t} else if (value[0] === \"$ArrayBuffer\") {\n\t\t\t\treturn base64DecodeToArrayBuffer(value[1]);\n\t\t\t} else if (value[0] === \"$Uint8Array\") {\n\t\t\t\treturn base64DecodeToUint8Array(value[1]);\n\t\t\t}\n\n\t\t\t// Unescape user arrays that started with $ ($$foo -> $foo)\n\t\t\tif (value[0].startsWith(\"$$\")) {\n\t\t\t\treturn [value[0].substring(1), value[1]];\n\t\t\t}\n\n\t\t\t// Unknown type starting with $ - this is an error\n\t\t\tthrow new Error(\n\t\t\t\t`Unknown JSON encoding type: ${value[0]}. This may indicate corrupted data or a version mismatch.`,\n\t\t\t);\n\t\t}\n\n\t\treturn value;\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-PV22ZBDE.cjs","../../src/actor/log.ts","../../src/actor/utils.ts","../../src/common/actor-router-consts.ts","../../src/serde.ts","../../src/actor/protocol/serde.ts"],"names":["assertUnreachable"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACPO,SAAS,oBAAA,CAAA,EAAuB;AACtC,EAAA,OAAO,yCAAA,eAAyB,CAAA;AACjC;ADSA;AACA;AEZO,SAASA,kBAAAA,CAAkB,CAAA,EAAiB;AAClD,EAAA,oBAAA,CAAqB,CAAA,C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ACD,EAAA;AACN,IAAA;AACD,EAAA;AACD;AJwKY;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-PV22ZBDE.cjs","sourcesContent":[null,"import { getLogger } from \"@/common/log\";\n\n/** Prever to use ActorInstance.rlog child logger. This does not provide context in the log, should only be used as a last resort if you cannot pass the actor's child logger. */\nexport function loggerWithoutContext() {\n\treturn getLogger(\"actor-runtime\");\n}\n","import * as errors from \"./errors\";\nimport { loggerWithoutContext } from \"./log\";\n\nexport function assertUnreachable(x: never): never {\n\tloggerWithoutContext().error({\n\t\tmsg: \"unreachable\",\n\t\tvalue: `${x}`,\n\t\tstack: new Error().stack,\n\t});\n\tthrow new errors.Unreachable(x);\n}\n\nexport const throttle = <\n\t// biome-ignore lint/suspicious/noExplicitAny: we want to allow any function\n\tFn extends (...args: any) => any,\n>(\n\tfn: Fn,\n\tdelay: number,\n) => {\n\tlet lastRan = false;\n\tlet lastArgs: Parameters<Fn> | null = null;\n\n\treturn (...args: Parameters<Fn>) => {\n\t\tif (!lastRan) {\n\t\t\tfn.apply(this, args);\n\t\t\tlastRan = true;\n\t\t\tconst timer = () =>\n\t\t\t\tsetTimeout(() => {\n\t\t\t\t\tlastRan = false;\n\t\t\t\t\tif (lastArgs) {\n\t\t\t\t\t\tfn.apply(this, lastArgs);\n\t\t\t\t\t\tlastRan = true;\n\t\t\t\t\t\tlastArgs = null;\n\t\t\t\t\t\ttimer();\n\t\t\t\t\t}\n\t\t\t\t}, delay);\n\t\t\ttimer();\n\t\t} else lastArgs = args;\n\t};\n};\n\nexport class DeadlineError extends Error {\n\tconstructor() {\n\t\tsuper(\"Promise did not complete before deadline.\");\n\t}\n}\n\nexport function deadline<T>(promise: Promise<T>, timeout: number): Promise<T> {\n\tconst controller = new AbortController();\n\tconst signal = controller.signal;\n\n\t// Set a timeout to abort the operation\n\tconst timeoutId = setTimeout(() => controller.abort(), timeout);\n\n\treturn Promise.race<T>([\n\t\tpromise,\n\t\tnew Promise<T>((_, reject) => {\n\t\t\tsignal.addEventListener(\"abort\", () => reject(new DeadlineError()));\n\t\t}),\n\t]).finally(() => {\n\t\tclearTimeout(timeoutId);\n\t});\n}\n\nexport class Lock<T> {\n\tprivate _locked = false;\n\tprivate _waiting: Array<() => void> = [];\n\n\tconstructor(private _value: T) {}\n\n\tasync lock(fn: (value: T) => Promise<void>): Promise<void> {\n\t\tif (this._locked) {\n\t\t\tawait new Promise<void>((resolve) => this._waiting.push(resolve));\n\t\t}\n\t\tthis._locked = true;\n\n\t\ttry {\n\t\t\tawait fn(this._value);\n\t\t} finally {\n\t\t\tthis._locked = false;\n\t\t\tconst next = this._waiting.shift();\n\t\t\tif (next) next();\n\t\t}\n\t}\n}\n\nexport function generateSecureToken(length = 32) {\n\tconst array = new Uint8Array(length);\n\tcrypto.getRandomValues(array);\n\t// Replace base64 chars that are not URL safe with URL-safe chars and strip padding\n\treturn btoa(String.fromCharCode(...array))\n\t\t.replace(/\\+/g, \"-\")\n\t\t.replace(/\\//g, \"_\")\n\t\t.replace(/=/g, \"\");\n}\n\nexport function generateRandomString(length = 32) {\n\tconst characters =\n\t\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\tlet result = \"\";\n\tfor (let i = 0; i < length; i++) {\n\t\tconst randomIndex = Math.floor(Math.random() * characters.length);\n\t\tresult += characters[randomIndex];\n\t}\n\treturn result;\n}\n","// NOTE: This is in a separate file from the router since it needs to be shared between the client & the server. If this was in the router file, the client would end up importing the *entire* actor router and tree shaking would not work.\n\n// MARK: Paths\nexport const PATH_CONNECT_WEBSOCKET = \"/connect/websocket\";\nexport const PATH_RAW_WEBSOCKET_PREFIX = \"/raw/websocket/\";\n\n// MARK: Headers\nexport const HEADER_ACTOR_QUERY = \"x-rivet-query\";\n\nexport const HEADER_ENCODING = \"x-rivet-encoding\";\n\n// IMPORTANT: Params must be in headers or in an E2EE part of the request (i.e. NOT the URL or query string) in order to ensure that tokens can be securely passed in params.\nexport const HEADER_CONN_PARAMS = \"x-rivet-conn-params\";\n\nexport const HEADER_ACTOR_ID = \"x-rivet-actor\";\n\nexport const HEADER_CONN_ID = \"x-rivet-conn\";\n\nexport const HEADER_CONN_TOKEN = \"x-rivet-conn-token\";\n\nexport const HEADER_RIVET_TOKEN = \"x-rivet-token\";\n\n// MARK: Manager Gateway Headers\nexport const HEADER_RIVET_TARGET = \"x-rivet-target\";\nexport const HEADER_RIVET_ACTOR = \"x-rivet-actor\";\n\n// MARK: WebSocket Protocol Prefixes\n/** Some servers (such as node-ws & Cloudflare) require explicitly match a certain WebSocket protocol. This gives us a static protocol to match against. */\nexport const WS_PROTOCOL_STANDARD = \"rivet\";\nexport const WS_PROTOCOL_TARGET = \"rivet_target.\";\nexport const WS_PROTOCOL_ACTOR = \"rivet_actor.\";\nexport const WS_PROTOCOL_ENCODING = \"rivet_encoding.\";\nexport const WS_PROTOCOL_CONN_PARAMS = \"rivet_conn_params.\";\nexport const WS_PROTOCOL_CONN_ID = \"rivet_conn.\";\nexport const WS_PROTOCOL_CONN_TOKEN = \"rivet_conn_token.\";\nexport const WS_PROTOCOL_TOKEN = \"rivet_token.\";\n\n// MARK: WebSocket Inline Test Protocol Prefixes\nexport const WS_PROTOCOL_TRANSPORT = \"test_transport.\";\nexport const WS_PROTOCOL_PATH = \"test_path.\";\n\n/**\n * Headers that publics can send from public clients.\n *\n * Used for CORS.\n **/\nexport const ALLOWED_PUBLIC_HEADERS = [\n\t\"Content-Type\",\n\t\"User-Agent\",\n\tHEADER_ACTOR_QUERY,\n\tHEADER_ENCODING,\n\tHEADER_CONN_PARAMS,\n\tHEADER_ACTOR_ID,\n\tHEADER_CONN_ID,\n\tHEADER_CONN_TOKEN,\n\tHEADER_RIVET_TARGET,\n\tHEADER_RIVET_ACTOR,\n\tHEADER_RIVET_TOKEN,\n];\n","import * as cbor from \"cbor-x\";\nimport invariant from \"invariant\";\nimport { assertUnreachable } from \"@/common/utils\";\nimport type { VersionedDataHandler } from \"@/common/versioned-data\";\nimport type { Encoding } from \"@/mod\";\nimport { jsonParseCompat, jsonStringifyCompat } from \"./actor/protocol/serde\";\n\nexport function uint8ArrayToBase64(uint8Array: Uint8Array): string {\n\t// Check if Buffer is available (Node.js)\n\tif (typeof Buffer !== \"undefined\") {\n\t\treturn Buffer.from(uint8Array).toString(\"base64\");\n\t}\n\n\t// Browser environment - use btoa\n\tlet binary = \"\";\n\tconst len = uint8Array.byteLength;\n\tfor (let i = 0; i < len; i++) {\n\t\tbinary += String.fromCharCode(uint8Array[i]);\n\t}\n\treturn btoa(binary);\n}\n\nexport function encodingIsBinary(encoding: Encoding): boolean {\n\tif (encoding === \"json\") {\n\t\treturn false;\n\t} else if (encoding === \"cbor\" || encoding === \"bare\") {\n\t\treturn true;\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function contentTypeForEncoding(encoding: Encoding): string {\n\tif (encoding === \"json\") {\n\t\treturn \"application/json\";\n\t} else if (encoding === \"cbor\" || encoding === \"bare\") {\n\t\treturn \"application/octet-stream\";\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function wsBinaryTypeForEncoding(\n\tencoding: Encoding,\n): \"arraybuffer\" | \"blob\" {\n\tif (encoding === \"json\") {\n\t\treturn \"blob\";\n\t} else if (encoding === \"cbor\" || encoding === \"bare\") {\n\t\treturn \"arraybuffer\";\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function serializeWithEncoding<T>(\n\tencoding: Encoding,\n\tvalue: T,\n\tversionedDataHandler: VersionedDataHandler<T> | undefined,\n): Uint8Array | string {\n\tif (encoding === \"json\") {\n\t\treturn jsonStringifyCompat(value);\n\t} else if (encoding === \"cbor\") {\n\t\treturn cbor.encode(value);\n\t} else if (encoding === \"bare\") {\n\t\tif (!versionedDataHandler) {\n\t\t\tthrow new Error(\"VersionedDataHandler is required for 'bare' encoding\");\n\t\t}\n\t\treturn versionedDataHandler.serializeWithEmbeddedVersion(value);\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n\nexport function deserializeWithEncoding<T>(\n\tencoding: Encoding,\n\tbuffer: Uint8Array | string,\n\tversionedDataHandler: VersionedDataHandler<T> | undefined,\n): T {\n\tif (encoding === \"json\") {\n\t\tif (typeof buffer === \"string\") {\n\t\t\treturn jsonParseCompat(buffer);\n\t\t} else {\n\t\t\tconst decoder = new TextDecoder(\"utf-8\");\n\t\t\tconst jsonString = decoder.decode(buffer);\n\t\t\treturn jsonParseCompat(jsonString);\n\t\t}\n\t} else if (encoding === \"cbor\") {\n\t\tinvariant(\n\t\t\ttypeof buffer !== \"string\",\n\t\t\t\"buffer cannot be string for cbor encoding\",\n\t\t);\n\t\treturn cbor.decode(buffer);\n\t} else if (encoding === \"bare\") {\n\t\tinvariant(\n\t\t\ttypeof buffer !== \"string\",\n\t\t\t\"buffer cannot be string for bare encoding\",\n\t\t);\n\t\tif (!versionedDataHandler) {\n\t\t\tthrow new Error(\"VersionedDataHandler is required for 'bare' encoding\");\n\t\t}\n\t\treturn versionedDataHandler.deserializeWithEmbeddedVersion(buffer);\n\t} else {\n\t\tassertUnreachable(encoding);\n\t}\n}\n","import * as cbor from \"cbor-x\";\nimport { z } from \"zod\";\nimport * as errors from \"@/actor/errors\";\nimport type { VersionedDataHandler } from \"@/common/versioned-data\";\nimport { serializeWithEncoding } from \"@/serde\";\nimport { loggerWithoutContext } from \"../log\";\nimport { assertUnreachable } from \"../utils\";\n\n/** Data that can be deserialized. */\nexport type InputData = string | Buffer | Blob | ArrayBufferLike | Uint8Array;\n\n/** Data that's been serialized. */\nexport type OutputData = string | Uint8Array;\n\nexport const EncodingSchema = z.enum([\"json\", \"cbor\", \"bare\"]);\n\n/**\n * Encoding used to communicate between the client & actor.\n */\nexport type Encoding = z.infer<typeof EncodingSchema>;\n\n/**\n * Helper class that helps serialize data without re-serializing for the same encoding.\n */\nexport class CachedSerializer<T> {\n\t#data: T;\n\t#cache = new Map<Encoding, OutputData>();\n\t#versionedDataHandler: VersionedDataHandler<T>;\n\n\tconstructor(data: T, versionedDataHandler: VersionedDataHandler<T>) {\n\t\tthis.#data = data;\n\t\tthis.#versionedDataHandler = versionedDataHandler;\n\t}\n\n\tpublic get rawData(): T {\n\t\treturn this.#data;\n\t}\n\n\tpublic serialize(encoding: Encoding): OutputData {\n\t\tconst cached = this.#cache.get(encoding);\n\t\tif (cached) {\n\t\t\treturn cached;\n\t\t} else {\n\t\t\tconst serialized = serializeWithEncoding(\n\t\t\t\tencoding,\n\t\t\t\tthis.#data,\n\t\t\t\tthis.#versionedDataHandler,\n\t\t\t);\n\t\t\tthis.#cache.set(encoding, serialized);\n\t\t\treturn serialized;\n\t\t}\n\t}\n}\n\n///**\n// * Use `CachedSerializer` if serializing the same data repeatedly.\n// */\n//export function serialize<T>(value: T, encoding: Encoding): OutputData {\n//\tif (encoding === \"json\") {\n//\t\treturn JSON.stringify(value);\n//\t} else if (encoding === \"cbor\") {\n//\t\t// TODO: Remove this hack, but cbor-x can't handle anything extra in data structures\n//\t\tconst cleanValue = JSON.parse(JSON.stringify(value));\n//\t\treturn cbor.encode(cleanValue);\n//\t} else {\n//\t\tassertUnreachable(encoding);\n//\t}\n//}\n//\n//export async function deserialize(data: InputData, encoding: Encoding) {\n//\tif (encoding === \"json\") {\n//\t\tif (typeof data !== \"string\") {\n//\t\t\tlogger().warn(\"received non-string for json parse\");\n//\t\t\tthrow new errors.MalformedMessage();\n//\t\t} else {\n//\t\t\treturn JSON.parse(data);\n//\t\t}\n//\t} else if (encoding === \"cbor\") {\n//\t\tif (data instanceof Blob) {\n//\t\t\tconst arrayBuffer = await data.arrayBuffer();\n//\t\t\treturn cbor.decode(new Uint8Array(arrayBuffer));\n//\t\t} else if (data instanceof Uint8Array) {\n//\t\t\treturn cbor.decode(data);\n//\t\t} else if (\n//\t\t\tdata instanceof ArrayBuffer ||\n//\t\t\tdata instanceof SharedArrayBuffer\n//\t\t) {\n//\t\t\treturn cbor.decode(new Uint8Array(data));\n//\t\t} else {\n//\t\t\tlogger().warn(\"received non-binary type for cbor parse\");\n//\t\t\tthrow new errors.MalformedMessage();\n//\t\t}\n//\t} else {\n//\t\tassertUnreachable(encoding);\n//\t}\n//}\n\n// TODO: Encode base 128\nfunction base64EncodeUint8Array(uint8Array: Uint8Array): string {\n\tlet binary = \"\";\n\tconst len = uint8Array.byteLength;\n\tfor (let i = 0; i < len; i++) {\n\t\tbinary += String.fromCharCode(uint8Array[i]);\n\t}\n\treturn btoa(binary);\n}\n\nfunction base64EncodeArrayBuffer(arrayBuffer: ArrayBuffer): string {\n\tconst uint8Array = new Uint8Array(arrayBuffer);\n\treturn base64EncodeUint8Array(uint8Array);\n}\n\n/** Converts data that was encoded to a string. Some formats (like SSE) don't support raw binary data. */\nexport function encodeDataToString(message: OutputData): string {\n\tif (typeof message === \"string\") {\n\t\treturn message;\n\t} else if (message instanceof ArrayBuffer) {\n\t\treturn base64EncodeArrayBuffer(message);\n\t} else if (message instanceof Uint8Array) {\n\t\treturn base64EncodeUint8Array(message);\n\t} else {\n\t\tassertUnreachable(message);\n\t}\n}\n\nfunction base64DecodeToUint8Array(base64: string): Uint8Array {\n\t// Check if Buffer is available (Node.js)\n\tif (typeof Buffer !== \"undefined\") {\n\t\treturn new Uint8Array(Buffer.from(base64, \"base64\"));\n\t}\n\n\t// Browser environment - use atob\n\tconst binary = atob(base64);\n\tconst len = binary.length;\n\tconst bytes = new Uint8Array(len);\n\tfor (let i = 0; i < len; i++) {\n\t\tbytes[i] = binary.charCodeAt(i);\n\t}\n\treturn bytes;\n}\n\nfunction base64DecodeToArrayBuffer(base64: string): ArrayBuffer {\n\treturn base64DecodeToUint8Array(base64).buffer as ArrayBuffer;\n}\n\n/** Stringifies with compat for values that BARE & CBOR supports. */\nexport function jsonStringifyCompat(input: any): string {\n\treturn JSON.stringify(input, (_key, value) => {\n\t\tif (typeof value === \"bigint\") {\n\t\t\treturn [\"$BigInt\", value.toString()];\n\t\t} else if (value instanceof ArrayBuffer) {\n\t\t\treturn [\"$ArrayBuffer\", base64EncodeArrayBuffer(value)];\n\t\t} else if (value instanceof Uint8Array) {\n\t\t\treturn [\"$Uint8Array\", base64EncodeUint8Array(value)];\n\t\t}\n\n\t\t// Escape user arrays that start with $ by prepending another $\n\t\tif (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.length === 2 &&\n\t\t\ttypeof value[0] === \"string\" &&\n\t\t\tvalue[0].startsWith(\"$\")\n\t\t) {\n\t\t\treturn [\"$\" + value[0], value[1]];\n\t\t}\n\n\t\treturn value;\n\t});\n}\n\n/** Parses JSON with compat for values that BARE & CBOR supports. */\nexport function jsonParseCompat(input: string): any {\n\treturn JSON.parse(input, (_key, value) => {\n\t\t// Handle arrays with $ prefix\n\t\tif (\n\t\t\tArray.isArray(value) &&\n\t\t\tvalue.length === 2 &&\n\t\t\ttypeof value[0] === \"string\" &&\n\t\t\tvalue[0].startsWith(\"$\")\n\t\t) {\n\t\t\t// Known special types\n\t\t\tif (value[0] === \"$BigInt\") {\n\t\t\t\treturn BigInt(value[1]);\n\t\t\t} else if (value[0] === \"$ArrayBuffer\") {\n\t\t\t\treturn base64DecodeToArrayBuffer(value[1]);\n\t\t\t} else if (value[0] === \"$Uint8Array\") {\n\t\t\t\treturn base64DecodeToUint8Array(value[1]);\n\t\t\t}\n\n\t\t\t// Unescape user arrays that started with $ ($$foo -> $foo)\n\t\t\tif (value[0].startsWith(\"$$\")) {\n\t\t\t\treturn [value[0].substring(1), value[1]];\n\t\t\t}\n\n\t\t\t// Unknown type starting with $ - this is an error\n\t\t\tthrow new Error(\n\t\t\t\t`Unknown JSON encoding type: ${value[0]}. This may indicate corrupted data or a version mismatch.`,\n\t\t\t);\n\t\t}\n\n\t\treturn value;\n\t});\n}\n"]}
|
|
@@ -208,7 +208,7 @@ function noopNext() {
|
|
|
208
208
|
// package.json
|
|
209
209
|
var package_default = {
|
|
210
210
|
name: "rivetkit",
|
|
211
|
-
version: "2.0.
|
|
211
|
+
version: "2.0.20",
|
|
212
212
|
description: "Lightweight libraries for building stateful actors on edge platforms",
|
|
213
213
|
license: "Apache-2.0",
|
|
214
214
|
keywords: [
|
|
@@ -574,4 +574,4 @@ export {
|
|
|
574
574
|
bufferToArrayBuffer,
|
|
575
575
|
combineUrlPath
|
|
576
576
|
};
|
|
577
|
-
//# sourceMappingURL=chunk-
|
|
577
|
+
//# sourceMappingURL=chunk-QMVCFQ37.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/common/utils.ts","../../package.json","../../src/utils.ts"],"sourcesContent":["import type { Next } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport * as errors from \"@/actor/errors\";\nimport { getEnvUniversal } from \"@/utils\";\nimport type { Logger } from \"./log\";\n\nexport function assertUnreachable(x: never): never {\n\tthrow new Error(`Unreachable case: ${x}`);\n}\n\n/**\n * Safely stringifies an object, ensuring that the stringified object is under a certain size.\n * @param obj any object to stringify\n * @param maxSize maximum size of the stringified object in bytes\n * @returns stringified object\n */\nexport function safeStringify(obj: unknown, maxSize: number) {\n\tlet size = 0;\n\n\tfunction replacer(key: string, value: unknown) {\n\t\tif (value === null || value === undefined) return value;\n\t\tconst valueSize =\n\t\t\ttypeof value === \"string\" ? value.length : JSON.stringify(value).length;\n\t\tsize += key.length + valueSize;\n\n\t\tif (size > maxSize) {\n\t\t\tthrow new Error(`JSON object exceeds size limit of ${maxSize} bytes.`);\n\t\t}\n\n\t\treturn value;\n\t}\n\n\treturn JSON.stringify(obj, replacer);\n}\n\n// TODO: Instead of doing this, use a temp var for state and attempt to write\n// it. Roll back state if fails to serialize.\n\n/**\n * Check if a value is CBOR serializable.\n * Optionally pass an onInvalid callback to receive the path to invalid values.\n *\n * For a complete list of supported CBOR tags, see:\n * https://github.com/kriszyp/cbor-x/blob/cc1cf9df8ba72288c7842af1dd374d73e34cdbc1/README.md#list-of-supported-tags-for-decoding\n */\nexport function isCborSerializable(\n\tvalue: unknown,\n\tonInvalid?: (path: string) => void,\n\tcurrentPath = \"\",\n): boolean {\n\t// Handle primitive types directly\n\tif (value === null || value === undefined) {\n\t\treturn true;\n\t}\n\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tonInvalid?.(currentPath);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tif (typeof value === \"boolean\" || typeof value === \"string\") {\n\t\treturn true;\n\t}\n\n\t// Handle BigInt (CBOR tags 2 and 3)\n\tif (typeof value === \"bigint\") {\n\t\treturn true;\n\t}\n\n\t// Handle Date objects (CBOR tags 0 and 1)\n\tif (value instanceof Date) {\n\t\treturn true;\n\t}\n\n\t// Handle typed arrays (CBOR tags 64-82)\n\tif (\n\t\tvalue instanceof Uint8Array ||\n\t\tvalue instanceof Uint8ClampedArray ||\n\t\tvalue instanceof Uint16Array ||\n\t\tvalue instanceof Uint32Array ||\n\t\tvalue instanceof BigUint64Array ||\n\t\tvalue instanceof Int8Array ||\n\t\tvalue instanceof Int16Array ||\n\t\tvalue instanceof Int32Array ||\n\t\tvalue instanceof BigInt64Array ||\n\t\tvalue instanceof Float32Array ||\n\t\tvalue instanceof Float64Array\n\t) {\n\t\treturn true;\n\t}\n\n\t// Handle Map (CBOR tag 259)\n\tif (value instanceof Map) {\n\t\tfor (const [key, val] of value.entries()) {\n\t\t\tconst keyPath = currentPath\n\t\t\t\t? `${currentPath}.key(${String(key)})`\n\t\t\t\t: `key(${String(key)})`;\n\t\t\tconst valPath = currentPath\n\t\t\t\t? `${currentPath}.value(${String(key)})`\n\t\t\t\t: `value(${String(key)})`;\n\t\t\tif (\n\t\t\t\t!isCborSerializable(key, onInvalid, keyPath) ||\n\t\t\t\t!isCborSerializable(val, onInvalid, valPath)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle Set (CBOR tag 258)\n\tif (value instanceof Set) {\n\t\tlet index = 0;\n\t\tfor (const item of value.values()) {\n\t\t\tconst itemPath = currentPath\n\t\t\t\t? `${currentPath}.set[${index}]`\n\t\t\t\t: `set[${index}]`;\n\t\t\tif (!isCborSerializable(item, onInvalid, itemPath)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle RegExp (CBOR tag 27)\n\tif (value instanceof RegExp) {\n\t\treturn true;\n\t}\n\n\t// Handle Error objects (CBOR tag 27)\n\tif (value instanceof Error) {\n\t\treturn true;\n\t}\n\n\t// Handle arrays\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;\n\t\t\tif (!isCborSerializable(value[i], onInvalid, itemPath)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle plain objects and records (CBOR tags 105, 51, 57344-57599)\n\tif (typeof value === \"object\") {\n\t\t// Allow plain objects and objects with prototypes (for records and named objects)\n\t\tconst proto = Object.getPrototypeOf(value);\n\t\tif (proto !== null && proto !== Object.prototype) {\n\t\t\t// Check if it's a known serializable object type\n\t\t\tconst protoConstructor = value.constructor;\n\t\t\tif (protoConstructor && typeof protoConstructor.name === \"string\") {\n\t\t\t\t// Allow objects with named constructors (records, named objects)\n\t\t\t\t// This includes user-defined classes and built-in objects\n\t\t\t\t// that CBOR can serialize with tag 27 or record tags\n\t\t\t}\n\t\t}\n\n\t\t// Check all properties recursively\n\t\tfor (const key in value) {\n\t\t\tconst propPath = currentPath ? `${currentPath}.${key}` : key;\n\t\t\tif (\n\t\t\t\t!isCborSerializable(\n\t\t\t\t\tvalue[key as keyof typeof value],\n\t\t\t\t\tonInvalid,\n\t\t\t\t\tpropPath,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Not serializable\n\tonInvalid?.(currentPath);\n\treturn false;\n}\n\nexport interface DeconstructedError {\n\t__type: \"ActorError\";\n\tstatusCode: ContentfulStatusCode;\n\tpublic: boolean;\n\tgroup: string;\n\tcode: string;\n\tmessage: string;\n\tmetadata?: unknown;\n}\n\n/** Deconstructs error in to components that are used to build responses. */\nexport function deconstructError(\n\terror: unknown,\n\tlogger: Logger,\n\textraLog: Record<string, unknown>,\n\texposeInternalError = false,\n): DeconstructedError {\n\t// Build response error information. Only return errors if flagged as public in order to prevent leaking internal behavior.\n\t//\n\t// We log the error here instead of after generating the code & message because we need to log the original error, not the masked internal error.\n\tlet statusCode: ContentfulStatusCode;\n\tlet public_: boolean;\n\tlet group: string;\n\tlet code: string;\n\tlet message: string;\n\tlet metadata: unknown;\n\tif (errors.ActorError.isActorError(error) && error.public) {\n\t\t// Check if error has statusCode (could be ActorError instance or DeconstructedError)\n\t\tstatusCode = (\n\t\t\t\"statusCode\" in error && error.statusCode ? error.statusCode : 400\n\t\t) as ContentfulStatusCode;\n\t\tpublic_ = true;\n\t\tgroup = error.group;\n\t\tcode = error.code;\n\t\tmessage = getErrorMessage(error);\n\t\tmetadata = error.metadata;\n\n\t\tlogger.info({\n\t\t\tmsg: \"public error\",\n\t\t\tgroup,\n\t\t\tcode,\n\t\t\tmessage,\n\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t...extraLog,\n\t\t});\n\t} else if (exposeInternalError) {\n\t\tif (errors.ActorError.isActorError(error)) {\n\t\t\tstatusCode = 500;\n\t\t\tpublic_ = false;\n\t\t\tgroup = error.group;\n\t\t\tcode = error.code;\n\t\t\tmessage = getErrorMessage(error);\n\t\t\tmetadata = error.metadata;\n\n\t\t\tlogger.info({\n\t\t\t\tmsg: \"internal error\",\n\t\t\t\tgroup,\n\t\t\t\tcode,\n\t\t\t\tmessage,\n\t\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t\t...extraLog,\n\t\t\t});\n\t\t} else {\n\t\t\tstatusCode = 500;\n\t\t\tpublic_ = false;\n\t\t\tgroup = \"internal\";\n\t\t\tcode = errors.INTERNAL_ERROR_CODE;\n\t\t\tmessage = getErrorMessage(error);\n\n\t\t\tlogger.info({\n\t\t\t\tmsg: \"internal error\",\n\t\t\t\tgroup,\n\t\t\t\tcode,\n\t\t\t\tmessage,\n\t\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t\t...extraLog,\n\t\t\t});\n\t\t}\n\t} else {\n\t\tstatusCode = 500;\n\t\tpublic_ = false;\n\t\tgroup = \"internal\";\n\t\tcode = errors.INTERNAL_ERROR_CODE;\n\t\tmessage = errors.INTERNAL_ERROR_DESCRIPTION;\n\t\tmetadata = {\n\t\t\t//url: `https://hub.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,\n\t\t} satisfies errors.InternalErrorMetadata;\n\n\t\tlogger.warn({\n\t\t\tmsg: \"internal error\",\n\t\t\terror: getErrorMessage(error),\n\t\t\tstack: (error as Error)?.stack,\n\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t...extraLog,\n\t\t});\n\t}\n\n\treturn {\n\t\t__type: \"ActorError\",\n\t\tstatusCode,\n\t\tpublic: public_,\n\t\tgroup,\n\t\tcode,\n\t\tmessage,\n\t\tmetadata,\n\t};\n}\n\nexport function stringifyError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tif (\n\t\t\ttypeof process !== \"undefined\" &&\n\t\t\tgetEnvUniversal(\"_RIVETKIT_ERROR_STACK\") === \"1\"\n\t\t) {\n\t\t\treturn `${error.name}: ${error.message}${error.stack ? `\\n${error.stack}` : \"\"}`;\n\t\t} else {\n\t\t\treturn `${error.name}: ${error.message}`;\n\t\t}\n\t} else if (typeof error === \"string\") {\n\t\treturn error;\n\t} else if (typeof error === \"object\" && error !== null) {\n\t\ttry {\n\t\t\treturn `${JSON.stringify(error)}`;\n\t\t} catch {\n\t\t\treturn \"[cannot stringify error]\";\n\t\t}\n\t} else {\n\t\treturn `Unknown error: ${getErrorMessage(error)}`;\n\t}\n}\n\nfunction getErrorMessage(err: unknown): string {\n\tif (\n\t\terr &&\n\t\ttypeof err === \"object\" &&\n\t\t\"message\" in err &&\n\t\ttypeof err.message === \"string\"\n\t) {\n\t\treturn err.message;\n\t} else {\n\t\treturn String(err);\n\t}\n}\n\n/** Generates a `Next` handler to pass to middleware in order to be able to call arbitrary middleware. */\nexport function noopNext(): Next {\n\treturn async () => {};\n}\n","{\n \"name\": \"rivetkit\",\n \"version\": \"2.0.18\",\n \"description\": \"Lightweight libraries for building stateful actors on edge platforms\",\n \"license\": \"Apache-2.0\",\n \"keywords\": [\n \"rivetkit\",\n \"stateful\",\n \"serverless\",\n \"actors\",\n \"agents\",\n \"realtime\",\n \"websocket\",\n \"actors\",\n \"framework\"\n ],\n \"files\": [\n \"dist\",\n \"src\",\n \"deno.json\",\n \"bun.json\",\n \"package.json\"\n ],\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/tsup/mod.d.ts\",\n \"default\": \"./dist/tsup/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/mod.d.cts\",\n \"default\": \"./dist/tsup/mod.cjs\"\n }\n },\n \"./client\": {\n \"import\": {\n \"types\": \"./dist/tsup/client/mod.d.ts\",\n \"default\": \"./dist/tsup/client/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/client/mod.d.cts\",\n \"default\": \"./dist/tsup/client/mod.cjs\"\n }\n },\n \"./log\": {\n \"import\": {\n \"types\": \"./dist/tsup/common/log.d.ts\",\n \"default\": \"./dist/tsup/common/log.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/common/log.d.cts\",\n \"default\": \"./dist/tsup/common/log.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/tsup/actor/errors.d.ts\",\n \"default\": \"./dist/tsup/actor/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/actor/errors.d.cts\",\n \"default\": \"./dist/tsup/actor/errors.cjs\"\n }\n },\n \"./utils\": {\n \"import\": {\n \"types\": \"./dist/tsup/utils.d.ts\",\n \"default\": \"./dist/tsup/utils.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/utils.d.cts\",\n \"default\": \"./dist/tsup/utils.cjs\"\n }\n },\n \"./driver-helpers\": {\n \"import\": {\n \"types\": \"./dist/tsup/driver-helpers/mod.d.ts\",\n \"default\": \"./dist/tsup/driver-helpers/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/driver-helpers/mod.d.cts\",\n \"default\": \"./dist/tsup/driver-helpers/mod.cjs\"\n }\n },\n \"./driver-helpers/websocket\": {\n \"import\": {\n \"types\": \"./dist/tsup/common/websocket.d.ts\",\n \"default\": \"./dist/tsup/common/websocket.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/common/websocket.d.cts\",\n \"default\": \"./dist/tsup/common/websocket.cjs\"\n }\n },\n \"./driver-test-suite\": {\n \"import\": {\n \"types\": \"./dist/tsup/driver-test-suite/mod.d.ts\",\n \"default\": \"./dist/tsup/driver-test-suite/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/driver-test-suite/mod.d.cts\",\n \"default\": \"./dist/tsup/driver-test-suite/mod.cjs\"\n }\n },\n \"./topologies/coordinate\": {\n \"import\": {\n \"types\": \"./dist/tsup/topologies/coordinate/mod.d.ts\",\n \"default\": \"./dist/tsup/topologies/coordinate/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/topologies/coordinate/mod.d.cts\",\n \"default\": \"./dist/tsup/topologies/coordinate/mod.cjs\"\n }\n },\n \"./topologies/partition\": {\n \"import\": {\n \"types\": \"./dist/tsup/topologies/partition/mod.d.ts\",\n \"default\": \"./dist/tsup/topologies/partition/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/topologies/partition/mod.d.cts\",\n \"default\": \"./dist/tsup/topologies/partition/mod.cjs\"\n }\n },\n \"./test\": {\n \"import\": {\n \"types\": \"./dist/tsup/test/mod.d.ts\",\n \"default\": \"./dist/tsup/test/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/test/mod.d.cts\",\n \"default\": \"./dist/tsup/test/mod.cjs\"\n }\n },\n \"./inspector\": {\n \"import\": {\n \"types\": \"./dist/tsup/inspector/mod.d.ts\",\n \"default\": \"./dist/tsup/inspector/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/inspector/mod.d.cts\",\n \"default\": \"./dist/tsup/inspector/mod.cjs\"\n }\n }\n },\n \"engines\": {\n \"node\": \">=22.0.0\"\n },\n \"sideEffects\": [\n \"./dist/tsup/chunk-*.js\",\n \"./dist/tsup/chunk-*.cjs\"\n ],\n \"scripts\": {\n \"build\": \"tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/topologies/coordinate/mod.ts src/topologies/partition/mod.ts src/utils.ts src/driver-helpers/mod.ts src/driver-test-suite/mod.ts src/test/mod.ts src/inspector/mod.ts\",\n \"build:schema\": \"./scripts/compile-bare.ts compile schemas/client-protocol/v1.bare -o dist/schemas/client-protocol/v1.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v1.bare -o dist/schemas/file-system-driver/v1.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v1.bare -o dist/schemas/actor-persist/v1.ts\",\n \"check-types\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"dump-openapi\": \"tsx scripts/dump-openapi.ts\"\n },\n \"dependencies\": {\n \"@bare-ts/lib\": \"~0.3.0\",\n \"@hono/standard-validator\": \"^0.1.3\",\n \"@hono/zod-openapi\": \"^0.19.10\",\n \"@rivetkit/engine-runner\": \"https://pkg.pr.new/rivet-dev/engine/@rivetkit/engine-runner@6659217\",\n \"@rivetkit/fast-json-patch\": \"^3.1.2\",\n \"cbor-x\": \"^1.6.0\",\n \"hono\": \"^4.7.0\",\n \"invariant\": \"^2.2.4\",\n \"nanoevents\": \"^9.1.0\",\n \"on-change\": \"^5.0.1\",\n \"p-retry\": \"^6.2.1\",\n \"pino\": \"^9.5.0\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@bare-ts/tools\": \"^0.13.0\",\n \"@hono/node-server\": \"^1.18.2\",\n \"@hono/node-ws\": \"^1.1.1\",\n \"@types/invariant\": \"^2\",\n \"@types/node\": \"^22.13.1\",\n \"@types/ws\": \"^8\",\n \"@vitest/ui\": \"3.1.1\",\n \"bundle-require\": \"^5.1.0\",\n \"eventsource\": \"^4.0.0\",\n \"tsup\": \"^8.4.0\",\n \"tsx\": \"^4.19.4\",\n \"typescript\": \"^5.7.3\",\n \"vitest\": \"^3.1.1\",\n \"ws\": \"^8.18.1\"\n },\n \"peerDependencies\": {\n \"@hono/node-server\": \"^1.14.0\",\n \"@hono/node-ws\": \"^1.1.1\",\n \"eventsource\": \"^4.0.0\",\n \"ws\": \"^8.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"@hono/node-server\": {\n \"optional\": true\n },\n \"@hono/node-ws\": {\n \"optional\": true\n },\n \"eventsource\": {\n \"optional\": true\n },\n \"ws\": {\n \"optional\": true\n }\n },\n \"stableVersion\": \"0.8.0\"\n}\n","export { stringifyError } from \"@/common/utils\";\nexport { assertUnreachable } from \"./common/utils\";\n\nimport type { Context as HonoContext, Handler as HonoHandler } from \"hono\";\n\nimport pkgJson from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION = pkgJson.version;\n\nlet _userAgent: string | undefined;\n\nexport function httpUserAgent(): string {\n\t// Return cached value if already initialized\n\tif (_userAgent !== undefined) {\n\t\treturn _userAgent;\n\t}\n\n\t// Library\n\tlet userAgent = `RivetKit/${VERSION}`;\n\n\t// Navigator\n\tconst navigatorObj = typeof navigator !== \"undefined\" ? navigator : undefined;\n\tif (navigatorObj?.userAgent) userAgent += ` ${navigatorObj.userAgent}`;\n\n\t_userAgent = userAgent;\n\n\treturn userAgent;\n}\n\nexport type UpgradeWebSocket = (\n\tcreateEvents: (c: HonoContext) => any,\n) => HonoHandler;\n\nexport type GetUpgradeWebSocket = () => UpgradeWebSocket;\n\nexport function getEnvUniversal(key: string): string | undefined {\n\tif (typeof Deno !== \"undefined\") {\n\t\treturn Deno.env.get(key);\n\t} else if (typeof process !== \"undefined\") {\n\t\t// Do this after Deno since `process` is sometimes polyfilled\n\t\treturn process.env[key];\n\t}\n}\n\nexport function dbg<T>(x: T): T {\n\tconsole.trace(`=== DEBUG ===\\n${x}`);\n\treturn x;\n}\n\n/**\n * Converts various ArrayBuffer-like types to Uint8Array.\n * Handles ArrayBuffer, ArrayBufferView (including typed arrays), and passes through existing Uint8Array.\n *\n * @param data - The ArrayBuffer or ArrayBufferView to convert\n * @returns A Uint8Array view of the data\n */\nexport function toUint8Array(data: ArrayBuffer | ArrayBufferView): Uint8Array {\n\tif (data instanceof Uint8Array) {\n\t\treturn data;\n\t} else if (data instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(data);\n\t} else if (ArrayBuffer.isView(data)) {\n\t\t// Handle other ArrayBufferView types (Int8Array, Uint16Array, DataView, etc.)\n\t\treturn new Uint8Array(\n\t\t\tdata.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength),\n\t\t);\n\t} else {\n\t\tthrow new TypeError(\"Input must be ArrayBuffer or ArrayBufferView\");\n\t}\n}\n\n// Long timeouts\n//\n// JavaScript timers use a signed 32-bit integer for delays, so values above 2^31-1 (~24.8 days)\n// are not reliable and may fire immediately or overflow.\n//\n// https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#maximum_delay_value\nconst TIMEOUT_MAX = 2147483647; // 2^31-1\n\nexport type LongTimeoutHandle = { abort: () => void };\n\n/**\n * Polyfill for Promise.withResolvers().\n *\n * This is specifically for Cloudflare Workers. Their implementation of Promise.withResolvers does not work correctly.\n */\nexport function promiseWithResolvers<T>(): {\n\tpromise: Promise<T>;\n\tresolve: (value: T | PromiseLike<T>) => void;\n\treject: (reason?: any) => void;\n} {\n\tlet resolve!: (value: T | PromiseLike<T>) => void;\n\tlet reject!: (reason?: any) => void;\n\tconst promise = new Promise<T>((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\treturn { promise, resolve, reject };\n}\n\nexport function setLongTimeout(\n\tlistener: () => void,\n\tafter: number,\n): LongTimeoutHandle {\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\n\tfunction start(remaining: number) {\n\t\tif (remaining <= TIMEOUT_MAX) {\n\t\t\ttimeout = setTimeout(listener, remaining);\n\t\t} else {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tstart(remaining - TIMEOUT_MAX);\n\t\t\t}, TIMEOUT_MAX);\n\t\t}\n\t}\n\n\tstart(after);\n\n\treturn {\n\t\tabort: () => {\n\t\t\tif (timeout !== undefined) clearTimeout(timeout);\n\t\t},\n\t};\n}\n\n/**\n * A tiny utility that coalesces/enqueues async operations so only the latest\n * queued task runs per cycle, while callers receive a promise that resolves\n * when the task for the cycle they joined has completed.\n */\nexport class SinglePromiseQueue {\n\t/** Next operation to execute in the queue. If attempting to enqueue another op, it will override the existing op. */\n\t#queuedOp?: () => Promise<void>;\n\n\t/** The currently running promise of #drainLoop. Do not await this, instead await `pending` to await the current cycle. */\n\trunningDrainLoop?: Promise<void>;\n\n\t/** Pending resolver fro the currently queued entry. */\n\t#pending?: ReturnType<typeof promiseWithResolvers<void>>;\n\n\t/** Queue the next operation and return a promise that resolves when it flushes. */\n\tenqueue(op: () => Promise<void>): Promise<void> {\n\t\t// Replace any previously queued operation with the latest one\n\t\tthis.#queuedOp = op;\n\n\t\t// Ensure a shared resolver exists for all callers in this cycle\n\t\tif (!this.#pending) {\n\t\t\tthis.#pending = promiseWithResolvers<void>();\n\t\t}\n\n\t\tconst waitForThisCycle = this.#pending.promise;\n\n\t\t// Start runner if not already running\n\t\tif (!this.runningDrainLoop) {\n\t\t\tthis.runningDrainLoop = this.#drainLoop();\n\t\t}\n\n\t\treturn waitForThisCycle;\n\t}\n\n\t/** Drain queued operations sequentially until there is nothing left. */\n\tasync #drainLoop(): Promise<void> {\n\t\ttry {\n\t\t\twhile (this.#queuedOp) {\n\t\t\t\t// Capture current cycle resolver then reset for the next cycle\n\t\t\t\tconst resolver = this.#pending;\n\t\t\t\tthis.#pending = undefined;\n\n\t\t\t\t// Capture and clear the currently queued operation\n\t\t\t\tconst op = this.#queuedOp;\n\t\t\t\tthis.#queuedOp = undefined;\n\n\t\t\t\ttry {\n\t\t\t\t\tawait op();\n\t\t\t\t} catch {\n\t\t\t\t\t// Swallow errors: callers only await cycle completion, not success\n\t\t\t\t}\n\n\t\t\t\t// Notify all waiters for this cycle\n\t\t\t\tresolver?.resolve();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.runningDrainLoop = undefined;\n\t\t}\n\t}\n}\n\nexport function bufferToArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffer {\n\treturn buf.buffer.slice(\n\t\tbuf.byteOffset,\n\t\tbuf.byteOffset + buf.byteLength,\n\t) as ArrayBuffer;\n}\n\n/**\n * Properly combines a base URL endpoint with a path, preserving any base path in the endpoint.\n *\n * @example\n * combineUrlPath(\"http://localhost:8787/rivet\", \"/actors/action\")\n * // Returns: \"http://localhost:8787/rivet/actors/action\"\n *\n * @example\n * combineUrlPath(\"http://localhost:8787/rivet\", \"/actors?type=foo\", { namespace: \"test\" })\n * // Returns: \"http://localhost:8787/rivet/actors?type=foo&namespace=test\"\n *\n * @param endpoint The base URL endpoint that may contain a path component\n * @param path The path to append to the endpoint (may include query parameters)\n * @param queryParams Optional additional query parameters to append\n * @returns The properly combined URL string\n */\nexport function combineUrlPath(\n\tendpoint: string,\n\tpath: string,\n\tqueryParams?: Record<string, string | undefined>,\n): string {\n\tconst baseUrl = new URL(endpoint);\n\n\t// Extract path and query from the provided path\n\tconst pathParts = path.split(\"?\");\n\tconst pathOnly = pathParts[0];\n\tconst existingQuery = pathParts[1] || \"\";\n\n\t// Remove trailing slash from base path and ensure path starts with /\n\tconst basePath = baseUrl.pathname.replace(/\\/$/, \"\");\n\tconst cleanPath = pathOnly.startsWith(\"/\") ? pathOnly : `/${pathOnly}`;\n\t// Combine paths and remove any double slashes\n\tconst fullPath = (basePath + cleanPath).replace(/\\/\\//g, \"/\");\n\n\t// Build query string\n\tconst queryParts: string[] = [];\n\tif (existingQuery) {\n\t\tqueryParts.push(existingQuery);\n\t}\n\tif (queryParams) {\n\t\tfor (const [key, value] of Object.entries(queryParams)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tqueryParts.push(\n\t\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst fullQuery = queryParts.length > 0 ? `?${queryParts.join(\"&\")}` : \"\";\n\treturn `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;\n}\n"],"mappings":";;;;;;;AAMO,SAAS,kBAAkB,GAAiB;AAClD,QAAM,IAAI,MAAM,qBAAqB,CAAC,EAAE;AACzC;AAqCO,SAAS,mBACf,OACA,WACA,cAAc,IACJ;AAEV,MAAI,UAAU,QAAQ,UAAU,QAAW;AAC1C,WAAO;AAAA,EACR;AAEA,MAAI,OAAO,UAAU,UAAU;AAC9B,QAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC5B,6CAAY;AACZ,aAAO;AAAA,IACR;AACA,WAAO;AAAA,EACR;AAEA,MAAI,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU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AK,aAAa;AAAA,EAC9B;AACA,MAAI,aAAa;AAChB,eAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,GAAG;AACvD,UAAI,UAAU,QAAW;AACxB,mBAAW;AAAA,UACV,GAAG,mBAAmB,GAAG,CAAC,IAAI,mBAAmB,KAAK,CAAC;AAAA,QACxD;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAEA,QAAM,YAAY,WAAW,SAAS,IAAI,IAAI,WAAW,KAAK,GAAG,CAAC,KAAK;AACvE,SAAO,GAAG,QAAQ,QAAQ,KAAK,QAAQ,IAAI,GAAG,QAAQ,GAAG,SAAS;AACnE;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/common/utils.ts","../../package.json","../../src/utils.ts"],"sourcesContent":["import type { Next } from \"hono\";\nimport type { ContentfulStatusCode } from \"hono/utils/http-status\";\nimport * as errors from \"@/actor/errors\";\nimport { getEnvUniversal } from \"@/utils\";\nimport type { Logger } from \"./log\";\n\nexport function assertUnreachable(x: never): never {\n\tthrow new Error(`Unreachable case: ${x}`);\n}\n\n/**\n * Safely stringifies an object, ensuring that the stringified object is under a certain size.\n * @param obj any object to stringify\n * @param maxSize maximum size of the stringified object in bytes\n * @returns stringified object\n */\nexport function safeStringify(obj: unknown, maxSize: number) {\n\tlet size = 0;\n\n\tfunction replacer(key: string, value: unknown) {\n\t\tif (value === null || value === undefined) return value;\n\t\tconst valueSize =\n\t\t\ttypeof value === \"string\" ? value.length : JSON.stringify(value).length;\n\t\tsize += key.length + valueSize;\n\n\t\tif (size > maxSize) {\n\t\t\tthrow new Error(`JSON object exceeds size limit of ${maxSize} bytes.`);\n\t\t}\n\n\t\treturn value;\n\t}\n\n\treturn JSON.stringify(obj, replacer);\n}\n\n// TODO: Instead of doing this, use a temp var for state and attempt to write\n// it. Roll back state if fails to serialize.\n\n/**\n * Check if a value is CBOR serializable.\n * Optionally pass an onInvalid callback to receive the path to invalid values.\n *\n * For a complete list of supported CBOR tags, see:\n * https://github.com/kriszyp/cbor-x/blob/cc1cf9df8ba72288c7842af1dd374d73e34cdbc1/README.md#list-of-supported-tags-for-decoding\n */\nexport function isCborSerializable(\n\tvalue: unknown,\n\tonInvalid?: (path: string) => void,\n\tcurrentPath = \"\",\n): boolean {\n\t// Handle primitive types directly\n\tif (value === null || value === undefined) {\n\t\treturn true;\n\t}\n\n\tif (typeof value === \"number\") {\n\t\tif (!Number.isFinite(value)) {\n\t\t\tonInvalid?.(currentPath);\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tif (typeof value === \"boolean\" || typeof value === \"string\") {\n\t\treturn true;\n\t}\n\n\t// Handle BigInt (CBOR tags 2 and 3)\n\tif (typeof value === \"bigint\") {\n\t\treturn true;\n\t}\n\n\t// Handle Date objects (CBOR tags 0 and 1)\n\tif (value instanceof Date) {\n\t\treturn true;\n\t}\n\n\t// Handle typed arrays (CBOR tags 64-82)\n\tif (\n\t\tvalue instanceof Uint8Array ||\n\t\tvalue instanceof Uint8ClampedArray ||\n\t\tvalue instanceof Uint16Array ||\n\t\tvalue instanceof Uint32Array ||\n\t\tvalue instanceof BigUint64Array ||\n\t\tvalue instanceof Int8Array ||\n\t\tvalue instanceof Int16Array ||\n\t\tvalue instanceof Int32Array ||\n\t\tvalue instanceof BigInt64Array ||\n\t\tvalue instanceof Float32Array ||\n\t\tvalue instanceof Float64Array\n\t) {\n\t\treturn true;\n\t}\n\n\t// Handle Map (CBOR tag 259)\n\tif (value instanceof Map) {\n\t\tfor (const [key, val] of value.entries()) {\n\t\t\tconst keyPath = currentPath\n\t\t\t\t? `${currentPath}.key(${String(key)})`\n\t\t\t\t: `key(${String(key)})`;\n\t\t\tconst valPath = currentPath\n\t\t\t\t? `${currentPath}.value(${String(key)})`\n\t\t\t\t: `value(${String(key)})`;\n\t\t\tif (\n\t\t\t\t!isCborSerializable(key, onInvalid, keyPath) ||\n\t\t\t\t!isCborSerializable(val, onInvalid, valPath)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle Set (CBOR tag 258)\n\tif (value instanceof Set) {\n\t\tlet index = 0;\n\t\tfor (const item of value.values()) {\n\t\t\tconst itemPath = currentPath\n\t\t\t\t? `${currentPath}.set[${index}]`\n\t\t\t\t: `set[${index}]`;\n\t\t\tif (!isCborSerializable(item, onInvalid, itemPath)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\tindex++;\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle RegExp (CBOR tag 27)\n\tif (value instanceof RegExp) {\n\t\treturn true;\n\t}\n\n\t// Handle Error objects (CBOR tag 27)\n\tif (value instanceof Error) {\n\t\treturn true;\n\t}\n\n\t// Handle arrays\n\tif (Array.isArray(value)) {\n\t\tfor (let i = 0; i < value.length; i++) {\n\t\t\tconst itemPath = currentPath ? `${currentPath}[${i}]` : `[${i}]`;\n\t\t\tif (!isCborSerializable(value[i], onInvalid, itemPath)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Handle plain objects and records (CBOR tags 105, 51, 57344-57599)\n\tif (typeof value === \"object\") {\n\t\t// Allow plain objects and objects with prototypes (for records and named objects)\n\t\tconst proto = Object.getPrototypeOf(value);\n\t\tif (proto !== null && proto !== Object.prototype) {\n\t\t\t// Check if it's a known serializable object type\n\t\t\tconst protoConstructor = value.constructor;\n\t\t\tif (protoConstructor && typeof protoConstructor.name === \"string\") {\n\t\t\t\t// Allow objects with named constructors (records, named objects)\n\t\t\t\t// This includes user-defined classes and built-in objects\n\t\t\t\t// that CBOR can serialize with tag 27 or record tags\n\t\t\t}\n\t\t}\n\n\t\t// Check all properties recursively\n\t\tfor (const key in value) {\n\t\t\tconst propPath = currentPath ? `${currentPath}.${key}` : key;\n\t\t\tif (\n\t\t\t\t!isCborSerializable(\n\t\t\t\t\tvalue[key as keyof typeof value],\n\t\t\t\t\tonInvalid,\n\t\t\t\t\tpropPath,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n\n\t// Not serializable\n\tonInvalid?.(currentPath);\n\treturn false;\n}\n\nexport interface DeconstructedError {\n\t__type: \"ActorError\";\n\tstatusCode: ContentfulStatusCode;\n\tpublic: boolean;\n\tgroup: string;\n\tcode: string;\n\tmessage: string;\n\tmetadata?: unknown;\n}\n\n/** Deconstructs error in to components that are used to build responses. */\nexport function deconstructError(\n\terror: unknown,\n\tlogger: Logger,\n\textraLog: Record<string, unknown>,\n\texposeInternalError = false,\n): DeconstructedError {\n\t// Build response error information. Only return errors if flagged as public in order to prevent leaking internal behavior.\n\t//\n\t// We log the error here instead of after generating the code & message because we need to log the original error, not the masked internal error.\n\tlet statusCode: ContentfulStatusCode;\n\tlet public_: boolean;\n\tlet group: string;\n\tlet code: string;\n\tlet message: string;\n\tlet metadata: unknown;\n\tif (errors.ActorError.isActorError(error) && error.public) {\n\t\t// Check if error has statusCode (could be ActorError instance or DeconstructedError)\n\t\tstatusCode = (\n\t\t\t\"statusCode\" in error && error.statusCode ? error.statusCode : 400\n\t\t) as ContentfulStatusCode;\n\t\tpublic_ = true;\n\t\tgroup = error.group;\n\t\tcode = error.code;\n\t\tmessage = getErrorMessage(error);\n\t\tmetadata = error.metadata;\n\n\t\tlogger.info({\n\t\t\tmsg: \"public error\",\n\t\t\tgroup,\n\t\t\tcode,\n\t\t\tmessage,\n\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t...extraLog,\n\t\t});\n\t} else if (exposeInternalError) {\n\t\tif (errors.ActorError.isActorError(error)) {\n\t\t\tstatusCode = 500;\n\t\t\tpublic_ = false;\n\t\t\tgroup = error.group;\n\t\t\tcode = error.code;\n\t\t\tmessage = getErrorMessage(error);\n\t\t\tmetadata = error.metadata;\n\n\t\t\tlogger.info({\n\t\t\t\tmsg: \"internal error\",\n\t\t\t\tgroup,\n\t\t\t\tcode,\n\t\t\t\tmessage,\n\t\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t\t...extraLog,\n\t\t\t});\n\t\t} else {\n\t\t\tstatusCode = 500;\n\t\t\tpublic_ = false;\n\t\t\tgroup = \"internal\";\n\t\t\tcode = errors.INTERNAL_ERROR_CODE;\n\t\t\tmessage = getErrorMessage(error);\n\n\t\t\tlogger.info({\n\t\t\t\tmsg: \"internal error\",\n\t\t\t\tgroup,\n\t\t\t\tcode,\n\t\t\t\tmessage,\n\t\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t\t...extraLog,\n\t\t\t});\n\t\t}\n\t} else {\n\t\tstatusCode = 500;\n\t\tpublic_ = false;\n\t\tgroup = \"internal\";\n\t\tcode = errors.INTERNAL_ERROR_CODE;\n\t\tmessage = errors.INTERNAL_ERROR_DESCRIPTION;\n\t\tmetadata = {\n\t\t\t//url: `https://hub.rivet.dev/projects/${actorMetadata.project.slug}/environments/${actorMetadata.environment.slug}/actors?actorId=${actorMetadata.actor.id}`,\n\t\t} satisfies errors.InternalErrorMetadata;\n\n\t\tlogger.warn({\n\t\t\tmsg: \"internal error\",\n\t\t\terror: getErrorMessage(error),\n\t\t\tstack: (error as Error)?.stack,\n\t\t\tissues: \"https://github.com/rivet-dev/rivetkit/issues\",\n\t\t\tsupport: \"https://rivet.dev/discord\",\n\t\t\t...extraLog,\n\t\t});\n\t}\n\n\treturn {\n\t\t__type: \"ActorError\",\n\t\tstatusCode,\n\t\tpublic: public_,\n\t\tgroup,\n\t\tcode,\n\t\tmessage,\n\t\tmetadata,\n\t};\n}\n\nexport function stringifyError(error: unknown): string {\n\tif (error instanceof Error) {\n\t\tif (\n\t\t\ttypeof process !== \"undefined\" &&\n\t\t\tgetEnvUniversal(\"_RIVETKIT_ERROR_STACK\") === \"1\"\n\t\t) {\n\t\t\treturn `${error.name}: ${error.message}${error.stack ? `\\n${error.stack}` : \"\"}`;\n\t\t} else {\n\t\t\treturn `${error.name}: ${error.message}`;\n\t\t}\n\t} else if (typeof error === \"string\") {\n\t\treturn error;\n\t} else if (typeof error === \"object\" && error !== null) {\n\t\ttry {\n\t\t\treturn `${JSON.stringify(error)}`;\n\t\t} catch {\n\t\t\treturn \"[cannot stringify error]\";\n\t\t}\n\t} else {\n\t\treturn `Unknown error: ${getErrorMessage(error)}`;\n\t}\n}\n\nfunction getErrorMessage(err: unknown): string {\n\tif (\n\t\terr &&\n\t\ttypeof err === \"object\" &&\n\t\t\"message\" in err &&\n\t\ttypeof err.message === \"string\"\n\t) {\n\t\treturn err.message;\n\t} else {\n\t\treturn String(err);\n\t}\n}\n\n/** Generates a `Next` handler to pass to middleware in order to be able to call arbitrary middleware. */\nexport function noopNext(): Next {\n\treturn async () => {};\n}\n","{\n \"name\": \"rivetkit\",\n \"version\": \"2.0.20\",\n \"description\": \"Lightweight libraries for building stateful actors on edge platforms\",\n \"license\": \"Apache-2.0\",\n \"keywords\": [\n \"rivetkit\",\n \"stateful\",\n \"serverless\",\n \"actors\",\n \"agents\",\n \"realtime\",\n \"websocket\",\n \"actors\",\n \"framework\"\n ],\n \"files\": [\n \"dist\",\n \"src\",\n \"deno.json\",\n \"bun.json\",\n \"package.json\"\n ],\n \"type\": \"module\",\n \"exports\": {\n \".\": {\n \"import\": {\n \"types\": \"./dist/tsup/mod.d.ts\",\n \"default\": \"./dist/tsup/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/mod.d.cts\",\n \"default\": \"./dist/tsup/mod.cjs\"\n }\n },\n \"./client\": {\n \"import\": {\n \"types\": \"./dist/tsup/client/mod.d.ts\",\n \"default\": \"./dist/tsup/client/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/client/mod.d.cts\",\n \"default\": \"./dist/tsup/client/mod.cjs\"\n }\n },\n \"./log\": {\n \"import\": {\n \"types\": \"./dist/tsup/common/log.d.ts\",\n \"default\": \"./dist/tsup/common/log.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/common/log.d.cts\",\n \"default\": \"./dist/tsup/common/log.cjs\"\n }\n },\n \"./errors\": {\n \"import\": {\n \"types\": \"./dist/tsup/actor/errors.d.ts\",\n \"default\": \"./dist/tsup/actor/errors.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/actor/errors.d.cts\",\n \"default\": \"./dist/tsup/actor/errors.cjs\"\n }\n },\n \"./utils\": {\n \"import\": {\n \"types\": \"./dist/tsup/utils.d.ts\",\n \"default\": \"./dist/tsup/utils.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/utils.d.cts\",\n \"default\": \"./dist/tsup/utils.cjs\"\n }\n },\n \"./driver-helpers\": {\n \"import\": {\n \"types\": \"./dist/tsup/driver-helpers/mod.d.ts\",\n \"default\": \"./dist/tsup/driver-helpers/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/driver-helpers/mod.d.cts\",\n \"default\": \"./dist/tsup/driver-helpers/mod.cjs\"\n }\n },\n \"./driver-helpers/websocket\": {\n \"import\": {\n \"types\": \"./dist/tsup/common/websocket.d.ts\",\n \"default\": \"./dist/tsup/common/websocket.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/common/websocket.d.cts\",\n \"default\": \"./dist/tsup/common/websocket.cjs\"\n }\n },\n \"./driver-test-suite\": {\n \"import\": {\n \"types\": \"./dist/tsup/driver-test-suite/mod.d.ts\",\n \"default\": \"./dist/tsup/driver-test-suite/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/driver-test-suite/mod.d.cts\",\n \"default\": \"./dist/tsup/driver-test-suite/mod.cjs\"\n }\n },\n \"./topologies/coordinate\": {\n \"import\": {\n \"types\": \"./dist/tsup/topologies/coordinate/mod.d.ts\",\n \"default\": \"./dist/tsup/topologies/coordinate/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/topologies/coordinate/mod.d.cts\",\n \"default\": \"./dist/tsup/topologies/coordinate/mod.cjs\"\n }\n },\n \"./topologies/partition\": {\n \"import\": {\n \"types\": \"./dist/tsup/topologies/partition/mod.d.ts\",\n \"default\": \"./dist/tsup/topologies/partition/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/topologies/partition/mod.d.cts\",\n \"default\": \"./dist/tsup/topologies/partition/mod.cjs\"\n }\n },\n \"./test\": {\n \"import\": {\n \"types\": \"./dist/tsup/test/mod.d.ts\",\n \"default\": \"./dist/tsup/test/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/test/mod.d.cts\",\n \"default\": \"./dist/tsup/test/mod.cjs\"\n }\n },\n \"./inspector\": {\n \"import\": {\n \"types\": \"./dist/tsup/inspector/mod.d.ts\",\n \"default\": \"./dist/tsup/inspector/mod.js\"\n },\n \"require\": {\n \"types\": \"./dist/tsup/inspector/mod.d.cts\",\n \"default\": \"./dist/tsup/inspector/mod.cjs\"\n }\n }\n },\n \"engines\": {\n \"node\": \">=22.0.0\"\n },\n \"sideEffects\": [\n \"./dist/tsup/chunk-*.js\",\n \"./dist/tsup/chunk-*.cjs\"\n ],\n \"scripts\": {\n \"build\": \"tsup src/mod.ts src/client/mod.ts src/common/log.ts src/common/websocket.ts src/actor/errors.ts src/topologies/coordinate/mod.ts src/topologies/partition/mod.ts src/utils.ts src/driver-helpers/mod.ts src/driver-test-suite/mod.ts src/test/mod.ts src/inspector/mod.ts\",\n \"build:schema\": \"./scripts/compile-bare.ts compile schemas/client-protocol/v1.bare -o dist/schemas/client-protocol/v1.ts && ./scripts/compile-bare.ts compile schemas/file-system-driver/v1.bare -o dist/schemas/file-system-driver/v1.ts && ./scripts/compile-bare.ts compile schemas/actor-persist/v1.bare -o dist/schemas/actor-persist/v1.ts\",\n \"check-types\": \"tsc --noEmit\",\n \"test\": \"vitest run\",\n \"test:watch\": \"vitest\",\n \"dump-openapi\": \"tsx scripts/dump-openapi.ts\"\n },\n \"dependencies\": {\n \"@bare-ts/lib\": \"~0.3.0\",\n \"@hono/standard-validator\": \"^0.1.3\",\n \"@hono/zod-openapi\": \"^0.19.10\",\n \"@rivetkit/engine-runner\": \"https://pkg.pr.new/rivet-dev/engine/@rivetkit/engine-runner@6659217\",\n \"@rivetkit/fast-json-patch\": \"^3.1.2\",\n \"cbor-x\": \"^1.6.0\",\n \"hono\": \"^4.7.0\",\n \"invariant\": \"^2.2.4\",\n \"nanoevents\": \"^9.1.0\",\n \"on-change\": \"^5.0.1\",\n \"p-retry\": \"^6.2.1\",\n \"pino\": \"^9.5.0\",\n \"zod\": \"^3.25.76\"\n },\n \"devDependencies\": {\n \"@bare-ts/tools\": \"^0.13.0\",\n \"@hono/node-server\": \"^1.18.2\",\n \"@hono/node-ws\": \"^1.1.1\",\n \"@types/invariant\": \"^2\",\n \"@types/node\": \"^22.13.1\",\n \"@types/ws\": \"^8\",\n \"@vitest/ui\": \"3.1.1\",\n \"bundle-require\": \"^5.1.0\",\n \"eventsource\": \"^4.0.0\",\n \"tsup\": \"^8.4.0\",\n \"tsx\": \"^4.19.4\",\n \"typescript\": \"^5.7.3\",\n \"vitest\": \"^3.1.1\",\n \"ws\": \"^8.18.1\"\n },\n \"peerDependencies\": {\n \"@hono/node-server\": \"^1.14.0\",\n \"@hono/node-ws\": \"^1.1.1\",\n \"eventsource\": \"^4.0.0\",\n \"ws\": \"^8.0.0\"\n },\n \"peerDependenciesMeta\": {\n \"@hono/node-server\": {\n \"optional\": true\n },\n \"@hono/node-ws\": {\n \"optional\": true\n },\n \"eventsource\": {\n \"optional\": true\n },\n \"ws\": {\n \"optional\": true\n }\n },\n \"stableVersion\": \"0.8.0\"\n}\n","export { stringifyError } from \"@/common/utils\";\nexport { assertUnreachable } from \"./common/utils\";\n\nimport type { Context as HonoContext, Handler as HonoHandler } from \"hono\";\n\nimport pkgJson from \"../package.json\" with { type: \"json\" };\n\nexport const VERSION = pkgJson.version;\n\nlet _userAgent: string | undefined;\n\nexport function httpUserAgent(): string {\n\t// Return cached value if already initialized\n\tif (_userAgent !== undefined) {\n\t\treturn _userAgent;\n\t}\n\n\t// Library\n\tlet userAgent = `RivetKit/${VERSION}`;\n\n\t// Navigator\n\tconst navigatorObj = typeof navigator !== \"undefined\" ? navigator : undefined;\n\tif (navigatorObj?.userAgent) userAgent += ` ${navigatorObj.userAgent}`;\n\n\t_userAgent = userAgent;\n\n\treturn userAgent;\n}\n\nexport type UpgradeWebSocket = (\n\tcreateEvents: (c: HonoContext) => any,\n) => HonoHandler;\n\nexport type GetUpgradeWebSocket = () => UpgradeWebSocket;\n\nexport function getEnvUniversal(key: string): string | undefined {\n\tif (typeof Deno !== \"undefined\") {\n\t\treturn Deno.env.get(key);\n\t} else if (typeof process !== \"undefined\") {\n\t\t// Do this after Deno since `process` is sometimes polyfilled\n\t\treturn process.env[key];\n\t}\n}\n\nexport function dbg<T>(x: T): T {\n\tconsole.trace(`=== DEBUG ===\\n${x}`);\n\treturn x;\n}\n\n/**\n * Converts various ArrayBuffer-like types to Uint8Array.\n * Handles ArrayBuffer, ArrayBufferView (including typed arrays), and passes through existing Uint8Array.\n *\n * @param data - The ArrayBuffer or ArrayBufferView to convert\n * @returns A Uint8Array view of the data\n */\nexport function toUint8Array(data: ArrayBuffer | ArrayBufferView): Uint8Array {\n\tif (data instanceof Uint8Array) {\n\t\treturn data;\n\t} else if (data instanceof ArrayBuffer) {\n\t\treturn new Uint8Array(data);\n\t} else if (ArrayBuffer.isView(data)) {\n\t\t// Handle other ArrayBufferView types (Int8Array, Uint16Array, DataView, etc.)\n\t\treturn new Uint8Array(\n\t\t\tdata.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength),\n\t\t);\n\t} else {\n\t\tthrow new TypeError(\"Input must be ArrayBuffer or ArrayBufferView\");\n\t}\n}\n\n// Long timeouts\n//\n// JavaScript timers use a signed 32-bit integer for delays, so values above 2^31-1 (~24.8 days)\n// are not reliable and may fire immediately or overflow.\n//\n// https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#maximum_delay_value\nconst TIMEOUT_MAX = 2147483647; // 2^31-1\n\nexport type LongTimeoutHandle = { abort: () => void };\n\n/**\n * Polyfill for Promise.withResolvers().\n *\n * This is specifically for Cloudflare Workers. Their implementation of Promise.withResolvers does not work correctly.\n */\nexport function promiseWithResolvers<T>(): {\n\tpromise: Promise<T>;\n\tresolve: (value: T | PromiseLike<T>) => void;\n\treject: (reason?: any) => void;\n} {\n\tlet resolve!: (value: T | PromiseLike<T>) => void;\n\tlet reject!: (reason?: any) => void;\n\tconst promise = new Promise<T>((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\treturn { promise, resolve, reject };\n}\n\nexport function setLongTimeout(\n\tlistener: () => void,\n\tafter: number,\n): LongTimeoutHandle {\n\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\n\tfunction start(remaining: number) {\n\t\tif (remaining <= TIMEOUT_MAX) {\n\t\t\ttimeout = setTimeout(listener, remaining);\n\t\t} else {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tstart(remaining - TIMEOUT_MAX);\n\t\t\t}, TIMEOUT_MAX);\n\t\t}\n\t}\n\n\tstart(after);\n\n\treturn {\n\t\tabort: () => {\n\t\t\tif (timeout !== undefined) clearTimeout(timeout);\n\t\t},\n\t};\n}\n\n/**\n * A tiny utility that coalesces/enqueues async operations so only the latest\n * queued task runs per cycle, while callers receive a promise that resolves\n * when the task for the cycle they joined has completed.\n */\nexport class SinglePromiseQueue {\n\t/** Next operation to execute in the queue. If attempting to enqueue another op, it will override the existing op. */\n\t#queuedOp?: () => Promise<void>;\n\n\t/** The currently running promise of #drainLoop. Do not await this, instead await `pending` to await the current cycle. */\n\trunningDrainLoop?: Promise<void>;\n\n\t/** Pending resolver fro the currently queued entry. */\n\t#pending?: ReturnType<typeof promiseWithResolvers<void>>;\n\n\t/** Queue the next operation and return a promise that resolves when it flushes. */\n\tenqueue(op: () => Promise<void>): Promise<void> {\n\t\t// Replace any previously queued operation with the latest one\n\t\tthis.#queuedOp = op;\n\n\t\t// Ensure a shared resolver exists for all callers in this cycle\n\t\tif (!this.#pending) {\n\t\t\tthis.#pending = promiseWithResolvers<void>();\n\t\t}\n\n\t\tconst waitForThisCycle = this.#pending.promise;\n\n\t\t// Start runner if not already running\n\t\tif (!this.runningDrainLoop) {\n\t\t\tthis.runningDrainLoop = this.#drainLoop();\n\t\t}\n\n\t\treturn waitForThisCycle;\n\t}\n\n\t/** Drain queued operations sequentially until there is nothing left. */\n\tasync #drainLoop(): Promise<void> {\n\t\ttry {\n\t\t\twhile (this.#queuedOp) {\n\t\t\t\t// Capture current cycle resolver then reset for the next cycle\n\t\t\t\tconst resolver = this.#pending;\n\t\t\t\tthis.#pending = undefined;\n\n\t\t\t\t// Capture and clear the currently queued operation\n\t\t\t\tconst op = this.#queuedOp;\n\t\t\t\tthis.#queuedOp = undefined;\n\n\t\t\t\ttry {\n\t\t\t\t\tawait op();\n\t\t\t\t} catch {\n\t\t\t\t\t// Swallow errors: callers only await cycle completion, not success\n\t\t\t\t}\n\n\t\t\t\t// Notify all waiters for this cycle\n\t\t\t\tresolver?.resolve();\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.runningDrainLoop = undefined;\n\t\t}\n\t}\n}\n\nexport function bufferToArrayBuffer(buf: Buffer | Uint8Array): ArrayBuffer {\n\treturn buf.buffer.slice(\n\t\tbuf.byteOffset,\n\t\tbuf.byteOffset + buf.byteLength,\n\t) as ArrayBuffer;\n}\n\n/**\n * Properly combines a base URL endpoint with a path, preserving any base path in the endpoint.\n *\n * @example\n * combineUrlPath(\"http://localhost:8787/rivet\", \"/actors/action\")\n * // Returns: \"http://localhost:8787/rivet/actors/action\"\n *\n * @example\n * combineUrlPath(\"http://localhost:8787/rivet\", \"/actors?type=foo\", { namespace: \"test\" })\n * // Returns: \"http://localhost:8787/rivet/actors?type=foo&namespace=test\"\n *\n * @param endpoint The base URL endpoint that may contain a path component\n * @param path The path to append to the endpoint (may include query parameters)\n * @param queryParams Optional additional query parameters to append\n * @returns The properly combined URL string\n */\nexport function combineUrlPath(\n\tendpoint: string,\n\tpath: string,\n\tqueryParams?: Record<string, string | undefined>,\n): string {\n\tconst baseUrl = new URL(endpoint);\n\n\t// Extract path and query from the provided path\n\tconst pathParts = path.split(\"?\");\n\tconst pathOnly = pathParts[0];\n\tconst existingQuery = pathParts[1] || \"\";\n\n\t// Remove trailing slash from base path and ensure path starts with /\n\tconst basePath = baseUrl.pathname.replace(/\\/$/, \"\");\n\tconst cleanPath = pathOnly.startsWith(\"/\") ? pathOnly : `/${pathOnly}`;\n\t// Combine paths and remove any double slashes\n\tconst fullPath = (basePath + cleanPath).replace(/\\/\\//g, \"/\");\n\n\t// Build query string\n\tconst queryParts: string[] = [];\n\tif (existingQuery) {\n\t\tqueryParts.push(existingQuery);\n\t}\n\tif (queryParams) {\n\t\tfor (const [key, value] of Object.entries(queryParams)) {\n\t\t\tif (value !== undefined) {\n\t\t\t\tqueryParts.push(\n\t\t\t\t\t`${encodeURIComponent(key)}=${encodeURIComponent(value)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst fullQuery = queryParts.length > 0 ? `?${queryParts.join(\"&\")}` : \"\";\n\treturn `${baseUrl.protocol}//${baseUrl.host}${fullPath}${fullQuery}`;\n}\n"],"mappings":";;;;;;;AAMO,SAAS,kBAAkB,GAAiB;AAClD,QAAM,IAAI,MAAM,qBAAqB,CAAC,EAAE;AACzC;AAqCO,SAAS,mBACf,OACA,WACA,cAAc,IACJ;AAEV,MAAI,UAAU,QAAQ,UAAU,QAAW;AAC1C,WAAO;AAAA,EACR;AAEA,MAAI,OAAO,UAAU,UAAU;AAC9B,QAAI,CAAC,OAAO,SAAS,KAAK,GAAG;AAC5B,6CAAY;AACZ,aAAO;AAAA,IACR;AACA,WAAO;AAAA,EACR;AAEA,MAAI,OAAO,UAAU,aAAa,OAAO,UAAU,UAAU;AAC5D,WAAO;AAAA,EACR;AAGA,MAAI,OAAO,UAAU,UAAU;AA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KAAK,KAAK,KAAK,OAAO,QAAQ,WAAW,GAAG;AACvD,UAAI,UAAU,QAAW;AACxB,mBAAW;AAAA,UACV,GAAG,mBAAmB,GAAG,CAAC,IAAI,mBAAmB,KAAK,CAAC;AAAA,QACxD;AAAA,MACD;AAAA,IACD;AAAA,EACD;AAEA,QAAM,YAAY,WAAW,SAAS,IAAI,IAAI,WAAW,KAAK,GAAG,CAAC,KAAK;AACvE,SAAO,GAAG,QAAQ,QAAQ,KAAK,QAAQ,IAAI,GAAG,QAAQ,GAAG,SAAS;AACnE;","names":[]}
|
|
@@ -6,7 +6,7 @@ import {
|
|
|
6
6
|
HEADER_CONN_PARAMS,
|
|
7
7
|
HEADER_CONN_TOKEN,
|
|
8
8
|
HEADER_ENCODING
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-YFFCPYHY.js";
|
|
10
10
|
|
|
11
11
|
// src/inspector/protocol/common.ts
|
|
12
12
|
import z2 from "zod/v4";
|
|
@@ -236,4 +236,4 @@ export {
|
|
|
236
236
|
BuildsSchema,
|
|
237
237
|
CreateActorSchema
|
|
238
238
|
};
|
|
239
|
-
//# sourceMappingURL=chunk-
|
|
239
|
+
//# sourceMappingURL=chunk-QRUGCDA5.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getLogger
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-ER5OT3SQ.js";
|
|
4
4
|
|
|
5
5
|
// src/inspector/protocol/actor.ts
|
|
6
6
|
import { hc } from "hono/client";
|
|
@@ -100,4 +100,4 @@ export {
|
|
|
100
100
|
createActorInspectorClient,
|
|
101
101
|
createManagerInspectorClient
|
|
102
102
|
};
|
|
103
|
-
//# sourceMappingURL=chunk-
|
|
103
|
+
//# sourceMappingURL=chunk-RI4YHZZW.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var _chunkKUZWEM23cjs = require('./chunk-KUZWEM23.cjs');
|
|
4
4
|
|
|
5
5
|
// src/common/log.ts
|
|
6
6
|
|
|
@@ -128,7 +128,7 @@ function getPinoLevel(logLevel) {
|
|
|
128
128
|
if (configuredLogLevel) {
|
|
129
129
|
return configuredLogLevel;
|
|
130
130
|
}
|
|
131
|
-
const raw = (
|
|
131
|
+
const raw = (_chunkKUZWEM23cjs.getEnvUniversal.call(void 0, "LOG_LEVEL") || "warn").toString().toLowerCase();
|
|
132
132
|
const parsed = LogLevelSchema.safeParse(raw);
|
|
133
133
|
if (parsed.success) {
|
|
134
134
|
return parsed.data;
|
|
@@ -136,7 +136,7 @@ function getPinoLevel(logLevel) {
|
|
|
136
136
|
return "info";
|
|
137
137
|
}
|
|
138
138
|
function getIncludeTarget() {
|
|
139
|
-
return
|
|
139
|
+
return _chunkKUZWEM23cjs.getEnvUniversal.call(void 0, "LOG_TARGET") === "1";
|
|
140
140
|
}
|
|
141
141
|
function configureBaseLogger(logger) {
|
|
142
142
|
baseLogger = logger;
|
|
@@ -144,7 +144,7 @@ function configureBaseLogger(logger) {
|
|
|
144
144
|
}
|
|
145
145
|
function customWrite(level, o) {
|
|
146
146
|
const entries = {};
|
|
147
|
-
if (
|
|
147
|
+
if (_chunkKUZWEM23cjs.getEnvUniversal.call(void 0, "LOG_TIMESTAMP") === "1" && o.time) {
|
|
148
148
|
const date = typeof o.time === "number" ? new Date(o.time) : /* @__PURE__ */ new Date();
|
|
149
149
|
entries.ts = formatTimestamp(date);
|
|
150
150
|
}
|
|
@@ -178,7 +178,7 @@ async function configureDefaultLogger(logLevel) {
|
|
|
178
178
|
return { level: number };
|
|
179
179
|
}
|
|
180
180
|
},
|
|
181
|
-
timestamp:
|
|
181
|
+
timestamp: _chunkKUZWEM23cjs.getEnvUniversal.call(void 0, "LOG_TIMESTAMP") === "1" ? _pino.stdTimeFunctions.epochTime : false,
|
|
182
182
|
browser: {
|
|
183
183
|
write: {
|
|
184
184
|
fatal: customWrite.bind(null, "fatal"),
|
|
@@ -200,7 +200,7 @@ async function configureDefaultLogger(logLevel) {
|
|
|
200
200
|
60: "fatal"
|
|
201
201
|
};
|
|
202
202
|
const levelName = levelMap[level] || "info";
|
|
203
|
-
const time =
|
|
203
|
+
const time = _chunkKUZWEM23cjs.getEnvUniversal.call(void 0, "LOG_TIMESTAMP") === "1" ? Date.now() : void 0;
|
|
204
204
|
if (inputArgs.length >= 2) {
|
|
205
205
|
const [objOrMsg, msg] = inputArgs;
|
|
206
206
|
if (typeof objOrMsg === "object" && objOrMsg !== null) {
|
|
@@ -247,4 +247,4 @@ function getLogger(name = "default") {
|
|
|
247
247
|
|
|
248
248
|
|
|
249
249
|
exports.LogLevelSchema = LogLevelSchema; exports.getPinoLevel = getPinoLevel; exports.getIncludeTarget = getIncludeTarget; exports.configureBaseLogger = configureBaseLogger; exports.configureDefaultLogger = configureDefaultLogger; exports.getBaseLogger = getBaseLogger; exports.getLogger = getLogger;
|
|
250
|
-
//# sourceMappingURL=chunk-
|
|
250
|
+
//# sourceMappingURL=chunk-RJVSNJO7.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-QMF6X2E2.cjs","../../src/common/log.ts","../../src/common/log-levels.ts","../../src/common/logfmt.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA;AAGC;AACA;AAAA,4BACM;AACP,0BAAkB;ADIlB;AACA;AEHO,IAAM,UAAA,EAA0C;AAAA,EACtD,KAAA,EAAO,CAAA;AAAA,EACP,KAAA,EAAO,CAAA;AAAA,EACP,IAAA,EAAM,CAAA;AAAA,EACN,IAAA,EAAM,CAAA;AAAA,EACN,KAAA,EAAO,CAAA;AAAA,EACP,QAAA,EAAU;AACX,CAAA;AFKA;AACA;AGnBA,IAAM,iBAAA,EAA2C;AAAA,EAChD,CAAC,SAAA,CAAU,QAAQ,C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AAA;AACD,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACR,MAAA;AACD,IAAA;AACO,IAAA;AACI,MAAA;AAGH,QAAA;AACD,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACL,QAAA;AACM,QAAA;AAEL,QAAA;AAEG,QAAA;AACI,UAAA;AACI,UAAA;AACV,YAAA;AACM,UAAA;AACN,YAAA;AACD,UAAA;AACU,QAAA;AACH,UAAA;AACI,UAAA;AACV,YAAA;AACM,UAAA;AACN,YAAA;AACD,UAAA;AACD,QAAA;AACD,MAAA;AACD,IAAA;AACA,EAAA;AAEiB,EAAA;AACnB;AAKgB;AACE,EAAA;AAChB,IAAA;AACD,EAAA;AACO,EAAA;AACR;AAK0B;AAEV,EAAA;AACH,EAAA;AACJ,IAAA;AACR,EAAA;AAGa,EAAA;AAGC,EAAA;AAGE,EAAA;AAET,EAAA;AACR;AD0BqB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-QMF6X2E2.cjs","sourcesContent":[null,"import {\n\ttype LevelWithSilent,\n\ttype Logger,\n\tpino,\n\tstdTimeFunctions,\n} from \"pino\";\nimport { z } from \"zod\";\nimport { getEnvUniversal } from \"@/utils\";\nimport {\n\tcastToLogValue,\n\tformatTimestamp,\n\tLOGGER_CONFIG,\n\tstringify,\n} from \"./logfmt\";\n\nexport type { Logger } from \"pino\";\n\nlet baseLogger: Logger | undefined;\nlet configuredLogLevel: LogLevel | undefined;\n\n/** Cache of child loggers by logger name. */\nconst loggerCache = new Map<string, Logger>();\n\nexport const LogLevelSchema = z.enum([\n\t\"trace\",\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"error\",\n\t\"fatal\",\n\t\"silent\",\n]);\n\nexport type LogLevel = z.infer<typeof LogLevelSchema>;\n\nexport function getPinoLevel(logLevel?: LogLevel): LevelWithSilent {\n\t// Priority: provided > configured > env > default\n\tif (logLevel) {\n\t\treturn logLevel;\n\t}\n\n\tif (configuredLogLevel) {\n\t\treturn configuredLogLevel;\n\t}\n\n\tconst raw = (getEnvUniversal(\"LOG_LEVEL\") || \"warn\").toString().toLowerCase();\n\n\tconst parsed = LogLevelSchema.safeParse(raw);\n\tif (parsed.success) {\n\t\treturn parsed.data;\n\t}\n\n\t// Default to info if invalid\n\treturn \"info\";\n}\n\nexport function getIncludeTarget(): boolean {\n\treturn getEnvUniversal(\"LOG_TARGET\") === \"1\";\n}\n\n/**\n * Configure a custom base logger.\n */\nexport function configureBaseLogger(logger: Logger): void {\n\tbaseLogger = logger;\n\tloggerCache.clear();\n}\n\n// TODO: This can be simplified in logfmt.ts\nfunction customWrite(level: string, o: any) {\n\tconst entries: any = {};\n\n\t// Add timestamp if enabled\n\tif (getEnvUniversal(\"LOG_TIMESTAMP\") === \"1\" && o.time) {\n\t\tconst date = typeof o.time === \"number\" ? new Date(o.time) : new Date();\n\t\tentries.ts = formatTimestamp(date);\n\t}\n\n\t// Add level\n\tentries.level = level.toUpperCase();\n\n\t// Add target if present\n\tif (o.target) {\n\t\tentries.target = o.target;\n\t}\n\n\t// Add message\n\tif (o.msg) {\n\t\tentries.msg = o.msg;\n\t}\n\n\t// Add other properties\n\tfor (const [key, value] of Object.entries(o)) {\n\t\tif (\n\t\t\tkey !== \"time\" &&\n\t\t\tkey !== \"level\" &&\n\t\t\tkey !== \"target\" &&\n\t\t\tkey !== \"msg\" &&\n\t\t\tkey !== \"pid\" &&\n\t\t\tkey !== \"hostname\"\n\t\t) {\n\t\t\tentries[key] = castToLogValue(value);\n\t\t}\n\t}\n\n\tconst output = stringify(entries);\n\tconsole.log(output);\n}\n\n/**\n * Configure the default logger with optional log level.\n */\nexport async function configureDefaultLogger(\n\tlogLevel?: LogLevel,\n): Promise<void> {\n\t// Store the configured log level\n\tif (logLevel) {\n\t\tconfiguredLogLevel = logLevel;\n\t}\n\n\tbaseLogger = pino({\n\t\tlevel: getPinoLevel(logLevel),\n\t\tmessageKey: \"msg\",\n\t\t// Do not include pid/hostname in output\n\t\tbase: {},\n\t\t// Keep a string level in the output\n\t\tformatters: {\n\t\t\tlevel(_label: string, number: number) {\n\t\t\t\treturn { level: number };\n\t\t\t},\n\t\t},\n\t\ttimestamp:\n\t\t\tgetEnvUniversal(\"LOG_TIMESTAMP\") === \"1\"\n\t\t\t\t? stdTimeFunctions.epochTime\n\t\t\t\t: false,\n\t\tbrowser: {\n\t\t\twrite: {\n\t\t\t\tfatal: customWrite.bind(null, \"fatal\"),\n\t\t\t\terror: customWrite.bind(null, \"error\"),\n\t\t\t\twarn: customWrite.bind(null, \"warn\"),\n\t\t\t\tinfo: customWrite.bind(null, \"info\"),\n\t\t\t\tdebug: customWrite.bind(null, \"debug\"),\n\t\t\t\ttrace: customWrite.bind(null, \"trace\"),\n\t\t\t},\n\t\t},\n\t\thooks: {\n\t\t\tlogMethod(inputArgs, _method, level) {\n\t\t\t\t// TODO: This is a hack to not implement our own transport target. We can get better perf if we have our own transport target.\n\n\t\t\t\tconst levelMap: Record<number, string> = {\n\t\t\t\t\t10: \"trace\",\n\t\t\t\t\t20: \"debug\",\n\t\t\t\t\t30: \"info\",\n\t\t\t\t\t40: \"warn\",\n\t\t\t\t\t50: \"error\",\n\t\t\t\t\t60: \"fatal\",\n\t\t\t\t};\n\t\t\t\tconst levelName = levelMap[level] || \"info\";\n\t\t\t\tconst time =\n\t\t\t\t\tgetEnvUniversal(\"LOG_TIMESTAMP\") === \"1\" ? Date.now() : undefined;\n\t\t\t\t// TODO: This can be simplified in logfmt.ts\n\t\t\t\tif (inputArgs.length >= 2) {\n\t\t\t\t\tconst [objOrMsg, msg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, { ...objOrMsg, msg, time });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, { msg: String(objOrMsg), time });\n\t\t\t\t\t}\n\t\t\t\t} else if (inputArgs.length === 1) {\n\t\t\t\t\tconst [objOrMsg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, { ...objOrMsg, time });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, { msg: String(objOrMsg), time });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\n\tloggerCache.clear();\n}\n\n/**\n * Get or initialize the base logger.\n */\nexport function getBaseLogger(): Logger {\n\tif (!baseLogger) {\n\t\tconfigureDefaultLogger();\n\t}\n\treturn baseLogger!;\n}\n\n/**\n * Returns a child logger with `target` bound for the given name.\n */\nexport function getLogger(name = \"default\"): Logger {\n\t// Check cache first\n\tconst cached = loggerCache.get(name);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\n\t// Create\n\tconst base = getBaseLogger();\n\n\t// Add target to log if enabled\n\tconst child = getIncludeTarget() ? base.child({ target: name }) : base;\n\n\t// Cache the logger\n\tloggerCache.set(name, child);\n\n\treturn child;\n}\n","export type LogLevel =\n\t| \"TRACE\"\n\t| \"DEBUG\"\n\t| \"INFO\"\n\t| \"WARN\"\n\t| \"ERROR\"\n\t| \"CRITICAL\";\n\nexport const LogLevels: Record<LogLevel, LevelIndex> = {\n\tTRACE: 0,\n\tDEBUG: 1,\n\tINFO: 2,\n\tWARN: 3,\n\tERROR: 4,\n\tCRITICAL: 5,\n} as const;\n\nexport const LevelNameMap: Record<number, LogLevel> = {\n\t0: \"TRACE\",\n\t1: \"DEBUG\",\n\t2: \"INFO\",\n\t3: \"WARN\",\n\t4: \"ERROR\",\n\t5: \"CRITICAL\",\n};\n\nexport type LevelIndex = number;\n","import { type LogLevel, LogLevels } from \"./log-levels\";\n\nconst LOG_LEVEL_COLORS: Record<number, string> = {\n\t[LogLevels.CRITICAL]: \"\\x1b[31m\", // Red\n\t[LogLevels.ERROR]: \"\\x1b[31m\", // Red\n\t[LogLevels.WARN]: \"\\x1b[33m\", // Yellow\n\t[LogLevels.INFO]: \"\\x1b[32m\", // Green\n\t[LogLevels.DEBUG]: \"\\x1b[36m\", // Cyan\n\t[LogLevels.TRACE]: \"\\x1b[36m\", // Cyan\n};\n\nconst RESET_COLOR = \"\\x1b[0m\";\n\n/**\n * Serializes logfmt line from an object.\n *\n * ## Styling Methodology\n *\n * The three things you need to know for every log line is the level, the\n * message, and who called it. These properties are highlighted in different colros\n * and sorted in th eorder that you usually read them.\n *\n * Once you've found a log line you care about, then you want to find the\n * property you need to see. The property names are bolded and the default color\n * while the rest of the data is dim. This lets you scan to find the property\n * name quickly then look closer to read the data associated with the\n * property.\n */\nexport function stringify(data: any) {\n\tlet line = \"\";\n\tconst entries = Object.entries(data);\n\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tconst [key, valueRaw] = entries[i];\n\n\t\tlet isNull = false;\n\t\tlet valueString: string;\n\t\tif (valueRaw == null) {\n\t\t\tisNull = true;\n\t\t\tvalueString = \"\";\n\t\t} else {\n\t\t\tvalueString = valueRaw.toString();\n\t\t}\n\n\t\t// Clip value unless specifically the error message\n\t\tif (valueString.length > 512 && key !== \"msg\" && key !== \"error\")\n\t\t\tvalueString = `${valueString.slice(0, 512)}...`;\n\n\t\tconst needsQuoting =\n\t\t\tvalueString.indexOf(\" \") > -1 || valueString.indexOf(\"=\") > -1;\n\t\tconst needsEscaping =\n\t\t\tvalueString.indexOf('\"') > -1 || valueString.indexOf(\"\\\\\") > -1;\n\n\t\tvalueString = valueString.replace(/\\n/g, \"\\\\n\");\n\t\tif (needsEscaping) valueString = valueString.replace(/[\"\\\\]/g, \"\\\\$&\");\n\t\tif (needsQuoting || needsEscaping) valueString = `\"${valueString}\"`;\n\t\tif (valueString === \"\" && !isNull) valueString = '\"\"';\n\n\t\tif (LOGGER_CONFIG.enableColor) {\n\t\t\t// With color\n\n\t\t\t// Special message colors\n\t\t\tlet color = \"\\x1b[2m\";\n\t\t\tif (key === \"level\") {\n\t\t\t\tconst level = LogLevels[valueString as LogLevel];\n\t\t\t\tconst levelColor = LOG_LEVEL_COLORS[level];\n\t\t\t\tif (levelColor) {\n\t\t\t\t\tcolor = levelColor;\n\t\t\t\t}\n\t\t\t} else if (key === \"msg\") {\n\t\t\t\tcolor = \"\\x1b[32m\";\n\t\t\t} else if (key === \"trace\") {\n\t\t\t\tcolor = \"\\x1b[34m\";\n\t\t\t}\n\n\t\t\t// Format line\n\t\t\tline += `\\x1b[0m\\x1b[1m${key}\\x1b[0m\\x1b[2m=\\x1b[0m${color}${valueString}${RESET_COLOR}`;\n\t\t} else {\n\t\t\t// No color\n\t\t\tline += `${key}=${valueString}`;\n\t\t}\n\n\t\tif (i !== entries.length - 1) {\n\t\t\tline += \" \";\n\t\t}\n\t}\n\n\treturn line;\n}\n\nexport function formatTimestamp(date: Date): string {\n\tconst year = date.getUTCFullYear();\n\tconst month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n\tconst day = String(date.getUTCDate()).padStart(2, \"0\");\n\tconst hours = String(date.getUTCHours()).padStart(2, \"0\");\n\tconst minutes = String(date.getUTCMinutes()).padStart(2, \"0\");\n\tconst seconds = String(date.getUTCSeconds()).padStart(2, \"0\");\n\tconst milliseconds = String(date.getUTCMilliseconds()).padStart(3, \"0\");\n\n\treturn `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`;\n}\n\nexport function castToLogValue(v: unknown): any {\n\tif (\n\t\ttypeof v === \"string\" ||\n\t\ttypeof v === \"number\" ||\n\t\ttypeof v === \"bigint\" ||\n\t\ttypeof v === \"boolean\" ||\n\t\tv === null ||\n\t\tv === undefined\n\t) {\n\t\treturn v;\n\t}\n\tif (v instanceof Error) {\n\t\t//args.push(...errorToLogEntries(k, v));\n\t\treturn String(v);\n\t}\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch {\n\t\treturn \"[cannot stringify]\";\n\t}\n}\n\n// MARK: Config\ninterface GlobalLoggerConfig {\n\tenableColor: boolean;\n\tenableSpreadObject: boolean;\n\tenableErrorStack: boolean;\n}\n\nexport const LOGGER_CONFIG: GlobalLoggerConfig = {\n\tenableColor: false,\n\tenableSpreadObject: false,\n\tenableErrorStack: false,\n};\n\n// MARK: Utils\n/**\n * Converts an object in to an easier to read KV of entries.\n */\nexport function spreadObjectToLogEntries(base: string, data: unknown): any {\n\tif (\n\t\tLOGGER_CONFIG.enableSpreadObject &&\n\t\ttypeof data === \"object\" &&\n\t\t!Array.isArray(data) &&\n\t\tdata !== null &&\n\t\tObject.keys(data).length !== 0 &&\n\t\tObject.keys(data).length < 16\n\t) {\n\t\tconst logData: any = {};\n\t\tfor (const key in data) {\n\t\t\tObject.assign(\n\t\t\t\tlogData,\n\t\t\t\tspreadObjectToLogEntries(\n\t\t\t\t\t`${base}.${key}`,\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: FIXME\n\t\t\t\t\t(data as any)[key],\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn logData;\n\t}\n\n\treturn { [base]: JSON.stringify(data) };\n}\n\nexport function errorToLogEntries(base: string, error: unknown): any {\n\tif (error instanceof Error) {\n\t\treturn {\n\t\t\t[`${base}.message`]: error.message,\n\t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n\t\t\t\t? { [`${base}.stack`]: formatStackTrace(error.stack) }\n\t\t\t\t: {}),\n\t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : {}),\n\t\t};\n\t}\n\treturn { [base]: `${error}` };\n}\n\n// export function errorToLogEntries(base: string, error: unknown): LogEntry[] {\n// \tif (error instanceof RuntimeError) {\n// \t\treturn [\n// \t\t\t[`${base}.code`, error.code],\n// \t\t\t[`${base}.description`, error.errorConfig?.description],\n// \t\t\t[`${base}.module`, error.moduleName],\n// \t\t\t...(error.trace ? [[`${base}.trace`, stringifyTrace(error.trace)] as LogEntry] : []),\n// \t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n// \t\t\t\t? [[`${base}.stack`, formatStackTrace(error.stack)] as LogEntry]\n// \t\t\t\t: []),\n// \t\t\t...(error.meta ? [[`${base}.meta`, JSON.stringify(error.meta)] as LogEntry] : []),\n// \t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : []),\n// \t\t];\n// \t} else if (error instanceof Error) {\n// \t\treturn [\n// \t\t\t[`${base}.name`, error.name],\n// \t\t\t[`${base}.message`, error.message],\n// \t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n// \t\t\t\t? [[`${base}.stack`, formatStackTrace(error.stack)] as LogEntry]\n// \t\t\t\t: []),\n// \t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : []),\n// \t\t];\n// \t} else {\n// \t\treturn [\n// \t\t\t[base, `${error}`],\n// \t\t];\n// \t}\n// }\n\n/**\n * Formats a JS stack trace in to a legible one-liner.\n */\nfunction formatStackTrace(stackTrace: string): string {\n\tconst regex = /at (.+?)$/gm;\n\tconst matches = [...stackTrace.matchAll(regex)];\n\t// Reverse array since the stack goes from top level -> bottom level\n\tmatches.reverse();\n\treturn matches.map((match) => match[1].trim()).join(\" > \");\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-RJVSNJO7.cjs","../../src/common/log.ts","../../src/common/log-levels.ts","../../src/common/logfmt.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACA;ACJA;AAGC;AACA;AAAA,4BACM;AACP,0BAAkB;ADIlB;AACA;AEHO,IAAM,UAAA,EAA0C;AAAA,EACtD,KAAA,EAAO,CAAA;AAAA,EACP,KAAA,EAAO,CAAA;AAAA,EACP,IAAA,EAAM,CAAA;AAAA,EACN,IAAA,EAAM,CAAA;AAAA,EACN,KAAA,EAAO,CAAA;AAAA,EACP,QAAA,EAAU;AACX,CAAA;AFKA;AACA;AGnBA,IAAM,iBAAA,EAA2C;AAAA,EAChD,CAAC,SAAA,CAAU,QAAQ,CAA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A;AACD,QAAA;AACA,QAAA;AACC,QAAA;AACA,QAAA;AACR,MAAA;AACD,IAAA;AACO,IAAA;AACI,MAAA;AAGH,QAAA;AACD,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACA,UAAA;AACL,QAAA;AACM,QAAA;AAEL,QAAA;AAEG,QAAA;AACI,UAAA;AACI,UAAA;AACV,YAAA;AACM,UAAA;AACN,YAAA;AACD,UAAA;AACU,QAAA;AACH,UAAA;AACI,UAAA;AACV,YAAA;AACM,UAAA;AACN,YAAA;AACD,UAAA;AACD,QAAA;AACD,MAAA;AACD,IAAA;AACA,EAAA;AAEiB,EAAA;AACnB;AAKgB;AACE,EAAA;AAChB,IAAA;AACD,EAAA;AACO,EAAA;AACR;AAK0B;AAEV,EAAA;AACH,EAAA;AACJ,IAAA;AACR,EAAA;AAGa,EAAA;AAGC,EAAA;AAGE,EAAA;AAET,EAAA;AACR;AD0BqB;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/Users/nathan/rivetkit/packages/rivetkit/dist/tsup/chunk-RJVSNJO7.cjs","sourcesContent":[null,"import {\n\ttype LevelWithSilent,\n\ttype Logger,\n\tpino,\n\tstdTimeFunctions,\n} from \"pino\";\nimport { z } from \"zod\";\nimport { getEnvUniversal } from \"@/utils\";\nimport {\n\tcastToLogValue,\n\tformatTimestamp,\n\tLOGGER_CONFIG,\n\tstringify,\n} from \"./logfmt\";\n\nexport type { Logger } from \"pino\";\n\nlet baseLogger: Logger | undefined;\nlet configuredLogLevel: LogLevel | undefined;\n\n/** Cache of child loggers by logger name. */\nconst loggerCache = new Map<string, Logger>();\n\nexport const LogLevelSchema = z.enum([\n\t\"trace\",\n\t\"debug\",\n\t\"info\",\n\t\"warn\",\n\t\"error\",\n\t\"fatal\",\n\t\"silent\",\n]);\n\nexport type LogLevel = z.infer<typeof LogLevelSchema>;\n\nexport function getPinoLevel(logLevel?: LogLevel): LevelWithSilent {\n\t// Priority: provided > configured > env > default\n\tif (logLevel) {\n\t\treturn logLevel;\n\t}\n\n\tif (configuredLogLevel) {\n\t\treturn configuredLogLevel;\n\t}\n\n\tconst raw = (getEnvUniversal(\"LOG_LEVEL\") || \"warn\").toString().toLowerCase();\n\n\tconst parsed = LogLevelSchema.safeParse(raw);\n\tif (parsed.success) {\n\t\treturn parsed.data;\n\t}\n\n\t// Default to info if invalid\n\treturn \"info\";\n}\n\nexport function getIncludeTarget(): boolean {\n\treturn getEnvUniversal(\"LOG_TARGET\") === \"1\";\n}\n\n/**\n * Configure a custom base logger.\n */\nexport function configureBaseLogger(logger: Logger): void {\n\tbaseLogger = logger;\n\tloggerCache.clear();\n}\n\n// TODO: This can be simplified in logfmt.ts\nfunction customWrite(level: string, o: any) {\n\tconst entries: any = {};\n\n\t// Add timestamp if enabled\n\tif (getEnvUniversal(\"LOG_TIMESTAMP\") === \"1\" && o.time) {\n\t\tconst date = typeof o.time === \"number\" ? new Date(o.time) : new Date();\n\t\tentries.ts = formatTimestamp(date);\n\t}\n\n\t// Add level\n\tentries.level = level.toUpperCase();\n\n\t// Add target if present\n\tif (o.target) {\n\t\tentries.target = o.target;\n\t}\n\n\t// Add message\n\tif (o.msg) {\n\t\tentries.msg = o.msg;\n\t}\n\n\t// Add other properties\n\tfor (const [key, value] of Object.entries(o)) {\n\t\tif (\n\t\t\tkey !== \"time\" &&\n\t\t\tkey !== \"level\" &&\n\t\t\tkey !== \"target\" &&\n\t\t\tkey !== \"msg\" &&\n\t\t\tkey !== \"pid\" &&\n\t\t\tkey !== \"hostname\"\n\t\t) {\n\t\t\tentries[key] = castToLogValue(value);\n\t\t}\n\t}\n\n\tconst output = stringify(entries);\n\tconsole.log(output);\n}\n\n/**\n * Configure the default logger with optional log level.\n */\nexport async function configureDefaultLogger(\n\tlogLevel?: LogLevel,\n): Promise<void> {\n\t// Store the configured log level\n\tif (logLevel) {\n\t\tconfiguredLogLevel = logLevel;\n\t}\n\n\tbaseLogger = pino({\n\t\tlevel: getPinoLevel(logLevel),\n\t\tmessageKey: \"msg\",\n\t\t// Do not include pid/hostname in output\n\t\tbase: {},\n\t\t// Keep a string level in the output\n\t\tformatters: {\n\t\t\tlevel(_label: string, number: number) {\n\t\t\t\treturn { level: number };\n\t\t\t},\n\t\t},\n\t\ttimestamp:\n\t\t\tgetEnvUniversal(\"LOG_TIMESTAMP\") === \"1\"\n\t\t\t\t? stdTimeFunctions.epochTime\n\t\t\t\t: false,\n\t\tbrowser: {\n\t\t\twrite: {\n\t\t\t\tfatal: customWrite.bind(null, \"fatal\"),\n\t\t\t\terror: customWrite.bind(null, \"error\"),\n\t\t\t\twarn: customWrite.bind(null, \"warn\"),\n\t\t\t\tinfo: customWrite.bind(null, \"info\"),\n\t\t\t\tdebug: customWrite.bind(null, \"debug\"),\n\t\t\t\ttrace: customWrite.bind(null, \"trace\"),\n\t\t\t},\n\t\t},\n\t\thooks: {\n\t\t\tlogMethod(inputArgs, _method, level) {\n\t\t\t\t// TODO: This is a hack to not implement our own transport target. We can get better perf if we have our own transport target.\n\n\t\t\t\tconst levelMap: Record<number, string> = {\n\t\t\t\t\t10: \"trace\",\n\t\t\t\t\t20: \"debug\",\n\t\t\t\t\t30: \"info\",\n\t\t\t\t\t40: \"warn\",\n\t\t\t\t\t50: \"error\",\n\t\t\t\t\t60: \"fatal\",\n\t\t\t\t};\n\t\t\t\tconst levelName = levelMap[level] || \"info\";\n\t\t\t\tconst time =\n\t\t\t\t\tgetEnvUniversal(\"LOG_TIMESTAMP\") === \"1\" ? Date.now() : undefined;\n\t\t\t\t// TODO: This can be simplified in logfmt.ts\n\t\t\t\tif (inputArgs.length >= 2) {\n\t\t\t\t\tconst [objOrMsg, msg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, { ...objOrMsg, msg, time });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, { msg: String(objOrMsg), time });\n\t\t\t\t\t}\n\t\t\t\t} else if (inputArgs.length === 1) {\n\t\t\t\t\tconst [objOrMsg] = inputArgs;\n\t\t\t\t\tif (typeof objOrMsg === \"object\" && objOrMsg !== null) {\n\t\t\t\t\t\tcustomWrite(levelName, { ...objOrMsg, time });\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcustomWrite(levelName, { msg: String(objOrMsg), time });\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t});\n\n\tloggerCache.clear();\n}\n\n/**\n * Get or initialize the base logger.\n */\nexport function getBaseLogger(): Logger {\n\tif (!baseLogger) {\n\t\tconfigureDefaultLogger();\n\t}\n\treturn baseLogger!;\n}\n\n/**\n * Returns a child logger with `target` bound for the given name.\n */\nexport function getLogger(name = \"default\"): Logger {\n\t// Check cache first\n\tconst cached = loggerCache.get(name);\n\tif (cached) {\n\t\treturn cached;\n\t}\n\n\t// Create\n\tconst base = getBaseLogger();\n\n\t// Add target to log if enabled\n\tconst child = getIncludeTarget() ? base.child({ target: name }) : base;\n\n\t// Cache the logger\n\tloggerCache.set(name, child);\n\n\treturn child;\n}\n","export type LogLevel =\n\t| \"TRACE\"\n\t| \"DEBUG\"\n\t| \"INFO\"\n\t| \"WARN\"\n\t| \"ERROR\"\n\t| \"CRITICAL\";\n\nexport const LogLevels: Record<LogLevel, LevelIndex> = {\n\tTRACE: 0,\n\tDEBUG: 1,\n\tINFO: 2,\n\tWARN: 3,\n\tERROR: 4,\n\tCRITICAL: 5,\n} as const;\n\nexport const LevelNameMap: Record<number, LogLevel> = {\n\t0: \"TRACE\",\n\t1: \"DEBUG\",\n\t2: \"INFO\",\n\t3: \"WARN\",\n\t4: \"ERROR\",\n\t5: \"CRITICAL\",\n};\n\nexport type LevelIndex = number;\n","import { type LogLevel, LogLevels } from \"./log-levels\";\n\nconst LOG_LEVEL_COLORS: Record<number, string> = {\n\t[LogLevels.CRITICAL]: \"\\x1b[31m\", // Red\n\t[LogLevels.ERROR]: \"\\x1b[31m\", // Red\n\t[LogLevels.WARN]: \"\\x1b[33m\", // Yellow\n\t[LogLevels.INFO]: \"\\x1b[32m\", // Green\n\t[LogLevels.DEBUG]: \"\\x1b[36m\", // Cyan\n\t[LogLevels.TRACE]: \"\\x1b[36m\", // Cyan\n};\n\nconst RESET_COLOR = \"\\x1b[0m\";\n\n/**\n * Serializes logfmt line from an object.\n *\n * ## Styling Methodology\n *\n * The three things you need to know for every log line is the level, the\n * message, and who called it. These properties are highlighted in different colros\n * and sorted in th eorder that you usually read them.\n *\n * Once you've found a log line you care about, then you want to find the\n * property you need to see. The property names are bolded and the default color\n * while the rest of the data is dim. This lets you scan to find the property\n * name quickly then look closer to read the data associated with the\n * property.\n */\nexport function stringify(data: any) {\n\tlet line = \"\";\n\tconst entries = Object.entries(data);\n\n\tfor (let i = 0; i < entries.length; i++) {\n\t\tconst [key, valueRaw] = entries[i];\n\n\t\tlet isNull = false;\n\t\tlet valueString: string;\n\t\tif (valueRaw == null) {\n\t\t\tisNull = true;\n\t\t\tvalueString = \"\";\n\t\t} else {\n\t\t\tvalueString = valueRaw.toString();\n\t\t}\n\n\t\t// Clip value unless specifically the error message\n\t\tif (valueString.length > 512 && key !== \"msg\" && key !== \"error\")\n\t\t\tvalueString = `${valueString.slice(0, 512)}...`;\n\n\t\tconst needsQuoting =\n\t\t\tvalueString.indexOf(\" \") > -1 || valueString.indexOf(\"=\") > -1;\n\t\tconst needsEscaping =\n\t\t\tvalueString.indexOf('\"') > -1 || valueString.indexOf(\"\\\\\") > -1;\n\n\t\tvalueString = valueString.replace(/\\n/g, \"\\\\n\");\n\t\tif (needsEscaping) valueString = valueString.replace(/[\"\\\\]/g, \"\\\\$&\");\n\t\tif (needsQuoting || needsEscaping) valueString = `\"${valueString}\"`;\n\t\tif (valueString === \"\" && !isNull) valueString = '\"\"';\n\n\t\tif (LOGGER_CONFIG.enableColor) {\n\t\t\t// With color\n\n\t\t\t// Special message colors\n\t\t\tlet color = \"\\x1b[2m\";\n\t\t\tif (key === \"level\") {\n\t\t\t\tconst level = LogLevels[valueString as LogLevel];\n\t\t\t\tconst levelColor = LOG_LEVEL_COLORS[level];\n\t\t\t\tif (levelColor) {\n\t\t\t\t\tcolor = levelColor;\n\t\t\t\t}\n\t\t\t} else if (key === \"msg\") {\n\t\t\t\tcolor = \"\\x1b[32m\";\n\t\t\t} else if (key === \"trace\") {\n\t\t\t\tcolor = \"\\x1b[34m\";\n\t\t\t}\n\n\t\t\t// Format line\n\t\t\tline += `\\x1b[0m\\x1b[1m${key}\\x1b[0m\\x1b[2m=\\x1b[0m${color}${valueString}${RESET_COLOR}`;\n\t\t} else {\n\t\t\t// No color\n\t\t\tline += `${key}=${valueString}`;\n\t\t}\n\n\t\tif (i !== entries.length - 1) {\n\t\t\tline += \" \";\n\t\t}\n\t}\n\n\treturn line;\n}\n\nexport function formatTimestamp(date: Date): string {\n\tconst year = date.getUTCFullYear();\n\tconst month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n\tconst day = String(date.getUTCDate()).padStart(2, \"0\");\n\tconst hours = String(date.getUTCHours()).padStart(2, \"0\");\n\tconst minutes = String(date.getUTCMinutes()).padStart(2, \"0\");\n\tconst seconds = String(date.getUTCSeconds()).padStart(2, \"0\");\n\tconst milliseconds = String(date.getUTCMilliseconds()).padStart(3, \"0\");\n\n\treturn `${year}-${month}-${day}T${hours}:${minutes}:${seconds}.${milliseconds}Z`;\n}\n\nexport function castToLogValue(v: unknown): any {\n\tif (\n\t\ttypeof v === \"string\" ||\n\t\ttypeof v === \"number\" ||\n\t\ttypeof v === \"bigint\" ||\n\t\ttypeof v === \"boolean\" ||\n\t\tv === null ||\n\t\tv === undefined\n\t) {\n\t\treturn v;\n\t}\n\tif (v instanceof Error) {\n\t\t//args.push(...errorToLogEntries(k, v));\n\t\treturn String(v);\n\t}\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch {\n\t\treturn \"[cannot stringify]\";\n\t}\n}\n\n// MARK: Config\ninterface GlobalLoggerConfig {\n\tenableColor: boolean;\n\tenableSpreadObject: boolean;\n\tenableErrorStack: boolean;\n}\n\nexport const LOGGER_CONFIG: GlobalLoggerConfig = {\n\tenableColor: false,\n\tenableSpreadObject: false,\n\tenableErrorStack: false,\n};\n\n// MARK: Utils\n/**\n * Converts an object in to an easier to read KV of entries.\n */\nexport function spreadObjectToLogEntries(base: string, data: unknown): any {\n\tif (\n\t\tLOGGER_CONFIG.enableSpreadObject &&\n\t\ttypeof data === \"object\" &&\n\t\t!Array.isArray(data) &&\n\t\tdata !== null &&\n\t\tObject.keys(data).length !== 0 &&\n\t\tObject.keys(data).length < 16\n\t) {\n\t\tconst logData: any = {};\n\t\tfor (const key in data) {\n\t\t\tObject.assign(\n\t\t\t\tlogData,\n\t\t\t\tspreadObjectToLogEntries(\n\t\t\t\t\t`${base}.${key}`,\n\t\t\t\t\t// biome-ignore lint/suspicious/noExplicitAny: FIXME\n\t\t\t\t\t(data as any)[key],\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t\treturn logData;\n\t}\n\n\treturn { [base]: JSON.stringify(data) };\n}\n\nexport function errorToLogEntries(base: string, error: unknown): any {\n\tif (error instanceof Error) {\n\t\treturn {\n\t\t\t[`${base}.message`]: error.message,\n\t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n\t\t\t\t? { [`${base}.stack`]: formatStackTrace(error.stack) }\n\t\t\t\t: {}),\n\t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : {}),\n\t\t};\n\t}\n\treturn { [base]: `${error}` };\n}\n\n// export function errorToLogEntries(base: string, error: unknown): LogEntry[] {\n// \tif (error instanceof RuntimeError) {\n// \t\treturn [\n// \t\t\t[`${base}.code`, error.code],\n// \t\t\t[`${base}.description`, error.errorConfig?.description],\n// \t\t\t[`${base}.module`, error.moduleName],\n// \t\t\t...(error.trace ? [[`${base}.trace`, stringifyTrace(error.trace)] as LogEntry] : []),\n// \t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n// \t\t\t\t? [[`${base}.stack`, formatStackTrace(error.stack)] as LogEntry]\n// \t\t\t\t: []),\n// \t\t\t...(error.meta ? [[`${base}.meta`, JSON.stringify(error.meta)] as LogEntry] : []),\n// \t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : []),\n// \t\t];\n// \t} else if (error instanceof Error) {\n// \t\treturn [\n// \t\t\t[`${base}.name`, error.name],\n// \t\t\t[`${base}.message`, error.message],\n// \t\t\t...(LOGGER_CONFIG.enableErrorStack && error.stack\n// \t\t\t\t? [[`${base}.stack`, formatStackTrace(error.stack)] as LogEntry]\n// \t\t\t\t: []),\n// \t\t\t...(error.cause ? errorToLogEntries(`${base}.cause`, error.cause) : []),\n// \t\t];\n// \t} else {\n// \t\treturn [\n// \t\t\t[base, `${error}`],\n// \t\t];\n// \t}\n// }\n\n/**\n * Formats a JS stack trace in to a legible one-liner.\n */\nfunction formatStackTrace(stackTrace: string): string {\n\tconst regex = /at (.+?)$/gm;\n\tconst matches = [...stackTrace.matchAll(regex)];\n\t// Reverse array since the stack goes from top level -> bottom level\n\tmatches.reverse();\n\treturn matches.map((match) => match[1].trim()).join(\" > \");\n}\n"]}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getLogger
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-ER5OT3SQ.js";
|
|
4
4
|
import {
|
|
5
5
|
assertUnreachable
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-QMVCFQ37.js";
|
|
7
7
|
import {
|
|
8
8
|
Unreachable
|
|
9
9
|
} from "./chunk-G64QUEDJ.js";
|
|
@@ -310,4 +310,4 @@ export {
|
|
|
310
310
|
WS_PROTOCOL_PATH,
|
|
311
311
|
ALLOWED_PUBLIC_HEADERS
|
|
312
312
|
};
|
|
313
|
-
//# sourceMappingURL=chunk-
|
|
313
|
+
//# sourceMappingURL=chunk-YFFCPYHY.js.map
|