@bluelibs/runner 5.1.0 → 5.2.1

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 (314) hide show
  1. package/README.md +25 -15
  2. package/dist/browser/index.cjs +851 -478
  3. package/dist/browser/index.cjs.map +1 -1
  4. package/dist/browser/index.mjs +849 -478
  5. package/dist/browser/index.mjs.map +1 -1
  6. package/dist/edge/index.cjs +851 -478
  7. package/dist/edge/index.cjs.map +1 -1
  8. package/dist/edge/index.mjs +849 -478
  9. package/dist/edge/index.mjs.map +1 -1
  10. package/dist/node/node.cjs +1305 -583
  11. package/dist/node/node.cjs.map +1 -1
  12. package/dist/node/node.mjs +1299 -583
  13. package/dist/node/node.mjs.map +1 -1
  14. package/dist/types/define.d.ts +9 -0
  15. package/dist/types/definers/builders/asyncContext/fluent-builder.d.ts +6 -0
  16. package/dist/types/definers/builders/asyncContext/fluent-builder.interface.d.ts +9 -0
  17. package/dist/types/definers/builders/asyncContext/index.d.ts +10 -0
  18. package/dist/types/definers/builders/asyncContext/types.d.ts +13 -0
  19. package/dist/types/definers/builders/asyncContext/utils.d.ts +5 -0
  20. package/dist/types/definers/builders/asyncContext.d.ts +1 -0
  21. package/dist/types/definers/builders/core.d.ts +30 -0
  22. package/dist/types/definers/builders/error/fluent-builder.d.ts +7 -0
  23. package/dist/types/definers/builders/error/fluent-builder.interface.d.ts +10 -0
  24. package/dist/types/definers/builders/error/index.d.ts +11 -0
  25. package/dist/types/definers/builders/error/types.d.ts +14 -0
  26. package/dist/types/definers/builders/error/utils.d.ts +6 -0
  27. package/dist/types/definers/builders/error.d.ts +1 -0
  28. package/dist/types/definers/builders/event/fluent-builder.d.ts +7 -0
  29. package/dist/types/definers/builders/event/fluent-builder.interface.d.ts +18 -0
  30. package/dist/types/definers/builders/event/index.d.ts +10 -0
  31. package/dist/types/definers/builders/event/types.d.ts +8 -0
  32. package/dist/types/definers/builders/event/utils.d.ts +9 -0
  33. package/dist/types/definers/builders/event.d.ts +1 -0
  34. package/dist/types/definers/builders/hook/fluent-builder.d.ts +8 -0
  35. package/dist/types/definers/builders/hook/fluent-builder.interface.d.ts +27 -0
  36. package/dist/types/definers/builders/hook/index.d.ts +12 -0
  37. package/dist/types/definers/builders/hook/types.d.ts +14 -0
  38. package/dist/types/definers/builders/hook/utils.d.ts +14 -0
  39. package/dist/types/definers/builders/hook.d.ts +1 -0
  40. package/dist/types/definers/builders/middleware/index.d.ts +19 -0
  41. package/dist/types/definers/builders/middleware/resource.d.ts +7 -0
  42. package/dist/types/definers/builders/middleware/resource.interface.d.ts +18 -0
  43. package/dist/types/definers/builders/middleware/task.d.ts +7 -0
  44. package/dist/types/definers/builders/middleware/task.interface.d.ts +18 -0
  45. package/dist/types/definers/builders/middleware/types.d.ts +13 -0
  46. package/dist/types/definers/builders/middleware/utils.d.ts +18 -0
  47. package/dist/types/definers/builders/middleware.d.ts +1 -0
  48. package/dist/types/definers/builders/override/hook.d.ts +16 -0
  49. package/dist/types/definers/builders/override/index.d.ts +11 -0
  50. package/dist/types/definers/builders/override/resource-middleware.d.ts +3 -0
  51. package/dist/types/definers/builders/override/resource.d.ts +3 -0
  52. package/dist/types/definers/builders/override/task-middleware.d.ts +3 -0
  53. package/dist/types/definers/builders/override/task.d.ts +3 -0
  54. package/dist/types/definers/builders/resource/fluent-builder.d.ts +8 -0
  55. package/dist/types/definers/builders/resource/fluent-builder.interface.d.ts +42 -0
  56. package/dist/types/definers/builders/resource/index.d.ts +13 -0
  57. package/dist/types/definers/builders/resource/types.d.ts +37 -0
  58. package/dist/types/definers/builders/resource/utils.d.ts +26 -0
  59. package/dist/types/definers/builders/resource.d.ts +1 -0
  60. package/dist/types/definers/builders/tag/fluent-builder.d.ts +6 -0
  61. package/dist/types/definers/builders/tag/fluent-builder.interface.d.ts +8 -0
  62. package/dist/types/definers/builders/tag/index.d.ts +10 -0
  63. package/dist/types/definers/builders/tag/types.d.ts +12 -0
  64. package/dist/types/definers/builders/tag/utils.d.ts +5 -0
  65. package/dist/types/definers/builders/tag.d.ts +1 -0
  66. package/dist/types/definers/builders/task/fluent-builder.d.ts +8 -0
  67. package/dist/types/definers/builders/task/fluent-builder.interface.d.ts +33 -0
  68. package/dist/types/definers/builders/task/index.d.ts +21 -0
  69. package/dist/types/definers/builders/task/phantom-builder.d.ts +8 -0
  70. package/dist/types/definers/builders/task/phantom-builder.interface.d.ts +31 -0
  71. package/dist/types/definers/builders/task/types.d.ts +34 -0
  72. package/dist/types/definers/builders/task/utils.d.ts +14 -0
  73. package/dist/types/definers/builders/task.d.ts +1 -0
  74. package/dist/types/definers/builders/task.phantom.d.ts +1 -0
  75. package/dist/types/definers/builders/utils.d.ts +4 -0
  76. package/dist/types/definers/defineAsyncContext.d.ts +15 -0
  77. package/dist/types/definers/defineError.d.ts +27 -0
  78. package/dist/types/definers/defineEvent.d.ts +2 -0
  79. package/dist/types/definers/defineHook.d.ts +6 -0
  80. package/dist/types/definers/defineOverride.d.ts +12 -0
  81. package/dist/types/definers/defineResource.d.ts +2 -0
  82. package/dist/types/definers/defineResourceMiddleware.d.ts +2 -0
  83. package/dist/types/definers/defineTag.d.ts +12 -0
  84. package/dist/types/definers/defineTask.d.ts +18 -0
  85. package/dist/types/definers/defineTaskMiddleware.d.ts +2 -0
  86. package/dist/types/definers/middlewareConfig.d.ts +1 -0
  87. package/dist/types/definers/resourceFork.d.ts +13 -0
  88. package/dist/types/definers/tools.d.ts +53 -0
  89. package/dist/types/defs.d.ts +33 -0
  90. package/dist/types/errors.d.ts +75 -0
  91. package/dist/types/globals/debug.d.ts +10 -0
  92. package/dist/types/globals/globalEvents.d.ts +8 -0
  93. package/dist/types/globals/globalMiddleware.d.ts +97 -0
  94. package/dist/types/globals/globalResources.d.ts +64 -0
  95. package/dist/types/globals/globalTags.d.ts +12 -0
  96. package/dist/types/globals/middleware/cache.middleware.d.ts +36 -0
  97. package/dist/types/globals/middleware/circuitBreaker.middleware.d.ts +56 -0
  98. package/dist/types/globals/middleware/concurrency.middleware.d.ts +47 -0
  99. package/dist/types/globals/middleware/fallback.middleware.d.ts +23 -0
  100. package/dist/types/globals/middleware/rateLimit.middleware.d.ts +47 -0
  101. package/dist/types/globals/middleware/requireContext.middleware.d.ts +5 -0
  102. package/dist/types/globals/middleware/retry.middleware.d.ts +31 -0
  103. package/dist/types/globals/middleware/temporal.middleware.d.ts +48 -0
  104. package/dist/types/globals/middleware/timeout.middleware.d.ts +24 -0
  105. package/dist/types/globals/middleware/tunnel.middleware.d.ts +3 -0
  106. package/dist/types/globals/resources/debug/debug.resource.d.ts +7 -0
  107. package/dist/types/globals/resources/debug/debug.tag.d.ts +2 -0
  108. package/dist/types/globals/resources/debug/debugConfig.resource.d.ts +22 -0
  109. package/dist/types/globals/resources/debug/executionTracker.middleware.d.ts +50 -0
  110. package/dist/types/globals/resources/debug/globalEvent.hook.d.ts +27 -0
  111. package/dist/types/globals/resources/debug/hook.hook.d.ts +30 -0
  112. package/dist/types/globals/resources/debug/index.d.ts +6 -0
  113. package/dist/types/globals/resources/debug/middleware.hook.d.ts +30 -0
  114. package/dist/types/globals/resources/debug/types.d.ts +25 -0
  115. package/dist/types/globals/resources/debug/utils.d.ts +2 -0
  116. package/dist/types/globals/resources/httpClientFactory.resource.d.ts +28 -0
  117. package/dist/types/globals/resources/queue.resource.d.ts +10 -0
  118. package/dist/types/globals/resources/tunnel/error-utils.d.ts +1 -0
  119. package/dist/types/globals/resources/tunnel/plan.d.ts +19 -0
  120. package/dist/types/globals/resources/tunnel/protocol.d.ts +48 -0
  121. package/dist/types/globals/resources/tunnel/tunnel.policy.tag.d.ts +26 -0
  122. package/dist/types/globals/resources/tunnel/tunnel.tag.d.ts +2 -0
  123. package/dist/types/globals/resources/tunnel/types.d.ts +48 -0
  124. package/dist/types/globals/tunnels/index.d.ts +23 -0
  125. package/dist/types/globals/types.d.ts +15 -0
  126. package/dist/types/http-client.d.ts +26 -0
  127. package/dist/types/http-fetch-tunnel.resource.d.ts +11 -0
  128. package/dist/types/index.d.ts +44 -0
  129. package/dist/types/models/DependencyProcessor.d.ts +46 -0
  130. package/dist/types/models/EventManager.d.ts +115 -0
  131. package/dist/types/models/ExecutionJournal.d.ts +35 -0
  132. package/dist/types/models/LogPrinter.d.ts +56 -0
  133. package/dist/types/models/Logger.d.ts +85 -0
  134. package/dist/types/models/MiddlewareManager.d.ts +73 -0
  135. package/dist/types/models/OverrideManager.d.ts +13 -0
  136. package/dist/types/models/Queue.d.ts +40 -0
  137. package/dist/types/models/ResourceInitializer.d.ts +20 -0
  138. package/dist/types/models/RunResult.d.ts +41 -0
  139. package/dist/types/models/Semaphore.d.ts +80 -0
  140. package/dist/types/models/Store.d.ts +76 -0
  141. package/dist/types/models/StoreRegistry.d.ts +49 -0
  142. package/dist/types/models/StoreValidator.d.ts +8 -0
  143. package/dist/types/models/TaskRunner.d.ts +28 -0
  144. package/dist/types/models/UnhandledError.d.ts +11 -0
  145. package/dist/types/models/event/CycleContext.d.ts +9 -0
  146. package/dist/types/models/event/EmissionExecutor.d.ts +11 -0
  147. package/dist/types/models/event/InterceptorPipeline.d.ts +5 -0
  148. package/dist/types/models/event/ListenerRegistry.d.ts +31 -0
  149. package/dist/types/models/event/types.d.ts +50 -0
  150. package/dist/types/models/index.d.ts +13 -0
  151. package/dist/types/models/middleware/InterceptorRegistry.d.ts +56 -0
  152. package/dist/types/models/middleware/MiddlewareResolver.d.ts +31 -0
  153. package/dist/types/models/middleware/ResourceMiddlewareComposer.d.ts +34 -0
  154. package/dist/types/models/middleware/TaskMiddlewareComposer.d.ts +44 -0
  155. package/dist/types/models/middleware/ValidationHelper.d.ts +20 -0
  156. package/dist/types/models/middleware/index.d.ts +6 -0
  157. package/dist/types/models/middleware/types.d.ts +10 -0
  158. package/dist/types/models/utils/findCircularDependencies.d.ts +16 -0
  159. package/dist/types/models/utils/safeStringify.d.ts +3 -0
  160. package/dist/types/node/durable/bus/MemoryEventBus.d.ts +7 -0
  161. package/dist/types/node/durable/bus/NoopEventBus.d.ts +6 -0
  162. package/dist/types/node/durable/bus/RedisEventBus.d.ts +30 -0
  163. package/dist/types/node/durable/core/CronParser.d.ts +15 -0
  164. package/dist/types/node/durable/core/DurableContext.d.ts +64 -0
  165. package/dist/types/node/durable/core/DurableOperator.d.ts +47 -0
  166. package/dist/types/node/durable/core/DurableResource.d.ts +80 -0
  167. package/dist/types/node/durable/core/DurableService.d.ts +73 -0
  168. package/dist/types/node/durable/core/DurableWorker.d.ts +19 -0
  169. package/dist/types/node/durable/core/StepBuilder.d.ts +23 -0
  170. package/dist/types/node/durable/core/audit.d.ts +152 -0
  171. package/dist/types/node/durable/core/createRunnerDurableRuntime.d.ts +18 -0
  172. package/dist/types/node/durable/core/durable-context/DurableContext.audit.d.ts +14 -0
  173. package/dist/types/node/durable/core/durable-context/DurableContext.determinism.d.ts +13 -0
  174. package/dist/types/node/durable/core/durable-context/DurableContext.emit.d.ts +16 -0
  175. package/dist/types/node/durable/core/durable-context/DurableContext.sleep.d.ts +16 -0
  176. package/dist/types/node/durable/core/durable-context/DurableContext.steps.d.ts +25 -0
  177. package/dist/types/node/durable/core/durable-context/DurableContext.switch.d.ts +22 -0
  178. package/dist/types/node/durable/core/durable-context/DurableContext.waitForSignal.d.ts +23 -0
  179. package/dist/types/node/durable/core/flowShape.d.ts +50 -0
  180. package/dist/types/node/durable/core/ids.d.ts +11 -0
  181. package/dist/types/node/durable/core/index.d.ts +11 -0
  182. package/dist/types/node/durable/core/interfaces/bus.d.ts +13 -0
  183. package/dist/types/node/durable/core/interfaces/context.d.ts +105 -0
  184. package/dist/types/node/durable/core/interfaces/queue.d.ts +17 -0
  185. package/dist/types/node/durable/core/interfaces/service.d.ts +146 -0
  186. package/dist/types/node/durable/core/interfaces/store.d.ts +66 -0
  187. package/dist/types/node/durable/core/managers/AuditLogger.d.ts +29 -0
  188. package/dist/types/node/durable/core/managers/ExecutionManager.d.ts +48 -0
  189. package/dist/types/node/durable/core/managers/PollingManager.d.ts +48 -0
  190. package/dist/types/node/durable/core/managers/ScheduleManager.d.ts +33 -0
  191. package/dist/types/node/durable/core/managers/SignalHandler.d.ts +25 -0
  192. package/dist/types/node/durable/core/managers/TaskRegistry.d.ts +16 -0
  193. package/dist/types/node/durable/core/managers/WaitManager.d.ts +26 -0
  194. package/dist/types/node/durable/core/managers/index.d.ts +7 -0
  195. package/dist/types/node/durable/core/resource.d.ts +14 -0
  196. package/dist/types/node/durable/core/types.d.ts +84 -0
  197. package/dist/types/node/durable/core/utils.d.ts +28 -0
  198. package/dist/types/node/durable/dashboard/server.d.ts +20 -0
  199. package/dist/types/node/durable/emitters/runnerAuditEmitter.d.ts +6 -0
  200. package/dist/types/node/durable/events.d.ts +76 -0
  201. package/dist/types/node/durable/index.d.ts +34 -0
  202. package/dist/types/node/durable/optionalDeps/amqplib.d.ts +1 -0
  203. package/dist/types/node/durable/optionalDeps/ioredis.d.ts +1 -0
  204. package/dist/types/node/durable/queue/MemoryQueue.d.ts +12 -0
  205. package/dist/types/node/durable/queue/RabbitMQQueue.d.ts +30 -0
  206. package/dist/types/node/durable/resources/isolation.d.ts +15 -0
  207. package/dist/types/node/durable/resources/memoryDurableResource.d.ts +21 -0
  208. package/dist/types/node/durable/resources/redisDurableResource.d.ts +35 -0
  209. package/dist/types/node/durable/store/MemoryStore.d.ts +56 -0
  210. package/dist/types/node/durable/store/RedisStore.d.ts +89 -0
  211. package/dist/types/node/durable/test-utils.d.ts +29 -0
  212. package/dist/types/node/exposure/allowList.d.ts +3 -0
  213. package/dist/types/node/exposure/authenticator.d.ts +16 -0
  214. package/dist/types/node/exposure/cors.d.ts +4 -0
  215. package/dist/types/node/exposure/createNodeExposure.d.ts +2 -0
  216. package/dist/types/node/exposure/exposureServer.d.ts +18 -0
  217. package/dist/types/node/exposure/handlers/contextWrapper.d.ts +18 -0
  218. package/dist/types/node/exposure/handlers/errorHandlers.d.ts +23 -0
  219. package/dist/types/node/exposure/handlers/eventHandler.d.ts +20 -0
  220. package/dist/types/node/exposure/handlers/taskHandler.d.ts +24 -0
  221. package/dist/types/node/exposure/httpResponse.d.ts +10 -0
  222. package/dist/types/node/exposure/index.d.ts +3 -0
  223. package/dist/types/node/exposure/logging.d.ts +4 -0
  224. package/dist/types/node/exposure/multipart.d.ts +36 -0
  225. package/dist/types/node/exposure/requestBody.d.ts +11 -0
  226. package/dist/types/node/exposure/requestContext.d.ts +17 -0
  227. package/dist/types/node/exposure/requestHandlers.d.ts +29 -0
  228. package/dist/types/node/exposure/resource.d.ts +12 -0
  229. package/dist/types/node/exposure/resourceTypes.d.ts +73 -0
  230. package/dist/types/node/exposure/router.d.ts +17 -0
  231. package/dist/types/node/exposure/serverLifecycle.d.ts +13 -0
  232. package/dist/types/node/exposure/types.d.ts +45 -0
  233. package/dist/types/node/exposure/utils.d.ts +17 -0
  234. package/dist/types/node/files/createNodeFile.d.ts +9 -0
  235. package/dist/types/node/files/index.d.ts +4 -0
  236. package/dist/types/node/files/inputFile.model.d.ts +22 -0
  237. package/dist/types/node/files/inputFile.utils.d.ts +14 -0
  238. package/dist/types/node/http/http-mixed-client.d.ts +45 -0
  239. package/dist/types/node/http/http-mixed-client.factory.resource.d.ts +17 -0
  240. package/dist/types/node/http/http-smart-client.factory.resource.d.ts +16 -0
  241. package/dist/types/node/http/http-smart-client.model.d.ts +27 -0
  242. package/dist/types/node/http/index.d.ts +4 -0
  243. package/dist/types/node/index.d.ts +1 -0
  244. package/dist/types/node/node.d.ts +193 -0
  245. package/dist/types/node/platform/createFile.d.ts +9 -0
  246. package/dist/types/node/tunnel/allowlist.d.ts +7 -0
  247. package/dist/types/node/tunnel/index.d.ts +2 -0
  248. package/dist/types/node/upload/manifest.d.ts +23 -0
  249. package/dist/types/platform/adapters/browser.d.ts +14 -0
  250. package/dist/types/platform/adapters/edge.d.ts +5 -0
  251. package/dist/types/platform/adapters/node-als.d.ts +1 -0
  252. package/dist/types/platform/adapters/node.d.ts +15 -0
  253. package/dist/types/platform/adapters/universal-generic.d.ts +14 -0
  254. package/dist/types/platform/adapters/universal.d.ts +18 -0
  255. package/dist/types/platform/createFile.d.ts +10 -0
  256. package/dist/types/platform/createWebFile.d.ts +11 -0
  257. package/dist/types/platform/factory.d.ts +2 -0
  258. package/dist/types/platform/index.d.ts +27 -0
  259. package/dist/types/platform/types.d.ts +31 -0
  260. package/dist/types/processHooks.d.ts +2 -0
  261. package/dist/types/public-types.d.ts +13 -0
  262. package/dist/types/public.d.ts +210 -0
  263. package/dist/types/run.d.ts +14 -0
  264. package/dist/types/serializer/Serializer.d.ts +84 -0
  265. package/dist/types/serializer/binary-builtins.d.ts +5 -0
  266. package/dist/types/serializer/builtins.d.ts +47 -0
  267. package/dist/types/serializer/deserializer.d.ts +27 -0
  268. package/dist/types/serializer/error-url-builtins.d.ts +13 -0
  269. package/dist/types/serializer/graph-serializer.d.ts +27 -0
  270. package/dist/types/serializer/index.d.ts +6 -0
  271. package/dist/types/serializer/option-normalizers.d.ts +2 -0
  272. package/dist/types/serializer/regexp-validator.d.ts +34 -0
  273. package/dist/types/serializer/serialize-utils.d.ts +15 -0
  274. package/dist/types/serializer/special-values.d.ts +20 -0
  275. package/dist/types/serializer/tree-serializer.d.ts +20 -0
  276. package/dist/types/serializer/type-registry.d.ts +58 -0
  277. package/dist/types/serializer/types.d.ts +126 -0
  278. package/dist/types/serializer/validation.d.ts +34 -0
  279. package/dist/types/testing.d.ts +19 -0
  280. package/dist/types/tools/detectRunnerMode.d.ts +9 -0
  281. package/dist/types/tools/getCallerFile.d.ts +1 -0
  282. package/dist/types/tools/throws.d.ts +7 -0
  283. package/dist/types/tunnels/buildUniversalManifest.d.ts +24 -0
  284. package/dist/types/types/asyncContext.d.ts +41 -0
  285. package/dist/types/types/contracts.d.ts +62 -0
  286. package/dist/types/types/error.d.ts +39 -0
  287. package/dist/types/types/event.d.ts +79 -0
  288. package/dist/types/types/executionJournal.d.ts +29 -0
  289. package/dist/types/types/hook.d.ts +23 -0
  290. package/dist/types/types/inputFile.d.ts +34 -0
  291. package/dist/types/types/meta.d.ts +22 -0
  292. package/dist/types/types/resource.d.ts +133 -0
  293. package/dist/types/types/resourceMiddleware.d.ts +48 -0
  294. package/dist/types/types/runner.d.ts +68 -0
  295. package/dist/types/types/storeTypes.d.ts +46 -0
  296. package/dist/types/types/symbols.d.ts +34 -0
  297. package/dist/types/types/tag.d.ts +45 -0
  298. package/dist/types/types/task.d.ts +76 -0
  299. package/dist/types/types/taskMiddleware.d.ts +55 -0
  300. package/dist/types/types/utilities.d.ts +125 -0
  301. package/dist/universal/index.cjs +851 -476
  302. package/dist/universal/index.cjs.map +1 -1
  303. package/dist/universal/index.mjs +849 -476
  304. package/dist/universal/index.mjs.map +1 -1
  305. package/package.json +15 -14
  306. package/readmes/AI.md +30 -9
  307. package/dist/browser/index.d.mts +0 -2919
  308. package/dist/browser/index.d.ts +0 -2919
  309. package/dist/edge/index.d.mts +0 -2919
  310. package/dist/edge/index.d.ts +0 -2919
  311. package/dist/node/node.d.mts +0 -4622
  312. package/dist/node/node.d.ts +0 -4622
  313. package/dist/universal/index.d.mts +0 -2919
  314. package/dist/universal/index.d.ts +0 -2919
@@ -2666,10 +2666,10 @@ var require_bom_handling = __commonJS({
2666
2666
  // node_modules/raw-body/node_modules/iconv-lite/lib/helpers/merge-exports.js
2667
2667
  var require_merge_exports = __commonJS({
2668
2668
  "node_modules/raw-body/node_modules/iconv-lite/lib/helpers/merge-exports.js"(exports, module) {
2669
- var hasOwn2 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
2669
+ var hasOwn3 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
2670
2670
  function mergeModules(target, module2) {
2671
2671
  for (var key in module2) {
2672
- if (hasOwn2(module2, key)) {
2672
+ if (hasOwn3(module2, key)) {
2673
2673
  target[key] = module2[key];
2674
2674
  }
2675
2675
  }
@@ -6640,10 +6640,10 @@ var require_bom_handling2 = __commonJS({
6640
6640
  // node_modules/body-parser/node_modules/iconv-lite/lib/helpers/merge-exports.js
6641
6641
  var require_merge_exports2 = __commonJS({
6642
6642
  "node_modules/body-parser/node_modules/iconv-lite/lib/helpers/merge-exports.js"(exports, module) {
6643
- var hasOwn2 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
6643
+ var hasOwn3 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
6644
6644
  function mergeModules(target, module2) {
6645
6645
  for (var key in module2) {
6646
- if (hasOwn2(module2, key)) {
6646
+ if (hasOwn3(module2, key)) {
6647
6647
  target[key] = module2[key];
6648
6648
  }
6649
6649
  }
@@ -20967,11 +20967,11 @@ var require_object_inspect = __commonJS({
20967
20967
  return false;
20968
20968
  }
20969
20969
  __name(isBigInt, "isBigInt");
20970
- var hasOwn2 = Object.prototype.hasOwnProperty || function(key) {
20970
+ var hasOwn3 = Object.prototype.hasOwnProperty || function(key) {
20971
20971
  return key in this;
20972
20972
  };
20973
20973
  function has(obj, key) {
20974
- return hasOwn2.call(obj, key);
20974
+ return hasOwn3.call(obj, key);
20975
20975
  }
20976
20976
  __name(has, "has");
20977
20977
  function toStr(obj) {
@@ -21954,7 +21954,7 @@ var require_get_intrinsic = __commonJS({
21954
21954
  "%WeakSetPrototype%": ["WeakSet", "prototype"]
21955
21955
  };
21956
21956
  var bind = require_function_bind();
21957
- var hasOwn2 = require_hasown();
21957
+ var hasOwn3 = require_hasown();
21958
21958
  var $concat = bind.call($call, Array.prototype.concat);
21959
21959
  var $spliceApply = bind.call($apply, Array.prototype.splice);
21960
21960
  var $replace = bind.call($call, String.prototype.replace);
@@ -21979,11 +21979,11 @@ var require_get_intrinsic = __commonJS({
21979
21979
  var getBaseIntrinsic = /* @__PURE__ */ __name(function getBaseIntrinsic2(name, allowMissing) {
21980
21980
  var intrinsicName = name;
21981
21981
  var alias;
21982
- if (hasOwn2(LEGACY_ALIASES, intrinsicName)) {
21982
+ if (hasOwn3(LEGACY_ALIASES, intrinsicName)) {
21983
21983
  alias = LEGACY_ALIASES[intrinsicName];
21984
21984
  intrinsicName = "%" + alias[0] + "%";
21985
21985
  }
21986
- if (hasOwn2(INTRINSICS, intrinsicName)) {
21986
+ if (hasOwn3(INTRINSICS, intrinsicName)) {
21987
21987
  var value = INTRINSICS[intrinsicName];
21988
21988
  if (value === needsEval) {
21989
21989
  value = doEval(intrinsicName);
@@ -22032,7 +22032,7 @@ var require_get_intrinsic = __commonJS({
22032
22032
  }
22033
22033
  intrinsicBaseName += "." + part;
22034
22034
  intrinsicRealName = "%" + intrinsicBaseName + "%";
22035
- if (hasOwn2(INTRINSICS, intrinsicRealName)) {
22035
+ if (hasOwn3(INTRINSICS, intrinsicRealName)) {
22036
22036
  value = INTRINSICS[intrinsicRealName];
22037
22037
  } else if (value != null) {
22038
22038
  if (!(part in value)) {
@@ -22050,7 +22050,7 @@ var require_get_intrinsic = __commonJS({
22050
22050
  value = value[part];
22051
22051
  }
22052
22052
  } else {
22053
- isOwn = hasOwn2(value, part);
22053
+ isOwn = hasOwn3(value, part);
22054
22054
  value = value[part];
22055
22055
  }
22056
22056
  if (isOwn && !skipFurtherCaching) {
@@ -28647,88 +28647,227 @@ var symbolAsyncContext = Symbol.for(
28647
28647
  "runner.asyncContext"
28648
28648
  );
28649
28649
 
28650
- // src/platform/adapters/node-als.ts
28651
- async function loadAsyncLocalStorageClass() {
28652
- const mod = __require("async_hooks");
28653
- return mod.AsyncLocalStorage;
28650
+ // src/tools/getCallerFile.ts
28651
+ function isNodeInline() {
28652
+ return typeof process !== "undefined" && typeof process?.versions?.node === "string";
28654
28653
  }
28655
- __name(loadAsyncLocalStorageClass, "loadAsyncLocalStorageClass");
28656
-
28657
- // src/platform/adapters/node.ts
28658
- var NodePlatformAdapter = class {
28659
- constructor() {
28660
- this.id = "node";
28661
- this.setTimeout = globalThis.setTimeout;
28662
- this.clearTimeout = globalThis.clearTimeout;
28663
- }
28664
- static {
28665
- __name(this, "NodePlatformAdapter");
28666
- }
28667
- async init() {
28668
- this.alsClass = await loadAsyncLocalStorageClass();
28669
- }
28670
- onUncaughtException(handler) {
28671
- const h = /* @__PURE__ */ __name((error2) => handler(error2), "h");
28672
- process.on("uncaughtException", h);
28673
- return () => process.off("uncaughtException", h);
28674
- }
28675
- onUnhandledRejection(handler) {
28676
- const h = /* @__PURE__ */ __name((reason) => handler(reason), "h");
28677
- process.on("unhandledRejection", h);
28678
- return () => process.off("unhandledRejection", h);
28679
- }
28680
- onShutdownSignal(handler) {
28681
- process.on("SIGINT", handler);
28682
- process.on("SIGTERM", handler);
28683
- return () => {
28684
- process.off("SIGINT", handler);
28685
- process.off("SIGTERM", handler);
28686
- };
28687
- }
28688
- exit(code) {
28689
- process.exit(code);
28690
- }
28691
- getEnv(key) {
28692
- return process.env[key];
28693
- }
28694
- hasAsyncLocalStorage() {
28695
- return true;
28654
+ __name(isNodeInline, "isNodeInline");
28655
+ function getCallerFile() {
28656
+ const originalPrepare = Error.prepareStackTrace;
28657
+ try {
28658
+ if (isNodeInline()) {
28659
+ const err = new Error();
28660
+ Error.prepareStackTrace = (_err, stack2) => stack2;
28661
+ const stack = err.stack;
28662
+ stack.shift();
28663
+ stack.shift();
28664
+ const candidate = stack.shift();
28665
+ const file = candidate?.getFileName?.();
28666
+ return file;
28667
+ }
28668
+ return "unknown";
28669
+ } finally {
28670
+ Error.prepareStackTrace = originalPrepare;
28696
28671
  }
28697
- createAsyncLocalStorage() {
28698
- let instance;
28699
- const ensure = /* @__PURE__ */ __name(() => {
28700
- if (!this.alsClass) {
28701
- let als;
28702
- const forceNoop = typeof process !== "undefined" && !!process.env?.RUNNER_FORCE_NOOP_ALS;
28703
- if (!forceNoop) {
28704
- try {
28705
- const mod = __require("async_hooks");
28706
- als = mod?.AsyncLocalStorage;
28707
- } catch (_) {
28708
- als = void 0;
28709
- }
28710
- }
28711
- this.alsClass = als || class NoopAsyncLocalStorage {
28712
- static {
28713
- __name(this, "NoopAsyncLocalStorage");
28714
- }
28715
- getStore() {
28716
- return void 0;
28717
- }
28718
- run(_store, callback) {
28719
- return callback();
28720
- }
28721
- };
28672
+ }
28673
+ __name(getCallerFile, "getCallerFile");
28674
+
28675
+ // src/defs.ts
28676
+ var defs_exports = {};
28677
+ __export(defs_exports, {
28678
+ CONTRACT: () => CONTRACT,
28679
+ HookDependencyState: () => HookDependencyState,
28680
+ RunnerMode: () => RunnerMode,
28681
+ isOneOf: () => isOneOf,
28682
+ onAnyOf: () => onAnyOf,
28683
+ symbolAsyncContext: () => symbolAsyncContext,
28684
+ symbolError: () => symbolError,
28685
+ symbolEvent: () => symbolEvent,
28686
+ symbolFilePath: () => symbolFilePath,
28687
+ symbolHook: () => symbolHook,
28688
+ symbolMiddleware: () => symbolMiddleware,
28689
+ symbolMiddlewareConfigured: () => symbolMiddlewareConfigured,
28690
+ symbolOptionalDependency: () => symbolOptionalDependency,
28691
+ symbolPhantomTask: () => symbolPhantomTask,
28692
+ symbolResource: () => symbolResource,
28693
+ symbolResourceForkedFrom: () => symbolResourceForkedFrom,
28694
+ symbolResourceMiddleware: () => symbolResourceMiddleware,
28695
+ symbolResourceWithConfig: () => symbolResourceWithConfig,
28696
+ symbolTag: () => symbolTag,
28697
+ symbolTagConfigured: () => symbolTagConfigured,
28698
+ symbolTask: () => symbolTask,
28699
+ symbolTaskMiddleware: () => symbolTaskMiddleware,
28700
+ symbolTunneledBy: () => symbolTunneledBy
28701
+ });
28702
+
28703
+ // src/types/event.ts
28704
+ function onAnyOf(...defs) {
28705
+ return defs;
28706
+ }
28707
+ __name(onAnyOf, "onAnyOf");
28708
+ function isOneOf(emission, defs) {
28709
+ return defs.some((d) => d.id === emission.id);
28710
+ }
28711
+ __name(isOneOf, "isOneOf");
28712
+
28713
+ // src/types/runner.ts
28714
+ var RunnerMode = /* @__PURE__ */ ((RunnerMode2) => {
28715
+ RunnerMode2["TEST"] = "test";
28716
+ RunnerMode2["DEV"] = "dev";
28717
+ RunnerMode2["PROD"] = "prod";
28718
+ return RunnerMode2;
28719
+ })(RunnerMode || {});
28720
+
28721
+ // src/types/contracts.ts
28722
+ var CONTRACT = Symbol.for("runner.contract");
28723
+
28724
+ // src/types/storeTypes.ts
28725
+ var HookDependencyState = /* @__PURE__ */ ((HookDependencyState2) => {
28726
+ HookDependencyState2["Pending"] = "pending";
28727
+ HookDependencyState2["Computing"] = "computing";
28728
+ HookDependencyState2["Ready"] = "ready";
28729
+ return HookDependencyState2;
28730
+ })(HookDependencyState || {});
28731
+
28732
+ // src/definers/tools.ts
28733
+ function isTask(definition) {
28734
+ return definition && definition[symbolTask];
28735
+ }
28736
+ __name(isTask, "isTask");
28737
+ function isResource(definition) {
28738
+ return definition && definition[symbolResource];
28739
+ }
28740
+ __name(isResource, "isResource");
28741
+ function isResourceWithConfig(definition) {
28742
+ return definition && definition[symbolResourceWithConfig];
28743
+ }
28744
+ __name(isResourceWithConfig, "isResourceWithConfig");
28745
+ function isEvent(definition) {
28746
+ return definition && definition[symbolEvent];
28747
+ }
28748
+ __name(isEvent, "isEvent");
28749
+ function isHook(definition) {
28750
+ return definition && definition[symbolHook];
28751
+ }
28752
+ __name(isHook, "isHook");
28753
+ function isTaskMiddleware(definition) {
28754
+ return definition && definition[symbolTaskMiddleware];
28755
+ }
28756
+ __name(isTaskMiddleware, "isTaskMiddleware");
28757
+ function isResourceMiddleware(definition) {
28758
+ return definition && definition[symbolResourceMiddleware];
28759
+ }
28760
+ __name(isResourceMiddleware, "isResourceMiddleware");
28761
+ function isTag(definition) {
28762
+ return definition && definition[symbolTag];
28763
+ }
28764
+ __name(isTag, "isTag");
28765
+ function isOptional(definition) {
28766
+ return definition && definition[symbolOptionalDependency];
28767
+ }
28768
+ __name(isOptional, "isOptional");
28769
+ function isError(definition) {
28770
+ return Boolean(definition && definition[symbolError]);
28771
+ }
28772
+ __name(isError, "isError");
28773
+ function isAsyncContext(definition) {
28774
+ return Boolean(definition && definition[symbolAsyncContext]);
28775
+ }
28776
+ __name(isAsyncContext, "isAsyncContext");
28777
+
28778
+ // src/tools/throws.ts
28779
+ function invalidThrowsEntryError(owner, item) {
28780
+ const got = item === null ? "null" : Array.isArray(item) ? "array" : typeof item === "object" ? "object" : typeof item;
28781
+ return new Error(
28782
+ `Invalid throws entry for ${owner.kind} ${owner.id}: expected error id string or Error helper, got ${got}`
28783
+ );
28784
+ }
28785
+ __name(invalidThrowsEntryError, "invalidThrowsEntryError");
28786
+ function toErrorIdList(owner, list) {
28787
+ const ids = [];
28788
+ const seen = /* @__PURE__ */ new Set();
28789
+ for (const item of list) {
28790
+ let id2;
28791
+ if (typeof item === "string") {
28792
+ if (item.trim().length === 0) {
28793
+ throw invalidThrowsEntryError(owner, item);
28722
28794
  }
28723
- return instance ??= new this.alsClass();
28724
- }, "ensure");
28725
- return {
28726
- getStore: /* @__PURE__ */ __name(() => ensure().getStore(), "getStore"),
28727
- run: /* @__PURE__ */ __name((store2, callback) => ensure().run(store2, callback), "run")
28728
- };
28795
+ id2 = item;
28796
+ } else if (isError(item)) {
28797
+ id2 = item.id;
28798
+ if (typeof id2 !== "string" || id2.trim().length === 0) {
28799
+ throw invalidThrowsEntryError(owner, item);
28800
+ }
28801
+ } else {
28802
+ throw invalidThrowsEntryError(owner, item);
28803
+ }
28804
+ if (seen.has(id2)) continue;
28805
+ seen.add(id2);
28806
+ ids.push(id2);
28729
28807
  }
28808
+ return ids;
28809
+ }
28810
+ __name(toErrorIdList, "toErrorIdList");
28811
+ function normalizeThrows(owner, throwsList) {
28812
+ if (throwsList === void 0) return void 0;
28813
+ return toErrorIdList(owner, throwsList);
28814
+ }
28815
+ __name(normalizeThrows, "normalizeThrows");
28816
+
28817
+ // src/definers/defineTask.ts
28818
+ function defineTask(taskConfig) {
28819
+ const filePath = getCallerFile();
28820
+ const id2 = taskConfig.id;
28821
+ return {
28822
+ [symbolTask]: true,
28823
+ [symbolFilePath]: filePath,
28824
+ id: id2,
28825
+ dependencies: taskConfig.dependencies || {},
28826
+ middleware: taskConfig.middleware || [],
28827
+ run: taskConfig.run,
28828
+ inputSchema: taskConfig.inputSchema,
28829
+ resultSchema: taskConfig.resultSchema,
28830
+ meta: taskConfig.meta || {},
28831
+ tags: taskConfig.tags || [],
28832
+ throws: normalizeThrows({ kind: "task", id: id2 }, taskConfig.throws),
28833
+ // autorun,
28834
+ optional() {
28835
+ return {
28836
+ inner: this,
28837
+ [symbolOptionalDependency]: true
28838
+ };
28839
+ }
28840
+ };
28841
+ }
28842
+ __name(defineTask, "defineTask");
28843
+ defineTask.phantom = (taskConfig) => {
28844
+ const taskDef = defineTask({
28845
+ ...taskConfig,
28846
+ run: /* @__PURE__ */ __name(async (_input) => {
28847
+ return void 0;
28848
+ }, "run")
28849
+ });
28850
+ taskDef[symbolPhantomTask] = true;
28851
+ return taskDef;
28730
28852
  };
28731
28853
 
28854
+ // src/definers/defineHook.ts
28855
+ function defineHook(hookDef) {
28856
+ const filePath = getCallerFile();
28857
+ return {
28858
+ [symbolHook]: true,
28859
+ [symbolFilePath]: filePath,
28860
+ id: hookDef.id,
28861
+ dependencies: hookDef.dependencies || {},
28862
+ on: hookDef.on,
28863
+ order: hookDef.order,
28864
+ run: hookDef.run,
28865
+ meta: hookDef.meta || {},
28866
+ tags: hookDef.tags || []
28867
+ };
28868
+ }
28869
+ __name(defineHook, "defineHook");
28870
+
28732
28871
  // src/errors.ts
28733
28872
  var errors_exports = {};
28734
28873
  __export(errors_exports, {
@@ -28770,9 +28909,10 @@ var RunnerError = class extends Error {
28770
28909
  var _a;
28771
28910
  _a = symbolError;
28772
28911
  var ErrorHelper = class {
28773
- constructor(definition) {
28912
+ constructor(definition, filePath) {
28774
28913
  this.definition = definition;
28775
28914
  this[_a] = true;
28915
+ this[symbolFilePath] = filePath;
28776
28916
  }
28777
28917
  static {
28778
28918
  __name(this, "ErrorHelper");
@@ -28795,11 +28935,15 @@ var ErrorHelper = class {
28795
28935
  };
28796
28936
  }
28797
28937
  };
28798
- function defineError(definition) {
28938
+ function defineError(definition, filePath) {
28799
28939
  if (!definition.format) {
28800
28940
  definition.format = (data) => `${JSON.stringify(data)}`;
28801
28941
  }
28802
- return new ErrorHelper(definition);
28942
+ const resolvedFilePath = filePath ?? getCallerFile();
28943
+ return new ErrorHelper(
28944
+ definition,
28945
+ resolvedFilePath
28946
+ );
28803
28947
  }
28804
28948
  __name(defineError, "defineError");
28805
28949
 
@@ -28837,14 +28981,17 @@ function makeErrorBuilder(state) {
28837
28981
  return makeErrorBuilder(next);
28838
28982
  },
28839
28983
  build() {
28840
- return defineError({
28841
- id: state.id,
28842
- serialize: state.serialize,
28843
- parse: state.parse,
28844
- dataSchema: state.dataSchema,
28845
- format: state.format,
28846
- meta: state.meta
28847
- });
28984
+ return defineError(
28985
+ {
28986
+ id: state.id,
28987
+ serialize: state.serialize,
28988
+ parse: state.parse,
28989
+ dataSchema: state.dataSchema,
28990
+ format: state.format,
28991
+ meta: state.meta
28992
+ },
28993
+ state.filePath
28994
+ );
28848
28995
  }
28849
28996
  };
28850
28997
  return builder;
@@ -28853,8 +29000,10 @@ __name(makeErrorBuilder, "makeErrorBuilder");
28853
29000
 
28854
29001
  // src/definers/builders/error/index.ts
28855
29002
  function errorBuilder(id2) {
29003
+ const filePath = getCallerFile();
28856
29004
  const initial = Object.freeze({
28857
29005
  id: id2,
29006
+ filePath,
28858
29007
  serialize: void 0,
28859
29008
  parse: void 0,
28860
29009
  dataSchema: void 0,
@@ -28865,103 +29014,87 @@ function errorBuilder(id2) {
28865
29014
  __name(errorBuilder, "errorBuilder");
28866
29015
  var error = errorBuilder;
28867
29016
 
28868
- // src/errors.ts
28869
- var duplicateRegistrationError = error("runner.errors.duplicateRegistration").format(
28870
- ({ type, id: id2 }) => `${type} "${id2.toString()}" already registered. You might have used the same 'id' in two different components or you may have registered the same element twice.`
28871
- ).build();
28872
- var dependencyNotFoundError = error("runner.errors.dependencyNotFound").format(
28873
- ({ key }) => `Dependency ${key.toString()} not found. Did you forget to register it through a resource?`
28874
- ).build();
28875
- var unknownItemTypeError = error(
28876
- "runner.errors.unknownItemType"
28877
- ).format(
28878
- ({ item }) => `Unknown item type: ${String(
28879
- item
28880
- )}. Please ensure you are not using different versions of '@bluelibs/runner'`
28881
- ).build();
28882
- var contextError = error(
28883
- "runner.errors.context"
28884
- ).format(({ details }) => details ?? "Context error").build();
28885
- var circularDependenciesError = error("runner.errors.circularDependencies").format(({ cycles }) => {
28886
- const cycleDetails = cycles.map((cycle) => ` \u2022 ${cycle}`).join("\n");
28887
- const hasMiddleware = cycles.some((cycle) => cycle.includes("middleware"));
28888
- let guidance = "\n\nTo resolve circular dependencies:";
28889
- guidance += "\n \u2022 Consider refactoring to reduce coupling between components";
28890
- guidance += "\n \u2022 Extract shared dependencies into separate resources";
28891
- if (hasMiddleware) {
28892
- guidance += "\n \u2022 For middleware: you can filter out tasks/resources using everywhere(fn)";
28893
- guidance += "\n \u2022 Consider using events for communication instead of direct dependencies";
28894
- }
28895
- return `Circular dependencies detected:
28896
- ${cycleDetails}${guidance}`;
28897
- }).build();
28898
- var eventNotFoundError = error(
28899
- "runner.errors.eventNotFound"
28900
- ).format(
28901
- ({ id: id2 }) => `Event "${id2.toString()}" not found. Did you forget to register it?`
28902
- ).build();
28903
- var resourceNotFoundError = error(
28904
- "runner.errors.resourceNotFound"
28905
- ).format(
28906
- ({ id: id2 }) => `Resource "${id2.toString()}" not found. Did you forget to register it or are you using the correct id?`
28907
- ).build();
28908
- var middlewareNotRegisteredError = error("runner.errors.middlewareNotRegistered").format(
28909
- ({ type, source, middlewareId }) => `Middleware inside ${type} "${source}" depends on "${middlewareId}" but it's not registered. Did you forget to register it?`
28910
- ).build();
28911
- var tagNotFoundError = error(
28912
- "runner.errors.tagNotFound"
28913
- ).format(
28914
- ({ id: id2 }) => `Tag "${id2}" not registered. Did you forget to register it inside a resource?`
28915
- ).build();
28916
- var lockedError = error(
28917
- "runner.errors.locked"
28918
- ).format(
28919
- ({ what }) => `Cannot modify the ${what.toString()} when it is locked.`
28920
- ).build();
28921
- var storeAlreadyInitializedError = error(
28922
- "runner.errors.storeAlreadyInitialized"
28923
- ).format(() => "Store already initialized. Cannot reinitialize.").build();
28924
- var validationError = error("runner.errors.validation").format(({ subject, id: id2, originalError }) => {
28925
- const errorMessage2 = originalError instanceof Error ? originalError.message : String(originalError);
28926
- return `${subject} validation failed for ${id2.toString()}: ${errorMessage2}`;
28927
- }).build();
28928
- var eventCycleError = error("runner.errors.eventCycle").format(({ path: path4 }) => {
28929
- const chain = path4.map((p) => `${p.id}\u2190${p.source}`).join(" -> ");
28930
- return `Event emission cycle detected:
28931
- ${chain}
28932
-
28933
- Break the cycle by changing hook logic (avoid mutual emits) or gate with conditions/tags.`;
28934
- }).build();
28935
- var eventEmissionCycleError = error("runner.errors.eventEmissionCycle").format(({ cycles }) => {
28936
- const list = cycles.map((c) => ` \u2022 ${c}`).join("\n");
28937
- return `Event emission cycles detected between hooks and events:
28938
- ${list}
28939
-
28940
- This was detected at compile time (dry-run). Break the cycle by avoiding mutual emits between hooks or scoping hooks using tags.`;
28941
- }).build();
28942
- var platformUnsupportedFunctionError = error("runner.errors.platformUnsupportedFunction").format(
28943
- ({ functionName }) => `Platform function not supported in this environment: ${functionName}. Detected platform: ${detectEnvironment()}.`
28944
- ).build();
28945
- var cancellationError = error(
28946
- "runner.errors.cancellation"
28947
- ).format(({ reason }) => reason || "Operation cancelled").build();
28948
- var tunnelOwnershipConflictError = error("runner.errors.tunnelOwnershipConflict").format(
28949
- ({ taskId, currentOwnerId, attemptedOwnerId }) => `Task "${taskId}" is already tunneled by resource "${currentOwnerId}". Resource "${attemptedOwnerId}" cannot tunnel it again. Ensure each task is owned by a single tunnel client.`
28950
- ).build();
28951
- var phantomTaskNotRoutedError = error("runner.errors.phantomTaskNotRouted").format(
28952
- ({ taskId }) => `Phantom task "${taskId}" is not routed through any tunnel. Ensure a tunnel client selects this task id (or avoid calling the phantom task directly).`
28953
- ).build();
28954
- var taskNotRegisteredError = error("runner.errors.taskNotRegistered").format(
28955
- ({ taskId }) => `Task "${taskId}" is not registered in the Store. This is an internal error\u2014ensure the task is registered before execution.`
28956
- ).build();
28957
- var builderIncompleteError = error("runner.errors.builderIncomplete").format(({ type, builderId, missingFields }) => {
28958
- const typeLabel = type === "hook" ? "Hook" : type === "task-middleware" ? "Task middleware" : "Resource middleware";
28959
- return `${typeLabel} "${builderId}" is incomplete. Missing required: ${missingFields.join(", ")}. Call ${missingFields.map((f) => `.${f}()`).join(" and ")} before .build().`;
28960
- }).build();
28961
- function isCancellationError(err) {
28962
- return cancellationError.is(err);
29017
+ // src/platform/adapters/node-als.ts
29018
+ async function loadAsyncLocalStorageClass() {
29019
+ const mod = __require("async_hooks");
29020
+ return mod.AsyncLocalStorage;
28963
29021
  }
28964
- __name(isCancellationError, "isCancellationError");
29022
+ __name(loadAsyncLocalStorageClass, "loadAsyncLocalStorageClass");
29023
+
29024
+ // src/platform/adapters/node.ts
29025
+ var NodePlatformAdapter = class {
29026
+ constructor() {
29027
+ this.id = "node";
29028
+ this.setTimeout = globalThis.setTimeout;
29029
+ this.clearTimeout = globalThis.clearTimeout;
29030
+ }
29031
+ static {
29032
+ __name(this, "NodePlatformAdapter");
29033
+ }
29034
+ async init() {
29035
+ this.alsClass = await loadAsyncLocalStorageClass();
29036
+ }
29037
+ onUncaughtException(handler) {
29038
+ const h = /* @__PURE__ */ __name((error2) => handler(error2), "h");
29039
+ process.on("uncaughtException", h);
29040
+ return () => process.off("uncaughtException", h);
29041
+ }
29042
+ onUnhandledRejection(handler) {
29043
+ const h = /* @__PURE__ */ __name((reason) => handler(reason), "h");
29044
+ process.on("unhandledRejection", h);
29045
+ return () => process.off("unhandledRejection", h);
29046
+ }
29047
+ onShutdownSignal(handler) {
29048
+ process.on("SIGINT", handler);
29049
+ process.on("SIGTERM", handler);
29050
+ return () => {
29051
+ process.off("SIGINT", handler);
29052
+ process.off("SIGTERM", handler);
29053
+ };
29054
+ }
29055
+ exit(code) {
29056
+ process.exit(code);
29057
+ }
29058
+ getEnv(key) {
29059
+ return process.env[key];
29060
+ }
29061
+ hasAsyncLocalStorage() {
29062
+ return true;
29063
+ }
29064
+ createAsyncLocalStorage() {
29065
+ let instance;
29066
+ const ensure = /* @__PURE__ */ __name(() => {
29067
+ if (!this.alsClass) {
29068
+ let als;
29069
+ const forceNoop = typeof process !== "undefined" && !!process.env?.RUNNER_FORCE_NOOP_ALS;
29070
+ if (!forceNoop) {
29071
+ try {
29072
+ const mod = __require("async_hooks");
29073
+ als = mod?.AsyncLocalStorage;
29074
+ } catch (_) {
29075
+ als = void 0;
29076
+ }
29077
+ }
29078
+ this.alsClass = als || class NoopAsyncLocalStorage {
29079
+ static {
29080
+ __name(this, "NoopAsyncLocalStorage");
29081
+ }
29082
+ getStore() {
29083
+ return void 0;
29084
+ }
29085
+ run(_store, callback) {
29086
+ return callback();
29087
+ }
29088
+ };
29089
+ }
29090
+ return instance ??= new this.alsClass();
29091
+ }, "ensure");
29092
+ return {
29093
+ getStore: /* @__PURE__ */ __name(() => ensure().getStore(), "getStore"),
29094
+ run: /* @__PURE__ */ __name((store2, callback) => ensure().run(store2, callback), "run")
29095
+ };
29096
+ }
29097
+ };
28965
29098
 
28966
29099
  // src/platform/adapters/browser.ts
28967
29100
  var BrowserPlatformAdapter = class {
@@ -29254,16 +29387,11 @@ function setPlatform(adapter) {
29254
29387
  adapter.id;
29255
29388
  }
29256
29389
  __name(setPlatform, "setPlatform");
29257
- function isNode() {
29258
- {
29259
- return true;
29260
- }
29261
- }
29262
- __name(isNode, "isNode");
29263
29390
  var PlatformAdapter = class {
29391
+ static {
29392
+ __name(this, "PlatformAdapter");
29393
+ }
29264
29394
  constructor(env) {
29265
- this.setTimeout = globalThis.setTimeout;
29266
- this.clearTimeout = globalThis.clearTimeout;
29267
29395
  const kind = env ?? detectEnvironment();
29268
29396
  this.env = kind;
29269
29397
  switch (kind) {
@@ -29283,9 +29411,8 @@ var PlatformAdapter = class {
29283
29411
  this.inner = new UniversalPlatformAdapter();
29284
29412
  }
29285
29413
  this.id = this.inner.id;
29286
- }
29287
- static {
29288
- __name(this, "PlatformAdapter");
29414
+ this.setTimeout = this.inner.setTimeout;
29415
+ this.clearTimeout = this.inner.clearTimeout;
29289
29416
  }
29290
29417
  async init() {
29291
29418
  return this.inner.init();
@@ -29313,209 +29440,103 @@ var PlatformAdapter = class {
29313
29440
  }
29314
29441
  };
29315
29442
 
29316
- // src/tools/getCallerFile.ts
29317
- function getCallerFile() {
29318
- const originalPrepare = Error.prepareStackTrace;
29319
- try {
29320
- if (isNode()) {
29321
- const err = new Error();
29322
- Error.prepareStackTrace = (_err, stack2) => stack2;
29323
- const stack = err.stack;
29324
- stack.shift();
29325
- stack.shift();
29326
- const candidate = stack.shift();
29327
- const file = candidate?.getFileName?.();
29328
- return file;
29329
- }
29330
- return "unknown";
29331
- } finally {
29332
- Error.prepareStackTrace = originalPrepare;
29333
- }
29334
- }
29335
- __name(getCallerFile, "getCallerFile");
29336
-
29337
- // src/defs.ts
29338
- var defs_exports = {};
29339
- __export(defs_exports, {
29340
- RunnerMode: () => RunnerMode,
29341
- isOneOf: () => isOneOf,
29342
- onAnyOf: () => onAnyOf,
29343
- symbolAsyncContext: () => symbolAsyncContext,
29344
- symbolError: () => symbolError,
29345
- symbolEvent: () => symbolEvent,
29346
- symbolFilePath: () => symbolFilePath,
29347
- symbolHook: () => symbolHook,
29348
- symbolMiddleware: () => symbolMiddleware,
29349
- symbolMiddlewareConfigured: () => symbolMiddlewareConfigured,
29350
- symbolOptionalDependency: () => symbolOptionalDependency,
29351
- symbolPhantomTask: () => symbolPhantomTask,
29352
- symbolResource: () => symbolResource,
29353
- symbolResourceForkedFrom: () => symbolResourceForkedFrom,
29354
- symbolResourceMiddleware: () => symbolResourceMiddleware,
29355
- symbolResourceWithConfig: () => symbolResourceWithConfig,
29356
- symbolTag: () => symbolTag,
29357
- symbolTagConfigured: () => symbolTagConfigured,
29358
- symbolTask: () => symbolTask,
29359
- symbolTaskMiddleware: () => symbolTaskMiddleware,
29360
- symbolTunneledBy: () => symbolTunneledBy
29361
- });
29362
-
29363
- // src/types/event.ts
29364
- function onAnyOf(...defs) {
29365
- return defs;
29366
- }
29367
- __name(onAnyOf, "onAnyOf");
29368
- function isOneOf(emission, defs) {
29369
- return defs.some((d) => d.id === emission.id);
29370
- }
29371
- __name(isOneOf, "isOneOf");
29372
-
29373
- // src/types/runner.ts
29374
- var RunnerMode = /* @__PURE__ */ ((RunnerMode2) => {
29375
- RunnerMode2["TEST"] = "test";
29376
- RunnerMode2["DEV"] = "dev";
29377
- RunnerMode2["PROD"] = "prod";
29378
- return RunnerMode2;
29379
- })(RunnerMode || {});
29380
-
29381
- // src/definers/tools.ts
29382
- function isTask(definition) {
29383
- return definition && definition[symbolTask];
29384
- }
29385
- __name(isTask, "isTask");
29386
- function isResource(definition) {
29387
- return definition && definition[symbolResource];
29388
- }
29389
- __name(isResource, "isResource");
29390
- function isResourceWithConfig(definition) {
29391
- return definition && definition[symbolResourceWithConfig];
29392
- }
29393
- __name(isResourceWithConfig, "isResourceWithConfig");
29394
- function isEvent(definition) {
29395
- return definition && definition[symbolEvent];
29396
- }
29397
- __name(isEvent, "isEvent");
29398
- function isHook(definition) {
29399
- return definition && definition[symbolHook];
29400
- }
29401
- __name(isHook, "isHook");
29402
- function isTaskMiddleware(definition) {
29403
- return definition && definition[symbolTaskMiddleware];
29404
- }
29405
- __name(isTaskMiddleware, "isTaskMiddleware");
29406
- function isResourceMiddleware(definition) {
29407
- return definition && definition[symbolResourceMiddleware];
29408
- }
29409
- __name(isResourceMiddleware, "isResourceMiddleware");
29410
- function isTag(definition) {
29411
- return definition && definition[symbolTag];
29412
- }
29413
- __name(isTag, "isTag");
29414
- function isOptional(definition) {
29415
- return definition && definition[symbolOptionalDependency];
29416
- }
29417
- __name(isOptional, "isOptional");
29418
- function isError(definition) {
29419
- return Boolean(definition && definition[symbolError]);
29420
- }
29421
- __name(isError, "isError");
29422
- function isAsyncContext(definition) {
29423
- return Boolean(definition && definition[symbolAsyncContext]);
29424
- }
29425
- __name(isAsyncContext, "isAsyncContext");
29426
-
29427
- // src/tools/throws.ts
29428
- function invalidThrowsEntryError(owner, item) {
29429
- const got = item === null ? "null" : Array.isArray(item) ? "array" : typeof item === "object" ? "object" : typeof item;
29430
- return new Error(
29431
- `Invalid throws entry for ${owner.kind} ${owner.id}: expected error id string or Error helper, got ${got}`
29432
- );
29433
- }
29434
- __name(invalidThrowsEntryError, "invalidThrowsEntryError");
29435
- function toErrorIdList(owner, list) {
29436
- const ids = [];
29437
- const seen = /* @__PURE__ */ new Set();
29438
- for (const item of list) {
29439
- let id2;
29440
- if (typeof item === "string") {
29441
- if (item.trim().length === 0) {
29442
- throw invalidThrowsEntryError(owner, item);
29443
- }
29444
- id2 = item;
29445
- } else if (isError(item)) {
29446
- id2 = item.id;
29447
- if (typeof id2 !== "string" || id2.trim().length === 0) {
29448
- throw invalidThrowsEntryError(owner, item);
29449
- }
29450
- } else {
29451
- throw invalidThrowsEntryError(owner, item);
29452
- }
29453
- if (seen.has(id2)) continue;
29454
- seen.add(id2);
29455
- ids.push(id2);
29443
+ // src/errors.ts
29444
+ var duplicateRegistrationError = error("runner.errors.duplicateRegistration").format(
29445
+ ({ type, id: id2 }) => `${type} "${id2.toString()}" already registered. You might have used the same 'id' in two different components or you may have registered the same element twice.`
29446
+ ).build();
29447
+ var dependencyNotFoundError = error("runner.errors.dependencyNotFound").format(
29448
+ ({ key }) => `Dependency ${key.toString()} not found. Did you forget to register it through a resource?`
29449
+ ).build();
29450
+ var unknownItemTypeError = error(
29451
+ "runner.errors.unknownItemType"
29452
+ ).format(
29453
+ ({ item }) => `Unknown item type: ${String(
29454
+ item
29455
+ )}. Please ensure you are not using different versions of '@bluelibs/runner'`
29456
+ ).build();
29457
+ var contextError = error(
29458
+ "runner.errors.context"
29459
+ ).format(({ details }) => details ?? "Context error").build();
29460
+ var circularDependenciesError = error("runner.errors.circularDependencies").format(({ cycles }) => {
29461
+ const cycleDetails = cycles.map((cycle) => ` \u2022 ${cycle}`).join("\n");
29462
+ const hasMiddleware = cycles.some((cycle) => cycle.includes("middleware"));
29463
+ let guidance = "\n\nTo resolve circular dependencies:";
29464
+ guidance += "\n \u2022 Consider refactoring to reduce coupling between components";
29465
+ guidance += "\n \u2022 Extract shared dependencies into separate resources";
29466
+ if (hasMiddleware) {
29467
+ guidance += "\n \u2022 For middleware: you can filter out tasks/resources using everywhere(fn)";
29468
+ guidance += "\n \u2022 Consider using events for communication instead of direct dependencies";
29456
29469
  }
29457
- return ids;
29458
- }
29459
- __name(toErrorIdList, "toErrorIdList");
29460
- function normalizeThrows(owner, throwsList) {
29461
- if (throwsList === void 0) return void 0;
29462
- return toErrorIdList(owner, throwsList);
29463
- }
29464
- __name(normalizeThrows, "normalizeThrows");
29470
+ return `Circular dependencies detected:
29471
+ ${cycleDetails}${guidance}`;
29472
+ }).build();
29473
+ var eventNotFoundError = error(
29474
+ "runner.errors.eventNotFound"
29475
+ ).format(
29476
+ ({ id: id2 }) => `Event "${id2.toString()}" not found. Did you forget to register it?`
29477
+ ).build();
29478
+ var resourceNotFoundError = error(
29479
+ "runner.errors.resourceNotFound"
29480
+ ).format(
29481
+ ({ id: id2 }) => `Resource "${id2.toString()}" not found. Did you forget to register it or are you using the correct id?`
29482
+ ).build();
29483
+ var middlewareNotRegisteredError = error("runner.errors.middlewareNotRegistered").format(
29484
+ ({ type, source, middlewareId }) => `Middleware inside ${type} "${source}" depends on "${middlewareId}" but it's not registered. Did you forget to register it?`
29485
+ ).build();
29486
+ var tagNotFoundError = error(
29487
+ "runner.errors.tagNotFound"
29488
+ ).format(
29489
+ ({ id: id2 }) => `Tag "${id2}" not registered. Did you forget to register it inside a resource?`
29490
+ ).build();
29491
+ var lockedError = error(
29492
+ "runner.errors.locked"
29493
+ ).format(
29494
+ ({ what }) => `Cannot modify the ${what.toString()} when it is locked.`
29495
+ ).build();
29496
+ var storeAlreadyInitializedError = error(
29497
+ "runner.errors.storeAlreadyInitialized"
29498
+ ).format(() => "Store already initialized. Cannot reinitialize.").build();
29499
+ var validationError = error("runner.errors.validation").format(({ subject, id: id2, originalError }) => {
29500
+ const errorMessage2 = originalError instanceof Error ? originalError.message : String(originalError);
29501
+ return `${subject} validation failed for ${id2.toString()}: ${errorMessage2}`;
29502
+ }).build();
29503
+ var eventCycleError = error("runner.errors.eventCycle").format(({ path: path4 }) => {
29504
+ const chain = path4.map((p) => `${p.id}\u2190${p.source}`).join(" -> ");
29505
+ return `Event emission cycle detected:
29506
+ ${chain}
29465
29507
 
29466
- // src/definers/defineTask.ts
29467
- function defineTask(taskConfig) {
29468
- const filePath = getCallerFile();
29469
- const id2 = taskConfig.id;
29470
- return {
29471
- [symbolTask]: true,
29472
- [symbolFilePath]: filePath,
29473
- id: id2,
29474
- dependencies: taskConfig.dependencies || {},
29475
- middleware: taskConfig.middleware || [],
29476
- run: taskConfig.run,
29477
- inputSchema: taskConfig.inputSchema,
29478
- resultSchema: taskConfig.resultSchema,
29479
- meta: taskConfig.meta || {},
29480
- tags: taskConfig.tags || [],
29481
- throws: normalizeThrows({ kind: "task", id: id2 }, taskConfig.throws),
29482
- // autorun,
29483
- optional() {
29484
- return {
29485
- inner: this,
29486
- [symbolOptionalDependency]: true
29487
- };
29488
- }
29489
- };
29490
- }
29491
- __name(defineTask, "defineTask");
29492
- defineTask.phantom = (taskConfig) => {
29493
- const taskDef = defineTask({
29494
- ...taskConfig,
29495
- run: /* @__PURE__ */ __name(async (_input) => {
29496
- return void 0;
29497
- }, "run")
29498
- });
29499
- taskDef[symbolPhantomTask] = true;
29500
- return taskDef;
29501
- };
29508
+ Break the cycle by changing hook logic (avoid mutual emits) or gate with conditions/tags.`;
29509
+ }).build();
29510
+ var eventEmissionCycleError = error("runner.errors.eventEmissionCycle").format(({ cycles }) => {
29511
+ const list = cycles.map((c) => ` \u2022 ${c}`).join("\n");
29512
+ return `Event emission cycles detected between hooks and events:
29513
+ ${list}
29502
29514
 
29503
- // src/definers/defineHook.ts
29504
- function defineHook(hookDef) {
29505
- const filePath = getCallerFile();
29506
- return {
29507
- [symbolHook]: true,
29508
- [symbolFilePath]: filePath,
29509
- id: hookDef.id,
29510
- dependencies: hookDef.dependencies || {},
29511
- on: hookDef.on,
29512
- order: hookDef.order,
29513
- run: hookDef.run,
29514
- meta: hookDef.meta || {},
29515
- tags: hookDef.tags || []
29516
- };
29515
+ This was detected at compile time (dry-run). Break the cycle by avoiding mutual emits between hooks or scoping hooks using tags.`;
29516
+ }).build();
29517
+ var platformUnsupportedFunctionError = error("runner.errors.platformUnsupportedFunction").format(
29518
+ ({ functionName }) => `Platform function not supported in this environment: ${functionName}. Detected platform: ${detectEnvironment()}.`
29519
+ ).build();
29520
+ var cancellationError = error(
29521
+ "runner.errors.cancellation"
29522
+ ).format(({ reason }) => reason || "Operation cancelled").build();
29523
+ var tunnelOwnershipConflictError = error("runner.errors.tunnelOwnershipConflict").format(
29524
+ ({ taskId, currentOwnerId, attemptedOwnerId }) => `Task "${taskId}" is already tunneled by resource "${currentOwnerId}". Resource "${attemptedOwnerId}" cannot tunnel it again. Ensure each task is owned by a single tunnel client.`
29525
+ ).build();
29526
+ var phantomTaskNotRoutedError = error("runner.errors.phantomTaskNotRouted").format(
29527
+ ({ taskId }) => `Phantom task "${taskId}" is not routed through any tunnel. Ensure a tunnel client selects this task id (or avoid calling the phantom task directly).`
29528
+ ).build();
29529
+ var taskNotRegisteredError = error("runner.errors.taskNotRegistered").format(
29530
+ ({ taskId }) => `Task "${taskId}" is not registered in the Store. This is an internal error\u2014ensure the task is registered before execution.`
29531
+ ).build();
29532
+ var builderIncompleteError = error("runner.errors.builderIncomplete").format(({ type, builderId, missingFields }) => {
29533
+ const typeLabel = type === "hook" ? "Hook" : type === "task-middleware" ? "Task middleware" : "Resource middleware";
29534
+ return `${typeLabel} "${builderId}" is incomplete. Missing required: ${missingFields.join(", ")}. Call ${missingFields.map((f) => `.${f}()`).join(" and ")} before .build().`;
29535
+ }).build();
29536
+ function isCancellationError(err) {
29537
+ return cancellationError.is(err);
29517
29538
  }
29518
- __name(defineHook, "defineHook");
29539
+ __name(isCancellationError, "isCancellationError");
29519
29540
 
29520
29541
  // src/definers/resourceFork.ts
29521
29542
  function resolveReId(forkId, options) {
@@ -29890,7 +29911,7 @@ function defineOverride(base, patch) {
29890
29911
  ...patch,
29891
29912
  id: base.id
29892
29913
  };
29893
- if (base.on !== void 0) {
29914
+ if ("on" in base && base.on !== void 0) {
29894
29915
  overridden.on = base.on;
29895
29916
  }
29896
29917
  return overridden;
@@ -30010,6 +30031,309 @@ var SymbolPolicy = /* @__PURE__ */ ((SymbolPolicy2) => {
30010
30031
  SymbolPolicy2["Disabled"] = "Disabled";
30011
30032
  return SymbolPolicy2;
30012
30033
  })(SymbolPolicy || {});
30034
+ var SymbolPolicyErrorMessage = /* @__PURE__ */ ((SymbolPolicyErrorMessage2) => {
30035
+ SymbolPolicyErrorMessage2["GlobalSymbolsNotAllowed"] = "Global symbols are not allowed";
30036
+ SymbolPolicyErrorMessage2["SymbolsNotAllowed"] = "Symbols are not allowed";
30037
+ SymbolPolicyErrorMessage2["UnsupportedSymbolPolicy"] = "Unsupported symbol policy";
30038
+ return SymbolPolicyErrorMessage2;
30039
+ })(SymbolPolicyErrorMessage || {});
30040
+
30041
+ // src/serializer/binary-builtins.ts
30042
+ var INVALID_PAYLOAD_MESSAGE_PREFIX = "Invalid";
30043
+ var typedArrayTypeIds = [
30044
+ "Int8Array",
30045
+ "Uint8Array",
30046
+ "Uint8ClampedArray",
30047
+ "Int16Array",
30048
+ "Uint16Array",
30049
+ "Int32Array",
30050
+ "Uint32Array",
30051
+ "Float32Array",
30052
+ "Float64Array",
30053
+ "BigInt64Array",
30054
+ "BigUint64Array"
30055
+ ];
30056
+ var getTypedArrayConstructor = /* @__PURE__ */ __name((typeId) => {
30057
+ const value = globalThis[typeId];
30058
+ if (typeof value !== "function") {
30059
+ return null;
30060
+ }
30061
+ return value;
30062
+ }, "getTypedArrayConstructor");
30063
+ var getRuntimeBufferConstructor = /* @__PURE__ */ __name(() => {
30064
+ const value = globalThis.Buffer;
30065
+ if (typeof value !== "function") {
30066
+ return null;
30067
+ }
30068
+ const valueRecord = value;
30069
+ if (typeof valueRecord.from !== "function" || typeof valueRecord.isBuffer !== "function") {
30070
+ return null;
30071
+ }
30072
+ return value;
30073
+ }, "getRuntimeBufferConstructor");
30074
+ var isNodeBuffer = /* @__PURE__ */ __name((value) => {
30075
+ const runtimeBufferConstructor = getRuntimeBufferConstructor();
30076
+ if (!runtimeBufferConstructor) {
30077
+ return false;
30078
+ }
30079
+ return runtimeBufferConstructor.isBuffer(value);
30080
+ }, "isNodeBuffer");
30081
+ var assertBytePayload = /* @__PURE__ */ __name((payload, typeId) => {
30082
+ if (!Array.isArray(payload)) {
30083
+ throw new Error(`${INVALID_PAYLOAD_MESSAGE_PREFIX} ${typeId} payload`);
30084
+ }
30085
+ const bytes = new Array(payload.length);
30086
+ for (let index = 0; index < payload.length; index += 1) {
30087
+ const byteValue = payload[index];
30088
+ if (typeof byteValue !== "number" || !Number.isInteger(byteValue) || byteValue < 0 || byteValue > 255) {
30089
+ throw new Error(`${INVALID_PAYLOAD_MESSAGE_PREFIX} ${typeId} payload`);
30090
+ }
30091
+ bytes[index] = byteValue;
30092
+ }
30093
+ return bytes;
30094
+ }, "assertBytePayload");
30095
+ var toBytePayload = /* @__PURE__ */ __name((value) => Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)), "toBytePayload");
30096
+ var bytesToArrayBuffer = /* @__PURE__ */ __name((payload, typeId) => {
30097
+ const bytes = assertBytePayload(payload, typeId);
30098
+ return Uint8Array.from(bytes).buffer;
30099
+ }, "bytesToArrayBuffer");
30100
+ var deserializeTypedArray = /* @__PURE__ */ __name((typeId, payload) => {
30101
+ const typedArrayConstructor = getTypedArrayConstructor(typeId);
30102
+ if (!typedArrayConstructor) {
30103
+ throw new Error(`${typeId} is not available in this runtime`);
30104
+ }
30105
+ const bytes = assertBytePayload(payload, typeId);
30106
+ const bytesPerElement = typedArrayConstructor.BYTES_PER_ELEMENT;
30107
+ if (bytes.length % bytesPerElement !== 0) {
30108
+ throw new Error(`${INVALID_PAYLOAD_MESSAGE_PREFIX} ${typeId} payload`);
30109
+ }
30110
+ const arrayBuffer = Uint8Array.from(bytes).buffer;
30111
+ return new typedArrayConstructor(arrayBuffer);
30112
+ }, "deserializeTypedArray");
30113
+ var createTypedArrayType = /* @__PURE__ */ __name((typeId) => ({
30114
+ id: typeId,
30115
+ is: /* @__PURE__ */ __name((value) => {
30116
+ const typedArrayConstructor = getTypedArrayConstructor(typeId);
30117
+ if (!typedArrayConstructor) {
30118
+ return false;
30119
+ }
30120
+ if (!(value instanceof typedArrayConstructor)) {
30121
+ return false;
30122
+ }
30123
+ if (typeId === "Uint8Array" && isNodeBuffer(value)) {
30124
+ return false;
30125
+ }
30126
+ return true;
30127
+ }, "is"),
30128
+ serialize: /* @__PURE__ */ __name((value) => toBytePayload(value), "serialize"),
30129
+ deserialize: /* @__PURE__ */ __name((payload) => deserializeTypedArray(typeId, payload), "deserialize"),
30130
+ strategy: "value"
30131
+ }), "createTypedArrayType");
30132
+ var ArrayBufferType = {
30133
+ id: "ArrayBuffer",
30134
+ is: /* @__PURE__ */ __name((value) => value instanceof ArrayBuffer, "is"),
30135
+ serialize: /* @__PURE__ */ __name((value) => Array.from(new Uint8Array(value)), "serialize"),
30136
+ deserialize: /* @__PURE__ */ __name((payload) => bytesToArrayBuffer(payload, "ArrayBuffer"), "deserialize"),
30137
+ strategy: "value"
30138
+ };
30139
+ var DataViewType = {
30140
+ id: "DataView",
30141
+ is: /* @__PURE__ */ __name((value) => value instanceof DataView, "is"),
30142
+ serialize: /* @__PURE__ */ __name((value) => toBytePayload(value), "serialize"),
30143
+ deserialize: /* @__PURE__ */ __name((payload) => new DataView(bytesToArrayBuffer(payload, "DataView")), "deserialize"),
30144
+ strategy: "value"
30145
+ };
30146
+ var BufferType = {
30147
+ id: "Buffer",
30148
+ is: /* @__PURE__ */ __name((value) => isNodeBuffer(value), "is"),
30149
+ serialize: /* @__PURE__ */ __name((value) => toBytePayload(value), "serialize"),
30150
+ deserialize: /* @__PURE__ */ __name((payload) => {
30151
+ const bytes = assertBytePayload(payload, "Buffer");
30152
+ const runtimeBufferConstructor = getRuntimeBufferConstructor();
30153
+ if (runtimeBufferConstructor) {
30154
+ return runtimeBufferConstructor.from(bytes);
30155
+ }
30156
+ return Uint8Array.from(bytes);
30157
+ }, "deserialize"),
30158
+ strategy: "value"
30159
+ };
30160
+ var typedArrayTypes = typedArrayTypeIds.map(
30161
+ (typeId) => createTypedArrayType(typeId)
30162
+ );
30163
+ var binaryBuiltInTypes = [
30164
+ ArrayBufferType,
30165
+ DataViewType,
30166
+ BufferType,
30167
+ ...typedArrayTypes
30168
+ ];
30169
+
30170
+ // src/serializer/error-url-builtins.ts
30171
+ var hasOwn = Object.prototype.hasOwnProperty;
30172
+ var errorReservedPropertyNames = /* @__PURE__ */ new Set([
30173
+ "name",
30174
+ "message",
30175
+ "stack",
30176
+ "cause"
30177
+ ]);
30178
+ var isRecord = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRecord");
30179
+ var isUnsafePropertyName = /* @__PURE__ */ __name((propertyName) => propertyName === "__proto__" || propertyName === "constructor" || propertyName === "prototype", "isUnsafePropertyName");
30180
+ var collectErrorCustomFields = /* @__PURE__ */ __name((error2) => {
30181
+ const customFields = {};
30182
+ for (const propertyName of Object.getOwnPropertyNames(error2)) {
30183
+ if (errorReservedPropertyNames.has(propertyName)) {
30184
+ continue;
30185
+ }
30186
+ if (isUnsafePropertyName(propertyName)) {
30187
+ continue;
30188
+ }
30189
+ const descriptor = Object.getOwnPropertyDescriptor(error2, propertyName);
30190
+ if (!descriptor || !("value" in descriptor)) {
30191
+ continue;
30192
+ }
30193
+ customFields[propertyName] = descriptor.value;
30194
+ }
30195
+ return customFields;
30196
+ }, "collectErrorCustomFields");
30197
+ var assertSerializedErrorPayload = /* @__PURE__ */ __name((value) => {
30198
+ if (!isRecord(value)) {
30199
+ throw new Error("Invalid Error payload");
30200
+ }
30201
+ const { name, message, stack, customFields } = value;
30202
+ if (typeof name !== "string" || typeof message !== "string") {
30203
+ throw new Error("Invalid Error payload");
30204
+ }
30205
+ if (stack !== void 0 && typeof stack !== "string") {
30206
+ throw new Error("Invalid Error payload");
30207
+ }
30208
+ if (customFields !== void 0 && !isRecord(customFields)) {
30209
+ throw new Error("Invalid Error payload");
30210
+ }
30211
+ const normalizedCustomFields = {};
30212
+ const customFieldEntries = Object.entries(customFields ?? {});
30213
+ for (const [propertyName, propertyValue] of customFieldEntries) {
30214
+ if (isUnsafePropertyName(propertyName)) {
30215
+ continue;
30216
+ }
30217
+ normalizedCustomFields[propertyName] = propertyValue;
30218
+ }
30219
+ return {
30220
+ name,
30221
+ message,
30222
+ stack,
30223
+ hasCause: hasOwn.call(value, "cause"),
30224
+ cause: value.cause,
30225
+ customFields: normalizedCustomFields
30226
+ };
30227
+ }, "assertSerializedErrorPayload");
30228
+ var getUrlConstructor = /* @__PURE__ */ __name(() => {
30229
+ const value = globalThis.URL;
30230
+ if (typeof value !== "function") {
30231
+ return null;
30232
+ }
30233
+ return value;
30234
+ }, "getUrlConstructor");
30235
+ var getUrlSearchParamsConstructor = /* @__PURE__ */ __name(() => {
30236
+ const value = globalThis.URLSearchParams;
30237
+ if (typeof value !== "function") {
30238
+ return null;
30239
+ }
30240
+ return value;
30241
+ }, "getUrlSearchParamsConstructor");
30242
+ var ErrorType = {
30243
+ id: "Error",
30244
+ is: /* @__PURE__ */ __name((value) => value instanceof Error, "is"),
30245
+ serialize: /* @__PURE__ */ __name((error2) => {
30246
+ const serializedErrorPayload = {
30247
+ name: error2.name,
30248
+ message: error2.message,
30249
+ customFields: collectErrorCustomFields(error2)
30250
+ };
30251
+ if (typeof error2.stack === "string") {
30252
+ serializedErrorPayload.stack = error2.stack;
30253
+ }
30254
+ if (hasOwn.call(error2, "cause")) {
30255
+ serializedErrorPayload.cause = error2.cause;
30256
+ }
30257
+ return serializedErrorPayload;
30258
+ }, "serialize"),
30259
+ deserialize: /* @__PURE__ */ __name((payload) => {
30260
+ const { name, message, stack, hasCause, cause, customFields } = assertSerializedErrorPayload(payload);
30261
+ const restoredError = new Error(message);
30262
+ restoredError.name = name;
30263
+ if (stack !== void 0) {
30264
+ Object.defineProperty(restoredError, "stack", {
30265
+ value: stack,
30266
+ writable: true,
30267
+ configurable: true,
30268
+ enumerable: false
30269
+ });
30270
+ }
30271
+ if (hasCause) {
30272
+ Object.defineProperty(restoredError, "cause", {
30273
+ value: cause,
30274
+ writable: true,
30275
+ configurable: true,
30276
+ enumerable: false
30277
+ });
30278
+ }
30279
+ for (const [propertyName, propertyValue] of Object.entries(customFields)) {
30280
+ if (errorReservedPropertyNames.has(propertyName)) {
30281
+ continue;
30282
+ }
30283
+ restoredError[propertyName] = propertyValue;
30284
+ }
30285
+ return restoredError;
30286
+ }, "deserialize")
30287
+ };
30288
+ var URLType = {
30289
+ id: "URL",
30290
+ is: /* @__PURE__ */ __name((value) => {
30291
+ const runtimeUrlConstructor = getUrlConstructor();
30292
+ if (!runtimeUrlConstructor) {
30293
+ return false;
30294
+ }
30295
+ return value instanceof runtimeUrlConstructor;
30296
+ }, "is"),
30297
+ serialize: /* @__PURE__ */ __name((value) => value.href, "serialize"),
30298
+ deserialize: /* @__PURE__ */ __name((payload) => {
30299
+ if (typeof payload !== "string") {
30300
+ throw new Error("Invalid URL payload");
30301
+ }
30302
+ const runtimeUrlConstructor = getUrlConstructor();
30303
+ if (!runtimeUrlConstructor) {
30304
+ throw new Error("URL is not available in this runtime");
30305
+ }
30306
+ return new runtimeUrlConstructor(payload);
30307
+ }, "deserialize"),
30308
+ strategy: "value"
30309
+ };
30310
+ var URLSearchParamsType = {
30311
+ id: "URLSearchParams",
30312
+ is: /* @__PURE__ */ __name((value) => {
30313
+ const runtimeUrlSearchParamsConstructor = getUrlSearchParamsConstructor();
30314
+ if (!runtimeUrlSearchParamsConstructor) {
30315
+ return false;
30316
+ }
30317
+ return value instanceof runtimeUrlSearchParamsConstructor;
30318
+ }, "is"),
30319
+ serialize: /* @__PURE__ */ __name((value) => value.toString(), "serialize"),
30320
+ deserialize: /* @__PURE__ */ __name((payload) => {
30321
+ if (typeof payload !== "string") {
30322
+ throw new Error("Invalid URLSearchParams payload");
30323
+ }
30324
+ const runtimeUrlSearchParamsConstructor = getUrlSearchParamsConstructor();
30325
+ if (!runtimeUrlSearchParamsConstructor) {
30326
+ throw new Error("URLSearchParams is not available in this runtime");
30327
+ }
30328
+ return new runtimeUrlSearchParamsConstructor(payload);
30329
+ }, "deserialize"),
30330
+ strategy: "value"
30331
+ };
30332
+ var errorAndUrlBuiltInTypes = [
30333
+ ErrorType,
30334
+ URLType,
30335
+ URLSearchParamsType
30336
+ ];
30013
30337
 
30014
30338
  // src/serializer/special-values.ts
30015
30339
  var serializeUndefined = /* @__PURE__ */ __name(() => ({
@@ -30215,7 +30539,9 @@ var builtInTypes = [
30215
30539
  UndefinedType,
30216
30540
  NonFiniteNumberType,
30217
30541
  BigIntType,
30218
- SymbolType
30542
+ SymbolType,
30543
+ ...errorAndUrlBuiltInTypes,
30544
+ ...binaryBuiltInTypes
30219
30545
  ];
30220
30546
 
30221
30547
  // src/serializer/type-registry.ts
@@ -30706,7 +31032,7 @@ var serializeTreeValue = /* @__PURE__ */ __name((value, context, depth, options)
30706
31032
  }, "serializeTreeValue");
30707
31033
 
30708
31034
  // src/serializer/deserializer.ts
30709
- var hasOwn = Object.prototype.hasOwnProperty;
31035
+ var hasOwn2 = Object.prototype.hasOwnProperty;
30710
31036
  var copyOwnProperties = /* @__PURE__ */ __name((target, source, unsafeKeys) => {
30711
31037
  const descriptors = Object.getOwnPropertyDescriptors(source);
30712
31038
  for (const key of Object.keys(descriptors)) {
@@ -30787,7 +31113,7 @@ var deserializeValue = /* @__PURE__ */ __name((value, context, depth, options) =
30787
31113
  const obj = {};
30788
31114
  const source = value;
30789
31115
  for (const key in source) {
30790
- if (!hasOwn.call(source, key)) {
31116
+ if (!hasOwn2.call(source, key)) {
30791
31117
  continue;
30792
31118
  }
30793
31119
  if (isUnsafeKey(key, options.unsafeKeys)) {
@@ -30832,7 +31158,7 @@ var resolveReference = /* @__PURE__ */ __name((id2, context, depth, options) =>
30832
31158
  context.resolved.set(id2, target);
30833
31159
  const source = node.value;
30834
31160
  for (const key in source) {
30835
- if (!hasOwn.call(source, key)) {
31161
+ if (!hasOwn2.call(source, key)) {
30836
31162
  continue;
30837
31163
  }
30838
31164
  if (isUnsafeKey(key, options.unsafeKeys)) {
@@ -30904,7 +31230,7 @@ var mergePlaceholder = /* @__PURE__ */ __name((placeholder, result, unsafeKeys)
30904
31230
  const target = placeholder;
30905
31231
  const source = result;
30906
31232
  for (const key in source) {
30907
- if (!hasOwn.call(source, key)) {
31233
+ if (!hasOwn2.call(source, key)) {
30908
31234
  continue;
30909
31235
  }
30910
31236
  if (isUnsafeKey(key, unsafeKeys)) {
@@ -30937,7 +31263,7 @@ var deserializeLegacy = /* @__PURE__ */ __name((value, depth, options) => {
30937
31263
  const obj = {};
30938
31264
  const source = value;
30939
31265
  for (const key in source) {
30940
- if (!hasOwn.call(source, key)) {
31266
+ if (!hasOwn2.call(source, key)) {
30941
31267
  continue;
30942
31268
  }
30943
31269
  if (isUnsafeKey(key, options.unsafeKeys)) {
@@ -30948,6 +31274,26 @@ var deserializeLegacy = /* @__PURE__ */ __name((value, depth, options) => {
30948
31274
  return obj;
30949
31275
  }, "deserializeLegacy");
30950
31276
 
31277
+ // src/serializer/option-normalizers.ts
31278
+ var normalizeMaxDepth = /* @__PURE__ */ __name((value, fallback) => {
31279
+ if (value === Number.POSITIVE_INFINITY) {
31280
+ return Number.POSITIVE_INFINITY;
31281
+ }
31282
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
31283
+ return Math.floor(value);
31284
+ }
31285
+ return fallback;
31286
+ }, "normalizeMaxDepth");
31287
+ var normalizeMaxRegExpPatternLength = /* @__PURE__ */ __name((value, fallback) => {
31288
+ if (value === Number.POSITIVE_INFINITY) {
31289
+ return Number.POSITIVE_INFINITY;
31290
+ }
31291
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
31292
+ return Math.floor(value);
31293
+ }
31294
+ return fallback;
31295
+ }, "normalizeMaxRegExpPatternLength");
31296
+
30951
31297
  // src/serializer/Serializer.ts
30952
31298
  var GRAPH_VERSION = 1;
30953
31299
  var DEFAULT_MAX_DEPTH = 1e3;
@@ -30983,10 +31329,11 @@ var Serializer = class {
30983
31329
  return check(pattern, index);
30984
31330
  }, "isBoundedQuantifier");
30985
31331
  this.indent = options.pretty ? 2 : void 0;
30986
- const maxDepth = options.maxDepth;
30987
- this.maxDepth = typeof maxDepth === "number" && Number.isFinite(maxDepth) && maxDepth >= 0 ? Math.floor(maxDepth) : DEFAULT_MAX_DEPTH;
30988
- const maxPatternLength = options.maxRegExpPatternLength;
30989
- this.maxRegExpPatternLength = maxPatternLength === Number.POSITIVE_INFINITY ? Number.POSITIVE_INFINITY : typeof maxPatternLength === "number" && Number.isFinite(maxPatternLength) && maxPatternLength > 0 ? Math.floor(maxPatternLength) : DEFAULT_MAX_REGEXP_PATTERN_LENGTH;
31332
+ this.maxDepth = normalizeMaxDepth(options.maxDepth, DEFAULT_MAX_DEPTH);
31333
+ this.maxRegExpPatternLength = normalizeMaxRegExpPatternLength(
31334
+ options.maxRegExpPatternLength,
31335
+ DEFAULT_MAX_REGEXP_PATTERN_LENGTH
31336
+ );
30990
31337
  this.allowUnsafeRegExp = options.allowUnsafeRegExp ?? false;
30991
31338
  this.unsafeKeys = DEFAULT_UNSAFE_KEYS;
30992
31339
  this.typeRegistry = new TypeRegistry({
@@ -31121,13 +31468,6 @@ var Serializer = class {
31121
31468
  }
31122
31469
  };
31123
31470
 
31124
- // src/serializer/index.ts
31125
- var defaultSerializer = new Serializer();
31126
- function getDefaultSerializer() {
31127
- return defaultSerializer;
31128
- }
31129
- __name(getDefaultSerializer, "getDefaultSerializer");
31130
-
31131
31471
  // src/definers/defineAsyncContext.ts
31132
31472
  var platform = getPlatform();
31133
31473
  var storage = platform.createAsyncLocalStorage();
@@ -31135,13 +31475,14 @@ function getCurrentStore() {
31135
31475
  return storage.getStore();
31136
31476
  }
31137
31477
  __name(getCurrentStore, "getCurrentStore");
31138
- function defineAsyncContext(def) {
31478
+ function defineAsyncContext(def, filePath) {
31139
31479
  if (!platform.hasAsyncLocalStorage()) {
31140
31480
  platformUnsupportedFunctionError.throw({
31141
31481
  functionName: `createAsyncLocalStorage: Cannot create context ${def.id}: no async storage available in this environment`
31142
31482
  });
31143
31483
  }
31144
31484
  const ctxId = def.id;
31485
+ const resolvedFilePath = filePath ?? getCallerFile();
31145
31486
  const use = /* @__PURE__ */ __name(() => {
31146
31487
  const store2 = getCurrentStore();
31147
31488
  if (!store2 || !store2.has(ctxId)) {
@@ -31158,10 +31499,11 @@ function defineAsyncContext(def) {
31158
31499
  map.set(ctxId, value);
31159
31500
  return storage.run(map, fn);
31160
31501
  }, "provide");
31161
- const serializer3 = getDefaultSerializer();
31502
+ const serializer3 = new Serializer();
31162
31503
  const api = {
31163
31504
  id: ctxId,
31164
31505
  [symbolAsyncContext]: true,
31506
+ [symbolFilePath]: resolvedFilePath,
31165
31507
  use,
31166
31508
  /* istanbul ignore next */
31167
31509
  provide(value, fn) {
@@ -31813,12 +32155,12 @@ var EventManager = class {
31813
32155
  data,
31814
32156
  timestamp: /* @__PURE__ */ new Date(),
31815
32157
  source,
31816
- meta: eventDefinition.meta || {},
32158
+ meta: { ...eventDefinition.meta || {} },
31817
32159
  stopPropagation: /* @__PURE__ */ __name(() => {
31818
32160
  propagationStopped = true;
31819
32161
  }, "stopPropagation"),
31820
32162
  isPropagationStopped: /* @__PURE__ */ __name(() => propagationStopped, "isPropagationStopped"),
31821
- tags: eventDefinition.tags
32163
+ tags: [...eventDefinition.tags]
31822
32164
  };
31823
32165
  const baseEmit = /* @__PURE__ */ __name(async (eventToEmit) => {
31824
32166
  if (allListeners.length === 0) {
@@ -31844,10 +32186,14 @@ var EventManager = class {
31844
32186
  if (!interceptor) {
31845
32187
  return baseEmit(eventToEmit);
31846
32188
  }
31847
- return interceptor(
31848
- (nextEvent) => runInterceptor(index + 1, nextEvent),
31849
- eventToEmit
31850
- );
32189
+ return interceptor((nextEvent) => {
32190
+ this.assertPropagationMethodsUnchanged(
32191
+ eventDefinition.id,
32192
+ eventToEmit,
32193
+ nextEvent
32194
+ );
32195
+ return runInterceptor(index + 1, nextEvent);
32196
+ }, eventToEmit);
31851
32197
  }, "runInterceptor");
31852
32198
  await runInterceptor(0, event2);
31853
32199
  return deepestEvent;
@@ -31958,21 +32304,24 @@ var EventManager = class {
31958
32304
  lockedError.throw({ what: "EventManager" });
31959
32305
  }
31960
32306
  }
31961
- /**
31962
- * Clears all listeners and interceptors.
31963
- * Call this to release references and free memory.
31964
- */
31965
- clear() {
31966
- this.registry.clear();
31967
- this.emissionInterceptors.length = 0;
31968
- this.hookInterceptors.length = 0;
32307
+ assertPropagationMethodsUnchanged(eventId, currentEvent, nextEvent) {
32308
+ if (nextEvent.stopPropagation !== currentEvent.stopPropagation || nextEvent.isPropagationStopped !== currentEvent.isPropagationStopped) {
32309
+ validationError.throw({
32310
+ subject: "Event interceptor",
32311
+ id: eventId,
32312
+ originalError: new Error(
32313
+ "Interceptors cannot override stopPropagation/isPropagationStopped"
32314
+ )
32315
+ });
32316
+ }
31969
32317
  }
31970
32318
  /**
31971
32319
  * Disposes the EventManager, releasing all listeners and interceptors.
31972
- * Alias for clear() following the IResource disposal pattern.
31973
32320
  */
31974
32321
  dispose() {
31975
- this.clear();
32322
+ this.registry.clear();
32323
+ this.emissionInterceptors.length = 0;
32324
+ this.hookInterceptors.length = 0;
31976
32325
  }
31977
32326
  /**
31978
32327
  * Retrieves cached merged listeners for an event, or creates them if not cached.
@@ -33279,7 +33628,7 @@ var TaskRunner = class {
33279
33628
  __name(this, "TaskRunner");
33280
33629
  }
33281
33630
  /**
33282
- * Begins the execution of an task. These are registered tasks and all sanity checks have been performed at this stage to ensure consistency of the object.
33631
+ * Begins the execution of a task. These are registered tasks and all sanity checks have been performed at this stage to ensure consistency of the object.
33283
33632
  * This function can throw only if any of the event listeners or run function throws
33284
33633
  * @param task the task to be run
33285
33634
  * @param input the input to be passed to the task
@@ -33308,8 +33657,6 @@ var TaskRunner = class {
33308
33657
  /**
33309
33658
  * Creates the function with the chain of middleware.
33310
33659
  * @param task
33311
- * @param input
33312
- * @param taskDependencies
33313
33660
  * @returns
33314
33661
  */
33315
33662
  createRunnerWithMiddleware(task2) {
@@ -33329,7 +33676,7 @@ var ResourceInitializer = class {
33329
33676
  __name(this, "ResourceInitializer");
33330
33677
  }
33331
33678
  /**
33332
- * Begins the execution of an task. These are registered tasks and all sanity checks have been performed at this stage to ensure consistency of the object.
33679
+ * Begins the execution of a task. These are registered tasks and all sanity checks have been performed at this stage to ensure consistency of the object.
33333
33680
  * This function can throw only if any of the event listeners or run function throws
33334
33681
  */
33335
33682
  async initializeResource(resource2, config, dependencies) {
@@ -33819,23 +34166,28 @@ var DependencyProcessor = class {
33819
34166
  middleware.computedDependencies = computedDependencies;
33820
34167
  middleware.isInitialized = true;
33821
34168
  }
33822
- for (const resource2 of this.store.resources.values()) {
33823
- await this.processResourceDependencies(resource2);
33824
- }
33825
- for (const task2 of this.store.tasks.values()) {
33826
- await this.computeTaskDependencies(task2);
33827
- }
33828
34169
  for (const hookStoreElement of this.store.hooks.values()) {
33829
34170
  const hook2 = hookStoreElement.hook;
33830
34171
  const deps = hook2.dependencies;
34172
+ hookStoreElement.dependencyState = "computing" /* Computing */;
33831
34173
  hookStoreElement.computedDependencies = await this.extractDependencies(
33832
34174
  deps,
33833
34175
  hook2.id
33834
34176
  );
34177
+ hookStoreElement.dependencyState = "ready" /* Ready */;
34178
+ }
34179
+ for (const resource2 of this.store.resources.values()) {
34180
+ await this.processResourceDependencies(resource2);
34181
+ }
34182
+ for (const task2 of this.store.tasks.values()) {
34183
+ await this.computeTaskDependencies(task2);
33835
34184
  }
33836
34185
  await this.initializeUninitializedResources();
33837
34186
  }
33838
34187
  async computeTaskDependencies(task2) {
34188
+ if (task2.isInitialized) {
34189
+ return;
34190
+ }
33839
34191
  const deps = task2.task.dependencies;
33840
34192
  task2.computedDependencies = await this.extractDependencies(
33841
34193
  deps,
@@ -33967,6 +34319,9 @@ var DependencyProcessor = class {
33967
34319
  if (receivedEvent.source === hook2.id) {
33968
34320
  return;
33969
34321
  }
34322
+ if (hookStoreElement.dependencyState !== "ready" /* Ready */) {
34323
+ return;
34324
+ }
33970
34325
  return this.eventManager.executeHookWithInterceptors(
33971
34326
  hook2,
33972
34327
  receivedEvent,
@@ -34083,7 +34438,7 @@ var DependencyProcessor = class {
34083
34438
  }
34084
34439
  const st = storeTask;
34085
34440
  if (!st.isInitialized) {
34086
- const dependencies = object.dependencies;
34441
+ const dependencies = st.task.dependencies;
34087
34442
  st.computedDependencies = await this.extractDependencies(
34088
34443
  dependencies,
34089
34444
  st.task.id
@@ -34109,14 +34464,19 @@ var DependencyProcessor = class {
34109
34464
  wrapped = this.wrapResourceDependencies(depMap, raw);
34110
34465
  sr.computedDependencies = wrapped;
34111
34466
  }
34112
- const { value, context } = await this.resourceInitializer.initializeResource(
34113
- resource2,
34114
- config,
34115
- wrapped
34116
- );
34117
- sr.context = context;
34118
- sr.value = value;
34119
- sr.isInitialized = true;
34467
+ try {
34468
+ const { value, context } = await this.resourceInitializer.initializeResource(
34469
+ resource2,
34470
+ config,
34471
+ wrapped
34472
+ );
34473
+ sr.context = context;
34474
+ sr.value = value;
34475
+ sr.isInitialized = true;
34476
+ this.store.recordResourceInitialized(resource2.id);
34477
+ } catch (error2) {
34478
+ this.rethrowResourceInitError(resource2.id, error2);
34479
+ }
34120
34480
  }
34121
34481
  return sr.value;
34122
34482
  }
@@ -34319,7 +34679,8 @@ var StoreRegistry = class {
34319
34679
  const hook2 = this.getFreshValue(item, this.hooks, "hook", overrideMode);
34320
34680
  this.hooks.set(hook2.id, {
34321
34681
  hook: hook2,
34322
- computedDependencies: {}
34682
+ computedDependencies: {},
34683
+ dependencyState: "pending" /* Pending */
34323
34684
  });
34324
34685
  }
34325
34686
  storeTaskMiddleware(item, storingMode = "normal") {
@@ -34374,7 +34735,10 @@ var StoreRegistry = class {
34374
34735
  return prepared;
34375
34736
  }
34376
34737
  computeRegistrationDeeply(element, config) {
34377
- const items = typeof element.register === "function" ? element.register(config) : element.register;
34738
+ let items = typeof element.register === "function" ? element.register(config) : element.register;
34739
+ if (!items) {
34740
+ items = [];
34741
+ }
34378
34742
  element.register = items;
34379
34743
  for (const item of items) {
34380
34744
  this.storeGenericItem(item);
@@ -34912,25 +35276,27 @@ var InterceptorRegistry = class {
34912
35276
  * Gets all global task interceptors
34913
35277
  */
34914
35278
  getGlobalTaskInterceptors() {
34915
- return this.taskInterceptors;
35279
+ return Object.freeze([...this.taskInterceptors]);
34916
35280
  }
34917
35281
  /**
34918
35282
  * Gets all global resource interceptors
34919
35283
  */
34920
35284
  getGlobalResourceInterceptors() {
34921
- return this.resourceInterceptors;
35285
+ return Object.freeze([...this.resourceInterceptors]);
34922
35286
  }
34923
35287
  /**
34924
35288
  * Gets interceptors for a specific task middleware
34925
35289
  */
34926
35290
  getTaskMiddlewareInterceptors(middlewareId) {
34927
- return this.perTaskMiddleware.get(middlewareId) || [];
35291
+ const interceptors = this.perTaskMiddleware.get(middlewareId) ?? [];
35292
+ return Object.freeze([...interceptors]);
34928
35293
  }
34929
35294
  /**
34930
35295
  * Gets interceptors for a specific resource middleware
34931
35296
  */
34932
35297
  getResourceMiddlewareInterceptors(middlewareId) {
34933
- return this.perResourceMiddleware.get(middlewareId) || [];
35298
+ const interceptors = this.perResourceMiddleware.get(middlewareId) ?? [];
35299
+ return Object.freeze([...interceptors]);
34934
35300
  }
34935
35301
  };
34936
35302
 
@@ -35409,10 +35775,8 @@ var ResourceMiddlewareComposer = class {
35409
35775
 
35410
35776
  // src/models/MiddlewareManager.ts
35411
35777
  var MiddlewareManager = class {
35412
- constructor(store2, eventManager, logger) {
35778
+ constructor(store2, _eventManager, _logger) {
35413
35779
  this.store = store2;
35414
- this.eventManager = eventManager;
35415
- this.logger = logger;
35416
35780
  this.interceptorRegistry = new InterceptorRegistry();
35417
35781
  this.middlewareResolver = new MiddlewareResolver(store2);
35418
35782
  this.taskComposer = new TaskMiddlewareComposer(
@@ -35453,14 +35817,6 @@ var MiddlewareManager = class {
35453
35817
  lock() {
35454
35818
  this.interceptorRegistry.lock();
35455
35819
  }
35456
- /**
35457
- * Adds an interceptor for task or resource middleware execution
35458
- * Interceptors are executed in the order they are added, with the ability to
35459
- * modify, log, or prevent middleware execution
35460
- *
35461
- * @param kind - The type of middleware to intercept ("task" or "resource")
35462
- * @param interceptor - The interceptor function to add
35463
- */
35464
35820
  intercept(kind, interceptor) {
35465
35821
  if (kind === "task") {
35466
35822
  this.interceptorRegistry.addGlobalTaskInterceptor(
@@ -35472,13 +35828,6 @@ var MiddlewareManager = class {
35472
35828
  );
35473
35829
  }
35474
35830
  }
35475
- /**
35476
- * Adds an interceptor for a specific middleware instance with better type safety
35477
- * This method automatically determines the type and provides type-safe access
35478
- *
35479
- * @param middleware - The middleware instance to intercept
35480
- * @param interceptor - The interceptor function with proper typing
35481
- */
35482
35831
  interceptMiddleware(middleware, interceptor) {
35483
35832
  if (isTaskMiddleware(middleware)) {
35484
35833
  this.interceptorRegistry.addTaskMiddlewareInterceptor(
@@ -35617,12 +35966,17 @@ var Store = class {
35617
35966
  }
35618
35967
  }
35619
35968
  registerGlobalComponents() {
35969
+ if (!this.taskRunner) {
35970
+ throw new Error(
35971
+ "TaskRunner is not set. Call store.setTaskRunner() before initializeStore()."
35972
+ );
35973
+ }
35620
35974
  const builtInResourcesMap = /* @__PURE__ */ new Map();
35621
35975
  builtInResourcesMap.set(globalResources.store, this);
35622
35976
  builtInResourcesMap.set(globalResources.eventManager, this.eventManager);
35623
35977
  builtInResourcesMap.set(globalResources.logger, this.logger);
35624
35978
  builtInResourcesMap.set(globalResources.taskRunner, this.taskRunner);
35625
- builtInResourcesMap.set(globalResources.serializer, getDefaultSerializer());
35979
+ builtInResourcesMap.set(globalResources.serializer, new Serializer());
35626
35980
  builtInResourcesMap.set(
35627
35981
  globalResources.middlewareManager,
35628
35982
  this.middlewareManager
@@ -35682,8 +36036,11 @@ var Store = class {
35682
36036
  setTaskRunner(taskRunner) {
35683
36037
  this.taskRunner = taskRunner;
35684
36038
  }
35685
- setupRootResource(root, config) {
35686
- root.dependencies = typeof root.dependencies === "function" ? root.dependencies(config) : root.dependencies;
36039
+ setupRootResource(rootDefinition, config) {
36040
+ const root = {
36041
+ ...rootDefinition,
36042
+ dependencies: typeof rootDefinition.dependencies === "function" ? rootDefinition.dependencies(config) : rootDefinition.dependencies
36043
+ };
35687
36044
  this.root = {
35688
36045
  resource: root,
35689
36046
  computedDependencies: {},
@@ -36236,6 +36593,18 @@ var RunResult = class {
36236
36593
  }
36237
36594
  return this.store.resources.get(resourceId).value;
36238
36595
  }, "getResourceValue");
36596
+ /**
36597
+ * Get the config of a resource from the run result.
36598
+ * @param resource - The resource to get the config of.
36599
+ * @returns The config passed for the resource.
36600
+ */
36601
+ this.getResourceConfig = /* @__PURE__ */ __name((resource2) => {
36602
+ const resourceId = typeof resource2 === "string" ? resource2 : resource2.id;
36603
+ if (!this.store.resources.has(resourceId)) {
36604
+ throw new Error(`Resource "${resourceId}" not found.`);
36605
+ }
36606
+ return this.store.resources.get(resourceId).config;
36607
+ }, "getResourceConfig");
36239
36608
  this.dispose = /* @__PURE__ */ __name(() => {
36240
36609
  return this.disposeFn();
36241
36610
  }, "dispose");
@@ -37417,7 +37786,7 @@ function makeAsyncContextBuilder(state) {
37417
37786
  configSchema: state.configSchema,
37418
37787
  meta: state.meta
37419
37788
  };
37420
- return defineAsyncContext(def);
37789
+ return defineAsyncContext(def, state.filePath);
37421
37790
  }
37422
37791
  };
37423
37792
  return builder;
@@ -37426,8 +37795,10 @@ __name(makeAsyncContextBuilder, "makeAsyncContextBuilder");
37426
37795
 
37427
37796
  // src/definers/builders/asyncContext/index.ts
37428
37797
  function asyncContextBuilder(id2) {
37798
+ const filePath = getCallerFile();
37429
37799
  const initial = Object.freeze({
37430
37800
  id: id2,
37801
+ filePath,
37431
37802
  serialize: void 0,
37432
37803
  parse: void 0,
37433
37804
  configSchema: void 0,
@@ -37900,7 +38271,7 @@ function override(base) {
37900
38271
  }
37901
38272
  __name(override, "override");
37902
38273
 
37903
- // src/index.ts
38274
+ // src/public.ts
37904
38275
  init_http_fetch_tunnel_resource();
37905
38276
  var globals = {
37906
38277
  events: globalEvents,
@@ -39044,15 +39415,15 @@ var UNSAFE_ERROR_FIELDS = /* @__PURE__ */ new Set([
39044
39415
  "cause" /* Cause */,
39045
39416
  "sql" /* Sql */
39046
39417
  ]);
39047
- var isRecord = /* @__PURE__ */ __name((value) => !!value && typeof value === "object", "isRecord");
39048
- var isJsonBody = /* @__PURE__ */ __name((value) => isRecord(value) && typeof value.ok === "boolean", "isJsonBody");
39049
- var toErrorRecord = /* @__PURE__ */ __name((value) => isRecord(value) ? value : void 0, "toErrorRecord");
39418
+ var isRecord2 = /* @__PURE__ */ __name((value) => !!value && typeof value === "object", "isRecord");
39419
+ var isJsonBody = /* @__PURE__ */ __name((value) => isRecord2(value) && typeof value.ok === "boolean", "isJsonBody");
39420
+ var toErrorRecord = /* @__PURE__ */ __name((value) => isRecord2(value) ? value : void 0, "toErrorRecord");
39050
39421
  var sanitizeErrorResponse = /* @__PURE__ */ __name((response) => {
39051
- const asRecord = isRecord(response) ? response : void 0;
39422
+ const asRecord = isRecord2(response) ? response : void 0;
39052
39423
  const statusRaw = asRecord?.status ?? asRecord?.statusCode;
39053
39424
  const status = typeof statusRaw === "number" && Number.isFinite(statusRaw) ? statusRaw : 500;
39054
39425
  const bodyRaw = asRecord?.body;
39055
- const body = isRecord(bodyRaw) ? bodyRaw : void 0;
39426
+ const body = isRecord2(bodyRaw) ? bodyRaw : void 0;
39056
39427
  const errorRaw = (body ? toErrorRecord(body.error) : void 0) ?? toErrorRecord(asRecord?.error);
39057
39428
  const normalizedBody = (() => {
39058
39429
  if (isJsonBody(bodyRaw)) {
@@ -39109,7 +39480,7 @@ var resolveAppErrorExtra = /* @__PURE__ */ __name((store2, error2) => {
39109
39480
  try {
39110
39481
  for (const helper of store2.errors.values()) {
39111
39482
  if (helper.is(error2)) {
39112
- if (!isRecord(error2)) return { id: void 0, data: void 0 };
39483
+ if (!isRecord2(error2)) return { id: void 0, data: void 0 };
39113
39484
  const name = error2["name" /* Name */];
39114
39485
  const id2 = typeof name === "string" ? name : void 0;
39115
39486
  const data = error2["data" /* Data */];
@@ -39825,10 +40196,10 @@ function createDurableStepId(id2) {
39825
40196
  return { id: id2 };
39826
40197
  }
39827
40198
  __name(createDurableStepId, "createDurableStepId");
39828
- function isRecord2(value) {
40199
+ function isRecord3(value) {
39829
40200
  return typeof value === "object" && value !== null;
39830
40201
  }
39831
- __name(isRecord2, "isRecord");
40202
+ __name(isRecord3, "isRecord");
39832
40203
  function sleepMs(ms) {
39833
40204
  return new Promise((resolve) => {
39834
40205
  const timer = timers.setTimeout(resolve, ms);
@@ -39858,7 +40229,7 @@ function createExecutionId() {
39858
40229
  }
39859
40230
  __name(createExecutionId, "createExecutionId");
39860
40231
  function parseSignalState(value) {
39861
- if (!isRecord2(value)) return null;
40232
+ if (!isRecord3(value)) return null;
39862
40233
  const state = value.state;
39863
40234
  if (state === "waiting") {
39864
40235
  const timerId = value.timerId;
@@ -39900,6 +40271,7 @@ var DurableAuditEntryKind = {
39900
40271
  SignalDelivered: "signal_delivered",
39901
40272
  SignalTimedOut: "signal_timed_out",
39902
40273
  EmitPublished: "emit_published",
40274
+ SwitchEvaluated: "switch_evaluated",
39903
40275
  Note: "note"
39904
40276
  };
39905
40277
  function isDurableInternalStepId(stepId) {
@@ -39923,15 +40295,194 @@ var SuspensionSignal = class extends Error {
39923
40295
  }
39924
40296
  };
39925
40297
 
40298
+ // src/node/durable/core/DurableOperator.ts
40299
+ var DurableOperator = class {
40300
+ constructor(store2) {
40301
+ this.store = store2;
40302
+ }
40303
+ static {
40304
+ __name(this, "DurableOperator");
40305
+ }
40306
+ async listExecutions(options) {
40307
+ if (this.store.listExecutions) {
40308
+ return await this.store.listExecutions(options);
40309
+ }
40310
+ return await this.store.listIncompleteExecutions();
40311
+ }
40312
+ async getExecutionDetail(executionId) {
40313
+ const execution = await this.store.getExecution(executionId);
40314
+ const steps = this.store.listStepResults ? await this.store.listStepResults(executionId) : [];
40315
+ const audit = this.store.listAuditEntries ? await this.store.listAuditEntries(executionId) : [];
40316
+ return { execution, steps, audit };
40317
+ }
40318
+ /**
40319
+ * Resets an execution from `compensation_failed` (or other states) to `pending`.
40320
+ * This effectively retries the workflow from the last memoized step.
40321
+ */
40322
+ async retryRollback(executionId) {
40323
+ if (!this.store.retryRollback) {
40324
+ throw new Error("Store does not support retryRollback");
40325
+ }
40326
+ await this.store.retryRollback(executionId);
40327
+ }
40328
+ /**
40329
+ * Manually marks a step as completed with a specific result.
40330
+ * Useful for skipping broken steps or providing a manual fix.
40331
+ */
40332
+ async skipStep(executionId, stepId) {
40333
+ if (!this.store.skipStep) {
40334
+ throw new Error("Store does not support skipStep");
40335
+ }
40336
+ await this.store.skipStep(executionId, stepId);
40337
+ }
40338
+ /**
40339
+ * Forces an execution to the `failed` state.
40340
+ */
40341
+ async forceFail(executionId, reason) {
40342
+ if (!this.store.forceFail) {
40343
+ throw new Error("Store does not support forceFail");
40344
+ }
40345
+ await this.store.forceFail(executionId, { message: reason });
40346
+ }
40347
+ /**
40348
+ * Manually patches the result of a step.
40349
+ * Useful when a step failed to save its result but the side effect occurred.
40350
+ */
40351
+ async editState(executionId, stepId, newState) {
40352
+ if (!this.store.editStepResult) {
40353
+ throw new Error("Store does not support editStepResult");
40354
+ }
40355
+ await this.store.editStepResult(executionId, stepId, newState);
40356
+ }
40357
+ /**
40358
+ * Lists all executions that require manual intervention.
40359
+ */
40360
+ async listStuckExecutions() {
40361
+ if (!this.store.listStuckExecutions) {
40362
+ throw new Error("Store does not support listStuckExecutions");
40363
+ }
40364
+ return await this.store.listStuckExecutions();
40365
+ }
40366
+ };
40367
+
40368
+ // src/node/durable/core/flowShape.ts
40369
+ var FlowRecorder = class {
40370
+ constructor() {
40371
+ this.nodes = [];
40372
+ this.executionId = "__flow_record__";
40373
+ this.attempt = 0;
40374
+ }
40375
+ static {
40376
+ __name(this, "FlowRecorder");
40377
+ }
40378
+ resolveStepId(stepId) {
40379
+ return typeof stepId === "string" ? stepId : stepId.id;
40380
+ }
40381
+ step(stepId, optionsOrFn, _fn) {
40382
+ const id2 = this.resolveStepId(stepId);
40383
+ if (optionsOrFn === void 0) {
40384
+ return new FlowStepRecorder(this, id2);
40385
+ }
40386
+ this.nodes.push({ kind: "step", stepId: id2, hasCompensation: false });
40387
+ return Promise.resolve(void 0);
40388
+ }
40389
+ async sleep(durationMs, options) {
40390
+ this.nodes.push({
40391
+ kind: "sleep",
40392
+ durationMs,
40393
+ stepId: options?.stepId
40394
+ });
40395
+ }
40396
+ async waitForSignal(signal, options) {
40397
+ this.nodes.push({
40398
+ kind: "waitForSignal",
40399
+ signalId: signal.id,
40400
+ timeoutMs: options?.timeoutMs,
40401
+ stepId: options?.stepId
40402
+ });
40403
+ return void 0;
40404
+ }
40405
+ async emit(_event, _payload, options) {
40406
+ this.nodes.push({
40407
+ kind: "emit",
40408
+ eventId: _event.id,
40409
+ stepId: options?.stepId
40410
+ });
40411
+ }
40412
+ async switch(stepId, _value, branches, defaultBranch) {
40413
+ this.nodes.push({
40414
+ kind: "switch",
40415
+ stepId,
40416
+ branchIds: branches.map((b) => b.id),
40417
+ hasDefault: defaultBranch !== void 0
40418
+ });
40419
+ return void 0;
40420
+ }
40421
+ async note(message, _meta) {
40422
+ this.nodes.push({ kind: "note", message });
40423
+ }
40424
+ async rollback() {
40425
+ }
40426
+ };
40427
+ var FlowStepRecorder = class {
40428
+ constructor(recorder, stepId) {
40429
+ this.recorder = recorder;
40430
+ this.stepId = stepId;
40431
+ this.hasDown = false;
40432
+ }
40433
+ static {
40434
+ __name(this, "FlowStepRecorder");
40435
+ }
40436
+ up(_fn) {
40437
+ return this;
40438
+ }
40439
+ down(_fn) {
40440
+ this.hasDown = true;
40441
+ return this;
40442
+ }
40443
+ then(onfulfilled, onrejected) {
40444
+ this.recorder.nodes.push({
40445
+ kind: "step",
40446
+ stepId: this.stepId,
40447
+ hasCompensation: this.hasDown
40448
+ });
40449
+ const result = Promise.resolve(void 0);
40450
+ return result.then(
40451
+ onfulfilled ?? ((v) => v),
40452
+ onrejected
40453
+ );
40454
+ }
40455
+ };
40456
+ async function recordFlowShape(descriptor) {
40457
+ const recorder = new FlowRecorder();
40458
+ await descriptor(recorder);
40459
+ return { nodes: recorder.nodes };
40460
+ }
40461
+ __name(recordFlowShape, "recordFlowShape");
40462
+
39926
40463
  // src/node/durable/core/DurableResource.ts
39927
- var DurableResource = class {
39928
- constructor(service, contextStorage) {
40464
+ var DurableResource = class _DurableResource {
40465
+ constructor(service, contextStorage, store2, runnerStore) {
39929
40466
  this.service = service;
39930
40467
  this.contextStorage = contextStorage;
40468
+ this.store = store2;
40469
+ this.runnerStore = runnerStore;
40470
+ this.operatorInstance = null;
39931
40471
  }
39932
40472
  static {
39933
40473
  __name(this, "DurableResource");
39934
40474
  }
40475
+ get operator() {
40476
+ if (!this.store) {
40477
+ throw new Error(
40478
+ "Durable operator API is not available: store was not provided to DurableResource. Use a Runner durable resource (durableResource/memoryDurableResource/redisDurableResource) or construct a DurableOperator(store) directly."
40479
+ );
40480
+ }
40481
+ if (!this.operatorInstance) {
40482
+ this.operatorInstance = new DurableOperator(this.store);
40483
+ }
40484
+ return this.operatorInstance;
40485
+ }
39935
40486
  use() {
39936
40487
  const ctx = this.contextStorage.getStore();
39937
40488
  if (!ctx) {
@@ -39941,6 +40492,47 @@ var DurableResource = class {
39941
40492
  }
39942
40493
  return ctx;
39943
40494
  }
40495
+ async describe(task2, input) {
40496
+ if (!this.runnerStore) {
40497
+ throw new Error(
40498
+ "Durable describe API is not available: runner store was not provided to DurableResource. Use a Runner durable resource (durableResource/memoryDurableResource/redisDurableResource) instead of manually constructing DurableResource."
40499
+ );
40500
+ }
40501
+ const storeTask = this.runnerStore.tasks.get(task2.id);
40502
+ if (!storeTask) {
40503
+ throw new Error(
40504
+ `Cannot describe task "${task2.id}": task is not registered in the runtime store.`
40505
+ );
40506
+ }
40507
+ const effectiveTask = storeTask.task;
40508
+ if (!storeTask.computedDependencies) {
40509
+ throw new Error(
40510
+ `Cannot describe task "${task2.id}": task dependencies are not available in the runtime store.`
40511
+ );
40512
+ }
40513
+ const deps = storeTask.computedDependencies;
40514
+ return await recordFlowShape(async (ctx) => {
40515
+ const depsWithRecorder = this.injectRecorderIntoDurableDeps(deps, ctx);
40516
+ await effectiveTask.run(input, depsWithRecorder);
40517
+ });
40518
+ }
40519
+ injectRecorderIntoDurableDeps(deps, ctx) {
40520
+ const next = { ...deps };
40521
+ for (const [key, value] of Object.entries(deps)) {
40522
+ if (!(value instanceof _DurableResource)) {
40523
+ continue;
40524
+ }
40525
+ next[key] = new Proxy(value, {
40526
+ get(target, prop, receiver) {
40527
+ if (prop === "use") {
40528
+ return () => ctx;
40529
+ }
40530
+ return Reflect.get(target, prop, receiver);
40531
+ }
40532
+ });
40533
+ }
40534
+ return next;
40535
+ }
39944
40536
  startExecution(task2, input, options) {
39945
40537
  return this.service.startExecution(task2, input, options);
39946
40538
  }
@@ -40636,7 +41228,7 @@ var ScheduleManager = class {
40636
41228
  // src/node/durable/core/managers/SignalHandler.ts
40637
41229
  var isWaitingSignalStep = /* @__PURE__ */ __name((step) => {
40638
41230
  const result = step.result;
40639
- if (!isRecord2(result)) return false;
41231
+ if (!isRecord3(result)) return false;
40640
41232
  const waitResult = result;
40641
41233
  if (waitResult.state !== "waiting") return false;
40642
41234
  if (typeof waitResult.signalId !== "string") return false;
@@ -41113,7 +41705,7 @@ function getSignalId(signal) {
41113
41705
  }
41114
41706
  __name(getSignalId, "getSignalId");
41115
41707
  function parseSignalStepState(value) {
41116
- if (!isRecord2(value)) return null;
41708
+ if (!isRecord3(value)) return null;
41117
41709
  const state = value.state;
41118
41710
  if (state === "waiting") {
41119
41711
  const signalId = value.signalId;
@@ -41309,6 +41901,58 @@ async function waitForSignalDurably(params) {
41309
41901
  }
41310
41902
  __name(waitForSignalDurably, "waitForSignalDurably");
41311
41903
 
41904
+ // src/node/durable/core/durable-context/DurableContext.switch.ts
41905
+ async function switchDurably(params) {
41906
+ await params.assertNotCancelled();
41907
+ params.assertUniqueStepId(params.stepId);
41908
+ const cached = await params.store.getStepResult(
41909
+ params.executionId,
41910
+ params.stepId
41911
+ );
41912
+ if (cached) {
41913
+ const persisted = cached.result;
41914
+ return persisted.result;
41915
+ }
41916
+ const startedAt = Date.now();
41917
+ let matchedBranch = null;
41918
+ for (const branch of params.branches) {
41919
+ if (branch.match(params.value)) {
41920
+ matchedBranch = { id: branch.id, run: branch.run };
41921
+ break;
41922
+ }
41923
+ }
41924
+ if (!matchedBranch && params.defaultBranch) {
41925
+ matchedBranch = {
41926
+ id: params.defaultBranch.id,
41927
+ run: params.defaultBranch.run
41928
+ };
41929
+ }
41930
+ if (!matchedBranch) {
41931
+ throw new Error(
41932
+ `Durable switch '${params.stepId}': no branch matched and no default provided`
41933
+ );
41934
+ }
41935
+ const result = await matchedBranch.run(params.value);
41936
+ const durationMs = Date.now() - startedAt;
41937
+ await params.store.saveStepResult({
41938
+ executionId: params.executionId,
41939
+ stepId: params.stepId,
41940
+ result: {
41941
+ branchId: matchedBranch.id,
41942
+ result
41943
+ },
41944
+ completedAt: /* @__PURE__ */ new Date()
41945
+ });
41946
+ await params.appendAuditEntry({
41947
+ kind: DurableAuditEntryKind.SwitchEvaluated,
41948
+ stepId: params.stepId,
41949
+ branchId: matchedBranch.id,
41950
+ durationMs
41951
+ });
41952
+ return result;
41953
+ }
41954
+ __name(switchDurably, "switchDurably");
41955
+
41312
41956
  // src/node/durable/core/DurableContext.ts
41313
41957
  var DurableContext = class {
41314
41958
  constructor(store2, bus, executionId, attempt, options = {}) {
@@ -41429,6 +42073,20 @@ var DurableContext = class {
41429
42073
  options
41430
42074
  });
41431
42075
  }
42076
+ async switch(stepId, value, branches, defaultBranch) {
42077
+ this.determinism.assertUserStepId(stepId);
42078
+ return await switchDurably({
42079
+ store: this.store,
42080
+ executionId: this.executionId,
42081
+ assertNotCancelled: this.assertNotCancelled.bind(this),
42082
+ appendAuditEntry: this.audit.append,
42083
+ assertUniqueStepId: this.determinism.assertUniqueStepId,
42084
+ stepId,
42085
+ value,
42086
+ branches,
42087
+ defaultBranch
42088
+ });
42089
+ }
41432
42090
  async note(message, meta) {
41433
42091
  if (!this.audit.isEnabled()) return;
41434
42092
  const stepId = `__note:${this.noteIndex}`;
@@ -42242,13 +42900,11 @@ async function initDurableWorker(service, queue) {
42242
42900
  }
42243
42901
  __name(initDurableWorker, "initDurableWorker");
42244
42902
 
42245
- // src/node/durable/core/resource.ts
42246
- var durableResource = r.resource("base.durable").register(durableEventsArray).dependencies({
42247
- taskRunner: globals.resources.taskRunner,
42248
- eventManager: globals.resources.eventManager,
42249
- runnerStore: globals.resources.store
42250
- }).init(async (config, { taskRunner, eventManager, runnerStore }) => {
42251
- const runnerEmitter = createDurableRunnerAuditEmitter({ eventManager });
42903
+ // src/node/durable/core/createRunnerDurableRuntime.ts
42904
+ async function createRunnerDurableRuntime(config, deps) {
42905
+ const runnerEmitter = createDurableRunnerAuditEmitter({
42906
+ eventManager: deps.eventManager
42907
+ });
42252
42908
  const userEmitter = config.audit?.emitter;
42253
42909
  const auditEmitter = userEmitter ? {
42254
42910
  emit: /* @__PURE__ */ __name(async (entry) => {
@@ -42271,7 +42927,10 @@ var durableResource = r.resource("base.durable").register(durableEventsArray).de
42271
42927
  },
42272
42928
  taskExecutor: {
42273
42929
  run: /* @__PURE__ */ __name(async (task2, input) => {
42274
- const outputPromise = await taskRunner.run(task2, input);
42930
+ const outputPromise = await deps.taskRunner.run(
42931
+ task2,
42932
+ input
42933
+ );
42275
42934
  if (outputPromise === void 0) {
42276
42935
  throw new Error(
42277
42936
  `Durable task '${task2.id}' completed without a result promise.`
@@ -42281,7 +42940,7 @@ var durableResource = r.resource("base.durable").register(durableEventsArray).de
42281
42940
  }, "run")
42282
42941
  },
42283
42942
  taskResolver: /* @__PURE__ */ __name((taskId) => {
42284
- const storeTask = runnerStore.tasks.get(taskId);
42943
+ const storeTask = deps.runnerStore.tasks.get(taskId);
42285
42944
  return storeTask?.task;
42286
42945
  }, "taskResolver"),
42287
42946
  contextProvider: /* @__PURE__ */ __name((ctx, fn) => contextStorage.run(ctx, fn), "contextProvider")
@@ -42289,81 +42948,30 @@ var durableResource = r.resource("base.durable").register(durableEventsArray).de
42289
42948
  if (config.worker === true && config.queue) {
42290
42949
  await initDurableWorker(service, config.queue);
42291
42950
  }
42292
- return new DurableResource(service, contextStorage);
42951
+ return new DurableResource(
42952
+ service,
42953
+ contextStorage,
42954
+ config.store,
42955
+ deps.runnerStore
42956
+ );
42957
+ }
42958
+ __name(createRunnerDurableRuntime, "createRunnerDurableRuntime");
42959
+
42960
+ // src/node/durable/core/resource.ts
42961
+ var durableResource = r.resource("base.durable").register(durableEventsArray).dependencies({
42962
+ taskRunner: globals.resources.taskRunner,
42963
+ eventManager: globals.resources.eventManager,
42964
+ runnerStore: globals.resources.store
42965
+ }).init(async (config, { taskRunner, eventManager, runnerStore }) => {
42966
+ return await createRunnerDurableRuntime(config, {
42967
+ taskRunner,
42968
+ eventManager,
42969
+ runnerStore
42970
+ });
42293
42971
  }).dispose(
42294
42972
  async (durable, config) => disposeDurableService(durable.service, config)
42295
42973
  ).build();
42296
42974
 
42297
- // src/node/durable/core/DurableOperator.ts
42298
- var DurableOperator = class {
42299
- constructor(store2) {
42300
- this.store = store2;
42301
- }
42302
- static {
42303
- __name(this, "DurableOperator");
42304
- }
42305
- async listExecutions(options) {
42306
- if (this.store.listExecutions) {
42307
- return await this.store.listExecutions(options);
42308
- }
42309
- return await this.store.listIncompleteExecutions();
42310
- }
42311
- async getExecutionDetail(executionId) {
42312
- const execution = await this.store.getExecution(executionId);
42313
- const steps = this.store.listStepResults ? await this.store.listStepResults(executionId) : [];
42314
- const audit = this.store.listAuditEntries ? await this.store.listAuditEntries(executionId) : [];
42315
- return { execution, steps, audit };
42316
- }
42317
- /**
42318
- * Resets an execution from `compensation_failed` (or other states) to `pending`.
42319
- * This effectively retries the workflow from the last memoized step.
42320
- */
42321
- async retryRollback(executionId) {
42322
- if (!this.store.retryRollback) {
42323
- throw new Error("Store does not support retryRollback");
42324
- }
42325
- await this.store.retryRollback(executionId);
42326
- }
42327
- /**
42328
- * Manually marks a step as completed with a specific result.
42329
- * Useful for skipping broken steps or providing a manual fix.
42330
- */
42331
- async skipStep(executionId, stepId) {
42332
- if (!this.store.skipStep) {
42333
- throw new Error("Store does not support skipStep");
42334
- }
42335
- await this.store.skipStep(executionId, stepId);
42336
- }
42337
- /**
42338
- * Forces an execution to the `failed` state.
42339
- */
42340
- async forceFail(executionId, reason) {
42341
- if (!this.store.forceFail) {
42342
- throw new Error("Store does not support forceFail");
42343
- }
42344
- await this.store.forceFail(executionId, { message: reason });
42345
- }
42346
- /**
42347
- * Manually patches the result of a step.
42348
- * Useful when a step failed to save its result but the side effect occurred.
42349
- */
42350
- async editState(executionId, stepId, newState) {
42351
- if (!this.store.editStepResult) {
42352
- throw new Error("Store does not support editStepResult");
42353
- }
42354
- await this.store.editStepResult(executionId, stepId, newState);
42355
- }
42356
- /**
42357
- * Lists all executions that require manual intervention.
42358
- */
42359
- async listStuckExecutions() {
42360
- if (!this.store.listStuckExecutions) {
42361
- throw new Error("Store does not support listStuckExecutions");
42362
- }
42363
- return await this.store.listStuckExecutions();
42364
- }
42365
- };
42366
-
42367
42975
  // src/node/durable/dashboard/server.ts
42368
42976
  var express = __toESM(require_express2());
42369
42977
  function findUp(startDir, filename) {
@@ -42747,7 +43355,7 @@ function createIORedisClient(url) {
42747
43355
  __name(createIORedisClient, "createIORedisClient");
42748
43356
 
42749
43357
  // src/node/durable/store/RedisStore.ts
42750
- var serializer2 = getDefaultSerializer();
43358
+ var serializer2 = new Serializer();
42751
43359
  var RedisStore = class {
42752
43360
  static {
42753
43361
  __name(this, "RedisStore");
@@ -43491,6 +44099,114 @@ async function waitUntil(predicate, options) {
43491
44099
  }
43492
44100
  __name(waitUntil, "waitUntil");
43493
44101
 
44102
+ // src/node/durable/resources/memoryDurableResource.ts
44103
+ var memoryDurableResource = r.resource("base.durable.memory").register(durableEventsArray).dependencies({
44104
+ taskRunner: globals.resources.taskRunner,
44105
+ eventManager: globals.resources.eventManager,
44106
+ runnerStore: globals.resources.store
44107
+ }).context(() => ({ runtimeConfig: null })).init(async function(config, { taskRunner, eventManager, runnerStore }, ctx) {
44108
+ config.namespace ?? this.id;
44109
+ const shouldCreateQueue = config.queue?.enabled ?? config.worker === true;
44110
+ const queue = shouldCreateQueue ? new MemoryQueue() : void 0;
44111
+ const worker = config.worker ?? Boolean(queue);
44112
+ const runtimeConfig = {
44113
+ ...config,
44114
+ worker,
44115
+ store: new MemoryStore(),
44116
+ eventBus: new MemoryEventBus(),
44117
+ queue
44118
+ };
44119
+ ctx.runtimeConfig = runtimeConfig;
44120
+ return await createRunnerDurableRuntime(runtimeConfig, {
44121
+ taskRunner,
44122
+ eventManager,
44123
+ runnerStore
44124
+ });
44125
+ }).dispose(async (durable, _config, _deps, ctx) => {
44126
+ if (!ctx.runtimeConfig) return;
44127
+ await disposeDurableService(durable.service, ctx.runtimeConfig);
44128
+ }).build();
44129
+
44130
+ // src/node/durable/resources/isolation.ts
44131
+ function normalizePrefix(prefix) {
44132
+ return prefix.endsWith(":") ? prefix : `${prefix}:`;
44133
+ }
44134
+ __name(normalizePrefix, "normalizePrefix");
44135
+ function deriveDurableIsolation(params) {
44136
+ if (params.namespace.trim().length === 0) {
44137
+ validationError.throw({
44138
+ subject: "Durable isolation namespace",
44139
+ id: "params.namespace",
44140
+ originalError: "must be a non-empty string"
44141
+ });
44142
+ }
44143
+ const encodedNamespace = encodeURIComponent(params.namespace);
44144
+ const storePrefix = normalizePrefix(
44145
+ params.storePrefix ?? `durable:${encodedNamespace}:`
44146
+ );
44147
+ const busPrefix = normalizePrefix(
44148
+ params.busPrefix ?? `durable:bus:${encodedNamespace}:`
44149
+ );
44150
+ return {
44151
+ namespace: params.namespace,
44152
+ encodedNamespace,
44153
+ storePrefix,
44154
+ busPrefix,
44155
+ queueName: params.queueName ?? `durable_executions:${encodedNamespace}`,
44156
+ deadLetterQueueName: params.deadLetterQueueName ?? `durable_executions:dlq:${encodedNamespace}`
44157
+ };
44158
+ }
44159
+ __name(deriveDurableIsolation, "deriveDurableIsolation");
44160
+
44161
+ // src/node/durable/resources/redisDurableResource.ts
44162
+ var redisDurableResource = r.resource("base.durable.redis").register(durableEventsArray).dependencies({
44163
+ taskRunner: globals.resources.taskRunner,
44164
+ eventManager: globals.resources.eventManager,
44165
+ runnerStore: globals.resources.store
44166
+ }).context(() => ({ runtimeConfig: null })).init(async function(config, { taskRunner, eventManager, runnerStore }, ctx) {
44167
+ const namespace = config.namespace ?? this.id;
44168
+ const isolation = deriveDurableIsolation({
44169
+ namespace,
44170
+ storePrefix: config.store?.prefix,
44171
+ busPrefix: config.eventBus?.prefix,
44172
+ queueName: config.queue?.name,
44173
+ deadLetterQueueName: config.queue?.deadLetter
44174
+ });
44175
+ const queue = config.queue ? new RabbitMQQueue({
44176
+ url: config.queue.url,
44177
+ prefetch: config.queue.prefetch,
44178
+ queue: {
44179
+ name: isolation.queueName,
44180
+ quorum: config.queue.quorum,
44181
+ deadLetter: isolation.deadLetterQueueName,
44182
+ messageTtl: config.queue.messageTtl
44183
+ }
44184
+ }) : void 0;
44185
+ const worker = config.worker ?? Boolean(queue);
44186
+ const runtimeConfig = {
44187
+ ...config,
44188
+ worker,
44189
+ store: new RedisStore({
44190
+ redis: config.redis.url,
44191
+ prefix: isolation.storePrefix
44192
+ }),
44193
+ eventBus: new RedisEventBus({
44194
+ redis: config.redis.url,
44195
+ prefix: isolation.busPrefix
44196
+ }),
44197
+ queue
44198
+ };
44199
+ ctx.runtimeConfig = runtimeConfig;
44200
+ return await createRunnerDurableRuntime(runtimeConfig, {
44201
+ taskRunner,
44202
+ eventManager,
44203
+ runnerStore
44204
+ });
44205
+ }).dispose(async (durable, _config, _deps, ctx) => {
44206
+ if (!ctx.runtimeConfig) return;
44207
+ await disposeDurableService(durable.service, ctx.runtimeConfig);
44208
+ }).build();
44209
+
43494
44210
  // src/node/node.ts
43495
44211
  var globals2 = {
43496
44212
  ...globals,
@@ -43832,11 +44548,13 @@ exports.DurableWorker = DurableWorker;
43832
44548
  exports.Errors = errors_exports;
43833
44549
  exports.EventManager = EventManager;
43834
44550
  exports.ExecutionStatus = ExecutionStatus;
44551
+ exports.LogPrinter = LogPrinter;
43835
44552
  exports.Logger = Logger;
43836
44553
  exports.MemoryEventBus = MemoryEventBus;
43837
44554
  exports.MemoryQueue = MemoryQueue;
43838
44555
  exports.MemoryStore = MemoryStore;
43839
44556
  exports.MiddlewareManager = MiddlewareManager;
44557
+ exports.NodeInputFile = NodeInputFile;
43840
44558
  exports.NoopEventBus = NoopEventBus;
43841
44559
  exports.PlatformAdapter = PlatformAdapter;
43842
44560
  exports.Queue = Queue;
@@ -43852,6 +44570,8 @@ exports.Serializer = Serializer;
43852
44570
  exports.StepBuilder = StepBuilder;
43853
44571
  exports.Store = Store;
43854
44572
  exports.SuspensionSignal = SuspensionSignal;
44573
+ exports.SymbolPolicy = SymbolPolicy;
44574
+ exports.SymbolPolicyErrorMessage = SymbolPolicyErrorMessage;
43855
44575
  exports.TaskRunner = TaskRunner;
43856
44576
  exports.TimerStatus = TimerStatus;
43857
44577
  exports.TimerType = TimerType;
@@ -43870,6 +44590,7 @@ exports.createHttpClient = createHttpClient;
43870
44590
  exports.createHttpMixedClient = createHttpMixedClient;
43871
44591
  exports.createHttpSmartClient = createHttpSmartClient;
43872
44592
  exports.createNodeFile = createNodeFile;
44593
+ exports.createRunnerDurableRuntime = createRunnerDurableRuntime;
43873
44594
  exports.createTestResource = createTestResource;
43874
44595
  exports.debug = debug;
43875
44596
  exports.debugLevels = debugLevels;
@@ -43880,7 +44601,6 @@ exports.durableEventsArray = durableEventsArray;
43880
44601
  exports.durableResource = durableResource;
43881
44602
  exports.event = defineEvent;
43882
44603
  exports.getConfig = getConfig;
43883
- exports.getDefaultSerializer = getDefaultSerializer;
43884
44604
  exports.globals = globals2;
43885
44605
  exports.hasExposureContext = hasExposureContext;
43886
44606
  exports.hook = defineHook;
@@ -43890,11 +44610,13 @@ exports.isDurableInternalStepId = isDurableInternalStepId;
43890
44610
  exports.journal = journal;
43891
44611
  exports.levelNormal = levelNormal;
43892
44612
  exports.levelVerbose = levelVerbose;
44613
+ exports.memoryDurableResource = memoryDurableResource;
43893
44614
  exports.nodeExposure = nodeExposure;
43894
44615
  exports.normalizeError = normalizeError;
43895
44616
  exports.override = defineOverride;
43896
44617
  exports.r = r;
43897
44618
  exports.readInputFileToBuffer = readInputFileToBuffer;
44619
+ exports.redisDurableResource = redisDurableResource;
43898
44620
  exports.resource = defineResource;
43899
44621
  exports.resourceMiddleware = defineResourceMiddleware;
43900
44622
  exports.run = run2;