rivetkit 2.3.12-rc.3 → 2.3.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/dist/browser/client.d.ts +17 -2
  2. package/dist/browser/client.js +32 -24
  3. package/dist/browser/client.js.map +1 -1
  4. package/dist/browser/inspector/client.js +2 -1
  5. package/dist/browser/inspector/client.js.map +1 -1
  6. package/dist/tsup/actor/errors.cjs +2 -2
  7. package/dist/tsup/actor/errors.js +1 -1
  8. package/dist/tsup/agent-os/index.cjs +2 -1
  9. package/dist/tsup/agent-os/index.cjs.map +1 -1
  10. package/dist/tsup/agent-os/index.d.cts +17 -2
  11. package/dist/tsup/agent-os/index.d.ts +17 -2
  12. package/dist/tsup/agent-os/index.js +2 -1
  13. package/dist/tsup/agent-os/index.js.map +1 -1
  14. package/dist/tsup/{chunk-SPJORZMM.cjs → chunk-2JSYYH6P.cjs} +1 -1
  15. package/dist/tsup/chunk-2JSYYH6P.cjs.map +1 -0
  16. package/dist/tsup/{chunk-IJWTHKH6.cjs → chunk-AN7WO7BM.cjs} +3 -3
  17. package/dist/tsup/{chunk-IJWTHKH6.cjs.map → chunk-AN7WO7BM.cjs.map} +1 -1
  18. package/dist/tsup/{chunk-PSXMESQJ.js → chunk-EBXARMGI.js} +2 -2
  19. package/dist/tsup/{chunk-O6H3BUN4.cjs → chunk-FGQABMXZ.cjs} +3 -3
  20. package/dist/tsup/{chunk-O6H3BUN4.cjs.map → chunk-FGQABMXZ.cjs.map} +1 -1
  21. package/dist/tsup/{chunk-WVFTFWJL.js → chunk-GEN4NHXM.js} +2 -2
  22. package/dist/tsup/{chunk-XI4MEUUI.js → chunk-JYTXOMM7.js} +2 -2
  23. package/dist/tsup/{chunk-OX6WVQE6.cjs → chunk-MEF7RVQ7.cjs} +10 -10
  24. package/dist/tsup/{chunk-OX6WVQE6.cjs.map → chunk-MEF7RVQ7.cjs.map} +1 -1
  25. package/dist/tsup/{chunk-OLGQYFUW.js → chunk-MF42PRF2.js} +9 -3
  26. package/dist/tsup/chunk-MF42PRF2.js.map +1 -0
  27. package/dist/tsup/{chunk-IXBD7BXC.js → chunk-OUQUIBVW.js} +1 -1
  28. package/dist/tsup/chunk-OUQUIBVW.js.map +1 -0
  29. package/dist/tsup/{chunk-QLOBB27M.cjs → chunk-PW2VSGUR.cjs} +4 -4
  30. package/dist/tsup/{chunk-QLOBB27M.cjs.map → chunk-PW2VSGUR.cjs.map} +1 -1
  31. package/dist/tsup/{chunk-NHI5L7C7.js → chunk-RBXJWAJB.js} +3 -3
  32. package/dist/tsup/{chunk-UBB32UOG.cjs → chunk-SSPTEGTX.cjs} +7 -7
  33. package/dist/tsup/{chunk-UBB32UOG.cjs.map → chunk-SSPTEGTX.cjs.map} +1 -1
  34. package/dist/tsup/{chunk-4ESGNS3Z.cjs → chunk-TAG6UEL5.cjs} +17 -11
  35. package/dist/tsup/chunk-TAG6UEL5.cjs.map +1 -0
  36. package/dist/tsup/{chunk-EQKSWDIH.cjs → chunk-TXUHVBKH.cjs} +3 -3
  37. package/dist/tsup/{chunk-EQKSWDIH.cjs.map → chunk-TXUHVBKH.cjs.map} +1 -1
  38. package/dist/tsup/{chunk-PZBWSCQR.cjs → chunk-TZPNSOG2.cjs} +203 -195
  39. package/dist/tsup/chunk-TZPNSOG2.cjs.map +1 -0
  40. package/dist/tsup/{chunk-YYIDQBBM.js → chunk-VOYNLY57.js} +41 -33
  41. package/dist/tsup/chunk-VOYNLY57.js.map +1 -0
  42. package/dist/tsup/{chunk-UN5JNDBT.js → chunk-XUODFCRJ.js} +4 -4
  43. package/dist/tsup/{chunk-34Q4YVCX.js → chunk-ZIPXAVKR.js} +2 -2
  44. package/dist/tsup/client/mod.cjs +6 -6
  45. package/dist/tsup/client/mod.d.cts +2 -2
  46. package/dist/tsup/client/mod.d.ts +2 -2
  47. package/dist/tsup/client/mod.js +5 -5
  48. package/dist/tsup/common/log.cjs +3 -3
  49. package/dist/tsup/common/log.js +2 -2
  50. package/dist/tsup/common/websocket.cjs +4 -4
  51. package/dist/tsup/common/websocket.js +3 -3
  52. package/dist/tsup/{config-Bi1r6gI7.d.ts → config-BGTanB_3.d.ts} +18 -2
  53. package/dist/tsup/{config-BXSV17G7.d.cts → config-NHz6oMb9.d.cts} +18 -2
  54. package/dist/tsup/{context-4fJemY0D.d.cts → context-DB8zG_Ib.d.cts} +1 -1
  55. package/dist/tsup/{context-D4sNYboo.d.ts → context-SHomdVV8.d.ts} +1 -1
  56. package/dist/tsup/db/drizzle.cjs +3 -3
  57. package/dist/tsup/db/drizzle.js +2 -2
  58. package/dist/tsup/db/mod.cjs +4 -4
  59. package/dist/tsup/db/mod.js +3 -3
  60. package/dist/tsup/dynamic/mod.d.cts +1 -1
  61. package/dist/tsup/dynamic/mod.d.ts +1 -1
  62. package/dist/tsup/inspector/mod.cjs +6 -6
  63. package/dist/tsup/inspector/mod.js +5 -5
  64. package/dist/tsup/inspector/workflow.cjs +5 -5
  65. package/dist/tsup/inspector/workflow.js +4 -4
  66. package/dist/tsup/inspector-tab/mod.d.cts +2 -2
  67. package/dist/tsup/inspector-tab/mod.d.ts +2 -2
  68. package/dist/tsup/mod.cjs +423 -177
  69. package/dist/tsup/mod.cjs.map +1 -1
  70. package/dist/tsup/mod.d.cts +3 -3
  71. package/dist/tsup/mod.d.ts +3 -3
  72. package/dist/tsup/mod.js +322 -76
  73. package/dist/tsup/mod.js.map +1 -1
  74. package/dist/tsup/test/mod.cjs +7 -7
  75. package/dist/tsup/test/mod.d.cts +1 -1
  76. package/dist/tsup/test/mod.d.ts +1 -1
  77. package/dist/tsup/test/mod.js +5 -5
  78. package/dist/tsup/utils.cjs +3 -3
  79. package/dist/tsup/utils.js +2 -2
  80. package/dist/tsup/workflow/mod.cjs +11 -11
  81. package/dist/tsup/workflow/mod.d.cts +3 -3
  82. package/dist/tsup/workflow/mod.d.ts +3 -3
  83. package/dist/tsup/workflow/mod.js +5 -5
  84. package/package.json +9 -8
  85. package/src/actor/errors.ts +2 -1
  86. package/src/client/actor-handle.ts +10 -3
  87. package/src/client/raw-utils.ts +8 -0
  88. package/src/common/actor-router-consts.ts +2 -0
  89. package/src/engine-client/actor-http-client.ts +6 -22
  90. package/src/engine-client/mod.ts +1 -1
  91. package/src/registry/config/index.ts +27 -1
  92. package/src/registry/index.ts +48 -14
  93. package/src/registry/napi-runtime.ts +32 -5
  94. package/src/registry/native-http.ts +225 -0
  95. package/src/registry/native.ts +130 -64
  96. package/src/registry/runtime.ts +30 -2
  97. package/src/utils/env-vars.ts +4 -0
  98. package/dist/tsup/chunk-4ESGNS3Z.cjs.map +0 -1
  99. package/dist/tsup/chunk-IXBD7BXC.js.map +0 -1
  100. package/dist/tsup/chunk-OLGQYFUW.js.map +0 -1
  101. package/dist/tsup/chunk-PZBWSCQR.cjs.map +0 -1
  102. package/dist/tsup/chunk-SPJORZMM.cjs.map +0 -1
  103. package/dist/tsup/chunk-YYIDQBBM.js.map +0 -1
  104. /package/dist/tsup/{chunk-PSXMESQJ.js.map → chunk-EBXARMGI.js.map} +0 -0
  105. /package/dist/tsup/{chunk-WVFTFWJL.js.map → chunk-GEN4NHXM.js.map} +0 -0
  106. /package/dist/tsup/{chunk-XI4MEUUI.js.map → chunk-JYTXOMM7.js.map} +0 -0
  107. /package/dist/tsup/{chunk-NHI5L7C7.js.map → chunk-RBXJWAJB.js.map} +0 -0
  108. /package/dist/tsup/{chunk-UN5JNDBT.js.map → chunk-XUODFCRJ.js.map} +0 -0
  109. /package/dist/tsup/{chunk-34Q4YVCX.js.map → chunk-ZIPXAVKR.js.map} +0 -0
package/dist/tsup/mod.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  decodeWorkflowHistoryTransport
3
- } from "./chunk-WVFTFWJL.js";
3
+ } from "./chunk-GEN4NHXM.js";
4
4
  import {
5
5
  ACTOR_CONTEXT_INTERNAL_SYMBOL,
6
6
  ActorConfigSchema,
@@ -20,6 +20,7 @@ import {
20
20
  import {
21
21
  ALLOWED_PUBLIC_HEADERS,
22
22
  HEADER_CONN_PARAMS,
23
+ HEADER_ORIGINAL_REQUEST_URL,
23
24
  RemoteEngineControlClient,
24
25
  convertRegistryConfigToClientConfig,
25
26
  createClientWithDriver,
@@ -27,18 +28,18 @@ import {
27
28
  isResponseLike,
28
29
  tryParseEndpoint,
29
30
  updateRunnerConfig
30
- } from "./chunk-YYIDQBBM.js";
31
+ } from "./chunk-VOYNLY57.js";
31
32
  import {
32
33
  makePrefixedKey,
33
34
  removePrefixFromKey
34
35
  } from "./chunk-JI6GZ2C2.js";
36
+ import "./chunk-JYTXOMM7.js";
35
37
  import {
36
38
  bindNativeStateTransactionContext,
37
39
  db,
38
40
  registerNativeStateTransactionOpener
39
- } from "./chunk-PSXMESQJ.js";
41
+ } from "./chunk-EBXARMGI.js";
40
42
  import "./chunk-JTHHCZCZ.js";
41
- import "./chunk-XI4MEUUI.js";
42
43
  import {
43
44
  LogLevelSchema,
44
45
  VERSION,
@@ -61,6 +62,7 @@ import {
61
62
  getRivetRunEngineHost,
62
63
  getRivetRunEnginePort,
63
64
  getRivetRunEngineVersion,
65
+ getRivetRunServices,
64
66
  getRivetToken,
65
67
  getRivetTotalSlots,
66
68
  getRivetkitPublicDir,
@@ -71,7 +73,7 @@ import {
71
73
  parsePortEnv,
72
74
  stringifyError,
73
75
  toUint8Array
74
- } from "./chunk-OLGQYFUW.js";
76
+ } from "./chunk-MF42PRF2.js";
75
77
  import {
76
78
  INTERNAL_ERROR_CODE,
77
79
  RivetError,
@@ -83,7 +85,7 @@ import {
83
85
  isRivetErrorLike,
84
86
  toRivetError,
85
87
  unsupportedFeature
86
- } from "./chunk-IXBD7BXC.js";
88
+ } from "./chunk-OUQUIBVW.js";
87
89
 
88
90
  // src/actor/log.ts
89
91
  function loggerWithoutContext() {
@@ -729,6 +731,12 @@ var RegistryConfigSchema = z3.object({
729
731
  enginePort: z3.number().int().min(1).max(65535).optional().default(() => getRivetRunEnginePort() ?? ENGINE_PORT),
730
732
  /** @experimental */
731
733
  engineVersion: z3.string().optional().default(() => getRivetRunEngineVersion() ?? VERSION),
734
+ /**
735
+ * Starts the first-party Services actor host when RivetKit manages
736
+ * a local engine. Defaults to the local-engine decision. Set
737
+ * RIVET_RUN_SERVICES=0 or 1 to override it.
738
+ */
739
+ startServices: z3.boolean().optional(),
732
740
  /**
733
741
  * @experimental
734
742
  *
@@ -809,6 +817,7 @@ var RegistryConfigSchema = z3.object({
809
817
  config.enginePort
810
818
  );
811
819
  const endpoint = config.startEngine ? localEngineEndpoint : (parsedEndpoint == null ? void 0 : parsedEndpoint.endpoint) ?? (isDevEnv ? localEngineEndpoint : void 0);
820
+ const startServices = config.startServices ?? getRivetRunServices() ?? Boolean(endpoint && isLocalEngineEndpoint(endpoint));
812
821
  const validateServerlessEndpoint = Boolean(
813
822
  config.startEngine || parsedEndpoint
814
823
  );
@@ -832,6 +841,7 @@ var RegistryConfigSchema = z3.object({
832
841
  ...config,
833
842
  sqlite,
834
843
  endpoint,
844
+ startServices,
835
845
  namespace,
836
846
  token,
837
847
  publicEndpoint,
@@ -945,6 +955,9 @@ var DocRegistryConfigSchema = z3.object({
945
955
  engineVersion: z3.string().optional().describe(
946
956
  "Version of the local engine package to use. Defaults to the current RivetKit version."
947
957
  ),
958
+ startServices: z3.boolean().optional().describe(
959
+ "Starts Services when RivetKit manages a local Engine. Defaults to the local-Engine decision. Set RIVET_RUN_SERVICES=0 or 1 to override."
960
+ ),
948
961
  configurePool: DocConfigurePoolSchema.describe(
949
962
  "Automatically configure serverless runners in the engine."
950
963
  ),
@@ -1466,16 +1479,30 @@ function toNapiApplication(application) {
1466
1479
  if (!request) {
1467
1480
  throw new Error("application fetch callback received no request");
1468
1481
  }
1469
- const response = await application({
1470
- ...request,
1471
- body: new Uint8Array(request.body)
1472
- });
1482
+ const response = await application(
1483
+ {
1484
+ ...request,
1485
+ body: new Uint8Array(request.body),
1486
+ cancelToken: request.cancelToken
1487
+ },
1488
+ request.responseBodyStream ? fromNapiHttpResponseBodyStream(
1489
+ request.responseBodyStream
1490
+ ) : void 0
1491
+ );
1473
1492
  return {
1474
1493
  ...response,
1475
- body: toNapiBuffer(response.body)
1494
+ body: response.body === void 0 ? void 0 : toNapiBuffer(response.body)
1476
1495
  };
1477
1496
  };
1478
1497
  }
1498
+ function fromNapiHttpResponseBodyStream(stream) {
1499
+ return {
1500
+ cancelled: () => stream.cancelled(),
1501
+ write: (chunk) => stream.write(Buffer.from(chunk)),
1502
+ end: () => stream.end(),
1503
+ error: (message) => stream.error(message)
1504
+ };
1505
+ }
1479
1506
  function toNapiHttpRequest(request) {
1480
1507
  if (!request) {
1481
1508
  return request;
@@ -2019,6 +2046,149 @@ async function loadNapiRuntime() {
2019
2046
  };
2020
2047
  }
2021
2048
 
2049
+ // src/registry/native-http.ts
2050
+ var HTTP_BODY_CHUNK_SIZE = 64 * 1024;
2051
+ function runtimeBytesToArrayBuffer(value) {
2052
+ return value.buffer.slice(
2053
+ value.byteOffset,
2054
+ value.byteOffset + value.byteLength
2055
+ );
2056
+ }
2057
+ function buildNativeHttpRequest(init) {
2058
+ var _a;
2059
+ const headers = new Headers(init.headers);
2060
+ const originalUrl = headers.get(HEADER_ORIGINAL_REQUEST_URL);
2061
+ headers.delete(HEADER_ORIGINAL_REQUEST_URL);
2062
+ const url = originalUrl ?? (init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString());
2063
+ const method2 = init.method.toUpperCase();
2064
+ const bodyForbidden = method2 === "GET" || method2 === "HEAD";
2065
+ const body = bodyForbidden ? void 0 : init.bodyStream ? new ReadableStream({
2066
+ async pull(controller) {
2067
+ var _a2, _b;
2068
+ try {
2069
+ if (init.body && init.body.length > 0) {
2070
+ controller.enqueue(new Uint8Array(init.body));
2071
+ init.body = void 0;
2072
+ return;
2073
+ }
2074
+ const chunk = await ((_a2 = init.bodyStream) == null ? void 0 : _a2.read());
2075
+ if (!chunk) {
2076
+ controller.close();
2077
+ } else {
2078
+ controller.enqueue(new Uint8Array(chunk));
2079
+ }
2080
+ } catch (error) {
2081
+ (_b = init.abortController) == null ? void 0 : _b.abort(error);
2082
+ controller.error(error);
2083
+ }
2084
+ },
2085
+ async cancel() {
2086
+ var _a2;
2087
+ await ((_a2 = init.bodyStream) == null ? void 0 : _a2.cancel());
2088
+ }
2089
+ }) : init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
2090
+ const streamInit = init.bodyStream && !bodyForbidden ? { duplex: "half" } : {};
2091
+ return new Request(url, {
2092
+ method: method2,
2093
+ headers,
2094
+ body,
2095
+ signal: ((_a = init.abortController) == null ? void 0 : _a.signal) ?? init.signal,
2096
+ ...streamInit
2097
+ });
2098
+ }
2099
+ async function cancelNativeHttpRequestBody(bodyStream) {
2100
+ await (bodyStream == null ? void 0 : bodyStream.cancel());
2101
+ }
2102
+ async function writeResponseChunk(stream, chunk) {
2103
+ for (let offset = 0; offset < chunk.byteLength; offset += HTTP_BODY_CHUNK_SIZE) {
2104
+ await stream.write(
2105
+ chunk.subarray(offset, offset + HTTP_BODY_CHUNK_SIZE)
2106
+ );
2107
+ }
2108
+ }
2109
+ async function pumpResponseBody(reader, stream) {
2110
+ var _a;
2111
+ const cancelled = stream.cancelled().then(() => ({ cancelled: true }));
2112
+ try {
2113
+ for (; ; ) {
2114
+ const read = reader.read().then((next2) => ({ cancelled: false, next: next2 }));
2115
+ const result = await Promise.race([read, cancelled]);
2116
+ if (result.cancelled) {
2117
+ void reader.cancel(
2118
+ new Error(
2119
+ "native http response stream receiver dropped"
2120
+ )
2121
+ ).catch((error) => {
2122
+ logger2().debug({
2123
+ msg: "failed to cancel native http response reader",
2124
+ error
2125
+ });
2126
+ });
2127
+ return;
2128
+ }
2129
+ const { next } = result;
2130
+ if (next.done) {
2131
+ await stream.end();
2132
+ return;
2133
+ }
2134
+ if ((_a = next.value) == null ? void 0 : _a.byteLength) {
2135
+ await writeResponseChunk(stream, next.value);
2136
+ }
2137
+ }
2138
+ } catch (error) {
2139
+ try {
2140
+ await stream.error(stringifyError(error));
2141
+ } catch (streamError) {
2142
+ logger2().debug({
2143
+ msg: "failed to report native http response stream error",
2144
+ error: streamError
2145
+ });
2146
+ }
2147
+ void reader.cancel(error).catch(() => {
2148
+ });
2149
+ } finally {
2150
+ try {
2151
+ reader.releaseLock();
2152
+ } catch (error) {
2153
+ logger2().debug({
2154
+ msg: "failed to release native http response reader lock",
2155
+ error
2156
+ });
2157
+ }
2158
+ }
2159
+ }
2160
+ async function convertNativeHttpResponse(response, responseBodyStream) {
2161
+ const headers = Object.fromEntries(response.headers.entries());
2162
+ if (!response.body) {
2163
+ return {
2164
+ response: {
2165
+ status: response.status,
2166
+ headers,
2167
+ body: new Uint8Array()
2168
+ }
2169
+ };
2170
+ }
2171
+ if (responseBodyStream) {
2172
+ const reader = response.body.getReader();
2173
+ const bodyCompletion = pumpResponseBody(reader, responseBodyStream);
2174
+ return {
2175
+ response: {
2176
+ status: response.status,
2177
+ headers,
2178
+ stream: true
2179
+ },
2180
+ bodyCompletion
2181
+ };
2182
+ }
2183
+ return {
2184
+ response: {
2185
+ status: response.status,
2186
+ headers,
2187
+ body: new Uint8Array(await response.arrayBuffer())
2188
+ }
2189
+ };
2190
+ }
2191
+
2022
2192
  // src/registry/native-validation.ts
2023
2193
  var CONN_PARAMS_KEY = "__conn_params__";
2024
2194
  function validateActionArgs(schemas, name, args) {
@@ -3477,7 +3647,7 @@ function toRuntimeBytes(value) {
3477
3647
  function arrayBufferViewToRuntimeBytes(value) {
3478
3648
  return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
3479
3649
  }
3480
- function runtimeBytesToArrayBuffer(value) {
3650
+ function runtimeBytesToArrayBuffer2(value) {
3481
3651
  return value.buffer.slice(
3482
3652
  value.byteOffset,
3483
3653
  value.byteOffset + value.byteLength
@@ -3523,6 +3693,9 @@ function decodeNativeKvValue(value, options) {
3523
3693
  async function loadEngineCli() {
3524
3694
  return import(["@rivetkit", "engine-cli"].join("/"));
3525
3695
  }
3696
+ async function loadServices() {
3697
+ return import(["@rivet-dev", "services"].join("/"));
3698
+ }
3526
3699
  function decodeValue(value) {
3527
3700
  if (!value || value.length === 0) {
3528
3701
  return void 0;
@@ -3808,24 +3981,6 @@ function decodeArgs(value) {
3808
3981
  const decoded = decodeValue(value);
3809
3982
  return normalizeArgs(decoded);
3810
3983
  }
3811
- function buildRequest(init) {
3812
- const url = init.uri.startsWith("http") ? init.uri : new URL(init.uri, "http://127.0.0.1").toString();
3813
- const body = init.body && init.body.length > 0 ? runtimeBytesToArrayBuffer(init.body) : void 0;
3814
- return new Request(url, {
3815
- method: init.method,
3816
- headers: init.headers,
3817
- body
3818
- });
3819
- }
3820
- async function toRuntimeHttpResponse(response) {
3821
- const headers = Object.fromEntries(response.headers.entries());
3822
- const body = new Uint8Array(await response.arrayBuffer());
3823
- return {
3824
- status: response.status,
3825
- headers,
3826
- body
3827
- };
3828
- }
3829
3984
  function toActorKey(segments) {
3830
3985
  return segments.map(
3831
3986
  (segment) => segment.kind === "number" ? String(segment.numberValue ?? 0) : segment.stringValue ?? ""
@@ -4538,7 +4693,7 @@ var NativeWebSocketAdapter = class {
4538
4693
  this.#runtime.webSocketSetEventCallback(this.#ws, (event2) => {
4539
4694
  if (event2.kind === "message") {
4540
4695
  this.#virtual.triggerMessage(
4541
- event2.binary ? runtimeBytesToArrayBuffer(event2.data) : event2.data,
4696
+ event2.binary ? runtimeBytesToArrayBuffer2(event2.data) : event2.data,
4542
4697
  event2.messageIndex
4543
4698
  );
4544
4699
  return;
@@ -5921,12 +6076,14 @@ function buildNativeFactory(runtime, registryConfig, definition) {
5921
6076
  cancelToken,
5922
6077
  run !== void 0
5923
6078
  );
5924
- const maybeHandleNativeInspectorRequest = async (ctx, _rawRequest, jsRequest) => {
6079
+ const maybeHandleNativeInspectorRequest = async (ctx, rawRequest) => {
5925
6080
  var _a2, _b, _c, _d;
5926
- const url = new URL(jsRequest.url);
6081
+ const rawUrl = rawRequest.uri.startsWith("http") ? rawRequest.uri : new URL(rawRequest.uri, "http://127.0.0.1").toString();
6082
+ const url = new URL(rawUrl);
5927
6083
  if (!url.pathname.startsWith("/inspector/")) {
5928
6084
  return void 0;
5929
6085
  }
6086
+ const jsRequest = buildNativeHttpRequest(rawRequest);
5930
6087
  const jsonResponse = (body, init) => new Response(JSON.stringify(body), {
5931
6088
  status: (init == null ? void 0 : init.status) ?? 200,
5932
6089
  headers: {
@@ -6457,7 +6614,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6457
6614
  );
6458
6615
  const actorCtx = makeActorCtx(
6459
6616
  ctx,
6460
- request ? buildRequest(request) : void 0
6617
+ request ? buildNativeHttpRequest(request) : void 0
6461
6618
  );
6462
6619
  try {
6463
6620
  await config.onBeforeConnect(
@@ -6477,7 +6634,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6477
6634
  const { ctx, conn, params, request } = unwrapTsfnPayload(error, payload);
6478
6635
  const actorCtx = makeActorCtx(
6479
6636
  ctx,
6480
- request ? buildRequest(request) : void 0
6637
+ request ? buildNativeHttpRequest(request) : void 0
6481
6638
  );
6482
6639
  const connAdapter = new NativeConnAdapter(
6483
6640
  runtime,
@@ -6515,7 +6672,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6515
6672
  );
6516
6673
  const actorCtx = makeActorCtx(
6517
6674
  ctx,
6518
- request ? buildRequest(request) : void 0
6675
+ request ? buildNativeHttpRequest(request) : void 0
6519
6676
  );
6520
6677
  const connAdapter = new NativeConnAdapter(
6521
6678
  runtime,
@@ -6622,27 +6779,45 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6622
6779
  onRequest: wrapNativeCallback(
6623
6780
  async (error, payload) => {
6624
6781
  try {
6625
- const { ctx, request, cancelToken } = unwrapTsfnPayload(
6626
- error,
6627
- payload
6628
- );
6629
- const jsRequest = buildRequest(request);
6630
- const inspectorResponse = await maybeHandleNativeInspectorRequest(
6631
- ctx,
6632
- request,
6633
- jsRequest
6634
- );
6782
+ const { ctx, request, cancelToken, responseBodyStream } = unwrapTsfnPayload(error, payload);
6783
+ const inspectorResponse = await maybeHandleNativeInspectorRequest(ctx, request);
6635
6784
  if (inspectorResponse) {
6636
- return await toRuntimeHttpResponse(inspectorResponse);
6785
+ await cancelNativeHttpRequestBody(request.bodyStream);
6786
+ return (await convertNativeHttpResponse(
6787
+ inspectorResponse,
6788
+ responseBodyStream
6789
+ )).response;
6637
6790
  }
6638
6791
  if (typeof config.onRequest !== "function") {
6639
- return await toRuntimeHttpResponse(
6640
- new Response(null, { status: 404 })
6641
- );
6792
+ await cancelNativeHttpRequestBody(request.bodyStream);
6793
+ return (await convertNativeHttpResponse(
6794
+ new Response(null, { status: 404 }),
6795
+ responseBodyStream
6796
+ )).response;
6642
6797
  }
6643
- const rawConnParams = jsRequest.headers.get(HEADER_CONN_PARAMS);
6798
+ const requestAbortController = new AbortController();
6799
+ const handlerRequest = buildNativeHttpRequest({
6800
+ ...request,
6801
+ abortController: requestAbortController
6802
+ });
6803
+ const rawConnParams = handlerRequest.headers.get(HEADER_CONN_PARAMS);
6644
6804
  let requestCtx;
6645
6805
  let conn;
6806
+ let removeRequestAbortListener;
6807
+ let cleanupDeferredToBody = false;
6808
+ let cleanedUp = false;
6809
+ const cleanupRequest = async () => {
6810
+ if (cleanedUp) return;
6811
+ cleanedUp = true;
6812
+ removeRequestAbortListener == null ? void 0 : removeRequestAbortListener();
6813
+ try {
6814
+ await (requestCtx == null ? void 0 : requestCtx.dispose());
6815
+ } finally {
6816
+ if (conn) {
6817
+ await runtime.connDisconnect(conn);
6818
+ }
6819
+ }
6820
+ };
6646
6821
  try {
6647
6822
  const connParams = validateConnParams(
6648
6823
  schemaConfig.connParamsSchema,
@@ -6658,23 +6833,56 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6658
6833
  requestCtx = makeConnCtx(
6659
6834
  ctx,
6660
6835
  conn,
6661
- jsRequest,
6836
+ handlerRequest,
6662
6837
  cancelToken
6663
6838
  );
6839
+ const ctxAbortSignal = requestCtx.abortSignal;
6840
+ const abortRequest = () => requestAbortController.abort(ctxAbortSignal.reason);
6841
+ if (ctxAbortSignal.aborted) {
6842
+ abortRequest();
6843
+ } else {
6844
+ ctxAbortSignal.addEventListener(
6845
+ "abort",
6846
+ abortRequest,
6847
+ { once: true }
6848
+ );
6849
+ removeRequestAbortListener = () => ctxAbortSignal.removeEventListener(
6850
+ "abort",
6851
+ abortRequest
6852
+ );
6853
+ }
6664
6854
  const response = await config.onRequest(
6665
6855
  requestCtx,
6666
- jsRequest
6856
+ handlerRequest
6667
6857
  );
6668
6858
  if (!isResponseLike(response)) {
6669
6859
  throw new Error(
6670
6860
  "onRequest handler must return a Response"
6671
6861
  );
6672
6862
  }
6673
- return await toRuntimeHttpResponse(response);
6863
+ const conversion = await convertNativeHttpResponse(
6864
+ response,
6865
+ responseBodyStream
6866
+ );
6867
+ if (conversion.bodyCompletion) {
6868
+ cleanupDeferredToBody = true;
6869
+ void conversion.bodyCompletion.then(cleanupRequest).catch((cleanupError) => {
6870
+ logger2().error({
6871
+ msg: "failed to clean up native streaming http request",
6872
+ error: cleanupError
6873
+ });
6874
+ });
6875
+ }
6876
+ return conversion.response;
6674
6877
  } finally {
6675
- await (requestCtx == null ? void 0 : requestCtx.dispose());
6676
- if (conn) {
6677
- await runtime.connDisconnect(conn);
6878
+ try {
6879
+ await cancelNativeHttpRequestBody(
6880
+ request.bodyStream
6881
+ );
6882
+ } finally {
6883
+ if (!cleanupDeferredToBody) {
6884
+ await cleanupRequest();
6885
+ }
6678
6886
  }
6679
6887
  }
6680
6888
  } catch (error2) {
@@ -6689,7 +6897,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6689
6897
  onWebSocket: typeof config.onWebSocket === "function" ? wrapNativeCallback(
6690
6898
  async (error, payload) => {
6691
6899
  const { ctx, conn, ws, request } = unwrapTsfnPayload(error, payload);
6692
- const jsRequest = request ? buildRequest(request) : void 0;
6900
+ const jsRequest = request ? buildNativeHttpRequest(request) : void 0;
6693
6901
  const actorCtx = makeConnCtx(ctx, conn, jsRequest);
6694
6902
  try {
6695
6903
  await config.onWebSocket(
@@ -6795,7 +7003,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6795
7003
  timeoutMs,
6796
7004
  cancelToken
6797
7005
  } = unwrapTsfnPayload(error, payload);
6798
- const jsRequest = buildRequest(request);
7006
+ const jsRequest = buildNativeHttpRequest(request);
6799
7007
  const actorCtx = withConnContext(
6800
7008
  runtime,
6801
7009
  ctx,
@@ -6865,7 +7073,7 @@ function buildNativeFactory(runtime, registryConfig, definition) {
6865
7073
  buildActorConfig(definition, registryConfig, runtime.kind)
6866
7074
  );
6867
7075
  }
6868
- async function buildServeConfig(config) {
7076
+ async function buildServeConfig(config, resolveServicesBinary = true) {
6869
7077
  var _a;
6870
7078
  if (!config.endpoint) {
6871
7079
  throw nativeEndpointNotConfiguredError();
@@ -6876,6 +7084,7 @@ async function buildServeConfig(config) {
6876
7084
  token: config.token,
6877
7085
  namespace: config.namespace,
6878
7086
  poolName: config.envoy.poolName,
7087
+ startServices: resolveServicesBinary && config.startServices,
6879
7088
  handleInspectorHttpInRuntime: true,
6880
7089
  serverlessBasePath: config.serverless.basePath,
6881
7090
  serverlessPackageVersion: VERSION,
@@ -6894,6 +7103,17 @@ async function buildServeConfig(config) {
6894
7103
  error: stringifyError(error)
6895
7104
  });
6896
7105
  }
7106
+ if (resolveServicesBinary && config.startServices) {
7107
+ try {
7108
+ const { getServicesPath } = await loadServices();
7109
+ serveConfig.servicesBinaryPath = getServicesPath();
7110
+ } catch (error) {
7111
+ logger2().warn({
7112
+ msg: "could not resolve the Services binary; a local engine will fail with services.binary_unavailable \u2014 set RIVET_RUN_SERVICES=0 to disable Services or RIVET_SERVICES_BINARY to a local rivet-services binary",
7113
+ error: stringifyError(error)
7114
+ });
7115
+ }
7116
+ }
6897
7117
  serveConfig.engineHost = config.engineHost;
6898
7118
  serveConfig.enginePort = config.enginePort;
6899
7119
  if ((_a = config.test) == null ? void 0 : _a.enabled) {
@@ -6920,7 +7140,7 @@ async function buildRegistryWithRuntime(config, runtime) {
6920
7140
  return {
6921
7141
  runtime,
6922
7142
  registry,
6923
- serveConfig: await buildServeConfig(config)
7143
+ serveConfig: await buildServeConfig(config, runtime.kind === "napi")
6924
7144
  };
6925
7145
  }
6926
7146
  async function buildConfiguredRegistry(config) {
@@ -6947,15 +7167,27 @@ function finishShutdownSignal(signal) {
6947
7167
  }
6948
7168
  process.kill(process.pid, signal);
6949
7169
  }
6950
- function createApplicationFetch(application) {
6951
- return async (request) => {
7170
+ function createApplicationFetch(application, runtime) {
7171
+ return async (request, responseBodyStream) => {
6952
7172
  const method2 = request.method.toUpperCase();
6953
7173
  const body = method2 === "GET" || method2 === "HEAD" || request.body.length === 0 ? void 0 : Uint8Array.from(request.body).buffer;
7174
+ const abortController = new AbortController();
7175
+ if (request.cancelToken) {
7176
+ if (runtime.cancellationTokenAborted(request.cancelToken)) {
7177
+ abortController.abort();
7178
+ } else {
7179
+ runtime.onCancellationTokenCancelled(
7180
+ request.cancelToken,
7181
+ () => abortController.abort()
7182
+ );
7183
+ }
7184
+ }
6954
7185
  const response = await application.fetch(
6955
7186
  new Request(request.url, {
6956
7187
  method: method2,
6957
7188
  headers: request.headers,
6958
- body
7189
+ body,
7190
+ signal: abortController.signal
6959
7191
  })
6960
7192
  );
6961
7193
  if (!isResponseLike(response)) {
@@ -6963,10 +7195,23 @@ function createApplicationFetch(application) {
6963
7195
  "registry.listen() application fetch must return a Response"
6964
7196
  );
6965
7197
  }
7198
+ const conversion = await convertNativeHttpResponse(
7199
+ response,
7200
+ responseBodyStream
7201
+ );
7202
+ if (conversion.bodyCompletion) {
7203
+ void conversion.bodyCompletion.catch((error) => {
7204
+ logger2().error({
7205
+ msg: "application response stream failed",
7206
+ error
7207
+ });
7208
+ });
7209
+ }
6966
7210
  return {
6967
- status: response.status,
6968
- headers: Object.fromEntries(response.headers.entries()),
6969
- body: new Uint8Array(await response.arrayBuffer())
7211
+ status: conversion.response.status ?? response.status,
7212
+ headers: conversion.response.headers ?? Object.fromEntries(response.headers.entries()),
7213
+ body: conversion.response.body,
7214
+ stream: conversion.response.stream
6970
7215
  };
6971
7216
  };
6972
7217
  }
@@ -7224,8 +7469,7 @@ var Registry = class {
7224
7469
  const port = opts.port ?? parsePortEnv(process.env.RIVET_PORT) ?? 3e3;
7225
7470
  const publicDir = opts.publicDir ?? getRivetkitPublicDir();
7226
7471
  const config = this.parseConfig();
7227
- const application = opts.application ? createApplicationFetch(opts.application) : void 0;
7228
- if (application && getRivetkitRuntimeMode() !== "serverless") {
7472
+ if (opts.application && getRivetkitRuntimeMode() !== "serverless") {
7229
7473
  if (config.runtime === "wasm") {
7230
7474
  throw new Error(
7231
7475
  "registry.listen() requires the native runtime; use an application-owned HTTP server with WebAssembly"
@@ -7244,13 +7488,18 @@ var Registry = class {
7244
7488
  throw new Error("registry envoy startup did not initialize");
7245
7489
  }
7246
7490
  const { runtime: runtime2, registry: registry2, serveConfig: serveConfig2 } = await configuredRegistryPromise2;
7491
+ const application2 = createApplicationFetch(
7492
+ opts.application,
7493
+ runtime2
7494
+ );
7495
+ await readyPromise;
7247
7496
  const listenerPromise = runtime2.serveApplicationListener(
7248
7497
  registry2,
7249
7498
  {
7250
7499
  port,
7251
7500
  host: opts.host,
7252
7501
  publicDir,
7253
- application
7502
+ application: application2
7254
7503
  },
7255
7504
  serveConfig2
7256
7505
  );
@@ -7261,14 +7510,10 @@ var Registry = class {
7261
7510
  "registry envoy serve lifecycle did not initialize"
7262
7511
  );
7263
7512
  }
7264
- await Promise.all([
7265
- readyPromise,
7266
- listenerPromise,
7267
- serveLifecyclePromise
7268
- ]);
7513
+ await Promise.all([listenerPromise, serveLifecyclePromise]);
7269
7514
  return;
7270
7515
  }
7271
- const configuredRegistryPromise = buildConfiguredRegistry(config);
7516
+ const configuredRegistryPromise = this.#buildConfiguredRegistry(config);
7272
7517
  this.#runtimeServeConfiguredPromise = configuredRegistryPromise;
7273
7518
  this.#runtimeServerlessPromise = configuredRegistryPromise;
7274
7519
  this.#installSignalHandlers(config);
@@ -7279,6 +7524,7 @@ var Registry = class {
7279
7524
  });
7280
7525
  this.#ensureServerlessPoolConfigured(config);
7281
7526
  const { runtime, registry, serveConfig } = await configuredRegistryPromise;
7527
+ const application = opts.application ? createApplicationFetch(opts.application, runtime) : void 0;
7282
7528
  await runtime.serveListener(
7283
7529
  registry,
7284
7530
  {