@getstrata/core 2.2.59 → 3.0.3

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 (330) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/core/audit/exportAuditLogs.d.ts +12 -3
  3. package/dist/core/audit/exportStore.d.ts +6 -2
  4. package/dist/core/audit/siemFormatter.d.ts +2 -2
  5. package/dist/core/auth/abilityCatalog.d.ts +1 -9
  6. package/dist/core/auth/authContext.d.ts +2 -0
  7. package/dist/core/auth/authOutcome.d.ts +32 -0
  8. package/dist/core/auth/authReader.d.ts +22 -0
  9. package/dist/core/auth/basicAuthGuard.d.ts +19 -3
  10. package/dist/core/auth/emailVerification.d.ts +1 -1
  11. package/dist/core/auth/guard.d.ts +27 -6
  12. package/dist/core/auth/intendedUrlCookie.d.ts +13 -7
  13. package/dist/core/auth/jwt.d.ts +5 -4
  14. package/dist/core/auth/jwtGuard.d.ts +7 -6
  15. package/dist/core/auth/membershipContext.d.ts +10 -7
  16. package/dist/core/auth/membershipContextMiddleware.d.ts +3 -3
  17. package/dist/core/auth/membershipMiddleware.d.ts +1 -2
  18. package/dist/core/auth/membershipServiceImplementation.d.ts +1 -1
  19. package/dist/core/auth/oauth/oidcIdToken.d.ts +25 -16
  20. package/dist/core/auth/oauth/oidcProvider.d.ts +6 -4
  21. package/dist/core/auth/oauth/providers.d.ts +3 -1
  22. package/dist/core/auth/oneTimeToken.d.ts +2 -3
  23. package/dist/core/auth/passwordConfirmCookie.d.ts +15 -6
  24. package/dist/core/auth/passwordLogin.d.ts +5 -5
  25. package/dist/core/auth/pendingMfaCookie.d.ts +2 -2
  26. package/dist/core/auth/policy.d.ts +23 -10
  27. package/dist/core/auth/requireAuthCapability.d.ts +3 -0
  28. package/dist/core/auth/resolveMembershipService.d.ts +3 -2
  29. package/dist/core/auth/saml/samlAssertionReplay.d.ts +4 -4
  30. package/dist/core/auth/saml/samlServiceProvider.d.ts +11 -7
  31. package/dist/core/auth/scimAuthMiddleware.d.ts +10 -3
  32. package/dist/core/auth/sessionCookie.d.ts +20 -9
  33. package/dist/core/auth/sessionGuard.d.ts +14 -3
  34. package/dist/core/cache/createCacheStore.d.ts +6 -3
  35. package/dist/core/cache/redisCacheStore.d.ts +5 -1
  36. package/dist/core/cache/repository.d.ts +5 -1
  37. package/dist/core/cache/simpleCache.d.ts +2 -1
  38. package/dist/core/cache/tokens.d.ts +8 -0
  39. package/dist/core/config/applicationConfig.d.ts +21 -0
  40. package/dist/core/config/configSnapshot.d.ts +3 -0
  41. package/dist/core/config/envSchema.d.ts +3 -2
  42. package/dist/core/contracts/application.d.ts +153 -0
  43. package/dist/core/contracts/authUserDirectory.d.ts +24 -7
  44. package/dist/core/contracts/container.d.ts +20 -23
  45. package/dist/core/contracts/di.d.ts +4 -2
  46. package/dist/core/contracts/executionContext.d.ts +5 -0
  47. package/dist/core/contracts/executionOperations.d.ts +10 -0
  48. package/dist/core/contracts/executionOwnership.d.ts +38 -0
  49. package/dist/core/contracts/persistence.d.ts +20 -0
  50. package/dist/core/contracts/serviceTokens.d.ts +32 -18
  51. package/dist/core/contracts/services.d.ts +63 -0
  52. package/dist/core/contracts/token.d.ts +19 -0
  53. package/dist/core/crypto/fieldEncryption.d.ts +19 -7
  54. package/dist/core/crypto/fieldEncryptionRotation.d.ts +21 -5
  55. package/dist/core/crypto/mfaSecret.d.ts +10 -3
  56. package/dist/core/database/baseRepository.d.ts +14 -10
  57. package/dist/core/database/bindings.d.ts +6 -0
  58. package/dist/core/database/bunSql.d.ts +3 -12
  59. package/dist/core/database/definitions.d.ts +209 -0
  60. package/dist/core/database/dialect.d.ts +5 -24
  61. package/dist/core/database/driverPorts.d.ts +116 -0
  62. package/dist/core/database/errors.d.ts +47 -7
  63. package/dist/core/database/factory.d.ts +51 -31
  64. package/dist/core/database/index.d.ts +9 -10
  65. package/dist/core/database/keyset.d.ts +2 -1
  66. package/dist/core/database/legacyNativeTransaction.d.ts +5 -0
  67. package/dist/core/database/manager.d.ts +12 -0
  68. package/dist/core/database/model.d.ts +91 -97
  69. package/dist/core/database/modelQuery.d.ts +9 -5
  70. package/dist/core/database/modelRegistry.d.ts +52 -33
  71. package/dist/core/database/mysqlConnection.d.ts +1 -19
  72. package/dist/core/database/mysqlNative.d.ts +38 -0
  73. package/dist/core/database/nativeTransactions.d.ts +16 -0
  74. package/dist/core/database/ormInternal.d.ts +85 -0
  75. package/dist/core/database/ormRuntime.d.ts +4 -0
  76. package/dist/core/database/ownedReadOnlyObservation.d.ts +16 -0
  77. package/dist/core/database/postgresNative.d.ts +11 -0
  78. package/dist/core/database/query.d.ts +24 -23
  79. package/dist/core/database/queryPlanSnapshot.d.ts +7 -0
  80. package/dist/core/database/rawMysql.d.ts +7 -0
  81. package/dist/core/database/rawPostgres.d.ts +23 -0
  82. package/dist/core/database/rawSqlite.d.ts +6 -0
  83. package/dist/core/database/relationQueries.d.ts +3 -2
  84. package/dist/core/database/relationQuery.d.ts +24 -6
  85. package/dist/core/database/repositoryQuery.d.ts +6 -1
  86. package/dist/core/database/schema/driver.d.ts +1 -1
  87. package/dist/core/database/seeders/types.d.ts +1 -1
  88. package/dist/core/database/session.d.ts +13 -0
  89. package/dist/core/database/sessionFactory.d.ts +9 -0
  90. package/dist/core/database/sqlDialects.d.ts +22 -0
  91. package/dist/core/database/tokens.d.ts +7 -0
  92. package/dist/core/database/transactionSession.d.ts +43 -0
  93. package/dist/core/errors/http.d.ts +4 -1
  94. package/dist/core/events/{eventBus.d.ts → eventBusClass.d.ts} +1 -3
  95. package/dist/core/events/index.d.ts +2 -3
  96. package/dist/core/events/outbox/index.d.ts +44 -13
  97. package/dist/core/events/outbox/metrics.d.ts +4 -4
  98. package/dist/core/events/outbox/workerTransport.d.ts +17 -0
  99. package/dist/core/http/authMiddleware.d.ts +2 -2
  100. package/dist/core/http/authorizeMiddleware.d.ts +2 -2
  101. package/dist/core/http/bodySizeLimitMiddleware.d.ts +1 -1
  102. package/dist/core/http/conditionalResponse.d.ts +7 -2
  103. package/dist/core/http/contentSecurityPolicy.d.ts +4 -3
  104. package/dist/core/http/corsMiddleware.d.ts +2 -1
  105. package/dist/core/http/csrfMiddleware.d.ts +6 -1
  106. package/dist/core/http/csrfToken.d.ts +17 -7
  107. package/dist/core/http/databaseError.d.ts +4 -0
  108. package/dist/core/http/etag.d.ts +5 -2
  109. package/dist/core/http/flashMiddleware.d.ts +1 -1
  110. package/dist/core/http/flashSession.d.ts +13 -7
  111. package/dist/core/http/index.d.ts +1 -1
  112. package/dist/core/http/loginThrottleMiddleware.d.ts +3 -3
  113. package/dist/core/http/memoryThrottleMiddleware.d.ts +2 -2
  114. package/dist/core/http/parseMultipartUpload.d.ts +3 -2
  115. package/dist/core/http/requestMetaContext.d.ts +5 -0
  116. package/dist/core/http/requireAbilityMiddleware.d.ts +1 -1
  117. package/dist/core/http/requireAuthMiddleware.d.ts +2 -2
  118. package/dist/core/http/requirePasswordConfirmMiddleware.d.ts +2 -1
  119. package/dist/core/http/requireVerifiedMiddleware.d.ts +2 -2
  120. package/dist/core/http/requireWebAuthMiddleware.d.ts +2 -2
  121. package/dist/core/http/response.d.ts +4 -3
  122. package/dist/core/http/scimThrottleMiddleware.d.ts +4 -3
  123. package/dist/core/http/securedRouteModelBinding.d.ts +10 -3
  124. package/dist/core/http/securityHeadersMiddleware.d.ts +1 -2
  125. package/dist/core/http/signedUrl.d.ts +8 -6
  126. package/dist/core/http/throttleMiddleware.d.ts +9 -5
  127. package/dist/core/http/uploads.d.ts +9 -3
  128. package/dist/core/http/webErrorResponse.d.ts +8 -2
  129. package/dist/core/jobs/exportAuditLogsJob.d.ts +5 -2
  130. package/dist/core/jobs/invalidateCacheTagsJob.d.ts +5 -4
  131. package/dist/core/lifecycle/gracefulShutdown.d.ts +2 -5
  132. package/dist/core/logging/requestLoggingMiddleware.d.ts +1 -1
  133. package/dist/core/mail/mailer.d.ts +7 -5
  134. package/dist/core/openapi/generator.d.ts +12 -4
  135. package/dist/core/openapi/registeredRoute.d.ts +4 -4
  136. package/dist/core/queue/createAppQueue.d.ts +9 -4
  137. package/dist/core/queue/failedJobMetrics.d.ts +11 -2
  138. package/dist/core/queue/failedJobRepository.d.ts +6 -3
  139. package/dist/core/queue/failedJobService.d.ts +1 -0
  140. package/dist/core/queue/index.d.ts +16 -6
  141. package/dist/core/queue/jobRegistry.d.ts +3 -2
  142. package/dist/core/queue/jobRunner.d.ts +10 -4
  143. package/dist/core/queue/publicQueue.d.ts +18 -9
  144. package/dist/core/queue/queueConfig.d.ts +20 -10
  145. package/dist/core/queue/queueHandoff.d.ts +31 -0
  146. package/dist/core/queue/queueMetrics.d.ts +10 -3
  147. package/dist/core/queue/queueServices.d.ts +28 -0
  148. package/dist/core/queue/queueWorkerTransport.d.ts +28 -0
  149. package/dist/core/queue/redisQueue.d.ts +19 -10
  150. package/dist/core/queue/redisQueueKeys.d.ts +5 -5
  151. package/dist/core/queue/redisStreams.d.ts +17 -10
  152. package/dist/core/queue/resilientQueue.d.ts +10 -4
  153. package/dist/core/queue/types.d.ts +1 -0
  154. package/dist/core/runtime/appKeyPrefix.d.ts +5 -5
  155. package/dist/core/runtime/application.d.ts +7 -0
  156. package/dist/core/runtime/executionContext.d.ts +9 -0
  157. package/dist/core/runtime/executionTasks.d.ts +49 -0
  158. package/dist/core/runtime/resourceJournal.d.ts +67 -0
  159. package/dist/core/runtime/serviceGraph.d.ts +14 -0
  160. package/dist/core/security/oauthState.d.ts +13 -9
  161. package/dist/core/security/publicReads.d.ts +2 -2
  162. package/dist/core/security/safeFetch.d.ts +1 -0
  163. package/dist/core/security/safeUrl.d.ts +3 -0
  164. package/dist/core/security/scimTenantTokens.d.ts +1 -1
  165. package/dist/core/security/tokenExpiry.d.ts +1 -1
  166. package/dist/core/security/webhookSignature.d.ts +1 -1
  167. package/dist/core/storage/storage.d.ts +24 -16
  168. package/dist/core/tenant/databaseTenantContext.d.ts +5 -7
  169. package/dist/core/tenant/resolveTenant.d.ts +2 -2
  170. package/dist/core/tenant/scopedDatabasePolicy.d.ts +8 -0
  171. package/dist/core/tenant/tenantDatabaseScope.d.ts +3 -7
  172. package/dist/core/tenant/tenantMiddleware.d.ts +15 -4
  173. package/dist/core/tracing/otel.d.ts +4 -6
  174. package/dist/core/tracing/tracingMiddleware.d.ts +3 -3
  175. package/dist/core/view/etaViewEngine.d.ts +1 -1
  176. package/dist/core/view/index.d.ts +5 -4
  177. package/dist/core/view/tokens.d.ts +8 -0
  178. package/dist/core/view/viewRenderer.d.ts +2 -2
  179. package/dist/core/view/webErrorView.d.ts +8 -7
  180. package/dist/core/view/webLayoutData.d.ts +6 -4
  181. package/dist/entries/audit/exportAuditLogs.js +87 -1024
  182. package/dist/entries/audit/siemFormatter.js +4 -90
  183. package/dist/entries/auth/abilityCatalog.js +28 -0
  184. package/dist/entries/auth/accessControl.js +5 -16
  185. package/dist/entries/auth/accountStateMigration.js +216 -236
  186. package/dist/entries/auth/authOutcome.js +80 -0
  187. package/dist/entries/auth/authReader.js +68 -0
  188. package/dist/entries/auth/basicAuthGuard.js +144 -1249
  189. package/dist/entries/auth/emailVerification.js +2 -2
  190. package/dist/entries/auth/intendedUrlCookie.js +35 -59
  191. package/dist/entries/auth/jwt.js +22 -47
  192. package/dist/entries/auth/jwtGuard.js +99 -231
  193. package/dist/entries/auth/membershipMiddleware.js +71 -10
  194. package/dist/entries/auth/membershipScope.js +16 -22
  195. package/dist/entries/auth/membershipService.js +11 -28
  196. package/dist/entries/auth/oauth/oidcProvider.js +59 -64
  197. package/dist/entries/auth/oauth/providers.js +12 -95
  198. package/dist/entries/auth/oauth/samlProvider.js +53 -1080
  199. package/dist/entries/auth/oneTimeToken.js +27 -289
  200. package/dist/entries/auth/passwordConfirmCookie.js +40 -63
  201. package/dist/entries/auth/passwordLogin.js +94 -399
  202. package/dist/entries/auth/pendingMfaCookie.js +6 -6
  203. package/dist/entries/auth/policy.js +22 -56
  204. package/dist/entries/auth/saml/samlServiceProvider.js +55 -1084
  205. package/dist/entries/auth/scimAuthMiddleware.js +16 -3358
  206. package/dist/entries/auth/sessionCookie.js +58 -73
  207. package/dist/entries/auth/sessionGuard.js +95 -248
  208. package/dist/entries/auth/tokenHash.js +11 -43
  209. package/dist/entries/cache/createCacheStore.js +126 -117
  210. package/dist/entries/cache/repository.js +25 -0
  211. package/dist/entries/cache/simpleCache.js +12 -7
  212. package/dist/entries/cache/tokens.js +9 -0
  213. package/dist/entries/config/applicationConfig.js +163 -0
  214. package/dist/entries/config/envSchema.js +21 -4
  215. package/dist/entries/contracts/application.js +1 -0
  216. package/dist/entries/contracts/authUserDirectory.js +10 -0
  217. package/dist/entries/contracts/container.js +99 -26
  218. package/dist/entries/contracts/di.js +3 -0
  219. package/dist/entries/contracts/executionContext.js +7 -0
  220. package/dist/entries/contracts/executionOperations.js +7 -0
  221. package/dist/entries/contracts/executionOwnership.js +7 -0
  222. package/dist/entries/contracts/membership.js +1 -0
  223. package/dist/entries/contracts/persistence.js +1 -0
  224. package/dist/entries/contracts/serviceTokens.js +26 -116
  225. package/dist/entries/contracts/services.js +98 -0
  226. package/dist/entries/contracts/token.js +41 -0
  227. package/dist/entries/crypto/fieldEncryption.js +49 -50
  228. package/dist/entries/crypto/mfaSecret.js +86 -82
  229. package/dist/entries/database/acquisitionMetrics.js +107 -0
  230. package/dist/entries/database/baseRepository.d.ts +2 -0
  231. package/dist/entries/database/bindings.js +2082 -0
  232. package/dist/entries/database/definitions.js +175 -0
  233. package/dist/entries/database/errors.js +114 -89
  234. package/dist/entries/database/factory.js +67 -28
  235. package/dist/entries/database/migrations.js +172 -224
  236. package/dist/entries/database/model.d.ts +1 -0
  237. package/dist/entries/database/ownedReadOnlyObservation.js +1282 -0
  238. package/dist/entries/database/query.js +159 -161
  239. package/dist/entries/database/repositoryQuery.d.ts +1 -0
  240. package/dist/entries/database/repositoryQuery.js +1 -1373
  241. package/dist/entries/database/schema.js +216 -236
  242. package/dist/entries/database/session.js +1 -0
  243. package/dist/entries/database/sqliteConnection.js +525 -83
  244. package/dist/entries/database/tokens.js +9 -0
  245. package/dist/entries/errors/http.js +118 -1
  246. package/dist/entries/http/authMiddleware.js +8 -5
  247. package/dist/entries/http/authorizeMiddleware.js +1 -1
  248. package/dist/entries/http/bodySizeLimitMiddleware.js +2 -2
  249. package/dist/entries/http/clientIp.js +2 -2
  250. package/dist/entries/http/conditionalResponse.js +19 -7
  251. package/dist/entries/http/corsMiddleware.js +6 -101
  252. package/dist/entries/http/csrfMiddleware.js +92 -106
  253. package/dist/entries/http/csrfToken.js +58 -94
  254. package/dist/entries/http/etag.js +7 -4
  255. package/dist/entries/http/flashMiddleware.js +57 -99
  256. package/dist/entries/http/flashSession.js +41 -68
  257. package/dist/entries/http/memoryThrottleMiddleware.js +43 -186
  258. package/dist/entries/http/metricsMiddleware.js +2 -16
  259. package/dist/entries/http/parseMultipartUpload.js +15 -29
  260. package/dist/entries/http/requireAbilityMiddleware.js +2 -2
  261. package/dist/entries/http/requirePasswordConfirmMiddleware.js +19 -31
  262. package/dist/entries/http/requireVerifiedMiddleware.js +4 -7
  263. package/dist/entries/http/requireWebAuthMiddleware.js +2 -2
  264. package/dist/entries/http/response.js +67 -233
  265. package/dist/entries/http/routeMiddleware.js +0 -14
  266. package/dist/entries/http/scimThrottleMiddleware.js +43 -237
  267. package/dist/entries/http/securedRouteModelBinding.js +37 -25
  268. package/dist/entries/http/securityHeadersMiddleware.js +8 -25
  269. package/dist/entries/http/signedUrl.js +20 -110
  270. package/dist/entries/http/throttleMiddleware.js +41 -185
  271. package/dist/entries/http/uploads.js +9 -24
  272. package/dist/entries/jobs/exportAuditLogsJob.js +17 -1498
  273. package/dist/entries/jobs/invalidateCacheTagsJob.js +12 -47
  274. package/dist/entries/logging/requestLoggingMiddleware.js +4 -4
  275. package/dist/entries/mail/mailer.js +68 -78
  276. package/dist/entries/openapi/generator.js +33 -100
  277. package/dist/entries/queue/createAppQueue.js +416 -254
  278. package/dist/entries/queue/failedJobRepository.js +19 -8
  279. package/dist/entries/queue/failedJobService.js +1 -0
  280. package/dist/entries/queue/jobRunner.js +141 -66
  281. package/dist/entries/queue/publicQueue.js +411 -255
  282. package/dist/entries/queue/queueConfig.js +61 -0
  283. package/dist/entries/queue/queueHandoff.js +318 -0
  284. package/dist/entries/queue/queueMetrics.js +989 -1384
  285. package/dist/entries/queue/queueServices.js +133 -0
  286. package/dist/entries/queue/queueWorkerTransport.js +1703 -0
  287. package/dist/entries/queue/redisQueue.js +282 -180
  288. package/dist/entries/queue.js +6 -45
  289. package/dist/entries/runtime/application.js +1585 -0
  290. package/dist/entries/runtime/asyncContextStore.js +0 -16
  291. package/dist/entries/security/oauthState.js +35 -67
  292. package/dist/entries/security/publicReads.js +4 -4
  293. package/dist/entries/security/safeFetch.js +1 -0
  294. package/dist/entries/security/scimTenantTokens.js +3 -3
  295. package/dist/entries/security/tokenExpiry.js +2 -2
  296. package/dist/entries/security/totp.js +1 -87
  297. package/dist/entries/security/webhookSignature.js +2 -90
  298. package/dist/entries/storage/storage.js +120 -45
  299. package/dist/entries/tenant/databaseTenantContext.js +6 -907
  300. package/dist/entries/tenant/publicTenantHost.js +78 -0
  301. package/dist/entries/tenant/resolveTenant.js +14 -0
  302. package/dist/entries/tenant/scopedDatabasePolicy.js +75 -0
  303. package/dist/entries/tenant/tenancyConfig.js +1 -19
  304. package/dist/entries/tenant/tenantDatabaseScope.js +3 -892
  305. package/dist/entries/tracing/tracingMiddleware.js +104 -173
  306. package/dist/entries/view/tokens.js +11 -0
  307. package/dist/framework/public-api.d.ts +62 -44
  308. package/dist/index.js +10433 -11347
  309. package/dist/internal/ormInternal.js +117 -0
  310. package/dist/internal/ormRuntime.js +5000 -0
  311. package/package.json +158 -46
  312. package/dist/core/database/bindConnection.d.ts +0 -1
  313. package/dist/core/database/boundConnection.d.ts +0 -5
  314. package/dist/core/database/defaultConnection.d.ts +0 -7
  315. package/dist/core/database/namedConnections.d.ts +0 -15
  316. package/dist/core/database/readOnlyCollector.d.ts +0 -7
  317. package/dist/core/database/repositoryConnection.d.ts +0 -4
  318. package/dist/core/database/transaction.d.ts +0 -23
  319. package/dist/core/database/transactionControl.d.ts +0 -6
  320. package/dist/core/events/deferredModelEvents.d.ts +0 -7
  321. package/dist/core/facades/index.d.ts +0 -10
  322. package/dist/core/runtime/applicationRegistry.d.ts +0 -18
  323. package/dist/entries/database/bindConnection.js +0 -1
  324. package/dist/entries/database/boundConnection.js +0 -1
  325. package/dist/entries/database/defaultConnection.js +0 -1
  326. package/dist/entries/database/namedConnections.js +0 -1
  327. package/dist/entries/database/repositoryConnection.js +0 -1
  328. package/dist/entries/database/transaction.js +0 -1
  329. package/dist/entries/facades.js +0 -711
  330. package/dist/entries/runtime/applicationRegistry.js +0 -1
@@ -0,0 +1,1585 @@
1
+ // @bun
2
+ // ../../src/core/runtime/application.ts
3
+ import { AsyncLocalStorage } from "async_hooks";
4
+ import { ServiceContainer } from "@getstrata/core/contracts/container";
5
+ import { CORE_EXECUTION_CONTEXT_TOKEN as CORE_EXECUTION_CONTEXT_TOKEN2 } from "@getstrata/core/contracts/executionContext";
6
+ import {
7
+ CORE_EXECUTION_OPERATIONS_TOKEN as CORE_EXECUTION_OPERATIONS_TOKEN2
8
+ } from "@getstrata/core/contracts/executionOperations";
9
+ import {
10
+ CORE_EXECUTION_OWNERSHIP_TOKEN as CORE_EXECUTION_OWNERSHIP_TOKEN2
11
+ } from "@getstrata/core/contracts/executionOwnership";
12
+ import { assertServicePayload } from "@getstrata/core/contracts/services";
13
+
14
+ // ../../src/core/config/configSnapshot.ts
15
+ function copyApplicationConfig(value, ancestors = new Set) {
16
+ if (value === null || typeof value === "string" || typeof value === "boolean")
17
+ return value;
18
+ if (typeof value === "number" && Number.isFinite(value))
19
+ return value;
20
+ if (typeof value !== "object" || ancestors.has(value)) {
21
+ throw new TypeError("Application config must contain acyclic plain data.");
22
+ }
23
+ const array = Array.isArray(value);
24
+ const prototype = Object.getPrototypeOf(value);
25
+ if (prototype !== (array ? Array.prototype : Object.prototype) && !(prototype === null && !array)) {
26
+ throw new TypeError("Application config must contain only plain objects and arrays.");
27
+ }
28
+ if (Object.getOwnPropertySymbols(value).length > 0) {
29
+ throw new TypeError("Application config cannot contain symbol keys.");
30
+ }
31
+ const descriptors = Object.getOwnPropertyDescriptors(value);
32
+ for (const [key, descriptor] of Object.entries(descriptors)) {
33
+ if (!(array && key === "length") && (!descriptor.enumerable || !("value" in descriptor))) {
34
+ throw new TypeError("Application config cannot contain accessors or hidden properties.");
35
+ }
36
+ }
37
+ ancestors.add(value);
38
+ try {
39
+ if (array) {
40
+ const length = descriptors.length.value;
41
+ if (Object.keys(descriptors).length !== length + 1) {
42
+ throw new TypeError("Application config arrays must be dense and have no extra properties.");
43
+ }
44
+ const result = [];
45
+ for (let index = 0;index < length; index++) {
46
+ const descriptor = descriptors[String(index)];
47
+ if (!descriptor)
48
+ throw new TypeError("Application config arrays must be dense.");
49
+ result.push(copyApplicationConfig(descriptor.value, ancestors));
50
+ }
51
+ return Object.freeze(result);
52
+ }
53
+ const result = {};
54
+ for (const [key, descriptor] of Object.entries(descriptors)) {
55
+ Object.defineProperty(result, key, {
56
+ value: copyApplicationConfig(descriptor.value, ancestors),
57
+ enumerable: true
58
+ });
59
+ }
60
+ return Object.freeze(result);
61
+ } finally {
62
+ ancestors.delete(value);
63
+ }
64
+ }
65
+
66
+ // ../../src/core/runtime/executionContext.ts
67
+ function signalAccessor(name) {
68
+ const getter = Object.getOwnPropertyDescriptor(AbortSignal.prototype, name)?.get;
69
+ if (!getter)
70
+ throw new TypeError("Platform AbortSignal accessors are required.");
71
+ return getter;
72
+ }
73
+ var signalAborted = signalAccessor("aborted");
74
+ var signalReason = signalAccessor("reason");
75
+ var addListener = EventTarget.prototype.addEventListener;
76
+ var removeListener = EventTarget.prototype.removeEventListener;
77
+ function aborted(signal) {
78
+ return signalAborted.call(signal);
79
+ }
80
+ function reason(signal) {
81
+ return signalReason.call(signal);
82
+ }
83
+ function record(input, keys) {
84
+ if (input === null || typeof input !== "object" || Array.isArray(input)) {
85
+ throw new TypeError("Execution data must be a plain record.");
86
+ }
87
+ const prototype = Object.getPrototypeOf(input);
88
+ if (prototype !== Object.prototype && prototype !== null) {
89
+ throw new TypeError("Execution data must be a plain record.");
90
+ }
91
+ const result = Object.create(null);
92
+ for (const key of Reflect.ownKeys(input)) {
93
+ if (typeof key !== "string" || !keys.includes(key)) {
94
+ throw new TypeError("Unknown execution data field.");
95
+ }
96
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
97
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
98
+ throw new TypeError("Execution data must contain enumerable own data fields.");
99
+ }
100
+ result[key] = descriptor.value;
101
+ }
102
+ return result;
103
+ }
104
+ function metadata(value) {
105
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
106
+ throw new TypeError("Execution metadata must be a plain record.");
107
+ }
108
+ return copyApplicationConfig(value);
109
+ }
110
+ function nonempty(value) {
111
+ if (typeof value !== "string" || value.trim().length === 0) {
112
+ throw new TypeError("Execution identifiers and policies must be nonempty strings.");
113
+ }
114
+ }
115
+ function actor(input) {
116
+ const value = record(input, ["kind", "claims", "policy"]);
117
+ if (value.kind === "principal" && !("policy" in value)) {
118
+ return Object.freeze({ kind: "principal", claims: metadata(value.claims) });
119
+ }
120
+ if (value.kind === "system" && !("claims" in value)) {
121
+ nonempty(value.policy);
122
+ return Object.freeze({ kind: "system", policy: value.policy });
123
+ }
124
+ throw new TypeError("Invalid execution actor.");
125
+ }
126
+ function normalizeExecutionEnvelope(input) {
127
+ const value = record(input, [
128
+ "kind",
129
+ "actor",
130
+ "externalId",
131
+ "metadata",
132
+ "tenant",
133
+ "signal",
134
+ "deadlineAtMs"
135
+ ]);
136
+ if (value.kind !== "command" && value.kind !== "request" && value.kind !== "job") {
137
+ throw new TypeError("Invalid execution kind.");
138
+ }
139
+ const result = { kind: value.kind };
140
+ if (value.actor !== undefined)
141
+ result.actor = actor(value.actor);
142
+ else if (value.kind === "job")
143
+ throw new TypeError("Job executions require an actor.");
144
+ if (value.externalId !== undefined) {
145
+ nonempty(value.externalId);
146
+ result.externalId = value.externalId;
147
+ }
148
+ result.metadata = metadata(value.metadata === undefined ? {} : value.metadata);
149
+ if (value.tenant !== undefined)
150
+ result.tenant = metadata(value.tenant);
151
+ if (value.signal !== undefined) {
152
+ aborted(value.signal);
153
+ reason(value.signal);
154
+ result.signal = value.signal;
155
+ }
156
+ if (value.deadlineAtMs !== undefined) {
157
+ if (typeof value.deadlineAtMs !== "number")
158
+ throw new TypeError("Invalid execution deadline.");
159
+ if (!Number.isSafeInteger(value.deadlineAtMs) || value.deadlineAtMs < 0) {
160
+ throw new RangeError("Execution deadline must be a nonnegative safe integer.");
161
+ }
162
+ result.deadlineAtMs = value.deadlineAtMs;
163
+ }
164
+ return Object.freeze(result);
165
+ }
166
+
167
+ class ExecutionDeadlineError extends Error {
168
+ applicationId;
169
+ executionId;
170
+ code = "EXECUTION_DEADLINE";
171
+ constructor(applicationId, executionId) {
172
+ super("EXECUTION_DEADLINE");
173
+ this.applicationId = applicationId;
174
+ this.executionId = executionId;
175
+ }
176
+ }
177
+ function ownExecutionContext(envelope, applicationId, appSignal) {
178
+ const executionId = crypto.randomUUID();
179
+ const controller = new AbortController;
180
+ const subscriptions = [];
181
+ let timer;
182
+ let disposed = false;
183
+ const cancel = (signal) => {
184
+ if (!disposed && aborted(signal) && !controller.signal.aborted)
185
+ controller.abort(reason(signal));
186
+ };
187
+ const subscribe = (signal) => {
188
+ const listener = () => cancel(signal);
189
+ addListener.call(signal, "abort", listener);
190
+ subscriptions.push({ signal, listener });
191
+ cancel(signal);
192
+ };
193
+ const dispose = () => {
194
+ disposed = true;
195
+ clearTimeout(timer);
196
+ for (const { signal, listener } of subscriptions) {
197
+ removeListener.call(signal, "abort", listener);
198
+ }
199
+ };
200
+ try {
201
+ if (envelope.signal !== undefined)
202
+ subscribe(envelope.signal);
203
+ subscribe(appSignal);
204
+ const deadline = envelope.deadlineAtMs;
205
+ const refreshDeadline = () => {
206
+ if (disposed || controller.signal.aborted || deadline === undefined)
207
+ return;
208
+ const remaining = deadline - Date.now();
209
+ if (remaining <= 0) {
210
+ controller.abort(new ExecutionDeadlineError(applicationId, executionId));
211
+ return;
212
+ }
213
+ return remaining;
214
+ };
215
+ const check = () => {
216
+ refreshDeadline();
217
+ if (controller.signal.aborted)
218
+ throw controller.signal.reason;
219
+ };
220
+ if (deadline !== undefined) {
221
+ const tick = () => {
222
+ const remaining = refreshDeadline();
223
+ if (remaining !== undefined)
224
+ timer = setTimeout(tick, Math.min(remaining, 2147483647));
225
+ };
226
+ tick();
227
+ }
228
+ const context = Object.freeze({
229
+ ...envelope,
230
+ applicationId,
231
+ executionId,
232
+ signal: controller.signal
233
+ });
234
+ return { context, dispose, check };
235
+ } catch (error) {
236
+ dispose();
237
+ throw error;
238
+ }
239
+ }
240
+
241
+ // ../../src/core/runtime/executionTasks.ts
242
+ function joinedOutcome(result) {
243
+ return Object.freeze({
244
+ invoked: result.invoked,
245
+ body: Object.freeze({ ...result.body }),
246
+ strictFailed: result.failures.length > 0,
247
+ retained: result.retained,
248
+ strict: Object.freeze(result.failures.map((error) => Object.freeze({ error })))
249
+ });
250
+ }
251
+ function summary(failures) {
252
+ if (failures.length === 1)
253
+ return failures[0];
254
+ const error = new AggregateError([...failures], "Execution task failures.", {
255
+ cause: failures[0]
256
+ });
257
+ Object.freeze(error.errors);
258
+ return Object.freeze(error);
259
+ }
260
+ function outcome(result) {
261
+ if (result.body.ok && result.failures.length === 0)
262
+ return Object.freeze(result.body);
263
+ return Object.freeze({ ok: false, error: summary(result.failures) });
264
+ }
265
+ function rejected(error) {
266
+ const promise = Promise.reject(error);
267
+ promise.catch(() => {});
268
+ return promise;
269
+ }
270
+ function settleExecutionTasks(work, check, createOperation, resources, blank) {
271
+ const node = (body, resources, mode, ancestors, enter) => {
272
+ const children = [];
273
+ const path = Object.freeze([...ancestors, Symbol()]);
274
+ const launch = (childWork, mode, enter) => {
275
+ if (typeof childWork !== "function") {
276
+ throw new TypeError("Execution task callback must be a function.");
277
+ }
278
+ if (enter !== undefined && typeof enter !== "function") {
279
+ throw new TypeError("Owned invocation context must be a function.");
280
+ }
281
+ if (mode !== "bookkeeping")
282
+ check();
283
+ return blank(() => {
284
+ const child = node(childWork, resources.child(), mode, path, enter);
285
+ children.push(child.settlement);
286
+ Promise.resolve().then(child.invoke);
287
+ return child;
288
+ });
289
+ };
290
+ const spawn = (childWork) => {
291
+ try {
292
+ return launch(childWork, "strict").settlement.then(outcome);
293
+ } catch (error) {
294
+ return rejected(error);
295
+ }
296
+ };
297
+ const operation = (work) => {
298
+ try {
299
+ return launch(work, "operation").body;
300
+ } catch (error) {
301
+ return rejected(error);
302
+ }
303
+ };
304
+ const joined = (work, enter) => {
305
+ try {
306
+ return launch(work, "joined", enter).settlement.then(joinedOutcome);
307
+ } catch (error) {
308
+ return rejected(error);
309
+ }
310
+ };
311
+ const finalize = (work) => {
312
+ try {
313
+ return launch(work, "bookkeeping").settlement.then(joinedOutcome);
314
+ } catch (error) {
315
+ return rejected(error);
316
+ }
317
+ };
318
+ let invoked = false;
319
+ let entryFailure;
320
+ const bodyOperation = createOperation((scope, task) => {
321
+ if (mode !== "bookkeeping")
322
+ check();
323
+ invoked = true;
324
+ if (mode === "operation" || mode === "bookkeeping")
325
+ return body();
326
+ if (mode === "joined")
327
+ return body(task);
328
+ return body(scope);
329
+ }, spawn, resources, {
330
+ operation,
331
+ joined,
332
+ finalize,
333
+ bookkeeping: mode === "bookkeeping",
334
+ path,
335
+ enter,
336
+ entryFailed: (error) => {
337
+ entryFailure ??= { error };
338
+ }
339
+ });
340
+ const own = bodyOperation.promise.then((value) => ({ ok: true, value }), (error) => ({ ok: false, error }));
341
+ const settlement = own.then(async (result) => {
342
+ const descendants = await Promise.all(children);
343
+ const owned = await resources.finalize();
344
+ const failures = [];
345
+ if (!result.ok && (mode === "strict" || mode === "bookkeeping" || !invoked))
346
+ failures.push(result.error);
347
+ if (entryFailure)
348
+ failures.push(entryFailure.error);
349
+ for (const failure of owned.acquisitionFailures)
350
+ failures.push(failure);
351
+ for (const child of descendants) {
352
+ for (const failure of child.failures)
353
+ failures.push(failure);
354
+ }
355
+ for (const failure of owned.cleanupFailures)
356
+ failures.push(failure);
357
+ return {
358
+ invoked,
359
+ retained: owned.retained || descendants.some((child) => child.retained),
360
+ body: result,
361
+ failures
362
+ };
363
+ });
364
+ return { body: bodyOperation.promise, settlement, invoke: bodyOperation.invoke };
365
+ };
366
+ return blank(() => {
367
+ const root = node(work, resources, "strict", []);
368
+ root.invoke();
369
+ return root.settlement;
370
+ });
371
+ }
372
+ function completeExecution(result) {
373
+ const observed = outcome(result);
374
+ if (observed.ok)
375
+ return observed.value;
376
+ throw observed.error;
377
+ }
378
+
379
+ // ../../src/core/runtime/resourceJournal.ts
380
+ class ResourceJournal {
381
+ observer;
382
+ resources = new Map;
383
+ definitions = new Map;
384
+ providerOrder = new Map;
385
+ taskGroups = new WeakMap;
386
+ taskKeys = new Set;
387
+ staticKeys;
388
+ nextResource = 0;
389
+ nextGroup = 0;
390
+ nextHook = 0;
391
+ unsafe = false;
392
+ constructor(groups, observer) {
393
+ this.observer = observer;
394
+ this.staticKeys = Object.freeze(groups.map((group) => group.key));
395
+ for (const group of groups) {
396
+ this.definitions.set(group.key, group);
397
+ this.providerOrder.set(group.key, this.nextGroup++);
398
+ }
399
+ }
400
+ createTaskGroup(parent) {
401
+ if (parent && (!this.definitions.has(parent.key) || this.taskGroups.get(parent)?.sealed !== false)) {
402
+ throw new Error("Task resource parent is not admitting children.");
403
+ }
404
+ return this.registerDynamicGroup("execution task", parent ? [parent.key] : this.staticKeys);
405
+ }
406
+ createExecutionResources(templates) {
407
+ const keys = new Map(templates.map((template) => [template.key, Symbol()]));
408
+ const groups = new Map;
409
+ for (const template of templates) {
410
+ groups.set(template.key, this.registerDynamicGroup(template.name, [...this.staticKeys, ...template.requires.map((key) => keys.get(key) ?? key)], keys.get(template.key)));
411
+ }
412
+ let finalization;
413
+ return Object.freeze({
414
+ acquire: (template, spec, signal, validate, check) => this.acquire(groups.get(template.key), spec, signal, validate, check),
415
+ createRootTaskGroup: () => {
416
+ if (finalization)
417
+ throw new Error("Execution resources are no longer admitting tasks.");
418
+ return this.registerDynamicGroup("execution task", [
419
+ ...this.staticKeys,
420
+ ...[...groups.values()].map((group) => group.key)
421
+ ]);
422
+ },
423
+ finalize: (context) => {
424
+ finalization ??= this.finalizeGroups([...groups.values()], context);
425
+ return finalization;
426
+ }
427
+ });
428
+ }
429
+ registerDynamicGroup(name, requires, key = Symbol()) {
430
+ const group = Object.freeze({ key, name, requires: Object.freeze([...requires]) });
431
+ this.definitions.set(group.key, group);
432
+ this.providerOrder.set(group.key, this.nextGroup++);
433
+ this.taskGroups.set(group, { sealed: false });
434
+ this.taskKeys.add(group.key);
435
+ return group;
436
+ }
437
+ sealGroup(group) {
438
+ this.taskGroups.get(group).sealed = true;
439
+ }
440
+ finalizeGroup(group, context) {
441
+ const state = this.taskGroups.get(group);
442
+ state.finalization ??= this.finalizeGroups([group], context);
443
+ return state.finalization;
444
+ }
445
+ finalizeGroups(groups, context) {
446
+ const selected = new Set(groups.map((group) => group.key));
447
+ for (const group of groups)
448
+ this.sealGroup(group);
449
+ return Promise.resolve().then(async () => {
450
+ const resources = [...this.resources.values()].filter((resource) => selected.has(resource.group.key));
451
+ const acquisitions = await Promise.all(resources.map((resource) => resource.acquisition));
452
+ for (const resource of this.reverseResources(selected))
453
+ await this.hook(resource, "stop", context);
454
+ for (const resource of this.reverseResources(selected))
455
+ await this.hook(resource, "drain", context);
456
+ await this.flushAndClose(context, selected);
457
+ await Promise.all(resources.flatMap((resource) => [...resource.attempts.values()].map((attempt) => attempt.promise)));
458
+ const acquisitionFailures = [];
459
+ for (const acquisition of acquisitions) {
460
+ if (!acquisition.ok)
461
+ acquisitionFailures.push(acquisition.error);
462
+ }
463
+ const cleanupFailures = resources.flatMap((resource) => [...resource.internalCleanupErrors]);
464
+ const attempts = resources.flatMap((resource) => [...resource.attempts.values()]);
465
+ attempts.sort((left, right) => left.order - right.order);
466
+ for (const attempt of attempts) {
467
+ if (attempt.result && !attempt.result.ok)
468
+ cleanupFailures.push(attempt.result.error);
469
+ }
470
+ const retained = resources.some((resource) => resource.status === "acquired" || resource.status === "unknown");
471
+ const result = Object.freeze({
472
+ acquisitionFailures: Object.freeze(acquisitionFailures),
473
+ cleanupFailures: Object.freeze(cleanupFailures),
474
+ retained
475
+ });
476
+ for (const [key, resource] of this.resources) {
477
+ if (selected.has(resource.group.key) && (resource.status === "released" || resource.status === "discharged")) {
478
+ this.resources.delete(key);
479
+ }
480
+ }
481
+ this.pruneGroups();
482
+ this.observer.changed();
483
+ return result;
484
+ });
485
+ }
486
+ acquire(group, spec, signal, validate, check) {
487
+ let resource;
488
+ let open;
489
+ let close;
490
+ let stop;
491
+ let drain;
492
+ let flush;
493
+ try {
494
+ if (this.definitions.get(group.key) !== group || this.taskGroups.get(group)?.sealed) {
495
+ throw new Error("Resource owner is not admitting acquisitions.");
496
+ }
497
+ const name = dataField(spec, "name", true);
498
+ declarationName(name);
499
+ open = dataField(spec, "open", true);
500
+ close = dataField(spec, "close", true);
501
+ stop = dataField(spec, "stop");
502
+ drain = dataField(spec, "drain");
503
+ flush = dataField(spec, "flush");
504
+ if (typeof open !== "function" || typeof close !== "function") {
505
+ throw new TypeError("Owned resources must declare open and close functions.");
506
+ }
507
+ for (const hook of [stop, drain, flush]) {
508
+ if (hook !== undefined && typeof hook !== "function") {
509
+ throw new TypeError("Resource lifecycle hooks must be functions.");
510
+ }
511
+ }
512
+ check?.();
513
+ if (signal.aborted)
514
+ throw signal.reason;
515
+ if (this.definitions.get(group.key) !== group || this.taskGroups.get(group)?.sealed) {
516
+ throw new Error("Resource owner is not admitting acquisitions.");
517
+ }
518
+ if ([...this.resources.values()].some((item) => item.group.key === group.key && item.name === name)) {
519
+ throw new Error(`Duplicate resource name: ${name}.`);
520
+ }
521
+ resource = {
522
+ name,
523
+ group,
524
+ order: this.nextResource++,
525
+ status: "opening",
526
+ hooks: {},
527
+ attempts: new Map,
528
+ internalCleanupErrors: []
529
+ };
530
+ this.resources.set(Symbol(), resource);
531
+ } catch (error) {
532
+ return observed(Promise.reject(error));
533
+ }
534
+ const result = observed(Promise.resolve().then(async () => {
535
+ try {
536
+ const outcome = openOutcome(await open(signal));
537
+ if (!outcome.ok) {
538
+ resource.status = outcome.disposition === "unknown" ? "unknown" : "discharged";
539
+ resource.internalCleanupErrors = outcome.cleanupErrors ?? [];
540
+ this.record("acquisition", "ACQUISITION_FAILED", outcome.error, resource);
541
+ for (const error of resource.internalCleanupErrors) {
542
+ this.record("cleanup", "INTERNAL_ACQUISITION_CLEANUP_FAILED", error, resource, "close");
543
+ }
544
+ this.observer.changed();
545
+ throw outcome.error;
546
+ }
547
+ const value = outcome.value;
548
+ resource.status = "acquired";
549
+ resource.hooks.close = (context) => close(value, context);
550
+ if (stop)
551
+ resource.hooks.stop = (context) => stop(value, context);
552
+ if (drain)
553
+ resource.hooks.drain = (context) => drain(value, context);
554
+ if (flush)
555
+ resource.hooks.flush = (context) => flush(value, context);
556
+ this.observer.changed();
557
+ validate?.(value);
558
+ check?.();
559
+ if (signal.aborted)
560
+ throw signal.reason;
561
+ return value;
562
+ } catch (error) {
563
+ if (resource.status === "opening") {
564
+ resource.status = "unknown";
565
+ this.record("acquisition", "ACQUISITION_OUTCOME_UNKNOWN", error, resource);
566
+ this.observer.changed();
567
+ }
568
+ throw error;
569
+ }
570
+ }));
571
+ resource.acquisition = result.then(() => ({ ok: true }), (error) => ({ ok: false, error }));
572
+ this.observer.changed();
573
+ return result;
574
+ }
575
+ async scanStop(context) {
576
+ let safe = true;
577
+ for (const resource of this.reverseResources()) {
578
+ if (!await this.hook(resource, "stop", context))
579
+ safe = false;
580
+ }
581
+ return safe && !this.unsafe;
582
+ }
583
+ async drain(context) {
584
+ let safe = true;
585
+ for (const resource of this.reverseResources()) {
586
+ if (!await this.hook(resource, "stop", context))
587
+ safe = false;
588
+ if (!await this.hook(resource, "drain", context))
589
+ safe = false;
590
+ }
591
+ return safe && !this.unsafe;
592
+ }
593
+ async flushAndClose(context, selected) {
594
+ let blocked = this.blockedGroups(selected);
595
+ for (const resource of this.reverseResources(selected)) {
596
+ if (!blocked.has(resource.group.key))
597
+ await this.hook(resource, "flush", context);
598
+ }
599
+ for (const resource of this.reverseResources(selected)) {
600
+ blocked = this.blockedGroups(selected);
601
+ if (blocked.has(resource.group.key))
602
+ continue;
603
+ await this.hook(resource, "close", context);
604
+ }
605
+ }
606
+ view() {
607
+ const resources = [...this.resources.values()];
608
+ return Object.freeze({
609
+ pendingAcquisitions: Object.freeze(resources.filter((item) => item.status === "opening").map((item) => item.name)),
610
+ retainedResources: Object.freeze(resources.filter((item) => item.status === "acquired" || item.status === "unknown").map((item) => item.name)),
611
+ unstopped: resources.some((resource) => resource.status === "acquired" && resource.hooks.stop !== undefined && resource.attempts.get("stop")?.result === undefined),
612
+ unsafe: this.unsafe,
613
+ resourceCount: resources.length,
614
+ groupCount: this.definitions.size,
615
+ taskGroupCount: this.taskKeys.size
616
+ });
617
+ }
618
+ groupResources(group) {
619
+ return [...this.resources.values()].filter((resource) => resource.group === group);
620
+ }
621
+ blockedGroups(selected) {
622
+ const blocked = new Set;
623
+ for (const resource of this.resources.values()) {
624
+ if (resource.status === "unknown" || [...resource.attempts.entries()].some(([phase, attempt]) => phase !== "flush" && attempt.result?.ok === false)) {
625
+ this.blockDependencies(resource.group.key, blocked);
626
+ } else if (selected && !selected.has(resource.group.key) && (resource.status === "acquired" || resource.status === "opening")) {
627
+ for (const dependency of resource.group.requires)
628
+ this.blockDependencies(dependency, blocked);
629
+ }
630
+ }
631
+ return blocked;
632
+ }
633
+ blockDependencies(provider, blocked) {
634
+ if (blocked.has(provider))
635
+ return;
636
+ blocked.add(provider);
637
+ for (const dependency of this.definitions.get(provider)?.requires ?? []) {
638
+ this.blockDependencies(dependency, blocked);
639
+ }
640
+ }
641
+ reverseResources(selected) {
642
+ return [...this.resources.values()].filter((resource) => !selected || selected.has(resource.group.key)).sort((left, right) => (this.providerOrder.get(right.group.key) ?? 0) - (this.providerOrder.get(left.group.key) ?? 0) || right.order - left.order);
643
+ }
644
+ hook(resource, phase, context) {
645
+ const existing = resource.attempts.get(phase);
646
+ if (existing)
647
+ return existing.promise;
648
+ const handler = resource.hooks[phase];
649
+ if (resource.status !== "acquired" || !handler)
650
+ return Promise.resolve(true);
651
+ const attempt = {
652
+ order: -1,
653
+ promise: Promise.resolve().then(async () => {
654
+ attempt.order = this.nextHook++;
655
+ try {
656
+ await handler(context);
657
+ attempt.result = { ok: true };
658
+ if (phase === "close")
659
+ resource.status = "released";
660
+ this.observer.changed();
661
+ return true;
662
+ } catch (error) {
663
+ attempt.result = { ok: false, error };
664
+ if (phase === "stop" || phase === "drain")
665
+ this.unsafe = true;
666
+ this.record("cleanup", "RESOURCE_CLEANUP_FAILED", error, resource, phase);
667
+ this.observer.changed();
668
+ return false;
669
+ }
670
+ })
671
+ };
672
+ resource.attempts.set(phase, attempt);
673
+ return attempt.promise;
674
+ }
675
+ pruneGroups() {
676
+ let changed = true;
677
+ while (changed) {
678
+ changed = false;
679
+ for (const key of this.taskKeys) {
680
+ const group = this.definitions.get(key);
681
+ const state = this.taskGroups.get(group);
682
+ if (!state.sealed || this.groupResources(group).length > 0 || [...this.definitions.values()].some((item) => item.requires.includes(key)))
683
+ continue;
684
+ this.taskKeys.delete(key);
685
+ this.definitions.delete(key);
686
+ this.providerOrder.delete(key);
687
+ changed = true;
688
+ }
689
+ }
690
+ }
691
+ record(kind, code, error, resource, phase) {
692
+ const diagnostic = Object.freeze({
693
+ kind,
694
+ code,
695
+ error,
696
+ provider: resource.group.name,
697
+ resource: resource.name,
698
+ ...phase ? { phase } : {}
699
+ });
700
+ if (kind === "acquisition" && this.taskKeys.has(resource.group.key) && resource.status !== "unknown")
701
+ return;
702
+ this.observer.record(diagnostic);
703
+ }
704
+ }
705
+ function observed(promise) {
706
+ promise.catch(() => {});
707
+ return promise;
708
+ }
709
+ function declarationName(value) {
710
+ if (typeof value !== "string" || value.trim().length === 0) {
711
+ throw new TypeError("Provider and resource names must be nonempty strings.");
712
+ }
713
+ }
714
+ function dataField(record, key, required = false) {
715
+ const descriptor = Object.getOwnPropertyDescriptor(record, key);
716
+ if (!descriptor && (required || (key in record)) || descriptor && !("value" in descriptor)) {
717
+ throw new TypeError("Application adapter records must declare own data fields.");
718
+ }
719
+ return descriptor?.value;
720
+ }
721
+ function openOutcome(value) {
722
+ if (value === null || typeof value !== "object") {
723
+ throw new TypeError("Resource open must return an explicit outcome.");
724
+ }
725
+ const ok = dataField(value, "ok", true);
726
+ if (ok === true)
727
+ return { ok, value: dataField(value, "value", true) };
728
+ const disposition = dataField(value, "disposition", true);
729
+ if (ok !== false || disposition !== "unknown" && disposition !== "not-acquired" && disposition !== "cleaned") {
730
+ throw new TypeError("Resource open returned an invalid outcome disposition.");
731
+ }
732
+ const errors = dataField(value, "cleanupErrors");
733
+ if (errors !== undefined && !Array.isArray(errors)) {
734
+ throw new TypeError("Acquisition cleanup errors must be an array.");
735
+ }
736
+ return {
737
+ ok: false,
738
+ error: dataField(value, "error", true),
739
+ disposition,
740
+ cleanupErrors: errors === undefined ? [] : [...errors]
741
+ };
742
+ }
743
+
744
+ // ../../src/core/runtime/serviceGraph.ts
745
+ import { CORE_EXECUTION_CONTEXT_TOKEN } from "@getstrata/core/contracts/executionContext";
746
+ import { CORE_EXECUTION_OPERATIONS_TOKEN } from "@getstrata/core/contracts/executionOperations";
747
+ import { CORE_EXECUTION_OWNERSHIP_TOKEN } from "@getstrata/core/contracts/executionOwnership";
748
+ import {
749
+ aliasService,
750
+ isServiceDeclaration,
751
+ resourceService,
752
+ service,
753
+ valueService
754
+ } from "@getstrata/core/contracts/services";
755
+ import {
756
+ assertServiceToken,
757
+ serviceTokenKey,
758
+ serviceTokenName
759
+ } from "@getstrata/core/contracts/token";
760
+
761
+ class ServiceGraphError extends Error {
762
+ code;
763
+ constructor(code) {
764
+ super(code);
765
+ this.code = code;
766
+ }
767
+ }
768
+ function fail(code) {
769
+ throw new ServiceGraphError(`SERVICE_GRAPH_${code}`);
770
+ }
771
+ function field(record, name) {
772
+ if (record === null || typeof record !== "object")
773
+ return fail("INVALID_DECLARATION");
774
+ const descriptor = Object.getOwnPropertyDescriptor(record, name);
775
+ if (!descriptor || !("value" in descriptor))
776
+ return fail("INVALID_DECLARATION");
777
+ return descriptor.value;
778
+ }
779
+ function declaration(input) {
780
+ const kind = field(input, "kind");
781
+ const token = field(input, "token");
782
+ assertServiceToken(token);
783
+ const typed = token;
784
+ let normalized;
785
+ if (kind === "value") {
786
+ if (field(input, "lifetime") !== "application")
787
+ return fail("INVALID_LIFETIME");
788
+ normalized = valueService(typed, field(input, "value"));
789
+ } else if (kind === "alias") {
790
+ const target = field(input, "target");
791
+ assertServiceToken(target);
792
+ normalized = aliasService(typed, target);
793
+ } else {
794
+ if (kind !== "factory" && kind !== "resource")
795
+ return fail("INVALID_DECLARATION");
796
+ const lifetime = field(input, "lifetime");
797
+ if (lifetime !== "application" && lifetime !== "execution")
798
+ return fail("INVALID_LIFETIME");
799
+ const dependencies = field(input, "dependencies");
800
+ const create = field(input, "create");
801
+ if (!Array.isArray(dependencies) || typeof create !== "function") {
802
+ return fail("INVALID_DECLARATION");
803
+ }
804
+ if (kind === "resource") {
805
+ normalized = resourceService(typed, {
806
+ lifetime,
807
+ dependencies,
808
+ create
809
+ });
810
+ } else {
811
+ normalized = service(typed, {
812
+ lifetime,
813
+ dependencies,
814
+ create
815
+ });
816
+ }
817
+ }
818
+ if (!isServiceDeclaration(input))
819
+ return fail("INVALID_DECLARATION");
820
+ return normalized;
821
+ }
822
+ function dependencies(item) {
823
+ if (item.kind === "alias")
824
+ return [item.target];
825
+ return item.kind === "factory" || item.kind === "resource" ? item.dependencies : [];
826
+ }
827
+ function compileServiceGraph(declarations = [], overrides = []) {
828
+ if (!Array.isArray(declarations) || !Array.isArray(overrides))
829
+ return fail("INVALID_DECLARATION");
830
+ const implicit = new Set([
831
+ serviceTokenKey(CORE_EXECUTION_CONTEXT_TOKEN),
832
+ serviceTokenKey(CORE_EXECUTION_OPERATIONS_TOKEN),
833
+ serviceTokenKey(CORE_EXECUTION_OWNERSHIP_TOKEN)
834
+ ]);
835
+ const nodes = new Map;
836
+ for (const input of declarations) {
837
+ const item = declaration(input);
838
+ const key = serviceTokenKey(item.token);
839
+ if (implicit.has(key))
840
+ return fail("RESERVED_TOKEN");
841
+ if (nodes.has(key))
842
+ return fail("DUPLICATE_TOKEN");
843
+ nodes.set(key, item);
844
+ }
845
+ const replaced = new Set;
846
+ for (const input of overrides) {
847
+ const item = declaration(input);
848
+ const key = serviceTokenKey(item.token);
849
+ if (implicit.has(key))
850
+ return fail("RESERVED_TOKEN");
851
+ if (!nodes.has(key))
852
+ return fail("UNKNOWN_OVERRIDE");
853
+ if (replaced.has(key))
854
+ return fail("DUPLICATE_OVERRIDE");
855
+ replaced.add(key);
856
+ nodes.set(key, item);
857
+ }
858
+ for (const item of nodes.values()) {
859
+ for (const dependency of dependencies(item)) {
860
+ if (!implicit.has(serviceTokenKey(dependency)) && !nodes.has(serviceTokenKey(dependency)))
861
+ return fail("MISSING_DEPENDENCY");
862
+ }
863
+ }
864
+ const remaining = [...nodes.values()];
865
+ const ordered = [];
866
+ const lifetimes = new Map([
867
+ [serviceTokenKey(CORE_EXECUTION_CONTEXT_TOKEN), "execution"],
868
+ [serviceTokenKey(CORE_EXECUTION_OPERATIONS_TOKEN), "execution"],
869
+ [serviceTokenKey(CORE_EXECUTION_OWNERSHIP_TOKEN), "execution"]
870
+ ]);
871
+ while (remaining.length > 0) {
872
+ const index = remaining.findIndex((item) => dependencies(item).every((dependency) => lifetimes.has(serviceTokenKey(dependency))));
873
+ if (index === -1)
874
+ return fail("CYCLE");
875
+ const item = remaining.splice(index, 1)[0];
876
+ const lifetime = item.kind === "alias" ? lifetimes.get(serviceTokenKey(item.target)) : item.lifetime;
877
+ lifetimes.set(serviceTokenKey(item.token), lifetime);
878
+ ordered.push(item);
879
+ }
880
+ for (const item of ordered) {
881
+ if (lifetimes.get(serviceTokenKey(item.token)) !== "application")
882
+ continue;
883
+ if (dependencies(item).some((dependency) => lifetimes.get(serviceTokenKey(dependency)) === "execution")) {
884
+ return fail("CAPTIVE_DEPENDENCY");
885
+ }
886
+ }
887
+ Object.freeze(ordered);
888
+ const backing = new Map;
889
+ const resourceGroups = [];
890
+ const executionResourceTemplates = [];
891
+ const resourceOwners = new Map;
892
+ for (const item of ordered) {
893
+ const closure = new Set;
894
+ for (const dependency of dependencies(item)) {
895
+ for (const key of backing.get(serviceTokenKey(dependency)) ?? [])
896
+ closure.add(key);
897
+ }
898
+ if (item.kind === "resource") {
899
+ const group = Object.freeze({
900
+ key: Symbol(),
901
+ name: serviceTokenName(item.token),
902
+ requires: Object.freeze([...closure])
903
+ });
904
+ if (item.lifetime === "application")
905
+ resourceGroups.push(group);
906
+ else
907
+ executionResourceTemplates.push(group);
908
+ resourceOwners.set(serviceTokenKey(item.token), group);
909
+ closure.add(group.key);
910
+ }
911
+ backing.set(serviceTokenKey(item.token), Object.freeze([...closure]));
912
+ }
913
+ Object.freeze(resourceGroups);
914
+ Object.freeze(executionResourceTemplates);
915
+ async function initialize(container, signal, lifetime, checkpoint, acquisition) {
916
+ for (const item of ordered) {
917
+ if (lifetimes.get(serviceTokenKey(item.token)) !== lifetime)
918
+ continue;
919
+ checkpoint?.();
920
+ if (signal.aborted)
921
+ throw signal.reason;
922
+ const token = item.token;
923
+ if (item.kind === "value")
924
+ container.set(token, item.value);
925
+ else if (item.kind === "alias")
926
+ container.alias(token, item.target);
927
+ else {
928
+ await container.initialize(token, () => {
929
+ const values = item.dependencies.map((dependency) => container.resolve(dependency));
930
+ const value = item.create(...values);
931
+ if (item.kind !== "resource")
932
+ return value;
933
+ checkpoint?.();
934
+ if (signal.aborted)
935
+ throw signal.reason;
936
+ return acquisition.acquire(resourceOwners.get(serviceTokenKey(item.token)), value, signal, (payload) => {
937
+ valueService(token, payload);
938
+ }, checkpoint);
939
+ }, signal, checkpoint);
940
+ }
941
+ }
942
+ checkpoint?.();
943
+ if (signal.aborted)
944
+ throw signal.reason;
945
+ container.seal();
946
+ }
947
+ return Object.freeze({
948
+ resourceGroups,
949
+ executionResourceTemplates,
950
+ start: (container, signal, acquisition) => initialize(container, signal, "application", undefined, acquisition),
951
+ startExecution: (container, signal, checkpoint, acquisition) => initialize(container, signal, "execution", checkpoint, acquisition)
952
+ });
953
+ }
954
+
955
+ // ../../src/core/runtime/application.ts
956
+ import {
957
+ aliasService as aliasService2,
958
+ resourceService as resourceService2,
959
+ service as service2,
960
+ valueService as valueService2
961
+ } from "@getstrata/core/contracts/services";
962
+ function deferred() {
963
+ let resolve;
964
+ let reject;
965
+ const promise = new Promise((fulfill, fail) => {
966
+ resolve = fulfill;
967
+ reject = fail;
968
+ });
969
+ return { promise, resolve, reject };
970
+ }
971
+ function observed2(promise) {
972
+ promise.catch(() => {});
973
+ return promise;
974
+ }
975
+ function timeout(value) {
976
+ const result = value === undefined ? 30000 : value;
977
+ if (!Number.isSafeInteger(result) || result <= 0 || result > 2147483647) {
978
+ throw new RangeError("Application cleanup timeout must be an integer between 1 and 2147483647.");
979
+ }
980
+ return result;
981
+ }
982
+ function mayBeThenable(value) {
983
+ if (value === null || typeof value !== "object" && typeof value !== "function")
984
+ return false;
985
+ try {
986
+ let current = value;
987
+ const visited = new Set;
988
+ while (current !== null) {
989
+ if (visited.has(current))
990
+ return true;
991
+ visited.add(current);
992
+ const then = Object.getOwnPropertyDescriptor(current, "then");
993
+ if (then)
994
+ return !("value" in then) || typeof then.value === "function";
995
+ current = Object.getPrototypeOf(current);
996
+ }
997
+ return false;
998
+ } catch {
999
+ return true;
1000
+ }
1001
+ }
1002
+ function leasedOperation(work, close) {
1003
+ const result = deferred();
1004
+ observed2(result.promise);
1005
+ result.promise.then(close, close);
1006
+ return {
1007
+ promise: result.promise,
1008
+ fail(error) {
1009
+ close();
1010
+ result.reject(error);
1011
+ },
1012
+ invoke() {
1013
+ try {
1014
+ const value = work();
1015
+ if (!mayBeThenable(value))
1016
+ close();
1017
+ result.resolve(value);
1018
+ } catch (error) {
1019
+ close();
1020
+ result.reject(error);
1021
+ }
1022
+ }
1023
+ };
1024
+ }
1025
+ function declarationName2(value) {
1026
+ if (typeof value !== "string" || value.trim().length === 0) {
1027
+ throw new TypeError("Provider and resource names must be nonempty strings.");
1028
+ }
1029
+ }
1030
+ function normalize(input) {
1031
+ const copied = copyApplicationConfig(input.config === undefined ? {} : input.config);
1032
+ if (copied === null || typeof copied !== "object" || Array.isArray(copied)) {
1033
+ throw new TypeError("Application config must be a plain object.");
1034
+ }
1035
+ const names = new Set;
1036
+ const copy = (items) => {
1037
+ if (!Array.isArray(items))
1038
+ throw new TypeError("Application providers must be an array.");
1039
+ return items.map((item) => {
1040
+ declarationName2(item.name);
1041
+ if (names.has(item.name))
1042
+ throw new Error(`Duplicate provider name: ${item.name}.`);
1043
+ if (typeof item.setup !== "function")
1044
+ throw new TypeError("Provider setup must be a function.");
1045
+ if (item.requires !== undefined && !Array.isArray(item.requires)) {
1046
+ throw new TypeError("Provider dependencies must be an array.");
1047
+ }
1048
+ const requires = [...item.requires ?? []];
1049
+ for (const dependency of requires)
1050
+ declarationName2(dependency);
1051
+ names.add(item.name);
1052
+ return Object.freeze({
1053
+ name: item.name,
1054
+ setup: item.setup,
1055
+ requires: Object.freeze(requires)
1056
+ });
1057
+ });
1058
+ };
1059
+ const providers = copy(input.providers);
1060
+ const transports = copy(input.transports === undefined ? [] : input.transports);
1061
+ const transportNames = new Set(transports.map((item) => item.name));
1062
+ for (const item of [...providers, ...transports]) {
1063
+ for (const dependency of item.requires ?? []) {
1064
+ if (!names.has(dependency))
1065
+ throw new Error(`Missing provider dependency: ${dependency}.`);
1066
+ if (!transportNames.has(item.name) && transportNames.has(dependency)) {
1067
+ throw new Error("Providers cannot depend on transports that start after them.");
1068
+ }
1069
+ }
1070
+ }
1071
+ const complete = new Set;
1072
+ const order = (items) => {
1073
+ const remaining = [...items];
1074
+ const result = [];
1075
+ while (remaining.length > 0) {
1076
+ const index = remaining.findIndex((item) => (item.requires ?? []).every((dependency) => complete.has(dependency)));
1077
+ if (index === -1)
1078
+ throw new Error("Application provider dependency cycle.");
1079
+ const item = remaining.splice(index, 1)[0];
1080
+ complete.add(item.name);
1081
+ result.push(item);
1082
+ }
1083
+ return Object.freeze(result);
1084
+ };
1085
+ const orderedProviders = order(providers);
1086
+ const orderedTransports = order(transports);
1087
+ return {
1088
+ config: copied,
1089
+ providers: orderedProviders,
1090
+ transports: orderedTransports,
1091
+ shutdownTimeoutMs: timeout(input.shutdownTimeoutMs),
1092
+ startupCleanupTimeoutMs: timeout(input.startupCleanupTimeoutMs),
1093
+ services: compileServiceGraph(input.services, input.overrides)
1094
+ };
1095
+ }
1096
+
1097
+ class ApplicationStateError extends Error {
1098
+ code;
1099
+ applicationId;
1100
+ constructor(code, applicationId) {
1101
+ super(code);
1102
+ this.code = code;
1103
+ this.applicationId = applicationId;
1104
+ }
1105
+ }
1106
+
1107
+ class OwnedApplication {
1108
+ definition;
1109
+ taskStorage = new AsyncLocalStorage;
1110
+ id = crypto.randomUUID();
1111
+ completion;
1112
+ completed = deferred();
1113
+ cancellation = new AbortController;
1114
+ cleanupCancellation = new AbortController;
1115
+ cancelled = new ApplicationStateError("APPLICATION_START_CANCELLED", this.id);
1116
+ journal;
1117
+ providerGroups = new Map;
1118
+ commands = new Set;
1119
+ services = new ServiceContainer;
1120
+ diagnostics = [];
1121
+ changed = deferred();
1122
+ phase = "constructed";
1123
+ boot = "not-started";
1124
+ cleanup = "not-required";
1125
+ snapshot;
1126
+ startup;
1127
+ terminalStartup;
1128
+ stopping;
1129
+ startupRunning = false;
1130
+ stopTimer;
1131
+ timedOut = false;
1132
+ hasPrimary = false;
1133
+ primary;
1134
+ constructor(definition) {
1135
+ this.definition = definition;
1136
+ this.completion = this.completed.promise;
1137
+ const providerKeys = new Map([...definition.providers, ...definition.transports].map((item) => [item.name, Symbol()]));
1138
+ const managedKeys = definition.services.resourceGroups.map((group) => group.key);
1139
+ const providerKeysOnly = definition.providers.map((item) => providerKeys.get(item.name));
1140
+ for (const item of [...definition.providers, ...definition.transports]) {
1141
+ this.providerGroups.set(item, Object.freeze({
1142
+ key: providerKeys.get(item.name),
1143
+ name: item.name,
1144
+ requires: Object.freeze([
1145
+ ...managedKeys,
1146
+ ...definition.transports.includes(item) ? providerKeysOnly : [],
1147
+ ...(item.requires ?? []).map((name) => providerKeys.get(name))
1148
+ ])
1149
+ }));
1150
+ }
1151
+ const groups = Object.freeze([
1152
+ ...definition.services.resourceGroups,
1153
+ ...this.providerGroups.values()
1154
+ ]);
1155
+ this.journal = new ResourceJournal(groups, {
1156
+ record: (diagnostic) => this.diagnostics.push(diagnostic),
1157
+ changed: () => this.publish()
1158
+ });
1159
+ this.snapshot = this.makeSnapshot();
1160
+ }
1161
+ get state() {
1162
+ return this.snapshot;
1163
+ }
1164
+ start() {
1165
+ if (this.phase === "stopping" || this.phase === "stopped" || this.phase === "failed") {
1166
+ this.terminalStartup ??= observed2(Promise.reject(new ApplicationStateError("APPLICATION_TERMINAL", this.id)));
1167
+ return this.terminalStartup;
1168
+ }
1169
+ if (this.startup)
1170
+ return this.startup.promise;
1171
+ this.startup = deferred();
1172
+ observed2(this.startup.promise);
1173
+ this.phase = "starting";
1174
+ this.boot = "pending";
1175
+ this.cleanup = "open";
1176
+ this.startupRunning = true;
1177
+ this.publish();
1178
+ Promise.resolve().then(() => this.taskStorage.run(undefined, () => this.startProviders()));
1179
+ return this.startup.promise;
1180
+ }
1181
+ stop(options = {}) {
1182
+ return this.taskStorage.run(undefined, () => this.beginStop(options.reason ?? "shutdown", this.definition.shutdownTimeoutMs));
1183
+ }
1184
+ run(input, callback) {
1185
+ return this.taskStorage.run(undefined, () => {
1186
+ if (this.phase !== "ready") {
1187
+ return observed2(Promise.reject(new ApplicationStateError("APPLICATION_NOT_READY", this.id)));
1188
+ }
1189
+ let envelope;
1190
+ let work;
1191
+ try {
1192
+ const candidate = typeof input === "function" && callback === undefined ? input : callback;
1193
+ if (typeof candidate !== "function")
1194
+ throw new TypeError("Execution callback must be a function.");
1195
+ work = candidate;
1196
+ envelope = normalizeExecutionEnvelope(typeof input === "function" && callback === undefined ? { kind: "command" } : input);
1197
+ if (this.phase !== "ready" || this.cancellation.signal.aborted) {
1198
+ throw new ApplicationStateError("APPLICATION_NOT_READY", this.id);
1199
+ }
1200
+ } catch (error) {
1201
+ return observed2(Promise.reject(error));
1202
+ }
1203
+ const result = deferred();
1204
+ observed2(result.promise);
1205
+ this.commands.add(result.promise);
1206
+ result.promise.then(() => this.commandSettled(result.promise), () => this.commandSettled(result.promise));
1207
+ this.execute(envelope, work).then(result.resolve, result.reject);
1208
+ return result.promise;
1209
+ });
1210
+ }
1211
+ async execute(envelope, work) {
1212
+ const owner = ownExecutionContext(envelope, this.id, this.cancellation.signal);
1213
+ try {
1214
+ const { context } = owner;
1215
+ if (this.phase !== "ready" || this.cancellation.signal.aborted) {
1216
+ throw new ApplicationStateError("APPLICATION_NOT_READY", this.id);
1217
+ }
1218
+ owner.check();
1219
+ const services = new ServiceContainer(this.services);
1220
+ services.set(CORE_EXECUTION_CONTEXT_TOKEN2, context);
1221
+ const identityFrame = () => {
1222
+ const frame = this.taskStorage.getStore();
1223
+ if (!frame || frame.application !== this || frame.context !== context || !frame.lease.active) {
1224
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1225
+ }
1226
+ return frame;
1227
+ };
1228
+ const activeFrame = () => {
1229
+ const frame = identityFrame();
1230
+ owner.check();
1231
+ return frame;
1232
+ };
1233
+ const operations = Object.freeze({
1234
+ assertActive: () => {
1235
+ activeFrame();
1236
+ },
1237
+ operation: (work) => {
1238
+ try {
1239
+ return activeFrame().operation(work);
1240
+ } catch (error) {
1241
+ return observed2(Promise.reject(error));
1242
+ }
1243
+ }
1244
+ });
1245
+ services.set(CORE_EXECUTION_OPERATIONS_TOKEN2, operations);
1246
+ const ownership = Object.freeze({
1247
+ joined: (work, enter) => {
1248
+ try {
1249
+ return activeFrame().joined(work, enter);
1250
+ } catch (error) {
1251
+ return observed2(Promise.reject(error));
1252
+ }
1253
+ }
1254
+ });
1255
+ services.set(CORE_EXECUTION_OWNERSHIP_TOKEN2, ownership);
1256
+ const executionResources = this.journal.createExecutionResources(this.definition.services.executionResourceTemplates);
1257
+ const cleanupContext = Object.freeze({
1258
+ signal: this.cleanupCancellation.signal,
1259
+ reason: "task-complete"
1260
+ });
1261
+ const bindingCleanupContext = Object.freeze({
1262
+ signal: this.cleanupCancellation.signal,
1263
+ reason: "execution-complete"
1264
+ });
1265
+ let initialization;
1266
+ try {
1267
+ await this.definition.services.startExecution(services, context.signal, owner.check, {
1268
+ acquire: (template, spec, signal, validate, check) => executionResources.acquire(template, spec, signal, validate, check)
1269
+ });
1270
+ owner.check();
1271
+ initialization = { ok: true };
1272
+ } catch (error) {
1273
+ initialization = { ok: false, error };
1274
+ }
1275
+ const taskResources = (parent) => {
1276
+ const group = parent ? this.journal.createTaskGroup(parent) : executionResources.createRootTaskGroup();
1277
+ return Object.freeze({
1278
+ acquire: (spec) => this.journal.acquire(group, spec, context.signal, assertServicePayload, owner.check),
1279
+ child: () => taskResources(group),
1280
+ seal: () => this.journal.sealGroup(group),
1281
+ finalize: () => this.taskStorage.run(undefined, () => this.journal.finalizeGroup(group, cleanupContext))
1282
+ });
1283
+ };
1284
+ const callbacks = initialization.ok ? await settleExecutionTasks(work, owner.check, (body, spawn, resources, dispatch) => {
1285
+ const lease = { active: true };
1286
+ const frame = Object.freeze({
1287
+ application: this,
1288
+ context,
1289
+ lease,
1290
+ operation: dispatch.operation,
1291
+ joined: dispatch.joined,
1292
+ path: dispatch.path
1293
+ });
1294
+ const scope = Object.freeze({
1295
+ applicationId: this.id,
1296
+ config: this.definition.config,
1297
+ context,
1298
+ signal: context.signal,
1299
+ resolve: (token) => {
1300
+ if (!lease.active)
1301
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1302
+ return services.resolve(token);
1303
+ },
1304
+ acquire: (spec) => {
1305
+ try {
1306
+ if (!lease.active)
1307
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1308
+ owner.check();
1309
+ return resources.acquire(spec);
1310
+ } catch (error) {
1311
+ return observed2(Promise.reject(error));
1312
+ }
1313
+ },
1314
+ spawn: (childWork) => {
1315
+ if (!lease.active) {
1316
+ return observed2(Promise.reject(new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id)));
1317
+ }
1318
+ return spawn(childWork);
1319
+ }
1320
+ });
1321
+ const requireDirect = () => {
1322
+ if (activeFrame() !== frame)
1323
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1324
+ };
1325
+ const boundary = Object.freeze({
1326
+ finalize: (work) => {
1327
+ try {
1328
+ if (identityFrame() !== frame)
1329
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1330
+ return dispatch.finalize(work);
1331
+ } catch (error) {
1332
+ return observed2(Promise.reject(error));
1333
+ }
1334
+ },
1335
+ acquire: (spec) => {
1336
+ try {
1337
+ requireDirect();
1338
+ return resources.acquire(spec);
1339
+ } catch (error) {
1340
+ return observed2(Promise.reject(error));
1341
+ }
1342
+ },
1343
+ assertWithin: () => {
1344
+ const current = activeFrame();
1345
+ if (!current.path.includes(dispatch.path[dispatch.path.length - 1]))
1346
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1347
+ },
1348
+ bindNative: (work) => {
1349
+ requireDirect();
1350
+ if (typeof work !== "function")
1351
+ throw new TypeError("Native continuation must be a function.");
1352
+ return (...args) => {
1353
+ try {
1354
+ if (!lease.active)
1355
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1356
+ return this.taskStorage.run(frame, () => {
1357
+ owner.check();
1358
+ return observed2(work(...args));
1359
+ });
1360
+ } catch (error) {
1361
+ return observed2(Promise.reject(error));
1362
+ }
1363
+ };
1364
+ }
1365
+ });
1366
+ const bodyOperation = leasedOperation(() => body(scope, boundary), () => {
1367
+ lease.active = false;
1368
+ resources.seal();
1369
+ });
1370
+ return {
1371
+ promise: bodyOperation.promise,
1372
+ invoke: () => this.taskStorage.run(dispatch.bookkeeping ? undefined : frame, () => {
1373
+ if (!dispatch.enter)
1374
+ return bodyOperation.invoke();
1375
+ let started = false;
1376
+ let open = true;
1377
+ const protocolError = () => new Error("Owned invocation must run synchronously exactly once.");
1378
+ const invoke = () => {
1379
+ if (!open)
1380
+ throw protocolError();
1381
+ if (started) {
1382
+ const error = protocolError();
1383
+ dispatch.entryFailed(error);
1384
+ throw error;
1385
+ }
1386
+ started = true;
1387
+ return bodyOperation.invoke();
1388
+ };
1389
+ try {
1390
+ dispatch.enter(invoke);
1391
+ if (!started)
1392
+ bodyOperation.fail(protocolError());
1393
+ } catch (error) {
1394
+ if (started)
1395
+ dispatch.entryFailed(error);
1396
+ else
1397
+ bodyOperation.fail(error);
1398
+ } finally {
1399
+ open = false;
1400
+ }
1401
+ })
1402
+ };
1403
+ }, taskResources(), (work) => this.taskStorage.run(undefined, work)) : {
1404
+ invoked: false,
1405
+ retained: false,
1406
+ body: { ok: false, error: initialization.error },
1407
+ failures: []
1408
+ };
1409
+ const bindings = await this.taskStorage.run(undefined, () => executionResources.finalize(bindingCleanupContext));
1410
+ const failures = [];
1411
+ if (!initialization.ok && bindings.acquisitionFailures.length === 0) {
1412
+ failures.push(initialization.error);
1413
+ }
1414
+ for (const failure of bindings.acquisitionFailures)
1415
+ failures.push(failure);
1416
+ for (const failure of callbacks.failures)
1417
+ failures.push(failure);
1418
+ for (const failure of bindings.cleanupFailures)
1419
+ failures.push(failure);
1420
+ return completeExecution({ ...callbacks, failures });
1421
+ } finally {
1422
+ owner.dispose();
1423
+ }
1424
+ }
1425
+ commandSettled(promise) {
1426
+ this.commands.delete(promise);
1427
+ this.publish();
1428
+ }
1429
+ async startProviders() {
1430
+ try {
1431
+ await this.definition.services.start(this.services, this.cancellation.signal, {
1432
+ acquire: (group, spec, signal, validate) => this.journal.acquire(group, spec, signal, validate)
1433
+ });
1434
+ for (const provider of [...this.definition.providers, ...this.definition.transports]) {
1435
+ if (this.cancellation.signal.aborted)
1436
+ throw this.cancelled;
1437
+ let active = true;
1438
+ const acquisitions = [];
1439
+ const scope = Object.freeze({
1440
+ applicationId: this.id,
1441
+ config: this.definition.config,
1442
+ signal: this.cancellation.signal,
1443
+ resolve: (token) => {
1444
+ if (!active)
1445
+ throw new ApplicationStateError("APPLICATION_SCOPE_EXPIRED", this.id);
1446
+ return this.services.resolve(token);
1447
+ },
1448
+ acquire: (spec) => {
1449
+ if (!active || this.cancellation.signal.aborted) {
1450
+ return observed2(Promise.reject(this.cancelled));
1451
+ }
1452
+ const result = this.journal.acquire(this.providerGroups.get(provider), spec, this.cancellation.signal);
1453
+ acquisitions.push(result);
1454
+ return result;
1455
+ }
1456
+ });
1457
+ const operation = leasedOperation(() => provider.setup(scope), () => {
1458
+ active = false;
1459
+ });
1460
+ operation.invoke();
1461
+ await operation.promise;
1462
+ for (const acquisition of acquisitions)
1463
+ await acquisition;
1464
+ }
1465
+ if (this.cancellation.signal.aborted)
1466
+ throw this.cancelled;
1467
+ this.phase = "ready";
1468
+ this.boot = "ready";
1469
+ this.publish();
1470
+ this.startup?.resolve();
1471
+ } catch (error) {
1472
+ if (error !== this.cancelled) {
1473
+ this.recordPrimary(error);
1474
+ this.boot = "failed";
1475
+ }
1476
+ this.beginStop("startup-failed", this.definition.startupCleanupTimeoutMs);
1477
+ } finally {
1478
+ this.startupRunning = false;
1479
+ this.publish();
1480
+ }
1481
+ }
1482
+ beginStop(reason, timeoutMs) {
1483
+ if (this.stopping)
1484
+ return this.stopping.promise;
1485
+ this.stopping = deferred();
1486
+ this.phase = "stopping";
1487
+ if (this.boot === "pending" || this.boot === "not-started")
1488
+ this.boot = "cancelled";
1489
+ this.cleanup = "pending";
1490
+ const context = Object.freeze({ signal: this.cleanupCancellation.signal, reason });
1491
+ this.publish();
1492
+ this.stopTimer = setTimeout(() => {
1493
+ this.timedOut = true;
1494
+ this.cleanupCancellation.abort(new ApplicationStateError("APPLICATION_CLEANUP_DEADLINE", this.id));
1495
+ this.stopping?.resolve(this.result());
1496
+ this.rejectStartup();
1497
+ }, timeoutMs);
1498
+ Promise.resolve().then(() => this.taskStorage.run(undefined, () => this.finishCleanup(context)));
1499
+ this.cancellation.abort(this.cancelled);
1500
+ return this.stopping.promise;
1501
+ }
1502
+ async finishCleanup(context) {
1503
+ let unsafe = false;
1504
+ for (;; ) {
1505
+ const changed = this.changed.promise;
1506
+ if (!await this.journal.scanStop(context))
1507
+ unsafe = true;
1508
+ const view = this.journal.view();
1509
+ if (view.unsafe)
1510
+ unsafe = true;
1511
+ if (!this.startupRunning && view.pendingAcquisitions.length === 0 && !view.unstopped)
1512
+ break;
1513
+ await changed;
1514
+ }
1515
+ if (!await this.journal.drain(context))
1516
+ unsafe = true;
1517
+ while (this.commands.size > 0)
1518
+ await this.changed.promise;
1519
+ if (this.journal.view().unsafe)
1520
+ unsafe = true;
1521
+ if (!unsafe)
1522
+ await this.journal.flushAndClose(context);
1523
+ const retained = this.journal.view().retainedResources.length > 0;
1524
+ const failed = unsafe || retained || this.diagnostics.some((item) => item.kind === "cleanup");
1525
+ this.cleanup = failed ? "failed" : "clean";
1526
+ this.phase = this.boot === "failed" || failed ? "failed" : "stopped";
1527
+ clearTimeout(this.stopTimer);
1528
+ this.publish();
1529
+ const result = this.result();
1530
+ this.stopping?.resolve(result);
1531
+ this.completed.resolve(result);
1532
+ this.rejectStartup();
1533
+ }
1534
+ recordPrimary(error) {
1535
+ if (!this.hasPrimary) {
1536
+ this.hasPrimary = true;
1537
+ this.primary = error;
1538
+ }
1539
+ this.diagnostics.push(Object.freeze({ kind: "startup", code: "APPLICATION_START_FAILED", error }));
1540
+ }
1541
+ rejectStartup() {
1542
+ if (!this.startup || this.boot === "ready")
1543
+ return;
1544
+ const primary = this.hasPrimary ? this.primary : this.cancelled;
1545
+ const cleanupErrors = this.diagnostics.filter((item) => item.kind === "cleanup").map((item) => item.error);
1546
+ this.startup.reject(cleanupErrors.length > 0 ? new AggregateError([primary, ...cleanupErrors], "Application startup and cleanup failed.", {
1547
+ cause: primary
1548
+ }) : primary);
1549
+ }
1550
+ result() {
1551
+ return Object.freeze({
1552
+ successful: this.cleanup === "clean",
1553
+ timedOut: this.timedOut,
1554
+ snapshot: this.snapshot
1555
+ });
1556
+ }
1557
+ makeSnapshot() {
1558
+ const view = this.journal.view();
1559
+ return Object.freeze({
1560
+ phase: this.phase,
1561
+ boot: this.boot,
1562
+ cleanup: this.cleanup,
1563
+ pendingAcquisitions: view.pendingAcquisitions,
1564
+ retainedResources: view.retainedResources,
1565
+ errors: Object.freeze([...this.diagnostics])
1566
+ });
1567
+ }
1568
+ publish() {
1569
+ this.snapshot = this.makeSnapshot();
1570
+ const changed = this.changed;
1571
+ this.changed = deferred();
1572
+ changed.resolve();
1573
+ }
1574
+ }
1575
+ function createApplication(definition) {
1576
+ return new OwnedApplication(normalize(definition));
1577
+ }
1578
+ export {
1579
+ CORE_EXECUTION_CONTEXT_TOKEN2 as CORE_EXECUTION_CONTEXT_TOKEN,
1580
+ aliasService2 as aliasService,
1581
+ createApplication,
1582
+ resourceService2 as resourceService,
1583
+ service2 as service,
1584
+ valueService2 as valueService
1585
+ };