@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
@@ -2639,10 +2639,10 @@ var require_bom_handling = __commonJS({
2639
2639
  // node_modules/raw-body/node_modules/iconv-lite/lib/helpers/merge-exports.js
2640
2640
  var require_merge_exports = __commonJS({
2641
2641
  "node_modules/raw-body/node_modules/iconv-lite/lib/helpers/merge-exports.js"(exports, module) {
2642
- var hasOwn2 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
2642
+ var hasOwn3 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
2643
2643
  function mergeModules(target, module2) {
2644
2644
  for (var key in module2) {
2645
- if (hasOwn2(module2, key)) {
2645
+ if (hasOwn3(module2, key)) {
2646
2646
  target[key] = module2[key];
2647
2647
  }
2648
2648
  }
@@ -6613,10 +6613,10 @@ var require_bom_handling2 = __commonJS({
6613
6613
  // node_modules/body-parser/node_modules/iconv-lite/lib/helpers/merge-exports.js
6614
6614
  var require_merge_exports2 = __commonJS({
6615
6615
  "node_modules/body-parser/node_modules/iconv-lite/lib/helpers/merge-exports.js"(exports, module) {
6616
- var hasOwn2 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
6616
+ var hasOwn3 = typeof Object.hasOwn === "undefined" ? Function.call.bind(Object.prototype.hasOwnProperty) : Object.hasOwn;
6617
6617
  function mergeModules(target, module2) {
6618
6618
  for (var key in module2) {
6619
- if (hasOwn2(module2, key)) {
6619
+ if (hasOwn3(module2, key)) {
6620
6620
  target[key] = module2[key];
6621
6621
  }
6622
6622
  }
@@ -20940,11 +20940,11 @@ var require_object_inspect = __commonJS({
20940
20940
  return false;
20941
20941
  }
20942
20942
  __name(isBigInt, "isBigInt");
20943
- var hasOwn2 = Object.prototype.hasOwnProperty || function(key) {
20943
+ var hasOwn3 = Object.prototype.hasOwnProperty || function(key) {
20944
20944
  return key in this;
20945
20945
  };
20946
20946
  function has(obj, key) {
20947
- return hasOwn2.call(obj, key);
20947
+ return hasOwn3.call(obj, key);
20948
20948
  }
20949
20949
  __name(has, "has");
20950
20950
  function toStr(obj) {
@@ -21927,7 +21927,7 @@ var require_get_intrinsic = __commonJS({
21927
21927
  "%WeakSetPrototype%": ["WeakSet", "prototype"]
21928
21928
  };
21929
21929
  var bind = require_function_bind();
21930
- var hasOwn2 = require_hasown();
21930
+ var hasOwn3 = require_hasown();
21931
21931
  var $concat = bind.call($call, Array.prototype.concat);
21932
21932
  var $spliceApply = bind.call($apply, Array.prototype.splice);
21933
21933
  var $replace = bind.call($call, String.prototype.replace);
@@ -21952,11 +21952,11 @@ var require_get_intrinsic = __commonJS({
21952
21952
  var getBaseIntrinsic = /* @__PURE__ */ __name(function getBaseIntrinsic2(name, allowMissing) {
21953
21953
  var intrinsicName = name;
21954
21954
  var alias;
21955
- if (hasOwn2(LEGACY_ALIASES, intrinsicName)) {
21955
+ if (hasOwn3(LEGACY_ALIASES, intrinsicName)) {
21956
21956
  alias = LEGACY_ALIASES[intrinsicName];
21957
21957
  intrinsicName = "%" + alias[0] + "%";
21958
21958
  }
21959
- if (hasOwn2(INTRINSICS, intrinsicName)) {
21959
+ if (hasOwn3(INTRINSICS, intrinsicName)) {
21960
21960
  var value = INTRINSICS[intrinsicName];
21961
21961
  if (value === needsEval) {
21962
21962
  value = doEval(intrinsicName);
@@ -22005,7 +22005,7 @@ var require_get_intrinsic = __commonJS({
22005
22005
  }
22006
22006
  intrinsicBaseName += "." + part;
22007
22007
  intrinsicRealName = "%" + intrinsicBaseName + "%";
22008
- if (hasOwn2(INTRINSICS, intrinsicRealName)) {
22008
+ if (hasOwn3(INTRINSICS, intrinsicRealName)) {
22009
22009
  value = INTRINSICS[intrinsicRealName];
22010
22010
  } else if (value != null) {
22011
22011
  if (!(part in value)) {
@@ -22023,7 +22023,7 @@ var require_get_intrinsic = __commonJS({
22023
22023
  value = value[part];
22024
22024
  }
22025
22025
  } else {
22026
- isOwn = hasOwn2(value, part);
22026
+ isOwn = hasOwn3(value, part);
22027
22027
  value = value[part];
22028
22028
  }
22029
22029
  if (isOwn && !skipFurtherCaching) {
@@ -28620,88 +28620,227 @@ var symbolAsyncContext = Symbol.for(
28620
28620
  "runner.asyncContext"
28621
28621
  );
28622
28622
 
28623
- // src/platform/adapters/node-als.ts
28624
- async function loadAsyncLocalStorageClass() {
28625
- const mod = __require("async_hooks");
28626
- return mod.AsyncLocalStorage;
28623
+ // src/tools/getCallerFile.ts
28624
+ function isNodeInline() {
28625
+ return typeof process !== "undefined" && typeof process?.versions?.node === "string";
28627
28626
  }
28628
- __name(loadAsyncLocalStorageClass, "loadAsyncLocalStorageClass");
28629
-
28630
- // src/platform/adapters/node.ts
28631
- var NodePlatformAdapter = class {
28632
- constructor() {
28633
- this.id = "node";
28634
- this.setTimeout = globalThis.setTimeout;
28635
- this.clearTimeout = globalThis.clearTimeout;
28636
- }
28637
- static {
28638
- __name(this, "NodePlatformAdapter");
28639
- }
28640
- async init() {
28641
- this.alsClass = await loadAsyncLocalStorageClass();
28642
- }
28643
- onUncaughtException(handler) {
28644
- const h = /* @__PURE__ */ __name((error2) => handler(error2), "h");
28645
- process.on("uncaughtException", h);
28646
- return () => process.off("uncaughtException", h);
28647
- }
28648
- onUnhandledRejection(handler) {
28649
- const h = /* @__PURE__ */ __name((reason) => handler(reason), "h");
28650
- process.on("unhandledRejection", h);
28651
- return () => process.off("unhandledRejection", h);
28652
- }
28653
- onShutdownSignal(handler) {
28654
- process.on("SIGINT", handler);
28655
- process.on("SIGTERM", handler);
28656
- return () => {
28657
- process.off("SIGINT", handler);
28658
- process.off("SIGTERM", handler);
28659
- };
28660
- }
28661
- exit(code) {
28662
- process.exit(code);
28663
- }
28664
- getEnv(key) {
28665
- return process.env[key];
28666
- }
28667
- hasAsyncLocalStorage() {
28668
- return true;
28627
+ __name(isNodeInline, "isNodeInline");
28628
+ function getCallerFile() {
28629
+ const originalPrepare = Error.prepareStackTrace;
28630
+ try {
28631
+ if (isNodeInline()) {
28632
+ const err = new Error();
28633
+ Error.prepareStackTrace = (_err, stack2) => stack2;
28634
+ const stack = err.stack;
28635
+ stack.shift();
28636
+ stack.shift();
28637
+ const candidate = stack.shift();
28638
+ const file = candidate?.getFileName?.();
28639
+ return file;
28640
+ }
28641
+ return "unknown";
28642
+ } finally {
28643
+ Error.prepareStackTrace = originalPrepare;
28669
28644
  }
28670
- createAsyncLocalStorage() {
28671
- let instance;
28672
- const ensure = /* @__PURE__ */ __name(() => {
28673
- if (!this.alsClass) {
28674
- let als;
28675
- const forceNoop = typeof process !== "undefined" && !!process.env?.RUNNER_FORCE_NOOP_ALS;
28676
- if (!forceNoop) {
28677
- try {
28678
- const mod = __require("async_hooks");
28679
- als = mod?.AsyncLocalStorage;
28680
- } catch (_) {
28681
- als = void 0;
28682
- }
28683
- }
28684
- this.alsClass = als || class NoopAsyncLocalStorage {
28685
- static {
28686
- __name(this, "NoopAsyncLocalStorage");
28687
- }
28688
- getStore() {
28689
- return void 0;
28690
- }
28691
- run(_store, callback) {
28692
- return callback();
28693
- }
28694
- };
28645
+ }
28646
+ __name(getCallerFile, "getCallerFile");
28647
+
28648
+ // src/defs.ts
28649
+ var defs_exports = {};
28650
+ __export(defs_exports, {
28651
+ CONTRACT: () => CONTRACT,
28652
+ HookDependencyState: () => HookDependencyState,
28653
+ RunnerMode: () => RunnerMode,
28654
+ isOneOf: () => isOneOf,
28655
+ onAnyOf: () => onAnyOf,
28656
+ symbolAsyncContext: () => symbolAsyncContext,
28657
+ symbolError: () => symbolError,
28658
+ symbolEvent: () => symbolEvent,
28659
+ symbolFilePath: () => symbolFilePath,
28660
+ symbolHook: () => symbolHook,
28661
+ symbolMiddleware: () => symbolMiddleware,
28662
+ symbolMiddlewareConfigured: () => symbolMiddlewareConfigured,
28663
+ symbolOptionalDependency: () => symbolOptionalDependency,
28664
+ symbolPhantomTask: () => symbolPhantomTask,
28665
+ symbolResource: () => symbolResource,
28666
+ symbolResourceForkedFrom: () => symbolResourceForkedFrom,
28667
+ symbolResourceMiddleware: () => symbolResourceMiddleware,
28668
+ symbolResourceWithConfig: () => symbolResourceWithConfig,
28669
+ symbolTag: () => symbolTag,
28670
+ symbolTagConfigured: () => symbolTagConfigured,
28671
+ symbolTask: () => symbolTask,
28672
+ symbolTaskMiddleware: () => symbolTaskMiddleware,
28673
+ symbolTunneledBy: () => symbolTunneledBy
28674
+ });
28675
+
28676
+ // src/types/event.ts
28677
+ function onAnyOf(...defs) {
28678
+ return defs;
28679
+ }
28680
+ __name(onAnyOf, "onAnyOf");
28681
+ function isOneOf(emission, defs) {
28682
+ return defs.some((d) => d.id === emission.id);
28683
+ }
28684
+ __name(isOneOf, "isOneOf");
28685
+
28686
+ // src/types/runner.ts
28687
+ var RunnerMode = /* @__PURE__ */ ((RunnerMode2) => {
28688
+ RunnerMode2["TEST"] = "test";
28689
+ RunnerMode2["DEV"] = "dev";
28690
+ RunnerMode2["PROD"] = "prod";
28691
+ return RunnerMode2;
28692
+ })(RunnerMode || {});
28693
+
28694
+ // src/types/contracts.ts
28695
+ var CONTRACT = Symbol.for("runner.contract");
28696
+
28697
+ // src/types/storeTypes.ts
28698
+ var HookDependencyState = /* @__PURE__ */ ((HookDependencyState2) => {
28699
+ HookDependencyState2["Pending"] = "pending";
28700
+ HookDependencyState2["Computing"] = "computing";
28701
+ HookDependencyState2["Ready"] = "ready";
28702
+ return HookDependencyState2;
28703
+ })(HookDependencyState || {});
28704
+
28705
+ // src/definers/tools.ts
28706
+ function isTask(definition) {
28707
+ return definition && definition[symbolTask];
28708
+ }
28709
+ __name(isTask, "isTask");
28710
+ function isResource(definition) {
28711
+ return definition && definition[symbolResource];
28712
+ }
28713
+ __name(isResource, "isResource");
28714
+ function isResourceWithConfig(definition) {
28715
+ return definition && definition[symbolResourceWithConfig];
28716
+ }
28717
+ __name(isResourceWithConfig, "isResourceWithConfig");
28718
+ function isEvent(definition) {
28719
+ return definition && definition[symbolEvent];
28720
+ }
28721
+ __name(isEvent, "isEvent");
28722
+ function isHook(definition) {
28723
+ return definition && definition[symbolHook];
28724
+ }
28725
+ __name(isHook, "isHook");
28726
+ function isTaskMiddleware(definition) {
28727
+ return definition && definition[symbolTaskMiddleware];
28728
+ }
28729
+ __name(isTaskMiddleware, "isTaskMiddleware");
28730
+ function isResourceMiddleware(definition) {
28731
+ return definition && definition[symbolResourceMiddleware];
28732
+ }
28733
+ __name(isResourceMiddleware, "isResourceMiddleware");
28734
+ function isTag(definition) {
28735
+ return definition && definition[symbolTag];
28736
+ }
28737
+ __name(isTag, "isTag");
28738
+ function isOptional(definition) {
28739
+ return definition && definition[symbolOptionalDependency];
28740
+ }
28741
+ __name(isOptional, "isOptional");
28742
+ function isError(definition) {
28743
+ return Boolean(definition && definition[symbolError]);
28744
+ }
28745
+ __name(isError, "isError");
28746
+ function isAsyncContext(definition) {
28747
+ return Boolean(definition && definition[symbolAsyncContext]);
28748
+ }
28749
+ __name(isAsyncContext, "isAsyncContext");
28750
+
28751
+ // src/tools/throws.ts
28752
+ function invalidThrowsEntryError(owner, item) {
28753
+ const got = item === null ? "null" : Array.isArray(item) ? "array" : typeof item === "object" ? "object" : typeof item;
28754
+ return new Error(
28755
+ `Invalid throws entry for ${owner.kind} ${owner.id}: expected error id string or Error helper, got ${got}`
28756
+ );
28757
+ }
28758
+ __name(invalidThrowsEntryError, "invalidThrowsEntryError");
28759
+ function toErrorIdList(owner, list) {
28760
+ const ids = [];
28761
+ const seen = /* @__PURE__ */ new Set();
28762
+ for (const item of list) {
28763
+ let id2;
28764
+ if (typeof item === "string") {
28765
+ if (item.trim().length === 0) {
28766
+ throw invalidThrowsEntryError(owner, item);
28695
28767
  }
28696
- return instance ??= new this.alsClass();
28697
- }, "ensure");
28698
- return {
28699
- getStore: /* @__PURE__ */ __name(() => ensure().getStore(), "getStore"),
28700
- run: /* @__PURE__ */ __name((store2, callback) => ensure().run(store2, callback), "run")
28701
- };
28768
+ id2 = item;
28769
+ } else if (isError(item)) {
28770
+ id2 = item.id;
28771
+ if (typeof id2 !== "string" || id2.trim().length === 0) {
28772
+ throw invalidThrowsEntryError(owner, item);
28773
+ }
28774
+ } else {
28775
+ throw invalidThrowsEntryError(owner, item);
28776
+ }
28777
+ if (seen.has(id2)) continue;
28778
+ seen.add(id2);
28779
+ ids.push(id2);
28702
28780
  }
28781
+ return ids;
28782
+ }
28783
+ __name(toErrorIdList, "toErrorIdList");
28784
+ function normalizeThrows(owner, throwsList) {
28785
+ if (throwsList === void 0) return void 0;
28786
+ return toErrorIdList(owner, throwsList);
28787
+ }
28788
+ __name(normalizeThrows, "normalizeThrows");
28789
+
28790
+ // src/definers/defineTask.ts
28791
+ function defineTask(taskConfig) {
28792
+ const filePath = getCallerFile();
28793
+ const id2 = taskConfig.id;
28794
+ return {
28795
+ [symbolTask]: true,
28796
+ [symbolFilePath]: filePath,
28797
+ id: id2,
28798
+ dependencies: taskConfig.dependencies || {},
28799
+ middleware: taskConfig.middleware || [],
28800
+ run: taskConfig.run,
28801
+ inputSchema: taskConfig.inputSchema,
28802
+ resultSchema: taskConfig.resultSchema,
28803
+ meta: taskConfig.meta || {},
28804
+ tags: taskConfig.tags || [],
28805
+ throws: normalizeThrows({ kind: "task", id: id2 }, taskConfig.throws),
28806
+ // autorun,
28807
+ optional() {
28808
+ return {
28809
+ inner: this,
28810
+ [symbolOptionalDependency]: true
28811
+ };
28812
+ }
28813
+ };
28814
+ }
28815
+ __name(defineTask, "defineTask");
28816
+ defineTask.phantom = (taskConfig) => {
28817
+ const taskDef = defineTask({
28818
+ ...taskConfig,
28819
+ run: /* @__PURE__ */ __name(async (_input) => {
28820
+ return void 0;
28821
+ }, "run")
28822
+ });
28823
+ taskDef[symbolPhantomTask] = true;
28824
+ return taskDef;
28703
28825
  };
28704
28826
 
28827
+ // src/definers/defineHook.ts
28828
+ function defineHook(hookDef) {
28829
+ const filePath = getCallerFile();
28830
+ return {
28831
+ [symbolHook]: true,
28832
+ [symbolFilePath]: filePath,
28833
+ id: hookDef.id,
28834
+ dependencies: hookDef.dependencies || {},
28835
+ on: hookDef.on,
28836
+ order: hookDef.order,
28837
+ run: hookDef.run,
28838
+ meta: hookDef.meta || {},
28839
+ tags: hookDef.tags || []
28840
+ };
28841
+ }
28842
+ __name(defineHook, "defineHook");
28843
+
28705
28844
  // src/errors.ts
28706
28845
  var errors_exports = {};
28707
28846
  __export(errors_exports, {
@@ -28743,9 +28882,10 @@ var RunnerError = class extends Error {
28743
28882
  var _a;
28744
28883
  _a = symbolError;
28745
28884
  var ErrorHelper = class {
28746
- constructor(definition) {
28885
+ constructor(definition, filePath) {
28747
28886
  this.definition = definition;
28748
28887
  this[_a] = true;
28888
+ this[symbolFilePath] = filePath;
28749
28889
  }
28750
28890
  static {
28751
28891
  __name(this, "ErrorHelper");
@@ -28768,11 +28908,15 @@ var ErrorHelper = class {
28768
28908
  };
28769
28909
  }
28770
28910
  };
28771
- function defineError(definition) {
28911
+ function defineError(definition, filePath) {
28772
28912
  if (!definition.format) {
28773
28913
  definition.format = (data) => `${JSON.stringify(data)}`;
28774
28914
  }
28775
- return new ErrorHelper(definition);
28915
+ const resolvedFilePath = filePath ?? getCallerFile();
28916
+ return new ErrorHelper(
28917
+ definition,
28918
+ resolvedFilePath
28919
+ );
28776
28920
  }
28777
28921
  __name(defineError, "defineError");
28778
28922
 
@@ -28810,14 +28954,17 @@ function makeErrorBuilder(state) {
28810
28954
  return makeErrorBuilder(next);
28811
28955
  },
28812
28956
  build() {
28813
- return defineError({
28814
- id: state.id,
28815
- serialize: state.serialize,
28816
- parse: state.parse,
28817
- dataSchema: state.dataSchema,
28818
- format: state.format,
28819
- meta: state.meta
28820
- });
28957
+ return defineError(
28958
+ {
28959
+ id: state.id,
28960
+ serialize: state.serialize,
28961
+ parse: state.parse,
28962
+ dataSchema: state.dataSchema,
28963
+ format: state.format,
28964
+ meta: state.meta
28965
+ },
28966
+ state.filePath
28967
+ );
28821
28968
  }
28822
28969
  };
28823
28970
  return builder;
@@ -28826,8 +28973,10 @@ __name(makeErrorBuilder, "makeErrorBuilder");
28826
28973
 
28827
28974
  // src/definers/builders/error/index.ts
28828
28975
  function errorBuilder(id2) {
28976
+ const filePath = getCallerFile();
28829
28977
  const initial = Object.freeze({
28830
28978
  id: id2,
28979
+ filePath,
28831
28980
  serialize: void 0,
28832
28981
  parse: void 0,
28833
28982
  dataSchema: void 0,
@@ -28838,103 +28987,87 @@ function errorBuilder(id2) {
28838
28987
  __name(errorBuilder, "errorBuilder");
28839
28988
  var error = errorBuilder;
28840
28989
 
28841
- // src/errors.ts
28842
- var duplicateRegistrationError = error("runner.errors.duplicateRegistration").format(
28843
- ({ 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.`
28844
- ).build();
28845
- var dependencyNotFoundError = error("runner.errors.dependencyNotFound").format(
28846
- ({ key }) => `Dependency ${key.toString()} not found. Did you forget to register it through a resource?`
28847
- ).build();
28848
- var unknownItemTypeError = error(
28849
- "runner.errors.unknownItemType"
28850
- ).format(
28851
- ({ item }) => `Unknown item type: ${String(
28852
- item
28853
- )}. Please ensure you are not using different versions of '@bluelibs/runner'`
28854
- ).build();
28855
- var contextError = error(
28856
- "runner.errors.context"
28857
- ).format(({ details }) => details ?? "Context error").build();
28858
- var circularDependenciesError = error("runner.errors.circularDependencies").format(({ cycles }) => {
28859
- const cycleDetails = cycles.map((cycle) => ` \u2022 ${cycle}`).join("\n");
28860
- const hasMiddleware = cycles.some((cycle) => cycle.includes("middleware"));
28861
- let guidance = "\n\nTo resolve circular dependencies:";
28862
- guidance += "\n \u2022 Consider refactoring to reduce coupling between components";
28863
- guidance += "\n \u2022 Extract shared dependencies into separate resources";
28864
- if (hasMiddleware) {
28865
- guidance += "\n \u2022 For middleware: you can filter out tasks/resources using everywhere(fn)";
28866
- guidance += "\n \u2022 Consider using events for communication instead of direct dependencies";
28867
- }
28868
- return `Circular dependencies detected:
28869
- ${cycleDetails}${guidance}`;
28870
- }).build();
28871
- var eventNotFoundError = error(
28872
- "runner.errors.eventNotFound"
28873
- ).format(
28874
- ({ id: id2 }) => `Event "${id2.toString()}" not found. Did you forget to register it?`
28875
- ).build();
28876
- var resourceNotFoundError = error(
28877
- "runner.errors.resourceNotFound"
28878
- ).format(
28879
- ({ id: id2 }) => `Resource "${id2.toString()}" not found. Did you forget to register it or are you using the correct id?`
28880
- ).build();
28881
- var middlewareNotRegisteredError = error("runner.errors.middlewareNotRegistered").format(
28882
- ({ type, source, middlewareId }) => `Middleware inside ${type} "${source}" depends on "${middlewareId}" but it's not registered. Did you forget to register it?`
28883
- ).build();
28884
- var tagNotFoundError = error(
28885
- "runner.errors.tagNotFound"
28886
- ).format(
28887
- ({ id: id2 }) => `Tag "${id2}" not registered. Did you forget to register it inside a resource?`
28888
- ).build();
28889
- var lockedError = error(
28890
- "runner.errors.locked"
28891
- ).format(
28892
- ({ what }) => `Cannot modify the ${what.toString()} when it is locked.`
28893
- ).build();
28894
- var storeAlreadyInitializedError = error(
28895
- "runner.errors.storeAlreadyInitialized"
28896
- ).format(() => "Store already initialized. Cannot reinitialize.").build();
28897
- var validationError = error("runner.errors.validation").format(({ subject, id: id2, originalError }) => {
28898
- const errorMessage2 = originalError instanceof Error ? originalError.message : String(originalError);
28899
- return `${subject} validation failed for ${id2.toString()}: ${errorMessage2}`;
28900
- }).build();
28901
- var eventCycleError = error("runner.errors.eventCycle").format(({ path: path4 }) => {
28902
- const chain = path4.map((p) => `${p.id}\u2190${p.source}`).join(" -> ");
28903
- return `Event emission cycle detected:
28904
- ${chain}
28905
-
28906
- Break the cycle by changing hook logic (avoid mutual emits) or gate with conditions/tags.`;
28907
- }).build();
28908
- var eventEmissionCycleError = error("runner.errors.eventEmissionCycle").format(({ cycles }) => {
28909
- const list = cycles.map((c) => ` \u2022 ${c}`).join("\n");
28910
- return `Event emission cycles detected between hooks and events:
28911
- ${list}
28912
-
28913
- This was detected at compile time (dry-run). Break the cycle by avoiding mutual emits between hooks or scoping hooks using tags.`;
28914
- }).build();
28915
- var platformUnsupportedFunctionError = error("runner.errors.platformUnsupportedFunction").format(
28916
- ({ functionName }) => `Platform function not supported in this environment: ${functionName}. Detected platform: ${detectEnvironment()}.`
28917
- ).build();
28918
- var cancellationError = error(
28919
- "runner.errors.cancellation"
28920
- ).format(({ reason }) => reason || "Operation cancelled").build();
28921
- var tunnelOwnershipConflictError = error("runner.errors.tunnelOwnershipConflict").format(
28922
- ({ 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.`
28923
- ).build();
28924
- var phantomTaskNotRoutedError = error("runner.errors.phantomTaskNotRouted").format(
28925
- ({ 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).`
28926
- ).build();
28927
- var taskNotRegisteredError = error("runner.errors.taskNotRegistered").format(
28928
- ({ taskId }) => `Task "${taskId}" is not registered in the Store. This is an internal error\u2014ensure the task is registered before execution.`
28929
- ).build();
28930
- var builderIncompleteError = error("runner.errors.builderIncomplete").format(({ type, builderId, missingFields }) => {
28931
- const typeLabel = type === "hook" ? "Hook" : type === "task-middleware" ? "Task middleware" : "Resource middleware";
28932
- return `${typeLabel} "${builderId}" is incomplete. Missing required: ${missingFields.join(", ")}. Call ${missingFields.map((f) => `.${f}()`).join(" and ")} before .build().`;
28933
- }).build();
28934
- function isCancellationError(err) {
28935
- return cancellationError.is(err);
28990
+ // src/platform/adapters/node-als.ts
28991
+ async function loadAsyncLocalStorageClass() {
28992
+ const mod = __require("async_hooks");
28993
+ return mod.AsyncLocalStorage;
28936
28994
  }
28937
- __name(isCancellationError, "isCancellationError");
28995
+ __name(loadAsyncLocalStorageClass, "loadAsyncLocalStorageClass");
28996
+
28997
+ // src/platform/adapters/node.ts
28998
+ var NodePlatformAdapter = class {
28999
+ constructor() {
29000
+ this.id = "node";
29001
+ this.setTimeout = globalThis.setTimeout;
29002
+ this.clearTimeout = globalThis.clearTimeout;
29003
+ }
29004
+ static {
29005
+ __name(this, "NodePlatformAdapter");
29006
+ }
29007
+ async init() {
29008
+ this.alsClass = await loadAsyncLocalStorageClass();
29009
+ }
29010
+ onUncaughtException(handler) {
29011
+ const h = /* @__PURE__ */ __name((error2) => handler(error2), "h");
29012
+ process.on("uncaughtException", h);
29013
+ return () => process.off("uncaughtException", h);
29014
+ }
29015
+ onUnhandledRejection(handler) {
29016
+ const h = /* @__PURE__ */ __name((reason) => handler(reason), "h");
29017
+ process.on("unhandledRejection", h);
29018
+ return () => process.off("unhandledRejection", h);
29019
+ }
29020
+ onShutdownSignal(handler) {
29021
+ process.on("SIGINT", handler);
29022
+ process.on("SIGTERM", handler);
29023
+ return () => {
29024
+ process.off("SIGINT", handler);
29025
+ process.off("SIGTERM", handler);
29026
+ };
29027
+ }
29028
+ exit(code) {
29029
+ process.exit(code);
29030
+ }
29031
+ getEnv(key) {
29032
+ return process.env[key];
29033
+ }
29034
+ hasAsyncLocalStorage() {
29035
+ return true;
29036
+ }
29037
+ createAsyncLocalStorage() {
29038
+ let instance;
29039
+ const ensure = /* @__PURE__ */ __name(() => {
29040
+ if (!this.alsClass) {
29041
+ let als;
29042
+ const forceNoop = typeof process !== "undefined" && !!process.env?.RUNNER_FORCE_NOOP_ALS;
29043
+ if (!forceNoop) {
29044
+ try {
29045
+ const mod = __require("async_hooks");
29046
+ als = mod?.AsyncLocalStorage;
29047
+ } catch (_) {
29048
+ als = void 0;
29049
+ }
29050
+ }
29051
+ this.alsClass = als || class NoopAsyncLocalStorage {
29052
+ static {
29053
+ __name(this, "NoopAsyncLocalStorage");
29054
+ }
29055
+ getStore() {
29056
+ return void 0;
29057
+ }
29058
+ run(_store, callback) {
29059
+ return callback();
29060
+ }
29061
+ };
29062
+ }
29063
+ return instance ??= new this.alsClass();
29064
+ }, "ensure");
29065
+ return {
29066
+ getStore: /* @__PURE__ */ __name(() => ensure().getStore(), "getStore"),
29067
+ run: /* @__PURE__ */ __name((store2, callback) => ensure().run(store2, callback), "run")
29068
+ };
29069
+ }
29070
+ };
28938
29071
 
28939
29072
  // src/platform/adapters/browser.ts
28940
29073
  var BrowserPlatformAdapter = class {
@@ -29227,16 +29360,11 @@ function setPlatform(adapter) {
29227
29360
  adapter.id;
29228
29361
  }
29229
29362
  __name(setPlatform, "setPlatform");
29230
- function isNode() {
29231
- {
29232
- return true;
29233
- }
29234
- }
29235
- __name(isNode, "isNode");
29236
29363
  var PlatformAdapter = class {
29364
+ static {
29365
+ __name(this, "PlatformAdapter");
29366
+ }
29237
29367
  constructor(env) {
29238
- this.setTimeout = globalThis.setTimeout;
29239
- this.clearTimeout = globalThis.clearTimeout;
29240
29368
  const kind = env ?? detectEnvironment();
29241
29369
  this.env = kind;
29242
29370
  switch (kind) {
@@ -29256,9 +29384,8 @@ var PlatformAdapter = class {
29256
29384
  this.inner = new UniversalPlatformAdapter();
29257
29385
  }
29258
29386
  this.id = this.inner.id;
29259
- }
29260
- static {
29261
- __name(this, "PlatformAdapter");
29387
+ this.setTimeout = this.inner.setTimeout;
29388
+ this.clearTimeout = this.inner.clearTimeout;
29262
29389
  }
29263
29390
  async init() {
29264
29391
  return this.inner.init();
@@ -29286,209 +29413,103 @@ var PlatformAdapter = class {
29286
29413
  }
29287
29414
  };
29288
29415
 
29289
- // src/tools/getCallerFile.ts
29290
- function getCallerFile() {
29291
- const originalPrepare = Error.prepareStackTrace;
29292
- try {
29293
- if (isNode()) {
29294
- const err = new Error();
29295
- Error.prepareStackTrace = (_err, stack2) => stack2;
29296
- const stack = err.stack;
29297
- stack.shift();
29298
- stack.shift();
29299
- const candidate = stack.shift();
29300
- const file = candidate?.getFileName?.();
29301
- return file;
29302
- }
29303
- return "unknown";
29304
- } finally {
29305
- Error.prepareStackTrace = originalPrepare;
29306
- }
29307
- }
29308
- __name(getCallerFile, "getCallerFile");
29309
-
29310
- // src/defs.ts
29311
- var defs_exports = {};
29312
- __export(defs_exports, {
29313
- RunnerMode: () => RunnerMode,
29314
- isOneOf: () => isOneOf,
29315
- onAnyOf: () => onAnyOf,
29316
- symbolAsyncContext: () => symbolAsyncContext,
29317
- symbolError: () => symbolError,
29318
- symbolEvent: () => symbolEvent,
29319
- symbolFilePath: () => symbolFilePath,
29320
- symbolHook: () => symbolHook,
29321
- symbolMiddleware: () => symbolMiddleware,
29322
- symbolMiddlewareConfigured: () => symbolMiddlewareConfigured,
29323
- symbolOptionalDependency: () => symbolOptionalDependency,
29324
- symbolPhantomTask: () => symbolPhantomTask,
29325
- symbolResource: () => symbolResource,
29326
- symbolResourceForkedFrom: () => symbolResourceForkedFrom,
29327
- symbolResourceMiddleware: () => symbolResourceMiddleware,
29328
- symbolResourceWithConfig: () => symbolResourceWithConfig,
29329
- symbolTag: () => symbolTag,
29330
- symbolTagConfigured: () => symbolTagConfigured,
29331
- symbolTask: () => symbolTask,
29332
- symbolTaskMiddleware: () => symbolTaskMiddleware,
29333
- symbolTunneledBy: () => symbolTunneledBy
29334
- });
29335
-
29336
- // src/types/event.ts
29337
- function onAnyOf(...defs) {
29338
- return defs;
29339
- }
29340
- __name(onAnyOf, "onAnyOf");
29341
- function isOneOf(emission, defs) {
29342
- return defs.some((d) => d.id === emission.id);
29343
- }
29344
- __name(isOneOf, "isOneOf");
29345
-
29346
- // src/types/runner.ts
29347
- var RunnerMode = /* @__PURE__ */ ((RunnerMode2) => {
29348
- RunnerMode2["TEST"] = "test";
29349
- RunnerMode2["DEV"] = "dev";
29350
- RunnerMode2["PROD"] = "prod";
29351
- return RunnerMode2;
29352
- })(RunnerMode || {});
29353
-
29354
- // src/definers/tools.ts
29355
- function isTask(definition) {
29356
- return definition && definition[symbolTask];
29357
- }
29358
- __name(isTask, "isTask");
29359
- function isResource(definition) {
29360
- return definition && definition[symbolResource];
29361
- }
29362
- __name(isResource, "isResource");
29363
- function isResourceWithConfig(definition) {
29364
- return definition && definition[symbolResourceWithConfig];
29365
- }
29366
- __name(isResourceWithConfig, "isResourceWithConfig");
29367
- function isEvent(definition) {
29368
- return definition && definition[symbolEvent];
29369
- }
29370
- __name(isEvent, "isEvent");
29371
- function isHook(definition) {
29372
- return definition && definition[symbolHook];
29373
- }
29374
- __name(isHook, "isHook");
29375
- function isTaskMiddleware(definition) {
29376
- return definition && definition[symbolTaskMiddleware];
29377
- }
29378
- __name(isTaskMiddleware, "isTaskMiddleware");
29379
- function isResourceMiddleware(definition) {
29380
- return definition && definition[symbolResourceMiddleware];
29381
- }
29382
- __name(isResourceMiddleware, "isResourceMiddleware");
29383
- function isTag(definition) {
29384
- return definition && definition[symbolTag];
29385
- }
29386
- __name(isTag, "isTag");
29387
- function isOptional(definition) {
29388
- return definition && definition[symbolOptionalDependency];
29389
- }
29390
- __name(isOptional, "isOptional");
29391
- function isError(definition) {
29392
- return Boolean(definition && definition[symbolError]);
29393
- }
29394
- __name(isError, "isError");
29395
- function isAsyncContext(definition) {
29396
- return Boolean(definition && definition[symbolAsyncContext]);
29397
- }
29398
- __name(isAsyncContext, "isAsyncContext");
29399
-
29400
- // src/tools/throws.ts
29401
- function invalidThrowsEntryError(owner, item) {
29402
- const got = item === null ? "null" : Array.isArray(item) ? "array" : typeof item === "object" ? "object" : typeof item;
29403
- return new Error(
29404
- `Invalid throws entry for ${owner.kind} ${owner.id}: expected error id string or Error helper, got ${got}`
29405
- );
29406
- }
29407
- __name(invalidThrowsEntryError, "invalidThrowsEntryError");
29408
- function toErrorIdList(owner, list) {
29409
- const ids = [];
29410
- const seen = /* @__PURE__ */ new Set();
29411
- for (const item of list) {
29412
- let id2;
29413
- if (typeof item === "string") {
29414
- if (item.trim().length === 0) {
29415
- throw invalidThrowsEntryError(owner, item);
29416
- }
29417
- id2 = item;
29418
- } else if (isError(item)) {
29419
- id2 = item.id;
29420
- if (typeof id2 !== "string" || id2.trim().length === 0) {
29421
- throw invalidThrowsEntryError(owner, item);
29422
- }
29423
- } else {
29424
- throw invalidThrowsEntryError(owner, item);
29425
- }
29426
- if (seen.has(id2)) continue;
29427
- seen.add(id2);
29428
- ids.push(id2);
29416
+ // src/errors.ts
29417
+ var duplicateRegistrationError = error("runner.errors.duplicateRegistration").format(
29418
+ ({ 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.`
29419
+ ).build();
29420
+ var dependencyNotFoundError = error("runner.errors.dependencyNotFound").format(
29421
+ ({ key }) => `Dependency ${key.toString()} not found. Did you forget to register it through a resource?`
29422
+ ).build();
29423
+ var unknownItemTypeError = error(
29424
+ "runner.errors.unknownItemType"
29425
+ ).format(
29426
+ ({ item }) => `Unknown item type: ${String(
29427
+ item
29428
+ )}. Please ensure you are not using different versions of '@bluelibs/runner'`
29429
+ ).build();
29430
+ var contextError = error(
29431
+ "runner.errors.context"
29432
+ ).format(({ details }) => details ?? "Context error").build();
29433
+ var circularDependenciesError = error("runner.errors.circularDependencies").format(({ cycles }) => {
29434
+ const cycleDetails = cycles.map((cycle) => ` \u2022 ${cycle}`).join("\n");
29435
+ const hasMiddleware = cycles.some((cycle) => cycle.includes("middleware"));
29436
+ let guidance = "\n\nTo resolve circular dependencies:";
29437
+ guidance += "\n \u2022 Consider refactoring to reduce coupling between components";
29438
+ guidance += "\n \u2022 Extract shared dependencies into separate resources";
29439
+ if (hasMiddleware) {
29440
+ guidance += "\n \u2022 For middleware: you can filter out tasks/resources using everywhere(fn)";
29441
+ guidance += "\n \u2022 Consider using events for communication instead of direct dependencies";
29429
29442
  }
29430
- return ids;
29431
- }
29432
- __name(toErrorIdList, "toErrorIdList");
29433
- function normalizeThrows(owner, throwsList) {
29434
- if (throwsList === void 0) return void 0;
29435
- return toErrorIdList(owner, throwsList);
29436
- }
29437
- __name(normalizeThrows, "normalizeThrows");
29443
+ return `Circular dependencies detected:
29444
+ ${cycleDetails}${guidance}`;
29445
+ }).build();
29446
+ var eventNotFoundError = error(
29447
+ "runner.errors.eventNotFound"
29448
+ ).format(
29449
+ ({ id: id2 }) => `Event "${id2.toString()}" not found. Did you forget to register it?`
29450
+ ).build();
29451
+ var resourceNotFoundError = error(
29452
+ "runner.errors.resourceNotFound"
29453
+ ).format(
29454
+ ({ id: id2 }) => `Resource "${id2.toString()}" not found. Did you forget to register it or are you using the correct id?`
29455
+ ).build();
29456
+ var middlewareNotRegisteredError = error("runner.errors.middlewareNotRegistered").format(
29457
+ ({ type, source, middlewareId }) => `Middleware inside ${type} "${source}" depends on "${middlewareId}" but it's not registered. Did you forget to register it?`
29458
+ ).build();
29459
+ var tagNotFoundError = error(
29460
+ "runner.errors.tagNotFound"
29461
+ ).format(
29462
+ ({ id: id2 }) => `Tag "${id2}" not registered. Did you forget to register it inside a resource?`
29463
+ ).build();
29464
+ var lockedError = error(
29465
+ "runner.errors.locked"
29466
+ ).format(
29467
+ ({ what }) => `Cannot modify the ${what.toString()} when it is locked.`
29468
+ ).build();
29469
+ var storeAlreadyInitializedError = error(
29470
+ "runner.errors.storeAlreadyInitialized"
29471
+ ).format(() => "Store already initialized. Cannot reinitialize.").build();
29472
+ var validationError = error("runner.errors.validation").format(({ subject, id: id2, originalError }) => {
29473
+ const errorMessage2 = originalError instanceof Error ? originalError.message : String(originalError);
29474
+ return `${subject} validation failed for ${id2.toString()}: ${errorMessage2}`;
29475
+ }).build();
29476
+ var eventCycleError = error("runner.errors.eventCycle").format(({ path: path4 }) => {
29477
+ const chain = path4.map((p) => `${p.id}\u2190${p.source}`).join(" -> ");
29478
+ return `Event emission cycle detected:
29479
+ ${chain}
29438
29480
 
29439
- // src/definers/defineTask.ts
29440
- function defineTask(taskConfig) {
29441
- const filePath = getCallerFile();
29442
- const id2 = taskConfig.id;
29443
- return {
29444
- [symbolTask]: true,
29445
- [symbolFilePath]: filePath,
29446
- id: id2,
29447
- dependencies: taskConfig.dependencies || {},
29448
- middleware: taskConfig.middleware || [],
29449
- run: taskConfig.run,
29450
- inputSchema: taskConfig.inputSchema,
29451
- resultSchema: taskConfig.resultSchema,
29452
- meta: taskConfig.meta || {},
29453
- tags: taskConfig.tags || [],
29454
- throws: normalizeThrows({ kind: "task", id: id2 }, taskConfig.throws),
29455
- // autorun,
29456
- optional() {
29457
- return {
29458
- inner: this,
29459
- [symbolOptionalDependency]: true
29460
- };
29461
- }
29462
- };
29463
- }
29464
- __name(defineTask, "defineTask");
29465
- defineTask.phantom = (taskConfig) => {
29466
- const taskDef = defineTask({
29467
- ...taskConfig,
29468
- run: /* @__PURE__ */ __name(async (_input) => {
29469
- return void 0;
29470
- }, "run")
29471
- });
29472
- taskDef[symbolPhantomTask] = true;
29473
- return taskDef;
29474
- };
29481
+ Break the cycle by changing hook logic (avoid mutual emits) or gate with conditions/tags.`;
29482
+ }).build();
29483
+ var eventEmissionCycleError = error("runner.errors.eventEmissionCycle").format(({ cycles }) => {
29484
+ const list = cycles.map((c) => ` \u2022 ${c}`).join("\n");
29485
+ return `Event emission cycles detected between hooks and events:
29486
+ ${list}
29475
29487
 
29476
- // src/definers/defineHook.ts
29477
- function defineHook(hookDef) {
29478
- const filePath = getCallerFile();
29479
- return {
29480
- [symbolHook]: true,
29481
- [symbolFilePath]: filePath,
29482
- id: hookDef.id,
29483
- dependencies: hookDef.dependencies || {},
29484
- on: hookDef.on,
29485
- order: hookDef.order,
29486
- run: hookDef.run,
29487
- meta: hookDef.meta || {},
29488
- tags: hookDef.tags || []
29489
- };
29488
+ This was detected at compile time (dry-run). Break the cycle by avoiding mutual emits between hooks or scoping hooks using tags.`;
29489
+ }).build();
29490
+ var platformUnsupportedFunctionError = error("runner.errors.platformUnsupportedFunction").format(
29491
+ ({ functionName }) => `Platform function not supported in this environment: ${functionName}. Detected platform: ${detectEnvironment()}.`
29492
+ ).build();
29493
+ var cancellationError = error(
29494
+ "runner.errors.cancellation"
29495
+ ).format(({ reason }) => reason || "Operation cancelled").build();
29496
+ var tunnelOwnershipConflictError = error("runner.errors.tunnelOwnershipConflict").format(
29497
+ ({ 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.`
29498
+ ).build();
29499
+ var phantomTaskNotRoutedError = error("runner.errors.phantomTaskNotRouted").format(
29500
+ ({ 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).`
29501
+ ).build();
29502
+ var taskNotRegisteredError = error("runner.errors.taskNotRegistered").format(
29503
+ ({ taskId }) => `Task "${taskId}" is not registered in the Store. This is an internal error\u2014ensure the task is registered before execution.`
29504
+ ).build();
29505
+ var builderIncompleteError = error("runner.errors.builderIncomplete").format(({ type, builderId, missingFields }) => {
29506
+ const typeLabel = type === "hook" ? "Hook" : type === "task-middleware" ? "Task middleware" : "Resource middleware";
29507
+ return `${typeLabel} "${builderId}" is incomplete. Missing required: ${missingFields.join(", ")}. Call ${missingFields.map((f) => `.${f}()`).join(" and ")} before .build().`;
29508
+ }).build();
29509
+ function isCancellationError(err) {
29510
+ return cancellationError.is(err);
29490
29511
  }
29491
- __name(defineHook, "defineHook");
29512
+ __name(isCancellationError, "isCancellationError");
29492
29513
 
29493
29514
  // src/definers/resourceFork.ts
29494
29515
  function resolveReId(forkId, options) {
@@ -29863,7 +29884,7 @@ function defineOverride(base, patch) {
29863
29884
  ...patch,
29864
29885
  id: base.id
29865
29886
  };
29866
- if (base.on !== void 0) {
29887
+ if ("on" in base && base.on !== void 0) {
29867
29888
  overridden.on = base.on;
29868
29889
  }
29869
29890
  return overridden;
@@ -29983,6 +30004,309 @@ var SymbolPolicy = /* @__PURE__ */ ((SymbolPolicy2) => {
29983
30004
  SymbolPolicy2["Disabled"] = "Disabled";
29984
30005
  return SymbolPolicy2;
29985
30006
  })(SymbolPolicy || {});
30007
+ var SymbolPolicyErrorMessage = /* @__PURE__ */ ((SymbolPolicyErrorMessage2) => {
30008
+ SymbolPolicyErrorMessage2["GlobalSymbolsNotAllowed"] = "Global symbols are not allowed";
30009
+ SymbolPolicyErrorMessage2["SymbolsNotAllowed"] = "Symbols are not allowed";
30010
+ SymbolPolicyErrorMessage2["UnsupportedSymbolPolicy"] = "Unsupported symbol policy";
30011
+ return SymbolPolicyErrorMessage2;
30012
+ })(SymbolPolicyErrorMessage || {});
30013
+
30014
+ // src/serializer/binary-builtins.ts
30015
+ var INVALID_PAYLOAD_MESSAGE_PREFIX = "Invalid";
30016
+ var typedArrayTypeIds = [
30017
+ "Int8Array",
30018
+ "Uint8Array",
30019
+ "Uint8ClampedArray",
30020
+ "Int16Array",
30021
+ "Uint16Array",
30022
+ "Int32Array",
30023
+ "Uint32Array",
30024
+ "Float32Array",
30025
+ "Float64Array",
30026
+ "BigInt64Array",
30027
+ "BigUint64Array"
30028
+ ];
30029
+ var getTypedArrayConstructor = /* @__PURE__ */ __name((typeId) => {
30030
+ const value = globalThis[typeId];
30031
+ if (typeof value !== "function") {
30032
+ return null;
30033
+ }
30034
+ return value;
30035
+ }, "getTypedArrayConstructor");
30036
+ var getRuntimeBufferConstructor = /* @__PURE__ */ __name(() => {
30037
+ const value = globalThis.Buffer;
30038
+ if (typeof value !== "function") {
30039
+ return null;
30040
+ }
30041
+ const valueRecord = value;
30042
+ if (typeof valueRecord.from !== "function" || typeof valueRecord.isBuffer !== "function") {
30043
+ return null;
30044
+ }
30045
+ return value;
30046
+ }, "getRuntimeBufferConstructor");
30047
+ var isNodeBuffer = /* @__PURE__ */ __name((value) => {
30048
+ const runtimeBufferConstructor = getRuntimeBufferConstructor();
30049
+ if (!runtimeBufferConstructor) {
30050
+ return false;
30051
+ }
30052
+ return runtimeBufferConstructor.isBuffer(value);
30053
+ }, "isNodeBuffer");
30054
+ var assertBytePayload = /* @__PURE__ */ __name((payload, typeId) => {
30055
+ if (!Array.isArray(payload)) {
30056
+ throw new Error(`${INVALID_PAYLOAD_MESSAGE_PREFIX} ${typeId} payload`);
30057
+ }
30058
+ const bytes = new Array(payload.length);
30059
+ for (let index = 0; index < payload.length; index += 1) {
30060
+ const byteValue = payload[index];
30061
+ if (typeof byteValue !== "number" || !Number.isInteger(byteValue) || byteValue < 0 || byteValue > 255) {
30062
+ throw new Error(`${INVALID_PAYLOAD_MESSAGE_PREFIX} ${typeId} payload`);
30063
+ }
30064
+ bytes[index] = byteValue;
30065
+ }
30066
+ return bytes;
30067
+ }, "assertBytePayload");
30068
+ var toBytePayload = /* @__PURE__ */ __name((value) => Array.from(new Uint8Array(value.buffer, value.byteOffset, value.byteLength)), "toBytePayload");
30069
+ var bytesToArrayBuffer = /* @__PURE__ */ __name((payload, typeId) => {
30070
+ const bytes = assertBytePayload(payload, typeId);
30071
+ return Uint8Array.from(bytes).buffer;
30072
+ }, "bytesToArrayBuffer");
30073
+ var deserializeTypedArray = /* @__PURE__ */ __name((typeId, payload) => {
30074
+ const typedArrayConstructor = getTypedArrayConstructor(typeId);
30075
+ if (!typedArrayConstructor) {
30076
+ throw new Error(`${typeId} is not available in this runtime`);
30077
+ }
30078
+ const bytes = assertBytePayload(payload, typeId);
30079
+ const bytesPerElement = typedArrayConstructor.BYTES_PER_ELEMENT;
30080
+ if (bytes.length % bytesPerElement !== 0) {
30081
+ throw new Error(`${INVALID_PAYLOAD_MESSAGE_PREFIX} ${typeId} payload`);
30082
+ }
30083
+ const arrayBuffer = Uint8Array.from(bytes).buffer;
30084
+ return new typedArrayConstructor(arrayBuffer);
30085
+ }, "deserializeTypedArray");
30086
+ var createTypedArrayType = /* @__PURE__ */ __name((typeId) => ({
30087
+ id: typeId,
30088
+ is: /* @__PURE__ */ __name((value) => {
30089
+ const typedArrayConstructor = getTypedArrayConstructor(typeId);
30090
+ if (!typedArrayConstructor) {
30091
+ return false;
30092
+ }
30093
+ if (!(value instanceof typedArrayConstructor)) {
30094
+ return false;
30095
+ }
30096
+ if (typeId === "Uint8Array" && isNodeBuffer(value)) {
30097
+ return false;
30098
+ }
30099
+ return true;
30100
+ }, "is"),
30101
+ serialize: /* @__PURE__ */ __name((value) => toBytePayload(value), "serialize"),
30102
+ deserialize: /* @__PURE__ */ __name((payload) => deserializeTypedArray(typeId, payload), "deserialize"),
30103
+ strategy: "value"
30104
+ }), "createTypedArrayType");
30105
+ var ArrayBufferType = {
30106
+ id: "ArrayBuffer",
30107
+ is: /* @__PURE__ */ __name((value) => value instanceof ArrayBuffer, "is"),
30108
+ serialize: /* @__PURE__ */ __name((value) => Array.from(new Uint8Array(value)), "serialize"),
30109
+ deserialize: /* @__PURE__ */ __name((payload) => bytesToArrayBuffer(payload, "ArrayBuffer"), "deserialize"),
30110
+ strategy: "value"
30111
+ };
30112
+ var DataViewType = {
30113
+ id: "DataView",
30114
+ is: /* @__PURE__ */ __name((value) => value instanceof DataView, "is"),
30115
+ serialize: /* @__PURE__ */ __name((value) => toBytePayload(value), "serialize"),
30116
+ deserialize: /* @__PURE__ */ __name((payload) => new DataView(bytesToArrayBuffer(payload, "DataView")), "deserialize"),
30117
+ strategy: "value"
30118
+ };
30119
+ var BufferType = {
30120
+ id: "Buffer",
30121
+ is: /* @__PURE__ */ __name((value) => isNodeBuffer(value), "is"),
30122
+ serialize: /* @__PURE__ */ __name((value) => toBytePayload(value), "serialize"),
30123
+ deserialize: /* @__PURE__ */ __name((payload) => {
30124
+ const bytes = assertBytePayload(payload, "Buffer");
30125
+ const runtimeBufferConstructor = getRuntimeBufferConstructor();
30126
+ if (runtimeBufferConstructor) {
30127
+ return runtimeBufferConstructor.from(bytes);
30128
+ }
30129
+ return Uint8Array.from(bytes);
30130
+ }, "deserialize"),
30131
+ strategy: "value"
30132
+ };
30133
+ var typedArrayTypes = typedArrayTypeIds.map(
30134
+ (typeId) => createTypedArrayType(typeId)
30135
+ );
30136
+ var binaryBuiltInTypes = [
30137
+ ArrayBufferType,
30138
+ DataViewType,
30139
+ BufferType,
30140
+ ...typedArrayTypes
30141
+ ];
30142
+
30143
+ // src/serializer/error-url-builtins.ts
30144
+ var hasOwn = Object.prototype.hasOwnProperty;
30145
+ var errorReservedPropertyNames = /* @__PURE__ */ new Set([
30146
+ "name",
30147
+ "message",
30148
+ "stack",
30149
+ "cause"
30150
+ ]);
30151
+ var isRecord = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRecord");
30152
+ var isUnsafePropertyName = /* @__PURE__ */ __name((propertyName) => propertyName === "__proto__" || propertyName === "constructor" || propertyName === "prototype", "isUnsafePropertyName");
30153
+ var collectErrorCustomFields = /* @__PURE__ */ __name((error2) => {
30154
+ const customFields = {};
30155
+ for (const propertyName of Object.getOwnPropertyNames(error2)) {
30156
+ if (errorReservedPropertyNames.has(propertyName)) {
30157
+ continue;
30158
+ }
30159
+ if (isUnsafePropertyName(propertyName)) {
30160
+ continue;
30161
+ }
30162
+ const descriptor = Object.getOwnPropertyDescriptor(error2, propertyName);
30163
+ if (!descriptor || !("value" in descriptor)) {
30164
+ continue;
30165
+ }
30166
+ customFields[propertyName] = descriptor.value;
30167
+ }
30168
+ return customFields;
30169
+ }, "collectErrorCustomFields");
30170
+ var assertSerializedErrorPayload = /* @__PURE__ */ __name((value) => {
30171
+ if (!isRecord(value)) {
30172
+ throw new Error("Invalid Error payload");
30173
+ }
30174
+ const { name, message, stack, customFields } = value;
30175
+ if (typeof name !== "string" || typeof message !== "string") {
30176
+ throw new Error("Invalid Error payload");
30177
+ }
30178
+ if (stack !== void 0 && typeof stack !== "string") {
30179
+ throw new Error("Invalid Error payload");
30180
+ }
30181
+ if (customFields !== void 0 && !isRecord(customFields)) {
30182
+ throw new Error("Invalid Error payload");
30183
+ }
30184
+ const normalizedCustomFields = {};
30185
+ const customFieldEntries = Object.entries(customFields ?? {});
30186
+ for (const [propertyName, propertyValue] of customFieldEntries) {
30187
+ if (isUnsafePropertyName(propertyName)) {
30188
+ continue;
30189
+ }
30190
+ normalizedCustomFields[propertyName] = propertyValue;
30191
+ }
30192
+ return {
30193
+ name,
30194
+ message,
30195
+ stack,
30196
+ hasCause: hasOwn.call(value, "cause"),
30197
+ cause: value.cause,
30198
+ customFields: normalizedCustomFields
30199
+ };
30200
+ }, "assertSerializedErrorPayload");
30201
+ var getUrlConstructor = /* @__PURE__ */ __name(() => {
30202
+ const value = globalThis.URL;
30203
+ if (typeof value !== "function") {
30204
+ return null;
30205
+ }
30206
+ return value;
30207
+ }, "getUrlConstructor");
30208
+ var getUrlSearchParamsConstructor = /* @__PURE__ */ __name(() => {
30209
+ const value = globalThis.URLSearchParams;
30210
+ if (typeof value !== "function") {
30211
+ return null;
30212
+ }
30213
+ return value;
30214
+ }, "getUrlSearchParamsConstructor");
30215
+ var ErrorType = {
30216
+ id: "Error",
30217
+ is: /* @__PURE__ */ __name((value) => value instanceof Error, "is"),
30218
+ serialize: /* @__PURE__ */ __name((error2) => {
30219
+ const serializedErrorPayload = {
30220
+ name: error2.name,
30221
+ message: error2.message,
30222
+ customFields: collectErrorCustomFields(error2)
30223
+ };
30224
+ if (typeof error2.stack === "string") {
30225
+ serializedErrorPayload.stack = error2.stack;
30226
+ }
30227
+ if (hasOwn.call(error2, "cause")) {
30228
+ serializedErrorPayload.cause = error2.cause;
30229
+ }
30230
+ return serializedErrorPayload;
30231
+ }, "serialize"),
30232
+ deserialize: /* @__PURE__ */ __name((payload) => {
30233
+ const { name, message, stack, hasCause, cause, customFields } = assertSerializedErrorPayload(payload);
30234
+ const restoredError = new Error(message);
30235
+ restoredError.name = name;
30236
+ if (stack !== void 0) {
30237
+ Object.defineProperty(restoredError, "stack", {
30238
+ value: stack,
30239
+ writable: true,
30240
+ configurable: true,
30241
+ enumerable: false
30242
+ });
30243
+ }
30244
+ if (hasCause) {
30245
+ Object.defineProperty(restoredError, "cause", {
30246
+ value: cause,
30247
+ writable: true,
30248
+ configurable: true,
30249
+ enumerable: false
30250
+ });
30251
+ }
30252
+ for (const [propertyName, propertyValue] of Object.entries(customFields)) {
30253
+ if (errorReservedPropertyNames.has(propertyName)) {
30254
+ continue;
30255
+ }
30256
+ restoredError[propertyName] = propertyValue;
30257
+ }
30258
+ return restoredError;
30259
+ }, "deserialize")
30260
+ };
30261
+ var URLType = {
30262
+ id: "URL",
30263
+ is: /* @__PURE__ */ __name((value) => {
30264
+ const runtimeUrlConstructor = getUrlConstructor();
30265
+ if (!runtimeUrlConstructor) {
30266
+ return false;
30267
+ }
30268
+ return value instanceof runtimeUrlConstructor;
30269
+ }, "is"),
30270
+ serialize: /* @__PURE__ */ __name((value) => value.href, "serialize"),
30271
+ deserialize: /* @__PURE__ */ __name((payload) => {
30272
+ if (typeof payload !== "string") {
30273
+ throw new Error("Invalid URL payload");
30274
+ }
30275
+ const runtimeUrlConstructor = getUrlConstructor();
30276
+ if (!runtimeUrlConstructor) {
30277
+ throw new Error("URL is not available in this runtime");
30278
+ }
30279
+ return new runtimeUrlConstructor(payload);
30280
+ }, "deserialize"),
30281
+ strategy: "value"
30282
+ };
30283
+ var URLSearchParamsType = {
30284
+ id: "URLSearchParams",
30285
+ is: /* @__PURE__ */ __name((value) => {
30286
+ const runtimeUrlSearchParamsConstructor = getUrlSearchParamsConstructor();
30287
+ if (!runtimeUrlSearchParamsConstructor) {
30288
+ return false;
30289
+ }
30290
+ return value instanceof runtimeUrlSearchParamsConstructor;
30291
+ }, "is"),
30292
+ serialize: /* @__PURE__ */ __name((value) => value.toString(), "serialize"),
30293
+ deserialize: /* @__PURE__ */ __name((payload) => {
30294
+ if (typeof payload !== "string") {
30295
+ throw new Error("Invalid URLSearchParams payload");
30296
+ }
30297
+ const runtimeUrlSearchParamsConstructor = getUrlSearchParamsConstructor();
30298
+ if (!runtimeUrlSearchParamsConstructor) {
30299
+ throw new Error("URLSearchParams is not available in this runtime");
30300
+ }
30301
+ return new runtimeUrlSearchParamsConstructor(payload);
30302
+ }, "deserialize"),
30303
+ strategy: "value"
30304
+ };
30305
+ var errorAndUrlBuiltInTypes = [
30306
+ ErrorType,
30307
+ URLType,
30308
+ URLSearchParamsType
30309
+ ];
29986
30310
 
29987
30311
  // src/serializer/special-values.ts
29988
30312
  var serializeUndefined = /* @__PURE__ */ __name(() => ({
@@ -30188,7 +30512,9 @@ var builtInTypes = [
30188
30512
  UndefinedType,
30189
30513
  NonFiniteNumberType,
30190
30514
  BigIntType,
30191
- SymbolType
30515
+ SymbolType,
30516
+ ...errorAndUrlBuiltInTypes,
30517
+ ...binaryBuiltInTypes
30192
30518
  ];
30193
30519
 
30194
30520
  // src/serializer/type-registry.ts
@@ -30679,7 +31005,7 @@ var serializeTreeValue = /* @__PURE__ */ __name((value, context, depth, options)
30679
31005
  }, "serializeTreeValue");
30680
31006
 
30681
31007
  // src/serializer/deserializer.ts
30682
- var hasOwn = Object.prototype.hasOwnProperty;
31008
+ var hasOwn2 = Object.prototype.hasOwnProperty;
30683
31009
  var copyOwnProperties = /* @__PURE__ */ __name((target, source, unsafeKeys) => {
30684
31010
  const descriptors = Object.getOwnPropertyDescriptors(source);
30685
31011
  for (const key of Object.keys(descriptors)) {
@@ -30760,7 +31086,7 @@ var deserializeValue = /* @__PURE__ */ __name((value, context, depth, options) =
30760
31086
  const obj = {};
30761
31087
  const source = value;
30762
31088
  for (const key in source) {
30763
- if (!hasOwn.call(source, key)) {
31089
+ if (!hasOwn2.call(source, key)) {
30764
31090
  continue;
30765
31091
  }
30766
31092
  if (isUnsafeKey(key, options.unsafeKeys)) {
@@ -30805,7 +31131,7 @@ var resolveReference = /* @__PURE__ */ __name((id2, context, depth, options) =>
30805
31131
  context.resolved.set(id2, target);
30806
31132
  const source = node.value;
30807
31133
  for (const key in source) {
30808
- if (!hasOwn.call(source, key)) {
31134
+ if (!hasOwn2.call(source, key)) {
30809
31135
  continue;
30810
31136
  }
30811
31137
  if (isUnsafeKey(key, options.unsafeKeys)) {
@@ -30877,7 +31203,7 @@ var mergePlaceholder = /* @__PURE__ */ __name((placeholder, result, unsafeKeys)
30877
31203
  const target = placeholder;
30878
31204
  const source = result;
30879
31205
  for (const key in source) {
30880
- if (!hasOwn.call(source, key)) {
31206
+ if (!hasOwn2.call(source, key)) {
30881
31207
  continue;
30882
31208
  }
30883
31209
  if (isUnsafeKey(key, unsafeKeys)) {
@@ -30910,7 +31236,7 @@ var deserializeLegacy = /* @__PURE__ */ __name((value, depth, options) => {
30910
31236
  const obj = {};
30911
31237
  const source = value;
30912
31238
  for (const key in source) {
30913
- if (!hasOwn.call(source, key)) {
31239
+ if (!hasOwn2.call(source, key)) {
30914
31240
  continue;
30915
31241
  }
30916
31242
  if (isUnsafeKey(key, options.unsafeKeys)) {
@@ -30921,6 +31247,26 @@ var deserializeLegacy = /* @__PURE__ */ __name((value, depth, options) => {
30921
31247
  return obj;
30922
31248
  }, "deserializeLegacy");
30923
31249
 
31250
+ // src/serializer/option-normalizers.ts
31251
+ var normalizeMaxDepth = /* @__PURE__ */ __name((value, fallback) => {
31252
+ if (value === Number.POSITIVE_INFINITY) {
31253
+ return Number.POSITIVE_INFINITY;
31254
+ }
31255
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) {
31256
+ return Math.floor(value);
31257
+ }
31258
+ return fallback;
31259
+ }, "normalizeMaxDepth");
31260
+ var normalizeMaxRegExpPatternLength = /* @__PURE__ */ __name((value, fallback) => {
31261
+ if (value === Number.POSITIVE_INFINITY) {
31262
+ return Number.POSITIVE_INFINITY;
31263
+ }
31264
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
31265
+ return Math.floor(value);
31266
+ }
31267
+ return fallback;
31268
+ }, "normalizeMaxRegExpPatternLength");
31269
+
30924
31270
  // src/serializer/Serializer.ts
30925
31271
  var GRAPH_VERSION = 1;
30926
31272
  var DEFAULT_MAX_DEPTH = 1e3;
@@ -30956,10 +31302,11 @@ var Serializer = class {
30956
31302
  return check(pattern, index);
30957
31303
  }, "isBoundedQuantifier");
30958
31304
  this.indent = options.pretty ? 2 : void 0;
30959
- const maxDepth = options.maxDepth;
30960
- this.maxDepth = typeof maxDepth === "number" && Number.isFinite(maxDepth) && maxDepth >= 0 ? Math.floor(maxDepth) : DEFAULT_MAX_DEPTH;
30961
- const maxPatternLength = options.maxRegExpPatternLength;
30962
- 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;
31305
+ this.maxDepth = normalizeMaxDepth(options.maxDepth, DEFAULT_MAX_DEPTH);
31306
+ this.maxRegExpPatternLength = normalizeMaxRegExpPatternLength(
31307
+ options.maxRegExpPatternLength,
31308
+ DEFAULT_MAX_REGEXP_PATTERN_LENGTH
31309
+ );
30963
31310
  this.allowUnsafeRegExp = options.allowUnsafeRegExp ?? false;
30964
31311
  this.unsafeKeys = DEFAULT_UNSAFE_KEYS;
30965
31312
  this.typeRegistry = new TypeRegistry({
@@ -31094,13 +31441,6 @@ var Serializer = class {
31094
31441
  }
31095
31442
  };
31096
31443
 
31097
- // src/serializer/index.ts
31098
- var defaultSerializer = new Serializer();
31099
- function getDefaultSerializer() {
31100
- return defaultSerializer;
31101
- }
31102
- __name(getDefaultSerializer, "getDefaultSerializer");
31103
-
31104
31444
  // src/definers/defineAsyncContext.ts
31105
31445
  var platform = getPlatform();
31106
31446
  var storage = platform.createAsyncLocalStorage();
@@ -31108,13 +31448,14 @@ function getCurrentStore() {
31108
31448
  return storage.getStore();
31109
31449
  }
31110
31450
  __name(getCurrentStore, "getCurrentStore");
31111
- function defineAsyncContext(def) {
31451
+ function defineAsyncContext(def, filePath) {
31112
31452
  if (!platform.hasAsyncLocalStorage()) {
31113
31453
  platformUnsupportedFunctionError.throw({
31114
31454
  functionName: `createAsyncLocalStorage: Cannot create context ${def.id}: no async storage available in this environment`
31115
31455
  });
31116
31456
  }
31117
31457
  const ctxId = def.id;
31458
+ const resolvedFilePath = filePath ?? getCallerFile();
31118
31459
  const use = /* @__PURE__ */ __name(() => {
31119
31460
  const store2 = getCurrentStore();
31120
31461
  if (!store2 || !store2.has(ctxId)) {
@@ -31131,10 +31472,11 @@ function defineAsyncContext(def) {
31131
31472
  map.set(ctxId, value);
31132
31473
  return storage.run(map, fn);
31133
31474
  }, "provide");
31134
- const serializer3 = getDefaultSerializer();
31475
+ const serializer3 = new Serializer();
31135
31476
  const api = {
31136
31477
  id: ctxId,
31137
31478
  [symbolAsyncContext]: true,
31479
+ [symbolFilePath]: resolvedFilePath,
31138
31480
  use,
31139
31481
  /* istanbul ignore next */
31140
31482
  provide(value, fn) {
@@ -31786,12 +32128,12 @@ var EventManager = class {
31786
32128
  data,
31787
32129
  timestamp: /* @__PURE__ */ new Date(),
31788
32130
  source,
31789
- meta: eventDefinition.meta || {},
32131
+ meta: { ...eventDefinition.meta || {} },
31790
32132
  stopPropagation: /* @__PURE__ */ __name(() => {
31791
32133
  propagationStopped = true;
31792
32134
  }, "stopPropagation"),
31793
32135
  isPropagationStopped: /* @__PURE__ */ __name(() => propagationStopped, "isPropagationStopped"),
31794
- tags: eventDefinition.tags
32136
+ tags: [...eventDefinition.tags]
31795
32137
  };
31796
32138
  const baseEmit = /* @__PURE__ */ __name(async (eventToEmit) => {
31797
32139
  if (allListeners.length === 0) {
@@ -31817,10 +32159,14 @@ var EventManager = class {
31817
32159
  if (!interceptor) {
31818
32160
  return baseEmit(eventToEmit);
31819
32161
  }
31820
- return interceptor(
31821
- (nextEvent) => runInterceptor(index + 1, nextEvent),
31822
- eventToEmit
31823
- );
32162
+ return interceptor((nextEvent) => {
32163
+ this.assertPropagationMethodsUnchanged(
32164
+ eventDefinition.id,
32165
+ eventToEmit,
32166
+ nextEvent
32167
+ );
32168
+ return runInterceptor(index + 1, nextEvent);
32169
+ }, eventToEmit);
31824
32170
  }, "runInterceptor");
31825
32171
  await runInterceptor(0, event2);
31826
32172
  return deepestEvent;
@@ -31931,21 +32277,24 @@ var EventManager = class {
31931
32277
  lockedError.throw({ what: "EventManager" });
31932
32278
  }
31933
32279
  }
31934
- /**
31935
- * Clears all listeners and interceptors.
31936
- * Call this to release references and free memory.
31937
- */
31938
- clear() {
31939
- this.registry.clear();
31940
- this.emissionInterceptors.length = 0;
31941
- this.hookInterceptors.length = 0;
32280
+ assertPropagationMethodsUnchanged(eventId, currentEvent, nextEvent) {
32281
+ if (nextEvent.stopPropagation !== currentEvent.stopPropagation || nextEvent.isPropagationStopped !== currentEvent.isPropagationStopped) {
32282
+ validationError.throw({
32283
+ subject: "Event interceptor",
32284
+ id: eventId,
32285
+ originalError: new Error(
32286
+ "Interceptors cannot override stopPropagation/isPropagationStopped"
32287
+ )
32288
+ });
32289
+ }
31942
32290
  }
31943
32291
  /**
31944
32292
  * Disposes the EventManager, releasing all listeners and interceptors.
31945
- * Alias for clear() following the IResource disposal pattern.
31946
32293
  */
31947
32294
  dispose() {
31948
- this.clear();
32295
+ this.registry.clear();
32296
+ this.emissionInterceptors.length = 0;
32297
+ this.hookInterceptors.length = 0;
31949
32298
  }
31950
32299
  /**
31951
32300
  * Retrieves cached merged listeners for an event, or creates them if not cached.
@@ -33252,7 +33601,7 @@ var TaskRunner = class {
33252
33601
  __name(this, "TaskRunner");
33253
33602
  }
33254
33603
  /**
33255
- * 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.
33604
+ * 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.
33256
33605
  * This function can throw only if any of the event listeners or run function throws
33257
33606
  * @param task the task to be run
33258
33607
  * @param input the input to be passed to the task
@@ -33281,8 +33630,6 @@ var TaskRunner = class {
33281
33630
  /**
33282
33631
  * Creates the function with the chain of middleware.
33283
33632
  * @param task
33284
- * @param input
33285
- * @param taskDependencies
33286
33633
  * @returns
33287
33634
  */
33288
33635
  createRunnerWithMiddleware(task2) {
@@ -33302,7 +33649,7 @@ var ResourceInitializer = class {
33302
33649
  __name(this, "ResourceInitializer");
33303
33650
  }
33304
33651
  /**
33305
- * 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.
33652
+ * 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.
33306
33653
  * This function can throw only if any of the event listeners or run function throws
33307
33654
  */
33308
33655
  async initializeResource(resource2, config, dependencies) {
@@ -33792,23 +34139,28 @@ var DependencyProcessor = class {
33792
34139
  middleware.computedDependencies = computedDependencies;
33793
34140
  middleware.isInitialized = true;
33794
34141
  }
33795
- for (const resource2 of this.store.resources.values()) {
33796
- await this.processResourceDependencies(resource2);
33797
- }
33798
- for (const task2 of this.store.tasks.values()) {
33799
- await this.computeTaskDependencies(task2);
33800
- }
33801
34142
  for (const hookStoreElement of this.store.hooks.values()) {
33802
34143
  const hook2 = hookStoreElement.hook;
33803
34144
  const deps = hook2.dependencies;
34145
+ hookStoreElement.dependencyState = "computing" /* Computing */;
33804
34146
  hookStoreElement.computedDependencies = await this.extractDependencies(
33805
34147
  deps,
33806
34148
  hook2.id
33807
34149
  );
34150
+ hookStoreElement.dependencyState = "ready" /* Ready */;
34151
+ }
34152
+ for (const resource2 of this.store.resources.values()) {
34153
+ await this.processResourceDependencies(resource2);
34154
+ }
34155
+ for (const task2 of this.store.tasks.values()) {
34156
+ await this.computeTaskDependencies(task2);
33808
34157
  }
33809
34158
  await this.initializeUninitializedResources();
33810
34159
  }
33811
34160
  async computeTaskDependencies(task2) {
34161
+ if (task2.isInitialized) {
34162
+ return;
34163
+ }
33812
34164
  const deps = task2.task.dependencies;
33813
34165
  task2.computedDependencies = await this.extractDependencies(
33814
34166
  deps,
@@ -33940,6 +34292,9 @@ var DependencyProcessor = class {
33940
34292
  if (receivedEvent.source === hook2.id) {
33941
34293
  return;
33942
34294
  }
34295
+ if (hookStoreElement.dependencyState !== "ready" /* Ready */) {
34296
+ return;
34297
+ }
33943
34298
  return this.eventManager.executeHookWithInterceptors(
33944
34299
  hook2,
33945
34300
  receivedEvent,
@@ -34056,7 +34411,7 @@ var DependencyProcessor = class {
34056
34411
  }
34057
34412
  const st = storeTask;
34058
34413
  if (!st.isInitialized) {
34059
- const dependencies = object.dependencies;
34414
+ const dependencies = st.task.dependencies;
34060
34415
  st.computedDependencies = await this.extractDependencies(
34061
34416
  dependencies,
34062
34417
  st.task.id
@@ -34082,14 +34437,19 @@ var DependencyProcessor = class {
34082
34437
  wrapped = this.wrapResourceDependencies(depMap, raw);
34083
34438
  sr.computedDependencies = wrapped;
34084
34439
  }
34085
- const { value, context } = await this.resourceInitializer.initializeResource(
34086
- resource2,
34087
- config,
34088
- wrapped
34089
- );
34090
- sr.context = context;
34091
- sr.value = value;
34092
- sr.isInitialized = true;
34440
+ try {
34441
+ const { value, context } = await this.resourceInitializer.initializeResource(
34442
+ resource2,
34443
+ config,
34444
+ wrapped
34445
+ );
34446
+ sr.context = context;
34447
+ sr.value = value;
34448
+ sr.isInitialized = true;
34449
+ this.store.recordResourceInitialized(resource2.id);
34450
+ } catch (error2) {
34451
+ this.rethrowResourceInitError(resource2.id, error2);
34452
+ }
34093
34453
  }
34094
34454
  return sr.value;
34095
34455
  }
@@ -34292,7 +34652,8 @@ var StoreRegistry = class {
34292
34652
  const hook2 = this.getFreshValue(item, this.hooks, "hook", overrideMode);
34293
34653
  this.hooks.set(hook2.id, {
34294
34654
  hook: hook2,
34295
- computedDependencies: {}
34655
+ computedDependencies: {},
34656
+ dependencyState: "pending" /* Pending */
34296
34657
  });
34297
34658
  }
34298
34659
  storeTaskMiddleware(item, storingMode = "normal") {
@@ -34347,7 +34708,10 @@ var StoreRegistry = class {
34347
34708
  return prepared;
34348
34709
  }
34349
34710
  computeRegistrationDeeply(element, config) {
34350
- const items = typeof element.register === "function" ? element.register(config) : element.register;
34711
+ let items = typeof element.register === "function" ? element.register(config) : element.register;
34712
+ if (!items) {
34713
+ items = [];
34714
+ }
34351
34715
  element.register = items;
34352
34716
  for (const item of items) {
34353
34717
  this.storeGenericItem(item);
@@ -34885,25 +35249,27 @@ var InterceptorRegistry = class {
34885
35249
  * Gets all global task interceptors
34886
35250
  */
34887
35251
  getGlobalTaskInterceptors() {
34888
- return this.taskInterceptors;
35252
+ return Object.freeze([...this.taskInterceptors]);
34889
35253
  }
34890
35254
  /**
34891
35255
  * Gets all global resource interceptors
34892
35256
  */
34893
35257
  getGlobalResourceInterceptors() {
34894
- return this.resourceInterceptors;
35258
+ return Object.freeze([...this.resourceInterceptors]);
34895
35259
  }
34896
35260
  /**
34897
35261
  * Gets interceptors for a specific task middleware
34898
35262
  */
34899
35263
  getTaskMiddlewareInterceptors(middlewareId) {
34900
- return this.perTaskMiddleware.get(middlewareId) || [];
35264
+ const interceptors = this.perTaskMiddleware.get(middlewareId) ?? [];
35265
+ return Object.freeze([...interceptors]);
34901
35266
  }
34902
35267
  /**
34903
35268
  * Gets interceptors for a specific resource middleware
34904
35269
  */
34905
35270
  getResourceMiddlewareInterceptors(middlewareId) {
34906
- return this.perResourceMiddleware.get(middlewareId) || [];
35271
+ const interceptors = this.perResourceMiddleware.get(middlewareId) ?? [];
35272
+ return Object.freeze([...interceptors]);
34907
35273
  }
34908
35274
  };
34909
35275
 
@@ -35382,10 +35748,8 @@ var ResourceMiddlewareComposer = class {
35382
35748
 
35383
35749
  // src/models/MiddlewareManager.ts
35384
35750
  var MiddlewareManager = class {
35385
- constructor(store2, eventManager, logger) {
35751
+ constructor(store2, _eventManager, _logger) {
35386
35752
  this.store = store2;
35387
- this.eventManager = eventManager;
35388
- this.logger = logger;
35389
35753
  this.interceptorRegistry = new InterceptorRegistry();
35390
35754
  this.middlewareResolver = new MiddlewareResolver(store2);
35391
35755
  this.taskComposer = new TaskMiddlewareComposer(
@@ -35426,14 +35790,6 @@ var MiddlewareManager = class {
35426
35790
  lock() {
35427
35791
  this.interceptorRegistry.lock();
35428
35792
  }
35429
- /**
35430
- * Adds an interceptor for task or resource middleware execution
35431
- * Interceptors are executed in the order they are added, with the ability to
35432
- * modify, log, or prevent middleware execution
35433
- *
35434
- * @param kind - The type of middleware to intercept ("task" or "resource")
35435
- * @param interceptor - The interceptor function to add
35436
- */
35437
35793
  intercept(kind, interceptor) {
35438
35794
  if (kind === "task") {
35439
35795
  this.interceptorRegistry.addGlobalTaskInterceptor(
@@ -35445,13 +35801,6 @@ var MiddlewareManager = class {
35445
35801
  );
35446
35802
  }
35447
35803
  }
35448
- /**
35449
- * Adds an interceptor for a specific middleware instance with better type safety
35450
- * This method automatically determines the type and provides type-safe access
35451
- *
35452
- * @param middleware - The middleware instance to intercept
35453
- * @param interceptor - The interceptor function with proper typing
35454
- */
35455
35804
  interceptMiddleware(middleware, interceptor) {
35456
35805
  if (isTaskMiddleware(middleware)) {
35457
35806
  this.interceptorRegistry.addTaskMiddlewareInterceptor(
@@ -35590,12 +35939,17 @@ var Store = class {
35590
35939
  }
35591
35940
  }
35592
35941
  registerGlobalComponents() {
35942
+ if (!this.taskRunner) {
35943
+ throw new Error(
35944
+ "TaskRunner is not set. Call store.setTaskRunner() before initializeStore()."
35945
+ );
35946
+ }
35593
35947
  const builtInResourcesMap = /* @__PURE__ */ new Map();
35594
35948
  builtInResourcesMap.set(globalResources.store, this);
35595
35949
  builtInResourcesMap.set(globalResources.eventManager, this.eventManager);
35596
35950
  builtInResourcesMap.set(globalResources.logger, this.logger);
35597
35951
  builtInResourcesMap.set(globalResources.taskRunner, this.taskRunner);
35598
- builtInResourcesMap.set(globalResources.serializer, getDefaultSerializer());
35952
+ builtInResourcesMap.set(globalResources.serializer, new Serializer());
35599
35953
  builtInResourcesMap.set(
35600
35954
  globalResources.middlewareManager,
35601
35955
  this.middlewareManager
@@ -35655,8 +36009,11 @@ var Store = class {
35655
36009
  setTaskRunner(taskRunner) {
35656
36010
  this.taskRunner = taskRunner;
35657
36011
  }
35658
- setupRootResource(root, config) {
35659
- root.dependencies = typeof root.dependencies === "function" ? root.dependencies(config) : root.dependencies;
36012
+ setupRootResource(rootDefinition, config) {
36013
+ const root = {
36014
+ ...rootDefinition,
36015
+ dependencies: typeof rootDefinition.dependencies === "function" ? rootDefinition.dependencies(config) : rootDefinition.dependencies
36016
+ };
35660
36017
  this.root = {
35661
36018
  resource: root,
35662
36019
  computedDependencies: {},
@@ -36209,6 +36566,18 @@ var RunResult = class {
36209
36566
  }
36210
36567
  return this.store.resources.get(resourceId).value;
36211
36568
  }, "getResourceValue");
36569
+ /**
36570
+ * Get the config of a resource from the run result.
36571
+ * @param resource - The resource to get the config of.
36572
+ * @returns The config passed for the resource.
36573
+ */
36574
+ this.getResourceConfig = /* @__PURE__ */ __name((resource2) => {
36575
+ const resourceId = typeof resource2 === "string" ? resource2 : resource2.id;
36576
+ if (!this.store.resources.has(resourceId)) {
36577
+ throw new Error(`Resource "${resourceId}" not found.`);
36578
+ }
36579
+ return this.store.resources.get(resourceId).config;
36580
+ }, "getResourceConfig");
36212
36581
  this.dispose = /* @__PURE__ */ __name(() => {
36213
36582
  return this.disposeFn();
36214
36583
  }, "dispose");
@@ -37390,7 +37759,7 @@ function makeAsyncContextBuilder(state) {
37390
37759
  configSchema: state.configSchema,
37391
37760
  meta: state.meta
37392
37761
  };
37393
- return defineAsyncContext(def);
37762
+ return defineAsyncContext(def, state.filePath);
37394
37763
  }
37395
37764
  };
37396
37765
  return builder;
@@ -37399,8 +37768,10 @@ __name(makeAsyncContextBuilder, "makeAsyncContextBuilder");
37399
37768
 
37400
37769
  // src/definers/builders/asyncContext/index.ts
37401
37770
  function asyncContextBuilder(id2) {
37771
+ const filePath = getCallerFile();
37402
37772
  const initial = Object.freeze({
37403
37773
  id: id2,
37774
+ filePath,
37404
37775
  serialize: void 0,
37405
37776
  parse: void 0,
37406
37777
  configSchema: void 0,
@@ -37873,7 +38244,7 @@ function override(base) {
37873
38244
  }
37874
38245
  __name(override, "override");
37875
38246
 
37876
- // src/index.ts
38247
+ // src/public.ts
37877
38248
  init_http_fetch_tunnel_resource();
37878
38249
  var globals = {
37879
38250
  events: globalEvents,
@@ -39017,15 +39388,15 @@ var UNSAFE_ERROR_FIELDS = /* @__PURE__ */ new Set([
39017
39388
  "cause" /* Cause */,
39018
39389
  "sql" /* Sql */
39019
39390
  ]);
39020
- var isRecord = /* @__PURE__ */ __name((value) => !!value && typeof value === "object", "isRecord");
39021
- var isJsonBody = /* @__PURE__ */ __name((value) => isRecord(value) && typeof value.ok === "boolean", "isJsonBody");
39022
- var toErrorRecord = /* @__PURE__ */ __name((value) => isRecord(value) ? value : void 0, "toErrorRecord");
39391
+ var isRecord2 = /* @__PURE__ */ __name((value) => !!value && typeof value === "object", "isRecord");
39392
+ var isJsonBody = /* @__PURE__ */ __name((value) => isRecord2(value) && typeof value.ok === "boolean", "isJsonBody");
39393
+ var toErrorRecord = /* @__PURE__ */ __name((value) => isRecord2(value) ? value : void 0, "toErrorRecord");
39023
39394
  var sanitizeErrorResponse = /* @__PURE__ */ __name((response) => {
39024
- const asRecord = isRecord(response) ? response : void 0;
39395
+ const asRecord = isRecord2(response) ? response : void 0;
39025
39396
  const statusRaw = asRecord?.status ?? asRecord?.statusCode;
39026
39397
  const status = typeof statusRaw === "number" && Number.isFinite(statusRaw) ? statusRaw : 500;
39027
39398
  const bodyRaw = asRecord?.body;
39028
- const body = isRecord(bodyRaw) ? bodyRaw : void 0;
39399
+ const body = isRecord2(bodyRaw) ? bodyRaw : void 0;
39029
39400
  const errorRaw = (body ? toErrorRecord(body.error) : void 0) ?? toErrorRecord(asRecord?.error);
39030
39401
  const normalizedBody = (() => {
39031
39402
  if (isJsonBody(bodyRaw)) {
@@ -39082,7 +39453,7 @@ var resolveAppErrorExtra = /* @__PURE__ */ __name((store2, error2) => {
39082
39453
  try {
39083
39454
  for (const helper of store2.errors.values()) {
39084
39455
  if (helper.is(error2)) {
39085
- if (!isRecord(error2)) return { id: void 0, data: void 0 };
39456
+ if (!isRecord2(error2)) return { id: void 0, data: void 0 };
39086
39457
  const name = error2["name" /* Name */];
39087
39458
  const id2 = typeof name === "string" ? name : void 0;
39088
39459
  const data = error2["data" /* Data */];
@@ -39798,10 +40169,10 @@ function createDurableStepId(id2) {
39798
40169
  return { id: id2 };
39799
40170
  }
39800
40171
  __name(createDurableStepId, "createDurableStepId");
39801
- function isRecord2(value) {
40172
+ function isRecord3(value) {
39802
40173
  return typeof value === "object" && value !== null;
39803
40174
  }
39804
- __name(isRecord2, "isRecord");
40175
+ __name(isRecord3, "isRecord");
39805
40176
  function sleepMs(ms) {
39806
40177
  return new Promise((resolve) => {
39807
40178
  const timer = setTimeout$1(resolve, ms);
@@ -39831,7 +40202,7 @@ function createExecutionId() {
39831
40202
  }
39832
40203
  __name(createExecutionId, "createExecutionId");
39833
40204
  function parseSignalState(value) {
39834
- if (!isRecord2(value)) return null;
40205
+ if (!isRecord3(value)) return null;
39835
40206
  const state = value.state;
39836
40207
  if (state === "waiting") {
39837
40208
  const timerId = value.timerId;
@@ -39873,6 +40244,7 @@ var DurableAuditEntryKind = {
39873
40244
  SignalDelivered: "signal_delivered",
39874
40245
  SignalTimedOut: "signal_timed_out",
39875
40246
  EmitPublished: "emit_published",
40247
+ SwitchEvaluated: "switch_evaluated",
39876
40248
  Note: "note"
39877
40249
  };
39878
40250
  function isDurableInternalStepId(stepId) {
@@ -39896,15 +40268,194 @@ var SuspensionSignal = class extends Error {
39896
40268
  }
39897
40269
  };
39898
40270
 
40271
+ // src/node/durable/core/DurableOperator.ts
40272
+ var DurableOperator = class {
40273
+ constructor(store2) {
40274
+ this.store = store2;
40275
+ }
40276
+ static {
40277
+ __name(this, "DurableOperator");
40278
+ }
40279
+ async listExecutions(options) {
40280
+ if (this.store.listExecutions) {
40281
+ return await this.store.listExecutions(options);
40282
+ }
40283
+ return await this.store.listIncompleteExecutions();
40284
+ }
40285
+ async getExecutionDetail(executionId) {
40286
+ const execution = await this.store.getExecution(executionId);
40287
+ const steps = this.store.listStepResults ? await this.store.listStepResults(executionId) : [];
40288
+ const audit = this.store.listAuditEntries ? await this.store.listAuditEntries(executionId) : [];
40289
+ return { execution, steps, audit };
40290
+ }
40291
+ /**
40292
+ * Resets an execution from `compensation_failed` (or other states) to `pending`.
40293
+ * This effectively retries the workflow from the last memoized step.
40294
+ */
40295
+ async retryRollback(executionId) {
40296
+ if (!this.store.retryRollback) {
40297
+ throw new Error("Store does not support retryRollback");
40298
+ }
40299
+ await this.store.retryRollback(executionId);
40300
+ }
40301
+ /**
40302
+ * Manually marks a step as completed with a specific result.
40303
+ * Useful for skipping broken steps or providing a manual fix.
40304
+ */
40305
+ async skipStep(executionId, stepId) {
40306
+ if (!this.store.skipStep) {
40307
+ throw new Error("Store does not support skipStep");
40308
+ }
40309
+ await this.store.skipStep(executionId, stepId);
40310
+ }
40311
+ /**
40312
+ * Forces an execution to the `failed` state.
40313
+ */
40314
+ async forceFail(executionId, reason) {
40315
+ if (!this.store.forceFail) {
40316
+ throw new Error("Store does not support forceFail");
40317
+ }
40318
+ await this.store.forceFail(executionId, { message: reason });
40319
+ }
40320
+ /**
40321
+ * Manually patches the result of a step.
40322
+ * Useful when a step failed to save its result but the side effect occurred.
40323
+ */
40324
+ async editState(executionId, stepId, newState) {
40325
+ if (!this.store.editStepResult) {
40326
+ throw new Error("Store does not support editStepResult");
40327
+ }
40328
+ await this.store.editStepResult(executionId, stepId, newState);
40329
+ }
40330
+ /**
40331
+ * Lists all executions that require manual intervention.
40332
+ */
40333
+ async listStuckExecutions() {
40334
+ if (!this.store.listStuckExecutions) {
40335
+ throw new Error("Store does not support listStuckExecutions");
40336
+ }
40337
+ return await this.store.listStuckExecutions();
40338
+ }
40339
+ };
40340
+
40341
+ // src/node/durable/core/flowShape.ts
40342
+ var FlowRecorder = class {
40343
+ constructor() {
40344
+ this.nodes = [];
40345
+ this.executionId = "__flow_record__";
40346
+ this.attempt = 0;
40347
+ }
40348
+ static {
40349
+ __name(this, "FlowRecorder");
40350
+ }
40351
+ resolveStepId(stepId) {
40352
+ return typeof stepId === "string" ? stepId : stepId.id;
40353
+ }
40354
+ step(stepId, optionsOrFn, _fn) {
40355
+ const id2 = this.resolveStepId(stepId);
40356
+ if (optionsOrFn === void 0) {
40357
+ return new FlowStepRecorder(this, id2);
40358
+ }
40359
+ this.nodes.push({ kind: "step", stepId: id2, hasCompensation: false });
40360
+ return Promise.resolve(void 0);
40361
+ }
40362
+ async sleep(durationMs, options) {
40363
+ this.nodes.push({
40364
+ kind: "sleep",
40365
+ durationMs,
40366
+ stepId: options?.stepId
40367
+ });
40368
+ }
40369
+ async waitForSignal(signal, options) {
40370
+ this.nodes.push({
40371
+ kind: "waitForSignal",
40372
+ signalId: signal.id,
40373
+ timeoutMs: options?.timeoutMs,
40374
+ stepId: options?.stepId
40375
+ });
40376
+ return void 0;
40377
+ }
40378
+ async emit(_event, _payload, options) {
40379
+ this.nodes.push({
40380
+ kind: "emit",
40381
+ eventId: _event.id,
40382
+ stepId: options?.stepId
40383
+ });
40384
+ }
40385
+ async switch(stepId, _value, branches, defaultBranch) {
40386
+ this.nodes.push({
40387
+ kind: "switch",
40388
+ stepId,
40389
+ branchIds: branches.map((b) => b.id),
40390
+ hasDefault: defaultBranch !== void 0
40391
+ });
40392
+ return void 0;
40393
+ }
40394
+ async note(message, _meta) {
40395
+ this.nodes.push({ kind: "note", message });
40396
+ }
40397
+ async rollback() {
40398
+ }
40399
+ };
40400
+ var FlowStepRecorder = class {
40401
+ constructor(recorder, stepId) {
40402
+ this.recorder = recorder;
40403
+ this.stepId = stepId;
40404
+ this.hasDown = false;
40405
+ }
40406
+ static {
40407
+ __name(this, "FlowStepRecorder");
40408
+ }
40409
+ up(_fn) {
40410
+ return this;
40411
+ }
40412
+ down(_fn) {
40413
+ this.hasDown = true;
40414
+ return this;
40415
+ }
40416
+ then(onfulfilled, onrejected) {
40417
+ this.recorder.nodes.push({
40418
+ kind: "step",
40419
+ stepId: this.stepId,
40420
+ hasCompensation: this.hasDown
40421
+ });
40422
+ const result = Promise.resolve(void 0);
40423
+ return result.then(
40424
+ onfulfilled ?? ((v) => v),
40425
+ onrejected
40426
+ );
40427
+ }
40428
+ };
40429
+ async function recordFlowShape(descriptor) {
40430
+ const recorder = new FlowRecorder();
40431
+ await descriptor(recorder);
40432
+ return { nodes: recorder.nodes };
40433
+ }
40434
+ __name(recordFlowShape, "recordFlowShape");
40435
+
39899
40436
  // src/node/durable/core/DurableResource.ts
39900
- var DurableResource = class {
39901
- constructor(service, contextStorage) {
40437
+ var DurableResource = class _DurableResource {
40438
+ constructor(service, contextStorage, store2, runnerStore) {
39902
40439
  this.service = service;
39903
40440
  this.contextStorage = contextStorage;
40441
+ this.store = store2;
40442
+ this.runnerStore = runnerStore;
40443
+ this.operatorInstance = null;
39904
40444
  }
39905
40445
  static {
39906
40446
  __name(this, "DurableResource");
39907
40447
  }
40448
+ get operator() {
40449
+ if (!this.store) {
40450
+ throw new Error(
40451
+ "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."
40452
+ );
40453
+ }
40454
+ if (!this.operatorInstance) {
40455
+ this.operatorInstance = new DurableOperator(this.store);
40456
+ }
40457
+ return this.operatorInstance;
40458
+ }
39908
40459
  use() {
39909
40460
  const ctx = this.contextStorage.getStore();
39910
40461
  if (!ctx) {
@@ -39914,6 +40465,47 @@ var DurableResource = class {
39914
40465
  }
39915
40466
  return ctx;
39916
40467
  }
40468
+ async describe(task2, input) {
40469
+ if (!this.runnerStore) {
40470
+ throw new Error(
40471
+ "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."
40472
+ );
40473
+ }
40474
+ const storeTask = this.runnerStore.tasks.get(task2.id);
40475
+ if (!storeTask) {
40476
+ throw new Error(
40477
+ `Cannot describe task "${task2.id}": task is not registered in the runtime store.`
40478
+ );
40479
+ }
40480
+ const effectiveTask = storeTask.task;
40481
+ if (!storeTask.computedDependencies) {
40482
+ throw new Error(
40483
+ `Cannot describe task "${task2.id}": task dependencies are not available in the runtime store.`
40484
+ );
40485
+ }
40486
+ const deps = storeTask.computedDependencies;
40487
+ return await recordFlowShape(async (ctx) => {
40488
+ const depsWithRecorder = this.injectRecorderIntoDurableDeps(deps, ctx);
40489
+ await effectiveTask.run(input, depsWithRecorder);
40490
+ });
40491
+ }
40492
+ injectRecorderIntoDurableDeps(deps, ctx) {
40493
+ const next = { ...deps };
40494
+ for (const [key, value] of Object.entries(deps)) {
40495
+ if (!(value instanceof _DurableResource)) {
40496
+ continue;
40497
+ }
40498
+ next[key] = new Proxy(value, {
40499
+ get(target, prop, receiver) {
40500
+ if (prop === "use") {
40501
+ return () => ctx;
40502
+ }
40503
+ return Reflect.get(target, prop, receiver);
40504
+ }
40505
+ });
40506
+ }
40507
+ return next;
40508
+ }
39917
40509
  startExecution(task2, input, options) {
39918
40510
  return this.service.startExecution(task2, input, options);
39919
40511
  }
@@ -40609,7 +41201,7 @@ var ScheduleManager = class {
40609
41201
  // src/node/durable/core/managers/SignalHandler.ts
40610
41202
  var isWaitingSignalStep = /* @__PURE__ */ __name((step) => {
40611
41203
  const result = step.result;
40612
- if (!isRecord2(result)) return false;
41204
+ if (!isRecord3(result)) return false;
40613
41205
  const waitResult = result;
40614
41206
  if (waitResult.state !== "waiting") return false;
40615
41207
  if (typeof waitResult.signalId !== "string") return false;
@@ -41086,7 +41678,7 @@ function getSignalId(signal) {
41086
41678
  }
41087
41679
  __name(getSignalId, "getSignalId");
41088
41680
  function parseSignalStepState(value) {
41089
- if (!isRecord2(value)) return null;
41681
+ if (!isRecord3(value)) return null;
41090
41682
  const state = value.state;
41091
41683
  if (state === "waiting") {
41092
41684
  const signalId = value.signalId;
@@ -41282,6 +41874,58 @@ async function waitForSignalDurably(params) {
41282
41874
  }
41283
41875
  __name(waitForSignalDurably, "waitForSignalDurably");
41284
41876
 
41877
+ // src/node/durable/core/durable-context/DurableContext.switch.ts
41878
+ async function switchDurably(params) {
41879
+ await params.assertNotCancelled();
41880
+ params.assertUniqueStepId(params.stepId);
41881
+ const cached = await params.store.getStepResult(
41882
+ params.executionId,
41883
+ params.stepId
41884
+ );
41885
+ if (cached) {
41886
+ const persisted = cached.result;
41887
+ return persisted.result;
41888
+ }
41889
+ const startedAt = Date.now();
41890
+ let matchedBranch = null;
41891
+ for (const branch of params.branches) {
41892
+ if (branch.match(params.value)) {
41893
+ matchedBranch = { id: branch.id, run: branch.run };
41894
+ break;
41895
+ }
41896
+ }
41897
+ if (!matchedBranch && params.defaultBranch) {
41898
+ matchedBranch = {
41899
+ id: params.defaultBranch.id,
41900
+ run: params.defaultBranch.run
41901
+ };
41902
+ }
41903
+ if (!matchedBranch) {
41904
+ throw new Error(
41905
+ `Durable switch '${params.stepId}': no branch matched and no default provided`
41906
+ );
41907
+ }
41908
+ const result = await matchedBranch.run(params.value);
41909
+ const durationMs = Date.now() - startedAt;
41910
+ await params.store.saveStepResult({
41911
+ executionId: params.executionId,
41912
+ stepId: params.stepId,
41913
+ result: {
41914
+ branchId: matchedBranch.id,
41915
+ result
41916
+ },
41917
+ completedAt: /* @__PURE__ */ new Date()
41918
+ });
41919
+ await params.appendAuditEntry({
41920
+ kind: DurableAuditEntryKind.SwitchEvaluated,
41921
+ stepId: params.stepId,
41922
+ branchId: matchedBranch.id,
41923
+ durationMs
41924
+ });
41925
+ return result;
41926
+ }
41927
+ __name(switchDurably, "switchDurably");
41928
+
41285
41929
  // src/node/durable/core/DurableContext.ts
41286
41930
  var DurableContext = class {
41287
41931
  constructor(store2, bus, executionId, attempt, options = {}) {
@@ -41402,6 +42046,20 @@ var DurableContext = class {
41402
42046
  options
41403
42047
  });
41404
42048
  }
42049
+ async switch(stepId, value, branches, defaultBranch) {
42050
+ this.determinism.assertUserStepId(stepId);
42051
+ return await switchDurably({
42052
+ store: this.store,
42053
+ executionId: this.executionId,
42054
+ assertNotCancelled: this.assertNotCancelled.bind(this),
42055
+ appendAuditEntry: this.audit.append,
42056
+ assertUniqueStepId: this.determinism.assertUniqueStepId,
42057
+ stepId,
42058
+ value,
42059
+ branches,
42060
+ defaultBranch
42061
+ });
42062
+ }
41405
42063
  async note(message, meta) {
41406
42064
  if (!this.audit.isEnabled()) return;
41407
42065
  const stepId = `__note:${this.noteIndex}`;
@@ -42215,13 +42873,11 @@ async function initDurableWorker(service, queue) {
42215
42873
  }
42216
42874
  __name(initDurableWorker, "initDurableWorker");
42217
42875
 
42218
- // src/node/durable/core/resource.ts
42219
- var durableResource = r.resource("base.durable").register(durableEventsArray).dependencies({
42220
- taskRunner: globals.resources.taskRunner,
42221
- eventManager: globals.resources.eventManager,
42222
- runnerStore: globals.resources.store
42223
- }).init(async (config, { taskRunner, eventManager, runnerStore }) => {
42224
- const runnerEmitter = createDurableRunnerAuditEmitter({ eventManager });
42876
+ // src/node/durable/core/createRunnerDurableRuntime.ts
42877
+ async function createRunnerDurableRuntime(config, deps) {
42878
+ const runnerEmitter = createDurableRunnerAuditEmitter({
42879
+ eventManager: deps.eventManager
42880
+ });
42225
42881
  const userEmitter = config.audit?.emitter;
42226
42882
  const auditEmitter = userEmitter ? {
42227
42883
  emit: /* @__PURE__ */ __name(async (entry) => {
@@ -42244,7 +42900,10 @@ var durableResource = r.resource("base.durable").register(durableEventsArray).de
42244
42900
  },
42245
42901
  taskExecutor: {
42246
42902
  run: /* @__PURE__ */ __name(async (task2, input) => {
42247
- const outputPromise = await taskRunner.run(task2, input);
42903
+ const outputPromise = await deps.taskRunner.run(
42904
+ task2,
42905
+ input
42906
+ );
42248
42907
  if (outputPromise === void 0) {
42249
42908
  throw new Error(
42250
42909
  `Durable task '${task2.id}' completed without a result promise.`
@@ -42254,7 +42913,7 @@ var durableResource = r.resource("base.durable").register(durableEventsArray).de
42254
42913
  }, "run")
42255
42914
  },
42256
42915
  taskResolver: /* @__PURE__ */ __name((taskId) => {
42257
- const storeTask = runnerStore.tasks.get(taskId);
42916
+ const storeTask = deps.runnerStore.tasks.get(taskId);
42258
42917
  return storeTask?.task;
42259
42918
  }, "taskResolver"),
42260
42919
  contextProvider: /* @__PURE__ */ __name((ctx, fn) => contextStorage.run(ctx, fn), "contextProvider")
@@ -42262,81 +42921,30 @@ var durableResource = r.resource("base.durable").register(durableEventsArray).de
42262
42921
  if (config.worker === true && config.queue) {
42263
42922
  await initDurableWorker(service, config.queue);
42264
42923
  }
42265
- return new DurableResource(service, contextStorage);
42924
+ return new DurableResource(
42925
+ service,
42926
+ contextStorage,
42927
+ config.store,
42928
+ deps.runnerStore
42929
+ );
42930
+ }
42931
+ __name(createRunnerDurableRuntime, "createRunnerDurableRuntime");
42932
+
42933
+ // src/node/durable/core/resource.ts
42934
+ var durableResource = r.resource("base.durable").register(durableEventsArray).dependencies({
42935
+ taskRunner: globals.resources.taskRunner,
42936
+ eventManager: globals.resources.eventManager,
42937
+ runnerStore: globals.resources.store
42938
+ }).init(async (config, { taskRunner, eventManager, runnerStore }) => {
42939
+ return await createRunnerDurableRuntime(config, {
42940
+ taskRunner,
42941
+ eventManager,
42942
+ runnerStore
42943
+ });
42266
42944
  }).dispose(
42267
42945
  async (durable, config) => disposeDurableService(durable.service, config)
42268
42946
  ).build();
42269
42947
 
42270
- // src/node/durable/core/DurableOperator.ts
42271
- var DurableOperator = class {
42272
- constructor(store2) {
42273
- this.store = store2;
42274
- }
42275
- static {
42276
- __name(this, "DurableOperator");
42277
- }
42278
- async listExecutions(options) {
42279
- if (this.store.listExecutions) {
42280
- return await this.store.listExecutions(options);
42281
- }
42282
- return await this.store.listIncompleteExecutions();
42283
- }
42284
- async getExecutionDetail(executionId) {
42285
- const execution = await this.store.getExecution(executionId);
42286
- const steps = this.store.listStepResults ? await this.store.listStepResults(executionId) : [];
42287
- const audit = this.store.listAuditEntries ? await this.store.listAuditEntries(executionId) : [];
42288
- return { execution, steps, audit };
42289
- }
42290
- /**
42291
- * Resets an execution from `compensation_failed` (or other states) to `pending`.
42292
- * This effectively retries the workflow from the last memoized step.
42293
- */
42294
- async retryRollback(executionId) {
42295
- if (!this.store.retryRollback) {
42296
- throw new Error("Store does not support retryRollback");
42297
- }
42298
- await this.store.retryRollback(executionId);
42299
- }
42300
- /**
42301
- * Manually marks a step as completed with a specific result.
42302
- * Useful for skipping broken steps or providing a manual fix.
42303
- */
42304
- async skipStep(executionId, stepId) {
42305
- if (!this.store.skipStep) {
42306
- throw new Error("Store does not support skipStep");
42307
- }
42308
- await this.store.skipStep(executionId, stepId);
42309
- }
42310
- /**
42311
- * Forces an execution to the `failed` state.
42312
- */
42313
- async forceFail(executionId, reason) {
42314
- if (!this.store.forceFail) {
42315
- throw new Error("Store does not support forceFail");
42316
- }
42317
- await this.store.forceFail(executionId, { message: reason });
42318
- }
42319
- /**
42320
- * Manually patches the result of a step.
42321
- * Useful when a step failed to save its result but the side effect occurred.
42322
- */
42323
- async editState(executionId, stepId, newState) {
42324
- if (!this.store.editStepResult) {
42325
- throw new Error("Store does not support editStepResult");
42326
- }
42327
- await this.store.editStepResult(executionId, stepId, newState);
42328
- }
42329
- /**
42330
- * Lists all executions that require manual intervention.
42331
- */
42332
- async listStuckExecutions() {
42333
- if (!this.store.listStuckExecutions) {
42334
- throw new Error("Store does not support listStuckExecutions");
42335
- }
42336
- return await this.store.listStuckExecutions();
42337
- }
42338
- };
42339
-
42340
42948
  // src/node/durable/dashboard/server.ts
42341
42949
  var express = __toESM(require_express2());
42342
42950
  function findUp(startDir, filename) {
@@ -42720,7 +43328,7 @@ function createIORedisClient(url) {
42720
43328
  __name(createIORedisClient, "createIORedisClient");
42721
43329
 
42722
43330
  // src/node/durable/store/RedisStore.ts
42723
- var serializer2 = getDefaultSerializer();
43331
+ var serializer2 = new Serializer();
42724
43332
  var RedisStore = class {
42725
43333
  static {
42726
43334
  __name(this, "RedisStore");
@@ -43464,6 +44072,114 @@ async function waitUntil(predicate, options) {
43464
44072
  }
43465
44073
  __name(waitUntil, "waitUntil");
43466
44074
 
44075
+ // src/node/durable/resources/memoryDurableResource.ts
44076
+ var memoryDurableResource = r.resource("base.durable.memory").register(durableEventsArray).dependencies({
44077
+ taskRunner: globals.resources.taskRunner,
44078
+ eventManager: globals.resources.eventManager,
44079
+ runnerStore: globals.resources.store
44080
+ }).context(() => ({ runtimeConfig: null })).init(async function(config, { taskRunner, eventManager, runnerStore }, ctx) {
44081
+ config.namespace ?? this.id;
44082
+ const shouldCreateQueue = config.queue?.enabled ?? config.worker === true;
44083
+ const queue = shouldCreateQueue ? new MemoryQueue() : void 0;
44084
+ const worker = config.worker ?? Boolean(queue);
44085
+ const runtimeConfig = {
44086
+ ...config,
44087
+ worker,
44088
+ store: new MemoryStore(),
44089
+ eventBus: new MemoryEventBus(),
44090
+ queue
44091
+ };
44092
+ ctx.runtimeConfig = runtimeConfig;
44093
+ return await createRunnerDurableRuntime(runtimeConfig, {
44094
+ taskRunner,
44095
+ eventManager,
44096
+ runnerStore
44097
+ });
44098
+ }).dispose(async (durable, _config, _deps, ctx) => {
44099
+ if (!ctx.runtimeConfig) return;
44100
+ await disposeDurableService(durable.service, ctx.runtimeConfig);
44101
+ }).build();
44102
+
44103
+ // src/node/durable/resources/isolation.ts
44104
+ function normalizePrefix(prefix) {
44105
+ return prefix.endsWith(":") ? prefix : `${prefix}:`;
44106
+ }
44107
+ __name(normalizePrefix, "normalizePrefix");
44108
+ function deriveDurableIsolation(params) {
44109
+ if (params.namespace.trim().length === 0) {
44110
+ validationError.throw({
44111
+ subject: "Durable isolation namespace",
44112
+ id: "params.namespace",
44113
+ originalError: "must be a non-empty string"
44114
+ });
44115
+ }
44116
+ const encodedNamespace = encodeURIComponent(params.namespace);
44117
+ const storePrefix = normalizePrefix(
44118
+ params.storePrefix ?? `durable:${encodedNamespace}:`
44119
+ );
44120
+ const busPrefix = normalizePrefix(
44121
+ params.busPrefix ?? `durable:bus:${encodedNamespace}:`
44122
+ );
44123
+ return {
44124
+ namespace: params.namespace,
44125
+ encodedNamespace,
44126
+ storePrefix,
44127
+ busPrefix,
44128
+ queueName: params.queueName ?? `durable_executions:${encodedNamespace}`,
44129
+ deadLetterQueueName: params.deadLetterQueueName ?? `durable_executions:dlq:${encodedNamespace}`
44130
+ };
44131
+ }
44132
+ __name(deriveDurableIsolation, "deriveDurableIsolation");
44133
+
44134
+ // src/node/durable/resources/redisDurableResource.ts
44135
+ var redisDurableResource = r.resource("base.durable.redis").register(durableEventsArray).dependencies({
44136
+ taskRunner: globals.resources.taskRunner,
44137
+ eventManager: globals.resources.eventManager,
44138
+ runnerStore: globals.resources.store
44139
+ }).context(() => ({ runtimeConfig: null })).init(async function(config, { taskRunner, eventManager, runnerStore }, ctx) {
44140
+ const namespace = config.namespace ?? this.id;
44141
+ const isolation = deriveDurableIsolation({
44142
+ namespace,
44143
+ storePrefix: config.store?.prefix,
44144
+ busPrefix: config.eventBus?.prefix,
44145
+ queueName: config.queue?.name,
44146
+ deadLetterQueueName: config.queue?.deadLetter
44147
+ });
44148
+ const queue = config.queue ? new RabbitMQQueue({
44149
+ url: config.queue.url,
44150
+ prefetch: config.queue.prefetch,
44151
+ queue: {
44152
+ name: isolation.queueName,
44153
+ quorum: config.queue.quorum,
44154
+ deadLetter: isolation.deadLetterQueueName,
44155
+ messageTtl: config.queue.messageTtl
44156
+ }
44157
+ }) : void 0;
44158
+ const worker = config.worker ?? Boolean(queue);
44159
+ const runtimeConfig = {
44160
+ ...config,
44161
+ worker,
44162
+ store: new RedisStore({
44163
+ redis: config.redis.url,
44164
+ prefix: isolation.storePrefix
44165
+ }),
44166
+ eventBus: new RedisEventBus({
44167
+ redis: config.redis.url,
44168
+ prefix: isolation.busPrefix
44169
+ }),
44170
+ queue
44171
+ };
44172
+ ctx.runtimeConfig = runtimeConfig;
44173
+ return await createRunnerDurableRuntime(runtimeConfig, {
44174
+ taskRunner,
44175
+ eventManager,
44176
+ runnerStore
44177
+ });
44178
+ }).dispose(async (durable, _config, _deps, ctx) => {
44179
+ if (!ctx.runtimeConfig) return;
44180
+ await disposeDurableService(durable.service, ctx.runtimeConfig);
44181
+ }).build();
44182
+
43467
44183
  // src/node/node.ts
43468
44184
  var globals2 = {
43469
44185
  ...globals,
@@ -43794,6 +44510,6 @@ serve-static/index.js:
43794
44510
  *)
43795
44511
  */
43796
44512
 
43797
- export { DependencyProcessor, DurableAuditEntryKind, DurableContext, DurableExecutionError, DurableOperator, DurableResource, DurableService, DurableWorker, errors_exports as Errors, EventManager, ExecutionStatus, Logger, MemoryEventBus, MemoryQueue, MemoryStore, MiddlewareManager, NoopEventBus, PlatformAdapter, Queue, RabbitMQQueue, RedisEventBus, RedisStore, ResourceInitializer, RunResult, ScheduleStatus, ScheduleType, Semaphore, Serializer, StepBuilder, Store, SuspensionSignal, TaskRunner, TimerStatus, TimerType, allFalse, defineAsyncContext as asyncContext, bindProcessErrorHandler, createContext2 as createContext, createDashboardMiddleware, createDefaultUnhandledError, createDurableAuditEntryId, createDurableRunnerAuditEmitter, createDurableStepId, createDurableTestSetup, createExposureFetch, createHttpClient, createHttpMixedClient, createHttpSmartClient, createNodeFile, createTestResource, debug, debugLevels, defs_exports as definitions, disposeDurableService, durableEvents, durableEventsArray, durableResource, defineEvent as event, getConfig, getDefaultSerializer, globals2 as globals, hasExposureContext, defineHook as hook, initDurableService, initDurableWorker, isDurableInternalStepId, journal, levelNormal, levelVerbose, nodeExposure, normalizeError, defineOverride as override, r, readInputFileToBuffer, defineResource as resource, defineResourceMiddleware as resourceMiddleware, run2 as run, safeReportUnhandledError, setPlatform, defineTag as tag, defineTask as task, defineTaskMiddleware as taskMiddleware, useExposureContext, waitUntil, writeInputFileToPath };
44513
+ export { DependencyProcessor, DurableAuditEntryKind, DurableContext, DurableExecutionError, DurableOperator, DurableResource, DurableService, DurableWorker, errors_exports as Errors, EventManager, ExecutionStatus, LogPrinter, Logger, MemoryEventBus, MemoryQueue, MemoryStore, MiddlewareManager, NodeInputFile, NoopEventBus, PlatformAdapter, Queue, RabbitMQQueue, RedisEventBus, RedisStore, ResourceInitializer, RunResult, ScheduleStatus, ScheduleType, Semaphore, Serializer, StepBuilder, Store, SuspensionSignal, SymbolPolicy, SymbolPolicyErrorMessage, TaskRunner, TimerStatus, TimerType, allFalse, defineAsyncContext as asyncContext, bindProcessErrorHandler, createContext2 as createContext, createDashboardMiddleware, createDefaultUnhandledError, createDurableAuditEntryId, createDurableRunnerAuditEmitter, createDurableStepId, createDurableTestSetup, createExposureFetch, createHttpClient, createHttpMixedClient, createHttpSmartClient, createNodeFile, createRunnerDurableRuntime, createTestResource, debug, debugLevels, defs_exports as definitions, disposeDurableService, durableEvents, durableEventsArray, durableResource, defineEvent as event, getConfig, globals2 as globals, hasExposureContext, defineHook as hook, initDurableService, initDurableWorker, isDurableInternalStepId, journal, levelNormal, levelVerbose, memoryDurableResource, nodeExposure, normalizeError, defineOverride as override, r, readInputFileToBuffer, redisDurableResource, defineResource as resource, defineResourceMiddleware as resourceMiddleware, run2 as run, safeReportUnhandledError, setPlatform, defineTag as tag, defineTask as task, defineTaskMiddleware as taskMiddleware, useExposureContext, waitUntil, writeInputFileToPath };
43798
44514
  //# sourceMappingURL=node.mjs.map
43799
44515
  //# sourceMappingURL=node.mjs.map