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