@floegence/flowersec-core 6.1.0 → 7.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (713) hide show
  1. package/README.md +101 -170
  2. package/THIRD_PARTY_NOTICES.md +10 -3075
  3. package/dist/browser/connectSessionV3.d.ts +44 -0
  4. package/dist/browser/connectSessionV3.js +261 -0
  5. package/dist/browser/directWebSocketProfileV1.d.ts +14 -0
  6. package/dist/browser/directWebSocketProfileV1.js +71 -0
  7. package/dist/browser/httpDirectV1.d.ts +30 -0
  8. package/dist/browser/httpDirectV1.js +52 -0
  9. package/dist/browser/index.d.ts +10 -15
  10. package/dist/browser/index.js +4 -5
  11. package/dist/browser/privateLoopbackV1.d.ts +30 -0
  12. package/dist/browser/privateLoopbackV1.js +70 -0
  13. package/dist/cli.d.ts +1 -24
  14. package/dist/cli.js +129 -91
  15. package/dist/cliSpendMarker.js +8 -0
  16. package/dist/defaults.d.ts +23 -1
  17. package/dist/defaults.js +23 -1
  18. package/dist/facade.d.ts +21 -104
  19. package/dist/facade.js +8 -45
  20. package/dist/framing/jsonframe.d.ts +21 -0
  21. package/dist/framing/jsonframe.js +107 -0
  22. package/dist/node/acceptor.d.ts +1 -0
  23. package/dist/node/acceptor.js +1 -0
  24. package/dist/node/acceptorV3.d.ts +70 -0
  25. package/dist/node/acceptorV3.js +296 -0
  26. package/dist/node/byteStreamDuplex.d.ts +4 -0
  27. package/dist/node/byteStreamDuplex.js +69 -0
  28. package/dist/node/connectSessionV3.d.ts +33 -0
  29. package/dist/node/connectSessionV3.js +99 -0
  30. package/dist/node/connectionPath.d.ts +0 -2
  31. package/dist/node/connectionPath.js +0 -18
  32. package/dist/node/index.d.ts +16 -52
  33. package/dist/node/index.js +6 -24
  34. package/dist/node/listenerIngress.d.ts +5 -0
  35. package/dist/node/listenerIngress.js +12 -0
  36. package/dist/node/nativeTransportAddon.d.ts +138 -0
  37. package/dist/node/nativeTransportAddon.js +233 -0
  38. package/dist/node/proxyServer.d.ts +4 -30
  39. package/dist/node/proxyServer.js +169 -600
  40. package/dist/node/rawQuicAdapterV3.d.ts +11 -0
  41. package/dist/node/rawQuicAdapterV3.js +83 -0
  42. package/dist/node/rawQuicServerV3.d.ts +36 -0
  43. package/dist/node/rawQuicServerV3.js +64 -0
  44. package/dist/node/runtimeAuthorizationV3.d.ts +41 -0
  45. package/dist/node/runtimeAuthorizationV3.js +156 -0
  46. package/dist/node/tunnelRuntimeV3.d.ts +60 -0
  47. package/dist/node/tunnelRuntimeV3.js +838 -0
  48. package/dist/node/webSocketServerV3.d.ts +28 -0
  49. package/dist/node/webSocketServerV3.js +223 -0
  50. package/dist/proxy/fetch.d.ts +2 -3
  51. package/dist/proxy/fetch.js +29 -96
  52. package/dist/proxy/index.d.ts +1 -5
  53. package/dist/proxy/index.js +0 -2
  54. package/dist/proxy/integration.d.ts +8 -12
  55. package/dist/proxy/integration.js +16 -23
  56. package/dist/proxy/policy.d.ts +0 -5
  57. package/dist/proxy/policy.js +22 -60
  58. package/dist/proxy/runtime.d.ts +1 -3
  59. package/dist/proxy/runtime.js +186 -404
  60. package/dist/proxy/scope.js +2 -2
  61. package/dist/proxy/serviceWorker.d.ts +0 -3
  62. package/dist/proxy/serviceWorker.js +176 -634
  63. package/dist/proxy/serviceWorkerRuntime.js +1 -26
  64. package/dist/proxy/stream.d.ts +6 -17
  65. package/dist/proxy/stream.js +40 -9
  66. package/dist/proxy/types.d.ts +11 -50
  67. package/dist/proxy/windowBridge.d.ts +3 -11
  68. package/dist/proxy/windowBridge.js +31 -70
  69. package/dist/proxy/wsPatch.js +26 -34
  70. package/dist/public/contract.d.ts +74 -1
  71. package/dist/public/contract.js +8 -0
  72. package/dist/public/sessionHandlers.d.ts +47 -0
  73. package/dist/public/sessionHandlers.js +151 -0
  74. package/dist/public/streamHandlers.d.ts +20 -0
  75. package/dist/public/streamHandlers.js +127 -0
  76. package/dist/public/streamMetadata.d.ts +2 -34
  77. package/dist/public/streamMetadata.js +13 -206
  78. package/dist/rpc/client.d.ts +34 -0
  79. package/dist/rpc/client.js +244 -0
  80. package/dist/rpc/server.d.ts +59 -0
  81. package/dist/rpc/server.js +255 -0
  82. package/dist/rpc/validate.d.ts +4 -0
  83. package/dist/{application/rpcJSON.js → rpc/validate.js} +1 -1
  84. package/dist/rpc/wire.d.ts +15 -0
  85. package/dist/v3/admissionError.d.ts +4 -0
  86. package/dist/v3/admissionError.js +8 -0
  87. package/dist/v3/artifact.d.ts +145 -0
  88. package/dist/v3/artifact.js +1180 -0
  89. package/dist/v3/artifactLease.d.ts +19 -0
  90. package/dist/v3/artifactLease.js +128 -0
  91. package/dist/v3/browserRuntime.d.ts +37 -0
  92. package/dist/v3/browserRuntime.js +197 -0
  93. package/dist/v3/browserSessionRuntime.d.ts +2 -0
  94. package/dist/v3/browserSessionRuntime.js +21 -0
  95. package/dist/v3/capability.d.ts +32 -0
  96. package/dist/v3/capability.js +345 -0
  97. package/dist/v3/carrier.d.ts +86 -0
  98. package/dist/v3/carrier.js +414 -0
  99. package/dist/v3/connectionController.d.ts +101 -0
  100. package/dist/v3/connectionController.js +888 -0
  101. package/dist/v3/contract.d.ts +70 -0
  102. package/dist/v3/contract.js +3 -0
  103. package/dist/v3/controller.d.ts +45 -0
  104. package/dist/v3/controller.js +316 -0
  105. package/dist/v3/handshake.d.ts +81 -0
  106. package/dist/v3/handshake.js +471 -0
  107. package/dist/v3/jcs.d.ts +6 -0
  108. package/dist/v3/jcs.js +69 -0
  109. package/dist/v3/jsonPreflight.d.ts +1 -0
  110. package/dist/v3/jsonPreflight.js +251 -0
  111. package/dist/v3/nodeRuntime.d.ts +43 -0
  112. package/dist/v3/nodeRuntime.js +437 -0
  113. package/dist/v3/nodeSessionRuntime.d.ts +2 -0
  114. package/dist/v3/nodeSessionRuntime.js +13 -0
  115. package/dist/v3/protocol.d.ts +100 -0
  116. package/dist/v3/protocol.js +715 -0
  117. package/dist/v3/publicApi.d.ts +12 -0
  118. package/dist/v3/publicApi.js +46 -0
  119. package/dist/v3/publicSession.js +316 -0
  120. package/dist/v3/runtimeAdapters.d.ts +9 -0
  121. package/dist/v3/runtimeAdapters.js +109 -0
  122. package/dist/v3/security.d.ts +36 -0
  123. package/dist/v3/security.js +113 -0
  124. package/dist/v3/serverAdmission.d.ts +42 -0
  125. package/dist/v3/serverAdmission.js +242 -0
  126. package/dist/v3/session.d.ts +339 -0
  127. package/dist/v3/session.js +2399 -0
  128. package/dist/v3/sessionConnector.d.ts +46 -0
  129. package/dist/v3/sessionConnector.js +534 -0
  130. package/dist/v3/streamLifetimeLedger.d.ts +32 -0
  131. package/dist/v3/streamLifetimeLedger.js +146 -0
  132. package/dist/v3/streamMetadata.js +7 -0
  133. package/dist/v3/transportConstants.d.ts +56 -0
  134. package/dist/v3/transportConstants.js +59 -0
  135. package/dist/v3/tunnelIngress.d.ts +8 -0
  136. package/dist/v3/tunnelIngress.js +21 -0
  137. package/dist/v3/unreliableMessage.d.ts +44 -0
  138. package/dist/v3/unreliableMessage.js +287 -0
  139. package/dist/v3/webSocketCarrier.d.ts +33 -0
  140. package/dist/v3/webSocketCarrier.js +380 -0
  141. package/dist/v3/webTransportCarrier.d.ts +27 -0
  142. package/dist/v3/webTransportCarrier.js +580 -0
  143. package/dist/vendor/tr46.js +17 -23
  144. package/dist/ws-client/binaryTransport.d.ts +65 -0
  145. package/dist/ws-client/binaryTransport.js +348 -0
  146. package/dist/yamux/byteReader.d.ts +13 -0
  147. package/dist/yamux/byteReader.js +81 -0
  148. package/dist/yamux/constants.d.ts +10 -0
  149. package/dist/yamux/constants.js +14 -0
  150. package/dist/yamux/errors.d.ts +15 -0
  151. package/dist/yamux/errors.js +34 -0
  152. package/dist/yamux/header.d.ts +20 -0
  153. package/dist/yamux/header.js +30 -0
  154. package/dist/yamux/session.d.ts +81 -0
  155. package/dist/yamux/session.js +401 -0
  156. package/dist/yamux/stream.d.ts +42 -0
  157. package/dist/yamux/stream.js +307 -0
  158. package/package.json +23 -22
  159. package/sbom/cyclonedx.json +55 -773
  160. package/sbom/spdx.json +60 -577
  161. package/dist/application/rpcJSON.d.ts +0 -15
  162. package/dist/browser/clientV4.d.ts +0 -61
  163. package/dist/browser/clientV4.js +0 -179
  164. package/dist/browser/indexedDBPoolV4.d.ts +0 -101
  165. package/dist/browser/indexedDBPoolV4.js +0 -634
  166. package/dist/browser/liveHTTPSV4.d.ts +0 -35
  167. package/dist/browser/liveHTTPSV4.js +0 -162
  168. package/dist/browser/localBrowserBridge.d.ts +0 -20
  169. package/dist/browser/localBrowserBridge.js +0 -82
  170. package/dist/browser/poolServerAllow.d.ts +0 -21
  171. package/dist/browser/poolServerAllow.js +0 -151
  172. package/dist/browser/webTransportPositionsV4.d.ts +0 -16
  173. package/dist/browser/webTransportPositionsV4.js +0 -75
  174. package/dist/browser/webTransportStreamV4.d.ts +0 -36
  175. package/dist/browser/webTransportStreamV4.js +0 -370
  176. package/dist/browser/webTransportV4.d.ts +0 -126
  177. package/dist/browser/webTransportV4.js +0 -627
  178. package/dist/browser/wssV4.d.ts +0 -69
  179. package/dist/browser/wssV4.js +0 -339
  180. package/dist/generated/brotliWorker.d.ts +0 -1
  181. package/dist/generated/brotliWorker.js +0 -3
  182. package/dist/generated/idna151.d.ts +0 -2
  183. package/dist/generated/idna151.js +0 -38
  184. package/dist/generated/normalization151.d.ts +0 -5
  185. package/dist/generated/normalization151.js +0 -878
  186. package/dist/generated/sqliteWorkers.d.ts +0 -2
  187. package/dist/generated/sqliteWorkers.js +0 -3
  188. package/dist/generated/transportV4APIResults.d.ts +0 -145
  189. package/dist/generated/transportV4APIResults.js +0 -52
  190. package/dist/generated/transportV4Registry.d.ts +0 -3758
  191. package/dist/generated/transportV4Registry.js +0 -29
  192. package/dist/interop/browserRunner.d.ts +0 -72
  193. package/dist/interop/browserRunner.js +0 -354
  194. package/dist/interop/currentClock.d.ts +0 -3
  195. package/dist/interop/currentClock.js +0 -39
  196. package/dist/interop/currentContracts.d.ts +0 -6
  197. package/dist/interop/currentContracts.js +0 -14
  198. package/dist/interop/currentNativeTunnel.d.ts +0 -31
  199. package/dist/interop/currentNativeTunnel.js +0 -185
  200. package/dist/interop/currentParity.d.ts +0 -68
  201. package/dist/interop/currentParity.js +0 -392
  202. package/dist/interop/currentPeer.d.ts +0 -252
  203. package/dist/interop/currentPeer.js +0 -677
  204. package/dist/interop/currentRegisteredTunnelPeer.d.ts +0 -37
  205. package/dist/interop/currentRegisteredTunnelPeer.js +0 -93
  206. package/dist/interop/currentRelayPeer.d.ts +0 -131
  207. package/dist/interop/currentRelayPeer.js +0 -263
  208. package/dist/interop/currentServer.d.ts +0 -44
  209. package/dist/interop/currentServer.js +0 -299
  210. package/dist/interop/currentTLSPin.d.ts +0 -9
  211. package/dist/interop/currentTLSPin.js +0 -44
  212. package/dist/interop/currentTunnelMaterial.d.ts +0 -34
  213. package/dist/interop/currentTunnelMaterial.js +0 -100
  214. package/dist/interop/httpApplicationPeer.d.ts +0 -15
  215. package/dist/interop/httpApplicationPeer.js +0 -167
  216. package/dist/interop/invalidProofPeer.d.ts +0 -8
  217. package/dist/interop/invalidProofPeer.js +0 -106
  218. package/dist/interop/proxyServerPeer.js +0 -49
  219. package/dist/interop/serverParityPeer.d.ts +0 -101
  220. package/dist/interop/serverParityPeer.js +0 -609
  221. package/dist/node/acceptorCurrent.d.ts +0 -55
  222. package/dist/node/acceptorCurrent.js +0 -286
  223. package/dist/node/admissionRecord.d.ts +0 -23
  224. package/dist/node/admissionRecord.js +0 -178
  225. package/dist/node/clientV4.d.ts +0 -59
  226. package/dist/node/clientV4.js +0 -197
  227. package/dist/node/endpointDialer.d.ts +0 -70
  228. package/dist/node/endpointDialer.js +0 -231
  229. package/dist/node/endpointListener.d.ts +0 -48
  230. package/dist/node/endpointListener.js +0 -403
  231. package/dist/node/endpointTransport.d.ts +0 -7
  232. package/dist/node/endpointTransport.js +0 -18
  233. package/dist/node/grantIssuerCurrent.d.ts +0 -64
  234. package/dist/node/grantIssuerCurrent.js +0 -355
  235. package/dist/node/liveHTTPSV4.d.ts +0 -28
  236. package/dist/node/liveHTTPSV4.js +0 -298
  237. package/dist/node/liveTunnelAuthorityCurrent.d.ts +0 -153
  238. package/dist/node/liveTunnelAuthorityCurrent.js +0 -590
  239. package/dist/node/nativeDuplexBridgeV4.d.ts +0 -41
  240. package/dist/node/nativeDuplexBridgeV4.js +0 -494
  241. package/dist/node/nativeTransportCurrent.d.ts +0 -196
  242. package/dist/node/nativeTransportCurrent.js +0 -37
  243. package/dist/node/poolServerAllow.d.ts +0 -33
  244. package/dist/node/poolServerAllow.js +0 -277
  245. package/dist/node/proxyCredentials.d.ts +0 -67
  246. package/dist/node/proxyCredentials.js +0 -364
  247. package/dist/node/proxyNetwork.d.ts +0 -18
  248. package/dist/node/proxyNetwork.js +0 -213
  249. package/dist/node/rawQUICCurrent.d.ts +0 -139
  250. package/dist/node/rawQUICCurrent.js +0 -1177
  251. package/dist/node/registeredLiveTunnelControl.d.ts +0 -74
  252. package/dist/node/registeredLiveTunnelControl.js +0 -865
  253. package/dist/node/registeredPoolTunnelAuthority.d.ts +0 -50
  254. package/dist/node/registeredPoolTunnelAuthority.js +0 -305
  255. package/dist/node/registeredTunnelControl.d.ts +0 -189
  256. package/dist/node/registeredTunnelControl.js +0 -1007
  257. package/dist/node/registeredWinnerContinuation.d.ts +0 -26
  258. package/dist/node/registeredWinnerContinuation.js +0 -83
  259. package/dist/node/relayNativePair.d.ts +0 -62
  260. package/dist/node/relayNativePair.js +0 -737
  261. package/dist/node/relayRecord.d.ts +0 -57
  262. package/dist/node/relayRecord.js +0 -275
  263. package/dist/node/serveRawQUIC.d.ts +0 -58
  264. package/dist/node/serveRawQUIC.js +0 -331
  265. package/dist/node/serveWSS.d.ts +0 -58
  266. package/dist/node/serveWSS.js +0 -309
  267. package/dist/node/sqliteAdmission.d.ts +0 -100
  268. package/dist/node/sqliteAdmission.js +0 -1185
  269. package/dist/node/sqliteExecutionContentV4.d.ts +0 -63
  270. package/dist/node/sqliteExecutionContentV4.js +0 -251
  271. package/dist/node/sqliteExecutionV4.d.ts +0 -114
  272. package/dist/node/sqliteExecutionV4.js +0 -1052
  273. package/dist/node/sqliteFormat.d.ts +0 -20
  274. package/dist/node/sqliteFormat.js +0 -72
  275. package/dist/node/sqliteInspectionV4.d.ts +0 -7
  276. package/dist/node/sqliteInspectionV4.js +0 -47
  277. package/dist/node/sqliteNativeV4.d.ts +0 -3
  278. package/dist/node/sqliteNativeV4.js +0 -16
  279. package/dist/node/sqlitePoolV4.d.ts +0 -41
  280. package/dist/node/sqlitePoolV4.js +0 -282
  281. package/dist/node/sqlitePoolWorkerProgramV4.js +0 -411
  282. package/dist/node/sqlitePoolWorkerV4.d.ts +0 -67
  283. package/dist/node/sqlitePoolWorkerV4.js +0 -206
  284. package/dist/node/sqliteV4.d.ts +0 -82
  285. package/dist/node/sqliteV4.js +0 -166
  286. package/dist/node/sqliteWorkerProgramV4.js +0 -175
  287. package/dist/node/sqliteWorkerV4.d.ts +0 -47
  288. package/dist/node/sqliteWorkerV4.js +0 -142
  289. package/dist/node/streamDuplexV4.d.ts +0 -33
  290. package/dist/node/streamDuplexV4.js +0 -359
  291. package/dist/node/tunnelListenerPreparation.d.ts +0 -37
  292. package/dist/node/tunnelListenerPreparation.js +0 -162
  293. package/dist/node/tunnelRuntime.d.ts +0 -124
  294. package/dist/node/tunnelRuntime.js +0 -1205
  295. package/dist/node/webTransportCurrent.d.ts +0 -24
  296. package/dist/node/webTransportCurrent.js +0 -12
  297. package/dist/node/wssV4.d.ts +0 -99
  298. package/dist/node/wssV4.js +0 -846
  299. package/dist/proxy/admission.d.ts +0 -21
  300. package/dist/proxy/admission.js +0 -126
  301. package/dist/proxy/brotliBody.d.ts +0 -10
  302. package/dist/proxy/brotliBody.js +0 -85
  303. package/dist/proxy/credentialControl.d.ts +0 -30
  304. package/dist/proxy/credentialControl.js +0 -86
  305. package/dist/proxy/currentStream.d.ts +0 -24
  306. package/dist/proxy/currentStream.js +0 -158
  307. package/dist/proxy/headers.d.ts +0 -8
  308. package/dist/proxy/headers.js +0 -63
  309. package/dist/proxy/publicationOwner.d.ts +0 -10
  310. package/dist/proxy/publicationOwner.js +0 -130
  311. package/dist/proxy/requestAssociation.d.ts +0 -11
  312. package/dist/proxy/requestAssociation.js +0 -8
  313. package/dist/proxy/surface.d.ts +0 -45
  314. package/dist/proxy/surface.js +0 -384
  315. package/dist/proxy/wire.d.ts +0 -11
  316. package/dist/proxy/wire.js +0 -214
  317. package/dist/public/streamKind.d.ts +0 -3
  318. package/dist/public/streamKind.js +0 -19
  319. package/dist/testSupport/tlsFixture.d.ts +0 -2
  320. package/dist/testSupport/tlsFixture.js +0 -8
  321. package/dist/v4/admissionOffer.d.ts +0 -8
  322. package/dist/v4/admissionOffer.js +0 -1
  323. package/dist/v4/checkpoint.d.ts +0 -23
  324. package/dist/v4/checkpoint.js +0 -16
  325. package/dist/v4/clientServices.d.ts +0 -35
  326. package/dist/v4/clientServices.js +0 -11
  327. package/dist/v4/connectionDiagnostic.d.ts +0 -42
  328. package/dist/v4/connectionDiagnostic.js +0 -45
  329. package/dist/v4/connectionRequirements.d.ts +0 -5
  330. package/dist/v4/connectionRequirements.js +0 -34
  331. package/dist/v4/controller.d.ts +0 -122
  332. package/dist/v4/controller.js +0 -1161
  333. package/dist/v4/controllerNotifications.d.ts +0 -81
  334. package/dist/v4/controllerNotifications.js +0 -610
  335. package/dist/v4/diagnostics.d.ts +0 -44
  336. package/dist/v4/diagnostics.js +0 -9
  337. package/dist/v4/drain.d.ts +0 -39
  338. package/dist/v4/drain.js +0 -80
  339. package/dist/v4/duplexBridge.d.ts +0 -53
  340. package/dist/v4/duplexBridge.js +0 -446
  341. package/dist/v4/entrypoints.d.ts +0 -20
  342. package/dist/v4/entrypoints.js +0 -50
  343. package/dist/v4/eventSource.d.ts +0 -34
  344. package/dist/v4/eventSource.js +0 -28
  345. package/dist/v4/handlerPlan.d.ts +0 -53
  346. package/dist/v4/handlerPlan.js +0 -129
  347. package/dist/v4/liveness.d.ts +0 -20
  348. package/dist/v4/liveness.js +0 -10
  349. package/dist/v4/localReport.d.ts +0 -17
  350. package/dist/v4/localReport.js +0 -10
  351. package/dist/v4/messageDefinition.d.ts +0 -66
  352. package/dist/v4/messageDefinition.js +0 -109
  353. package/dist/v4/messageStream.d.ts +0 -89
  354. package/dist/v4/messageStream.js +0 -1375
  355. package/dist/v4/notificationOperation.d.ts +0 -30
  356. package/dist/v4/notificationOperation.js +0 -31
  357. package/dist/v4/notificationSubscription.d.ts +0 -47
  358. package/dist/v4/notificationSubscription.js +0 -24
  359. package/dist/v4/operationReference.d.ts +0 -28
  360. package/dist/v4/operationReference.js +0 -61
  361. package/dist/v4/operationReferenceCodec.d.ts +0 -20
  362. package/dist/v4/operationReferenceCodec.js +0 -129
  363. package/dist/v4/operationReferenceStore.d.ts +0 -90
  364. package/dist/v4/operationReferenceStore.js +0 -272
  365. package/dist/v4/operationResultRead.d.ts +0 -26
  366. package/dist/v4/operationResultRead.js +0 -24
  367. package/dist/v4/poolControl.d.ts +0 -11
  368. package/dist/v4/poolControl.js +0 -50
  369. package/dist/v4/poolSource.d.ts +0 -93
  370. package/dist/v4/poolSource.js +0 -900
  371. package/dist/v4/profileDHReference.d.ts +0 -2
  372. package/dist/v4/profileDHReference.js +0 -42
  373. package/dist/v4/public.d.ts +0 -232
  374. package/dist/v4/public.js +0 -632
  375. package/dist/v4/responsePublication.d.ts +0 -48
  376. package/dist/v4/responsePublication.js +0 -227
  377. package/dist/v4/resume.d.ts +0 -17
  378. package/dist/v4/resume.js +0 -15
  379. package/dist/v4/runtime/applicationExecutor.d.ts +0 -190
  380. package/dist/v4/runtime/applicationExecutor.js +0 -759
  381. package/dist/v4/runtime/applicationHeader.d.ts +0 -61
  382. package/dist/v4/runtime/applicationHeader.js +0 -222
  383. package/dist/v4/runtime/canonicalText.d.ts +0 -8
  384. package/dist/v4/runtime/canonicalText.js +0 -142
  385. package/dist/v4/runtime/cbor.d.ts +0 -92
  386. package/dist/v4/runtime/cbor.js +0 -728
  387. package/dist/v4/runtime/cborWriter.d.ts +0 -18
  388. package/dist/v4/runtime/cborWriter.js +0 -59
  389. package/dist/v4/runtime/checkpointToken.d.ts +0 -41
  390. package/dist/v4/runtime/checkpointToken.js +0 -61
  391. package/dist/v4/runtime/clientAdmission.d.ts +0 -40
  392. package/dist/v4/runtime/clientAdmission.js +0 -378
  393. package/dist/v4/runtime/clientSessionSpec.d.ts +0 -45
  394. package/dist/v4/runtime/clientSessionSpec.js +0 -91
  395. package/dist/v4/runtime/clock.d.ts +0 -80
  396. package/dist/v4/runtime/clock.js +0 -284
  397. package/dist/v4/runtime/connectionFacts.d.ts +0 -23
  398. package/dist/v4/runtime/connectionFacts.js +0 -106
  399. package/dist/v4/runtime/contractAcceptance.d.ts +0 -20
  400. package/dist/v4/runtime/contractAcceptance.js +0 -91
  401. package/dist/v4/runtime/contractQuery.d.ts +0 -57
  402. package/dist/v4/runtime/contractQuery.js +0 -265
  403. package/dist/v4/runtime/contractQueryAccess.d.ts +0 -25
  404. package/dist/v4/runtime/contractQueryAccess.js +0 -117
  405. package/dist/v4/runtime/contractQueryAcquisition.d.ts +0 -83
  406. package/dist/v4/runtime/contractQueryAcquisition.js +0 -572
  407. package/dist/v4/runtime/contractQueryClient.d.ts +0 -70
  408. package/dist/v4/runtime/contractQueryClient.js +0 -411
  409. package/dist/v4/runtime/contractQueryCodecs.d.ts +0 -20
  410. package/dist/v4/runtime/contractQueryCodecs.js +0 -71
  411. package/dist/v4/runtime/contractQueryExchange.d.ts +0 -36
  412. package/dist/v4/runtime/contractQueryExchange.js +0 -160
  413. package/dist/v4/runtime/contractQueryService.d.ts +0 -42
  414. package/dist/v4/runtime/contractQueryService.js +0 -572
  415. package/dist/v4/runtime/contractQuerySession.d.ts +0 -38
  416. package/dist/v4/runtime/contractQuerySession.js +0 -158
  417. package/dist/v4/runtime/contractRoutes.d.ts +0 -87
  418. package/dist/v4/runtime/contractRoutes.js +0 -396
  419. package/dist/v4/runtime/contractSnapshotReader.d.ts +0 -59
  420. package/dist/v4/runtime/contractSnapshotReader.js +0 -418
  421. package/dist/v4/runtime/contractSnapshotWriter.d.ts +0 -32
  422. package/dist/v4/runtime/contractSnapshotWriter.js +0 -208
  423. package/dist/v4/runtime/controllerServiceSource.d.ts +0 -23
  424. package/dist/v4/runtime/controllerServiceSource.js +0 -109
  425. package/dist/v4/runtime/controllerUnaryRoute.d.ts +0 -28
  426. package/dist/v4/runtime/controllerUnaryRoute.js +0 -1
  427. package/dist/v4/runtime/credentialNamespace.d.ts +0 -143
  428. package/dist/v4/runtime/credentialNamespace.js +0 -1286
  429. package/dist/v4/runtime/credentialSupport.d.ts +0 -60
  430. package/dist/v4/runtime/credentialSupport.js +0 -294
  431. package/dist/v4/runtime/credentialVerifier.d.ts +0 -404
  432. package/dist/v4/runtime/credentialVerifier.js +0 -1443
  433. package/dist/v4/runtime/cryptoUsage.d.ts +0 -135
  434. package/dist/v4/runtime/cryptoUsage.js +0 -552
  435. package/dist/v4/runtime/deadline.d.ts +0 -31
  436. package/dist/v4/runtime/deadline.js +0 -188
  437. package/dist/v4/runtime/diagnosticCounters.d.ts +0 -15
  438. package/dist/v4/runtime/diagnosticCounters.js +0 -78
  439. package/dist/v4/runtime/diagnosticObservation.d.ts +0 -25
  440. package/dist/v4/runtime/diagnosticObservation.js +0 -67
  441. package/dist/v4/runtime/diagnosticSink.d.ts +0 -16
  442. package/dist/v4/runtime/diagnosticSink.js +0 -320
  443. package/dist/v4/runtime/ed25519.d.ts +0 -1
  444. package/dist/v4/runtime/ed25519.js +0 -34
  445. package/dist/v4/runtime/endpointHop.d.ts +0 -12
  446. package/dist/v4/runtime/endpointHop.js +0 -26
  447. package/dist/v4/runtime/envelope.d.ts +0 -66
  448. package/dist/v4/runtime/envelope.js +0 -275
  449. package/dist/v4/runtime/environment.d.ts +0 -277
  450. package/dist/v4/runtime/environment.js +0 -1913
  451. package/dist/v4/runtime/executionManagementChannel.d.ts +0 -27
  452. package/dist/v4/runtime/executionManagementChannel.js +0 -733
  453. package/dist/v4/runtime/executionManagementCodec.d.ts +0 -84
  454. package/dist/v4/runtime/executionManagementCodec.js +0 -127
  455. package/dist/v4/runtime/executionStorage.d.ts +0 -71
  456. package/dist/v4/runtime/executionStorage.js +0 -10
  457. package/dist/v4/runtime/fixedDiagnosticExecutor.d.ts +0 -34
  458. package/dist/v4/runtime/fixedDiagnosticExecutor.js +0 -149
  459. package/dist/v4/runtime/fixedManagementExecutor.d.ts +0 -21
  460. package/dist/v4/runtime/fixedManagementExecutor.js +0 -153
  461. package/dist/v4/runtime/fixedQueryExecutor.d.ts +0 -46
  462. package/dist/v4/runtime/fixedQueryExecutor.js +0 -311
  463. package/dist/v4/runtime/grantDigest.d.ts +0 -9
  464. package/dist/v4/runtime/grantDigest.js +0 -31
  465. package/dist/v4/runtime/hopAuthentication.d.ts +0 -51
  466. package/dist/v4/runtime/hopAuthentication.js +0 -392
  467. package/dist/v4/runtime/host.d.ts +0 -15
  468. package/dist/v4/runtime/host.js +0 -332
  469. package/dist/v4/runtime/initializerWorkload.d.ts +0 -38
  470. package/dist/v4/runtime/initializerWorkload.js +0 -164
  471. package/dist/v4/runtime/lifecycle.d.ts +0 -5
  472. package/dist/v4/runtime/lifecycle.js +0 -17
  473. package/dist/v4/runtime/liveAuthorization.d.ts +0 -42
  474. package/dist/v4/runtime/liveAuthorization.js +0 -133
  475. package/dist/v4/runtime/liveAuthorizationWire.d.ts +0 -8
  476. package/dist/v4/runtime/liveAuthorizationWire.js +0 -31
  477. package/dist/v4/runtime/liveCarrierPreparation.d.ts +0 -9
  478. package/dist/v4/runtime/liveCarrierPreparation.js +0 -27
  479. package/dist/v4/runtime/liveness.d.ts +0 -37
  480. package/dist/v4/runtime/liveness.js +0 -319
  481. package/dist/v4/runtime/maintenancePositions.d.ts +0 -29
  482. package/dist/v4/runtime/maintenancePositions.js +0 -152
  483. package/dist/v4/runtime/messageCodec.d.ts +0 -20
  484. package/dist/v4/runtime/messageCodec.js +0 -192
  485. package/dist/v4/runtime/namespaceContinuity.d.ts +0 -20
  486. package/dist/v4/runtime/namespaceContinuity.js +0 -176
  487. package/dist/v4/runtime/nativeCandidates.d.ts +0 -18
  488. package/dist/v4/runtime/nativeCandidates.js +0 -109
  489. package/dist/v4/runtime/nativeFailure.d.ts +0 -10
  490. package/dist/v4/runtime/nativeFailure.js +0 -32
  491. package/dist/v4/runtime/nativeFrame.d.ts +0 -47
  492. package/dist/v4/runtime/nativeFrame.js +0 -318
  493. package/dist/v4/runtime/nativeIngress.d.ts +0 -30
  494. package/dist/v4/runtime/nativeIngress.js +0 -177
  495. package/dist/v4/runtime/nativePositions.d.ts +0 -24
  496. package/dist/v4/runtime/nativePositions.js +0 -131
  497. package/dist/v4/runtime/nativeProviderPositions.d.ts +0 -16
  498. package/dist/v4/runtime/nativeProviderPositions.js +0 -75
  499. package/dist/v4/runtime/nativeSend.d.ts +0 -15
  500. package/dist/v4/runtime/nativeSend.js +0 -57
  501. package/dist/v4/runtime/noiseHandshake.d.ts +0 -70
  502. package/dist/v4/runtime/noiseHandshake.js +0 -373
  503. package/dist/v4/runtime/noiseWasmBinary.d.ts +0 -2
  504. package/dist/v4/runtime/noiseWasmBinary.js +0 -3
  505. package/dist/v4/runtime/notifyChannel.d.ts +0 -37
  506. package/dist/v4/runtime/notifyChannel.js +0 -277
  507. package/dist/v4/runtime/notifyDispatch.d.ts +0 -108
  508. package/dist/v4/runtime/notifyDispatch.js +0 -717
  509. package/dist/v4/runtime/notifyExecution.d.ts +0 -18
  510. package/dist/v4/runtime/notifyExecution.js +0 -59
  511. package/dist/v4/runtime/notifyPreparation.d.ts +0 -70
  512. package/dist/v4/runtime/notifyPreparation.js +0 -465
  513. package/dist/v4/runtime/openAdmission.d.ts +0 -125
  514. package/dist/v4/runtime/openAdmission.js +0 -810
  515. package/dist/v4/runtime/peerOpenPreparation.d.ts +0 -18
  516. package/dist/v4/runtime/peerOpenPreparation.js +0 -61
  517. package/dist/v4/runtime/poolJournal.d.ts +0 -18
  518. package/dist/v4/runtime/poolJournal.js +0 -14
  519. package/dist/v4/runtime/poolJournalStorage.d.ts +0 -4
  520. package/dist/v4/runtime/poolJournalStorage.js +0 -172
  521. package/dist/v4/runtime/poolRecord.d.ts +0 -9
  522. package/dist/v4/runtime/poolRecord.js +0 -23
  523. package/dist/v4/runtime/poolRecordStorage.d.ts +0 -10
  524. package/dist/v4/runtime/poolRecordStorage.js +0 -216
  525. package/dist/v4/runtime/poolServerAllow.d.ts +0 -49
  526. package/dist/v4/runtime/poolServerAllow.js +0 -38
  527. package/dist/v4/runtime/poolSpend.d.ts +0 -20
  528. package/dist/v4/runtime/poolSpend.js +0 -4
  529. package/dist/v4/runtime/queryRenewalPosition.d.ts +0 -59
  530. package/dist/v4/runtime/queryRenewalPosition.js +0 -220
  531. package/dist/v4/runtime/random.d.ts +0 -15
  532. package/dist/v4/runtime/random.js +0 -71
  533. package/dist/v4/runtime/rawStreamPreparation.d.ts +0 -40
  534. package/dist/v4/runtime/rawStreamPreparation.js +0 -125
  535. package/dist/v4/runtime/receiveDirection.d.ts +0 -135
  536. package/dist/v4/runtime/receiveDirection.js +0 -957
  537. package/dist/v4/runtime/receiveWorkspace.d.ts +0 -19
  538. package/dist/v4/runtime/receiveWorkspace.js +0 -82
  539. package/dist/v4/runtime/record.d.ts +0 -7
  540. package/dist/v4/runtime/record.js +0 -173
  541. package/dist/v4/runtime/recordCrypto.d.ts +0 -121
  542. package/dist/v4/runtime/recordCrypto.js +0 -633
  543. package/dist/v4/runtime/recordWorkspace.d.ts +0 -17
  544. package/dist/v4/runtime/recordWorkspace.js +0 -69
  545. package/dist/v4/runtime/registeredCarrierPreparation.d.ts +0 -17
  546. package/dist/v4/runtime/registeredCarrierPreparation.js +0 -191
  547. package/dist/v4/runtime/rekey.d.ts +0 -40
  548. package/dist/v4/runtime/rekey.js +0 -362
  549. package/dist/v4/runtime/relayCredentials.d.ts +0 -126
  550. package/dist/v4/runtime/relayCredentials.js +0 -349
  551. package/dist/v4/runtime/replayWindow.d.ts +0 -6
  552. package/dist/v4/runtime/replayWindow.js +0 -59
  553. package/dist/v4/runtime/resources.d.ts +0 -200
  554. package/dist/v4/runtime/resources.js +0 -1236
  555. package/dist/v4/runtime/resumeCodec.d.ts +0 -44
  556. package/dist/v4/runtime/resumeCodec.js +0 -192
  557. package/dist/v4/runtime/resumeStream.d.ts +0 -23
  558. package/dist/v4/runtime/resumeStream.js +0 -23
  559. package/dist/v4/runtime/rpcApplication.d.ts +0 -234
  560. package/dist/v4/runtime/rpcApplication.js +0 -2170
  561. package/dist/v4/runtime/rpcApplicationServices.d.ts +0 -18
  562. package/dist/v4/runtime/rpcApplicationServices.js +0 -62
  563. package/dist/v4/runtime/rpcCallCapacity.d.ts +0 -62
  564. package/dist/v4/runtime/rpcCallCapacity.js +0 -289
  565. package/dist/v4/runtime/rpcChannel.d.ts +0 -58
  566. package/dist/v4/runtime/rpcChannel.js +0 -334
  567. package/dist/v4/runtime/rpcCompletion.d.ts +0 -42
  568. package/dist/v4/runtime/rpcCompletion.js +0 -152
  569. package/dist/v4/runtime/rpcEventSource.d.ts +0 -27
  570. package/dist/v4/runtime/rpcEventSource.js +0 -201
  571. package/dist/v4/runtime/rpcFragment.d.ts +0 -42
  572. package/dist/v4/runtime/rpcFragment.js +0 -227
  573. package/dist/v4/runtime/rpcInput.d.ts +0 -41
  574. package/dist/v4/runtime/rpcInput.js +0 -137
  575. package/dist/v4/runtime/rpcNetwork.d.ts +0 -143
  576. package/dist/v4/runtime/rpcNetwork.js +0 -652
  577. package/dist/v4/runtime/rpcOutputInterest.d.ts +0 -20
  578. package/dist/v4/runtime/rpcOutputInterest.js +0 -106
  579. package/dist/v4/runtime/rpcPayload.d.ts +0 -24
  580. package/dist/v4/runtime/rpcPayload.js +0 -82
  581. package/dist/v4/runtime/rpcPreacceptedStreams.d.ts +0 -46
  582. package/dist/v4/runtime/rpcPreacceptedStreams.js +0 -406
  583. package/dist/v4/runtime/rpcPublisher.d.ts +0 -49
  584. package/dist/v4/runtime/rpcPublisher.js +0 -406
  585. package/dist/v4/runtime/rpcReceiver.d.ts +0 -40
  586. package/dist/v4/runtime/rpcReceiver.js +0 -255
  587. package/dist/v4/runtime/rpcResumeDispatch.d.ts +0 -46
  588. package/dist/v4/runtime/rpcResumeDispatch.js +0 -266
  589. package/dist/v4/runtime/rpcStream.d.ts +0 -14
  590. package/dist/v4/runtime/rpcStream.js +0 -12
  591. package/dist/v4/runtime/rpcStreamMessages.d.ts +0 -53
  592. package/dist/v4/runtime/rpcStreamMessages.js +0 -428
  593. package/dist/v4/runtime/rpcStreamPreparation.d.ts +0 -21
  594. package/dist/v4/runtime/rpcStreamPreparation.js +0 -110
  595. package/dist/v4/runtime/rpcStreamingDispatch.d.ts +0 -26
  596. package/dist/v4/runtime/rpcStreamingDispatch.js +0 -607
  597. package/dist/v4/runtime/rpcStreamingExchange.d.ts +0 -91
  598. package/dist/v4/runtime/rpcStreamingExchange.js +0 -812
  599. package/dist/v4/runtime/rpcUnaryCall.d.ts +0 -16
  600. package/dist/v4/runtime/rpcUnaryCall.js +0 -152
  601. package/dist/v4/runtime/rpcUnaryDispatch.d.ts +0 -34
  602. package/dist/v4/runtime/rpcUnaryDispatch.js +0 -569
  603. package/dist/v4/runtime/rpcUnaryExchange.d.ts +0 -127
  604. package/dist/v4/runtime/rpcUnaryExchange.js +0 -1042
  605. package/dist/v4/runtime/rpcUnaryPreparation.d.ts +0 -102
  606. package/dist/v4/runtime/rpcUnaryPreparation.js +0 -736
  607. package/dist/v4/runtime/rpcUnaryRegistration.d.ts +0 -33
  608. package/dist/v4/runtime/rpcUnaryRegistration.js +0 -113
  609. package/dist/v4/runtime/rpcUnaryResultRecipient.d.ts +0 -21
  610. package/dist/v4/runtime/rpcUnaryResultRecipient.js +0 -57
  611. package/dist/v4/runtime/schema.d.ts +0 -26
  612. package/dist/v4/runtime/schema.js +0 -668
  613. package/dist/v4/runtime/schemaRegistry.d.ts +0 -128
  614. package/dist/v4/runtime/schemaRegistry.js +0 -74
  615. package/dist/v4/runtime/sendBudget.d.ts +0 -10
  616. package/dist/v4/runtime/sendBudget.js +0 -46
  617. package/dist/v4/runtime/serveGroup.d.ts +0 -73
  618. package/dist/v4/runtime/serveGroup.js +0 -589
  619. package/dist/v4/runtime/serverAdmission.d.ts +0 -33
  620. package/dist/v4/runtime/serverAdmission.js +0 -342
  621. package/dist/v4/runtime/serverAdmissionAuthority.d.ts +0 -23
  622. package/dist/v4/runtime/serverAdmissionAuthority.js +0 -5
  623. package/dist/v4/runtime/serverSessionSpec.d.ts +0 -9
  624. package/dist/v4/runtime/serverSessionSpec.js +0 -12
  625. package/dist/v4/runtime/serviceBinding.d.ts +0 -128
  626. package/dist/v4/runtime/serviceBinding.js +0 -1435
  627. package/dist/v4/runtime/serviceBindingConfig.d.ts +0 -72
  628. package/dist/v4/runtime/serviceBindingConfig.js +0 -85
  629. package/dist/v4/runtime/serviceBindingPool.d.ts +0 -58
  630. package/dist/v4/runtime/serviceBindingPool.js +0 -327
  631. package/dist/v4/runtime/serviceContract.d.ts +0 -111
  632. package/dist/v4/runtime/serviceContract.js +0 -588
  633. package/dist/v4/runtime/serviceInputs.d.ts +0 -30
  634. package/dist/v4/runtime/serviceInputs.js +0 -201
  635. package/dist/v4/runtime/serviceOfferPlan.d.ts +0 -81
  636. package/dist/v4/runtime/serviceOfferPlan.js +0 -335
  637. package/dist/v4/runtime/serviceOfferScheduler.d.ts +0 -12
  638. package/dist/v4/runtime/serviceOfferScheduler.js +0 -201
  639. package/dist/v4/runtime/serviceOfferWork.d.ts +0 -25
  640. package/dist/v4/runtime/serviceOfferWork.js +0 -1
  641. package/dist/v4/runtime/session.d.ts +0 -411
  642. package/dist/v4/runtime/session.js +0 -6369
  643. package/dist/v4/runtime/sessionActivity.d.ts +0 -19
  644. package/dist/v4/runtime/sessionActivity.js +0 -97
  645. package/dist/v4/runtime/sessionAdmission.d.ts +0 -93
  646. package/dist/v4/runtime/sessionAdmission.js +0 -498
  647. package/dist/v4/runtime/sessionCleanup.d.ts +0 -47
  648. package/dist/v4/runtime/sessionCleanup.js +0 -268
  649. package/dist/v4/runtime/sessionKeyPreparation.d.ts +0 -19
  650. package/dist/v4/runtime/sessionKeyPreparation.js +0 -50
  651. package/dist/v4/runtime/signedMap.d.ts +0 -68
  652. package/dist/v4/runtime/signedMap.js +0 -425
  653. package/dist/v4/runtime/streamAdapter.d.ts +0 -113
  654. package/dist/v4/runtime/streamAdapter.js +0 -62
  655. package/dist/v4/runtime/streamData.d.ts +0 -11
  656. package/dist/v4/runtime/streamData.js +0 -50
  657. package/dist/v4/runtime/streamOpenPreparation.d.ts +0 -23
  658. package/dist/v4/runtime/streamOpenPreparation.js +0 -77
  659. package/dist/v4/runtime/streamRegistration.d.ts +0 -87
  660. package/dist/v4/runtime/streamRegistration.js +0 -296
  661. package/dist/v4/runtime/taskObservation.d.ts +0 -1
  662. package/dist/v4/runtime/taskObservation.js +0 -48
  663. package/dist/v4/runtime/timeArithmetic.d.ts +0 -29
  664. package/dist/v4/runtime/timeArithmetic.js +0 -107
  665. package/dist/v4/runtime/unreliable.d.ts +0 -76
  666. package/dist/v4/runtime/unreliable.js +0 -473
  667. package/dist/v4/runtime/volatileExecutions.d.ts +0 -128
  668. package/dist/v4/runtime/volatileExecutions.js +0 -792
  669. package/dist/v4/runtime/wireRegistry.d.ts +0 -52
  670. package/dist/v4/runtime/wireRegistry.js +0 -29
  671. package/dist/v4/runtime/writeRequest.d.ts +0 -42
  672. package/dist/v4/runtime/writeRequest.js +0 -237
  673. package/dist/v4/serve.d.ts +0 -107
  674. package/dist/v4/serve.js +0 -80
  675. package/dist/v4/serviceClient.d.ts +0 -92
  676. package/dist/v4/serviceClient.js +0 -323
  677. package/dist/v4/serviceDefinition.d.ts +0 -138
  678. package/dist/v4/serviceDefinition.js +0 -150
  679. package/dist/v4/serviceDependencies.d.ts +0 -66
  680. package/dist/v4/serviceDependencies.js +0 -250
  681. package/dist/v4/serviceFactory.d.ts +0 -31
  682. package/dist/v4/serviceFactory.js +0 -157
  683. package/dist/v4/serviceHandlers.d.ts +0 -55
  684. package/dist/v4/serviceHandlers.js +0 -15
  685. package/dist/v4/serviceMembers.d.ts +0 -4
  686. package/dist/v4/serviceMembers.js +0 -12
  687. package/dist/v4/staticServiceContracts.d.ts +0 -43
  688. package/dist/v4/staticServiceContracts.js +0 -161
  689. package/dist/v4/storageFormat.d.ts +0 -16
  690. package/dist/v4/storageFormat.js +0 -5
  691. package/dist/v4/streamContent.d.ts +0 -30
  692. package/dist/v4/streamContent.js +0 -29
  693. package/dist/v4/streamHandlers.d.ts +0 -61
  694. package/dist/v4/streamHandlers.js +0 -16
  695. package/dist/v4/streamingOperation.d.ts +0 -64
  696. package/dist/v4/streamingOperation.js +0 -141
  697. package/dist/v4/strictEd25519Reference.d.ts +0 -2
  698. package/dist/v4/strictEd25519Reference.js +0 -37
  699. package/dist/v4/testSupport/cbor.d.ts +0 -124
  700. package/dist/v4/testSupport/cbor.js +0 -230
  701. package/dist/v4/testSupport/credentials.d.ts +0 -55
  702. package/dist/v4/testSupport/credentials.js +0 -111
  703. package/dist/v4/testSupport/unicode.d.ts +0 -19
  704. package/dist/v4/testSupport/unicode.js +0 -112
  705. package/dist/v4/unaryOperation.d.ts +0 -59
  706. package/dist/v4/unaryOperation.js +0 -80
  707. package/dist/v4/unreliable.d.ts +0 -26
  708. package/dist/v4/unreliable.js +0 -10
  709. package/dist/v4/webStreams.d.ts +0 -30
  710. package/dist/v4/webStreams.js +0 -377
  711. /package/dist/{interop/proxyServerPeer.d.ts → rpc/wire.js} +0 -0
  712. /package/dist/{node/sqlitePoolWorkerProgramV4.d.ts → v3/publicSession.d.ts} +0 -0
  713. /package/dist/{node/sqliteWorkerProgramV4.d.ts → v3/streamMetadata.d.ts} +0 -0
@@ -1,1913 +0,0 @@
1
- import { capturePoolServerAllowConfiguration, clearPoolServerAllowConfiguration, poolServerAllowConfigurationCharge } from "./poolServerAllow.js";
2
- import { observeNativeConnectionFailure, retainNativeConnectionFailure } from "./nativeFailure.js";
3
- import { ConnectionFacts, rememberConnectionFacts } from "./connectionFacts.js";
4
- import { ConnectionError, controllerFailureCode } from "../connectionDiagnostic.js";
5
- import { DiagnosticCounters, diagnosticCounterBytes } from "./diagnosticCounters.js";
6
- import { RuntimeDiagnosticSink } from "./diagnosticSink.js";
7
- import { DiagnosticActivity } from "./diagnosticObservation.js";
8
- import { prepareRegisteredCarrier } from "./registeredCarrierPreparation.js";
9
- import { applicationResumeFeature } from "./checkpointToken.js";
10
- import { UnreliablePreparation, unreliableCharges } from "./unreliable.js";
11
- import { RawStreamPreparation } from "./rawStreamPreparation.js";
12
- import { PeerOpenPreparation } from "./peerOpenPreparation.js";
13
- import { streamOpenCharges } from "./streamOpenPreparation.js";
14
- import { isServerAdmissionAuthority } from "./serverAdmissionAuthority.js";
15
- import { ClientSessionAdmission, sessionAdmissionPlan } from "./sessionAdmission.js";
16
- import { closeRPCApplicationServices } from "./rpcApplicationServices.js";
17
- import { executionStorage } from "./executionStorage.js";
18
- import { notifyChannelCharges } from "./notifyChannel.js";
19
- import { VolatileExecutions, captureVolatileExecution, executionServiceKey } from "./volatileExecutions.js";
20
- import { NativeProtocolPositions } from "./nativePositions.js";
21
- import { ContractQueryAcquisitions, contractQueryAcquisitionsCharges } from "./contractQueryAcquisition.js";
22
- import { ServiceBindingPool, serviceBindingPoolCharge, serviceBindingAccount } from "./serviceBindingPool.js";
23
- import { RPCApplicationAdmission } from "./rpcApplication.js";
24
- import { MaintenancePositions } from "./maintenancePositions.js";
25
- import { createSendAccount, createStreamSendAccounts } from "./sendBudget.js";
26
- import { captureConnectionRequirements, requireConnectionGuarantees } from "../connectionRequirements.js";
27
- import { cleanupResult, lifecycleResult } from "./lifecycle.js";
28
- import { selectedIdleDuration, captureAutomaticLiveness, qualifySessionActivity } from "./sessionActivity.js";
29
- import { V4TransportEnvironment, V4ConnectionMaterial } from "../public.js";
30
- import { TrustedClock, trustedClockCharge } from "./clock.js";
31
- import { TrustedWindow, timerChunk } from "./deadline.js";
32
- import { TrustedRandom, randomCharge, randomDH } from "./random.js";
33
- import { SessionKeyPreparation } from "./sessionKeyPreparation.js";
34
- import { ResourceVector, ResourceRoot, bindResourceDiagnostics } from "./resources.js";
35
- import { CredentialNamespace } from "./credentialNamespace.js";
36
- import { credentialWorkCharge, equalCredential, requireCredential } from "./credentialSupport.js";
37
- import { verifyDirectCredentials, TunnelCredentialPreparation, credentialVerifierCharge } from "./credentialVerifier.js";
38
- import { ClientAdmissionExchange, clientAdmissionCharge, clearClientPreparation } from "./clientAdmission.js";
39
- import { CryptoUsageLedger } from "./cryptoUsage.js";
40
- import { ReceiveDeliveryGate } from "./receiveDirection.js";
41
- import { establishV4CredentialSession } from "./session.js";
42
- import { isPoolSpendStore } from "./poolSpend.js";
43
- import { ownProfile } from "./wireRegistry.js";
44
- const token = Symbol("environment owner");
45
- const NativePromise = Promise;
46
- const complete = cleanupResult({ status: "complete", core_cleanup: "complete", pending_callbacks: 0n });
47
- /** Cleanup evidence scoped to one Connect admission. It never observes the
48
- * Environment's unrelated Sessions, shared dependencies, or sibling sources. */
49
- class ConnectionAttemptCleanup {
50
- #pending = 0;
51
- #incomplete = false;
52
- retain() { this.#pending++; }
53
- release() { if (this.#pending > 0)
54
- this.#pending--; }
55
- incomplete() { this.#incomplete = true; }
56
- status() {
57
- return cleanupResult({ status: this.#incomplete ? "cleanup_incomplete" : this.#pending === 0 ? "complete" : "pending",
58
- core_cleanup: this.#incomplete ? "pending" : this.#pending === 0 ? "complete" : "pending", pending_callbacks: BigInt(this.#pending) });
59
- }
60
- }
61
- const sizes = Object.freeze({ artifact: 65536, clientCertificate: 16384, serverCertificate: 16384, activation: 65536, tunnelGrant: 65536, relayCertificate: 16384 });
62
- const keys = Object.freeze(["artifact", "clientCertificate", "serverCertificate", "activation", "tunnelGrant", "relayCertificate"]);
63
- const max = 0xffffffffffffffffn;
64
- function fail(code) { throw new Error(code); }
65
- function bounded(value, cap = 65536) { if (!Number.isSafeInteger(value) || value < 1 || value > cap)
66
- fail("configuration_capacity"); return value; }
67
- function duration(value) { if (typeof value !== "bigint" || value <= 0n || value > max)
68
- fail("configuration_capacity"); return value; }
69
- function policyText(value) {
70
- return typeof value === "string" && /^[a-z0-9][a-z0-9._:/@-]{0,127}$/u.test(value);
71
- }
72
- function sameNamespace(a, b) {
73
- const fields = ["tenant", "authority", "maxTrustLifetimeMS", "bootstrapMS", "stateBytes", "stateNodes", "continuity", "trustConfigurations", "trustNodes", "subscriptions", "maxStateFetchMS", "maxFetchAttempts"];
74
- return fields.every(key => a[key] === b[key]) && equalCredential(a.rootKeyID, b.rootKeyID) && equalCredential(a.rootPublicKey, b.rootPublicKey);
75
- }
76
- function captureNamespace(c) {
77
- return Object.freeze({ tenant: c.tenant, authority: c.authority, rootKeyID: new Uint8Array(c.rootKeyID), rootPublicKey: new Uint8Array(c.rootPublicKey),
78
- maxTrustLifetimeMS: c.maxTrustLifetimeMS, bootstrapMS: c.bootstrapMS, stateBytes: c.stateBytes, stateNodes: c.stateNodes,
79
- continuity: c.continuity ?? "online_bootstrap", trustConfigurations: c.trustConfigurations ?? 8, trustNodes: c.trustNodes ?? 270336,
80
- subscriptions: c.subscriptions ?? 1024, maxStateFetchMS: c.maxStateFetchMS ?? 90000n, maxFetchAttempts: c.maxFetchAttempts ?? 3 });
81
- }
82
- const materials = new WeakMap();
83
- /** An original verified snapshot. Only Environment admission can claim it. */
84
- export class V4EnvironmentMaterial {
85
- constructor(capability, state) { if (capability !== token)
86
- fail("material_unavailable"); materials.set(this, state); Object.freeze(this); }
87
- closeMaterial() {
88
- const state = materials.get(this);
89
- if (!state.claimed)
90
- state.environment.releaseMaterial(token, this);
91
- return Promise.resolve();
92
- }
93
- toJSON() { return {}; }
94
- }
95
- const sources = new WeakMap();
96
- const publicSources = new WeakMap();
97
- export function wrapCredentialSource(source) {
98
- if (!sources.has(source))
99
- fail("source_unavailable");
100
- const result = Object.freeze({ acquire: async (request, options) => new V4ConnectionMaterial(await source.acquire(request, options)) });
101
- publicSources.set(result, source);
102
- return result;
103
- }
104
- /** Internal binding of the public pool owner to its original registered source. */
105
- export function bindCredentialSourceFacade(source, facade) {
106
- if (!sources.has(source) || publicSources.has(facade))
107
- fail("source_unavailable");
108
- publicSources.set(facade, source);
109
- }
110
- export class V4EnvironmentCredentialSource {
111
- constructor(capability, state) { if (capability !== token)
112
- fail("source_unavailable"); sources.set(this, state); Object.freeze(this); }
113
- acquire(request, options) { return sources.get(this).environment.acquire(this, request, options); }
114
- close() { const state = sources.get(this); state.closed = true; state.environment.releaseSource(token, this); }
115
- toJSON() { return {}; }
116
- }
117
- /** Original native/store task reference. The actual provider releases it only
118
- * after close returns; Environment cancellation does not refund native work. */
119
- export class EnvironmentDependency {
120
- reference;
121
- released;
122
- #close;
123
- #closed = false;
124
- #released = false;
125
- constructor(capability, reference, released) {
126
- this.reference = reference;
127
- this.released = released;
128
- if (capability !== token)
129
- fail("invalid_resource_owner");
130
- }
131
- check() { if (this.#closed || this.#released)
132
- fail("closed"); this.reference.check(); }
133
- onClose(close) { if (this.#close !== undefined)
134
- fail("invalid_resource_owner"); this.#close = close; if (this.#closed)
135
- close(); }
136
- close() { if (this.#closed)
137
- return; this.#closed = true; this.#close?.(); }
138
- release() { if (this.#released)
139
- return; this.#released = true; this.#close = undefined; this.reference.release(); this.released(); }
140
- }
141
- const publicEnvironments = new WeakMap();
142
- const environmentFacades = new WeakMap();
143
- export function originalEnvironment(environment) {
144
- const owner = publicEnvironments.get(environment);
145
- if (owner === undefined)
146
- fail("owner_unavailable");
147
- return owner;
148
- }
149
- /** One actual root owner for namespaces, sources, materials and Session assembly.
150
- * Connect requires an installed production once/provider adapter. */
151
- export class V4EnvironmentRuntime {
152
- diagnosticCounters;
153
- #diagnostics;
154
- clock;
155
- resources;
156
- diagnostics;
157
- #config;
158
- #random;
159
- #accounts;
160
- #environment;
161
- #namespaces = new Map();
162
- #sources = new Set();
163
- #materials = new Set();
164
- #acquisitions = new Set();
165
- #admissions = new Set();
166
- #preparations = new Set();
167
- #connectionClaims = new Set();
168
- #sessions = new Set();
169
- #results = new Set();
170
- #dependencyClaims = new Set();
171
- #dependencies = new Set();
172
- #reference;
173
- #contractQueries;
174
- #serviceBindings;
175
- #executionServices = new Map();
176
- #serviceAccount;
177
- #sequence = 0n;
178
- #working = 0;
179
- #verifying = 0;
180
- #closed = false;
181
- #closeResolve;
182
- #close = new NativePromise(resolve => { this.#closeResolve = resolve; });
183
- #closeInitializing = false;
184
- #cleaning = false;
185
- #cleaned;
186
- #cleanupWindow;
187
- #cleanupIncomplete = false;
188
- #cleanupFault = false;
189
- #resourceObserver;
190
- #cleanupObservers = new Set();
191
- #cleanupTimer;
192
- #waiters = 0;
193
- #connector;
194
- constructor(config) {
195
- if (new.target !== V4EnvironmentRuntime || Object.getPrototypeOf(config.root) !== ResourceRoot.prototype)
196
- fail("configuration_capacity");
197
- const inputDiagnostics = config.diagnostics;
198
- const diagnosticConfig = inputDiagnostics === undefined ? undefined : Object.freeze({
199
- callback: inputDiagnostics.callback, runtimeBytes: inputDiagnostics.runtimeBytes,
200
- sampleBasisPoints: inputDiagnostics.sampleBasisPoints ?? 100,
201
- operationSlots: inputDiagnostics.operationSlots ?? 64, queueEvents: inputDiagnostics.queueEvents ?? 64,
202
- });
203
- const c = this.#config = Object.freeze({ root: config.root, tenantID: config.tenantID, environmentID: config.environmentID, tenantLimit: config.tenantLimit,
204
- limit: config.limit, runtimeBytes: duration(config.runtimeBytes), namespaces: bounded(config.namespaces, 8), sources: bounded(config.sources), acquisitions: bounded(config.acquisitions),
205
- materials: bounded(config.materials), sessions: bounded(config.sessions), acquireMS: duration(config.acquireMS), cleanupMS: bounded(config.cleanupMS ?? 5000, 60000), dependencies: bounded(config.dependencies ?? 4, 64),
206
- clock: Object.freeze({ profile: config.clock.profile, tick: config.clock.tick, initial: config.clock.initial }), random: config.random });
207
- const tenant = c.root.account("tenant", c.tenantID, c.tenantLimit);
208
- this.#environment = c.root.account("environment", c.environmentID, c.limit);
209
- this.#accounts = Object.freeze([tenant, this.#environment]);
210
- const metadata = BigInt(c.namespaces + c.sources + c.acquisitions + c.materials + c.sessions + c.dependencies + 32) * c.runtimeBytes;
211
- const refs = c.root.reserveBatch([
212
- { owner: { tenant: c.tenantID, environment: c.environmentID, kind: "environment", backing: c.environmentID }, accounts: this.#accounts,
213
- charge: new ResourceVector([metadata + diagnosticCounterBytes, 0n, 0n, BigInt(c.namespaces + c.sources + c.materials + 32), 33n, 33n, 66n, 0n, 0n, 0n, 0n]) },
214
- this.#request("clock", trustedClockCharge(c.runtimeBytes)), this.#request("random", randomCharge(c.runtimeBytes)),
215
- ]);
216
- let clock, random;
217
- try {
218
- this.#reference = refs[0];
219
- this.diagnosticCounters = new DiagnosticCounters();
220
- bindResourceDiagnostics(this.#environment, this.diagnosticCounters);
221
- this.#random = random = new TrustedRandom(c.random, c.runtimeBytes, refs[2], () => { if (this.clock !== undefined)
222
- void this.close(); });
223
- this.clock = clock = new TrustedClock(c.clock.profile, c.clock.tick, c.runtimeBytes, refs[1], bytes => this.#random.fill(bytes));
224
- const mark = clock.monotonic();
225
- clock.installTrusted(mark, c.clock.initial());
226
- this.resources = Object.freeze({ root: c.root, accounts: this.#accounts, owner: this.#owner("credentials"), runtimeBytes: c.runtimeBytes });
227
- if (diagnosticConfig !== undefined)
228
- this.#diagnostics = new RuntimeDiagnosticSink(this.resources, diagnosticConfig, c.cleanupMS, this.diagnosticCounters, () => this.#cleanup());
229
- const sink = this.#diagnostics;
230
- this.diagnostics = Object.freeze({ counters: this.diagnosticCounters, begin: () => sink?.begin() });
231
- this.#resourceObserver = c.root.observeAvailability(this.#reference, () => this.#cleanup());
232
- }
233
- catch (error) {
234
- void this.#diagnostics?.close();
235
- this.#resourceObserver?.();
236
- this.#resourceObserver = undefined;
237
- clock?.close();
238
- random?.close();
239
- for (const ref of refs)
240
- ref.release();
241
- this.#environment.close();
242
- throw error;
243
- }
244
- finally {
245
- refs[1].release();
246
- refs[2].release();
247
- }
248
- Object.freeze(this);
249
- }
250
- #owner(kind) {
251
- if (this.#sequence === max)
252
- fail("configuration_capacity");
253
- return Object.freeze({ tenant: this.#config.tenantID, environment: this.#config.environmentID, kind, backing: (++this.#sequence).toString(16).padStart(32, "0") });
254
- }
255
- #request(kind, charge) { return { owner: this.#owner(kind), accounts: this.#accounts, charge }; }
256
- #reserve(kind, charge) { this.#check(); return this.#config.root.reserve(this.#request(kind, charge)); }
257
- #check() { if (this.#closed)
258
- fail("closed"); this.#reference.check(); }
259
- #resourceUnavailable() {
260
- this.diagnosticCounters.observe("resource_rejection", { code: "resource_exhausted" });
261
- fail("resource_exhausted");
262
- }
263
- diagnosticCounts(metric) { return this.diagnosticCounters.snapshot(metric); }
264
- diagnosticSink() { return this.#diagnostics; }
265
- /** One immutable ordinary/constrained query table for this Environment.
266
- * The full delivery vector is prepaid in its original tenant/root accounts;
267
- * no native dependency or general result-owner pool is used for queries. */
268
- contractQueries(limit = 4) {
269
- this.#check();
270
- if (this.#contractQueries !== undefined) {
271
- if (this.#contractQueries.limit !== limit)
272
- fail("configuration_capacity");
273
- return this.#contractQueries;
274
- }
275
- const costs = contractQueryAcquisitionsCharges(limit, this.#config.runtimeBytes);
276
- const references = this.#config.root.reserveBatch(costs.map(charge => this.#request("contract_query_acquisition", charge)));
277
- this.#working++;
278
- try {
279
- this.#contractQueries = new ContractQueryAcquisitions(this.#config.root, this.clock, limit, this.#config.runtimeBytes, references, this.diagnostics);
280
- this.#check();
281
- return this.#contractQueries;
282
- }
283
- catch (error) {
284
- this.#contractQueries?.close();
285
- throw error;
286
- }
287
- finally {
288
- for (const reference of references)
289
- reference.release();
290
- this.#working--;
291
- this.#cleanup();
292
- }
293
- }
294
- serviceBindings(limit) {
295
- this.#check();
296
- if (this.#serviceBindings !== undefined) {
297
- if (this.#serviceBindings.methodLimit !== limit)
298
- fail("configuration_capacity");
299
- return this.#serviceBindings;
300
- }
301
- const owner = this.#owner("service_bindings");
302
- const account = serviceBindingAccount(this.#config.root, owner, limit, this.#config.limit);
303
- let reference;
304
- try {
305
- const accounts = Object.freeze([...this.#accounts, account]);
306
- reference = this.#config.root.reserve({ accounts, owner, charge: serviceBindingPoolCharge(this.#config.runtimeBytes) });
307
- this.#serviceBindings = new ServiceBindingPool(this.#config.root, accounts, owner, limit, this.#config.runtimeBytes, reference, this.clock);
308
- this.#serviceAccount = account;
309
- return this.#serviceBindings;
310
- }
311
- catch (error) {
312
- account.close();
313
- throw error;
314
- }
315
- finally {
316
- reference?.release();
317
- }
318
- }
319
- reserveServiceBinding(config) {
320
- this.#check();
321
- if (this.#serviceBindings === undefined)
322
- fail("configuration_capacity");
323
- return this.#serviceBindings.reserve(config);
324
- }
325
- reserveDependencyQueries(admission) {
326
- this.#check();
327
- if (this.#contractQueries === undefined)
328
- fail("configuration_capacity");
329
- return admission.reserveDependencyQueries(this.#contractQueries);
330
- }
331
- reserveDependencyStreams(admission, targets) {
332
- this.#check();
333
- admission.reserveDependencyStreams(this.#config.root, this.#accounts, this.#owner("initial_streams"), this.#config.runtimeBytes, targets);
334
- }
335
- reserveRawStreams(admission, declarations) {
336
- this.#check();
337
- if (admission === undefined)
338
- fail("configuration_capacity");
339
- return admission.prepareRawStreams(this.#config.root, this.#accounts, this.#owner("initial_raw_streams"), this.#config.runtimeBytes, declarations);
340
- }
341
- /** A logical authority keeps one continuous execution owner across Sessions.
342
- * Repeated configuration cannot install an empty replacement history. */
343
- executionService(input) {
344
- this.#check();
345
- const config = captureVolatileExecution(input), key = executionServiceKey(config);
346
- const existing = this.#executionServices.get(key);
347
- if (existing !== undefined) {
348
- if (executionStorage(existing.config) !== executionStorage(config) || existing.configuration !== JSON.stringify(config, (_key, value) => typeof value === "bigint" ? value.toString() : value))
349
- fail("configuration_capacity");
350
- return existing;
351
- }
352
- if (this.#executionServices.size >= 64)
353
- this.#resourceUnavailable();
354
- const history = new VolatileExecutions(this.resources, this.clock, config);
355
- this.#executionServices.set(key, history);
356
- return history;
357
- }
358
- reserveClientAdmission(spec, carrierCosts = [], released) {
359
- this.#check();
360
- if (carrierCosts.length !== 0 && this.#dependencies.size + this.#dependencyClaims.size >= this.#config.dependencies)
361
- this.#resourceUnavailable();
362
- const plan = sessionAdmissionPlan(spec, this.#config.runtimeBytes);
363
- const costs = [...plan.costs, ["client_admission", clientAdmissionCharge(this.#config.runtimeBytes)], ...carrierCosts];
364
- const references = this.#config.root.reserveBatch(costs.map(([kind, charge]) => this.#request(kind, charge)));
365
- try {
366
- const admission = new ClientSessionAdmission(costs, references, () => { try {
367
- released?.();
368
- }
369
- finally {
370
- this.#dependencyClaims.delete(admission);
371
- this.#cleanup();
372
- } }, plan.rpcPlan === undefined ? undefined : { inputs: plan.rpcPlan.inputs, queries: plan.rpcPlan.queries });
373
- try {
374
- admission.reserveLedger(spec, this.clock, this.#config.runtimeBytes);
375
- admission.reserveAccounts(this.#config.root, this.#owner("send_headroom"), plan, this.#config.runtimeBytes);
376
- admission.reserveNativePositions(this.#config.root, plan, this.#config.runtimeBytes);
377
- if (spec.transport.nativeDatagrams !== undefined)
378
- admission.reserveUnreliable(this.#config.root, this.#config.runtimeBytes);
379
- // Environment services retain one original owner across candidates.
380
- // Establishment reuses these exact pools and execution histories.
381
- const application = plan.rpcConfig;
382
- if (application !== undefined) {
383
- admission.reserveCalls(spec.streams.rpcMaxGeneralOutstanding ?? 0, this.#config.runtimeBytes);
384
- admission.reserveServices(this.#config.root, this.#accounts, this.#owner("application_headroom"), this.#config.runtimeBytes, plan.rpcPlan);
385
- this.contractQueries(application.queryAcquisitions);
386
- this.serviceBindings(application.queryAcquisitions === 2 ? 16 : 256);
387
- for (const config of application.executionServices ?? [])
388
- this.executionService(config);
389
- for (const entry of [...application.unaryHandlers ?? [], ...application.streamingHandlers ?? [], ...application.notificationHandlers ?? []]) {
390
- if (entry.execution !== undefined)
391
- this.executionService(entry.execution);
392
- }
393
- }
394
- if (spec.initialRawStreams !== undefined && spec.initialRawStreams.length !== 0)
395
- admission.reserveInitialRawStreams(this.#config.root, this.#accounts, this.#owner("initial_raw_streams"), this.#config.runtimeBytes, spec.initialRawStreams);
396
- }
397
- catch (error) {
398
- admission.close();
399
- throw error;
400
- }
401
- if (carrierCosts.length !== 0)
402
- this.#dependencyClaims.add(admission);
403
- return admission;
404
- }
405
- catch (error) {
406
- for (const reference of references)
407
- reference.release();
408
- throw error;
409
- }
410
- }
411
- /** Trusted assembly reserves the original fixed work vectors before Acquire. */
412
- reserveInitializerWorkload(charges) {
413
- this.#check();
414
- if (charges.length < 1 || charges.length > 16)
415
- fail("configuration_capacity");
416
- return this.#config.root.reserveBatch(charges.map(charge => this.#request("initializer_workload", charge)));
417
- }
418
- fillRandom(bytes) { this.#check(); this.#random.fill(bytes); }
419
- reserveConnectionWork(kind, charge, admission) {
420
- this.#check();
421
- return admission?.take([[kind, charge]])[0] ?? this.#reserve(kind, charge);
422
- }
423
- admitDependency(kind, charge, prepaid, admission) {
424
- this.#check();
425
- if (this.#dependencies.size + this.#dependencyClaims.size - (admission !== undefined && this.#dependencyClaims.has(admission) ? 1 : 0) >= this.#config.dependencies)
426
- this.#resourceUnavailable();
427
- if (prepaid !== undefined && !prepaid.sameEnvironment(this.#reference))
428
- fail("owner_unavailable");
429
- const ref = prepaid?.take(charge) ?? this.#reserve(kind, charge);
430
- const dependency = new EnvironmentDependency(token, ref, () => { this.#dependencies.delete(dependency); this.#cleanup(); });
431
- if (admission !== undefined)
432
- this.#dependencyClaims.delete(admission);
433
- this.#dependencies.add(dependency);
434
- return dependency;
435
- }
436
- /** One provider lifecycle with prepaid reusable native positions. The full
437
- * vector and every physical reference slot precede native construction. */
438
- admitDependencyPositions(kind, charge, positionCharge, count, prepaid, admission) {
439
- this.#check();
440
- if (!Number.isSafeInteger(count) || count < 1 || count > 4097)
441
- fail("configuration_capacity");
442
- if (this.#dependencies.size + this.#dependencyClaims.size - (admission !== undefined && this.#dependencyClaims.has(admission) ? 1 : 0) >= this.#config.dependencies)
443
- this.#resourceUnavailable();
444
- const requests = [this.#request(kind, charge)];
445
- for (let i = 0; i < count; i++)
446
- requests.push(this.#request("native_stream_position", positionCharge));
447
- if (prepaid !== undefined && (prepaid.length !== requests.length || prepaid.some(ref => !ref.sameEnvironment(this.#reference))))
448
- fail("owner_unavailable");
449
- const refs = prepaid === undefined ? this.#config.root.reserveBatch(requests) : [...prepaid], positions = [];
450
- try {
451
- for (const reference of refs.slice(1))
452
- positions.push(this.#config.root.protect(reference, positionCharge));
453
- const dependency = new EnvironmentDependency(token, refs[0].take(charge), () => { this.#dependencies.delete(dependency); this.#cleanup(); });
454
- if (admission !== undefined)
455
- this.#dependencyClaims.delete(admission);
456
- this.#dependencies.add(dependency);
457
- return Object.freeze({ dependency, positions: Object.freeze(positions) });
458
- }
459
- catch (error) {
460
- for (const position of positions)
461
- position.close();
462
- for (const reference of refs)
463
- reference.release();
464
- throw error;
465
- }
466
- }
467
- namespace(options) {
468
- this.#check();
469
- const captured = captureNamespace(options), key = `${captured.tenant}\0${captured.authority}`;
470
- this.#check();
471
- const existing = this.#namespaces.get(key);
472
- if (existing !== undefined) {
473
- if (!sameNamespace(existing.options, captured))
474
- fail("credential_binding");
475
- return existing.namespace;
476
- }
477
- if (this.#namespaces.size >= this.#config.namespaces)
478
- this.#resourceUnavailable();
479
- const ref = this.#reserve("namespace", credentialWorkCharge(Math.max(270336, captured.stateBytes), this.#config.runtimeBytes));
480
- this.#working++;
481
- try {
482
- const namespace = new CredentialNamespace({ ...captured, clock: this.clock, random: bytes => this.#random.fill(bytes), resources: this.resources }, ref);
483
- if (this.#closed) {
484
- namespace.close();
485
- fail("closed");
486
- }
487
- this.#namespaces.set(key, { options: captured, namespace });
488
- return namespace;
489
- }
490
- finally {
491
- ref.release();
492
- this.#working--;
493
- this.#cleanup();
494
- }
495
- }
496
- #policy(policy) {
497
- const tenant = policy.tenant;
498
- if (!policyText(tenant) || !policyText(policy.audience) || !policyText(policy.clientSubject) || !policyText(policy.serverSubject))
499
- fail("configuration_capacity");
500
- if (!Array.isArray(policy.authorities) || policy.authorities.length < 1 || policy.authorities.length > 8)
501
- fail("configuration_capacity");
502
- const authorityNames = [...policy.authorities];
503
- if (authorityNames.some(authority => !policyText(authority)) || new Set(authorityNames).size !== authorityNames.length)
504
- fail("configuration_capacity");
505
- if (!Array.isArray(policy.cryptoProfiles) || policy.cryptoProfiles.length < 1 || policy.cryptoProfiles.length > 8)
506
- fail("configuration_capacity");
507
- const cryptoProfiles = [...policy.cryptoProfiles];
508
- if (cryptoProfiles.some(profile => typeof profile !== "string" || ownProfile(profile) === undefined) || new Set(cryptoProfiles).size !== cryptoProfiles.length)
509
- fail("configuration_capacity");
510
- if (policy.tunnel !== undefined && (policy.tunnel.role !== 0 && policy.tunnel.role !== 1 || !policyText(policy.tunnel.audience) || !policyText(policy.tunnel.service) || !policyText(policy.tunnel.relaySubject) ||
511
- policy.tunnel.candidateCapacity !== undefined && (!Number.isSafeInteger(policy.tunnel.candidateCapacity) || policy.tunnel.candidateCapacity < 1 || policy.tunnel.candidateCapacity > 16)))
512
- fail("configuration_capacity");
513
- const namespaces = authorityNames.map(authority => { const entry = this.#namespaces.get(`${tenant}\0${authority}`); if (entry === undefined)
514
- fail("credential_untrusted"); return entry.namespace; });
515
- const liveGrant = policy.tunnel?.liveGrant;
516
- if (liveGrant !== undefined && (!policyText(liveGrant.authority) || !authorityNames.includes(liveGrant.authority) || !(liveGrant.issuerKeyID instanceof Uint8Array) || liveGrant.issuerKeyID.length !== 16 ||
517
- !policyText(liveGrant.revocationPolicyID) || typeof liveGrant.revocationPolicyRevision !== "bigint" || liveGrant.revocationPolicyRevision < 0n || liveGrant.revocationPolicyRevision > 0xffffffffffffffffn ||
518
- typeof liveGrant.maxNotAfterMS !== "bigint" || liveGrant.maxNotAfterMS <= 0n || liveGrant.maxNotAfterMS > 0xffffffffffffffffn))
519
- fail("configuration_capacity");
520
- return Object.freeze({ tenant, audience: policy.audience, clientSubject: policy.clientSubject, serverSubject: policy.serverSubject, cryptoProfiles: Object.freeze(cryptoProfiles),
521
- ...(policy.tunnel === undefined ? {} : { tunnel: Object.freeze({ role: policy.tunnel.role, audience: policy.tunnel.audience, service: policy.tunnel.service, relaySubject: policy.tunnel.relaySubject, ...(policy.tunnel.candidateCapacity === undefined ? {} : { candidateCapacity: policy.tunnel.candidateCapacity }), ...(liveGrant === undefined ? {} : { liveGrant: Object.freeze({ ...liveGrant, issuerKeyID: new Uint8Array(liveGrant.issuerKeyID) }) }) }) }),
522
- resources: this.resources, clock: this.clock, namespaces: Object.freeze(namespaces) });
523
- }
524
- registerSource(policy, source, provider) {
525
- this.#check();
526
- if (source !== "live_authority" && source !== "preauthorized_pool" || typeof provider !== "function")
527
- fail("configuration_capacity");
528
- const verified = this.#policy(policy), captured = Object.freeze({ tenant: verified.tenant, audience: verified.audience, clientSubject: verified.clientSubject, serverSubject: verified.serverSubject,
529
- ...(verified.tunnel === undefined ? {} : { tunnel: verified.tunnel }), cryptoProfiles: verified.cryptoProfiles, authorities: Object.freeze(verified.namespaces.map(ns => ns.authority)) });
530
- this.#check();
531
- if (this.#sources.size >= this.#config.sources)
532
- this.#resourceUnavailable();
533
- const reference = this.#reserve("source", new ResourceVector([this.#config.runtimeBytes, 0n, 0n, 1n, 0n, 0n, 0n, 0n, 0n, 0n, 0n]));
534
- const owner = new V4EnvironmentCredentialSource(token, { environment: this, policy: captured, source, provider, reference, closed: false, active: 0 });
535
- this.#sources.add(owner);
536
- return owner;
537
- }
538
- releaseSource(capability, owner) {
539
- if (capability !== token)
540
- fail("source_unavailable");
541
- const state = sources.get(owner);
542
- if (state.closed) {
543
- if (state.source === "live_authority")
544
- this.#connector?.withdrawUnboundAcquisition?.();
545
- for (const job of this.#acquisitions)
546
- if (job.source === owner)
547
- job.abort.abort();
548
- for (const material of [...this.#materials]) {
549
- const original = materials.get(material);
550
- if (original.source !== owner || original.originalCustody === undefined)
551
- continue;
552
- original.preparationAbort?.abort();
553
- original.originalCustody.withdraw();
554
- if (!original.claimed)
555
- this.releaseMaterial(token, material);
556
- }
557
- }
558
- if (state.closed && state.active === 0) {
559
- state.reference.release();
560
- this.#sources.delete(owner);
561
- this.#cleanup();
562
- }
563
- }
564
- prepareRegisteredTunnelCarrier(policy, input, workMS) {
565
- this.#check();
566
- return prepareRegisteredCarrier(this.#policy(policy), input, workMS);
567
- }
568
- prepareTunnelCredentials(policy) {
569
- this.#check();
570
- return new TunnelCredentialPreparation(this.#policy(policy));
571
- }
572
- verify(policy, input, prepared) {
573
- this.#check();
574
- const config = this.#policy(policy);
575
- if (this.#materials.size + this.#acquisitions.size + this.#verifying >= this.#config.materials)
576
- this.#resourceUnavailable();
577
- const original = prepared ?? (config.tunnel === undefined ? undefined : new TunnelCredentialPreparation(config));
578
- try {
579
- return this.#verify(config, input, undefined, original);
580
- }
581
- finally {
582
- original?.close();
583
- }
584
- }
585
- #verify(config, input, subscriptions, prepared) {
586
- const ref = prepared?.takeMaterial() ?? this.#reserve("material", credentialVerifierCharge(this.#config.runtimeBytes).add(new ResourceVector([this.#config.runtimeBytes, 0n, 0n, 0n, 0n, 0n, 1n, 0n, 0n, 0n, 0n])));
587
- let closure, originalCustody;
588
- let poolServerAllow, poolServerAllowReference;
589
- this.#working++;
590
- this.#verifying++;
591
- try {
592
- if (input.poolServerAllow !== undefined) {
593
- requireCredential(input.source === "preauthorized_pool" && config.tunnel?.role === 0, "credential_binding");
594
- poolServerAllowReference = this.#reserve("pool_material_server_allow", poolServerAllowConfigurationCharge(input.poolServerAllow));
595
- poolServerAllow = capturePoolServerAllowConfiguration(input.poolServerAllow);
596
- }
597
- closure = verifyDirectCredentials(config, input, ref, subscriptions, prepared);
598
- // Verification transfers the primary reference to its closure. Custody
599
- // must borrow from that current owner after verification succeeds.
600
- originalCustody = closure.withOriginalMaterialReference(reference => this.#connector?.acquireMaterial?.(input, reference));
601
- this.#check();
602
- const material = new V4EnvironmentMaterial(token, { environment: this, closure, claimed: false, timer: undefined,
603
- ...(poolServerAllow === undefined ? {} : { poolServerAllow, poolServerAllowReference: poolServerAllowReference }),
604
- ...(originalCustody === undefined ? {} : { originalCustody }) });
605
- this.#materials.add(material);
606
- this.#expireMaterial(material);
607
- if (materials.get(material).closure === undefined)
608
- fail("material_unavailable");
609
- return material;
610
- }
611
- catch (error) {
612
- originalCustody?.withdraw();
613
- closure?.close();
614
- clearPoolServerAllowConfiguration(poolServerAllow);
615
- poolServerAllowReference?.release();
616
- throw error;
617
- }
618
- finally {
619
- ref.release();
620
- this.#working--;
621
- this.#verifying--;
622
- this.#cleanup();
623
- }
624
- }
625
- /** Internal pool installation check on the original verified closure. */
626
- checkOriginalPoolMaterialExpiry(material, expiry, reference) {
627
- this.checkOriginalServerPublication(material, reference);
628
- materials.get(material).closure.checkPoolInstallExpiry(expiry, reference);
629
- }
630
- acceptOriginalPoolServerAllow(material, request, grant, reference) {
631
- this.checkOriginalServerPublication(material, reference);
632
- const state = materials.get(material);
633
- requireCredential(state.poolServerAllowed !== true, "credential_binding");
634
- state.closure.checkPoolServerAllow(request, grant, reference);
635
- state.poolServerAllowed = true;
636
- }
637
- /** Internal original control publication preparation. The exact server
638
- * snapshot remains unclaimed; a received row cannot recreate this position. */
639
- beginOriginalLivePublication(material, attempt, reference) {
640
- this.checkOriginalLivePublication(material, reference);
641
- materials.get(material).closure.beginLivePreparation(attempt, reference);
642
- }
643
- checkOriginalLivePublication(material, reference) {
644
- this.checkOriginalServerPublication(material, reference);
645
- }
646
- checkOriginalServerPublication(material, reference) {
647
- this.#check();
648
- const state = materials.get(material);
649
- if (state?.environment !== this || state.claimed || state.closure === undefined || !this.#materials.has(material) || !reference.sameEnvironment(this.#reference))
650
- fail("material_unavailable");
651
- state.closure.checkPreparation(reference);
652
- }
653
- installOriginalLivePublication(material, bytes, reference) {
654
- this.checkOriginalLivePublication(material, reference);
655
- const proof = materials.get(material).closure.installLiveAuthorization(bytes, reference);
656
- proof.fill(0);
657
- this.checkOriginalLivePublication(material, reference);
658
- }
659
- #expireMaterial(material) {
660
- const state = materials.get(material);
661
- try {
662
- state.closure.checkPreparation(this.#reference);
663
- // The original credential deadlines remain authoritative; this bounded
664
- // wakeup only collects unused snapshots and never extends a deadline.
665
- state.timer = setTimeout(() => { state.timer = undefined; if (!state.claimed && state.closure !== undefined)
666
- this.#expireMaterial(material); }, 1000);
667
- }
668
- catch {
669
- this.releaseMaterial(token, material);
670
- }
671
- }
672
- releaseMaterial(capability, material) {
673
- if (capability !== token)
674
- fail("material_unavailable");
675
- const state = materials.get(material);
676
- if (state.environment !== this)
677
- fail("material_unavailable");
678
- if (state.timer !== undefined)
679
- clearTimeout(state.timer);
680
- state.timer = undefined;
681
- state.originalCustody?.withdraw();
682
- state.originalCustody = undefined;
683
- clearPoolServerAllowConfiguration(state.poolServerAllow);
684
- delete state.poolServerAllow;
685
- state.poolServerAllowReference?.release();
686
- delete state.poolServerAllowReference;
687
- state.closure?.close();
688
- state.closure = undefined;
689
- this.#materials.delete(material);
690
- this.#cleanup();
691
- }
692
- acquire(owner, request, options, attempt) {
693
- try {
694
- this.#check();
695
- const source = sources.get(owner);
696
- if (source?.environment !== this || source.closed || !this.#sources.has(owner))
697
- fail("source_unavailable");
698
- if (options?.signal?.aborted)
699
- fail("canceled");
700
- const requirements = captureConnectionRequirements(request), config = this.#policy(source.policy);
701
- // Freshness is checked before asking a source to issue or remove a lease.
702
- for (const namespace of config.namespaces)
703
- namespace.check();
704
- if (this.#acquisitions.size >= this.#config.acquisitions || this.#materials.size + this.#acquisitions.size + this.#verifying >= this.#config.materials)
705
- this.#resourceUnavailable();
706
- const original = new TrustedWindow(this.clock, this.#config.acquireMS), abort = new AbortController();
707
- const candidateCapacity = config.tunnel?.candidateCapacity ?? 1;
708
- const reference = this.#reserve("acquire", new ResourceVector([245760n + BigInt(candidateCapacity - 1) * 81920n + this.#config.runtimeBytes, 0n, 0n, 5n, 1n, 1n, 1n, 0n, 0n, 0n, 0n]));
709
- const job = { reference, abort, source: owner, timer: undefined };
710
- this.#acquisitions.add(job);
711
- source.active++;
712
- attempt?.retain();
713
- const subscriptions = new Map();
714
- let buffers, prepared;
715
- try {
716
- // A provider may issue or remove a once-only lease. Reserve every
717
- // possible namespace consumer before that irreversible source work.
718
- for (const namespace of config.namespaces)
719
- subscriptions.set(namespace, namespace.reserveSubscription(reference));
720
- if (config.tunnel !== undefined)
721
- prepared = new TunnelCredentialPreparation(config);
722
- buffers = Object.freeze({ artifact: new Uint8Array(sizes.artifact), clientCertificate: new Uint8Array(sizes.clientCertificate), serverCertificate: new Uint8Array(sizes.serverCertificate), activation: new Uint8Array(sizes.activation), tunnelGrant: new Uint8Array(sizes.tunnelGrant), relayCertificate: new Uint8Array(sizes.relayCertificate), tunnelCandidates: Object.freeze(Array.from({ length: candidateCapacity - 1 }, () => Object.freeze({ grant: new Uint8Array(sizes.tunnelGrant), relayCertificate: new Uint8Array(sizes.relayCertificate) }))) });
723
- }
724
- catch (error) {
725
- prepared?.close();
726
- for (const subscription of subscriptions.values())
727
- subscription.close();
728
- this.#acquisitions.delete(job);
729
- source.active--;
730
- reference.release();
731
- this.releaseSource(token, owner);
732
- this.#cleanup();
733
- attempt?.release();
734
- throw error;
735
- }
736
- let rejectCanceled;
737
- const canceled = new Promise((_resolve, reject) => { rejectCanceled = reject; });
738
- const canceledResult = () => rejectCanceled(new Error(this.#closed ? "closed" : "canceled"));
739
- abort.signal.addEventListener("abort", canceledResult, { once: true });
740
- const onAbort = () => { abort.abort(); };
741
- options?.signal?.addEventListener("abort", onAbort, { once: true });
742
- const timeout = () => {
743
- try {
744
- original.check();
745
- job.timer = setTimeout(timeout, timerChunk(original.remainingMS()));
746
- }
747
- catch {
748
- // Abort synchronously notifies cancellation observers, so preserve
749
- // the original deadline outcome before fencing the provider.
750
- rejectCanceled(new Error("deadline_exceeded"));
751
- abort.abort();
752
- }
753
- };
754
- timeout();
755
- // The original job is entered synchronously and remains paid until the
756
- // source callback has really returned. Abort only fences installation.
757
- let providerEntered = false;
758
- const tail = (async () => {
759
- try {
760
- if (abort.signal.aborted)
761
- fail("canceled");
762
- providerEntered = true;
763
- const returnedLengths = await source.provider(Object.freeze({ signal: abort.signal, requirements }), buffers);
764
- if (returnedLengths === null || typeof returnedLengths !== "object")
765
- fail("source_contract_invalid");
766
- const lengths = Object.freeze({ artifact: returnedLengths.artifact, clientCertificate: returnedLengths.clientCertificate,
767
- poolServerAllow: returnedLengths.poolServerAllow,
768
- serverCertificate: returnedLengths.serverCertificate, activation: returnedLengths.activation,
769
- tunnelGrant: returnedLengths.tunnelGrant ?? 0, relayCertificate: returnedLengths.relayCertificate ?? 0,
770
- candidateIndex: returnedLengths.candidateIndex, tunnelCandidates: returnedLengths.tunnelCandidates ?? [] });
771
- this.#check();
772
- original.check();
773
- if (abort.signal.aborted || source.closed)
774
- fail("canceled");
775
- for (const subscription of subscriptions.values())
776
- subscription.check();
777
- for (const key of keys) {
778
- const length = lengths[key] ?? (key === "tunnelGrant" || key === "relayCertificate" ? 0 : -1);
779
- if (!Number.isSafeInteger(length) || length < (key === "tunnelGrant" || key === "relayCertificate" || key === "activation" && source.source === "live_authority" ? 0 : 1) || length > sizes[key])
780
- fail("source_contract_invalid");
781
- }
782
- const candidateIndex = lengths.candidateIndex, tunnelCandidateLengths = lengths.tunnelCandidates ?? [];
783
- if (!Number.isSafeInteger(candidateIndex) || candidateIndex < 0 || candidateIndex >= 16 || !Array.isArray(tunnelCandidateLengths) ||
784
- tunnelCandidateLengths.length >= candidateCapacity || (source.source !== "preauthorized_pool" && tunnelCandidateLengths.length > 0))
785
- fail("source_contract_invalid");
786
- const seenCandidates = new Set([candidateIndex]);
787
- const candidateGrants = Array.from(tunnelCandidateLengths, (entry, position) => {
788
- if (entry === null || typeof entry !== "object")
789
- fail("source_contract_invalid");
790
- const index = entry.candidateIndex, grantLength = entry.grant, relayLength = entry.relayCertificate, supplied = buffers.tunnelCandidates?.[position];
791
- if (!Number.isSafeInteger(index) || index < 0 || index >= 16 || seenCandidates.has(index) || !Number.isSafeInteger(grantLength) || grantLength < 1 || grantLength > sizes.tunnelGrant ||
792
- !Number.isSafeInteger(relayLength) || relayLength < 1 || relayLength > sizes.relayCertificate || supplied === undefined)
793
- fail("source_contract_invalid");
794
- seenCandidates.add(index);
795
- return Object.freeze({ candidateIndex: index, grant: supplied.grant.subarray(0, grantLength), relayCertificate: supplied.relayCertificate.subarray(0, relayLength) });
796
- });
797
- if (candidateGrants.length > 0 && (lengths.tunnelGrant ?? 0) === 0)
798
- fail("source_contract_invalid");
799
- const input = { artifact: buffers.artifact.subarray(0, lengths.artifact), clientCertificate: buffers.clientCertificate.subarray(0, lengths.clientCertificate),
800
- ...(lengths.poolServerAllow === undefined ? {} : { poolServerAllow: lengths.poolServerAllow }),
801
- serverCertificate: buffers.serverCertificate.subarray(0, lengths.serverCertificate),
802
- ...((lengths.tunnelGrant ?? 0) === 0 && (lengths.relayCertificate ?? 0) === 0 ? {} : { tunnel: { grant: buffers.tunnelGrant.subarray(0, lengths.tunnelGrant ?? 0), relayCertificate: buffers.relayCertificate.subarray(0, lengths.relayCertificate ?? 0), ...(candidateGrants.length === 0 ? {} : { candidateGrants: Object.freeze(candidateGrants) }) } }), activation: buffers.activation.subarray(0, lengths.activation), source: source.source, candidateIndex };
803
- const result = this.#verify(config, input, subscriptions, prepared);
804
- materials.get(result).source = owner;
805
- try {
806
- materials.get(result).closure.checkConnectionRequirements(requirements, this.#reference);
807
- materials.get(result).requirements = requirements;
808
- if (abort.signal.aborted || this.#closed || source.closed)
809
- fail("canceled");
810
- return result;
811
- }
812
- catch (error) {
813
- this.releaseMaterial(token, result);
814
- throw error;
815
- }
816
- }
817
- catch (error) {
818
- if (providerEntered && source.source === "live_authority")
819
- this.#connector?.withdrawUnboundAcquisition?.();
820
- // Source exceptions do not expose their provider graph or host message.
821
- const code = controllerFailureCode(error);
822
- throw new Error(code === "controller_failed" ? "source_unavailable" : code);
823
- }
824
- finally {
825
- if (job.timer !== undefined)
826
- clearTimeout(job.timer);
827
- options?.signal?.removeEventListener("abort", onAbort);
828
- abort.signal.removeEventListener("abort", canceledResult);
829
- for (const key of keys)
830
- buffers[key].fill(0);
831
- for (const candidate of buffers.tunnelCandidates ?? []) {
832
- candidate.grant.fill(0);
833
- candidate.relayCertificate.fill(0);
834
- }
835
- prepared?.close();
836
- for (const subscription of subscriptions.values())
837
- subscription.close();
838
- subscriptions.clear();
839
- reference.release();
840
- this.#acquisitions.delete(job);
841
- source.active--;
842
- this.releaseSource(token, owner);
843
- this.#cleanup();
844
- attempt?.release();
845
- }
846
- })();
847
- return Promise.race([tail, canceled]).then(material => {
848
- if (this.#closed || options?.signal?.aborted || source.closed) {
849
- this.releaseMaterial(token, material);
850
- fail(this.#closed ? "closed" : "canceled");
851
- }
852
- return material;
853
- });
854
- }
855
- catch (error) {
856
- return Promise.reject(error);
857
- }
858
- }
859
- /** Private assembly, after an actual transport/once owner supplies its inputs.
860
- * No public API accepts this raw-key assembly or an authenticated flag. */
861
- establishVerified(material, spec, context, options) {
862
- return this.#establish(material, spec, context, options);
863
- }
864
- /** Internal pool assembly. The Node WSS entrance must still perform the real
865
- * HELLO/FSB/FSA sequence; this is not exposed as production Connect. */
866
- establishPoolVerified(material, spec, context, store, options) {
867
- if (!isPoolSpendStore(store))
868
- return Promise.reject(new Error("owner_unavailable"));
869
- return this.#establish(material, spec, context, options, store);
870
- }
871
- /** Internal production client assembly. A native carrier is prepared before
872
- * atomic Session admission; TxA-P precedes the first HELLO byte. */
873
- establishPoolClient(material, store, prepare, options) {
874
- if (!isPoolSpendStore(store))
875
- return Promise.reject(new Error("owner_unavailable"));
876
- return this.#establishClient(material, "preauthorized_pool", prepare, options, store);
877
- }
878
- establishLiveClient(material, live, prepare, options) {
879
- return this.#establishClient(material, "live_authority", prepare, options, undefined, live);
880
- }
881
- async #establishClient(material, source, prepare, options, store, live) {
882
- this.#check();
883
- const state = materials.get(material);
884
- if (state?.environment !== this || state.claimed || state.closure === undefined || !this.#materials.has(material))
885
- fail("material_unavailable");
886
- if (options?.signal?.aborted)
887
- fail("canceled");
888
- if (this.#sessions.size + this.#admissions.size + this.#preparations.size + this.#connectionClaims.size - (state.connectionClaim !== undefined && this.#connectionClaims.has(state.connectionClaim) ? 1 : 0) >= this.#config.sessions)
889
- this.#resourceUnavailable();
890
- const abort = new AbortController(), signal = options?.signal === undefined ? abort.signal : AbortSignal.any([abort.signal, options.signal]);
891
- state.preparationAbort = abort;
892
- this.#preparations.add(abort);
893
- if (state.connectionClaim !== undefined)
894
- this.#connectionClaims.delete(state.connectionClaim);
895
- state.claimed = true;
896
- if (state.timer !== undefined)
897
- clearTimeout(state.timer);
898
- state.timer = undefined;
899
- let fields, spec, exchange;
900
- const supersededFields = [];
901
- try {
902
- if (source === "live_authority") {
903
- const attempt = new Uint8Array(16);
904
- try {
905
- this.#random.fill(attempt);
906
- state.closure.beginLivePreparation(attempt, this.#reference);
907
- }
908
- finally {
909
- attempt.fill(0);
910
- }
911
- }
912
- fields = state.closure.clientPreparation(this.#reference);
913
- state.connectionFacts?.source(fields.source);
914
- if (fields.source !== source)
915
- fail("credential_binding");
916
- try {
917
- spec = await prepare(fields, signal, state.admission);
918
- }
919
- catch (error) {
920
- if (!signal.aborted)
921
- observeNativeConnectionFailure(error);
922
- throw error;
923
- }
924
- const selectedCandidateIndex = spec.selectedCandidateIndex ?? fields.candidateIndex;
925
- requireCredential(Number.isSafeInteger(selectedCandidateIndex), "credential_binding");
926
- if (state.requirements !== undefined)
927
- state.closure.checkConnectionRequirements(state.requirements, this.#reference, selectedCandidateIndex);
928
- const selected = state.closure.selectClientCandidate(this.#reference, selectedCandidateIndex);
929
- supersededFields.push(fields);
930
- fields = selected;
931
- spec = { ...spec, selectedCandidateIndex, peerReadyPublicKey: selected.identityKeys[1], noise: { ...spec.noise, localStaticPublic: selected.noiseKeys[0], peerStaticPublic: selected.noiseKeys[1], psk: selected.psk },
932
- ready: { ...spec.ready, localCertificateDigest: selected.identities[0], peerCertificateDigest: selected.identities[1] } };
933
- this.#check();
934
- if (signal.aborted)
935
- fail("canceled");
936
- if (typeof spec.transport.checkPreparation !== "function")
937
- fail("owner_unavailable");
938
- spec.transport.checkPreparation();
939
- state.closure.checkClientIdentity(spec.noise.localStaticPrivate, spec.signer.publicKey, this.#reference);
940
- const ref = state.admission?.take([["client_admission", clientAdmissionCharge(this.#config.runtimeBytes)]])[0] ?? this.#reserve("client_admission", clientAdmissionCharge(this.#config.runtimeBytes));
941
- try {
942
- exchange = new ClientAdmissionExchange(this.resources, state.closure, fields, spec.signer, bytes => this.#random.fill(bytes), ref, spec.transport, spec.bindingMode, state.requirements?.datagram === true ? 1n : 0n, spec.info.application_profile === "execution" && spec.application !== undefined ? applicationResumeFeature() : 0n, state.connectionFacts);
943
- }
944
- finally {
945
- ref.release();
946
- }
947
- return await this.#establish(material, spec, new Uint8Array(), { ...options, signal }, store, exchange, live);
948
- }
949
- catch (error) {
950
- state.originalCustody?.withdraw();
951
- if (spec !== undefined)
952
- await Promise.allSettled([spec.transport.close(), spec.transport.waitTermination()]);
953
- this.releaseMaterial(token, material);
954
- throw error;
955
- }
956
- finally {
957
- delete state.preparationAbort;
958
- exchange?.close();
959
- if (fields !== undefined)
960
- clearClientPreparation(fields);
961
- for (const previous of supersededFields)
962
- clearClientPreparation(previous);
963
- this.#preparations.delete(abort);
964
- this.#cleanup();
965
- }
966
- }
967
- checkPreparedTunnelCarrierMaterial(material, preparation) {
968
- this.#check();
969
- const state = materials.get(material);
970
- if (state?.environment !== this || state.claimed || state.closure === undefined)
971
- fail("material_unavailable");
972
- preparation.checkEnvironment(this.#reference);
973
- const candidateIndex = preparation.fields().candidateIndex;
974
- requireCredential(Number.isSafeInteger(candidateIndex), "credential_binding");
975
- const selected = state.closure.selectClientCandidate(this.#reference, candidateIndex);
976
- try {
977
- preparation.checkOriginalGrant(state.closure.tunnelCredentials(this.#reference), this.#reference);
978
- }
979
- finally {
980
- clearClientPreparation(selected);
981
- }
982
- }
983
- async authenticatePreparedEndpointHop(material, transport, signer, options) {
984
- this.#check();
985
- const state = materials.get(material);
986
- if (state?.environment !== this || state.claimed || state.closure === undefined || typeof transport.authenticateHop !== "function")
987
- fail("material_unavailable");
988
- state.closure.checkPreparation(this.#reference);
989
- this.#checkPoolServerActivation(state);
990
- const credentials = state.closure.tunnelCredentials(this.#reference), prepared = state.closure.takeTunnelHopPreparation(this.#reference);
991
- try {
992
- if (options?.signal?.aborted)
993
- fail("canceled");
994
- transport.activate?.();
995
- await transport.authenticateHop(credentials, signer, bytes => this.#random.fill(bytes), this.resources, this.#reference, options, undefined, prepared, state.closure.originalPreparationDeadline(this.#reference));
996
- }
997
- finally {
998
- prepared?.close();
999
- }
1000
- this.#check();
1001
- state.closure.checkPreparation(this.#reference);
1002
- }
1003
- /** Server assembly reaches its durable CAS only after the complete Session
1004
- * graph, FSA workspace and confirmation work have been reserved. */
1005
- async authenticateAcceptedHop(material, transport, signer, hello, options) {
1006
- const diagnostic = this.#connectionDiagnostic(material);
1007
- try {
1008
- await this.#authenticateAcceptedHop(material, transport, signer, hello, options);
1009
- }
1010
- catch (error) {
1011
- diagnostic.failure(error, true);
1012
- throw error;
1013
- }
1014
- }
1015
- #connectionDiagnostic(material) {
1016
- const state = materials.get(material);
1017
- const diagnostic = (state?.environment === this ? state.diagnostic : undefined) ?? new DiagnosticActivity(this.diagnostics, "prepare", true);
1018
- if (state?.environment === this)
1019
- state.diagnostic = diagnostic;
1020
- return diagnostic;
1021
- }
1022
- async #authenticateAcceptedHop(material, transport, signer, hello, options) {
1023
- this.#check();
1024
- const state = materials.get(material);
1025
- if (state?.environment !== this || state.claimed || state.closure === undefined || typeof transport.authenticateHop !== "function")
1026
- fail("material_unavailable");
1027
- state.closure.checkPreparation(this.#reference);
1028
- this.#checkPoolServerActivation(state);
1029
- const credentials = state.closure.tunnelCredentials(this.#reference), deadline = state.closure.originalPreparationDeadline(this.#reference), prepared = state.closure.takeTunnelHopPreparation(this.#reference);
1030
- try {
1031
- if (options?.signal?.aborted)
1032
- fail("canceled");
1033
- await transport.authenticateHop(credentials, signer, bytes => this.#random.fill(bytes), this.resources, this.#reference, options, hello, prepared, deadline);
1034
- }
1035
- finally {
1036
- prepared?.close();
1037
- }
1038
- this.#check();
1039
- state.closure.checkPreparation(this.#reference);
1040
- }
1041
- async establishServer(material, prepare, exchange, authority, owner, options) {
1042
- const diagnostic = this.#connectionDiagnostic(material);
1043
- try {
1044
- return await this.#establishServer(material, prepare, exchange, authority, owner, options);
1045
- }
1046
- catch (error) {
1047
- diagnostic.failure(error, true);
1048
- throw error;
1049
- }
1050
- }
1051
- async #establishServer(material, prepare, exchange, authority, owner, options) {
1052
- this.#check();
1053
- const state = materials.get(material);
1054
- if (state?.environment !== this || state.claimed || state.closure === undefined || !isServerAdmissionAuthority(authority))
1055
- fail("material_unavailable");
1056
- this.#checkPoolServerActivation(state);
1057
- if (options?.signal?.aborted)
1058
- fail("canceled");
1059
- if (this.#sessions.size + this.#admissions.size + this.#preparations.size + this.#connectionClaims.size >= this.#config.sessions)
1060
- this.#resourceUnavailable();
1061
- const abort = new AbortController(), signal = options?.signal === undefined ? abort.signal : AbortSignal.any([abort.signal, options.signal]);
1062
- state.preparationAbort = abort;
1063
- this.#preparations.add(abort);
1064
- state.claimed = true;
1065
- if (state.timer !== undefined)
1066
- clearTimeout(state.timer);
1067
- state.timer = undefined;
1068
- let fields;
1069
- try {
1070
- exchange.prepareClosure(state.closure);
1071
- fields = state.closure.clientPreparation(this.#reference);
1072
- await exchange.authenticate(state.closure, fields, { ...options, signal }, fields.applicationProfile === 2n ? applicationResumeFeature() : 0n);
1073
- this.#check();
1074
- if (signal.aborted)
1075
- fail("canceled");
1076
- const spec = await prepare(fields);
1077
- this.#check();
1078
- if (signal.aborted)
1079
- fail("canceled");
1080
- if (spec.noise.role !== "server" || spec.transport.role !== "server" || typeof spec.transport.checkPreparation !== "function")
1081
- fail("owner_unavailable");
1082
- spec.transport.checkPreparation();
1083
- state.closure.checkServerIdentity(spec.noise.localStaticPrivate, spec.signer.publicKey, this.#reference);
1084
- return await this.#establish(material, spec, new Uint8Array(), { ...options, signal }, undefined, undefined, undefined, { exchange, authority, owner, fields });
1085
- }
1086
- catch (error) {
1087
- this.releaseMaterial(token, material);
1088
- throw error;
1089
- }
1090
- finally {
1091
- delete state.preparationAbort;
1092
- exchange.close();
1093
- if (fields !== undefined)
1094
- clearClientPreparation(fields);
1095
- this.#preparations.delete(abort);
1096
- this.#cleanup();
1097
- }
1098
- }
1099
- #checkPoolServerActivation(state) {
1100
- if (state.closure.requiresPoolServerAllow(this.#reference) && state.poolServerAllowed !== true)
1101
- fail("owner_unavailable");
1102
- }
1103
- async #establish(material, spec, context, options, store, exchange, live, server) {
1104
- const state = materials.get(material);
1105
- if (state?.environment !== this)
1106
- fail("material_unavailable");
1107
- const diagnostic = state.diagnostic ??= new DiagnosticActivity(this.diagnostics, "prepare", true);
1108
- try {
1109
- return await this.#establishConnection(material, spec, context, options, store, exchange, live, server);
1110
- }
1111
- catch (error) {
1112
- diagnostic.failure(error, true);
1113
- throw error;
1114
- }
1115
- }
1116
- async #establishConnection(material, spec, context, options, store, exchange, live, server) {
1117
- this.#check();
1118
- const state = materials.get(material);
1119
- if (state?.environment !== this || state.claimed && exchange === undefined && server === undefined || state.closure === undefined || !this.#materials.has(material))
1120
- fail("material_unavailable");
1121
- if (options?.signal?.aborted)
1122
- fail("canceled");
1123
- if (this.#sessions.size + this.#admissions.size + this.#preparations.size - (exchange === undefined && server === undefined ? 0 : 1) + this.#connectionClaims.size - (state.connectionClaim !== undefined && this.#connectionClaims.has(state.connectionClaim) ? 1 : 0) >= this.#config.sessions)
1124
- this.#resourceUnavailable();
1125
- const c = this.#config, stream = spec.streams, noise = spec.noise, profile = ownProfile(noise.profile);
1126
- if (profile === undefined || !noise.authorizationDeadline.belongsTo(this.clock) || !noise.preparationDeadline.belongsTo(this.clock))
1127
- fail("credential_binding");
1128
- state.closure.checkPreparation(this.#reference);
1129
- const checkRequestedPreparation = () => {
1130
- if (state.requirements === undefined)
1131
- return;
1132
- const candidateIndex = exchange?.fields.candidateIndex ?? server?.fields.candidateIndex;
1133
- if (candidateIndex === undefined)
1134
- state.closure.checkConnectionRequirements(state.requirements, this.#reference);
1135
- else {
1136
- requireCredential(Number.isSafeInteger(candidateIndex), "credential_binding");
1137
- state.closure.checkConnectionRequirements(state.requirements, this.#reference, candidateIndex);
1138
- }
1139
- const maximum = spec.transport.nativeDatagrams?.maxDatagramBytes() ?? 0;
1140
- requireConnectionGuarantees(state.requirements, { ...spec.info, guarantees: { ...spec.info.guarantees,
1141
- datagram: Number.isSafeInteger(maximum) && maximum >= 76 } });
1142
- };
1143
- checkRequestedPreparation();
1144
- qualifySessionActivity(this.clock, selectedIdleDuration(spec.idleDurationMS ?? 0n, spec.localIdleDurationMS), stream.operationDeadlineMS, captureAutomaticLiveness(spec.automaticLiveness));
1145
- const crypto = { ...spec.crypto, clock: this.clock, profile: noise.profile, sendDirection: noise.role === "client" ? 0 : 1, runtimeBytes: c.runtimeBytes };
1146
- const streamOwner = this.#owner("stream");
1147
- const { costs, datagramIndex, sendQueueBytes, streamSendQueueBytes, nativePositionIndex, nativeOpeningIndex, nativePositionCount, nativeOpeningCount, maintenanceConfig, maintenanceIndex, sendAccountCount, sendAccountIndex, bootstrapIndex, bootstrapCosts, rpcStreamsIndex, managementIndex, managementCosts, notifyIndex, applicationProfile, rpcConfig, rpcPlan, rpcIndex } = sessionAdmissionPlan(spec, c.runtimeBytes, state.admission !== undefined);
1148
- this.#check();
1149
- if (this.#sessions.size + this.#admissions.size + this.#preparations.size - (exchange === undefined && server === undefined ? 0 : 1) + this.#connectionClaims.size - (state.connectionClaim !== undefined && this.#connectionClaims.has(state.connectionClaim) ? 1 : 0) >= c.sessions)
1150
- this.#resourceUnavailable();
1151
- const serverWorkIndex = costs.length;
1152
- if (server !== undefined)
1153
- costs.push(["server_admission_store", server.authority.charge()]);
1154
- const refs = state.admission?.take(costs, rpcPlan === undefined ? undefined : { inputs: rpcPlan.inputs, queries: rpcPlan.queries }) ?? c.root.reserveBatch(costs.map(([kind, charge]) => this.#request(kind, charge)));
1155
- const abort = new AbortController(), signal = options?.signal === undefined ? abort.signal : AbortSignal.any([abort.signal, options.signal]);
1156
- this.#admissions.add(abort);
1157
- // Transfer the original connection slot into admission. Carrier and
1158
- // exchange custody remain retained, but one connection counts only once.
1159
- if (state.preparationAbort !== undefined)
1160
- this.#preparations.delete(state.preparationAbort);
1161
- if (state.connectionClaim !== undefined)
1162
- this.#connectionClaims.delete(state.connectionClaim);
1163
- state.claimed = true;
1164
- if (state.timer !== undefined)
1165
- clearTimeout(state.timer);
1166
- state.timer = undefined;
1167
- let ledger, delivery, runtime;
1168
- let ephemeral = new Uint8Array(), sendAccount, sendAccounts, nativePositions;
1169
- let maintenancePositions;
1170
- let internalKeys;
1171
- let peerOpenPreparation;
1172
- let rpcAdmission;
1173
- let calls;
1174
- let applicationServices;
1175
- let initialStreams;
1176
- let initialRawStreams;
1177
- let unreliablePreparation;
1178
- const notifySendAccounts = [];
1179
- let notifyNativePosition;
1180
- let managementSendAccount, managementNativePosition;
1181
- let bootstrapSendAccount, bootstrapNativePosition;
1182
- const rpcSendAccounts = [], rpcNativePositions = Array.from({ length: 8 });
1183
- try {
1184
- maintenancePositions = new MaintenancePositions(c.root, maintenanceConfig, refs[maintenanceIndex], refs.slice(maintenanceIndex + 1, maintenanceIndex + 3), [refs[1], refs[9], refs[10], ...refs.slice(maintenanceIndex + 3, maintenanceIndex + 6)]);
1185
- const initialEpoch = maintenancePositions.epoch();
1186
- refs[1] = initialEpoch[0];
1187
- refs[9] = initialEpoch[1];
1188
- refs[10] = initialEpoch[2];
1189
- if (state.admission !== undefined) {
1190
- const prepaid = state.admission.takeAccounts(sendAccountCount, sendQueueBytes, streamSendQueueBytes);
1191
- sendAccount = prepaid.session;
1192
- sendAccounts = prepaid.directions;
1193
- }
1194
- else {
1195
- sendAccount = createSendAccount(c.root, streamOwner, sendQueueBytes);
1196
- sendAccounts = createStreamSendAccounts(c.root, sendAccountCount, streamSendQueueBytes, c.runtimeBytes, refs[sendAccountIndex]);
1197
- }
1198
- if (nativePositionCount > 0)
1199
- nativePositions = state.admission?.takeNativePositions(nativePositionCount, nativeOpeningCount) ?? new NativeProtocolPositions(c.root, nativePositionCount, nativeOpeningCount, c.runtimeBytes, refs[nativePositionIndex], refs.slice(nativePositionIndex + 1, nativeOpeningIndex), refs.slice(nativeOpeningIndex, nativeOpeningIndex + nativeOpeningCount));
1200
- if (bootstrapCosts.length !== 0) {
1201
- bootstrapSendAccount = sendAccounts.checkout();
1202
- const output = refs[bootstrapIndex + 9];
1203
- refs[bootstrapIndex + 9] = output.transfer({ ...streamOwner, kind: "bootstrap_output" }, streamOwner.backing, [...this.#accounts, sendAccount, bootstrapSendAccount]);
1204
- output.release();
1205
- rpcSendAccounts.push(bootstrapSendAccount);
1206
- if (nativePositions !== undefined && noise.role === "client")
1207
- bootstrapNativePosition = rpcNativePositions[0] = nativePositions.checkout(true);
1208
- for (let position = 1; position < 8; position++) {
1209
- const account = sendAccounts.checkout();
1210
- rpcSendAccounts.push(account);
1211
- const index = rpcStreamsIndex + (position - 1) * bootstrapCosts.length + 9, output = refs[index];
1212
- refs[index] = output.transfer({ ...streamOwner, kind: `rpc_open_output_${position}` }, streamOwner.backing, [...this.#accounts, sendAccount, account]);
1213
- output.release();
1214
- if (nativePositions !== undefined && (position < 4) === (noise.role === "client"))
1215
- rpcNativePositions[position] = nativePositions.checkout(true);
1216
- }
1217
- }
1218
- if (managementCosts.length !== 0) {
1219
- managementSendAccount = sendAccounts.checkout();
1220
- const output = refs[managementIndex + 9];
1221
- refs[managementIndex + 9] = output.transfer({ ...streamOwner, kind: "management_open_output" }, streamOwner.backing, [...this.#accounts, sendAccount, managementSendAccount]);
1222
- output.release();
1223
- if (nativePositions !== undefined && noise.role === "client")
1224
- managementNativePosition = nativePositions.checkout(true);
1225
- }
1226
- if (bootstrapCosts.length !== 0) {
1227
- for (let position = 0; position < 2; position++) {
1228
- const account = sendAccounts.checkout();
1229
- notifySendAccounts.push(account);
1230
- const index = notifyIndex + position * bootstrapCosts.length + 9, output = refs[index];
1231
- refs[index] = output.transfer({ ...streamOwner, kind: `notify_open_output_${position}` }, streamOwner.backing, [...this.#accounts, sendAccount, account]);
1232
- output.release();
1233
- }
1234
- if (nativePositions !== undefined)
1235
- notifyNativePosition = nativePositions.checkout();
1236
- }
1237
- ledger = state.admission?.takeLedger(crypto) ?? new CryptoUsageLedger(crypto, refs[12]);
1238
- internalKeys = state.admission?.takeInternalKeys() ?? new SessionKeyPreparation(ledger, spec.info.application_profile, refs[0]);
1239
- peerOpenPreparation = state.admission?.takePeerOpens();
1240
- if (spec.transport.nativeDatagrams !== undefined)
1241
- unreliablePreparation = state.admission?.takeUnreliable() ??
1242
- new UnreliablePreparation(c.root, c.runtimeBytes, refs.slice(datagramIndex, datagramIndex + unreliableCharges(c.runtimeBytes).length), ledger);
1243
- delivery = new ReceiveDeliveryGate(noise.authorizationDeadline, c.runtimeBytes, refs[11]);
1244
- if (rpcConfig !== undefined && rpcPlan !== undefined && applicationProfile !== "transport") {
1245
- for (let position = 0; position < 8; position++) {
1246
- for (const [part, kind] of [[rpcPlan.channel, "channel"], [rpcPlan.publication, "publication"]]) {
1247
- const index = rpcIndex + part + position * rpcPlan.channelWidth, original = refs[index];
1248
- refs[index] = original.transfer({ ...streamOwner, kind: `rpc_${kind}_${position}` }, streamOwner.backing, [...this.#accounts, sendAccount, rpcSendAccounts[position]]);
1249
- original.release();
1250
- }
1251
- }
1252
- if (applicationProfile === "execution") {
1253
- const index = rpcIndex + rpcPlan.management + 6, output = refs[index];
1254
- refs[index] = output.transfer({ ...streamOwner, kind: "management_publication" }, streamOwner.backing, [...this.#accounts, sendAccount, managementSendAccount]);
1255
- output.release();
1256
- }
1257
- for (let position = 0; position < 2; position++) {
1258
- const index = rpcIndex + rpcPlan.notify + position * notifyChannelCharges(c.runtimeBytes).length + 5, output = refs[index];
1259
- refs[index] = output.transfer({ ...streamOwner, kind: `notify_publication_${position}` }, streamOwner.backing, [...this.#accounts, sendAccount, notifySendAccounts[position]]);
1260
- output.release();
1261
- }
1262
- calls = state.admission?.takeCalls(stream.rpcMaxGeneralOutstanding ?? 0);
1263
- applicationServices = state.admission?.takeServices();
1264
- initialStreams = state.admission?.takeStreams();
1265
- rpcAdmission = new RPCApplicationAdmission(rpcConfig, applicationProfile, stream.rpcMaxGeneralOutstanding ?? 0, c.root, this.#accounts, [...this.#accounts, sendAccount], streamOwner, this.clock, noise.authorizationDeadline, delivery, c.runtimeBytes, refs.slice(rpcIndex, rpcIndex + rpcPlan.charges.length), this.contractQueries(rpcConfig.queryAcquisitions), bytes => this.#random.fill(bytes), this.serviceBindings(rpcConfig.queryAcquisitions === 2 ? 16 : 256), config => this.executionService(config), notifySendAccounts.map(account => Object.freeze([...this.#accounts, sendAccount, account])), rpcSendAccounts.map(account => Object.freeze([...this.#accounts, sendAccount, account])), calls, applicationServices, initialStreams, this.diagnostics);
1266
- // The application now owns retirement, including independent results.
1267
- // Later connection failure must use that lifecycle rather than close
1268
- // its transferred groups as unused preparation resources.
1269
- applicationServices = undefined;
1270
- calls = undefined;
1271
- initialStreams = undefined;
1272
- }
1273
- if (state.admission !== undefined)
1274
- initialRawStreams = state.admission.takeInitialRawStreams(spec.initialRawStreams);
1275
- else if (spec.initialRawStreams !== undefined && spec.initialRawStreams.length > 0) {
1276
- const charges = streamOpenCharges(spec.maxFrame, c.runtimeBytes, stream.receive, spec.maxFrame);
1277
- initialRawStreams = new RawStreamPreparation(c.root, this.#accounts, streamOwner, c.runtimeBytes, spec.initialRawStreams, charges, sendAccounts, ledger);
1278
- if (peerOpenPreparation !== undefined)
1279
- fail("configuration_capacity");
1280
- peerOpenPreparation = new PeerOpenPreparation(c.root, this.#accounts, streamOwner, ledger, spec.initialRawStreams.reduce((count, declaration) => count + declaration.options.maxActive, 0), charges.slice(0, 2));
1281
- }
1282
- ephemeral = randomDH(profile.dh_algorithm === 0, bytes => this.#random.fill(bytes));
1283
- let config = { ...spec, ...(c.cleanupMS === undefined ? {} : { cleanupMS: c.cleanupMS }), diagnostics: this.diagnostics, diagnosticActivity: state.diagnostic, unreliablePreparation, preparedRawStreams: initialRawStreams, runtimeBytes: c.runtimeBytes, ledger,
1284
- noise: { ...noise, clock: this.clock, ephemeralPrivate: ephemeral },
1285
- reservations: { session: refs[0], epoch: refs[1], ingress: refs[2], envelope: refs[3], output: refs[4],
1286
- ...(spec.transport.nativeStreams === undefined ? {} : { nativeIngress: refs[13], nativeRecord: refs[14], nativeEnvelope: refs[15], nativeReceive: refs[16], nativeReceiveDecoder: refs[17], nativeCandidates: refs[18], nativeSendCrypto: refs[19], nativeSendEncode: refs[20] }) },
1287
- streams: { ...stream, maintenancePositions, internalKeys, ...(peerOpenPreparation === undefined ? {} : { peerOpenPreparation }), ...(nativePositions === undefined ? {} : { nativePositions }),
1288
- ...(rpcAdmission === undefined ? {} : { rpcAdmission,
1289
- rpcReservations: Array.from({ length: 7 }, (_, position) => refs.slice(rpcStreamsIndex + position * bootstrapCosts.length, rpcStreamsIndex + (position + 1) * bootstrapCosts.length)),
1290
- rpcSendAccounts, rpcNativePositions,
1291
- notifyReservations: [refs.slice(notifyIndex, notifyIndex + bootstrapCosts.length), refs.slice(notifyIndex + bootstrapCosts.length, notifyIndex + 2 * bootstrapCosts.length)],
1292
- notifySendAccounts, ...(notifyNativePosition === undefined ? {} : { notifyNativePosition }) }),
1293
- ...(managementCosts.length === 0 ? {} : { managementReservations: refs.slice(managementIndex, managementIndex + managementCosts.length), managementSendAccount: managementSendAccount,
1294
- ...(managementNativePosition === undefined ? {} : { managementNativePosition }) }),
1295
- ...(bootstrapCosts.length === 0 ? {} : { bootstrapReservations: refs.slice(bootstrapIndex, bootstrapIndex + bootstrapCosts.length), bootstrapSendAccount: bootstrapSendAccount,
1296
- ...(bootstrapNativePosition === undefined ? {} : { bootstrapNativePosition }) }),
1297
- sendQueueBytes, streamSendQueueBytes, sendAccount, sendAccounts, root: c.root, accounts: this.#accounts, owner: streamOwner, random: bytes => this.#random.fill(bytes),
1298
- delivery, authorization: { check: () => noise.authorizationDeadline.check() },
1299
- open: refs[5], openDecoder: refs[6], control: refs[7], controlDecoder: refs[8], controlSendCipher: refs[9], controlReceiveCipher: refs[10] } };
1300
- if (store !== undefined) {
1301
- state.diagnostic?.phase("spend");
1302
- if (noise.role !== "client")
1303
- fail("credential_binding");
1304
- if (exchange === undefined)
1305
- state.closure.checkSessionInputs(config, context);
1306
- const facts = state.closure.poolSpendFacts(refs[0]), connect = new Uint8Array(16), carrier = new Uint8Array(16), originalTransport = spec.transport;
1307
- let publication;
1308
- let dispatch;
1309
- try {
1310
- this.#random.fill(connect);
1311
- this.#random.fill(carrier);
1312
- const guard = () => { this.#check(); if (signal.aborted || spec.transport !== originalTransport)
1313
- fail("closed"); state.closure.checkPreparation(refs[0]); if (exchange !== undefined)
1314
- originalTransport.checkPreparation(); checkRequestedPreparation(); };
1315
- if (state.poolServerAllow !== undefined && spec.poolServerAllow !== undefined)
1316
- fail("configuration_capacity");
1317
- const candidate = state.closure.poolServerAllowCandidate(refs[0]), provider = state.poolServerAllow ?? spec.poolServerAllow;
1318
- if (candidate === undefined && provider !== undefined)
1319
- fail("configuration_capacity");
1320
- if (candidate !== undefined) {
1321
- const recipient = provider?.recipients.find(value => value.candidateIndex === candidate);
1322
- if (recipient === undefined || provider === undefined)
1323
- fail("owner_unavailable");
1324
- publication = state.closure.preparePoolServerAllow(recipient, refs[0]);
1325
- publication.check();
1326
- dispatch = provider.prepare(publication.request, publication.grant);
1327
- if (dispatch === null || typeof dispatch !== "object" || typeof dispatch.publish !== "function" || typeof dispatch.close !== "function")
1328
- fail("owner_unavailable");
1329
- guard();
1330
- publication.check();
1331
- }
1332
- await store.consume(facts, { connect, carrier, generation: 1n, signal,
1333
- spendDispatched: () => state.connectionFacts?.spendDispatched(), spent: () => state.connectionFacts?.spent(),
1334
- unspent: () => state.connectionFacts?.unspent() }, noise.preparationDeadline, refs[0], guard);
1335
- guard();
1336
- if (publication !== undefined) {
1337
- // Only this explicit success continuation may publish. No stored
1338
- // spend fact, replay or later retry can enter this invocation.
1339
- const original = publication, window = new TrustedWindow(this.clock, 2000n), check = () => { guard(); original.check(); window.check(); };
1340
- check();
1341
- await dispatch.publish(Object.freeze({ signal, check, remainingMS: () => { check(); const remaining = original.remainingMS(), windowRemaining = window.remainingMS(); return remaining < windowRemaining ? remaining : windowRemaining; } }));
1342
- check();
1343
- }
1344
- }
1345
- finally {
1346
- try {
1347
- dispatch?.close();
1348
- }
1349
- finally {
1350
- publication?.close();
1351
- facts.close();
1352
- connect.fill(0);
1353
- carrier.fill(0);
1354
- }
1355
- }
1356
- }
1357
- if (live !== undefined) {
1358
- state.diagnostic?.phase("activate");
1359
- if (store !== undefined || exchange === undefined || noise.role !== "client")
1360
- fail("credential_binding");
1361
- const originalTransport = spec.transport;
1362
- const guard = () => {
1363
- this.#check();
1364
- if (signal.aborted || spec.transport !== originalTransport)
1365
- fail("closed");
1366
- state.closure.checkPreparation(refs[0]);
1367
- originalTransport.checkPreparation();
1368
- checkRequestedPreparation();
1369
- };
1370
- await live.authorize(state.closure, exchange, refs[0], guard, signal, state.connectionFacts);
1371
- // Only the original exchange's verified installation completes custody.
1372
- state.originalCustody?.handoff();
1373
- state.originalCustody = undefined;
1374
- guard();
1375
- }
1376
- if (exchange !== undefined) {
1377
- if (store === undefined && live === undefined)
1378
- fail("owner_unavailable");
1379
- const admission = await exchange.run(spec.transport, { ...options, signal });
1380
- context = admission.context;
1381
- config = { ...config, noise: { ...config.noise, contextDigest: admission.contextDigest, fsb: admission.fsb, fsa: admission.fsa },
1382
- ready: admission.ready, info: { ...config.info, selected_features: admission.selected, guarantees: { ...config.info.guarantees, datagram: (admission.selected & 1n) !== 0n && spec.transport.nativeDatagrams !== undefined } } };
1383
- }
1384
- if (server !== undefined) {
1385
- if (store !== undefined || live !== undefined || exchange !== undefined || noise.role !== "server")
1386
- fail("owner_unavailable");
1387
- const admitted = await server.exchange.run(state.closure, server.fields, server.authority, { ...server.owner, signal }, refs[serverWorkIndex], { ...options, signal });
1388
- context = admitted.context;
1389
- config = { ...config, noise: { ...config.noise, contextDigest: admitted.contextDigest, fsb: admitted.fsb, fsa: admitted.fsa },
1390
- ready: admitted.ready, info: { ...config.info, selected_features: admitted.selected, guarantees: { ...config.info.guarantees, datagram: (admitted.selected & 1n) !== 0n && spec.transport.nativeDatagrams !== undefined } } };
1391
- }
1392
- if (state.requirements !== undefined)
1393
- requireConnectionGuarantees(state.requirements, config.info);
1394
- state.diagnostic?.phase("handshake");
1395
- runtime = await establishV4CredentialSession({ ...config, observeNetworkReady: () => state.connectionFacts?.ready(), ...(state.prepareInbound === undefined ? {} : { prepareInbound: state.prepareInbound }) }, state.closure, context, { ...options, signal });
1396
- state.connectionFacts?.ready();
1397
- state.diagnostic?.event({ state: "ready", code: "ok" });
1398
- if (state.connectionFacts !== undefined)
1399
- rememberConnectionFacts(runtime, state.connectionFacts.snapshot());
1400
- unreliablePreparation = undefined;
1401
- if (this.#closed || signal.aborted) {
1402
- delivery.close();
1403
- await runtime.close();
1404
- fail("closed");
1405
- }
1406
- const entry = { runtime, cleanup: runtime.cleanupOwner, delivery, material, monitor: Promise.resolve() };
1407
- this.#sessions.add(entry);
1408
- this.#observeSession(entry);
1409
- return runtime;
1410
- }
1411
- catch (error) {
1412
- state.originalCustody?.withdraw();
1413
- for (const account of rpcSendAccounts)
1414
- account.close();
1415
- for (const position of rpcNativePositions)
1416
- for (const ref of position?.references ?? [])
1417
- ref.release();
1418
- for (const account of notifySendAccounts)
1419
- account.close();
1420
- for (const ref of notifyNativePosition?.references ?? [])
1421
- ref.release();
1422
- rpcAdmission?.close();
1423
- calls?.close();
1424
- managementSendAccount?.close();
1425
- for (const ref of managementNativePosition?.references ?? [])
1426
- ref.release();
1427
- delivery?.close();
1428
- if (applicationServices !== undefined)
1429
- closeRPCApplicationServices(applicationServices);
1430
- unreliablePreparation?.close();
1431
- initialStreams?.close();
1432
- initialRawStreams?.close();
1433
- peerOpenPreparation?.close();
1434
- internalKeys?.close();
1435
- if (runtime === undefined)
1436
- await Promise.allSettled([spec.transport.close(), spec.transport.waitTermination()]);
1437
- else
1438
- await runtime.close().catch(() => undefined);
1439
- for (const reference of bootstrapNativePosition?.references ?? [])
1440
- reference.release();
1441
- bootstrapSendAccount?.close();
1442
- maintenancePositions?.close();
1443
- nativePositions?.close();
1444
- sendAccounts?.close();
1445
- sendAccount?.close();
1446
- ledger?.close();
1447
- this.releaseMaterial(token, material);
1448
- throw error;
1449
- }
1450
- finally {
1451
- initialRawStreams?.close();
1452
- ephemeral.fill(0);
1453
- for (const ref of refs)
1454
- ref.release();
1455
- // A failure before Session ownership returns the initial epoch references
1456
- // here, after closing the pool. Collect its now-empty metadata as well.
1457
- maintenancePositions?.cleanupComplete();
1458
- this.#admissions.delete(abort);
1459
- this.#cleanup();
1460
- }
1461
- }
1462
- installClientConnector(connector) {
1463
- this.#check();
1464
- const profile = connector.applicationProfile;
1465
- if (this.#connector !== undefined || !["transport", "services", "execution"].includes(profile))
1466
- fail("configuration_capacity");
1467
- this.#connector = Object.freeze({ applicationProfile: profile, connect: connector.connect.bind(connector),
1468
- checkRequirements: connector.checkRequirements.bind(connector),
1469
- ...(connector.withdrawUnboundAcquisition === undefined ? {} : { withdrawUnboundAcquisition: connector.withdrawUnboundAcquisition.bind(connector) }),
1470
- ...(connector.acquireMaterial === undefined ? {} : { acquireMaterial: connector.acquireMaterial.bind(connector) }),
1471
- ...(connector.reserveAdmission === undefined ? {} : { reserveAdmission: connector.reserveAdmission.bind(connector) }) });
1472
- }
1473
- assertConnectAvailable() { this.#check(); if (this.#connector === undefined)
1474
- fail("runtime_unavailable"); }
1475
- async connect(source, request, options, prepareDependencies) {
1476
- const diagnostic = new DiagnosticActivity(this.diagnostics, "material", true);
1477
- try {
1478
- return await this.#prepareConnect(source, request, diagnostic, options, prepareDependencies).start();
1479
- }
1480
- catch (error) {
1481
- diagnostic.failure(error, true);
1482
- throw error;
1483
- }
1484
- }
1485
- /** Reserve the actual connection before starting source or network work.
1486
- * Multiple factory groups may prepare first, then transfer each reservation. */
1487
- prepareConnect(source, request, options, prepareDependencies, factsChanged, prepareInbound) {
1488
- return this.#prepareConnect(source, request, undefined, options, prepareDependencies, factsChanged, prepareInbound);
1489
- }
1490
- #prepareConnect(source, request, diagnostic, options, prepareDependencies, factsChanged, prepareInbound) {
1491
- this.assertConnectAvailable();
1492
- const original = publicSources.get(source), state = original === undefined ? undefined : sources.get(original);
1493
- if (original === undefined || state?.environment !== this || state.closed || !this.#sources.has(original))
1494
- fail("source_unavailable");
1495
- const requirements = captureConnectionRequirements(request), applicationProfile = this.#connector.applicationProfile;
1496
- if (requirements.application_profile !== undefined && requirements.application_profile !== applicationProfile)
1497
- fail("connection_requirement_unavailable");
1498
- // The local assembly plan supplies the source's precise profile before
1499
- // acquisition; omission never silently chooses a lower application tier.
1500
- const captured = Object.freeze({ ...requirements, application_profile: applicationProfile });
1501
- this.#connector.checkRequirements(captured);
1502
- this.#check();
1503
- if (this.#sessions.size + this.#admissions.size + this.#preparations.size + this.#connectionClaims.size >= this.#config.sessions)
1504
- this.#resourceUnavailable();
1505
- const claim = new AbortController();
1506
- this.#connectionClaims.add(claim);
1507
- const attempt = new ConnectionAttemptCleanup();
1508
- attempt.retain();
1509
- const signal = options?.signal === undefined ? claim.signal : AbortSignal.any([claim.signal, options.signal]);
1510
- const facts = new ConnectionFacts(factsChanged);
1511
- facts.source(state.source);
1512
- let admission, started = false, closed = false, cleaned = false;
1513
- const cleanup = () => {
1514
- if (cleaned)
1515
- return;
1516
- cleaned = true;
1517
- signal.removeEventListener("abort", cancelled);
1518
- admission?.close();
1519
- admission = undefined;
1520
- this.#connectionClaims.delete(claim);
1521
- attempt.release();
1522
- this.#cleanup();
1523
- };
1524
- const close = () => { diagnostic?.finishPublication(); if (closed)
1525
- return; closed = true; claim.abort(); if (!started) {
1526
- diagnostic?.close();
1527
- cleanup();
1528
- } };
1529
- const cancelled = () => { if (!started)
1530
- close(); };
1531
- try {
1532
- admission = this.#connector.reserveAdmission?.();
1533
- prepareDependencies?.(admission);
1534
- this.#check();
1535
- if (signal.aborted)
1536
- fail("canceled");
1537
- signal.addEventListener("abort", cancelled, { once: true });
1538
- const start = async (ordinal = 1n, awaitPublication = false) => {
1539
- if (started || closed)
1540
- fail("closed");
1541
- started = true;
1542
- diagnostic ??= new DiagnosticActivity(this.diagnostics, "material", true, ordinal);
1543
- if (awaitPublication)
1544
- diagnostic.holdPublication();
1545
- let material;
1546
- try {
1547
- this.#check();
1548
- if (signal.aborted)
1549
- fail("canceled");
1550
- material = await this.acquire(original, captured, { signal }, attempt);
1551
- materials.get(material).connectionFacts = facts;
1552
- materials.get(material).diagnostic = diagnostic;
1553
- this.#check();
1554
- if (signal.aborted)
1555
- fail("canceled");
1556
- materials.get(material).connectionClaim = claim;
1557
- if (prepareInbound !== undefined)
1558
- materials.get(material).prepareInbound = prepareInbound;
1559
- if (admission !== undefined)
1560
- materials.get(material).admission = admission;
1561
- return await this.connectMaterial(material, { signal });
1562
- }
1563
- catch (error) {
1564
- diagnostic.failure(error, true);
1565
- facts.failed();
1566
- await material?.closeMaterial();
1567
- cleanup();
1568
- throw retainNativeConnectionFailure(new ConnectionError(controllerFailureCode(error), facts.snapshot(), attempt.status()), error);
1569
- }
1570
- finally {
1571
- if (material !== undefined) {
1572
- delete materials.get(material).admission;
1573
- delete materials.get(material).prepareInbound;
1574
- }
1575
- closed = true;
1576
- cleanup();
1577
- }
1578
- };
1579
- return Object.freeze({ close, facts: () => facts.snapshot(), failed: (error) => { diagnostic?.failure(error, true); }, start: (ordinal, awaitPublication) => start(ordinal, awaitPublication).catch(error => {
1580
- if (error instanceof ConnectionError)
1581
- throw error;
1582
- throw retainNativeConnectionFailure(new ConnectionError(controllerFailureCode(error), facts.snapshot(), attempt.status()), error);
1583
- }) });
1584
- }
1585
- catch (error) {
1586
- diagnostic?.failure(error, true);
1587
- close();
1588
- throw error;
1589
- }
1590
- }
1591
- async connectMaterial(material, options) {
1592
- const state = material instanceof V4EnvironmentMaterial ? materials.get(material) : undefined;
1593
- const diagnostic = (state?.environment === this ? state.diagnostic : undefined) ?? new DiagnosticActivity(this.diagnostics, "prepare", true);
1594
- if (state?.environment === this)
1595
- state.diagnostic = diagnostic;
1596
- try {
1597
- return await this.#connectMaterialOriginal(material, options);
1598
- }
1599
- catch (error) {
1600
- diagnostic.failure(error, true);
1601
- throw error;
1602
- }
1603
- }
1604
- async #connectMaterialOriginal(material, options) {
1605
- this.assertConnectAvailable();
1606
- if (!(material instanceof V4EnvironmentMaterial))
1607
- fail("material_unavailable");
1608
- const state = materials.get(material);
1609
- if (state.environment !== this || state.claimed || !this.#materials.has(material))
1610
- fail("material_unavailable");
1611
- state.connectionFacts ??= new ConnectionFacts();
1612
- const diagnostic = state.diagnostic ??= new DiagnosticActivity(this.diagnostics, "prepare", true);
1613
- diagnostic.phase("prepare");
1614
- let admission;
1615
- try {
1616
- admission = state.admission === undefined ? this.#connector.reserveAdmission?.() : undefined;
1617
- if (admission !== undefined)
1618
- state.admission = admission;
1619
- return await this.#connector.connect(material, options);
1620
- }
1621
- catch (error) {
1622
- // The public handle transferred this material before entering admission.
1623
- // A local capacity failure must retire its verified closure immediately;
1624
- // the caller can no longer close or consume that original handle.
1625
- diagnostic.failure(error, true);
1626
- state.connectionFacts.failed();
1627
- await material.closeMaterial();
1628
- throw retainNativeConnectionFailure(new ConnectionError(controllerFailureCode(error), state.connectionFacts.snapshot(), complete), error);
1629
- }
1630
- finally {
1631
- if (admission !== undefined) {
1632
- admission.close();
1633
- delete state.admission;
1634
- }
1635
- }
1636
- }
1637
- close() {
1638
- if (this.#closed)
1639
- return this.#close;
1640
- this.#closeInitializing = true;
1641
- this.#closed = true;
1642
- try {
1643
- this.#cleanupWindow = new TrustedWindow(this.clock, BigInt(this.#config.cleanupMS));
1644
- }
1645
- catch {
1646
- this.#cleanupIncomplete = true;
1647
- }
1648
- const tick = () => {
1649
- this.#cleanupTimer = undefined;
1650
- if (this.#reference === undefined)
1651
- return;
1652
- try {
1653
- this.#cleanupWindow.check();
1654
- this.#cleanupTimer = setTimeout(tick, timerChunk(this.#cleanupWindow.remainingMS()));
1655
- }
1656
- catch {
1657
- this.#recordCleanupTimeout();
1658
- this.#notifyCleanup();
1659
- }
1660
- };
1661
- if (this.#cleanupWindow !== undefined)
1662
- tick();
1663
- void this.#diagnostics?.close();
1664
- this.#contractQueries?.close();
1665
- this.#serviceBindings?.close();
1666
- for (const history of this.#executionServices.values())
1667
- history.close();
1668
- for (const job of this.#acquisitions)
1669
- job.abort.abort();
1670
- for (const abort of this.#admissions)
1671
- abort.abort();
1672
- for (const abort of this.#preparations)
1673
- abort.abort();
1674
- for (const claim of this.#connectionClaims)
1675
- claim.abort();
1676
- for (const source of [...this.#sources])
1677
- source.close();
1678
- for (const admission of [...this.#dependencyClaims])
1679
- admission.close();
1680
- for (const dependency of [...this.#dependencies])
1681
- try {
1682
- dependency.close();
1683
- }
1684
- catch {
1685
- this.#cleanupFault = this.#cleanupIncomplete = true;
1686
- }
1687
- for (const material of [...this.#materials])
1688
- if (!materials.get(material).claimed)
1689
- this.releaseMaterial(token, material);
1690
- for (const entry of this.#sessions) {
1691
- entry.delivery.close();
1692
- void entry.runtime?.close().catch(() => undefined);
1693
- }
1694
- for (const entry of this.#results)
1695
- entry.delivery.close();
1696
- for (const entry of this.#namespaces.values())
1697
- entry.namespace.close();
1698
- // Keep clock/random/accounts alive until every original callback and
1699
- // Session reference has returned; shared root/tenant are borrowed.
1700
- this.#closeInitializing = false;
1701
- this.#cleanup();
1702
- return this.#close;
1703
- }
1704
- #cleanup() {
1705
- if (this.#cleaning || this.#closeInitializing)
1706
- return;
1707
- this.#cleaning = true;
1708
- try {
1709
- this.#collect();
1710
- }
1711
- finally {
1712
- this.#cleaning = false;
1713
- }
1714
- this.#notifyCleanup();
1715
- }
1716
- #observeSession(entry) {
1717
- entry.delivery.onCleanup(() => this.#cleanup());
1718
- entry.cleanup.onCleanup(() => this.#cleanup());
1719
- entry.monitor = entry.runtime.waitTermination().catch(() => undefined).then(async () => {
1720
- await (entry.runtime?.close() ?? entry.cleanup.closed).catch(() => undefined);
1721
- entry.delivery.retire();
1722
- this.#cleanup();
1723
- });
1724
- entry.cleanup.onCoreCleanup(() => {
1725
- // Preserve callback accounting and result authorization without making
1726
- // the Environment's root observer retain the old Session/key graph.
1727
- entry.runtime = undefined;
1728
- entry.delivery.retire();
1729
- this.#cleanup();
1730
- });
1731
- }
1732
- #notifyCleanup() {
1733
- if (this.#closeInitializing)
1734
- return;
1735
- const status = this.#cleanupProjection();
1736
- if (this.#closed && status.status !== "pending") {
1737
- const resolve = this.#closeResolve;
1738
- this.#closeResolve = undefined;
1739
- resolve?.(this.#lifecycleProjection(status));
1740
- }
1741
- for (const wake of this.#cleanupObservers)
1742
- wake();
1743
- if (status.status === "complete") {
1744
- const cleaned = this.#cleaned;
1745
- this.#cleaned = undefined;
1746
- cleaned?.();
1747
- }
1748
- }
1749
- onCleanup(callback) {
1750
- if (this.#cleaned !== undefined)
1751
- fail("configuration_capacity");
1752
- if (this.#reference === undefined)
1753
- callback();
1754
- else
1755
- this.#cleaned = callback;
1756
- }
1757
- #collect() {
1758
- for (const entry of this.#sessions)
1759
- if ((entry.runtime?.cleanupStatus() ?? entry.cleanup.cleanupStatus()).status === "complete") {
1760
- this.#sessions.delete(entry);
1761
- if (entry.delivery.cleanupStatus().status === "complete")
1762
- this.releaseMaterial(token, entry.material);
1763
- else
1764
- this.#results.add({ delivery: entry.delivery, material: entry.material });
1765
- }
1766
- for (const entry of this.#results)
1767
- if (entry.delivery.cleanupStatus().status === "complete") {
1768
- this.#results.delete(entry);
1769
- this.releaseMaterial(token, entry.material);
1770
- }
1771
- if (!this.#closed || this.#reference === undefined)
1772
- return;
1773
- if (this.#contractQueries?.cleanupComplete())
1774
- this.#contractQueries = undefined;
1775
- if (this.#serviceBindings?.cleanupComplete()) {
1776
- this.#serviceBindings = undefined;
1777
- this.#serviceAccount?.close();
1778
- this.#serviceAccount = undefined;
1779
- }
1780
- for (const [key, history] of this.#executionServices)
1781
- if (history.cleanupComplete())
1782
- this.#executionServices.delete(key);
1783
- const pending = Number(this.#diagnostics !== undefined && this.#diagnostics.cleanupStatus().status !== "complete") + this.#dependencyClaims.size + this.#connectionClaims.size + this.#executionServices.size + (this.#contractQueries === undefined ? 0 : 1) + (this.#serviceBindings === undefined ? 0 : 1) + this.#dependencies.size + this.#working + this.#acquisitions.size + this.#admissions.size + this.#preparations.size + this.#sessions.size + this.#results.size + this.#materials.size + this.#sources.size;
1784
- if (pending === 0 && [...this.#namespaces.values()].every(entry => entry.namespace.cleanupComplete())) {
1785
- this.clock.close();
1786
- this.#random.close();
1787
- if (this.clock.cleanupComplete() && this.#random.cleanupComplete()) {
1788
- for (const entry of this.#namespaces.values()) {
1789
- entry.options.rootKeyID.fill(0);
1790
- entry.options.rootPublicKey.fill(0);
1791
- }
1792
- this.#namespaces.clear();
1793
- this.#connector = undefined;
1794
- this.#resourceObserver?.();
1795
- this.#resourceObserver = undefined;
1796
- this.#reference.release();
1797
- this.#reference = undefined;
1798
- this.#environment.close();
1799
- if (this.#cleanupTimer !== undefined)
1800
- clearTimeout(this.#cleanupTimer);
1801
- this.#cleanupTimer = undefined;
1802
- this.#cleanupWindow = undefined;
1803
- return;
1804
- }
1805
- }
1806
- }
1807
- #recordCleanupTimeout() {
1808
- if (!this.#cleanupIncomplete)
1809
- this.diagnosticCounters.observe("cleanup_timeout", { phase: "cleanup", code: "cleanup_incomplete" });
1810
- this.#cleanupIncomplete = true;
1811
- }
1812
- #lifecycleProjection(status) {
1813
- return lifecycleResult("environment", this.#closed ? "closed" : "active", status, this.#cleanupFault ? "core_cleanup_failed" : status.status === "cleanup_incomplete" ? "deadline_exceeded" : "none");
1814
- }
1815
- lifecycleResult() { return this.#lifecycleProjection(this.cleanupStatus()); }
1816
- #cleanupProjection() {
1817
- if (this.#reference === undefined)
1818
- return complete;
1819
- return cleanupResult({ status: this.#cleanupIncomplete ? "cleanup_incomplete" : "pending", core_cleanup: "pending",
1820
- pending_callbacks: (this.#diagnostics?.cleanupStatus().pending_callbacks ?? 0n) + BigInt(this.#connectionClaims.size + (this.#contractQueries?.pending ?? 0) + this.#acquisitions.size + this.#admissions.size + this.#preparations.size + this.#sessions.size + this.#dependencies.size + this.#working) });
1821
- }
1822
- cleanupStatus() {
1823
- this.#cleanup();
1824
- if (this.#cleanupWindow !== undefined)
1825
- try {
1826
- this.#cleanupWindow.check();
1827
- }
1828
- catch {
1829
- if (!this.#cleanupIncomplete) {
1830
- this.#recordCleanupTimeout();
1831
- this.#notifyCleanup();
1832
- }
1833
- }
1834
- return this.#cleanupProjection();
1835
- }
1836
- waitCleanup(options) {
1837
- if (options?.signal?.aborted)
1838
- return Promise.reject(new Error("canceled"));
1839
- const initial = this.cleanupStatus();
1840
- if (initial.status !== "pending")
1841
- return Promise.resolve(initial);
1842
- if (this.#waiters >= 32)
1843
- return Promise.reject(new Error("resource_exhausted"));
1844
- const retained = this.#reference.borrow();
1845
- this.#waiters++;
1846
- return new Promise((resolve, reject) => {
1847
- let timer, window, finished = false;
1848
- const finish = (canceled = false, expired = false) => {
1849
- if (finished)
1850
- return;
1851
- finished = true;
1852
- this.#cleanupObservers.delete(wake);
1853
- if (timer !== undefined)
1854
- clearTimeout(timer);
1855
- options?.signal?.removeEventListener("abort", abort);
1856
- this.#waiters--;
1857
- retained.release();
1858
- if (canceled)
1859
- reject(new Error("canceled"));
1860
- else {
1861
- const status = this.#cleanupProjection();
1862
- resolve(expired && status.status === "pending" ? cleanupResult({ ...status, status: "cleanup_incomplete" }) : status);
1863
- }
1864
- };
1865
- const abort = () => finish(true), wake = () => { if (this.#cleanupProjection().status !== "pending")
1866
- finish(); };
1867
- const tick = () => {
1868
- try {
1869
- window.check();
1870
- timer = setTimeout(tick, timerChunk(window.remainingMS()));
1871
- }
1872
- catch {
1873
- finish(false, true);
1874
- }
1875
- };
1876
- this.#cleanupObservers.add(wake);
1877
- options?.signal?.addEventListener("abort", abort, { once: true });
1878
- try {
1879
- window = new TrustedWindow(this.clock, BigInt(this.#config.cleanupMS));
1880
- if (options?.signal?.aborted)
1881
- abort();
1882
- else {
1883
- wake();
1884
- if (!finished)
1885
- tick();
1886
- }
1887
- }
1888
- catch {
1889
- finish(false, true);
1890
- }
1891
- });
1892
- }
1893
- toJSON() { return {}; }
1894
- }
1895
- /** Creates shared-resource lifecycle ownership. Connect requires installation
1896
- * of a production provider/once adapter before calling a credential source. */
1897
- export function createV4TransportEnvironment(config) {
1898
- return wrapTransportEnvironment(new V4EnvironmentRuntime(config));
1899
- }
1900
- /** One public facade per original Environment lifecycle. */
1901
- export function wrapTransportEnvironment(owner) {
1902
- const existing = environmentFacades.get(owner);
1903
- if (existing !== undefined)
1904
- return existing;
1905
- const environment = new V4TransportEnvironment(owner);
1906
- publicEnvironments.set(environment, owner);
1907
- environmentFacades.set(owner, environment);
1908
- return environment;
1909
- }
1910
- for (const constructor of [EnvironmentDependency, V4EnvironmentRuntime, V4EnvironmentCredentialSource, V4EnvironmentMaterial]) {
1911
- Object.freeze(constructor.prototype);
1912
- Object.freeze(constructor);
1913
- }