alchemy 2.0.0-beta.44 → 2.0.0-beta.45
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.
- package/bin/exec.js +67 -8
- package/bin/exec.js.map +1 -1
- package/lib/AWS/Lambda/Function.d.ts +17 -0
- package/lib/AWS/Lambda/Function.d.ts.map +1 -1
- package/lib/AWS/Lambda/Function.js +61 -16
- package/lib/AWS/Lambda/Function.js.map +1 -1
- package/lib/AWS/Providers.d.ts +2 -1
- package/lib/AWS/Providers.d.ts.map +1 -1
- package/lib/AWS/Providers.js +3 -1
- package/lib/AWS/Providers.js.map +1 -1
- package/lib/Apply.js +17 -1
- package/lib/Apply.js.map +1 -1
- package/lib/Auth/AuthProvider.d.ts.map +1 -1
- package/lib/Auth/AuthProvider.js +24 -6
- package/lib/Auth/AuthProvider.js.map +1 -1
- package/lib/Auth/Credentials.d.ts.map +1 -1
- package/lib/Auth/Credentials.js +3 -3
- package/lib/Auth/Credentials.js.map +1 -1
- package/lib/Cli/commands/_shared.d.ts +13 -1
- package/lib/Cli/commands/_shared.d.ts.map +1 -1
- package/lib/Cli/commands/_shared.js +33 -2
- package/lib/Cli/commands/_shared.js.map +1 -1
- package/lib/Cli/commands/dev.d.ts.map +1 -1
- package/lib/Cli/commands/dev.js +10 -1
- package/lib/Cli/commands/dev.js.map +1 -1
- package/lib/Cli/commands/login.d.ts.map +1 -1
- package/lib/Cli/commands/login.js +19 -5
- package/lib/Cli/commands/login.js.map +1 -1
- package/lib/Cli/commands/profile.d.ts.map +1 -1
- package/lib/Cli/commands/profile.js +7 -27
- package/lib/Cli/commands/profile.js.map +1 -1
- package/lib/Cli/main.d.ts.map +1 -1
- package/lib/Cli/main.js +0 -2
- package/lib/Cli/main.js.map +1 -1
- package/lib/Cloudflare/AiGateway/AiGateway.d.ts +0 -2
- package/lib/Cloudflare/AiGateway/AiGateway.d.ts.map +1 -1
- package/lib/Cloudflare/AiGateway/AiGateway.js +2 -4
- package/lib/Cloudflare/AiGateway/AiGateway.js.map +1 -1
- package/lib/Cloudflare/BrowserRendering/BrowserRendering.d.ts +116 -0
- package/lib/Cloudflare/BrowserRendering/BrowserRendering.d.ts.map +1 -0
- package/lib/Cloudflare/BrowserRendering/BrowserRendering.js +92 -0
- package/lib/Cloudflare/BrowserRendering/BrowserRendering.js.map +1 -0
- package/lib/Cloudflare/BrowserRendering/BrowserRenderingBinding.d.ts +55 -0
- package/lib/Cloudflare/BrowserRendering/BrowserRenderingBinding.d.ts.map +1 -0
- package/lib/Cloudflare/BrowserRendering/BrowserRenderingBinding.js +55 -0
- package/lib/Cloudflare/BrowserRendering/BrowserRenderingBinding.js.map +1 -0
- package/lib/Cloudflare/BrowserRendering/index.d.ts +3 -0
- package/lib/Cloudflare/BrowserRendering/index.d.ts.map +1 -0
- package/lib/Cloudflare/BrowserRendering/index.js +3 -0
- package/lib/Cloudflare/BrowserRendering/index.js.map +1 -0
- package/lib/Cloudflare/Container/Container.d.ts +3 -3
- package/lib/Cloudflare/Container/Container.js +3 -3
- package/lib/Cloudflare/Container/StartContainer.d.ts.map +1 -1
- package/lib/Cloudflare/Container/StartContainer.js.map +1 -1
- package/lib/Cloudflare/D1/D1Database.d.ts +1 -0
- package/lib/Cloudflare/D1/D1Database.d.ts.map +1 -1
- package/lib/Cloudflare/D1/D1Database.js +2 -1
- package/lib/Cloudflare/D1/D1Database.js.map +1 -1
- package/lib/Cloudflare/D1/D1DatabaseBinding.js +1 -1
- package/lib/Cloudflare/D1/D1DatabaseBinding.js.map +1 -1
- package/lib/Cloudflare/Fetcher.d.ts.map +1 -1
- package/lib/Cloudflare/Fetcher.js +0 -2
- package/lib/Cloudflare/Fetcher.js.map +1 -1
- package/lib/Cloudflare/Hyperdrive/Hyperdrive.d.ts +1 -0
- package/lib/Cloudflare/Hyperdrive/Hyperdrive.d.ts.map +1 -1
- package/lib/Cloudflare/Hyperdrive/Hyperdrive.js +3 -0
- package/lib/Cloudflare/Hyperdrive/Hyperdrive.js.map +1 -1
- package/lib/Cloudflare/Hyperdrive/HyperdriveBinding.d.ts +3 -2
- package/lib/Cloudflare/Hyperdrive/HyperdriveBinding.d.ts.map +1 -1
- package/lib/Cloudflare/Hyperdrive/HyperdriveBinding.js +32 -33
- package/lib/Cloudflare/Hyperdrive/HyperdriveBinding.js.map +1 -1
- package/lib/Cloudflare/KV/KVNamespace.d.ts +1 -0
- package/lib/Cloudflare/KV/KVNamespace.d.ts.map +1 -1
- package/lib/Cloudflare/KV/KVNamespace.js +2 -0
- package/lib/Cloudflare/KV/KVNamespace.js.map +1 -1
- package/lib/Cloudflare/Local.js +1 -1
- package/lib/Cloudflare/Local.js.map +1 -1
- package/lib/Cloudflare/Providers.d.ts +2 -1
- package/lib/Cloudflare/Providers.d.ts.map +1 -1
- package/lib/Cloudflare/Providers.js +21 -17
- package/lib/Cloudflare/Providers.js.map +1 -1
- package/lib/Cloudflare/Queue/Queue.d.ts +1 -0
- package/lib/Cloudflare/Queue/Queue.d.ts.map +1 -1
- package/lib/Cloudflare/Queue/Queue.js +1 -0
- package/lib/Cloudflare/Queue/Queue.js.map +1 -1
- package/lib/Cloudflare/Queue/QueueConsumer.d.ts +2 -1
- package/lib/Cloudflare/Queue/QueueConsumer.d.ts.map +1 -1
- package/lib/Cloudflare/Queue/QueueConsumer.js +11 -3
- package/lib/Cloudflare/Queue/QueueConsumer.js.map +1 -1
- package/lib/Cloudflare/Queue/QueueEventSource.d.ts +30 -4
- package/lib/Cloudflare/Queue/QueueEventSource.d.ts.map +1 -1
- package/lib/Cloudflare/Queue/QueueEventSource.js +22 -1
- package/lib/Cloudflare/Queue/QueueEventSource.js.map +1 -1
- package/lib/Cloudflare/R2/R2Bucket.d.ts +1 -0
- package/lib/Cloudflare/R2/R2Bucket.d.ts.map +1 -1
- package/lib/Cloudflare/R2/R2Bucket.js +18 -0
- package/lib/Cloudflare/R2/R2Bucket.js.map +1 -1
- package/lib/Cloudflare/SecretsStore/Secret.d.ts.map +1 -1
- package/lib/Cloudflare/SecretsStore/Secret.js +13 -34
- package/lib/Cloudflare/SecretsStore/Secret.js.map +1 -1
- package/lib/Cloudflare/SecretsStore/SecretBinding.d.ts +3 -2
- package/lib/Cloudflare/SecretsStore/SecretBinding.d.ts.map +1 -1
- package/lib/Cloudflare/SecretsStore/SecretBinding.js +3 -2
- package/lib/Cloudflare/SecretsStore/SecretBinding.js.map +1 -1
- package/lib/Cloudflare/StateStore/Api.d.ts +5 -13
- package/lib/Cloudflare/StateStore/Api.d.ts.map +1 -1
- package/lib/Cloudflare/StateStore/Api.js +14 -8
- package/lib/Cloudflare/StateStore/Api.js.map +1 -1
- package/lib/Cloudflare/StateStore/State.d.ts.map +1 -1
- package/lib/Cloudflare/StateStore/State.js +45 -9
- package/lib/Cloudflare/StateStore/State.js.map +1 -1
- package/lib/Cloudflare/StateStore/Store.d.ts.map +1 -1
- package/lib/Cloudflare/StateStore/Store.js +5 -2
- package/lib/Cloudflare/StateStore/Store.js.map +1 -1
- package/lib/Cloudflare/VpcService/VpcService.d.ts +2 -2
- package/lib/Cloudflare/VpcService/VpcService.d.ts.map +1 -1
- package/lib/Cloudflare/Website/StaticSite.d.ts +5 -5
- package/lib/Cloudflare/Website/StaticSite.d.ts.map +1 -1
- package/lib/Cloudflare/Website/StaticSite.js +3 -0
- package/lib/Cloudflare/Website/StaticSite.js.map +1 -1
- package/lib/Cloudflare/Website/Vite.d.ts +5 -5
- package/lib/Cloudflare/Website/Vite.d.ts.map +1 -1
- package/lib/Cloudflare/Website/Vite.js.map +1 -1
- package/lib/Cloudflare/Workers/Assets.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/Assets.js +1 -1
- package/lib/Cloudflare/Workers/Assets.js.map +1 -1
- package/lib/Cloudflare/Workers/DurableObjectBridge.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/DurableObjectBridge.js +4 -2
- package/lib/Cloudflare/Workers/DurableObjectBridge.js.map +1 -1
- package/lib/Cloudflare/Workers/DurableObjectNamespace.d.ts +183 -6
- package/lib/Cloudflare/Workers/DurableObjectNamespace.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/DurableObjectNamespace.js +279 -76
- package/lib/Cloudflare/Workers/DurableObjectNamespace.js.map +1 -1
- package/lib/Cloudflare/Workers/HttpServer.d.ts +6 -4
- package/lib/Cloudflare/Workers/HttpServer.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/HttpServer.js +20 -15
- package/lib/Cloudflare/Workers/HttpServer.js.map +1 -1
- package/lib/Cloudflare/Workers/InferEnv.d.ts +3 -2
- package/lib/Cloudflare/Workers/InferEnv.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/LocalWorkerProvider.d.ts +4 -7
- package/lib/Cloudflare/Workers/LocalWorkerProvider.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/LocalWorkerProvider.js +111 -66
- package/lib/Cloudflare/Workers/LocalWorkerProvider.js.map +1 -1
- package/lib/Cloudflare/Workers/Rpc.d.ts +16 -0
- package/lib/Cloudflare/Workers/Rpc.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/Rpc.js +22 -0
- package/lib/Cloudflare/Workers/Rpc.js.map +1 -1
- package/lib/Cloudflare/Workers/RpcDurableObjectNamespace.d.ts +285 -0
- package/lib/Cloudflare/Workers/RpcDurableObjectNamespace.d.ts.map +1 -0
- package/lib/Cloudflare/Workers/RpcDurableObjectNamespace.js +288 -0
- package/lib/Cloudflare/Workers/RpcDurableObjectNamespace.js.map +1 -0
- package/lib/Cloudflare/Workers/RpcWorker.d.ts +305 -0
- package/lib/Cloudflare/Workers/RpcWorker.d.ts.map +1 -0
- package/lib/Cloudflare/Workers/RpcWorker.js +350 -0
- package/lib/Cloudflare/Workers/RpcWorker.js.map +1 -0
- package/lib/Cloudflare/Workers/Vite.d.ts +1 -1
- package/lib/Cloudflare/Workers/Vite.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/Vite.js +2 -1
- package/lib/Cloudflare/Workers/Vite.js.map +1 -1
- package/lib/Cloudflare/Workers/Worker.d.ts +69 -24
- package/lib/Cloudflare/Workers/Worker.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/Worker.js +168 -47
- package/lib/Cloudflare/Workers/Worker.js.map +1 -1
- package/lib/Cloudflare/Workers/WorkerAsyncBindings.d.ts +1 -1
- package/lib/Cloudflare/Workers/WorkerAsyncBindings.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/WorkerAsyncBindings.js +158 -97
- package/lib/Cloudflare/Workers/WorkerAsyncBindings.js.map +1 -1
- package/lib/Cloudflare/Workers/WorkerBinding.d.ts +11 -23
- package/lib/Cloudflare/Workers/WorkerBinding.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/WorkerBinding.js +3 -0
- package/lib/Cloudflare/Workers/WorkerBinding.js.map +1 -1
- package/lib/Cloudflare/Workers/WorkerBridge.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/WorkerBridge.js +5 -2
- package/lib/Cloudflare/Workers/WorkerBridge.js.map +1 -1
- package/lib/Cloudflare/Workers/WorkerBundle.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/WorkerBundle.js +4 -1
- package/lib/Cloudflare/Workers/WorkerBundle.js.map +1 -1
- package/lib/Cloudflare/Workers/WorkerRuntimeContext.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/WorkerRuntimeContext.js +9 -10
- package/lib/Cloudflare/Workers/WorkerRuntimeContext.js.map +1 -1
- package/lib/Cloudflare/Workers/Workflow.d.ts +5 -3
- package/lib/Cloudflare/Workers/Workflow.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/Workflow.js +19 -1
- package/lib/Cloudflare/Workers/Workflow.js.map +1 -1
- package/lib/Cloudflare/Workers/index.d.ts +2 -0
- package/lib/Cloudflare/Workers/index.d.ts.map +1 -1
- package/lib/Cloudflare/Workers/index.js +2 -0
- package/lib/Cloudflare/Workers/index.js.map +1 -1
- package/lib/Cloudflare/index.d.ts +1 -0
- package/lib/Cloudflare/index.d.ts.map +1 -1
- package/lib/Cloudflare/index.js +1 -0
- package/lib/Cloudflare/index.js.map +1 -1
- package/lib/Dependencies.d.ts +10 -0
- package/lib/Dependencies.d.ts.map +1 -0
- package/lib/Dependencies.js +1 -0
- package/lib/Dependencies.js.map +1 -0
- package/lib/Deploy.d.ts +2 -1
- package/lib/Deploy.d.ts.map +1 -1
- package/lib/Deploy.js +2 -2
- package/lib/Deploy.js.map +1 -1
- package/lib/Diff.d.ts +11 -0
- package/lib/Diff.d.ts.map +1 -1
- package/lib/Diff.js +11 -0
- package/lib/Diff.js.map +1 -1
- package/lib/Input.d.ts +2 -1
- package/lib/Input.d.ts.map +1 -1
- package/lib/KeyPair.d.ts +77 -0
- package/lib/KeyPair.d.ts.map +1 -0
- package/lib/KeyPair.js +102 -0
- package/lib/KeyPair.js.map +1 -0
- package/lib/Local/RpcProvider.d.ts +3 -1
- package/lib/Local/RpcProvider.d.ts.map +1 -1
- package/lib/Local/RpcProvider.js +28 -2
- package/lib/Local/RpcProvider.js.map +1 -1
- package/lib/Local/RpcServerEnvironment.js +1 -1
- package/lib/Local/RpcServerEnvironment.js.map +1 -1
- package/lib/Neon/Project.d.ts.map +1 -1
- package/lib/Neon/Project.js +14 -3
- package/lib/Neon/Project.js.map +1 -1
- package/lib/Output.d.ts.map +1 -1
- package/lib/Output.js +9 -2
- package/lib/Output.js.map +1 -1
- package/lib/Phase.d.ts +2 -1
- package/lib/Phase.d.ts.map +1 -1
- package/lib/Phase.js +6 -1
- package/lib/Phase.js.map +1 -1
- package/lib/Plan.d.ts.map +1 -1
- package/lib/Plan.js +14 -3
- package/lib/Plan.js.map +1 -1
- package/lib/Platform.d.ts +8 -6
- package/lib/Platform.d.ts.map +1 -1
- package/lib/Platform.js +33 -3
- package/lib/Platform.js.map +1 -1
- package/lib/Random.d.ts.map +1 -1
- package/lib/Random.js +9 -14
- package/lib/Random.js.map +1 -1
- package/lib/RuntimeContext.d.ts +21 -1
- package/lib/RuntimeContext.d.ts.map +1 -1
- package/lib/RuntimeContext.js +12 -0
- package/lib/RuntimeContext.js.map +1 -1
- package/lib/Stack.d.ts +3 -3
- package/lib/Stack.d.ts.map +1 -1
- package/lib/Stack.js.map +1 -1
- package/lib/State/HttpStateApi.d.ts +2 -2
- package/lib/State/StateEncoding.d.ts +8 -0
- package/lib/State/StateEncoding.d.ts.map +1 -1
- package/lib/State/StateEncoding.js +55 -5
- package/lib/State/StateEncoding.js.map +1 -1
- package/lib/Test/Bun.d.ts.map +1 -1
- package/lib/Test/Bun.js +0 -2
- package/lib/Test/Bun.js.map +1 -1
- package/lib/Test/Vitest.d.ts.map +1 -1
- package/lib/Test/Vitest.js +0 -2
- package/lib/Test/Vitest.js.map +1 -1
- package/lib/Util/Duration.d.ts +14 -0
- package/lib/Util/Duration.d.ts.map +1 -0
- package/lib/Util/Duration.js +18 -0
- package/lib/Util/Duration.js.map +1 -0
- package/lib/Util/index.d.ts +0 -6
- package/lib/Util/index.d.ts.map +1 -1
- package/lib/Util/index.js +0 -6
- package/lib/Util/index.js.map +1 -1
- package/lib/Util/types.d.ts +3 -1
- package/lib/Util/types.d.ts.map +1 -1
- package/lib/Util/types.js +5 -1
- package/lib/Util/types.js.map +1 -1
- package/lib/index.d.ts +2 -3
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +1 -3
- package/lib/index.js.map +1 -1
- package/lib/tsconfig.test.tsbuildinfo +1 -1
- package/package.json +20 -19
- package/src/AWS/Lambda/Function.ts +87 -34
- package/src/AWS/Providers.ts +3 -0
- package/src/Apply.ts +18 -1
- package/src/Auth/AuthProvider.ts +25 -5
- package/src/Auth/Credentials.ts +8 -7
- package/src/Cli/commands/_shared.ts +47 -4
- package/src/Cli/commands/dev.ts +13 -1
- package/src/Cli/commands/login.ts +20 -4
- package/src/Cli/commands/profile.ts +24 -34
- package/src/Cli/main.ts +0 -3
- package/src/Cloudflare/AiGateway/AiGateway.ts +2 -6
- package/src/Cloudflare/BrowserRendering/BrowserRendering.ts +132 -0
- package/src/Cloudflare/BrowserRendering/BrowserRenderingBinding.ts +137 -0
- package/src/Cloudflare/BrowserRendering/index.ts +11 -0
- package/src/Cloudflare/Container/Container.ts +3 -3
- package/src/Cloudflare/Container/StartContainer.ts +1 -2
- package/src/Cloudflare/D1/D1Database.ts +4 -1
- package/src/Cloudflare/D1/D1DatabaseBinding.ts +1 -1
- package/src/Cloudflare/Fetcher.ts +0 -2
- package/src/Cloudflare/Hyperdrive/Hyperdrive.ts +5 -0
- package/src/Cloudflare/Hyperdrive/HyperdriveBinding.ts +41 -43
- package/src/Cloudflare/KV/KVNamespace.ts +4 -0
- package/src/Cloudflare/Local.ts +1 -1
- package/src/Cloudflare/Providers.ts +25 -16
- package/src/Cloudflare/Queue/Queue.ts +3 -0
- package/src/Cloudflare/Queue/QueueConsumer.ts +23 -8
- package/src/Cloudflare/Queue/QueueEventSource.ts +33 -5
- package/src/Cloudflare/R2/R2Bucket.ts +26 -0
- package/src/Cloudflare/SecretsStore/Secret.ts +14 -41
- package/src/Cloudflare/SecretsStore/SecretBinding.ts +11 -11
- package/src/Cloudflare/StateStore/Api.ts +15 -15
- package/src/Cloudflare/StateStore/State.ts +68 -6
- package/src/Cloudflare/StateStore/Store.ts +5 -2
- package/src/Cloudflare/VpcService/VpcService.ts +2 -2
- package/src/Cloudflare/Website/StaticSite.ts +8 -10
- package/src/Cloudflare/Website/Vite.ts +4 -7
- package/src/Cloudflare/Workers/Assets.ts +1 -1
- package/src/Cloudflare/Workers/DurableObjectBridge.ts +7 -4
- package/src/Cloudflare/Workers/DurableObjectNamespace.ts +380 -121
- package/src/Cloudflare/Workers/HttpServer.ts +31 -25
- package/src/Cloudflare/Workers/InferEnv.ts +15 -8
- package/src/Cloudflare/Workers/LocalWorkerProvider.ts +139 -78
- package/src/Cloudflare/Workers/Rpc.ts +50 -0
- package/src/Cloudflare/Workers/RpcDurableObjectNamespace.ts +502 -0
- package/src/Cloudflare/Workers/RpcWorker.ts +562 -0
- package/src/Cloudflare/Workers/Vite.ts +2 -0
- package/src/Cloudflare/Workers/Worker.ts +274 -93
- package/src/Cloudflare/Workers/WorkerAsyncBindings.ts +158 -103
- package/src/Cloudflare/Workers/WorkerBinding.ts +10 -0
- package/src/Cloudflare/Workers/WorkerBridge.ts +7 -4
- package/src/Cloudflare/Workers/WorkerBundle.ts +4 -1
- package/src/Cloudflare/Workers/WorkerRuntimeContext.ts +8 -15
- package/src/Cloudflare/Workers/Workflow.ts +22 -3
- package/src/Cloudflare/Workers/index.ts +2 -0
- package/src/Cloudflare/index.ts +1 -0
- package/src/Dependencies.ts +10 -0
- package/src/Deploy.ts +3 -1
- package/src/Diff.ts +13 -0
- package/src/Input.ts +2 -0
- package/src/KeyPair.ts +146 -0
- package/src/Local/RpcProvider.ts +45 -1
- package/src/Local/RpcServerEnvironment.ts +1 -1
- package/src/Neon/Project.ts +16 -3
- package/src/Output.ts +8 -2
- package/src/Phase.ts +8 -0
- package/src/Plan.ts +16 -3
- package/src/Platform.ts +74 -27
- package/src/Random.ts +22 -27
- package/src/RuntimeContext.ts +23 -1
- package/src/Stack.ts +3 -3
- package/src/State/StateEncoding.ts +58 -7
- package/src/Test/Bun.ts +0 -3
- package/src/Test/Vitest.ts +0 -3
- package/src/Util/Duration.ts +21 -0
- package/src/Util/index.ts +0 -6
- package/src/Util/types.ts +9 -2
- package/src/index.ts +2 -3
- package/lib/Secret.d.ts +0 -50
- package/lib/Secret.d.ts.map +0 -1
- package/lib/Secret.js +0 -23
- package/lib/Secret.js.map +0 -1
- package/lib/Trait.d.ts +0 -43
- package/lib/Trait.d.ts.map +0 -1
- package/lib/Trait.js +0 -17
- package/lib/Trait.js.map +0 -1
- package/lib/Util/LocalhostDns.d.ts +0 -23
- package/lib/Util/LocalhostDns.d.ts.map +0 -1
- package/lib/Util/LocalhostDns.js +0 -46
- package/lib/Util/LocalhostDns.js.map +0 -1
- package/lib/Util/assert-never.d.ts +0 -12
- package/lib/Util/assert-never.d.ts.map +0 -1
- package/lib/Util/assert-never.js +0 -11
- package/lib/Util/assert-never.js.map +0 -1
- package/lib/Util/class.d.ts +0 -3
- package/lib/Util/class.d.ts.map +0 -1
- package/lib/Util/class.js +0 -1
- package/lib/Util/class.js.map +0 -1
- package/lib/Util/ignore.d.ts +0 -40
- package/lib/Util/ignore.d.ts.map +0 -1
- package/lib/Util/ignore.js +0 -591
- package/lib/Util/ignore.js.map +0 -1
- package/lib/Util/instance.d.ts +0 -4
- package/lib/Util/instance.d.ts.map +0 -1
- package/lib/Util/instance.js +0 -1
- package/lib/Util/instance.js.map +0 -1
- package/lib/Util/pointer.d.ts +0 -5
- package/lib/Util/pointer.d.ts.map +0 -1
- package/lib/Util/pointer.js +0 -1
- package/lib/Util/pointer.js.map +0 -1
- package/lib/Util/schema-to-type.d.ts +0 -42
- package/lib/Util/schema-to-type.d.ts.map +0 -1
- package/lib/Util/schema-to-type.js +0 -364
- package/lib/Util/schema-to-type.js.map +0 -1
- package/lib/Util/todo.d.ts +0 -3
- package/lib/Util/todo.d.ts.map +0 -1
- package/lib/Util/todo.js +0 -3
- package/lib/Util/todo.js.map +0 -1
- package/lib/Variable.d.ts +0 -29
- package/lib/Variable.d.ts.map +0 -1
- package/lib/Variable.js +0 -9
- package/lib/Variable.js.map +0 -1
- package/src/Secret.ts +0 -87
- package/src/Trait.ts +0 -105
- package/src/Util/LocalhostDns.ts +0 -52
- package/src/Util/assert-never.ts +0 -18
- package/src/Util/class.ts +0 -7
- package/src/Util/ignore.ts +0 -815
- package/src/Util/instance.ts +0 -9
- package/src/Util/pointer.ts +0 -5
- package/src/Util/schema-to-type.ts +0 -456
- package/src/Util/todo.ts +0 -4
- package/src/Variable.ts +0 -44
package/bin/exec.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"exec.js","names":["Path","Context","profile","path","profile","Context","Context","Context","Context","path","Context","Context","Context","Context","stage","proxy","target","upstream","State.State","value","envFile","tag","path","Context","Output.stackRef","stackName","options","eff","make","services","Output.isOutput","Context","make","Context","Output.isExpr","Output.hasOutputs","Context","stage","c","Output.ResourceExpr","Output.isExpr","Output.of","value","Output.isResourceExpr","Output.isPropExpr","Output.isApplyExpr","upstream","Output.hasOutputs","Output.isEffectExpr","Output.isAllExpr","Output.isLiteralExpr","Output.isRefExpr","Output.InvalidReferenceError","Output.isStackRefExpr","Output.isNamedExpr","Output.upstreamAny","diff","stage","Output.evaluate","Output.resolveUpstream","node","path","S","stage","Path","services","adopt","envFile","profile","stage","CLI.Cli","Plan.make","dryRun","yes","dryRunFlag","actionColor","statusColor","path","_jsx","_jsxs","_jsxs","_jsx","_jsx","_jsxs","color","icon","_jsx","PlanComponent","RpcProviderProxy.fromEnv"],"sources":["../lib/AlchemyContext.js","../lib/Auth/Profile.js","../lib/Auth/Credentials.js","../lib/Artifacts.js","../lib/Auth/AuthProvider.js","../lib/Cli/Cli.js","../lib/Ref.js","../lib/FQN.js","../lib/Provider.js","../lib/Resource.js","../lib/RuntimeContext.js","../lib/Stage.js","../lib/State/State.js","../lib/Util/data.js","../lib/Output.js","../lib/Util/ConfigProvider.js","../lib/Util/effect.js","../lib/Util/FileLogger.js","../lib/Util/PlatformServices.js","../lib/Stack.js","../lib/Local/RpcSerialization.js","../lib/Local/RpcProviderProxy.js","../lib/AdoptPolicy.js","../lib/Diff.js","../lib/InstanceId.js","../lib/Util/types.js","../lib/Telemetry/Metrics.js","../lib/Action.js","../lib/Util/hash.js","../lib/Util/scc.js","../lib/Plan.js","../lib/Apply.js","../lib/Cli/commands/_shared.js","../lib/Cli/commands/deploy.js","../lib/Cli/LoggingCli.js","../lib/Cli/NamespaceTree.js","../lib/Cli/tui/components/Plan.js","../lib/Cli/tui/components/ApprovePlan.js","../lib/Cli/tui/components/PlanProgress.js","../lib/Cli/tui/InkCLI.js","../lib/Cli/selectCli.js","../lib/Cli/exec.js","exec.ts"],"sourcesContent":["import * as EffectContext from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nexport class AlchemyContext extends EffectContext.Service()(\"alchemy/Context\") {\n}\nexport const AlchemyContextLive = Layer.effect(AlchemyContext, Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const dir = path.join(process.cwd(), \".alchemy\");\n yield* fs.makeDirectory(dir, { recursive: true });\n return {\n dotAlchemy: dir,\n updateStateStore: false,\n dev: false,\n adopt: false,\n };\n}));\n//# sourceMappingURL=AlchemyContext.js.map","import * as Config from \"effect/Config\";\nimport * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport os from \"node:os\";\nimport path from \"pathe\";\nexport const rootDir = path.join(os.homedir(), \".alchemy\");\nexport const configFilePath = path.join(rootDir, \"profiles.json\");\n/**\n * Config key consulted by the various `fromAuthProvider` /\n * `fromEnvironment` layers to pick which named profile in\n * `~/.alchemy/profiles.json` to use. Defaults to `\"default\"`.\n */\nexport const ALCHEMY_PROFILE = Config.string(\"ALCHEMY_PROFILE\").pipe(Config.withDefault(\"default\"));\nexport const CONFIG_VERSION = 0;\nexport class AlchemyConfig extends Context.Service()(\"Alchemy::Profiles\") {\n}\nconst emptyConfig = () => ({\n version: CONFIG_VERSION,\n profiles: {},\n});\nexport class Profile extends Context.Service()(\"Alchemy::Profile\") {\n}\n/**\n * Layer that builds the {@link Profile} service. Captures the\n * {@link FileSystem.FileSystem} dependency at layer-build time, so any\n * Effect that yields {@link Profile} ends up with `R = Profile` (no\n * `FileSystem` leak). Provide this once at the top of your runtime\n * (alongside `PlatformServices` / `NodeContext`).\n */\nexport const ProfileLive = Layer.effect(Profile, Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const readConfig = fs\n .readFileString(configFilePath)\n .pipe(Effect.flatMap((data) => Effect.try({\n try: () => {\n const parsed = JSON.parse(data);\n if (parsed?.version !== CONFIG_VERSION) {\n // TODO(sam): this is destructive, should we maintain a chain of migrations from 0 to current?\n return emptyConfig();\n }\n return parsed;\n },\n catch: emptyConfig,\n })), Effect.orElseSucceed(emptyConfig));\n const writeConfig = (config) => fs\n .makeDirectory(path.dirname(configFilePath), { recursive: true })\n .pipe(Effect.flatMap(() => fs.writeFileString(configFilePath, JSON.stringify(config, null, 2))));\n const getProfile = (name) => readConfig.pipe(Effect.map((config) => config.profiles[name]));\n const setProfile = (name, profile) => readConfig.pipe(Effect.tap((config) => Effect.sync(() => (config.profiles[name] = profile))), Effect.flatMap(writeConfig));\n const deleteProfile = (name) => readConfig.pipe(Effect.flatMap((config) => {\n if (!(name in config.profiles)) {\n return Effect.succeed(false);\n }\n delete config.profiles[name];\n return writeConfig(config).pipe(Effect.as(true));\n }));\n const loadOrConfigure = (auth, profileName, ctx) => Effect.flatMap(getProfile(profileName), (existing) => existing?.[auth.name]\n ? Effect.succeed(existing[auth.name])\n : Effect.tap(auth.configure(profileName, ctx), (config) => setProfile(profileName, { ...existing, [auth.name]: config })));\n return {\n readConfig,\n writeConfig,\n getProfile,\n setProfile,\n deleteProfile,\n loadOrConfigure,\n };\n}));\n/**\n * Returns a `ConfigProvider` that overrides `ALCHEMY_PROFILE` with the\n * given `profile` (when explicitly passed via the CLI `--profile` flag),\n * falling through to `base` for everything else.\n *\n * Use this to let the CLI's `--profile <name>` win over `$ALCHEMY_PROFILE`\n * without disturbing other config lookups.\n */\nexport const withProfileOverride = (base, profile) => {\n if (profile === undefined)\n return base;\n const overrides = { ALCHEMY_PROFILE: profile };\n const overrideProvider = ConfigProvider.make((path) => Effect.succeed(path.length === 1 && typeof path[0] === \"string\" && path[0] in overrides\n ? ConfigProvider.makeValue(overrides[path[0]])\n : undefined));\n return ConfigProvider.orElse(base)(overrideProvider);\n};\n//# sourceMappingURL=Profile.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\nimport path from \"pathe\";\nimport { rootDir } from \"./Profile.js\";\nconst credentialsDirPath = path.join(rootDir, \"credentials\");\nexport const profileCredentialsDirPath = (profile) => path.join(credentialsDirPath, profile);\nexport const credentialsFilePath = (profile, provider) => path.join(profileCredentialsDirPath(profile), `${provider}.json`);\nexport class CredentialsStore extends Context.Service()(\"Alchemy::CredentialsStore\") {\n}\nexport const CredentialsStoreLive = Layer.effect(CredentialsStore, Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const read = (profile, provider) => fs.readFileString(credentialsFilePath(profile, provider)).pipe(Effect.catch(() => Effect.succeed(undefined)), Effect.map((data) => {\n if (data === undefined)\n return undefined;\n try {\n return JSON.parse(data);\n }\n catch {\n return undefined;\n }\n }));\n const write = (profile, provider, credentials) => {\n const filePath = credentialsFilePath(profile, provider);\n return fs\n .makeDirectory(path.dirname(filePath), { recursive: true })\n .pipe(Effect.flatMap(() => fs.writeFileString(filePath, JSON.stringify(credentials, null, 2))));\n };\n const remove_ = (profile, provider) => fs\n .remove(credentialsFilePath(profile, provider))\n .pipe(Effect.catch(() => Effect.void));\n const deleteProfile = (profile) => fs\n .remove(profileCredentialsDirPath(profile), { recursive: true })\n .pipe(Effect.catch(() => Effect.void));\n return {\n read,\n write,\n delete: remove_,\n deleteProfile,\n };\n}));\nexport function displayRedacted(r, visibleChars = 4) {\n const raw = Redacted.value(r);\n if (raw.length <= visibleChars)\n return \"****\";\n return `${raw.slice(0, visibleChars)}****`;\n}\n//# sourceMappingURL=Credentials.js.map","import * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\n/**\n * Per-resource in-memory artifacts shared across a single `Plan.make -> apply`\n * execution.\n *\n * The engine scopes this service by resource `FQN` before invoking lifecycle\n * handlers, so providers should treat it as a resource-local bag for expensive,\n * deterministic intermediate results that can be reused across phases.\n *\n * Expected usage:\n *\n * - `diff` computes an expensive artifact once and stores it\n * - `create` / `update` reads the same artifact and skips recomputing it\n * - artifacts are ephemeral and must never be required for correctness on a\n * later deploy because the bag is reset between runs\n *\n * Example:\n *\n * ```ts\n * const artifacts = yield* Artifacts;\n * const cached = yield* artifacts.get<PreparedBundle>(\"bundle\");\n * if (cached) return cached;\n *\n * const bundle = yield* prepareBundle();\n * yield* artifacts.set(\"bundle\", bundle);\n * return bundle;\n * ```\n */\nexport class Artifacts extends Context.Service()(\"Artifacts\") {\n}\nexport class ArtifactStore extends Context.Service()(\"Artifacts/Store\") {\n}\n/**\n * Create a fresh root store for one deploy/test run.\n */\nexport const createArtifactStore = () => new Map();\nconst getOrCreateBag = (store, fqn) => {\n const existing = store.get(fqn);\n if (existing) {\n return existing;\n }\n const bag = new Map();\n store.set(fqn, bag);\n return bag;\n};\nexport const makeScopedArtifacts = (store, fqn) => {\n const bag = getOrCreateBag(store, fqn);\n return {\n get: (key) => Effect.sync(() => bag.get(key)),\n set: (key, value) => Effect.sync(() => {\n bag.set(key, value);\n }),\n delete: (key) => Effect.sync(() => {\n bag.delete(key);\n }),\n };\n};\nexport const scopedArtifacts = (fqn) => Layer.effect(Artifacts, ArtifactStore.useSync((store) => makeScopedArtifacts(store, fqn)));\n/**\n * Run an effect with a fresh artifact root, replacing any existing store.\n * Use this at top-level entrypoints that intentionally define a new deploy run.\n */\nexport const provideFreshArtifactStore = (effect) => effect.pipe(Effect.provideServiceEffect(ArtifactStore, Effect.sync(createArtifactStore)));\n/**\n * Ensure an artifact root exists, reusing the ambient store when one is already\n * present. This lets nested helpers participate in the same run-scoped cache.\n */\nexport const ensureArtifactStore = (effect) => Effect.serviceOption(ArtifactStore).pipe(Effect.map(Option.getOrUndefined), Effect.flatMap((existing) => effect.pipe(Effect.provideService(ArtifactStore, existing ?? createArtifactStore()))));\nexport const cached = (id) => (eff) => Effect.gen(function* () {\n const artifacts = yield* Artifacts;\n const deferred = yield* Deferred.make();\n const cached = yield* artifacts.get(id);\n if (cached) {\n if (Effect.isEffect(cached)) {\n return yield* cached;\n }\n return cached;\n }\n yield* artifacts.set(id, Deferred.await(deferred));\n const result = yield* eff;\n yield* Deferred.succeed(deferred, result);\n yield* artifacts.set(id, result);\n return result;\n});\n//# sourceMappingURL=Artifacts.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport { withLock } from \"./Lock.js\";\n/**\n * Methods on an {@link AuthProviderImpl} that mutate (or could trigger\n * mutation of) on-disk credentials. The factory wraps these in a\n * cross-process file lock keyed by `(profileName, providerName)` so that\n * concurrent processes never refresh / write credentials simultaneously.\n *\n * `prettyPrint` is intentionally excluded: it's read-only display.\n */\nconst LOCKED_METHODS = new Set([\"read\", \"login\", \"logout\", \"configure\"]);\nexport class AuthError extends Schema.TaggedErrorClass()(\"AuthError\", {\n message: Schema.String,\n cause: Schema.optional(Schema.Defect),\n}) {\n}\nexport class AuthProviders extends Context.Service()(\"AuthProviders\") {\n}\nexport const AuthProvider = () => (name, impl) => Effect.gen(function* () {\n const ctx = yield* Effect.context();\n const providers = yield* AuthProviders;\n const service = yield* Effect.isEffect(impl)\n ? impl\n : Effect.succeed(impl);\n return yield* Effect.sync(() => (providers[name] = {\n kind: \"AuthProvider\",\n name,\n ...Object.fromEntries(Object.entries(service).map(([methodName, fn]) => [\n methodName,\n (...args) => {\n const eff = fn(...args).pipe(Effect.provideContext(ctx));\n if (!LOCKED_METHODS.has(methodName))\n return eff;\n // First positional arg is always `profileName`.\n const profileName = args[0];\n return withLock(`${profileName}-${name}`, eff);\n },\n ])),\n }));\n});\n/**\n * Build a Layer that registers an AuthProvider into the {@link AuthProviders}\n * registry when its parent layer is built. Use this from a provider's\n * top-level `providers()` Layer so that `alchemy login` can discover the\n * provider via the registry without forcing credential resolution.\n */\nexport const AuthProviderLayer = () => (name, impl) => Layer.effectDiscard(AuthProvider()(name, impl));\n/**\n * Look up a registered {@link AuthProvider} by name. Fails with\n * {@link AuthError} if the provider hasn't been registered (typically because\n * its layer hasn't been built).\n */\nexport const getAuthProvider = (name) => AuthProviders.use((registry) => registry[name] == null\n ? Effect.fail(new AuthError({\n message: `AuthProvider '${name}' is not registered. Make sure its layer has been provided.`,\n }))\n : Effect.succeed(registry[name]));\n//# sourceMappingURL=AuthProvider.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nexport class Cli extends Context.Service()(\"CLI\") {\n}\n//# sourceMappingURL=Cli.js.map","import * as Output from \"./Output.js\";\n// special runtime-only symbol for probing the Ref proxy for its metadata\nconst RefMetadata = Symbol.for(\"alchemy/RefMetadata\");\nexport const isRef = (s) => s && s[RefMetadata] !== undefined;\nexport const getRefMetadata = (ref) => ref[RefMetadata];\nexport const ref = (id, { stack, stage, } = {}) => {\n const ref = new Proxy({}, {\n get: (_, prop) => {\n if (prop === RefMetadata) {\n return {\n stack,\n stage,\n id,\n };\n }\n return Output.of(ref)[prop];\n },\n });\n return ref;\n};\n//# sourceMappingURL=Ref.js.map","/**\n * Separator used in FQN strings.\n */\nexport const FQN_SEPARATOR = \"/\";\n/**\n * Encode an FQN for safe filesystem storage.\n * Replaces `/` (FQN separator) with `__` to avoid subdirectory creation.\n */\nexport const encodeFqn = (fqn) => fqn.replaceAll(FQN_SEPARATOR, \"__\");\n/**\n * Decode a filename back to FQN.\n */\nexport const decodeFqn = (filename) => filename.replaceAll(\"__\", FQN_SEPARATOR);\n/**\n * Convert a NamespaceNode chain to an array of namespace IDs, from root to leaf.\n *\n * @example\n * ```ts\n * const ns = { Id: \"Child\", Parent: { Id: \"Parent\", Parent: { Id: \"Root\" } } };\n * toPath(ns); // [\"Root\", \"Parent\", \"Child\"]\n * ```\n */\nexport const toPath = (ns) => {\n if (!ns)\n return [];\n const path = [];\n let current = ns;\n while (current) {\n path.unshift(current.Id);\n current = current.Parent;\n }\n return path;\n};\n/**\n * Create a fully-qualified name (FQN) from a namespace and logical ID.\n * The FQN is a flat key suitable for state storage.\n *\n * @example\n * ```ts\n * const ns = { Id: \"Child\", Parent: { Id: \"Parent\" } };\n * toFqn(ns, \"MyResource\"); // \"Parent/Child/MyResource\"\n * toFqn(undefined, \"MyResource\"); // \"MyResource\"\n * ```\n */\nexport const toFqn = (ns, logicalId) => {\n const path = toPath(ns);\n path.push(logicalId);\n return path.join(FQN_SEPARATOR);\n};\n/**\n * Parse an FQN back into namespace path segments and the logical ID.\n *\n * @example\n * ```ts\n * parseFqn(\"Parent/Child/MyResource\"); // { path: [\"Parent\", \"Child\"], logicalId: \"MyResource\" }\n * parseFqn(\"MyResource\"); // { path: [], logicalId: \"MyResource\" }\n * ```\n */\nexport const parseFqn = (fqn) => {\n const parts = fqn.split(FQN_SEPARATOR);\n const logicalId = parts.pop();\n return { path: parts, logicalId };\n};\n/**\n * Reconstruct a NamespaceNode chain from a path array.\n *\n * @example\n * ```ts\n * fromPath([\"Parent\", \"Child\"]);\n * // { Id: \"Child\", Parent: { Id: \"Parent\" } }\n * ```\n */\nexport const fromPath = (path) => {\n if (path.length === 0)\n return undefined;\n let node;\n for (const id of path) {\n node = { Id: id, Parent: node };\n }\n return node;\n};\n//# sourceMappingURL=FQN.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nexport const Provider = (type) => Context.Service()(type);\nexport const effect = (cls, eff) => \n// @ts-expect-error\nLayer.effect(Provider(cls.Type), eff);\nexport const succeed = (cls, service) => \n// @ts-expect-error\nLayer.succeed(Provider(cls.Type), service);\nexport const ProviderCollection = () => (id) => Context.Service()(id);\nexport const collection = (resources) => Effect.gen(function* () {\n const context = yield* Effect.context();\n const providers = Object.fromEntries(yield* Effect.all(resources.map((resource) => \"Provider\" in resource\n ? resource.Provider.pipe(Effect.map((provider) => [resource.Type, provider]))\n : Effect.succeed([\n resource.key,\n context.mapUnsafe.get(resource.key),\n ])), { concurrency: \"unbounded\" }));\n return {\n kind: \"ProviderCollection\",\n get: (service) => providers[service],\n };\n});\nconst isProviderCollectionService = (value) => {\n return (typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n value.kind === \"ProviderCollection\");\n};\nexport const findProviderByType = (type) => tryFindProviderByType(type).pipe(Effect.flatMap(Option.match({\n onNone: () => Effect.die(`Provider not found for ${type}`),\n onSome: (provider) => Effect.succeed(provider),\n})));\nexport const tryFindProviderByType = Effect.fnUntraced(function* (resourceType) {\n const Tag = Provider(resourceType);\n const direct = yield* Effect.serviceOption(Tag);\n if (Option.isSome(direct)) {\n return direct;\n }\n const context = yield* Effect.context();\n for (const value of context.mapUnsafe.values()) {\n if (isProviderCollectionService(value)) {\n const provider = value.get(resourceType);\n if (provider) {\n return Option.some(provider);\n }\n }\n }\n return Option.none();\n});\n//# sourceMappingURL=Provider.js.map","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport { pipeArguments } from \"effect/Pipeable\";\nimport { SingleShotGen } from \"effect/Utils\";\nimport { toFqn } from \"./FQN.js\";\nimport { CurrentNamespace } from \"./Namespace.js\";\nimport * as Output from \"./Output.js\";\nimport { Provider } from \"./Provider.js\";\nimport { ref as makeRef } from \"./Ref.js\";\nimport { RemovalPolicy } from \"./RemovalPolicy.js\";\nimport { Self } from \"./Self.js\";\nimport { Stack } from \"./Stack.js\";\nexport const isResource = (value) => {\n return typeof value === \"object\" && value !== null && \"Type\" in value;\n};\n/**\n * Creates a resource constructor for a concrete resource type.\n *\n * The returned constructor registers the resource on the current stack,\n * resolves input props, exposes output attributes as `Output` expressions, and\n * records bindings contributed by policies and event sources. Resource\n * providers are attached separately through `.provider`.\n */\nexport function Resource(type) {\n const self = Self(type);\n const constructor = (id, props) => Effect.gen(function* () {\n const stack = yield* Stack;\n const namespace = yield* CurrentNamespace;\n const fqn = toFqn(namespace, id);\n const existing = stack.resources[fqn];\n if (existing) {\n // // TODO(sam): check if props are different and die\n return existing;\n }\n const bind = (...args) => typeof args[0] === \"string\"\n ? Effect.gen(function* () {\n const [sid, data] = args;\n (stack.bindings[fqn] ??= []).push({\n sid,\n data,\n });\n return undefined;\n })\n : (data) => {\n const stringifyBindArg = (arg) => {\n if (arg === undefined) {\n return undefined;\n }\n if (Array.isArray(arg)) {\n return arg\n .flatMap((item) => {\n const stringified = stringifyBindArg(item);\n return stringified === undefined ? [] : [stringified];\n })\n .join(\", \");\n }\n if (arg &&\n (typeof arg === \"object\" || typeof arg === \"function\")) {\n if (\"LogicalId\" in arg && typeof arg.LogicalId === \"string\") {\n return arg.LogicalId;\n }\n if (\"id\" in arg && typeof arg.id === \"string\") {\n return arg.id;\n }\n }\n return String(arg);\n };\n return bind(`${args[0]\n .flatMap((text, i) => {\n const stringified = stringifyBindArg(args[i + 1]);\n return stringified !== undefined\n ? [text, stringified]\n : [text];\n })\n .join(\"\")}`, data);\n };\n const target = {\n Type: type,\n Namespace: namespace,\n FQN: fqn,\n LogicalId: id,\n Props: props,\n Provider: ProviderTag,\n RemovalPolicy: yield* Effect.serviceOption(RemovalPolicy).pipe(Effect.map(Option.getOrElse(() => \"destroy\"))),\n bind,\n toString() {\n return `Resource<${this.Type}>(${this.LogicalId})`;\n },\n [Symbol.toPrimitive](hint) {\n return hint === \"number\" ? NaN : this.toString();\n },\n };\n const Resource = (stack.resources[fqn] = new Proxy(target, {\n set: (t, prop, value) => {\n t[prop] = value;\n return true;\n },\n get: (t, prop) => typeof prop === \"symbol\" || prop in t\n ? t[prop]\n : new Output.PropExpr(Output.of(Resource), prop),\n }));\n Resource.Props = Effect.isEffect(props)\n ? yield* props.pipe(Effect.provideService(Self, Resource), Effect.provideService(Self(type), Resource))\n : props;\n return Resource;\n });\n const ProviderTag = Provider(type);\n const Service = {\n [Symbol.iterator]() {\n return new SingleShotGen(this.asEffect());\n },\n pipe() {\n return pipeArguments(this, arguments);\n },\n asEffect() {\n return Effect.succeed((id, props) => constructor(id, props));\n },\n /**\n * Build a typed reference to a deployed instance of this resource\n * — in the current stack/stage by default, or in another via\n * `options`. Resolves to the same shape as `yield*\n * MyResource(\"id\", props)` so downstream code can read attributes\n * (`ref.someAttr`) exactly the way it would for a locally-declared\n * resource.\n */\n ref: (id, options) => Effect.succeed(Output.of(makeRef(id, options))),\n Type: type,\n Provider: ProviderTag,\n Self: self,\n };\n const ResourceClass = Object.assign((...args) => typeof args[0] === \"object\"\n ? Object.assign(ResourceClass, args[0])\n : constructor(...args), Service);\n return ResourceClass;\n}\n//# sourceMappingURL=Resource.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\n/**\n * Context of the runtime environment.\n *\n * E.g. the context of a running Worker, Task, Process, Function\n */\nexport class RuntimeContext extends Context.Service()(\"RuntimeContext\") {\n}\nexport const CurrentRuntimeContext = Effect.serviceOption(RuntimeContext).pipe(Effect.map(Option.getOrUndefined));\n//# sourceMappingURL=RuntimeContext.js.map","import * as Context from \"effect/Context\";\nexport class Stage extends Context.Service()(\"Stage\") {\n}\n//# sourceMappingURL=Stage.js.map","import * as Context from \"effect/Context\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nexport const isActionState = (s) => !!s && s.kind === \"action\";\nexport const isResourceState = (s) => !!s && s.kind !== \"task\";\nexport class StateStoreError extends Data.TaggedError(\"StateStoreError\") {\n}\nexport class State extends Context.Service()(\"alchemy/State\") {\n}\n//# sourceMappingURL=State.js.map","import * as Predicate from \"effect/Predicate\";\nimport * as EffectRecord from \"effect/Record\";\nimport * as Redacted from \"effect/Redacted\";\nexport const isPrimitive = (value) => value === undefined ||\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"number\" ||\n typeof value === \"string\" ||\n typeof value === \"symbol\" ||\n typeof value === \"bigint\";\nexport const isPlainObject = (value) => {\n if (!Predicate.isObject(value))\n return false;\n return Object.getPrototypeOf(value) === Object.prototype;\n};\nexport const stripFields = (value, empty) => {\n if (Array.isArray(value)) {\n return value.map((item) => stripFields(item, empty));\n }\n if (!isPlainObject(value))\n return value;\n return EffectRecord.map(EffectRecord.filter(value, (entry) => entry !== empty), (entry) => stripFields(entry, empty));\n};\nexport const stripNullFields = (value) => stripFields(value, null);\nexport const stripUndefinedFields = (value) => stripFields(value, undefined);\nexport const unwrapRedacted = (value) => {\n if (Redacted.isRedacted(value)) {\n return Redacted.value(value);\n }\n if (Array.isArray(value)) {\n return value.map(unwrapRedacted);\n }\n if (!isPlainObject(value))\n return value;\n return EffectRecord.map(value, unwrapRedacted);\n};\n//# sourceMappingURL=data.js.map","import * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport { pipe } from \"effect/Function\";\nimport * as Redacted from \"effect/Redacted\";\nimport { SingleShotGen } from \"effect/Utils\";\nimport { getRefMetadata, isRef } from \"./Ref.js\";\nimport { isResource } from \"./Resource.js\";\nimport { RuntimeContext } from \"./RuntimeContext.js\";\nimport { Stack } from \"./Stack.js\";\nimport { Stage } from \"./Stage.js\";\nimport * as State from \"./State/State.js\";\nimport { isPrimitive } from \"./Util/data.js\";\nconst inspect = Symbol.for(\"nodejs.util.inspect.custom\");\nexport const of = (resource) => {\n if (isRef(resource)) {\n const metadata = getRefMetadata(resource);\n return new RefExpr(metadata.stack, metadata.stage, metadata.id);\n }\n return new ResourceExpr(resource);\n};\nexport const asOutput = (t) => isOutput(t)\n ? t\n : Effect.isEffect(t)\n ? new EffectExpr(VoidExpr, () => t)\n : new LiteralExpr(t);\nexport const isOutput = (value) => value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n ExprSymbol in value;\nexport const ExprSymbol = Symbol.for(\"alchemy/Expr\");\nexport const isExpr = (value) => value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n ExprSymbol in value;\nexport class BaseExpr {\n // we use a kind tag instead of instanceof to protect ourselves from duplicate alchemy module imports\n constructor() { }\n as() {\n return this;\n }\n [Symbol.iterator]() {\n // @ts-expect-error - TODO(sam): fix this (works at runtime, but maybe indicates a bad assumption)\n return new SingleShotGen(this.asEffect());\n }\n asEffect() {\n return this.bind(this.toString());\n }\n bind(id) {\n return RuntimeContext.pipe(Effect.flatMap((ctx) => Effect.map(ctx.set(id, this), (key) => ctx.get(key))));\n }\n pipe(...fns) {\n // @ts-expect-error\n return pipe(this, ...fns);\n }\n toString() {\n return this[inspect]();\n }\n}\nexport const isResourceExpr = (node) => node?.kind === \"ResourceExpr\";\nexport class ResourceExpr extends BaseExpr {\n src;\n stables;\n kind = \"ResourceExpr\";\n constructor(src, stables) {\n super();\n this.src = src;\n this.stables = stables;\n return proxy(this);\n }\n [inspect]() {\n return this.src.LogicalId;\n }\n}\nexport const isPropExpr = (node) => node?.kind === \"PropExpr\";\nexport class PropExpr extends BaseExpr {\n expr;\n identifier;\n kind = \"PropExpr\";\n constructor(expr, identifier) {\n super();\n this.expr = expr;\n this.identifier = identifier;\n return proxy(this);\n }\n [inspect]() {\n return `${this.expr[inspect]()}.${this.identifier.toString()}`;\n }\n}\nexport const literal = (value) => new LiteralExpr(value);\nexport const isLiteralExpr = (node) => node?.kind === \"LiteralExpr\";\nexport class LiteralExpr extends BaseExpr {\n value;\n kind = \"LiteralExpr\";\n constructor(value) {\n super();\n this.value = value;\n return proxy(this);\n }\n [inspect]() {\n return String(this.value);\n }\n}\nexport const VoidExpr = new LiteralExpr(void 0);\nexport const map = ((...args) => args.length === 1\n ? (output) => new ApplyExpr(output, args[0])\n : new ApplyExpr(args[0], args[1]));\n//Output.ApplyExpr<any, any, ResourceLike, any>\nexport const isApplyExpr = (node) => node?.kind === \"ApplyExpr\";\nexport class ApplyExpr extends BaseExpr {\n expr;\n f;\n kind = \"ApplyExpr\";\n constructor(expr, f) {\n super();\n this.expr = expr;\n this.f = f;\n return proxy(this);\n }\n [inspect]() {\n return `${this.expr[inspect]()}.map(${this.f.toString()})`;\n }\n}\nexport const mapEffect = (fn) => (output) => new EffectExpr(output, fn);\nexport const isEffectExpr = (node) => node?.kind === \"EffectExpr\";\nexport class EffectExpr extends BaseExpr {\n expr;\n f;\n kind = \"EffectExpr\";\n constructor(expr, f) {\n super();\n this.expr = expr;\n this.f = f;\n return proxy(this);\n }\n [inspect]() {\n return `${this.expr[inspect]()}.mapEffect(${this.f.toString()})`;\n }\n}\nexport const isNamedExpr = (node) => node?.kind === \"NamedExpr\";\n/**\n * Wraps another `Expr` and overrides its `toString()` / inspect output.\n *\n * `BaseExpr` derives the binding id from `this.toString()`, so\n * wrapping an expression in `NamedExpr` makes that derived id stable and\n * caller-controlled (e.g. an env var name like `\"API_KEY\"`).\n */\nexport class NamedExpr extends BaseExpr {\n expr;\n bindingName;\n kind = \"NamedExpr\";\n constructor(expr, bindingName) {\n super();\n this.expr = expr;\n this.bindingName = bindingName;\n return proxy(this);\n }\n [inspect]() {\n return this.bindingName;\n }\n}\nexport const named = (expr, name) => new NamedExpr(expr, name);\nexport const all = (...outs) => new AllExpr(outs);\nexport const isAllExpr = (node) => node?.kind === \"AllExpr\";\nexport class AllExpr extends BaseExpr {\n outs;\n kind = \"AllExpr\";\n constructor(outs) {\n super();\n this.outs = outs;\n return proxy(this);\n }\n [inspect]() {\n return `all(${this.outs.map((out) => out[inspect]()).join(\", \")})`;\n }\n}\nexport const isRefExpr = (node) => node?.kind === \"RefExpr\";\nexport class RefExpr extends BaseExpr {\n stack;\n stage;\n resourceId;\n kind = \"RefExpr\";\n constructor(stack, stage, resourceId) {\n super();\n this.stack = stack;\n this.stage = stage;\n this.resourceId = resourceId;\n return proxy(this);\n }\n [inspect]() {\n return `ref(${this.resourceId}, { stack: ${this.stack}, stage: ${this.stage} })`;\n }\n}\nexport const isStackRefExpr = (node) => node?.kind === \"StackRefExpr\";\n/**\n * A reference to the persisted output of a Stack at `(stack, stage)`.\n *\n * Resolved at evaluation time by reading `state.getOutput({ stack,\n * stage })`. Distinct from {@link RefExpr}, which references a\n * single resource's attributes within a stack/stage. `stage` may be\n * `undefined`, in which case it falls back to the current stage.\n */\nexport class StackRefExpr extends BaseExpr {\n stack;\n stage;\n kind = \"StackRefExpr\";\n constructor(stack, stage) {\n super();\n this.stack = stack;\n this.stage = stage;\n return proxy(this);\n }\n [inspect]() {\n return `stackRef(${this.stack}${this.stage ? `, { stage: ${this.stage} }` : \"\"})`;\n }\n}\n/**\n * Build an `Output<A>` referencing the persisted output of another\n * Stack. The returned Effect resolves to a lazy `Output<A>` whose\n * value is read from the state store at plan/apply time.\n *\n * Returns `Effect<Output<A>>` (not `Output<A>` directly) so that\n * `yield* Output.stackRef(...)` reads ergonomically inside an Effect\n * generator and lines up with `Resource.ref` and `Stack.stage.<name>`.\n */\nexport const stackRef = (stack, options = {}) => Effect.succeed(new StackRefExpr(stack, options.stage));\nexport const filter = (...outs) => outs.filter(isOutput);\nexport const interpolate = (template, ...args) => all(...args.map((arg) => (isOutput(arg) ? arg : literal(arg)))).pipe(map((args) => template\n .map((str, i) => str + (args[i] == null ? \"\" : String(args[i])))\n .join(\"\")));\nfunction proxy(self) {\n const target = Object.assign(() => { }, self);\n if (inspect in self) {\n Object.defineProperty(target, inspect, {\n value: self[inspect].bind(self),\n configurable: true,\n });\n }\n const proxy = new Proxy(target, {\n has: (_, prop) => prop === ExprSymbol || prop === inspect ? true : prop in self,\n get: (target, prop) => prop === Symbol.toPrimitive\n ? (hint) => {\n // Any JS-level coercion of an unresolved Output produces a\n // placeholder that *looks* like a real value but isn't:\n //\n // - `string` / `default` hints (`${output}`, `output + \"\"`,\n // `==` against a primitive) previously fell through to\n // `self.toString()` and returned the inspect form\n // (e.g. \"tunnel.tunnelId\"). The bogus string flowed\n // into resource props and into the cloud — only\n // surfacing as an opaque downstream error (see PR\n // description for a real Cloudflare DNS landing).\n //\n // - `number` hint (`+output`, `output * 2`,\n // `Math.max(0, output)`) previously returned NaN, which\n // propagates silently through arithmetic and lands as\n // \"the API rejected a NaN field\" much later.\n //\n // All three hints fail loud at the coercion site with a\n // pointer to the right composition API.\n throw new Error(`Cannot coerce Output<${self[inspect]()}> to a ` +\n `${hint === \"number\" ? \"number\" : \"string\"} via JS coercion. ` +\n `Use Output.interpolate\\`...\\` or Output.map(output, fn) ` +\n `to compose Outputs — the value isn't known until deploy time.`);\n }\n : prop === ExprSymbol\n ? self\n : prop === inspect\n ? target[inspect]\n : isResourceExpr(self) && self.stables && prop in self.stables\n ? self.stables[prop]\n : prop === \"apply\"\n ? self[prop]\n : prop in self\n ? typeof self[prop] === \"function\" &&\n !(\"kind\" in self)\n ? new PropExpr(proxy, prop)\n : self[prop]\n : new PropExpr(proxy, prop),\n apply: (_, thisArg, args) => {\n if (isPropExpr(self)) {\n if (self.identifier === \"apply\") {\n return new ApplyExpr(self.expr, args[0]);\n }\n else if (self.identifier === \"effect\") {\n return new EffectExpr(self.expr, args[0]);\n }\n }\n return undefined;\n },\n });\n return proxy;\n}\n/// Evaluation\nexport class MissingSourceError extends Data.TaggedError(\"MissingSourceError\") {\n}\nexport class InvalidReferenceError extends Data.TaggedError(\"InvalidReferenceError\") {\n}\nexport const evaluate = (expr, upstream) => Effect.gen(function* () {\n if (isResource(expr)) {\n const srcId = expr.FQN;\n const src = upstream[srcId];\n if (!src) {\n // type-safety should prevent this but let the caller decide how to handle it\n return yield* new MissingSourceError({\n message: `Source ${srcId} not found`,\n srcId,\n });\n }\n return src;\n }\n else if (isOutput(expr)) {\n if (isResourceExpr(expr)) {\n const srcId = expr.src.FQN;\n const src = upstream[srcId];\n if (!src) {\n // type-safety should prevent this but let the caller decide how to handle it\n return yield* new MissingSourceError({\n message: `Source ${srcId} not found`,\n srcId,\n });\n }\n return src;\n }\n else if (isLiteralExpr(expr)) {\n return expr.value;\n }\n else if (isApplyExpr(expr)) {\n return expr.f(yield* evaluate(expr.expr, upstream));\n }\n else if (isEffectExpr(expr)) {\n // TODO(sam): the same effect shoudl be memoized so that it's not run multiple times\n return yield* expr.f(yield* evaluate(expr.expr, upstream));\n }\n else if (isAllExpr(expr)) {\n return yield* Effect.all(expr.outs.map((out) => evaluate(out, upstream)));\n }\n else if (isPropExpr(expr)) {\n return (yield* evaluate(expr.expr, upstream))?.[expr.identifier];\n }\n else if (isNamedExpr(expr)) {\n return yield* evaluate(expr.expr, upstream);\n }\n else if (isRefExpr(expr)) {\n const state = yield* State.State;\n const stack = expr.stack ?? (yield* Stack).name;\n const stage = expr.stage ?? (yield* Stage);\n const resource = yield* state.get({\n stack,\n stage,\n fqn: expr.resourceId,\n });\n if (!resource) {\n return yield* Effect.fail(new InvalidReferenceError({\n message: `Reference to '${expr.resourceId}' in stack '${stack}' and stage '${stage}' not found. Have you deployed '${stage}' or '${stack}'?`,\n stack,\n stage,\n resourceId: expr.resourceId,\n }));\n }\n // RefExpr targets persisted resources; tasks aren't cross-stack\n // referenceable. Return the resource's output attrs, otherwise the\n // task's output value, otherwise undefined.\n return resource.attr ?? resource.output;\n }\n else if (isStackRefExpr(expr)) {\n const state = yield* State.State;\n const stack = expr.stack;\n const stage = expr.stage ?? (yield* Stage);\n const output = yield* state.getOutput({ stack, stage });\n if (output == null) {\n return yield* Effect.fail(new InvalidReferenceError({\n message: `Reference to stack '${stack}' at stage '${stage}' not found. Have you deployed stage '${stage}' of '${stack}'?`,\n stack,\n stage,\n resourceId: stack,\n }));\n }\n return output;\n }\n }\n if (Array.isArray(expr)) {\n return yield* Effect.all(expr.map((item) => evaluate(item, upstream)));\n }\n else if (Redacted.isRedacted(expr)) {\n return expr;\n }\n else if (typeof expr === \"object\" && expr !== null) {\n return Object.fromEntries(yield* Effect.all(Object.entries(expr).map(([key, value]) => evaluate(value, upstream).pipe(Effect.map((value) => [key, value])))));\n }\n return expr;\n});\nexport const hasOutputs = (value) => Object.keys(upstreamAny(value)).length > 0;\nexport const upstreamAny = (value) => {\n if (isResource(value)) {\n return { [value.FQN]: value };\n }\n else if (isExpr(value)) {\n return upstream(value);\n }\n else if (Array.isArray(value)) {\n return Object.assign({}, ...value.map(resolveUpstream));\n }\n else if (value &&\n (typeof value === \"object\" || typeof value === \"function\")) {\n return Object.assign({}, ...Object.values(value).map((value) => resolveUpstream(value)));\n }\n return {};\n};\n// TODO(sam): add a type\nexport const upstream = (expr) => {\n if (isResource(expr)) {\n return {\n [expr.FQN]: expr,\n };\n }\n else if (isResourceExpr(expr)) {\n return {\n [expr.src.FQN]: expr.src,\n };\n }\n else if (isPropExpr(expr)) {\n return upstream(expr.expr);\n }\n else if (isAllExpr(expr)) {\n return Object.assign({}, ...expr.outs.map((out) => upstream(out)));\n }\n else if (isEffectExpr(expr) || isApplyExpr(expr) || isNamedExpr(expr)) {\n return upstream(expr.expr);\n }\n else if (Array.isArray(expr)) {\n return expr.map(upstream).reduce(toObject, {});\n }\n else if (typeof expr === \"object\" && expr !== null) {\n return Object.values(expr)\n .map((v) => upstream(v))\n .reduce(toObject, {});\n }\n return {};\n};\n// TODO(sam): add a type\nexport const resolveUpstream = (value) => {\n if (isPrimitive(value)) {\n return {};\n }\n else if (isResource(value)) {\n return { [value.FQN]: value };\n }\n else if (isOutput(value)) {\n return upstream(value);\n }\n else if (Array.isArray(value)) {\n return Object.fromEntries(value.map((v) => resolveUpstream(v)).flatMap(Object.entries));\n }\n else if (typeof value === \"object\" || typeof value === \"function\") {\n return Object.fromEntries(Object.values(value)\n .map(resolveUpstream)\n .flatMap(Object.entries));\n }\n return {};\n};\nconst toObject = (acc, v) => ({\n ...acc,\n ...v,\n});\nexport const log = (_value) => Effect.gen(function* () {\n // TODO(sam): implement a log effect\n});\nexport const toEnvKey = (id, suffix) => `${replace(toUpper(id))}_${replace(toUpper(suffix))}`;\nexport const toUpper = (str) => str.toUpperCase();\nconst replace = (str) => str.replace(/-/g, \"_\");\n//# sourceMappingURL=Output.js.map","import * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nexport const loadConfigProvider = (envFile) => {\n if (Option.isSome(envFile)) {\n return ConfigProvider.fromDotEnv({ path: envFile.value }).pipe(Effect.map((dotEnv) => ConfigProvider.orElse(dotEnv, ConfigProvider.fromEnv())));\n }\n return Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const exists = yield* fs.exists(\".env\");\n if (!exists) {\n return ConfigProvider.fromEnv();\n }\n return ConfigProvider.orElse(yield* ConfigProvider.fromDotEnv({ path: \".env\" }), ConfigProvider.fromEnv());\n });\n};\n//# sourceMappingURL=ConfigProvider.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport { pipeArguments } from \"effect/Pipeable\";\nimport { SingleShotGen } from \"effect/Utils\";\nexport const effectClass = ((impl) => impl === undefined\n ? (innerImpl) => effectClass(innerImpl)\n : Object.assign(class {\n static asEffect() {\n return impl;\n }\n static [Symbol.iterator]() {\n return new SingleShotGen(this.asEffect());\n }\n static pipe(...fns) {\n return pipeArguments(this, fns);\n }\n }, impl));\nexport const taggedFunction = (tag, fn) => {\n const overrides = {\n asEffect: () => tag,\n [Symbol.iterator]: () => tag[Symbol.iterator](),\n pipe: (...fns) => pipeArguments(tag, fns),\n toString: () => `${tag.toString()}.${fn.name}`,\n };\n return new Proxy(fn, {\n get: (target, prop, receiver) => Reflect.has(overrides, prop)\n ? Reflect.get(overrides, prop, receiver)\n : Reflect.has(target, prop)\n ? Reflect.get(target, prop, receiver)\n : Reflect.get(tag, prop, tag),\n has: (target, prop) => Reflect.has(overrides, prop) ||\n Reflect.has(target, prop) ||\n Reflect.has(tag, prop),\n });\n};\nexport const isYieldableEffect = (value) => Effect.isEffect(value) &&\n typeof value[Symbol.iterator] ===\n \"function\";\nexport const isEffectClassLike = (value) => typeof value === \"function\" &&\n typeof value.asEffect === \"function\";\nexport const isYieldableEffectLike = (value) => isYieldableEffect(value) || isEffectClassLike(value);\nexport const toEffectInterface = (raw) => ({\n raw,\n ...Object.fromEntries(Object.entries(raw).map(([key, value]) => [\n key,\n typeof value === \"function\"\n ? (...args) => Effect.tryPromise(async () => value(...args))\n : value,\n ])),\n});\n//# sourceMappingURL=effect.js.map","import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Logger from \"effect/Logger\";\nimport { Path } from \"effect/Path\";\nimport { AlchemyContext } from \"../AlchemyContext.js\";\nexport const fileLogger = Effect.fnUntraced(function* (...segments) {\n const { dotAlchemy } = yield* AlchemyContext;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path;\n const logFile = path.join(dotAlchemy, \"log\", ...segments);\n yield* fs.makeDirectory(path.dirname(logFile), { recursive: true });\n return yield* Logger.formatLogFmt.pipe(Logger.toFile(logFile, {\n flag: \"a\",\n }));\n});\n//# sourceMappingURL=FileLogger.js.map","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nconst isBun = typeof Bun !== \"undefined\";\n/**\n * Constructs a layer with different implementations for Bun and Node.\n */\nexport const platformLayer = (constructors) => Layer.unwrap(Effect.promise(async () => {\n if (isBun) {\n return await constructors.bun();\n }\n else {\n return await constructors.node();\n }\n}));\nexport const PlatformServices = platformLayer({\n bun: async () => {\n const [BunServices, BunSocket] = await Promise.all([\n import(\"@effect/platform-bun/BunServices\"),\n import(\"@effect/platform-bun/BunSocket\"),\n ]);\n return Layer.merge(BunServices.layer, BunSocket.layerWebSocketConstructor);\n },\n node: async () => {\n const [NodeServices, NodeSocket] = await Promise.all([\n import(\"@effect/platform-node/NodeServices\"),\n import(\"@effect/platform-node/NodeSocket\"),\n ]);\n return Layer.merge(NodeServices.layer, NodeSocket.layerWebSocketConstructor);\n },\n});\nexport const runMain = (effect, options) => {\n if (isBun) {\n void import(\"@effect/platform-bun/BunRuntime\").then((BunRuntime) => BunRuntime.runMain(effect, options));\n }\n else {\n void import(\"@effect/platform-node/NodeRuntime\").then((NodeRuntime) => NodeRuntime.runMain(effect, options));\n }\n};\nexport const httpServer = (port = 0, host = \"127.0.0.1\") => platformLayer({\n bun: async () => {\n const BunHttpServer = await import(\"@effect/platform-bun/BunHttpServer\");\n return BunHttpServer.layer({ hostname: host, port });\n },\n node: async () => {\n const [NodeHttpServer, Http] = await Promise.all([\n import(\"@effect/platform-node/NodeHttpServer\"),\n import(\"node:http\"),\n ]);\n return NodeHttpServer.layerServer(Http.createServer, { host, port });\n },\n});\n//# sourceMappingURL=PlatformServices.js.map","import { ConfigProvider } from \"effect/ConfigProvider\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport { FileSystem } from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Logger from \"effect/Logger\";\nimport * as Option from \"effect/Option\";\nimport { Path } from \"effect/Path\";\nimport * as Scope from \"effect/Scope\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport { AlchemyContext, AlchemyContextLive } from \"./AlchemyContext.js\";\nimport { provideFreshArtifactStore } from \"./Artifacts.js\";\nimport { AuthProviders } from \"./Auth/AuthProvider.js\";\nimport { CredentialsStore, CredentialsStoreLive } from \"./Auth/Credentials.js\";\nimport { Profile, ProfileLive } from \"./Auth/Profile.js\";\nimport { Cli } from \"./Cli/Cli.js\";\nimport * as Output from \"./Output.js\";\nimport { Stage } from \"./Stage.js\";\nimport { loadConfigProvider } from \"./Util/ConfigProvider.js\";\nimport { effectClass, taggedFunction } from \"./Util/effect.js\";\nimport { fileLogger } from \"./Util/FileLogger.js\";\nimport { PlatformServices } from \"./Util/PlatformServices.js\";\nexport const Stack = Object.assign(taggedFunction(Context.Service()(\"Stack\"), (stackName, options, eff) => {\n if (!stackName) {\n return (stackName) => Object.assign(\n // by default, reference the stack at the \"current\" stage of the importer\n Output.stackRef(stackName).pipe(effectClass), {\n stage: createStageProxy(stackName),\n make: (options, eff) => Stack(stackName, options, eff),\n });\n }\n return eff.pipe(make({\n name: stackName,\n ...options,\n }), (eff) => Object.assign(eff, {\n stage: createStageProxy(stackName),\n }));\n}));\nconst createStageProxy = (stackName) => new Proxy({}, {\n get: (_, stage) => Output.stackRef(stackName, { stage }),\n});\nexport const StackName = Stack.use((stack) => Effect.succeed(stack.name));\nexport const make = (options) => (effect) => Effect.scope.pipe(Effect.flatMap((scope) => {\n if (options.state == null) {\n return Effect.die(new Error(`Stack \"${options.name}\" is missing a state store. ` +\n `Add a \\`state\\` layer to the stack options, e.g.:\\n` +\n ` Alchemy.Stack(\"${options.name}\", {\\n` +\n ` providers: Cloudflare.providers(),\\n` +\n ` state: Cloudflare.state(), // <-- required\\n` +\n ` }, ...)\\n` +\n `See https://v2.alchemy.run/concepts/state-store for available state stores.`));\n }\n if (options.providers == null) {\n return Effect.die(new Error(`Stack \"${options.name}\" is missing a providers layer. ` +\n `Add a \\`providers\\` layer to the stack options, e.g.:\\n` +\n ` Alchemy.Stack(\"${options.name}\", {\\n` +\n ` providers: Cloudflare.providers(), // <-- required\\n` +\n ` state: Cloudflare.state(),\\n` +\n ` }, ...)`));\n }\n return options.providers.pipe(Layer.provideMerge(options.state), Layer.provideMerge(Layer.effect(Stack, Stage.pipe(Effect.map((stage) => options.stack ?? {\n name: options.name,\n stage,\n resources: {},\n bindings: {},\n actions: {},\n })))), Layer.buildWithScope(scope));\n}), Effect.flatMap((context) => Effect.all([\n effect,\n Stack,\n Effect.context(),\n]).pipe(Effect.map(([output, stack, services]) => ({\n ...stack,\n output,\n services: Context.merge(services, context),\n})), Effect.provideContext(context))));\nexport const CurrentStack = Effect.serviceOption(Stack)\n .pipe(Effect.map(Option.getOrUndefined));\nconst platform = Layer.mergeAll(PlatformServices, FetchHttpClient.layer, Logger.layer([fileLogger(\"out\")], { mergeWithExisting: true }), Layer.provide(ProfileLive, PlatformServices), Layer.provide(CredentialsStoreLive, PlatformServices));\n// override alchemy state store, CLI/reporting, state, and Config\nconst alchemy = (overrides) => Layer.mergeAll(\n// CLI.inkCLI(),\n// optional\noverrides?.dev\n ? Layer.provide(Layer.effect(AlchemyContext, AlchemyContext.useSync((ctx) => ({ ...ctx, dev: overrides.dev }))), AlchemyContextLive)\n : AlchemyContextLive);\nexport const evalStack = (effect, fn, options) => {\n const body = Effect.gen(function* () {\n const stack = yield* effect;\n const configProvider = yield* loadConfigProvider(Option.none());\n return yield* fn(stack).pipe(provideFreshArtifactStore, Effect.provide(stack.services), Effect.provide(Layer.succeed(ConfigProvider, configProvider)));\n }).pipe(Effect.provide(Layer.effect(AuthProviders, Effect.serviceOption(AuthProviders).pipe(Effect.map(Option.getOrElse(() => ({})))))), Effect.provide(Layer.succeed(Stage, options.stage)), Effect.provide(Layer.provideMerge(alchemy({ dev: options.dev }), platform)));\n return options.scope === undefined\n ? Effect.scoped(body)\n : Scope.provide(body, options.scope);\n};\n//# sourceMappingURL=Stack.js.map","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport { flow } from \"effect/Function\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as NodeUtil from \"node:util\";\nimport * as Output from \"../Output.js\";\nexport const wrapRpcHandlers = (handlers, streamKeys) => {\n return Object.fromEntries(Object.entries(handlers).map(([key, value]) => [\n key,\n typeof value === \"function\"\n ? streamKeys?.includes(key)\n ? wrapRpcStreamHandler(value)\n : wrapRpcEffectHandler(value)\n : typeof value === \"object\" && value !== null\n ? wrapRpcHandlers(value)\n : value,\n ]));\n};\nexport const unwrapRpcHandlers = (handlers, streamKeys) => {\n return Object.fromEntries(Object.entries(handlers).map(([key, value]) => [\n key,\n typeof value === \"function\"\n ? streamKeys?.includes(key)\n ? unwrapRpcStreamHandler(value)\n : unwrapRpcEffectHandler(value)\n : typeof value === \"object\" && value !== null\n ? unwrapRpcHandlers(value)\n : value,\n ]));\n};\nconst serializeError = Schema.encodeSync(Schema.Defect);\nconst wrapRpcEffectHandler = (handler) => flow((args) => deserializeRpcArgs(args), (args) => handler(...args), Effect.exit, Effect.map((exit) => {\n if (exit._tag === \"Success\") {\n return { _tag: \"Success\", value: exit.value };\n }\n return {\n _tag: \"Failure\",\n cause: exit.cause.reasons.map((reason) => {\n switch (reason._tag) {\n case \"Fail\":\n return { _tag: \"Fail\", error: serializeError(reason.error) };\n case \"Die\":\n return { _tag: \"Die\", defect: serializeError(reason.defect) };\n case \"Interrupt\":\n return { _tag: \"Interrupt\", fiberId: reason.fiberId };\n }\n }),\n };\n}), Effect.runPromise);\nconst wrapRpcStreamHandler = (handler) => flow((args) => deserializeRpcArgs(args), (args) => handler(...args), (stream) => Stream.toReadableStream(stream));\nconst unwrapRpcEffectHandler = (handler) => flow((...args) => serializeRpcArgs(args), (args) => Effect.promise(() => handler(args)), Effect.flatMap((exit) => {\n if (exit._tag === \"Success\") {\n return Exit.succeed(exit.value);\n }\n return Exit.failCause(Cause.fromReasons(exit.cause.map((reason) => {\n switch (reason._tag) {\n case \"Fail\":\n return Cause.makeFailReason(reason.error);\n case \"Die\":\n return Cause.makeDieReason(reason.defect);\n case \"Interrupt\":\n return Cause.makeInterruptReason(reason.fiberId);\n }\n })));\n}));\nconst unwrapRpcStreamHandler = (handler) => flow((...args) => serializeRpcArgs(args), (args) => handler(args), (stream) => Stream.fromReadableStream({\n evaluate: () => stream,\n onError: (error) => error,\n}));\nconst serializeRpcArgs = (value) => {\n if (Redacted.isRedacted(value)) {\n return { _tag: \"Redacted\", value: Redacted.value(value) };\n }\n if (Output.isOutput(value)) {\n return {\n _tag: \"Output\",\n description: NodeUtil.inspect(value),\n };\n }\n if (typeof value === \"function\") {\n return null;\n }\n if (Array.isArray(value)) {\n return value.map(serializeRpcArgs);\n }\n if (value && typeof value === \"object\" && !(\"toJSON\" in value)) {\n return Object.fromEntries(Object.entries(value).map(([key, child]) => [\n key,\n serializeRpcArgs(child),\n ]));\n }\n return value;\n};\nconst deserializeRpcArgs = (value) => {\n if (Array.isArray(value)) {\n return value.map(deserializeRpcArgs);\n }\n else if (typeof value === \"object\" && value !== null) {\n // These values are serialized as `{_tag: \"Redacted\", value: ...}` and `{_tag: \"Output\", description: ...}`,\n // so we need to detect them manually - Redacted.isRedacted and Output.isOutput do not work.\n if (\"_tag\" in value && value._tag === \"Redacted\" && \"value\" in value) {\n return Redacted.make(value.value);\n }\n else if (\"_tag\" in value &&\n value._tag === \"Output\" &&\n \"description\" in value &&\n typeof value.description === \"string\") {\n return new Output.NamedExpr(new Output.EffectExpr(Output.VoidExpr, () => Effect.never), value.description);\n }\n return Object.fromEntries(Object.entries(value).map(([key, child]) => [\n key,\n deserializeRpcArgs(child),\n ]));\n }\n return value;\n};\n//# sourceMappingURL=RpcSerialization.js.map","import { newWebSocketRpcSession } from \"capnweb\";\nimport * as Cache from \"effect/Cache\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as HttpBody from \"effect/unstable/http/HttpBody\";\nimport * as HttpClient from \"effect/unstable/http/HttpClient\";\nimport { AlchemyContext } from \"../AlchemyContext.js\";\nimport { Stack } from \"../Stack.js\";\nimport { unwrapRpcHandlers } from \"./RpcSerialization.js\";\nexport class RpcProviderProxy extends Context.Service()(\"alchemy/Local/RpcProviderProxy\") {\n}\nexport const SPAWNER_URL_ENV_KEY = \"ALCHEMY_RPC_SPAWNER_URL\";\nconst make = Effect.fnUntraced(function* (spawnerUrl) {\n const client = yield* HttpClient.HttpClient;\n const getSession = Effect.fnUntraced(function* (serverEntryUrl) {\n const alchemyContext = yield* AlchemyContext;\n const stack = yield* Stack;\n const payload = {\n serverEntryUrl,\n alchemyContext,\n stack: { name: stack.name, stage: stack.stage },\n };\n const response = yield* client.post(spawnerUrl, {\n body: yield* HttpBody.json(payload),\n });\n const websocketUrl = yield* response.text;\n return newWebSocketRpcSession(websocketUrl);\n }, (effect, serverEntryUrl) => Effect.catch(effect, (error) => Effect.die(new Error(`Failed to create provider RPC session for \"${serverEntryUrl}\"`, {\n cause: error,\n }))));\n const cache = yield* Cache.make({\n lookup: getSession,\n capacity: Infinity,\n requireServicesAt: \"lookup\",\n });\n return RpcProviderProxy.of({\n get: Effect.fnUntraced(function* (mainUrl, providerName) {\n const session = yield* cache.lookup(mainUrl);\n const provider = yield* Effect.promise(() => session.getProvider(providerName));\n return unwrapRpcHandlers(provider, [\"tail\"]);\n }),\n });\n});\nexport const layer = (url) => Layer.effect(RpcProviderProxy, make(url));\nexport const fromEnv = () => Layer.effect(RpcProviderProxy, Config.string(SPAWNER_URL_ENV_KEY).pipe(Effect.flatMap(make)));\n//# sourceMappingURL=RpcProviderProxy.js.map","import * as Context from \"effect/Context\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\n/**\n * AdoptPolicy controls whether the engine should \"adopt\" pre-existing cloud\n * resources that conflict with this stack instead of failing.\n *\n * The engine always calls a provider's `read` lifecycle operation when there\n * is no prior state and `read` is implemented. The provider's job is to\n * report two things:\n *\n * 1. Whether the resource exists (returns attributes vs. `undefined`).\n * 2. Whether *we* own it (plain attributes vs. {@link Unowned}-branded).\n *\n * The engine then routes:\n *\n * | `read` outcome | `adopt: false` | `adopt: true` |\n * | ------------------- | -------------- | ----------------- |\n * | undefined | create | create |\n * | owned (plain attrs) | silent adopt | silent adopt |\n * | {@link Unowned} | fail | takeover (adopt) |\n *\n * \"Owned\" means a provider has affirmatively determined the resource was\n * created by this stack/stage/logical-id (typically by inspecting tags or\n * naming conventions). Resources without ownership semantics simply always\n * return plain attrs — they are treated as owned by default, so silent\n * adoption is the norm and `--adopt` is unnecessary.\n *\n * The policy can be overridden per-effect via {@link adopt} — most commonly\n * applied at the resource or stack scope.\n */\nexport class AdoptPolicy extends Context.Service()(\"AdoptPolicy\") {\n}\n/**\n * Engine-raised failure produced when `read` reports an existing resource\n * marked as {@link Unowned} and `adopt` is `false`. Surface this to the user\n * to indicate they should either re-tag the cloud resource, pick a different\n * physical name, or re-run with `--adopt` (or `adopt(true)`) to force a\n * takeover.\n */\nexport class OwnedBySomeoneElse extends Data.TaggedError(\"OwnedBySomeoneElse\") {\n}\n/**\n * Private symbol used to brand attribute objects returned by `read` as\n * \"exists in cloud, but not owned by this stack/stage/logical-id\".\n *\n * Deliberately *not* registered via `Symbol.for` — the brand is an\n * engine-internal routing hint and must not be observable or\n * forgeable from outside this module. The engine strips it before any\n * state persistence (see {@link stripUnowned}) so it never leaks into\n * the state store, JSON serialization, or downstream `Output`s.\n */\nconst UnownedTag = Symbol(\"alchemy/Unowned\");\n/**\n * Brand a `read` return value as belonging to a different owner.\n *\n * Use this in a provider's `read` implementation when the resource exists in\n * the cloud but a positive ownership check (e.g. tag inspection) shows it\n * was *not* created by this stack/stage/logical-id:\n *\n * ```ts\n * read: Effect.fnUntraced(function* ({ id, output, olds }) {\n * const settings = yield* getScriptSettings({ ... }).pipe(\n * Effect.catchTag(\"WorkerNotFound\", () => Effect.succeed(undefined)),\n * );\n * if (!settings) return undefined;\n *\n * const attrs = { workerName, ...buildAttrs(settings) };\n * return hasAlchemyWorkerTags(id, settings.tags) ? attrs : Unowned(attrs);\n * }),\n * ```\n *\n * The returned value is structurally still `T` — there is no wrapper to\n * unwrap. The brand is a non-enumerable symbol that the engine inspects\n * during planning to decide whether to take over (`adopt: true`) or fail\n * loudly (`adopt: false`).\n *\n * Resources without ownership semantics should simply return plain attrs —\n * the engine treats them as owned and silent adoption is the default.\n */\nexport const Unowned = Object.assign((attrs) => {\n const cloned = { ...attrs };\n Object.defineProperty(cloned, UnownedTag, {\n value: true,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n return cloned;\n}, {\n is: (value) => typeof value === \"object\" &&\n value !== null &&\n value[UnownedTag] === true,\n});\n/**\n * Strip the {@link Unowned} brand from an attributes object before persisting\n * it — state should not carry per-deploy ownership-routing metadata.\n *\n * The brand is intentionally non-enumerable, so a plain spread already\n * drops it; the additional `delete` is defense-in-depth in case a future\n * change makes the descriptor enumerable. Always returns a fresh object\n * (never mutates the input).\n */\nexport const stripUnowned = (attrs) => {\n const out = { ...attrs };\n if (UnownedTag in out)\n delete out[UnownedTag];\n return out;\n};\nexport const adopt = ((enabled) => (eff) => eff.pipe(typeof enabled === \"boolean\"\n ? Effect.provideService(AdoptPolicy, enabled ?? true)\n : Effect.provideServiceEffect(AdoptPolicy, enabled)));\n//# sourceMappingURL=AdoptPolicy.js.map","import * as Effect from \"effect/Effect\";\nimport * as Output from \"./Output.js\";\nimport { isPrimitive } from \"./Util/data.js\";\n/**\n * Returns true when `value` (or any nested leaf) is still an unresolved\n * plan-time expression — i.e. an `Output`/`Expr` or an `Effect` that was\n * not fully evaluated by `resolveInput` in Plan.ts.\n *\n * Use at the top of a provider `diff` to short-circuit before field access:\n *\n * ```ts\n * if (!isResolved(news)) return undefined;\n * const resolved = news as MyProps;\n * ```\n */\nexport const hasUnresolvedInputs = (value) => _hasUnresolved(value);\nexport const isResolved = (value) => !_hasUnresolved(value);\nconst _hasUnresolved = (value) => {\n if (value == null || isPrimitive(value))\n return false;\n if (Output.isExpr(value) || Effect.isEffect(value))\n return true;\n if (Array.isArray(value))\n return value.some(_hasUnresolved);\n if (typeof value === \"object\") {\n return Object.values(value).some(_hasUnresolved);\n }\n return false;\n};\nexport const somePropsAreDifferent = (olds, news, props) => {\n for (const prop of props) {\n if (olds[prop] !== news[prop]) {\n return true;\n }\n }\n return false;\n};\nexport const anyPropsAreDifferent = (olds, news) => {\n for (const prop in olds) {\n if (olds[prop] !== news[prop]) {\n return true;\n }\n }\n for (const prop in news) {\n if (!(prop in olds)) {\n return true;\n }\n }\n return false;\n};\nexport const havePropsChanged = (oldProps, newProps) => Output.hasOutputs(newProps) ||\n JSON.stringify(canonicalize(oldProps ?? {}, false)) !==\n JSON.stringify(canonicalize(newProps ?? {}, false));\n/**\n * Sort-keys deep equality for plain data (objects, arrays, primitives).\n * Use in provider `diff` handlers instead of ad-hoc `JSON.stringify` comparisons.\n *\n * By default, `null` and `undefined` are treated as distinct. Pass\n * `{ stripNullish: true }` to opt into treating them as equivalent.\n */\nexport const deepEqual = (a, b, options) => JSON.stringify(canonicalize(a, options?.stripNullish ?? false)) ===\n JSON.stringify(canonicalize(b, options?.stripNullish ?? false));\nconst canonicalize = (value, stripNullish) => {\n if (stripNullish && value == null)\n return undefined;\n if (Array.isArray(value)) {\n return value.map((v) => canonicalize(v, stripNullish));\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(Object.entries(value)\n .filter(([, nested]) => !stripNullish || nested != null)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, nested]) => [key, canonicalize(nested, stripNullish)]));\n }\n return value;\n};\nexport const diffBindings = (oldBindings, newBindings) => {\n const oldMap = new Map(oldBindings.map((b) => [b.sid, b]));\n const newMap = new Map(newBindings.map((b) => [b.sid, b]));\n return [\n ...Array.from(oldMap)\n .filter(([sid]) => !newMap.has(sid))\n .map(([sid, old]) => ({\n sid,\n action: \"delete\",\n data: old.data,\n })),\n ...Array.from(newMap).map(([sid, binding]) => {\n const old = oldMap.get(sid);\n return {\n sid,\n action: (!old\n ? \"create\"\n : havePropsChanged(old.data, binding.data)\n ? \"update\"\n : \"noop\"),\n data: binding.data,\n };\n }),\n ];\n};\n//# sourceMappingURL=Diff.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\n/** A 16-byte (128-bit) random hex-encoded string representing an physical instance of a logical resource */\nexport class InstanceId extends Context.Service()(\"instance-id\") {\n}\n/**\n * @returns Hex-encoded instance ID (16 random bytes)\n */\nexport const generateInstanceId = () => Effect.sync(() => {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n});\n//# sourceMappingURL=InstanceId.js.map","import * as Effect from \"effect/Effect\";\nexport const assertDefined = (value, message) => {\n if (!value) {\n throw new Error(message);\n }\n return value;\n};\nexport const asEffect = (effect) => Effect.isEffect(effect) ? effect : Effect.succeed(effect);\n//# sourceMappingURL=types.js.map","import * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Metric from \"effect/Metric\";\n/**\n * Counter for resource lifecycle operations. Tagged per call with\n * `resource_type`, `op` (`precreate`/`create`/`update`/`delete`/`read`),\n * and `status` (`success`/`error`).\n */\nexport const resourceCounter = Metric.counter(\"alchemy.resource.operations\", {\n description: \"Number of resource lifecycle operations dispatched by alchemy apply.\",\n incremental: true,\n});\n/**\n * Histogram of how long each lifecycle operation takes.\n */\nexport const resourceDuration = Metric.timer(\"alchemy.resource.duration\", {\n description: \"Wall-clock duration of resource lifecycle operations dispatched by alchemy apply.\",\n});\n/**\n * Counter for CLI command invocations.\n */\nexport const cliCounter = Metric.counter(\"alchemy.cli.invocations\", {\n description: \"Number of alchemy CLI command invocations.\",\n incremental: true,\n});\n/**\n * Counter for Cloudflare State Store bootstrap/deploy operations.\n * Tagged per call with `op` (e.g. `deploy`) and `status`\n * (`success`/`error`) so that the deploy success rate of the\n * state store itself can be tracked separately from regular\n * resource lifecycle ops.\n */\nexport const stateStoreCounter = Metric.counter(\"alchemy.state_store.operations\", {\n description: \"Number of Cloudflare State Store deploy/bootstrap operations dispatched by alchemy.\",\n incremental: true,\n});\n/**\n * Counter for State store layer construction. Tagged with `id` (the\n * `StateService.id` slug) so we can answer \"how many distinct projects\n * are using each backend\" from the corresponding `state_store.init`\n * spans. Open-ended on purpose: third-party state stores get counted\n * automatically by setting their `StateService.id`.\n */\nexport const stateStoreInitCounter = Metric.counter(\"alchemy.state_store.inits\", {\n description: \"Number of times a State store layer is constructed.\",\n incremental: true,\n});\n/**\n * Wraps a resource lifecycle Effect to record a counter + timer entry,\n * tagged with `resource_type`, `op`, and `status` (`success`/`error`).\n *\n * Usage:\n * ```ts\n * provider.reconcile(input).pipe(recordResourceOp(node.resource.Type, \"create\"))\n * ```\n */\nexport const recordResourceOp = (resourceType, op) => (self) => Effect.suspend(() => {\n const startNs = process.hrtime.bigint();\n const baseAttrs = { resource_type: resourceType, op };\n return self.pipe(Effect.onExit((exit) => recordOutcome(baseAttrs, Exit.isSuccess(exit) ? \"success\" : \"error\", elapsed(startNs))));\n});\n/**\n * Wraps a CLI command Effect to bump {@link cliCounter} with the\n * outcome (`success`/`error`).\n */\nexport const recordCli = (command) => (self) => self.pipe(Effect.onExit((exit) => Metric.update(Metric.withAttributes(cliCounter, {\n command,\n status: Exit.isSuccess(exit) ? \"success\" : \"error\",\n}), 1)));\n/**\n * Wraps a Cloudflare State Store deploy/bootstrap Effect to bump\n * {@link stateStoreCounter} with the outcome (`success`/`error`),\n * tagged with the given `op`.\n */\nexport const recordStateStoreOp = (op) => (self) => self.pipe(Effect.onExit((exit) => Metric.update(Metric.withAttributes(stateStoreCounter, {\n op,\n status: Exit.isSuccess(exit) ? \"success\" : \"error\",\n}), 1)));\n/**\n * Wraps a State store construction Effect to:\n *\n * 1. Bump {@link stateStoreInitCounter} tagged with `id`.\n * 2. Open a `state_store.init` span carrying\n * `alchemy.state_store.id` so Axiom (which can't query metric\n * datasets via APL) can group projects by backend.\n *\n * The `id` is read off the constructed `StateService.id` field, so any\n * third-party state-store implementation gets tracked just by setting\n * a stable slug there. Apply at every `Layer.effect(State, …)` site\n * exactly once.\n */\nexport const recordStateStoreInit = (self) => self.pipe(Effect.tap((service) => Effect.all([\n Metric.update(Metric.withAttributes(stateStoreInitCounter, { id: service.id }), 1),\n Effect.annotateCurrentSpan(\"alchemy.state_store.id\", service.id),\n], { discard: true })), Effect.withSpan(\"state_store.init\"));\nconst elapsed = (startNs) => Duration.nanos(process.hrtime.bigint() - startNs);\nconst recordOutcome = (baseAttrs, status, duration) => {\n const attrs = { ...baseAttrs, status };\n return Effect.all([\n Metric.update(Metric.withAttributes(resourceCounter, attrs), 1),\n Metric.update(Metric.withAttributes(resourceDuration, attrs), duration),\n ], { discard: true });\n};\n//# sourceMappingURL=Metrics.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { toFqn } from \"./FQN.js\";\nimport { CurrentNamespace } from \"./Namespace.js\";\nimport * as Output from \"./Output.js\";\nimport { Stack } from \"./Stack.js\";\nexport const isAction = (value) => typeof value === \"object\" && value !== null && value?.Kind === \"action\";\nexport function Action(...args) {\n if (args.length === 0) {\n // Tagged form: Action<Self, In, Out>()(type)\n return (type) => makeActionClass(type, undefined);\n }\n // Inline form: Action(type, runnerOrInit)\n const [type, initOrRun] = args;\n return makeActionClass(type, initOrRun);\n}\nconst isRunnerEffect = (v) => Effect.isEffect(v);\nconst makeActionClass = (type, baked) => {\n // Pre-resolve baked init/runner into a single Effect<Runner, _, Req>. Use\n // Effect.cached so the init's body runs at most once per process — every\n // action instance after the first reuses the resolved runner without paying\n // the init cost (or re-yielding its dependencies).\n let resolveRunner;\n if (baked !== undefined) {\n resolveRunner = isRunnerEffect(baked)\n ? Effect.runSync(Effect.cached(baked))\n : Effect.succeed(baked);\n }\n // Tagged form needs a Context tag so the user can supply the runner\n // through a Layer. Inline form bakes the runner in and skips the tag.\n const SelfTag = baked\n ? undefined\n : Context.Service(`alchemy/Action<${type}>`);\n const constructor = (...args) => {\n const [id, input] = args.length === 1 ? [type, args[0]] : args;\n return Effect.gen(function* () {\n const run = resolveRunner\n ? yield* resolveRunner\n : (yield* SelfTag);\n return yield* registerAction(type, id, input, run);\n });\n };\n const extra = { Type: type };\n if (SelfTag) {\n extra.Self = SelfTag;\n // `.make(initOrRun)` — accepts either a direct runner or an init Effect.\n // For init form we use `Layer.effect` so the init's Req surfaces on the\n // Layer; for runners we use `Layer.succeed`.\n extra.make = (initOrRun) => isRunnerEffect(initOrRun)\n ? Layer.effect(SelfTag, initOrRun)\n : Layer.succeed(SelfTag, initOrRun);\n }\n return Object.assign(constructor, extra);\n};\nconst registerAction = (type, id, input, run) => Effect.gen(function* () {\n const stack = yield* Stack;\n const namespace = yield* CurrentNamespace;\n const fqn = toFqn(namespace, id);\n const actions = (stack.actions ??= {});\n const existing = actions[fqn];\n if (existing)\n return Output.of(existing);\n // FQN collision check: actions share the same FQN namespace as resources\n // so the dependency graph stays unified. Rejecting overlaps here makes\n // the constraint obvious at registration time.\n if (stack.resources[fqn]) {\n return yield* Effect.die(new Error(`Action '${fqn}' collides with a Resource of the same logical id`));\n }\n const target = {\n Kind: \"action\",\n Type: type,\n Namespace: namespace,\n FQN: fqn,\n LogicalId: id,\n Input: input,\n Run: run,\n Output: undefined,\n };\n target.toString = () => `Action<${type}>(${id})`;\n actions[fqn] = target;\n // `yield* Sync({...})` returns `Output<Out>`. The engine writes the\n // materialized value into `tracker[fqn]` during apply; `Output.of(action)`\n // resolves a ResourceExpr by looking up `outputs[fqn]` — which is\n // precisely that materialized value. Property access into the returned\n // Output chains through the standard PropExpr proxy.\n return Output.of(target);\n});\n//# sourceMappingURL=Action.js.map","import { createHash } from \"node:crypto\";\nimport * as Effect from \"effect/Effect\";\n/**\n * Stable hash of a resolved Task input. Wrapped in `Effect.sync` so the\n * call participates in the Effect runtime (tracing/interruption) per the\n * Effect-platform conventions.\n */\nexport const hashInput = (input) => Effect.sync(() => createHash(\"sha256\")\n .update(JSON.stringify(input ?? null))\n .digest(\"hex\"));\n//# sourceMappingURL=hash.js.map","/**\n * Compute the set of graph nodes that participate in a dependency cycle.\n *\n * A node is considered \"in a cycle\" iff it sits in a strongly-connected\n * component (SCC) of size > 1, or has a self-edge (size-1 SCC that loops\n * back to itself).\n *\n * Implementation is iterative Tarjan's algorithm to avoid blowing the JS\n * call stack on very wide graphs.\n */\nexport const findCycleMembers = (edges) => {\n const cycleMembers = new Set();\n let index = 0;\n const indexOf = new Map();\n const lowlink = new Map();\n const onStack = new Set();\n const stack = [];\n const callStack = [];\n const startNode = (node) => {\n indexOf.set(node, index);\n lowlink.set(node, index);\n index += 1;\n stack.push(node);\n onStack.add(node);\n callStack.push({ node, childIdx: 0 });\n };\n for (const root of Object.keys(edges)) {\n if (indexOf.has(root))\n continue;\n startNode(root);\n while (callStack.length > 0) {\n const frame = callStack[callStack.length - 1];\n const children = edges[frame.node] ?? [];\n if (frame.childIdx < children.length) {\n const child = children[frame.childIdx];\n frame.childIdx += 1;\n if (!indexOf.has(child)) {\n startNode(child);\n continue;\n }\n if (onStack.has(child)) {\n lowlink.set(frame.node, Math.min(lowlink.get(frame.node), indexOf.get(child)));\n }\n continue;\n }\n // All children processed: maybe close an SCC.\n if (lowlink.get(frame.node) === indexOf.get(frame.node)) {\n const scc = [];\n for (;;) {\n const w = stack.pop();\n onStack.delete(w);\n scc.push(w);\n if (w === frame.node)\n break;\n }\n if (scc.length > 1) {\n for (const fqn of scc)\n cycleMembers.add(fqn);\n }\n else {\n // Size-1 SCC: only counts as a cycle if it has a self-edge.\n const only = scc[0];\n if ((edges[only] ?? []).includes(only)) {\n cycleMembers.add(only);\n }\n }\n }\n // Pop frame and propagate lowlink up to the parent.\n callStack.pop();\n const parent = callStack[callStack.length - 1];\n if (parent) {\n const cur = lowlink.get(parent.node);\n const childLow = lowlink.get(frame.node);\n if (childLow < cur)\n lowlink.set(parent.node, childLow);\n }\n }\n }\n return cycleMembers;\n};\n//# sourceMappingURL=scc.js.map","import * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport { asEffect } from \".//Util/types.js\";\nimport { AdoptPolicy, OwnedBySomeoneElse, stripUnowned, Unowned, } from \"./AdoptPolicy.js\";\nimport { AlchemyContext } from \"./AlchemyContext.js\";\nimport { Artifacts, ArtifactStore, createArtifactStore, ensureArtifactStore, makeScopedArtifacts, } from \"./Artifacts.js\";\nimport { diffBindings, havePropsChanged, isResolved, } from \"./Diff.js\";\nimport { parseFqn } from \"./FQN.js\";\nimport { generateInstanceId, InstanceId } from \"./InstanceId.js\";\nimport * as Output from \"./Output.js\";\nimport { findProviderByType, Provider, } from \"./Provider.js\";\nimport { isResource, } from \"./Resource.js\";\nimport {} from \"./Stack.js\";\nimport { State, isActionState, } from \"./State/index.js\";\nimport { isAction } from \"./Action.js\";\nimport { hashInput } from \"./Util/hash.js\";\nimport { findCycleMembers } from \"./Util/scc.js\";\nexport const isCRUD = (node) => {\n return (node &&\n typeof node === \"object\" &&\n (node.action === \"create\" ||\n node.action === \"update\" ||\n node.action === \"replace\" ||\n node.action === \"noop\"));\n};\nexport const make = (stack, options = {}) => \n// @ts-expect-error\nEffect.gen(function* () {\n const state = yield* State;\n const resources = Object.values(stack.resources);\n const actions = Object.values(stack.actions ?? {});\n // TODO(sam): rename terminology to Stack\n const stackName = stack.name;\n const stage = stack.stage;\n // Resolve the effective adoption setting for this plan. AdoptPolicy\n // (provided by the CLI or scoped via `adopt(...)`) takes precedence; if\n // unset, fall back to the AlchemyContext's `adopt` default; otherwise\n // adoption is disabled.\n const shouldAdopt = Effect.gen(function* () {\n const fromService = yield* Effect.serviceOption(AdoptPolicy);\n if (Option.isSome(fromService))\n return fromService.value;\n const ctx = yield* Effect.serviceOption(AlchemyContext);\n return Option.match(ctx, {\n onNone: () => false,\n onSome: (c) => c.adopt,\n });\n });\n const resourceFqns = yield* state.list({\n stack: stackName,\n stage: stage,\n });\n const oldResources = yield* Effect.all(resourceFqns.map((fqn) => state.get({ stack: stackName, stage: stage, fqn })), { concurrency: \"unbounded\" });\n const resolvedResources = {};\n const resolveResource = (resourceExpr) => Effect.gen(function* () {\n // Tasks share the ResourceExpr machinery but have no provider /\n // stable-properties story at plan time. Leave the expression\n // unsubstituted — Apply resolves it from the tracker at run time.\n if (isAction(resourceExpr.src)) {\n return resourceExpr;\n }\n // @ts-expect-error\n return yield* (resolvedResources[resourceExpr.src.FQN] ??=\n yield* Effect.cached(Effect.gen(function* () {\n const resource = resourceExpr.src;\n const provider = yield* findProviderByType(resource.Type);\n const props = yield* resolveInput(resource.Props);\n const persisted = yield* state.get({\n stack: stackName,\n stage: stage,\n fqn: resource.FQN,\n });\n const oldState = isActionState(persisted)\n ? undefined\n : persisted;\n if (!oldState || oldState.status === \"creating\") {\n return resourceExpr;\n }\n const oldProps = oldState.status === \"updating\"\n ? oldState.old.props\n : oldState.props;\n const oldBindings = oldState.bindings ?? [];\n const newBindings = stack.bindings[resource.FQN] ?? [];\n const diff = yield* provider.diff\n ? provider\n .diff({\n id: resource.LogicalId,\n olds: oldProps,\n instanceId: oldState.instanceId,\n news: props,\n output: oldState.attr,\n oldBindings,\n newBindings,\n })\n .pipe(providePlanScope(resource.FQN, oldState.instanceId))\n : Effect.succeed(undefined);\n const stables = [\n ...(provider.stables ?? []),\n ...(diff?.stables ?? []),\n ];\n const withStables = (output) => stables.length > 0\n ? new Output.ResourceExpr(resourceExpr.src, Object.fromEntries(stables.map((stable) => [stable, output?.[stable]])))\n : // if there are no stable properties, treat every property as changed\n resourceExpr;\n if (diff == null) {\n if (havePropsChanged(oldProps, props)) {\n // the props have changed but the provider did not provide any hints as to what is stable\n // so we must assume everything has changed\n return withStables(oldState?.attr);\n }\n }\n else if (diff.action === \"update\") {\n return withStables(oldState?.attr);\n }\n else if (diff.action === \"replace\") {\n return resourceExpr;\n }\n if (oldState.status === \"created\" ||\n oldState.status === \"updated\" ||\n oldState.status === \"replaced\") {\n // we can safely return the attributes if we know they have stabilized\n return oldState?.attr;\n }\n else {\n // we must assume the resource doesn't exist if it hasn't stabilized\n return resourceExpr;\n }\n })));\n });\n const resolveInput = (input) => Effect.gen(function* () {\n if (!input) {\n return input;\n }\n else if (Output.isExpr(input)) {\n return yield* resolveOutput(input);\n }\n else if (Redacted.isRedacted(input)) {\n return input;\n }\n else if (Array.isArray(input)) {\n return yield* Effect.all(input.map(resolveInput), {\n concurrency: \"unbounded\",\n });\n }\n else if (isResource(input)) {\n // Resource objects have dynamic properties (path, hash, etc.) that are\n // created on-demand by a Proxy getter and aren't enumerable via Object.entries.\n // Resolve the ResourceExpr to get the actual resource output, then continue\n // resolving any nested outputs in the result.\n const resourceExpr = Output.of(input);\n const resolved = yield* resolveOutput(resourceExpr);\n return yield* resolveInput(resolved);\n }\n else if (typeof input === \"object\") {\n return Object.fromEntries(yield* Effect.all(Object.entries(input).map(([key, value]) => resolveInput(value).pipe(Effect.map((value) => [key, value]))), { concurrency: \"unbounded\" }));\n }\n return input;\n });\n const resolveOutput = (expr) => Effect.gen(function* () {\n if (Output.isResourceExpr(expr)) {\n return yield* resolveResource(expr);\n }\n else if (Output.isPropExpr(expr)) {\n const upstream = yield* resolveOutput(expr.expr);\n return upstream?.[expr.identifier];\n }\n else if (Output.isApplyExpr(expr)) {\n const upstream = yield* resolveOutput(expr.expr);\n return Output.hasOutputs(upstream) ? expr : expr.f(upstream);\n }\n else if (Output.isEffectExpr(expr)) {\n const upstream = yield* resolveOutput(expr.expr);\n return Output.hasOutputs(upstream) ? expr : yield* expr.f(upstream);\n }\n else if (Output.isAllExpr(expr)) {\n return yield* Effect.all(expr.outs.map(resolveOutput), {\n concurrency: \"unbounded\",\n });\n }\n else if (Output.isLiteralExpr(expr)) {\n return expr.value;\n }\n else if (Output.isRefExpr(expr)) {\n const refStack = expr.stack ?? stackName;\n const refStage = expr.stage ?? stage;\n const refState = yield* state\n .get({\n stack: refStack,\n stage: refStage,\n fqn: expr.resourceId,\n })\n .pipe(Effect.orDie);\n if (!refState) {\n return yield* Effect.die(new Output.InvalidReferenceError({\n message: `Reference to '${expr.resourceId}' in stack '${refStack}' and stage '${refStage}' not found. Have you deployed '${refStage}' of '${refStack}'?`,\n stack: refStack,\n stage: refStage,\n resourceId: expr.resourceId,\n }));\n }\n return refState.attr ?? refState.output;\n }\n else if (Output.isStackRefExpr(expr)) {\n const refStack = expr.stack;\n const refStage = expr.stage ?? stage;\n const output = yield* state\n .getOutput({\n stack: refStack,\n stage: refStage,\n })\n .pipe(Effect.orDie);\n if (output == null) {\n return yield* Effect.die(new Output.InvalidReferenceError({\n message: `Reference to stack '${refStack}' at stage '${refStage}' not found. Have you deployed stage '${refStage}' of '${refStack}'?`,\n stack: refStack,\n stage: refStage,\n resourceId: refStack,\n }));\n }\n return output;\n }\n else if (Output.isNamedExpr(expr)) {\n return yield* resolveOutput(expr.expr);\n }\n return yield* Effect.die(new Error(\"Not implemented yet\" + expr.kind));\n });\n // map of resource FQN -> its downstream dependencies (resources that depend on it)\n const oldDownstreamDependencies = Object.fromEntries(oldResources\n .filter((resource) => !!resource)\n .map((resource) => [resource.fqn, resource.downstream]));\n // Build a set of FQNs for the new resources to detect orphans\n const newResourceFqns = new Set(resources.map((r) => r.FQN));\n const newActionFqns = new Set(actions.map((t) => t.FQN));\n // Unified set used wherever the DAG must include both kinds.\n const newNodeFqns = new Set([...newResourceFqns, ...newActionFqns]);\n // Map FQN -> list of upstream FQNs (resources this one depends on via props).\n // Tasks contribute upstream edges through their `Input` expression.\n const newUpstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => [\n resource.FQN,\n Object.values(Output.upstreamAny(resource.Props)).map((r) => r.FQN),\n ]),\n ...actions.map((action) => [\n action.FQN,\n Object.values(Output.upstreamAny(action.Input)).map((r) => r.FQN),\n ]),\n ]);\n // Map FQN -> list of upstream FQNs from bindings\n const bindingUpstreamDependencies = Object.fromEntries(resources.map((resource) => [\n resource.FQN,\n Object.values(Output.upstreamAny(stack.bindings[resource.FQN] ?? [])).map((r) => r.FQN),\n ]));\n // Combined prop + binding upstream for the desired graph, including\n // references to resources outside the current graph so delete validation can\n // tell whether any surviving resource still points at an orphan.\n const rawUpstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => {\n const fqn = resource.FQN;\n const propDeps = newUpstreamDependencies[fqn] ?? [];\n const bindDeps = bindingUpstreamDependencies[fqn] ?? [];\n return [fqn, [...new Set([...propDeps, ...bindDeps])]];\n }),\n // Actions have no bindings — their upstream is purely their input.\n ...actions.map((action) => {\n const fqn = action.FQN;\n return [fqn, newUpstreamDependencies[fqn] ?? []];\n }),\n ]);\n // Combined prop + binding upstream, filtered to resources/tasks in this\n // graph for scheduling and cycle detection.\n const allUpstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => {\n const fqn = resource.FQN;\n const deps = rawUpstreamDependencies[fqn] ?? [];\n return [fqn, deps.filter((dep) => newNodeFqns.has(dep))];\n }),\n ...actions.map((action) => {\n const fqn = action.FQN;\n const deps = newUpstreamDependencies[fqn] ?? [];\n return [fqn, deps.filter((dep) => newNodeFqns.has(dep))];\n }),\n ]);\n // Resources that participate in a cycle when both prop and binding\n // edges are considered. Used below to decide whether an acyclic\n // binding edge should also become a downstream edge.\n const combinedCycleMembers = findCycleMembers(allUpstreamDependencies);\n // Map FQN -> list of downstream FQNs (resources/actions that depend on\n // this one).\n //\n // Prop edges always become downstream edges — they can't form cycles\n // (the resource graph is a DAG by construction once props are fully\n // resolved). Binding edges become downstream edges too, except when\n // they participate in a cycle in the combined graph: mutual bindings\n // (A binds to B's data, B binds to A's data) intentionally do not\n // create downstream edges, so deletion does not deadlock waiting on\n // each other (see the \"binding-only cycles inside a construct\" test\n // in `plan.test.ts`).\n //\n // Including acyclic binding edges is required for cloud APIs that\n // enforce the binding at the provider level — e.g. a Cloudflare\n // Worker with a `service` binding to another Worker cannot delete\n // the upstream worker until the downstream worker's binding has been\n // removed. Without the binding edge in `downstream`, the two delete\n // concurrently and the upstream delete fails with\n // `ServiceBindingConflict`.\n //\n // Actions don't have bindings, so for action upstreams we use only\n // prop edges (which collapse to `newUpstreamDependencies` lookups).\n const computeDownstream = (upFqn) => {\n const downstream = [];\n for (const [downFqn, upstreams] of Object.entries(rawUpstreamDependencies)) {\n if (downFqn === upFqn)\n continue;\n if (!upstreams.includes(upFqn))\n continue;\n const isPropEdge = (newUpstreamDependencies[downFqn] ?? []).includes(upFqn);\n if (isPropEdge) {\n downstream.push(downFqn);\n continue;\n }\n // Binding-only edge — exclude when both endpoints sit inside\n // the same SCC of the combined graph.\n if (combinedCycleMembers.has(upFqn) &&\n combinedCycleMembers.has(downFqn)) {\n continue;\n }\n downstream.push(downFqn);\n }\n return downstream;\n };\n const newDownstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => [resource.FQN, computeDownstream(resource.FQN)]),\n ...actions.map((action) => [action.FQN, computeDownstream(action.FQN)]),\n ]);\n const resourceGraph = Object.fromEntries((yield* Effect.all(resources.map(Effect.fn(\"plan.diff.resource\")(function* (resource) {\n const provider = yield* findProviderByType(resource.Type);\n const id = resource.LogicalId;\n const fqn = resource.FQN;\n const news = yield* resolveInput(resource.Props);\n const downstream = newDownstreamDependencies[fqn] ?? [];\n const newBindings = yield* resolveInput(stack.bindings[fqn] ?? []);\n const persisted = yield* state.get({\n stack: stackName,\n stage: stage,\n fqn,\n });\n // A Task previously held this FQN. Treat as if there were no\n // prior state — the Task's row will be reaped by `actionDeletions`\n // below and the resource starts from scratch.\n let oldState = isActionState(persisted)\n ? undefined\n : persisted;\n // Engine-level adoption. When there is no prior state, always\n // consult `provider.read` (if implemented) so the engine — not\n // each lifecycle method — owns the existence/ownership decision.\n //\n // The provider returns one of:\n // - `undefined` → resource doesn't exist; create it\n // - plain attrs → exists and is owned by us; silent adopt\n // - `Unowned(attrs)` → exists but is *not* ours\n //\n // Routing:\n // - owned → persist `created` state\n // from attrs and continue\n // through the normal diff\n // path (so subsequent props\n // drift produces an update).\n // - unowned + adopt enabled → take over: persist `created`\n // state and let the next\n // update overwrite tags / etc.\n // - unowned + adopt disabled → fail with\n // `OwnedBySomeoneElse`.\n // After a cold-start adoption (engine just discovered an\n // existing cloud resource via `read`), force the engine's\n // normal `update` path so the provider can re-sync ownership\n // tags, configuration, etc. against the desired props.\n // Adoption persists state with `props: news`, so the default\n // diff sees no drift and would noop — which would leave any\n // foreign-owned tags / divergent config in place. Forcing\n // update keeps the deploy idempotent: if cloud state already\n // matches news, the provider's update is a no-op write.\n //\n // Skip the adoption probe entirely when `news` still contains\n // unresolved upstream Outputs (e.g. a `streamArn` referencing\n // a stream being created in the same plan). Calling `read` with\n // an unresolved value would surface as `ParseError` from the\n // SDK protocol layer. Resources whose props depend on\n // not-yet-created upstreams cannot themselves be pre-existing\n // — there's nothing to adopt.\n let forceUpdateAfterAdoption = false;\n if (oldState === undefined && provider.read && isResolved(news)) {\n const adoptInstanceId = yield* generateInstanceId();\n const readResult = yield* provider\n .read({\n id,\n instanceId: adoptInstanceId,\n olds: news,\n output: undefined,\n })\n .pipe(providePlanScope(fqn, adoptInstanceId));\n if (readResult !== undefined) {\n const isUnowned = Unowned.is(readResult);\n if (isUnowned && !(yield* shouldAdopt)) {\n return yield* new OwnedBySomeoneElse({\n message: `Cannot adopt resource '${fqn}' (${resource.Type}): ` +\n \"it exists in the cloud but is not owned by this \" +\n \"stack/stage/logical-id. Re-run with `--adopt` (or \" +\n \"wrap the effect in `adopt(true)`) to take it over.\",\n resourceType: resource.Type,\n logicalId: id,\n });\n }\n const adoptedState = {\n status: \"created\",\n fqn,\n logicalId: id,\n instanceId: adoptInstanceId,\n namespace: resource.Namespace,\n resourceType: resource.Type,\n props: news,\n attr: stripUnowned(readResult),\n providerVersion: provider.version ?? 0,\n bindings: [],\n downstream,\n removalPolicy: resource.RemovalPolicy,\n };\n yield* state.set({\n stack: stackName,\n stage: stage,\n fqn,\n value: adoptedState,\n });\n oldState = adoptedState;\n forceUpdateAfterAdoption = true;\n }\n }\n const oldBindings = oldState?.bindings ?? [];\n const bindingDiffs = diffBindings(oldBindings, newBindings);\n const Node = (node) => ({\n ...node,\n provider,\n resource,\n bindings: bindingDiffs,\n downstream,\n });\n // Plan against the persisted state we have, not the ideal final state we\n // hoped to reach last time. Recovery is expressed by mapping each\n // intermediate state back onto a fresh CRUD action.\n if (oldState === undefined) {\n return Node({\n action: \"create\",\n props: news,\n state: oldState,\n });\n }\n else if (oldState.status === \"creating\" &&\n oldState.attr === undefined) {\n // A create may have succeeded before state persistence failed. If the\n // provider can recover an attribute snapshot, keep driving the same\n // create instead of starting over blindly.\n if (provider.read) {\n const attr = yield* provider\n .read({\n id,\n instanceId: oldState.instanceId,\n olds: oldState.props,\n output: oldState.attr,\n })\n .pipe(providePlanScope(fqn, oldState.instanceId));\n if (attr) {\n return Node({\n action: \"create\",\n props: news,\n state: { ...oldState, attr },\n });\n }\n }\n }\n // Diff against whatever props represent the best-known current attempt.\n // For replacement recovery that means the top-level replacement props,\n // not the older generations stored under `old`.\n const oldProps = oldState.props;\n const diff = yield* asEffect(provider\n ?.diff?.({\n id,\n olds: oldProps,\n instanceId: oldState.instanceId,\n output: oldState.attr,\n news,\n oldBindings,\n newBindings,\n })\n .pipe(providePlanScope(fqn, oldState.instanceId))).pipe(Effect.map((diff) => diff ??\n {\n action: havePropsChanged(oldProps, news) ||\n bindingDiffs.some((b) => b.action !== \"noop\")\n ? \"update\"\n : \"noop\",\n }), Effect.map((diff) => options.force && diff.action === \"noop\"\n ? {\n action: \"update\",\n }\n : diff), \n // After a cold-start adoption (silent or takeover), force at\n // least an update so the provider re-syncs ownership tags /\n // config against the desired props (otherwise the engine\n // would noop and any drift between the existing cloud\n // resource and `news` — including foreign-owned tags after a\n // takeover — would persist).\n Effect.map((diff) => forceUpdateAfterAdoption && diff.action === \"noop\"\n ? { action: \"update\" }\n : diff));\n if (oldState.status === \"creating\") {\n if (diff.action === \"noop\") {\n // we're in the creating state and props are un-changed\n // let's just continue where we left off\n return Node({\n action: \"create\",\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"update\") {\n // props have changed in a way that is updatable\n // again, just continue with the create\n // TODO(sam): should we maybe try an update instead?\n return Node({\n action: \"create\",\n props: news,\n state: oldState,\n });\n }\n else {\n // props have changed in an incompatible way\n // because it's possible that an un-updatable resource has already been created\n // we must use a replace step to create a new one and delete the potential old one\n return Node({\n action: \"replace\",\n props: news,\n deleteFirst: diff.deleteFirst ?? false,\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"updating\") {\n // Updating already targets the live resource, so noop/update both mean\n // \"finish the interrupted update\". Only a replace diff escalates it\n // into a fresh replacement.\n if (diff.action === \"update\" || diff.action === \"noop\") {\n // we can continue where we left off\n return Node({\n action: \"update\",\n props: news,\n state: oldState,\n });\n }\n else {\n // we started to update a resource but now believe we should replace it\n return Node({\n action: \"replace\",\n deleteFirst: diff.deleteFirst ?? false,\n props: news,\n // TODO(sam): can Apply handle replacements when the oldState is UpdatingResourceState?\n // -> or should we do a provider.read to try and reconcile back to UpdatedResourceState?\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"replacing\") {\n // The replacement candidate is still being created. Noop/update keep\n // driving the same generation; replace means that candidate itself is\n // now obsolete and must be wrapped in a new outer generation.\n if (diff.action === \"noop\") {\n // this is the stable case - noop means just continue with the replacement\n return Node({\n action: \"replace\",\n deleteFirst: oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"update\") {\n // potential problem here - the props have changed since we tried to replace,\n // but not enough to trigger another replacement. the resource provider should\n // be designed as idempotent to converge to the right state when creating the new resource\n // the newly generated instanceId is intended to assist with this\n return Node({\n action: \"replace\",\n deleteFirst: oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n else {\n // The in-flight replacement candidate itself now needs replacement.\n // Mark this as a restart so Apply creates a fresh generation instead\n // of resuming the old replacement instance.\n return Node({\n restart: true,\n action: \"replace\",\n deleteFirst: diff.deleteFirst ?? oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"replaced\") {\n // The new resource already exists. Noop means \"just let GC finish\",\n // update means \"mutate the current replacement before GC finishes\",\n // and replace means \"the current replacement also became obsolete\".\n if (diff.action === \"noop\") {\n // this is the stable case - noop means just continue cleaning up the replacement\n return Node({\n action: \"replace\",\n deleteFirst: oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"update\") {\n // the replacement has been created but now also needs to be updated\n // the resource provider should:\n // 1. Update the newly created replacement resource\n // 2. Then proceed as normal to delete the replaced resources (after all downstream references are updated)\n return Node({\n action: \"update\",\n props: news,\n state: oldState,\n });\n }\n else {\n // Cleanup is still pending, but the current \"new\" resource has already\n // become obsolete. Start another replacement generation and preserve\n // the existing replaced node as part of the recursive old chain.\n return Node({\n restart: true,\n action: \"replace\",\n deleteFirst: diff.deleteFirst ?? oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"deleting\") {\n // we're in a partially deleted state, it is unclear whether it was or was not deleted\n // so continue by re-creating it with the same instanceId and desired props\n return Node({\n action: \"create\",\n props: news,\n state: {\n ...oldState,\n status: \"creating\",\n props: news,\n },\n });\n }\n else if (diff.action === \"update\") {\n // Stable created/updated resources follow the normal CRUD mapping.\n return Node({\n action: \"update\",\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"replace\") {\n return Node({\n action: \"replace\",\n props: news,\n state: oldState,\n deleteFirst: diff?.deleteFirst ?? false,\n });\n }\n else {\n return Node({\n action: \"noop\",\n state: oldState,\n });\n }\n })), { concurrency: \"unbounded\" })).map((update) => [update.resource.FQN, update]));\n // ── Action plan nodes ────────────────────────────────────────────────\n const actionGraph = Object.fromEntries((yield* Effect.all(actions.map(Effect.fn(\"plan.diff.action\")(function* (action) {\n const fqn = action.FQN;\n const downstream = newDownstreamDependencies[fqn] ?? [];\n const resolvedInput = yield* resolveInput(action.Input);\n const inputHash = yield* hashInput(resolvedInput);\n const oldState = yield* state.get({\n stack: stackName,\n stage,\n fqn,\n });\n if (oldState && !isActionState(oldState)) {\n // FQN collision with a resource — surface as a fatal error so\n // the user resolves it before we touch anything.\n return [\n fqn,\n {\n kind: \"action\",\n action: \"run\",\n def: action,\n input: action.Input,\n state: undefined,\n downstream,\n forced: false,\n },\n ];\n }\n const prior = oldState;\n const sameInput = prior?.status === \"ran\" && prior.inputHash === inputHash;\n if (sameInput && !options.force) {\n return [\n fqn,\n {\n kind: \"action\",\n action: \"noop\",\n def: action,\n state: prior,\n downstream,\n },\n ];\n }\n return [\n fqn,\n {\n kind: \"action\",\n action: \"run\",\n def: action,\n input: action.Input,\n state: prior,\n downstream,\n forced: !!options.force,\n },\n ];\n })), { concurrency: \"unbounded\" })));\n // SCC membership of the combined upstream graph. Apply uses it to\n // decide whether an update node must publish its prior attr early to\n // break a cycle, or can simply wait for upstreams like a DAG node\n // (the common case). Computed once, above, for the downstream graph.\n const cycleMembers = combinedCycleMembers;\n // Detect unsatisfiable dependency cycles among create/replace nodes.\n // Update/noop nodes signal their Deferred before waitForDeps when in a\n // cycle so they cannot deadlock. Create/replace nodes only signal\n // early when they have a precreate handler. Simulate the concurrent\n // execution: precreate nodes are immediately \"resolved\", then\n // iteratively resolve any node whose deps are all resolved. Remaining\n // nodes would deadlock.\n {\n const createReplaceNodes = new Set(Object.entries(resourceGraph)\n .filter(([_, node]) => node.action === \"create\" || node.action === \"replace\")\n .map(([fqn]) => fqn));\n if (createReplaceNodes.size > 0) {\n const hasPrecreate = new Set([...createReplaceNodes].filter((fqn) => !!resourceGraph[fqn]?.provider?.precreate));\n const resolved = new Set(hasPrecreate);\n let changed = true;\n while (changed) {\n changed = false;\n for (const fqn of createReplaceNodes) {\n if (resolved.has(fqn))\n continue;\n const deps = (allUpstreamDependencies[fqn] ?? []).filter((dep) => createReplaceNodes.has(dep));\n if (deps.every((dep) => resolved.has(dep))) {\n resolved.add(fqn);\n changed = true;\n }\n }\n }\n const deadlocked = [...createReplaceNodes].filter((fqn) => !resolved.has(fqn));\n if (deadlocked.length > 0) {\n const missingPrecreate = deadlocked.filter((fqn) => !hasPrecreate.has(fqn));\n return yield* Effect.die(new UnsatisfiedResourceCycle({\n message: `Circular dependency detected that cannot be resolved: [${deadlocked.join(\", \")}]. ` +\n `Resources lacking a precreate handler: [${missingPrecreate.join(\", \")}]. ` +\n `All resources in a dependency cycle must implement precreate to allow early signaling.`,\n cycle: deadlocked,\n missingPrecreate,\n }));\n }\n }\n }\n // Task deletions: state rows previously written by tasks that no\n // longer appear in the stack. The body is NOT invoked — we just drop\n // the row.\n const actionDeletions = Object.fromEntries((yield* Effect.all((yield* state.list({ stack: stackName, stage })).map(Effect.fn(\"plan.diff.actionDeletion\")(function* (fqn) {\n if (newActionFqns.has(fqn) || newResourceFqns.has(fqn))\n return;\n const persisted = yield* state.get({\n stack: stackName,\n stage,\n fqn,\n });\n if (!isActionState(persisted))\n return;\n const { logicalId } = parseFqn(fqn);\n return [\n fqn,\n {\n kind: \"action\",\n action: \"delete\",\n state: persisted,\n downstream: persisted.downstream ?? [],\n def: {\n Kind: \"action\",\n Namespace: persisted.namespace,\n FQN: fqn,\n LogicalId: logicalId,\n Type: persisted.actionType,\n Input: persisted.input,\n Run: () => undefined,\n Output: undefined,\n },\n },\n ];\n })), { concurrency: \"unbounded\" })).filter((v) => !!v));\n const deletions = Object.fromEntries((yield* Effect.all((yield* state.list({ stack: stackName, stage: stage })).map(Effect.fn(\"plan.diff.deletion\")(function* (fqn) {\n if (newResourceFqns.has(fqn) || newActionFqns.has(fqn)) {\n return;\n }\n const persisted = yield* state.get({\n stack: stackName,\n stage: stage,\n fqn,\n });\n // Tasks are routed through `actionDeletions` above.\n if (isActionState(persisted))\n return;\n const oldState = persisted;\n let attr = oldState?.attr;\n if (oldState) {\n const { logicalId } = parseFqn(fqn);\n const resourceType = oldState.resourceType;\n const provider = yield* findProviderByType(resourceType);\n if (oldState.attr === undefined) {\n if (provider.read) {\n attr = yield* provider\n .read({\n id: logicalId,\n instanceId: oldState.instanceId,\n olds: oldState.props,\n output: oldState.attr,\n })\n .pipe(providePlanScope(fqn, oldState.instanceId));\n }\n }\n return [\n fqn,\n {\n action: \"delete\",\n state: { ...oldState, attr },\n provider: provider,\n resource: {\n Namespace: oldState.namespace,\n FQN: fqn,\n LogicalId: logicalId,\n Type: oldState.resourceType,\n Attributes: attr,\n Props: oldState.props,\n Binding: undefined,\n Provider: Provider(resourceType),\n RemovalPolicy: oldState.removalPolicy,\n RuntimeContext: undefined,\n Providers: undefined,\n },\n downstream: oldDownstreamDependencies[fqn] ?? [],\n bindings: oldState.bindings.map((binding) => ({\n sid: binding.sid,\n action: \"delete\",\n data: binding.data,\n })),\n },\n ];\n }\n })), { concurrency: \"unbounded\" })).filter((v) => !!v));\n for (const resourceFqn of Object.keys(deletions)) {\n const dependencies = Object.entries(rawUpstreamDependencies)\n .filter(([survivorFqn, upstream]) => survivorFqn in resourceGraph && upstream.includes(resourceFqn))\n .map(([survivorFqn]) => survivorFqn);\n if (dependencies.length > 0) {\n return yield* new DeleteResourceHasDownstreamDependencies({\n message: `Resource ${resourceFqn} has downstream dependencies`,\n resourceId: resourceFqn,\n dependencies,\n });\n }\n }\n return {\n resources: resourceGraph,\n actions: actionGraph,\n deletions,\n actionDeletions,\n output: stack.output,\n cycleMembers,\n };\n}).pipe(ensureArtifactStore, Effect.withSpan(\"plan.make\", {\n attributes: {\n \"alchemy.stack\": stack.name,\n \"alchemy.stage\": stack.stage,\n \"alchemy.resources.count\": Object.keys(stack.resources).length,\n \"alchemy.force\": !!options.force,\n },\n}));\nconst providePlanScope = (fqn, instanceId) => (effect) => Effect.serviceOption(ArtifactStore).pipe(Effect.map(Option.getOrElse(createArtifactStore)), Effect.flatMap((store) => effect.pipe(Effect.provideService(Artifacts, makeScopedArtifacts(store, fqn)), Effect.provideService(InstanceId, instanceId))));\nexport class DeleteResourceHasDownstreamDependencies extends Data.TaggedError(\"DeleteResourceHasDownstreamDependencies\") {\n}\nexport class UnsatisfiedResourceCycle extends Data.TaggedError(\"UnsatisfiedResourceCycle\") {\n}\n// TODO(sam): compare props\n// oldBinding.props !== newBinding.props;\n/**\n * Print a plan in a human-readable format that shows the graph topology.\n */\nexport const printPlan = (plan) => {\n const lines = [];\n const allNodes = { ...plan.resources, ...plan.deletions };\n // Build reverse mapping: upstream -> downstream\n const upstreamMap = {};\n for (const [id] of Object.entries(allNodes)) {\n upstreamMap[id] = [];\n }\n for (const [id, node] of Object.entries(allNodes)) {\n if (!node)\n continue;\n for (const downstreamId of node.state?.downstream ?? []) {\n if (upstreamMap[downstreamId]) {\n upstreamMap[downstreamId].push(id);\n }\n }\n }\n // Action symbols\n const actionSymbol = (action) => {\n switch (action) {\n case \"create\":\n return \"+\";\n case \"update\":\n return \"~\";\n case \"delete\":\n return \"-\";\n case \"replace\":\n return \"±\";\n case \"noop\":\n return \"=\";\n default:\n return \"?\";\n }\n };\n // Print header\n lines.push(\"╔════════════════════════════════════════════════════════════════╗\");\n lines.push(\"║ PLAN ║\");\n lines.push(\"╠════════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Legend: + create, ~ update, - delete, ± replace, = noop, ║\");\n lines.push(\"║ λ run task, · skip task ║\");\n lines.push(\"╚════════════════════════════════════════════════════════════════╝\");\n lines.push(\"\");\n // Print resources section\n lines.push(\"┌─ Resources ────────────────────────────────────────────────────┐\");\n const resourceIds = Object.keys(plan.resources).sort();\n for (const id of resourceIds) {\n const node = plan.resources[id];\n const symbol = actionSymbol(node.action);\n const type = node.resource?.type ?? \"unknown\";\n const downstream = node.state?.downstream?.length\n ? ` → [${node.state?.downstream.join(\", \")}]`\n : \"\";\n lines.push(`│ [${symbol}] ${id} (${type})${downstream}`);\n }\n if (resourceIds.length === 0) {\n lines.push(\"│ (none)\");\n }\n lines.push(\"└────────────────────────────────────────────────────────────────┘\");\n lines.push(\"\");\n // Print tasks section\n lines.push(\"┌─ Tasks ────────────────────────────────────────────────────────┐\");\n const taskIds = Object.keys(plan.actions ?? {}).sort();\n for (const id of taskIds) {\n const node = plan.actions[id];\n const symbol = node.action === \"run\" ? \"λ\" : \"·\";\n const type = node.def.Type;\n const downstream = node.downstream.length\n ? ` → [${node.downstream.join(\", \")}]`\n : \"\";\n lines.push(`│ [${symbol}] ${id} (${type})${downstream}`);\n }\n if (taskIds.length === 0) {\n lines.push(\"│ (none)\");\n }\n lines.push(\"└────────────────────────────────────────────────────────────────┘\");\n lines.push(\"\");\n // Print deletions section\n lines.push(\"┌─ Deletions ────────────────────────────────────────────────────┐\");\n const deletionIds = Object.keys(plan.deletions).sort();\n for (const id of deletionIds) {\n const node = plan.deletions[id];\n const type = node.resource?.Type ?? \"unknown\";\n const downstream = node.state.downstream?.length\n ? ` → [${node.state.downstream.join(\", \")}]`\n : \"\";\n lines.push(`│ [-] ${id} (${type})${downstream}`);\n }\n const taskDeletionIds = Object.keys(plan.actionDeletions ?? {}).sort();\n for (const id of taskDeletionIds) {\n const node = plan.actionDeletions[id];\n lines.push(`│ [-] ${id} (${node.def.Type}) [action]`);\n }\n if (deletionIds.length === 0 && taskDeletionIds.length === 0) {\n lines.push(\"│ (none)\");\n }\n lines.push(\"└────────────────────────────────────────────────────────────────┘\");\n lines.push(\"\");\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=Plan.js.map","import * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport { Artifacts, ArtifactStore, createArtifactStore, ensureArtifactStore, makeScopedArtifacts, } from \"./Artifacts.js\";\nimport { Cli, } from \"./Cli/Cli.js\";\nimport { havePropsChanged } from \"./Diff.js\";\nimport { toFqn } from \"./FQN.js\";\nimport { generateInstanceId, InstanceId } from \"./InstanceId.js\";\nimport * as Output from \"./Output.js\";\nimport {} from \"./Plan.js\";\nimport { findProviderByType } from \"./Provider.js\";\nimport { Stack } from \"./Stack.js\";\nimport { Stage } from \"./Stage.js\";\nimport { State, StateStoreError, } from \"./State/index.js\";\nimport { recordResourceOp } from \"./Telemetry/Metrics.js\";\nimport { hashInput } from \"./Util/hash.js\";\nconst provideLifecycleScope = (fqn, instanceId) => (effect) => Effect.serviceOption(ArtifactStore).pipe(Effect.map(Option.getOrElse(createArtifactStore)), Effect.flatMap((store) => effect.pipe(Effect.provideService(Artifacts, makeScopedArtifacts(store, fqn)), Effect.provideService(InstanceId, instanceId))));\n/**\n * Instruments a single provider lifecycle call with an OTel span\n * (`provider.<op>`), the resource counter / duration histogram, and the\n * scoped artifacts/instance services normally supplied by\n * {@link provideLifecycleScope}.\n *\n * This is the only call site through which provider lifecycle methods\n * are dispatched, so wrapping it here gives us a fully-instrumented\n * toolchain without touching any individual provider implementation.\n */\nconst instrumentLifecycle = (op, fqn, resourceType, logicalId, instanceId) => (effect) => effect.pipe(provideLifecycleScope(fqn, instanceId), recordResourceOp(resourceType, op), Effect.withSpan(`provider.${op}`, {\n attributes: {\n \"alchemy.resource.fqn\": fqn,\n \"alchemy.resource.type\": resourceType,\n \"alchemy.resource.logical_id\": logicalId,\n \"alchemy.resource.instance_id\": instanceId,\n \"alchemy.resource.op\": op,\n },\n}));\nexport const apply = (plan) => Effect.gen(function* () {\n const cli = yield* Cli;\n const session = yield* cli.startApplySession(plan);\n const state = yield* State;\n const stack = yield* Stack;\n const stage = yield* Stage;\n const stackName = stack.name;\n const tracker = {};\n const terminalStatuses = new Map();\n yield* executePlan(plan, tracker, terminalStatuses, session, state, stackName, stage);\n // TODO(sam): support roll back to previous state if errors occur during expansion\n // -> RISK: some UPDATEs may not be reversible (i.e. trigger replacements)\n // TODO(sam): should pivot be done separately? E.g shift traffic?\n yield* collectGarbage(plan, session);\n yield* converge(plan, tracker, terminalStatuses, session, state, stackName, stage);\n yield* Effect.forEach(Array.from(terminalStatuses.values()), ({ id, type, status }) => session.emit({ kind: \"status-change\", id, type, status }), { concurrency: \"unbounded\" });\n yield* session.done();\n if (!plan.output) {\n return undefined;\n }\n const outputs = Object.fromEntries(Object.entries(tracker).map(([fqn, t]) => [fqn, t.output]));\n const resolved = yield* Output.evaluate(plan.output, outputs);\n // Persist the stack's evaluated outputs so cross-stack references\n // (`yield* OtherStack` / `OtherStack.stage.<name>` / `Output.stackRef`)\n // can read them back out of the state store.\n yield* state.setOutput({ stack: stackName, stage, value: resolved });\n return resolved;\n}).pipe(ensureArtifactStore, Effect.withSpan(\"apply\", {\n attributes: {\n \"alchemy.resources.count\": Object.keys(plan.resources).length,\n \"alchemy.deletions.count\": Object.keys(plan.deletions).length,\n },\n}));\n// ── Phase 1: concurrent initial execution ──────────────────────────────────\n//\n// Each resource gets a Deferred<void> that signals \"I have some output\n// available in `tracker`.\" Resources with `precreate` signal early so that\n// downstream resources can resolve stable identifiers without deadlocking.\n// The actual output lives in the mutable `tracker` map, not in the Deferred.\nconst executePlan = Effect.fnUntraced(function* (plan, tracker, terminalStatuses, session, state, stackName, stage) {\n // Resources and tasks share the same FQN namespace and DAG, so the\n // scheduler tracks them together. Each entry gets a single Deferred that\n // signals \"my output is available in `tracker`.\"\n const allNodes = {\n ...plan.resources,\n ...plan.actions,\n };\n const ready = Object.fromEntries(yield* Effect.all(Object.keys(allNodes).map((fqn) => Effect.map(Deferred.make(), (d) => [fqn, d]))));\n // `readyStable` fires only when a node has reached its TERMINAL output —\n // resources after `reconcile`, tasks after the body completes. Resource\n // precreate stubs do NOT signal `readyStable`, so any consumer that\n // requires stable inputs (e.g. Tasks) waits past the precreate phase.\n const readyStable = Object.fromEntries(yield* Effect.all(Object.keys(allNodes).map((fqn) => Effect.map(Deferred.make(), (d) => [fqn, d]))));\n const getOutputs = () => Object.fromEntries(Object.entries(tracker).map(([fqn, t]) => [fqn, t.output]));\n const waitForDeps = (fqns) => Effect.all(fqns\n .filter((fqn) => fqn in ready)\n .map((fqn) => Deferred.await(ready[fqn])), { concurrency: \"unbounded\" });\n const waitForStableDeps = (fqns) => Effect.all(fqns\n .filter((fqn) => fqn in readyStable)\n .map((fqn) => Deferred.await(readyStable[fqn])), { concurrency: \"unbounded\" });\n const failures = [];\n yield* Effect.all(Object.entries(allNodes).map(([fqn, node]) => node.kind === \"action\"\n ? executeActionNode(fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForStableDeps, failures)\n : executeNode(fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForDeps, failures, plan.cycleMembers.has(fqn))), { concurrency: \"unbounded\" });\n if (failures.length > 0) {\n // Aggregate every collected lifecycle failure into a single parallel Cause\n // so the apply ends with one combined error containing every distinct\n // failure / defect that occurred across the concurrent fibers.\n yield* Effect.failCause(failures.map((f) => f.cause).reduce(Cause.combine));\n }\n});\nconst executeNode = (fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForDeps, failures, inCycle) => Effect.gen(function* () {\n const logicalId = node.resource.LogicalId;\n const namespace = node.resource.Namespace;\n const commit = (value) => state.set({\n stack: stackName,\n stage,\n fqn,\n value: { ...value, namespace },\n });\n const scopedSession = {\n ...session,\n note: (note) => session.emit({ id: logicalId, kind: \"annotate\", message: note }),\n };\n const report = (status) => session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: node.resource.Type,\n status,\n });\n const markTerminal = (status) => Effect.gen(function* () {\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: node.resource.Type,\n status,\n });\n // Emit immediately so the CLI surfaces the terminal status as soon\n // as the resource is actually done — instead of batching every\n // resource's \"created\"/\"updated\" event to the end of apply(), which\n // makes long-running siblings appear stuck in \"creating\" until the\n // entire deploy finishes.\n //\n // Cycle members are exempt: their initial pass produces an\n // intermediate result that Phase 3 (`converge`) will overwrite once\n // the SCC reaches a fixed point. Emitting \"created\"/\"updated\" here\n // would surface that intermediate state to the CLI before the real\n // terminal status is known. Their final status is flushed from\n // `terminalStatuses` after `converge` completes.\n if (inCycle)\n return;\n yield* session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: node.resource.Type,\n status,\n });\n });\n const signalReady = Deferred.succeed(ready[fqn], void 0);\n // Signal only after reconcile completes — never during precreate. Tasks\n // (and any other consumer that calls `waitForStableDeps`) block on this\n // so they observe the resource's final attrs rather than a stub.\n const signalReadyStable = Deferred.succeed(readyStable[fqn], void 0);\n const storeAndSignal = (t) => Effect.gen(function* () {\n tracker[fqn] = t;\n yield* signalReady;\n });\n // ── noop ──\n if (node.action === \"noop\") {\n // No work to do — the persisted attr is already stable.\n yield* signalReadyStable;\n yield* storeAndSignal({\n output: node.state.attr,\n props: node.state.props,\n bindings: node.state.bindings ?? [],\n instanceId: node.state.instanceId,\n });\n return;\n }\n const allUpstreamFqns = () => {\n const propDeps = Object.keys(Output.resolveUpstream(node.props));\n const bindingDeps = Object.keys(Output.resolveUpstream(node.bindings));\n return [...new Set([...propDeps, ...bindingDeps])];\n };\n // ── instance ID ──\n const instanceId = yield* Effect.gen(function* () {\n if (node.action === \"create\" && !node.state?.instanceId) {\n const id = yield* generateInstanceId();\n yield* commit({\n status: \"creating\",\n fqn,\n logicalId,\n instanceId: id,\n downstream: node.downstream,\n props: node.props,\n providerVersion: node.provider.version ?? 0,\n resourceType: node.resource.Type,\n bindings: excludeDeletedBindings(node.bindings),\n removalPolicy: node.resource.RemovalPolicy,\n });\n return id;\n }\n else if (node.action === \"replace\") {\n if ((node.state.status === \"replaced\" ||\n node.state.status === \"replacing\") &&\n !node.restart) {\n // Ordinary replacement recovery keeps using the same replacement\n // generation. Only `restart` is allowed to mint a new instance id.\n return node.state.instanceId;\n }\n const id = yield* generateInstanceId();\n yield* commit({\n status: \"replacing\",\n fqn,\n logicalId,\n instanceId: id,\n downstream: node.downstream,\n props: node.props,\n providerVersion: node.provider.version ?? 0,\n resourceType: node.resource.Type,\n bindings: excludeDeletedBindings(node.bindings),\n old: node.state,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.resource.RemovalPolicy,\n });\n return id;\n }\n else if (node.state?.instanceId) {\n return node.state.instanceId;\n }\n return yield* Effect.die(`Instance ID not found for resource '${logicalId}' and action is '${node.action}'`);\n });\n // ── lifecycle ──\n yield* Effect.gen(function* () {\n // ── create ──\n if (node.action === \"create\") {\n if (!node.state) {\n // First persistence point for a brand new logical resource. Once this is\n // written, retries know they should resume creation instead of planning\n // another fresh create from scratch.\n yield* commit({\n status: \"creating\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n attr: undefined,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n let attr = node.state?.attr;\n if (attr !== undefined) {\n // Precreate/read may already have produced a usable output snapshot. Publish\n // it early so downstream resources can start resolving against it.\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n if (node.provider.precreate && attr === undefined) {\n // Some resources need a placeholder physical resource before their real\n // create can finish. Persist that stub so downstream evaluation can proceed.\n yield* report(\"pre-creating\");\n attr = yield* node.provider\n .precreate({\n id: logicalId,\n news: node.props,\n session: scopedSession,\n instanceId,\n bindings: excludeDeletedBindings(node.bindings),\n })\n .pipe(instrumentLifecycle(\"precreate\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n status: \"creating\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n // While we're waiting on upstream outputs the resource isn't actually\n // creating anything yet — surface that as \"pending\" so the CLI doesn't\n // look stuck in \"creating\" for slow-upstream deploys.\n yield* report(\"pending\");\n // Create runs against fully resolved upstream outputs and bindings, not the\n // raw Output expressions stored in the plan.\n yield* waitForDeps(allUpstreamFqns());\n yield* report(\"creating\");\n const outputs = getOutputs();\n const news = (yield* Output.evaluate(node.props, outputs));\n const bindingOutputs = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news,\n instanceId,\n bindings: bindingOutputs,\n session: scopedSession,\n olds: undefined,\n output: attr,\n })\n .pipe(instrumentLifecycle(\"create\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n status: \"created\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr,\n bindings: excludeDeletedBindings(node.bindings),\n providerVersion: node.provider.version ?? 0,\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n tracker[fqn] = {\n output: attr,\n props: news,\n bindings: bindingOutputs,\n instanceId,\n };\n yield* signalReady;\n yield* signalReadyStable;\n yield* markTerminal(\"created\");\n return;\n }\n // ── update ──\n if (node.action === \"update\") {\n // Cycle members publish their previous live attr *before* waiting on\n // upstreams so the SCC can converge — peers in the cycle would\n // otherwise deadlock waiting on each other. Phase 3 (`converge`)\n // re-runs each peer's update against fresh outputs once everyone\n // has settled.\n //\n // Linear (DAG) update nodes skip this entirely and simply wait for\n // fresh upstream outputs, mirroring the create flow. This is the\n // important property: a downstream of a non-cycle update never\n // observes the upstream's stale attr, which prevents wasted/\n // destructive intermediate updates (e.g. a Worker deploying with\n // stale Build assets).\n if (inCycle) {\n yield* storeAndSignal({\n output: node.state.attr,\n props: node.state.props,\n bindings: node.state.bindings ?? [],\n instanceId,\n });\n }\n // See create-flow note: while we're waiting on upstream outputs\n // this resource isn't actually updating yet.\n yield* report(\"pending\");\n yield* waitForDeps(allUpstreamFqns());\n const outputs = getOutputs();\n const news = (yield* Output.evaluate(node.props, outputs));\n yield* node.state.status === \"replaced\"\n ? commit({\n // Keep the replacement wrapper intact while changing the live\n // replacement props; GC still has older generations to delete.\n ...node.state,\n attr: node.state.attr,\n props: news,\n })\n : commit({\n // For ordinary updates we snapshot the previously stable props/attrs\n // once, so retries can continue from the same baseline.\n status: \"updating\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr: node.state.attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n old: node.state.status === \"updating\" ? node.state.old : node.state,\n removalPolicy: node.resource.RemovalPolicy,\n });\n yield* report(\"updating\");\n const previousProps = node.state.status === \"created\" ||\n node.state.status === \"updated\" ||\n node.state.status === \"replaced\"\n ? node.state.props\n : node.state.old.props;\n // Providers receive the resolved binding payload for this exact pass, while\n // `previousProps` tells them what state the live resource is being updated from.\n const bindingOutputs = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n const attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news,\n instanceId,\n bindings: bindingOutputs,\n session: scopedSession,\n olds: previousProps,\n output: node.state.attr,\n })\n .pipe(instrumentLifecycle(\"update\", fqn, node.resource.Type, logicalId, instanceId));\n if (node.state.status === \"replaced\") {\n yield* commit({\n // The live replacement changed, but cleanup of older generations still\n // has to continue afterwards.\n ...node.state,\n attr,\n props: news,\n });\n }\n else {\n yield* commit({\n status: \"updated\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr,\n bindings: excludeDeletedBindings(node.bindings),\n providerVersion: node.provider.version ?? 0,\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n tracker[fqn] = {\n output: attr,\n props: news,\n bindings: bindingOutputs,\n instanceId,\n };\n // Signal here for the linear (non-cycle) path. For in-cycle updates\n // the deferred has already been resolved by the early `storeAndSignal`\n // above and `signalReady` is a no-op the second time.\n yield* signalReady;\n yield* signalReadyStable;\n yield* markTerminal(\"updated\");\n return;\n }\n // ── replace ──\n if (node.action === \"replace\") {\n if (node.state.status === \"replaced\" && !node.restart) {\n // The replacement already exists; this pass only needs GC to clean up\n // older generations, so expose the current replacement and stop here.\n tracker[fqn] = {\n output: node.state.attr,\n props: node.state.props,\n bindings: node.state.bindings ?? [],\n instanceId,\n };\n yield* signalReady;\n yield* signalReadyStable;\n yield* markTerminal(\"created\");\n return;\n }\n let replState;\n if (node.state.status !== \"replacing\" || node.restart) {\n // `restart` deliberately nests the previous top-level replacement state\n // into `old`, creating a new outer generation to replace it.\n replState = yield* commit({\n status: \"replacing\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n bindings: excludeDeletedBindings(node.bindings),\n attr: undefined,\n providerVersion: node.provider.version ?? 0,\n deleteFirst: node.deleteFirst,\n old: node.state,\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n else {\n // Resume the same replacement generation after an interrupted apply.\n replState = node.state;\n }\n let attr = replState.attr;\n if (attr !== undefined) {\n // If precreate already ran, expose that intermediate output immediately so\n // downstream resources can resolve against the same in-flight replacement.\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n if (node.provider.precreate && attr === undefined) {\n yield* report(\"pre-creating\");\n attr = yield* node.provider\n .precreate({\n id: logicalId,\n news: node.props,\n session: scopedSession,\n instanceId,\n bindings: excludeDeletedBindings(node.bindings),\n })\n .pipe(instrumentLifecycle(\"precreate\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n status: \"replacing\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n old: replState.old,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.resource.RemovalPolicy,\n });\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n // See create-flow note: while we're waiting on upstream outputs\n // the replacement isn't actually being created yet.\n yield* report(\"pending\");\n // Replacement create is evaluated exactly like create, but against the new\n // generation's instance id and with the previous generations preserved in `old`.\n yield* waitForDeps(allUpstreamFqns());\n yield* report(\"creating replacement\");\n const outputs = getOutputs();\n const news = (yield* Output.evaluate(node.props, outputs));\n const bindingOutputs = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news,\n instanceId,\n bindings: bindingOutputs,\n session: scopedSession,\n olds: undefined,\n output: attr,\n })\n .pipe(instrumentLifecycle(\"create\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n // Creation of the new generation succeeded; from here on the only remaining\n // work is draining the old chain via garbage collection.\n status: \"replaced\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n // Preserve the remaining backlog exactly as-is. GC is responsible for\n // popping one generation at a time until the chain is exhausted.\n old: replState.old,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.resource.RemovalPolicy,\n });\n tracker[fqn] = {\n output: attr,\n props: news,\n bindings: bindingOutputs,\n instanceId,\n };\n yield* signalReady;\n yield* signalReadyStable;\n // Keep progress anchored to the live replacement while GC drains the\n // previous generation(s) in the background.\n yield* markTerminal(\"created\");\n return;\n }\n // @ts-expect-error - node is never, this should be unreachable\n return yield* Effect.die(`Unknown action: ${node.action}`);\n });\n}).pipe(Effect.catchCause((cause) => \n// Record the failure, propagate it to any downstream resources waiting on\n// our Deferred (so their waitForDeps short-circuits instead of deadlocking),\n// emit a \"fail\" status to the session, and resolve to void so Effect.all\n// does not interrupt sibling fibers. The aggregated cause is raised at\n// the end of executePlan.\nEffect.gen(function* () {\n failures.push({\n fqn,\n logicalId: node.resource.LogicalId,\n type: node.resource.Type,\n cause,\n });\n yield* Deferred.failCause(ready[fqn], cause);\n yield* Deferred.failCause(readyStable[fqn], cause);\n yield* session.emit({\n kind: \"status-change\",\n id: node.resource.LogicalId,\n type: node.resource.Type,\n status: \"fail\",\n });\n})), Effect.withSpan(\"apply.resource\", {\n attributes: {\n \"alchemy.resource.fqn\": fqn,\n \"alchemy.resource.type\": node.resource.Type,\n \"alchemy.resource.logical_id\": node.resource.LogicalId,\n \"alchemy.resource.action\": node.action,\n },\n}));\n// ── Task execution ─────────────────────────────────────────────────────────\n//\n// Tasks slot into the same scheduler as resources. They have no provider\n// lifecycle — just a single Effect that runs when inputs change (or when\n// `--force` is set). The output value is written to `tracker[fqn].output`\n// so downstream Output evaluation works identically to resource attrs.\nconst executeActionNode = (fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForDeps, failures) => Effect.gen(function* () {\n const task = node.def;\n const logicalId = task.LogicalId;\n const namespace = task.Namespace;\n const commit = (value) => state.set({\n stack: stackName,\n stage,\n fqn,\n value: { ...value, namespace },\n });\n const report = (status) => session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: task.Type,\n status,\n });\n const signalReady = Deferred.succeed(ready[fqn], void 0);\n const signalReadyStable = Deferred.succeed(readyStable[fqn], void 0);\n if (node.action === \"noop\") {\n tracker[fqn] = {\n output: node.state.output,\n props: { __input: node.state.input },\n bindings: [],\n instanceId: fqn,\n };\n yield* signalReady;\n yield* signalReadyStable;\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: task.Type,\n status: \"skipped\",\n });\n yield* report(\"skipped\");\n return;\n }\n // ── run ──\n // Tasks wait on `waitForStableDeps` (post-reconcile attrs) for their\n // upstreams, which is often the slowest dep chain in the deploy.\n // Surface that as \"pending\" instead of having the task show no status\n // until its run actually starts.\n yield* report(\"pending\");\n yield* waitForDeps(Object.keys(Output.resolveUpstream(node.input)).filter((f) => f in readyStable));\n const outputs = getOutputs();\n const resolvedInput = (yield* Output.evaluate(node.input, outputs));\n const inputHashValue = yield* hashInput(resolvedInput);\n yield* commit({\n kind: \"action\",\n status: \"running\",\n fqn,\n logicalId,\n actionType: task.Type,\n inputHash: inputHashValue,\n input: resolvedInput,\n downstream: node.downstream,\n });\n yield* report(\"running\");\n const result = yield* task.Run(resolvedInput);\n yield* commit({\n kind: \"action\",\n status: \"ran\",\n fqn,\n logicalId,\n actionType: task.Type,\n inputHash: inputHashValue,\n input: resolvedInput,\n output: result,\n downstream: node.downstream,\n });\n tracker[fqn] = {\n output: result,\n props: { __input: resolvedInput },\n bindings: [],\n instanceId: fqn,\n };\n yield* signalReady;\n yield* signalReadyStable;\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: task.Type,\n status: \"ran\",\n });\n yield* report(\"ran\");\n}).pipe(Effect.catchCause((cause) => Effect.gen(function* () {\n failures.push({\n fqn,\n logicalId: node.def.LogicalId,\n type: node.def.Type,\n cause,\n });\n yield* Deferred.failCause(ready[fqn], cause);\n yield* Deferred.failCause(readyStable[fqn], cause);\n yield* session.emit({\n kind: \"status-change\",\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"fail\",\n });\n})), Effect.withSpan(\"apply.action\", {\n attributes: {\n \"alchemy.action.fqn\": fqn,\n \"alchemy.action.type\": node.def.Type,\n \"alchemy.action.logical_id\": node.def.LogicalId,\n \"alchemy.action.verb\": node.action,\n },\n}));\n// ── Phase 3: imperative convergence loop ───────────────────────────────────\n//\n// After the initial concurrent pass, some resources may have been created\n// with stale upstream values (e.g. a precreate stub instead of the final\n// output). Walk the plan and re-evaluate each resource's props/bindings\n// against the current tracker outputs. Call provider.reconcile for any\n// resource whose resolved inputs differ from what it was last applied with.\n// Repeat until no resource needs updating.\nconst converge = Effect.fnUntraced(function* (plan, tracker, terminalStatuses, session, state, stackName, stage) {\n for (;;) {\n let anyUpdated = false;\n for (const [fqn, node] of Object.entries(plan.resources)) {\n if (node.action === \"noop\")\n continue;\n if (!tracker[fqn])\n continue;\n const outputs = Object.fromEntries(Object.entries(tracker).map(([k, t]) => [k, t.output]));\n const newProps = (yield* Output.evaluate(node.props, outputs));\n const newBindings = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n const oldProps = tracker[fqn].props;\n const oldBindings = tracker[fqn].bindings;\n const propsChanged = havePropsChanged(oldProps, newProps);\n const bindingsChanged = JSON.stringify(oldBindings) !== JSON.stringify(newBindings);\n if (!propsChanged && !bindingsChanged)\n continue;\n anyUpdated = true;\n const logicalId = node.resource.LogicalId;\n const namespace = node.resource.Namespace;\n const instanceId = tracker[fqn].instanceId;\n const scopedSession = {\n ...session,\n note: (note) => session.emit({ id: logicalId, kind: \"annotate\", message: note }),\n };\n const attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news: newProps,\n instanceId,\n bindings: newBindings,\n session: scopedSession,\n olds: oldProps,\n output: tracker[fqn].output,\n })\n .pipe(instrumentLifecycle(\"update\", fqn, node.resource.Type, logicalId, instanceId));\n tracker[fqn] = {\n output: attr,\n props: newProps,\n bindings: newBindings,\n instanceId,\n };\n yield* state.set({\n stack: stackName,\n stage,\n fqn,\n value: {\n status: \"updated\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: newProps,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n namespace,\n removalPolicy: node.resource.RemovalPolicy,\n },\n });\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: node.resource.Type,\n status: \"updated\",\n });\n }\n // Tasks: re-run when their resolved input drifts vs. the value they\n // last applied with (e.g. an upstream resource produced new attrs in\n // this pass). Skipped (noop) tasks are not re-checked here — their\n // recorded inputHash is authoritative until the next plan.\n for (const [fqn, node] of Object.entries(plan.actions)) {\n if (node.action !== \"run\")\n continue;\n if (!tracker[fqn])\n continue;\n const outputs = Object.fromEntries(Object.entries(tracker).map(([k, t]) => [k, t.output]));\n const newInput = (yield* Output.evaluate(node.input, outputs));\n const newHash = yield* hashInput(newInput);\n const oldInput = tracker[fqn].props?.__input;\n const oldHash = yield* hashInput(oldInput);\n if (newHash === oldHash)\n continue;\n anyUpdated = true;\n yield* state.set({\n stack: stackName,\n stage,\n fqn,\n value: {\n kind: \"action\",\n status: \"running\",\n fqn,\n logicalId: node.def.LogicalId,\n namespace: node.def.Namespace,\n actionType: node.def.Type,\n inputHash: newHash,\n input: newInput,\n downstream: node.downstream,\n },\n });\n const result = yield* node.def.Run(newInput);\n yield* state.set({\n stack: stackName,\n stage,\n fqn,\n value: {\n kind: \"action\",\n status: \"ran\",\n fqn,\n logicalId: node.def.LogicalId,\n namespace: node.def.Namespace,\n actionType: node.def.Type,\n inputHash: newHash,\n input: newInput,\n output: result,\n downstream: node.downstream,\n },\n });\n tracker[fqn] = {\n output: result,\n props: { __input: newInput },\n bindings: [],\n instanceId: fqn,\n };\n terminalStatuses.set(fqn, {\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"ran\",\n });\n }\n if (!anyUpdated)\n break;\n }\n});\n// ── Phase 2: delete orphans and old replaced resources ─────────────────────\nconst collectGarbage = Effect.fnUntraced(function* (plan, session) {\n const state = yield* State;\n const stack = yield* Stack;\n const stackName = stack.name;\n const stage = yield* Stage;\n // Task deletions are pure state drops — no body is invoked. Run them in\n // parallel before resource GC; tasks never have provider-side dependencies\n // to wait on.\n yield* Effect.all(Object.entries(plan.actionDeletions ?? {}).map(([fqn, node]) => node === undefined\n ? Effect.void\n : Effect.gen(function* () {\n yield* session.emit({\n kind: \"status-change\",\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"deleting\",\n });\n yield* state.delete({ stack: stackName, stage, fqn });\n yield* session.emit({\n kind: \"status-change\",\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"deleted\",\n });\n })), { concurrency: \"unbounded\" });\n const deleteGraph = Effect.fnUntraced(function* (deletionGraph) {\n const deletions = {};\n const deleteResource = (node, ancestors = new Set()) => Effect.gen(function* () {\n const isDeleteNode = (node) => \"action\" in node;\n const { logicalId, namespace, resourceType, instanceId, downstream, props, attr, provider, } = isDeleteNode(node)\n ? {\n logicalId: node.resource.LogicalId,\n namespace: node.resource.Namespace,\n resourceType: node.resource.Type,\n instanceId: node.state.instanceId,\n downstream: node.downstream,\n props: node.state.props,\n attr: node.state.attr,\n provider: node.provider,\n }\n : {\n logicalId: node.logicalId,\n namespace: node.namespace,\n resourceType: node.old.resourceType,\n instanceId: node.old.instanceId,\n downstream: node.old.downstream,\n props: node.old.props,\n attr: node.old.attr,\n provider: yield* findProviderByType(node.old.resourceType),\n };\n const fqn = toFqn(namespace, logicalId);\n const nextAncestors = new Set(ancestors).add(fqn);\n const commit = (value) => state.set({\n stack: stackName,\n stage,\n fqn,\n value: { ...value, namespace },\n });\n const report = (status) => session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: resourceType,\n status,\n });\n const scopedSession = {\n ...session,\n note: (note) => session.emit({\n id: logicalId,\n kind: \"annotate\",\n message: note,\n }),\n };\n return yield* (deletions[fqn] ??= yield* Effect.cached(Effect.gen(function* () {\n yield* Effect.all(downstream.map((dep) => dep !== fqn && dep in deletionGraph && !ancestors.has(dep)\n ? deleteResource(deletionGraph[dep], nextAncestors)\n : Effect.void), { concurrency: \"unbounded\" });\n if (isDeleteNode(node)) {\n yield* report(\"deleting\");\n if (node.resource.RemovalPolicy === \"retain\") {\n yield* state.delete({\n stack: stackName,\n stage,\n fqn,\n });\n yield* report(\"deleted\");\n return;\n }\n yield* commit({\n status: \"deleting\",\n fqn,\n logicalId,\n instanceId,\n resourceType,\n props,\n attr,\n downstream,\n providerVersion: provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n if (attr !== undefined) {\n yield* provider\n .delete({\n id: logicalId,\n instanceId,\n olds: props,\n output: attr,\n session: scopedSession,\n bindings: [],\n })\n .pipe(instrumentLifecycle(\"delete\", fqn, resourceType, logicalId, instanceId));\n }\n if (isDeleteNode(node)) {\n yield* state.delete({\n stack: stackName,\n stage,\n fqn,\n });\n yield* report(\"deleted\");\n }\n else {\n yield* scopedSession.note(\"Cleaning up replaced resource...\");\n if (node.old.status === \"replacing\" ||\n node.old.status === \"replaced\") {\n // We only deleted the outermost old generation. A nested replacement\n // chain still exists, so stay in `replaced` and pop the chain forward\n // one level. The outer loop will pick this resource up again.\n yield* commit({\n status: \"replaced\",\n fqn,\n logicalId: node.logicalId,\n instanceId: node.instanceId,\n resourceType: node.resourceType,\n props: node.props,\n attr: node.attr,\n providerVersion: node.providerVersion,\n downstream: node.downstream,\n bindings: excludeDeletedBindings(node.bindings),\n old: node.old.old,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.removalPolicy,\n });\n }\n else {\n // The old chain is fully drained, so the current replacement is now\n // the stable resource and we can collapse back to a terminal state.\n yield* commit({\n status: \"created\",\n fqn,\n logicalId: node.logicalId,\n instanceId: node.instanceId,\n resourceType: node.resourceType,\n props: node.props,\n attr: node.attr,\n providerVersion: node.providerVersion,\n downstream: node.downstream,\n bindings: excludeDeletedBindings(node.bindings),\n removalPolicy: node.removalPolicy,\n });\n }\n yield* scopedSession.note(\"Replaced resource cleanup complete.\");\n }\n })));\n });\n yield* Effect.all(Object.values(deletionGraph)\n .filter((node) => node !== undefined)\n .map((node) => deleteResource(node)), { concurrency: \"unbounded\" });\n });\n // The first pass handles both planned deletions and any top-level replaced\n // resources already present in state. Later passes only drain replacement\n // chains that were re-committed as `replaced` while deleting older generations.\n let first = true;\n while (true) {\n const remainingReplacedResources = yield* state.getReplacedResources({\n stack: stackName,\n stage,\n });\n if (!first && remainingReplacedResources.length === 0) {\n break;\n }\n yield* deleteGraph({\n // Orphan/resource deletions from the current plan should only run once.\n ...(first ? plan.deletions : {}),\n ...Object.fromEntries(remainingReplacedResources.map((replaced) => [\n toFqn(replaced.namespace, replaced.logicalId),\n replaced,\n ])),\n });\n first = false;\n }\n});\nconst excludeDeletedBindings = (bindings) => bindings.flatMap(({ action, sid, data }) => action === \"delete\" ? [] : [{ sid, data }]);\n//# sourceMappingURL=Apply.js.map","var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n};\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as S from \"effect/Schema\";\nimport * as Argument from \"effect/unstable/cli/Argument\";\nimport * as CliError from \"effect/unstable/cli/CliError\";\nimport * as Flag from \"effect/unstable/cli/Flag\";\nimport { AuthError } from \"../../Auth/AuthProvider.js\";\nimport { recordCli } from \"../../Telemetry/Metrics.js\";\nimport { PromptCancelled } from \"../../Util/Clank.js\";\nexport const USER = Config.string(\"USER\").pipe(Config.orElse(() => Config.string(\"USERNAME\")), Config.withDefault(\"unknown\"));\nexport const STAGE = Config.string(\"stage\").pipe(Config.option, (a) => a, Effect.map(Option.getOrUndefined));\n/**\n * `true` if `e` is a {@link PromptCancelled}, or an {@link AuthError} whose\n * `cause` chain bottoms out in one. Schema-tagged errors don't always\n * survive `instanceof` across module boundaries, so we also accept any\n * object whose `_tag` matches.\n */\nconst isPromptCancellation = (e) => {\n for (let cur = e, i = 0; cur != null && i < 16; i++) {\n if (cur instanceof PromptCancelled)\n return true;\n if (typeof cur === \"object\" &&\n cur._tag === \"PromptCancelled\") {\n return true;\n }\n if (cur instanceof AuthError ||\n (typeof cur === \"object\" &&\n cur._tag === \"AuthError\")) {\n cur = cur.cause;\n continue;\n }\n return false;\n }\n return false;\n};\n/**\n * Catches user cancellations (Ctrl+C inside a prompt, surfaced as\n * {@link PromptCancelled} or wrapped in an {@link AuthError}) and exits\n * the CLI cleanly with a friendly message instead of dumping a stack\n * trace.\n */\nexport const handleCancellation = (self) => self.pipe(Effect.catchCause((cause) => {\n const cancelled = cause.reasons.some((r) => {\n if (Cause.isFailReason(r))\n return isPromptCancellation(r.error);\n if (Cause.isDieReason(r))\n return isPromptCancellation(r.defect);\n return false;\n });\n return cancelled\n ? Console.log(\"\\nCancelled.\")\n : Effect.failCause(cause);\n}), \n// A bare fiber interrupt (Ctrl+C while not inside a prompt) shouldn't\n// dump a stack trace either.\nEffect.onInterrupt(() => Console.log(\"\\nInterrupted.\")));\nexport const stage = Flag.string(\"stage\").pipe(Flag.withSchema(S.String.check(S.isPattern(/^[a-z0-9]+([-_a-z0-9]+)*$/gi))), Flag.withDescription(\"Stage to deploy to, defaults to dev_${USER}\"), Flag.optional, Flag.map(Option.getOrUndefined), Flag.mapEffect(Effect.fn(function* (stage) {\n if (stage) {\n return stage;\n }\n return yield* STAGE.pipe(Effect.catch(() => Effect.fail(new CliError.MissingOption({\n option: \"stage\",\n }))), Effect.flatMap((s) => s === undefined\n ? USER.pipe(Effect.map((user) => `dev_${user}`), Effect.catch(() => Effect.succeed(\"unknown\")))\n : Effect.succeed(s)));\n})));\nexport const envFile = Flag.file(\"env-file\").pipe(Flag.optional, Flag.withDescription(\"File to load environment variables from, defaults to .env\"));\nexport const dryRun = Flag.boolean(\"dry-run\").pipe(Flag.withDescription(\"Dry run the deployment, do not actually deploy\"), Flag.withDefault(false));\nexport const yes = Flag.boolean(\"yes\").pipe(Flag.withDescription(\"Yes to all prompts\"), Flag.withDefault(false));\nexport const force = Flag.boolean(\"force\").pipe(Flag.withDescription(\"Force updates for resources that would otherwise no-op\"), Flag.withDefault(false));\nexport const script = Argument.file(\"main\", {\n mustExist: true,\n}).pipe(Argument.withDescription(\"Main file to deploy, defaults to alchemy.run.ts\"), Argument.withDefault(\"alchemy.run.ts\"));\nexport const profile = Flag.string(\"profile\").pipe(Flag.withDescription(\"Auth profile to use (~/.alchemy/profiles.json). Defaults to 'default' or $ALCHEMY_PROFILE.\"), Flag.optional, Flag.map(Option.getOrElse(() => \"default\")));\nexport const resourceFilter = Flag.string(\"filter\").pipe(Flag.withDescription(\"Comma-separated logical resource IDs (e.g. Api,Sandbox). Only those resources are included.\"), Flag.optional, Flag.map(Option.getOrUndefined));\nexport const TAIL_COLORS = [\n \"\\x1b[36m\", // cyan\n \"\\x1b[35m\", // magenta\n \"\\x1b[33m\", // yellow\n \"\\x1b[32m\", // green\n \"\\x1b[34m\", // blue\n \"\\x1b[91m\", // bright red\n \"\\x1b[96m\", // bright cyan\n \"\\x1b[95m\", // bright magenta\n \"\\x1b[93m\", // bright yellow\n \"\\x1b[92m\", // bright green\n];\nexport const TAIL_RESET = \"\\x1b[0m\";\nexport const formatLocalTimestamp = (date) => {\n const y = date.getFullYear();\n const mo = String(date.getMonth() + 1).padStart(2, \"0\");\n const d = String(date.getDate()).padStart(2, \"0\");\n const h = String(date.getHours()).padStart(2, \"0\");\n const mi = String(date.getMinutes()).padStart(2, \"0\");\n const s = String(date.getSeconds()).padStart(2, \"0\");\n const ms = String(date.getMilliseconds()).padStart(3, \"0\");\n const tz = new Intl.DateTimeFormat(\"en-US\", { timeZoneName: \"short\" })\n .formatToParts(date)\n .find((p) => p.type === \"timeZoneName\")?.value ?? \"\";\n return `${y}-${mo}-${d} ${h}:${mi}:${s}.${ms} ${tz}`;\n};\nexport const parseResourceFilter = (filter) => {\n if (filter === undefined)\n return undefined;\n const ids = filter\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (ids.length === 0)\n return undefined;\n return new Set(ids);\n};\nexport const parseSince = (value) => {\n const match = value.match(/^(\\d+)([smhd])$/);\n if (match) {\n const num = parseInt(match[1], 10);\n const unit = match[2];\n const ms = unit === \"s\"\n ? num * 1000\n : unit === \"m\"\n ? num * 60_000\n : unit === \"h\"\n ? num * 3_600_000\n : num * 86_400_000;\n return new Date(Date.now() - ms);\n }\n const parsed = new Date(value);\n if (isNaN(parsed.getTime())) {\n throw new Error(`Invalid --since value: '${value}'. Use a duration (e.g. '1h', '30m') or ISO date.`);\n }\n return parsed;\n};\n/**\n * Wraps a CLI command handler with a top-level OpenTelemetry span\n * (`cli.<command>`) and bumps the `alchemy.cli.invocations` counter.\n *\n * `attrs` runs against the parsed command args and contributes\n * additional attributes to the span (e.g. stage, profile, dry-run flag).\n *\n * Usage:\n * ```ts\n * Command.make(\n * \"deploy\",\n * { ...flags },\n * instrumentCommand(\"deploy\", (a) => ({\n * \"alchemy.stage\": a.stage,\n * \"alchemy.profile\": a.profile,\n * }))(execStack),\n * );\n * ```\n */\nexport const instrumentCommand = (command, attrs) => (handler) => (args) => handler(args).pipe(Effect.withSpan(`cli.${command}`, {\n attributes: attrs ? attrs(args) : {},\n}), recordCli(command));\nexport const importStack = Effect.fn(function* (main) {\n const path = yield* Path.Path;\n const module = yield* Effect.promise(() => import(__rewriteRelativeImportExtension(path.resolve(process.cwd(), main))));\n const stackEffect = module.default;\n if (!Effect.isEffect(stackEffect)) {\n return yield* Effect.die(new Error(`Main file '${main}' must export a default stack definition (export default Alchemy.Stack({...}))`));\n }\n return stackEffect;\n});\n//# sourceMappingURL=_shared.js.map","import * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Logger from \"effect/Logger\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Command from \"effect/unstable/cli/Command\";\nimport * as Flag from \"effect/unstable/cli/Flag\";\nimport { AdoptPolicy } from \"../../AdoptPolicy.js\";\nimport { AlchemyContext } from \"../../AlchemyContext.js\";\nimport { apply } from \"../../Apply.js\";\nimport { ArtifactStore, createArtifactStore } from \"../../Artifacts.js\";\nimport { AuthProviders } from \"../../Auth/AuthProvider.js\";\nimport { withProfileOverride } from \"../../Auth/Profile.js\";\nimport * as CLI from \"../../Cli/Cli.js\";\nimport * as Plan from \"../../Plan.js\";\nimport { Stage } from \"../../Stage.js\";\nimport { loadConfigProvider } from \"../../Util/ConfigProvider.js\";\nimport { fileLogger } from \"../../Util/FileLogger.js\";\nimport { dryRun as dryRunFlag, envFile, force, importStack, instrumentCommand, profile, script, stage, yes, } from \"./_shared.js\";\nexport const ExecStackOptions = Schema.Struct({\n main: Schema.String,\n stage: Schema.String,\n envFile: Schema.OptionFromOptional(Schema.String),\n profile: Schema.optional(Schema.String),\n dryRun: Schema.optional(Schema.Boolean),\n force: Schema.optional(Schema.Boolean),\n yes: Schema.optional(Schema.Boolean),\n destroy: Schema.optional(Schema.Boolean),\n dev: Schema.optional(Schema.Boolean),\n adopt: Schema.optional(Schema.Boolean),\n});\nconst stackSpanAttrs = (args) => ({\n \"alchemy.stage\": args.stage,\n \"alchemy.profile\": args.profile,\n \"alchemy.main\": args.main,\n \"alchemy.dry_run\": !!args.dryRun,\n \"alchemy.force\": !!args.force,\n \"alchemy.destroy\": !!args.destroy,\n \"alchemy.dev\": !!args.dev,\n \"alchemy.adopt\": !!args.adopt,\n});\nconst adopt = Flag.boolean(\"adopt\").pipe(Flag.withDescription(\"Adopt pre-existing cloud resources that conflict with this stack instead of failing. \" +\n \"Useful for re-importing infrastructure into a fresh state store.\"), Flag.withDefault(false));\nexport const execStack = Effect.fn(function* ({ main, stage, envFile, profile, dryRun = false, force = false, yes = false, destroy = false, dev = false, adopt = false, }) {\n const stackEffect = yield* importStack(main);\n const services = Layer.mergeAll(Layer.effect(AlchemyContext, AlchemyContext.pipe(Effect.map((ctx) => ({\n ...ctx,\n dev,\n adopt,\n })))), \n // `--adopt` opts the entire deploy in to adoption-on-conflict.\n // Resource providers that wire `AdoptPolicy` (Worker domains,\n // Cloudflare.SecretsStore, etc.) will reconcile against\n // pre-existing cloud resources instead of failing on duplicates.\n // Default is `false` so an unintentional collision still surfaces\n // loudly.\n Layer.succeed(AdoptPolicy, adopt), Layer.succeed(ArtifactStore, createArtifactStore()), Layer.succeed(AuthProviders, yield* Effect.serviceOption(AuthProviders).pipe(Effect.map(Option.getOrElse(() => ({}))))), ConfigProvider.layer(withProfileOverride(yield* loadConfigProvider(envFile), profile)), Logger.layer([fileLogger(\"out\")], { mergeWithExisting: true }), Layer.succeed(Stage, stage));\n yield* Effect.gen(function* () {\n const cli = yield* CLI.Cli;\n const stack = yield* stackEffect;\n yield* Effect.gen(function* () {\n const updatePlan = yield* Plan.make(destroy\n ? {\n ...stack,\n // zero these out (destroy will treat all as orphans)\n // TODO(sam): probably better to have Plan.destroy and Plan.update\n resources: {},\n bindings: {},\n actions: {},\n output: {},\n }\n : stack, { force });\n if (dryRun) {\n yield* cli.displayPlan(updatePlan);\n }\n else {\n const hasChanges = Object.keys(updatePlan.deletions).length > 0 ||\n Object.values(updatePlan.resources).some((node) => node.action !== \"noop\" ||\n node.bindings.some((b) => b.action !== \"noop\"));\n if (!yes && hasChanges) {\n const approved = yield* cli.approvePlan(updatePlan);\n if (!approved) {\n return;\n }\n }\n const outputs = yield* apply(updatePlan);\n if (outputs !== undefined) {\n yield* Console.log(outputs);\n }\n if (dev) {\n yield* Effect.never;\n }\n }\n }).pipe(Effect.provide(stack.services));\n }).pipe(Effect.provide(services));\n});\nexport const deployCommand = Command.make(\"deploy\", {\n dryRun: dryRunFlag,\n force,\n main: script,\n envFile,\n stage,\n yes,\n profile,\n adopt,\n}, instrumentCommand(\"deploy\", stackSpanAttrs)(execStack));\nexport const destroyCommand = Command.make(\"destroy\", {\n dryRun: dryRunFlag,\n main: script,\n envFile,\n stage,\n yes,\n profile,\n}, instrumentCommand(\"destroy\", stackSpanAttrs)((args) => execStack({\n ...args,\n destroy: true,\n})));\nexport const planCommand = Command.make(\"plan\", {\n main: script,\n envFile,\n stage,\n profile,\n}, instrumentCommand(\"plan\", stackSpanAttrs)((args) => execStack({\n ...args,\n // plan is the same as deploy with dryRun always set to true\n dryRun: true,\n})));\n//# sourceMappingURL=deploy.js.map","import * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { Cli } from \"./Cli.js\";\nconst ESC = \"\\x1b[\";\nconst RESET = `${ESC}0m`;\nconst useColor = process.stdout.hasColors?.() ?? !!process.stdout.isTTY;\nconst c = (code, s) => useColor ? `${ESC}${code}m${s}${RESET}` : s;\nconst dim = (s) => c(\"2\", s);\nconst bold = (s) => c(\"1\", s);\nconst red = (s) => c(\"31\", s);\nconst green = (s) => c(\"32\", s);\nconst yellow = (s) => c(\"33\", s);\nconst blue = (s) => c(\"34\", s);\nconst magenta = (s) => c(\"35\", s);\nconst cyan = (s) => c(\"36\", s);\nconst actionColor = {\n create: green,\n update: yellow,\n replace: magenta,\n delete: red,\n noop: dim,\n};\nconst statusColor = (status) => {\n switch (status) {\n case \"created\":\n case \"updated\":\n case \"replaced\":\n return green;\n case \"deleted\":\n return dim;\n case \"fail\":\n return red;\n case \"attaching\":\n case \"post-attach\":\n return cyan;\n default:\n return yellow;\n }\n};\nconst tag = (id) => bold(`[${id}]`);\nconst isTerminal = (status) => status === \"created\" ||\n status === \"updated\" ||\n status === \"deleted\" ||\n status === \"replaced\" ||\n status === \"fail\";\nconst formatPlanLines = (plan) => {\n const items = [\n ...Object.values(plan.resources),\n ...Object.values(plan.deletions),\n ];\n if (items.length === 0)\n return [bold(\"Plan:\") + \" no changes\"];\n const counts = items.reduce((acc, item) => ((acc[item.action] = (acc[item.action] ?? 0) + 1), acc), {});\n const summary = [\"create\", \"update\", \"replace\", \"delete\", \"noop\"]\n .filter((a) => counts[a])\n .map((a) => actionColor[a](`${counts[a]} to ${a}`))\n .join(dim(\", \"));\n const sorted = [...items].sort((a, b) => a.resource.LogicalId.localeCompare(b.resource.LogicalId));\n const lines = [`${bold(\"Plan:\")} ${summary}`];\n for (const item of sorted) {\n const action = actionColor[item.action](item.action);\n lines.push(`${tag(item.resource.LogicalId)} ${action}`);\n for (const binding of item.bindings) {\n if (binding.action === \"noop\")\n continue;\n const bindingAction = actionColor[binding.action](binding.action);\n lines.push(`${tag(`${item.resource.LogicalId}/${binding.sid}`)} ${bindingAction}`);\n }\n }\n return lines;\n};\nexport const LoggingCli = Layer.succeed(Cli, Cli.of({\n approvePlan: (plan) => Effect.gen(function* () {\n for (const line of formatPlanLines(plan))\n yield* Console.log(line);\n yield* Console.log(`\\n${yellow(\"Non-interactive terminal detected.\")} Pass ${bold(\"--yes\")} to approve, or set ${bold(\"ALCHEMY_TUI=1\")} for the interactive UI.`);\n return false;\n }),\n displayPlan: (plan) => Effect.gen(function* () {\n for (const line of formatPlanLines(plan))\n yield* Console.log(line);\n }),\n startApplySession: (plan) => Effect.gen(function* () {\n for (const line of formatPlanLines(plan))\n yield* Console.log(line);\n yield* Console.log(\"\");\n const counts = { ok: 0, fail: 0 };\n return {\n emit: (event) => Effect.sync(() => {\n if (event.kind === \"annotate\") {\n console.log(`${tag(event.id)} ${blue(event.message)}`);\n return;\n }\n const id = event.bindingId\n ? `${event.id}/${event.bindingId}`\n : event.id;\n const status = statusColor(event.status)(event.status);\n const msg = event.message ? ` ${dim(\"—\")} ${event.message}` : \"\";\n console.log(`${tag(id)} ${status}${msg}`);\n if (isTerminal(event.status)) {\n if (event.status === \"fail\")\n counts.fail++;\n else\n counts.ok++;\n }\n }),\n done: () => Console.log(`\\n${bold(\"Done:\")} ${green(`${counts.ok} succeeded`)}${counts.fail ? dim(\", \") + red(`${counts.fail} failed`) : \"\"}`),\n };\n }),\n}));\n//# sourceMappingURL=LoggingCli.js.map","import { toPath } from \"../FQN.js\";\nexport function buildNamespaceTree(items, actions = []) {\n const root = {\n id: \"\",\n path: [],\n children: new Map(),\n resources: [],\n actions: [],\n };\n const getNode = (path) => {\n let current = root;\n for (let i = 0; i < path.length; i++) {\n const segment = path[i];\n let child = current.children.get(segment);\n if (!child) {\n child = {\n id: segment,\n path: path.slice(0, i + 1),\n children: new Map(),\n resources: [],\n actions: [],\n };\n current.children.set(segment, child);\n }\n current = child;\n }\n return current;\n };\n for (const item of items) {\n getNode(toPath(item.resource.Namespace)).resources.push(item);\n }\n for (const action of actions) {\n getNode(toPath(action.def.Namespace)).actions.push(action);\n }\n return root;\n}\nexport function deriveNamespaceAction(node) {\n const actions = new Set();\n for (const resource of node.resources) {\n actions.add(deriveResourceChildrenAction(resource, node));\n }\n for (const action of node.actions) {\n // Map task actions onto the resource action space for the rollup:\n // run → create, delete → delete, noop → noop.\n actions.add(action.action === \"run\"\n ? \"create\"\n : action.action === \"delete\"\n ? \"delete\"\n : \"noop\");\n }\n for (const child of node.children.values()) {\n const childAction = deriveNamespaceAction(child);\n if (childAction === \"mixed\") {\n return \"mixed\";\n }\n actions.add(childAction);\n }\n return deriveAction(actions);\n}\nexport function flattenTree(node, depth = 0, result = []) {\n flattenNamespace(node, depth, result);\n return result;\n}\nconst flattenNamespace = (node, depth, result) => {\n const sortedResources = [...node.resources].sort((a, b) => a.resource.LogicalId.localeCompare(b.resource.LogicalId));\n const sortedChildren = Array.from(node.children.entries()).sort(([a], [b]) => a.localeCompare(b));\n const resourceIds = new Set(sortedResources.map((resource) => resource.resource.LogicalId));\n for (const [id, child] of sortedChildren) {\n if (resourceIds.has(id) || isEmpty(child)) {\n continue;\n }\n result.push({\n type: \"namespace\",\n depth,\n id,\n path: child.path,\n action: deriveNamespaceAction(child),\n hasChildren: true,\n });\n flattenNamespace(child, depth + 1, result);\n }\n for (const resource of sortedResources) {\n const childNamespace = node.children.get(resource.resource.LogicalId);\n result.push({\n type: \"resource\",\n depth,\n id: resource.resource.LogicalId,\n path: [...node.path, resource.resource.LogicalId],\n action: resource.action,\n resourceType: resource.resource.Type,\n bindingCount: resource.bindings.length,\n });\n for (const binding of [...resource.bindings].sort((a, b) => a.sid.localeCompare(b.sid))) {\n result.push({\n type: \"binding\",\n depth: depth + 1,\n id: binding.sid,\n path: [...node.path, resource.resource.LogicalId, binding.sid],\n action: binding.action,\n bindingSid: binding.sid,\n });\n }\n if (childNamespace) {\n flattenNamespace(childNamespace, depth + 1, result);\n }\n }\n // Actions are listed after resources at the same depth.\n const sortedActions = [...node.actions].sort((a, b) => a.def.LogicalId.localeCompare(b.def.LogicalId));\n for (const action of sortedActions) {\n result.push({\n type: \"action\",\n depth,\n id: action.def.LogicalId,\n path: [...node.path, action.def.LogicalId],\n action: action.action,\n actionType: action.def.Type,\n });\n }\n};\nconst isEmpty = (node) => node.resources.length === 0 &&\n node.actions.length === 0 &&\n Array.from(node.children.values()).every(isEmpty);\nconst countVisibleChildren = (node) => {\n const resourceIds = new Set(node.resources.map((resource) => resource.resource.LogicalId));\n return (node.resources.length +\n Array.from(node.children.keys()).filter((id) => !resourceIds.has(id)).length);\n};\nconst deriveResourceChildrenAction = (resource, node) => {\n const actions = new Set([\n resource.action,\n ]);\n for (const binding of resource.bindings) {\n actions.add(binding.action);\n }\n const childNamespace = node.children.get(resource.resource.LogicalId);\n if (childNamespace) {\n actions.add(deriveNamespaceAction(childNamespace));\n }\n return deriveAction(actions);\n};\nconst deriveAction = (actions) => {\n if (actions.size === 0)\n return \"noop\";\n if (actions.has(\"replace\"))\n return actions.size === 1 ? \"replace\" : \"mixed\";\n if (actions.has(\"delete\"))\n return actions.size === 1 ? \"delete\" : \"mixed\";\n if (actions.has(\"create\"))\n return actions.size === 1 ? \"create\" : \"mixed\";\n if (actions.has(\"update\"))\n return actions.size === 1 ? \"update\" : \"mixed\";\n return \"noop\";\n};\n//# sourceMappingURL=NamespaceTree.js.map","import { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport { useMemo } from \"react\";\nimport { Box, Text } from \"ink\";\nimport { buildNamespaceTree, flattenTree, } from \"../../NamespaceTree.js\";\nexport function Plan({ plan }) {\n const items = useMemo(() => [\n ...Object.values(plan.resources),\n ...Object.values(plan.deletions),\n ], [plan]);\n const taskItems = useMemo(() => [\n ...Object.values(plan.actions ?? {}),\n ...Object.values(plan.actionDeletions ?? {}),\n ].filter((t) => t !== undefined), [plan]);\n const flatItems = useMemo(() => {\n const tree = buildNamespaceTree(items, taskItems);\n return flattenTree(tree);\n }, [items, taskItems]);\n if (items.length === 0 && taskItems.length === 0) {\n return _jsx(Text, { color: \"gray\", children: \"No changes planned\" });\n }\n const counts = items.reduce((acc, item) => (acc[item.action]++, acc), {\n create: 0,\n update: 0,\n delete: 0,\n noop: 0,\n replace: 0,\n });\n const taskCounts = taskItems.reduce((acc, item) => (acc[item.action]++, acc), { run: 0, noop: 0, delete: 0 });\n const actions = [\"create\", \"update\", \"delete\", \"replace\"].filter((action) => counts[action] > 0);\n const taskHeaderEntries = [\n taskCounts.run > 0 ? `${taskCounts.run} to run` : undefined,\n taskCounts.delete > 0 ? `${taskCounts.delete} to drop` : undefined,\n ].filter((s) => !!s);\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsxs(Box, { marginTop: 1, children: [_jsx(Text, { underline: true, children: \"Plan\" }), _jsx(Text, { children: \": \" }), [\n ...actions.map((action) => {\n const count = counts[action];\n const color = actionColor(action);\n return (_jsx(Box, { children: _jsxs(Text, { color: color, children: [count, \" to \", action] }) }, action));\n }),\n ...taskHeaderEntries.map((label, i) => (_jsx(Box, { children: _jsx(Text, { color: \"cyan\", children: label }) }, `task-${i}`))),\n ].flatMap((box, i, arr) => i === arr.length - 1\n ? [box]\n : [box, _jsx(Text, { children: \" | \" }, `sep-${i}`)])] }), _jsx(Box, { flexDirection: \"column\", marginTop: 1, children: flatItems.map((item) => {\n const indent = \" \".repeat(item.depth);\n const color = getActionColor(item.action);\n const icon = getActionIcon(item.action);\n const key = item.path.join(\"/\");\n if (item.type === \"namespace\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { color: \"blueBright\", children: item.id })] }, key));\n }\n if (item.type === \"binding\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { color: \"cyan\", children: item.bindingSid })] }, key));\n }\n if (item.type === \"action\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Box, { children: _jsx(Text, { bold: true, children: item.id }) }), _jsx(Box, { marginLeft: 1, children: _jsxs(Text, { color: \"blackBright\", children: [\"(\", item.actionType, \")\"] }) }), _jsx(Box, { marginLeft: 1, children: _jsx(Text, { color: \"cyan\", children: \"[action]\" }) })] }, key));\n }\n // Resource item\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Box, { children: _jsx(Text, { bold: true, children: item.id }) }), _jsx(Box, { marginLeft: 1, children: _jsxs(Text, { color: \"blackBright\", children: [\"(\", item.resourceType, \")\"] }) }), item.bindingCount !== undefined && item.bindingCount > 0 && (_jsx(Box, { marginLeft: 1, children: _jsxs(Text, { color: \"cyan\", children: [\"(\", item.bindingCount, \" bindings)\"] }) }))] }, key));\n }) })] }));\n}\nconst getActionColor = (action) => ({\n noop: \"gray\",\n create: \"green\",\n update: \"yellow\",\n delete: \"red\",\n replace: \"magenta\",\n mixed: \"cyan\",\n run: \"cyan\",\n})[action] ?? \"gray\";\nconst getActionIcon = (action) => ({\n create: \"+\",\n update: \"~\",\n delete: \"-\",\n noop: \"•\",\n replace: \"!\",\n mixed: \"*\",\n run: \"λ\",\n})[action] ?? \"?\";\nconst actionColor = (action) => getActionColor(action);\n//# sourceMappingURL=Plan.js.map","import { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport { useState } from \"react\";\nimport { Box, Text, useApp, useInput } from \"ink\";\nimport { Plan } from \"./Plan.js\";\nexport function ApprovePlan(props) {\n const { plan, approve } = props;\n const [selected, setSelected] = useState(0);\n const { exit } = useApp();\n useInput((_input, key) => {\n if (key.leftArrow || key.rightArrow) {\n setSelected((prev) => (prev === 0 ? 1 : 0));\n }\n else if (key.return) {\n approve(selected === 0);\n exit();\n }\n });\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsx(Plan, { plan: plan }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { children: \"Proceed?\" }) }), _jsxs(Box, { gap: 1, children: [_jsxs(Text, { color: selected === 0 ? \"green\" : \"gray\", children: [selected === 0 ? \"◉\" : \"○\", \" Yes\"] }), _jsxs(Text, { color: selected === 1 ? \"red\" : \"gray\", children: [selected === 1 ? \"◉\" : \"○\", \" No\"] })] })] }));\n}\n//# sourceMappingURL=ApprovePlan.js.map","import { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { Box, Text } from \"ink\";\nimport { buildNamespaceTree, flattenTree, } from \"../../NamespaceTree.js\";\nconst getTaskKey = (item) => item.path.join(\"/\");\nexport const buildProgressRows = (plan) => {\n const items = [\n ...Object.values(plan.resources),\n ...Object.values(plan.deletions).filter((item) => item !== undefined),\n ];\n const taskItems = [\n ...Object.values(plan.actions ?? {}),\n ...Object.values(plan.actionDeletions ?? {}),\n ].filter((t) => t !== undefined);\n const tree = buildNamespaceTree(items, taskItems);\n return flattenTree(tree)\n .filter((item) => item.type !== \"binding\")\n .map((item) => {\n if (item.type === \"namespace\") {\n return {\n key: getTaskKey(item),\n type: \"namespace\",\n id: item.id,\n depth: item.depth,\n action: item.action,\n };\n }\n if (item.type === \"action\") {\n return {\n key: getTaskKey(item),\n type: \"task\",\n id: item.id,\n depth: item.depth,\n actionType: item.actionType ?? \"unknown\",\n action: item.action,\n };\n }\n return {\n key: getTaskKey(item),\n type: \"resource\",\n id: item.id,\n depth: item.depth,\n resourceType: item.resourceType ?? \"unknown\",\n action: item.action,\n persistedApplyStatus: item.action === \"noop\"\n ? (() => {\n const crud = findCrudByLogicalId(plan, item.id);\n return crud?.action === \"noop\" ? crud.state.status : undefined;\n })()\n : undefined,\n };\n });\n};\nconst buildLogicalIdIndex = (rows) => {\n const index = new Map();\n for (const row of rows) {\n if (row.type !== \"resource\" && row.type !== \"task\")\n continue;\n const keys = index.get(row.id);\n if (keys) {\n keys.push(row.key);\n }\n else {\n index.set(row.id, [row.key]);\n }\n }\n return index;\n};\nexport function toPlanTask(rowOrId, planItem) {\n if (typeof rowOrId === \"string\") {\n return {\n key: rowOrId,\n id: rowOrId,\n type: planItem.resource.Type,\n status: planItem.action === \"noop\" ? planItem.state.status : \"pending\",\n updatedAt: Date.now(),\n };\n }\n return {\n key: rowOrId.key,\n id: rowOrId.id,\n type: rowOrId.resourceType,\n status: rowOrId.action === \"noop\"\n ? (rowOrId.persistedApplyStatus ?? \"created\")\n : \"pending\",\n updatedAt: Date.now(),\n };\n}\nconst buildInitialTasks = (rows) => new Map(rows.flatMap((row) => row.type === \"resource\"\n ? [[row.key, toPlanTask(row)]]\n : row.type === \"task\"\n ? [\n [\n row.key,\n {\n key: row.key,\n id: row.id,\n type: row.actionType,\n // `noop` tasks are skipped — render as gray `•` from the start\n // rather than briefly flashing the `ran` cyan styling.\n status: row.action === \"noop\"\n ? \"skipped\"\n : \"pending\",\n updatedAt: Date.now(),\n },\n ],\n ]\n : []));\nexport function PlanProgress(props) {\n const { source, plan } = props;\n const spinner = useGlobalSpinner();\n const rows = useMemo(() => buildProgressRows(plan), [plan]);\n const logicalIdIndex = useMemo(() => buildLogicalIdIndex(rows), [rows]);\n const [tasks, setTasks] = useState(() => buildInitialTasks(rows));\n const unsubscribeRef = useRef(null);\n useEffect(() => {\n unsubscribeRef.current?.();\n unsubscribeRef.current = source.subscribe((event) => {\n setTasks((prev) => {\n const next = new Map(prev);\n const keys = logicalIdIndex.get(event.id) ?? [];\n if (event.kind === \"status-change\") {\n if (!event.bindingId) {\n for (const key of keys) {\n const current = next.get(key);\n next.set(key, {\n key,\n id: event.id,\n type: event.type,\n status: event.status,\n message: event.message ?? current?.message,\n updatedAt: Date.now(),\n });\n }\n }\n }\n else {\n for (const key of keys) {\n const current = next.get(key);\n if (!current)\n continue;\n next.set(key, {\n ...current,\n message: event.message,\n updatedAt: Date.now(),\n });\n }\n }\n return next;\n });\n });\n return () => {\n unsubscribeRef.current?.();\n unsubscribeRef.current = null;\n };\n }, [logicalIdIndex, source]);\n useEffect(() => {\n setTasks(buildInitialTasks(rows));\n }, [rows]);\n return (_jsx(Box, { flexDirection: \"column\", children: rows.map((row) => {\n const indent = \" \".repeat(row.depth);\n if (row.type === \"namespace\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsx(Text, { color: \"blueBright\", children: \"\\u21B3 \" }) }), _jsx(Text, { color: \"blueBright\", children: row.id })] }, row.key));\n }\n if (row.type === \"task\") {\n const t = tasks.get(row.key);\n const status = t?.status ?? (row.action === \"noop\" ? \"ran\" : \"pending\");\n const color = statusColor(status);\n const icon = taskIcon(row.action, status, spinner);\n const label = row.action === \"delete\"\n ? status === \"deleted\"\n ? \"deleted\"\n : \"drop\"\n : status === \"ran\"\n ? row.action === \"noop\"\n ? \"skip\"\n : \"ran\"\n : status === \"running\"\n ? \"running\"\n : status === \"fail\"\n ? \"fail\"\n : row.action === \"noop\"\n ? \"skip\"\n : \"run\";\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { bold: true, children: row.id }), _jsxs(Text, { dimColor: true, children: [\" (\", row.actionType, \")\"] }), _jsxs(Text, { color: color, children: [\" \", label] }), _jsxs(Text, { color: \"cyan\", dimColor: true, children: [\" \", \"[action]\"] })] }), t?.message ? (_jsx(Box, { paddingLeft: row.depth * 2 + 2, children: _jsxs(Text, { dimColor: true, children: [\"\\u2022 \", t.message] }) })) : null] }, row.key));\n }\n const task = tasks.get(row.key) ?? toPlanTask(row);\n const displayStatus = getDisplayStatus(row, task.status);\n const color = statusColor(displayStatus);\n const icon = statusIcon(task.status, spinner);\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { bold: true, children: task.id }), _jsxs(Text, { dimColor: true, children: [\" (\", task.type, \")\"] }), _jsxs(Text, { color: color, children: [\" \", displayStatus] })] }), task.message ? (_jsx(Box, { paddingLeft: row.depth * 2 + 2, children: _jsxs(Text, { dimColor: true, children: [\"\\u2022 \", task.message] }) })) : null] }, row.key));\n }) }));\n}\nfunction getDisplayStatus(row, status) {\n if (row.action === \"noop\" && (status === \"created\" || status === \"updated\")) {\n return \"no change\";\n }\n return status;\n}\nfunction statusColor(status) {\n switch (status) {\n case \"no change\":\n return \"gray\";\n case \"pending\":\n return \"gray\";\n case \"creating\":\n case \"created\":\n return \"green\";\n case \"updating\":\n case \"updated\":\n return \"yellow\";\n case \"deleting\":\n case \"deleted\":\n return \"red\";\n case \"running\":\n case \"ran\":\n return \"cyan\";\n case \"skipped\":\n return \"gray\";\n case \"fail\":\n return \"redBright\";\n default:\n return undefined;\n }\n}\nfunction taskIcon(action, status, spinnerChar) {\n if (status === \"running\")\n return spinnerChar;\n if (status === \"fail\")\n return \"✗\";\n if (status === \"skipped\")\n return \"•\";\n if (status === \"ran\")\n return action === \"noop\" ? \"•\" : \"✓\";\n if (status === \"deleted\")\n return \"✓\";\n if (action === \"delete\")\n return \"-\";\n if (action === \"noop\")\n return \"•\";\n return \"λ\";\n}\nfunction statusIcon(status, spinnerChar) {\n if (isInProgress(status))\n return spinnerChar;\n if (status === \"fail\")\n return \"✗\";\n return \"✓\"; // created/updated/deleted/replaced/etc.\n}\nfunction isInProgress(status) {\n return (status === \"pending\" ||\n status === \"creating\" ||\n status === \"updating\" ||\n status === \"deleting\" ||\n status === \"running\");\n}\nconst spinnerFrames = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nfunction useGlobalSpinner(intervalMs = 80) {\n const [index, setIndex] = useState(0);\n useEffect(() => {\n const timer = setInterval(() => {\n setIndex((i) => (i + 1) % spinnerFrames.length);\n }, intervalMs);\n return () => clearInterval(timer);\n }, [intervalMs]);\n return spinnerFrames[index];\n}\nconst findCrudByLogicalId = (plan, logicalId) => {\n for (const node of Object.values(plan.resources)) {\n if (node.resource.LogicalId === logicalId) {\n return node;\n }\n }\n for (const node of Object.values(plan.deletions)) {\n if (node?.resource.LogicalId === logicalId) {\n return node;\n }\n }\n return undefined;\n};\n//# sourceMappingURL=PlanProgress.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { render } from \"ink\";\nimport { Cli } from \"../Cli.js\";\nimport { ApprovePlan } from \"./components/ApprovePlan.js\";\nimport { Plan as PlanComponent } from \"./components/Plan.js\";\nimport { PlanProgress } from \"./components/PlanProgress.js\";\nexport const inkCLI = () => Layer.succeed(Cli, Cli.of({\n approvePlan,\n displayPlan,\n startApplySession,\n}));\nconst approvePlan = Effect.fn(function* (plan) {\n let approved = false;\n const { waitUntilExit } = render(_jsx(ApprovePlan, { plan: plan, approve: (a) => (approved = a) }));\n yield* Effect.promise(waitUntilExit);\n return approved;\n});\nconst displayPlan = (plan) => Effect.sync(() => {\n const { unmount } = render(_jsx(PlanComponent, { plan: plan }));\n unmount();\n});\nconst startApplySession = Effect.fn(function* (plan) {\n const listeners = new Set();\n const { unmount } = render(_jsx(PlanProgress, { plan: plan, source: {\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n } }));\n return {\n done: Effect.fn(function* () {\n yield* Effect.sleep(10); // give the react event loop time to re-render\n yield* Effect.sync(() => unmount());\n }),\n emit: (event) => Effect.sync(() => {\n for (const listener of listeners)\n listener(event);\n }),\n };\n});\n//# sourceMappingURL=InkCLI.js.map","import * as Layer from \"effect/Layer\";\nimport { LoggingCli } from \"./LoggingCli.js\";\nimport { inkCLI } from \"./tui/InkCLI.js\";\n/**\n * Returns true when the current process looks like it's being driven by a\n * coding agent, CI runner, or anything else that won't render an interactive\n * TUI well. The Ink renderer repaints the screen on every event, which floods\n * agent transcripts with redundant frames; LoggingCli emits one line per\n * status change instead.\n */\nexport const isNonInteractive = () => {\n const env = process.env;\n if (env.ALCHEMY_PLAIN === \"1\" || env.ALCHEMY_NO_TUI === \"1\")\n return true;\n if (env.ALCHEMY_TUI === \"1\")\n return false;\n if (!process.stdout.isTTY)\n return true;\n if (env.CI)\n return true;\n // Known coding-agent env vars. These are best-effort — the isTTY check\n // above already catches most cases since agents typically pipe stdout.\n if (env.CLAUDECODE ||\n env.CLAUDE_CODE_ENTRYPOINT ||\n env.CURSOR_AGENT ||\n env.AIDER_MODEL ||\n env.CODEX_CLI)\n return true;\n return false;\n};\nexport const selectCli = () => isNonInteractive() ? LoggingCli : inkCLI();\n//# sourceMappingURL=selectCli.js.map","import * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport { AlchemyContextLive } from \"../AlchemyContext.js\";\nimport { CredentialsStoreLive } from \"../Auth/Credentials.js\";\nimport { ProfileLive } from \"../Auth/Profile.js\";\nimport * as RpcProviderProxy from \"../Local/RpcProviderProxy.js\";\nimport { PlatformServices } from \"../Util/PlatformServices.js\";\nimport { execStack, ExecStackOptions } from \"./commands/deploy.js\";\nimport { selectCli } from \"./selectCli.js\";\nconst services = Layer.merge(selectCli(), RpcProviderProxy.fromEnv()).pipe(Layer.provideMerge(Layer.mergeAll(AlchemyContextLive, ProfileLive, CredentialsStoreLive)), Layer.provideMerge(Layer.mergeAll(PlatformServices, FetchHttpClient.layer, ConfigProvider.layer(ConfigProvider.fromEnv()))));\nexport const exec = () => execStack(Schema.decodeSync(ExecStackOptions)(JSON.parse(process.env.ALCHEMY_EXEC_OPTIONS))).pipe(Effect.provide(services), Effect.scoped);\n//# sourceMappingURL=exec.js.map","import { exec } from \"alchemy/Cli\";\nimport { runMain } from \"alchemy/Util/PlatformServices\";\n\nexec().pipe(runMain);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAa,iBAAb,cAAoC,cAAc,SAAS,CAAC,kBAAkB,CAAC;AAE/E,MAAa,qBAAqB,MAAM,OAAO,gBAAgB,OAAO,IAAI,aAAa;CACnF,MAAM,KAAK,OAAO,WAAW;CAE7B,MAAM,OADO,OAAOA,OAAK,MACR,KAAK,QAAQ,KAAK,EAAE,WAAW;AAChD,QAAO,GAAG,cAAc,KAAK,EAAE,WAAW,MAAM,CAAC;AACjD,QAAO;EACH,YAAY;EACZ,kBAAkB;EAClB,KAAK;EACL,OAAO;EACV;EACH,CAAC;;;;ACVH,MAAa,UAAU,KAAK,KAAK,GAAG,SAAS,EAAE,WAAW;AAC1D,MAAa,iBAAiB,KAAK,KAAK,SAAS,gBAAgB;;;;;;AAMjE,MAAa,kBAAkB,OAAO,OAAO,kBAAkB,CAAC,KAAK,OAAO,YAAY,UAAU,CAAC;AACnG,MAAa,iBAAiB;AAG9B,MAAM,qBAAqB;CACvB,SAAS;CACT,UAAU,EAAE;CACf;AACD,IAAa,UAA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AAa,UAAU,OAAO,WAAW,iBAAiB,CAAC,KAAK,MAAM,QAAQ,IAAI,qBAAqB,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,SAAS,EAAE,OAAO,OAAO;;;;ACVpK,MAAM,CAAC,KAAK,QAAQ"}
|
|
1
|
+
{"version":3,"file":"exec.js","names":["Path","Context","profile","path","profile","Context","Context","Context","Context","path","Context","Context","Context","Context","stage","proxy","target","upstream","State.State","value","envFile","tag","path","Context","Output.stackRef","stackName","options","eff","make","services","Output.isOutput","Context","make","Context","Output.isExpr","Output.hasOutputs","Context","stage","c","Output.ResourceExpr","Output.isExpr","Output.of","value","Output.isResourceExpr","Output.isPropExpr","Output.isApplyExpr","upstream","Output.hasOutputs","Output.isEffectExpr","Output.isAllExpr","Output.isLiteralExpr","Output.isRefExpr","Output.InvalidReferenceError","Output.isStackRefExpr","Output.isNamedExpr","Output.upstreamAny","diff","stage","Output.evaluate","Output.resolveUpstream","node","path","S","stage","profile","Path","services","adopt","envFile","profile","stage","CLI.Cli","Plan.make","dryRun","yes","dryRunFlag","actionColor","statusColor","path","_jsx","_jsxs","_jsxs","_jsx","_jsx","_jsxs","color","icon","_jsx","PlanComponent","RpcProviderProxy.fromEnv"],"sources":["../lib/AlchemyContext.js","../lib/Auth/Profile.js","../lib/Auth/Credentials.js","../lib/Artifacts.js","../lib/Auth/AuthProvider.js","../lib/Cli/Cli.js","../lib/Ref.js","../lib/FQN.js","../lib/Provider.js","../lib/Resource.js","../lib/RuntimeContext.js","../lib/Stage.js","../lib/State/State.js","../lib/Util/data.js","../lib/Output.js","../lib/Util/ConfigProvider.js","../lib/Util/effect.js","../lib/Util/FileLogger.js","../lib/Util/PlatformServices.js","../lib/Stack.js","../lib/Local/RpcSerialization.js","../lib/Local/RpcProviderProxy.js","../lib/AdoptPolicy.js","../lib/Diff.js","../lib/InstanceId.js","../lib/Util/types.js","../lib/Telemetry/Metrics.js","../lib/Action.js","../lib/Util/hash.js","../lib/Util/scc.js","../lib/Plan.js","../lib/Apply.js","../lib/Cli/commands/_shared.js","../lib/Cli/commands/deploy.js","../lib/Cli/LoggingCli.js","../lib/Cli/NamespaceTree.js","../lib/Cli/tui/components/Plan.js","../lib/Cli/tui/components/ApprovePlan.js","../lib/Cli/tui/components/PlanProgress.js","../lib/Cli/tui/InkCLI.js","../lib/Cli/selectCli.js","../lib/Cli/exec.js","exec.ts"],"sourcesContent":["import * as EffectContext from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Path from \"effect/Path\";\nexport class AlchemyContext extends EffectContext.Service()(\"alchemy/Context\") {\n}\nexport const AlchemyContextLive = Layer.effect(AlchemyContext, Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const dir = path.join(process.cwd(), \".alchemy\");\n yield* fs.makeDirectory(dir, { recursive: true });\n return {\n dotAlchemy: dir,\n updateStateStore: false,\n dev: false,\n adopt: false,\n };\n}));\n//# sourceMappingURL=AlchemyContext.js.map","import * as Config from \"effect/Config\";\nimport * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport os from \"node:os\";\nimport path from \"pathe\";\nexport const rootDir = path.join(os.homedir(), \".alchemy\");\nexport const configFilePath = path.join(rootDir, \"profiles.json\");\n/**\n * Config key consulted by the various `fromAuthProvider` /\n * `fromEnvironment` layers to pick which named profile in\n * `~/.alchemy/profiles.json` to use. Defaults to `\"default\"`.\n */\nexport const ALCHEMY_PROFILE = Config.string(\"ALCHEMY_PROFILE\").pipe(Config.withDefault(\"default\"));\nexport const CONFIG_VERSION = 0;\nexport class AlchemyConfig extends Context.Service()(\"Alchemy::Profiles\") {\n}\nconst emptyConfig = () => ({\n version: CONFIG_VERSION,\n profiles: {},\n});\nexport class Profile extends Context.Service()(\"Alchemy::Profile\") {\n}\n/**\n * Layer that builds the {@link Profile} service. Captures the\n * {@link FileSystem.FileSystem} dependency at layer-build time, so any\n * Effect that yields {@link Profile} ends up with `R = Profile` (no\n * `FileSystem` leak). Provide this once at the top of your runtime\n * (alongside `PlatformServices` / `NodeContext`).\n */\nexport const ProfileLive = Layer.effect(Profile, Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const readConfig = fs\n .readFileString(configFilePath)\n .pipe(Effect.flatMap((data) => Effect.try({\n try: () => {\n const parsed = JSON.parse(data);\n if (parsed?.version !== CONFIG_VERSION) {\n // TODO(sam): this is destructive, should we maintain a chain of migrations from 0 to current?\n return emptyConfig();\n }\n return parsed;\n },\n catch: emptyConfig,\n })), Effect.orElseSucceed(emptyConfig));\n const writeConfig = (config) => fs\n .makeDirectory(path.dirname(configFilePath), { recursive: true })\n .pipe(Effect.flatMap(() => fs.writeFileString(configFilePath, JSON.stringify(config, null, 2))));\n const getProfile = (name) => readConfig.pipe(Effect.map((config) => config.profiles[name]));\n const setProfile = (name, profile) => readConfig.pipe(Effect.tap((config) => Effect.sync(() => (config.profiles[name] = profile))), Effect.flatMap(writeConfig));\n const deleteProfile = (name) => readConfig.pipe(Effect.flatMap((config) => {\n if (!(name in config.profiles)) {\n return Effect.succeed(false);\n }\n delete config.profiles[name];\n return writeConfig(config).pipe(Effect.as(true));\n }));\n const loadOrConfigure = (auth, profileName, ctx) => Effect.flatMap(getProfile(profileName), (existing) => existing?.[auth.name]\n ? Effect.succeed(existing[auth.name])\n : Effect.tap(auth.configure(profileName, ctx), (config) => setProfile(profileName, { ...existing, [auth.name]: config })));\n return {\n readConfig,\n writeConfig,\n getProfile,\n setProfile,\n deleteProfile,\n loadOrConfigure,\n };\n}));\n/**\n * Returns a `ConfigProvider` that overrides `ALCHEMY_PROFILE` with the\n * given `profile` (when explicitly passed via the CLI `--profile` flag),\n * falling through to `base` for everything else.\n *\n * Use this to let the CLI's `--profile <name>` win over `$ALCHEMY_PROFILE`\n * without disturbing other config lookups.\n */\nexport const withProfileOverride = (base, profile) => {\n if (profile === undefined)\n return base;\n const overrides = { ALCHEMY_PROFILE: profile };\n const overrideProvider = ConfigProvider.make((path) => Effect.succeed(path.length === 1 && typeof path[0] === \"string\" && path[0] in overrides\n ? ConfigProvider.makeValue(overrides[path[0]])\n : undefined));\n return ConfigProvider.orElse(base)(overrideProvider);\n};\n//# sourceMappingURL=Profile.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Redacted from \"effect/Redacted\";\nimport path from \"pathe\";\nimport { rootDir } from \"./Profile.js\";\nconst credentialsDirPath = path.join(rootDir, \"credentials\");\nexport const profileCredentialsDirPath = (profile) => path.join(credentialsDirPath, profile);\nexport const credentialsFilePath = (profile, provider) => path.join(profileCredentialsDirPath(profile), `${provider}.json`);\nexport class CredentialsStore extends Context.Service()(\"Alchemy::CredentialsStore\") {\n}\nexport const CredentialsStoreLive = Layer.effect(CredentialsStore, Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const read = (profile, provider) => fs.readFileString(credentialsFilePath(profile, provider)).pipe(Effect.catch(() => Effect.succeed(undefined)), Effect.map((data) => {\n if (data === undefined)\n return undefined;\n try {\n return JSON.parse(data);\n }\n catch {\n return undefined;\n }\n }));\n const write = (profile, provider, credentials) => {\n const filePath = credentialsFilePath(profile, provider);\n return fs.makeDirectory(path.dirname(filePath), { recursive: true }).pipe(Effect.flatMap(() => {\n return fs.writeFileString(filePath, JSON.stringify(credentials, null, 2));\n }));\n };\n const remove_ = (profile, provider) => fs\n .remove(credentialsFilePath(profile, provider))\n .pipe(Effect.catch(() => Effect.void));\n const deleteProfile = (profile) => fs\n .remove(profileCredentialsDirPath(profile), { recursive: true })\n .pipe(Effect.catch(() => Effect.void));\n return {\n read,\n write,\n delete: remove_,\n deleteProfile,\n };\n}));\nexport function displayRedacted(r, visibleChars = 4) {\n const raw = Redacted.value(r);\n if (raw.length <= visibleChars)\n return \"****\";\n return `${raw.slice(0, visibleChars)}****`;\n}\n//# sourceMappingURL=Credentials.js.map","import * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\n/**\n * Per-resource in-memory artifacts shared across a single `Plan.make -> apply`\n * execution.\n *\n * The engine scopes this service by resource `FQN` before invoking lifecycle\n * handlers, so providers should treat it as a resource-local bag for expensive,\n * deterministic intermediate results that can be reused across phases.\n *\n * Expected usage:\n *\n * - `diff` computes an expensive artifact once and stores it\n * - `create` / `update` reads the same artifact and skips recomputing it\n * - artifacts are ephemeral and must never be required for correctness on a\n * later deploy because the bag is reset between runs\n *\n * Example:\n *\n * ```ts\n * const artifacts = yield* Artifacts;\n * const cached = yield* artifacts.get<PreparedBundle>(\"bundle\");\n * if (cached) return cached;\n *\n * const bundle = yield* prepareBundle();\n * yield* artifacts.set(\"bundle\", bundle);\n * return bundle;\n * ```\n */\nexport class Artifacts extends Context.Service()(\"Artifacts\") {\n}\nexport class ArtifactStore extends Context.Service()(\"Artifacts/Store\") {\n}\n/**\n * Create a fresh root store for one deploy/test run.\n */\nexport const createArtifactStore = () => new Map();\nconst getOrCreateBag = (store, fqn) => {\n const existing = store.get(fqn);\n if (existing) {\n return existing;\n }\n const bag = new Map();\n store.set(fqn, bag);\n return bag;\n};\nexport const makeScopedArtifacts = (store, fqn) => {\n const bag = getOrCreateBag(store, fqn);\n return {\n get: (key) => Effect.sync(() => bag.get(key)),\n set: (key, value) => Effect.sync(() => {\n bag.set(key, value);\n }),\n delete: (key) => Effect.sync(() => {\n bag.delete(key);\n }),\n };\n};\nexport const scopedArtifacts = (fqn) => Layer.effect(Artifacts, ArtifactStore.useSync((store) => makeScopedArtifacts(store, fqn)));\n/**\n * Run an effect with a fresh artifact root, replacing any existing store.\n * Use this at top-level entrypoints that intentionally define a new deploy run.\n */\nexport const provideFreshArtifactStore = (effect) => effect.pipe(Effect.provideServiceEffect(ArtifactStore, Effect.sync(createArtifactStore)));\n/**\n * Ensure an artifact root exists, reusing the ambient store when one is already\n * present. This lets nested helpers participate in the same run-scoped cache.\n */\nexport const ensureArtifactStore = (effect) => Effect.serviceOption(ArtifactStore).pipe(Effect.map(Option.getOrUndefined), Effect.flatMap((existing) => effect.pipe(Effect.provideService(ArtifactStore, existing ?? createArtifactStore()))));\nexport const cached = (id) => (eff) => Effect.gen(function* () {\n const artifacts = yield* Artifacts;\n const deferred = yield* Deferred.make();\n const cached = yield* artifacts.get(id);\n if (cached) {\n if (Effect.isEffect(cached)) {\n return yield* cached;\n }\n return cached;\n }\n yield* artifacts.set(id, Deferred.await(deferred));\n const result = yield* eff;\n yield* Deferred.succeed(deferred, result);\n yield* artifacts.set(id, result);\n return result;\n});\n//# sourceMappingURL=Artifacts.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as Semaphore from \"effect/Semaphore\";\nimport { withLock } from \"./Lock.js\";\n/**\n * Methods on an {@link AuthProviderImpl} that mutate (or could trigger\n * mutation of) on-disk credentials. The factory wraps these in a\n * cross-process file lock keyed by `(profileName, providerName)` so that\n * concurrent processes never refresh / write credentials simultaneously.\n *\n * `prettyPrint` is intentionally excluded: it's read-only display.\n */\nconst LOCKED_METHODS = new Set([\"read\", \"login\", \"logout\", \"configure\"]);\n/**\n * Methods that may drive an interactive flow (prompts, browser-based\n * OAuth, etc.). A process-wide mutex serializes these across providers\n * so that, e.g., Cloudflare's `configure` finishes its prompt sequence\n * before Planetscale's begins — even when the two auth provider Layers\n * are built in parallel as part of a single `providers()` Layer.\n *\n * The clack prompt wrapper in `Util/Clank.ts` enforces per-prompt\n * serialization; this mutex enforces per-flow serialization so the user\n * sees one provider's prompts grouped together rather than interleaved.\n */\nconst INTERACTIVE_METHODS = new Set([\"login\", \"configure\"]);\nconst interactiveMutex = Semaphore.makeUnsafe(1);\nexport class AuthError extends Schema.TaggedErrorClass()(\"AuthError\", {\n message: Schema.String,\n cause: Schema.optional(Schema.Defect),\n}) {\n}\nexport class AuthProviders extends Context.Service()(\"AuthProviders\") {\n}\nexport const AuthProvider = () => (name, impl) => Effect.gen(function* () {\n const ctx = yield* Effect.context();\n const providers = yield* AuthProviders;\n const service = yield* Effect.isEffect(impl)\n ? impl\n : Effect.succeed(impl);\n return yield* Effect.sync(() => (providers[name] = {\n kind: \"AuthProvider\",\n name,\n ...Object.fromEntries(Object.entries(service).map(([methodName, fn]) => [\n methodName,\n (...args) => {\n let eff = fn(...args).pipe(Effect.provideContext(ctx));\n if (LOCKED_METHODS.has(methodName)) {\n // First positional arg is always `profileName`.\n const profileName = args[0];\n eff = withLock(`${profileName}-${name}`, eff);\n }\n if (INTERACTIVE_METHODS.has(methodName)) {\n eff = Semaphore.withPermits(interactiveMutex, 1)(eff);\n }\n return eff;\n },\n ])),\n }));\n});\n/**\n * Build a Layer that registers an AuthProvider into the {@link AuthProviders}\n * registry when its parent layer is built. Use this from a provider's\n * top-level `providers()` Layer so that `alchemy login` can discover the\n * provider via the registry without forcing credential resolution.\n */\nexport const AuthProviderLayer = () => (name, impl) => Layer.effectDiscard(AuthProvider()(name, impl));\n/**\n * Look up a registered {@link AuthProvider} by name. Fails with\n * {@link AuthError} if the provider hasn't been registered (typically because\n * its layer hasn't been built).\n */\nexport const getAuthProvider = (name) => AuthProviders.use((registry) => registry[name] == null\n ? Effect.fail(new AuthError({\n message: `AuthProvider '${name}' is not registered. Make sure its layer has been provided.`,\n }))\n : Effect.succeed(registry[name]));\n//# sourceMappingURL=AuthProvider.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nexport class Cli extends Context.Service()(\"CLI\") {\n}\n//# sourceMappingURL=Cli.js.map","import * as Output from \"./Output.js\";\n// special runtime-only symbol for probing the Ref proxy for its metadata\nconst RefMetadata = Symbol.for(\"alchemy/RefMetadata\");\nexport const isRef = (s) => s && s[RefMetadata] !== undefined;\nexport const getRefMetadata = (ref) => ref[RefMetadata];\nexport const ref = (id, { stack, stage, } = {}) => {\n const ref = new Proxy({}, {\n get: (_, prop) => {\n if (prop === RefMetadata) {\n return {\n stack,\n stage,\n id,\n };\n }\n return Output.of(ref)[prop];\n },\n });\n return ref;\n};\n//# sourceMappingURL=Ref.js.map","/**\n * Separator used in FQN strings.\n */\nexport const FQN_SEPARATOR = \"/\";\n/**\n * Encode an FQN for safe filesystem storage.\n * Replaces `/` (FQN separator) with `__` to avoid subdirectory creation.\n */\nexport const encodeFqn = (fqn) => fqn.replaceAll(FQN_SEPARATOR, \"__\");\n/**\n * Decode a filename back to FQN.\n */\nexport const decodeFqn = (filename) => filename.replaceAll(\"__\", FQN_SEPARATOR);\n/**\n * Convert a NamespaceNode chain to an array of namespace IDs, from root to leaf.\n *\n * @example\n * ```ts\n * const ns = { Id: \"Child\", Parent: { Id: \"Parent\", Parent: { Id: \"Root\" } } };\n * toPath(ns); // [\"Root\", \"Parent\", \"Child\"]\n * ```\n */\nexport const toPath = (ns) => {\n if (!ns)\n return [];\n const path = [];\n let current = ns;\n while (current) {\n path.unshift(current.Id);\n current = current.Parent;\n }\n return path;\n};\n/**\n * Create a fully-qualified name (FQN) from a namespace and logical ID.\n * The FQN is a flat key suitable for state storage.\n *\n * @example\n * ```ts\n * const ns = { Id: \"Child\", Parent: { Id: \"Parent\" } };\n * toFqn(ns, \"MyResource\"); // \"Parent/Child/MyResource\"\n * toFqn(undefined, \"MyResource\"); // \"MyResource\"\n * ```\n */\nexport const toFqn = (ns, logicalId) => {\n const path = toPath(ns);\n path.push(logicalId);\n return path.join(FQN_SEPARATOR);\n};\n/**\n * Parse an FQN back into namespace path segments and the logical ID.\n *\n * @example\n * ```ts\n * parseFqn(\"Parent/Child/MyResource\"); // { path: [\"Parent\", \"Child\"], logicalId: \"MyResource\" }\n * parseFqn(\"MyResource\"); // { path: [], logicalId: \"MyResource\" }\n * ```\n */\nexport const parseFqn = (fqn) => {\n const parts = fqn.split(FQN_SEPARATOR);\n const logicalId = parts.pop();\n return { path: parts, logicalId };\n};\n/**\n * Reconstruct a NamespaceNode chain from a path array.\n *\n * @example\n * ```ts\n * fromPath([\"Parent\", \"Child\"]);\n * // { Id: \"Child\", Parent: { Id: \"Parent\" } }\n * ```\n */\nexport const fromPath = (path) => {\n if (path.length === 0)\n return undefined;\n let node;\n for (const id of path) {\n node = { Id: id, Parent: node };\n }\n return node;\n};\n//# sourceMappingURL=FQN.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\nexport const Provider = (type) => Context.Service()(type);\nexport const effect = (cls, eff) => \n// @ts-expect-error\nLayer.effect(Provider(cls.Type), eff);\nexport const succeed = (cls, service) => \n// @ts-expect-error\nLayer.succeed(Provider(cls.Type), service);\nexport const ProviderCollection = () => (id) => Context.Service()(id);\nexport const collection = (resources) => Effect.gen(function* () {\n const context = yield* Effect.context();\n const providers = Object.fromEntries(yield* Effect.all(resources.map((resource) => \"Provider\" in resource\n ? resource.Provider.pipe(Effect.map((provider) => [resource.Type, provider]))\n : Effect.succeed([\n resource.key,\n context.mapUnsafe.get(resource.key),\n ])), { concurrency: \"unbounded\" }));\n return {\n kind: \"ProviderCollection\",\n get: (service) => providers[service],\n };\n});\nconst isProviderCollectionService = (value) => {\n return (typeof value === \"object\" &&\n value !== null &&\n \"kind\" in value &&\n value.kind === \"ProviderCollection\");\n};\nexport const findProviderByType = (type) => tryFindProviderByType(type).pipe(Effect.flatMap(Option.match({\n onNone: () => Effect.die(`Provider not found for ${type}`),\n onSome: (provider) => Effect.succeed(provider),\n})));\nexport const tryFindProviderByType = Effect.fnUntraced(function* (resourceType) {\n const Tag = Provider(resourceType);\n const direct = yield* Effect.serviceOption(Tag);\n if (Option.isSome(direct)) {\n return direct;\n }\n const context = yield* Effect.context();\n for (const value of context.mapUnsafe.values()) {\n if (isProviderCollectionService(value)) {\n const provider = value.get(resourceType);\n if (provider) {\n return Option.some(provider);\n }\n }\n }\n return Option.none();\n});\n//# sourceMappingURL=Provider.js.map","import * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport { pipeArguments } from \"effect/Pipeable\";\nimport { SingleShotGen } from \"effect/Utils\";\nimport { toFqn } from \"./FQN.js\";\nimport { CurrentNamespace } from \"./Namespace.js\";\nimport * as Output from \"./Output.js\";\nimport { Provider } from \"./Provider.js\";\nimport { ref as makeRef } from \"./Ref.js\";\nimport { RemovalPolicy } from \"./RemovalPolicy.js\";\nimport { Self } from \"./Self.js\";\nimport { Stack } from \"./Stack.js\";\nexport const isResource = (value) => {\n return typeof value === \"object\" && value !== null && \"Type\" in value;\n};\n/**\n * Creates a resource constructor for a concrete resource type.\n *\n * The returned constructor registers the resource on the current stack,\n * resolves input props, exposes output attributes as `Output` expressions, and\n * records bindings contributed by policies and event sources. Resource\n * providers are attached separately through `.provider`.\n */\nexport function Resource(type) {\n const self = Self(type);\n const constructor = (id, props) => Effect.gen(function* () {\n const stack = yield* Stack;\n const namespace = yield* CurrentNamespace;\n const fqn = toFqn(namespace, id);\n const existing = stack.resources[fqn];\n if (existing) {\n // // TODO(sam): check if props are different and die\n return existing;\n }\n const bind = (...args) => typeof args[0] === \"string\"\n ? Effect.gen(function* () {\n const [sid, data] = args;\n (stack.bindings[fqn] ??= []).push({\n sid,\n data,\n });\n return undefined;\n })\n : (data) => {\n const stringifyBindArg = (arg) => {\n if (arg === undefined) {\n return undefined;\n }\n if (Array.isArray(arg)) {\n return arg\n .flatMap((item) => {\n const stringified = stringifyBindArg(item);\n return stringified === undefined ? [] : [stringified];\n })\n .join(\", \");\n }\n if (arg &&\n (typeof arg === \"object\" || typeof arg === \"function\")) {\n if (\"LogicalId\" in arg && typeof arg.LogicalId === \"string\") {\n return arg.LogicalId;\n }\n if (\"id\" in arg && typeof arg.id === \"string\") {\n return arg.id;\n }\n }\n return String(arg);\n };\n return bind(`${args[0]\n .flatMap((text, i) => {\n const stringified = stringifyBindArg(args[i + 1]);\n return stringified !== undefined\n ? [text, stringified]\n : [text];\n })\n .join(\"\")}`, data);\n };\n const target = {\n Type: type,\n Namespace: namespace,\n FQN: fqn,\n LogicalId: id,\n Props: props,\n Provider: ProviderTag,\n RemovalPolicy: yield* Effect.serviceOption(RemovalPolicy).pipe(Effect.map(Option.getOrElse(() => \"destroy\"))),\n bind,\n toString() {\n return `Resource<${this.Type}>(${this.LogicalId})`;\n },\n [Symbol.toPrimitive](hint) {\n return hint === \"number\" ? NaN : this.toString();\n },\n };\n const Resource = (stack.resources[fqn] = new Proxy(target, {\n set: (t, prop, value) => {\n t[prop] = value;\n return true;\n },\n get: (t, prop) => typeof prop === \"symbol\" || prop in t\n ? t[prop]\n : new Output.PropExpr(Output.of(Resource), prop),\n }));\n Resource.Props = Effect.isEffect(props)\n ? yield* props.pipe(Effect.provideService(Self, Resource), Effect.provideService(Self(type), Resource))\n : props;\n return Resource;\n });\n const ProviderTag = Provider(type);\n const Service = {\n [Symbol.iterator]() {\n return new SingleShotGen(this.asEffect());\n },\n pipe() {\n return pipeArguments(this, arguments);\n },\n asEffect() {\n return Effect.succeed((id, props) => constructor(id, props));\n },\n /**\n * Build a typed reference to a deployed instance of this resource\n * — in the current stack/stage by default, or in another via\n * `options`. Resolves to the same shape as `yield*\n * MyResource(\"id\", props)` so downstream code can read attributes\n * (`ref.someAttr`) exactly the way it would for a locally-declared\n * resource.\n */\n ref: (id, options) => Effect.succeed(Output.of(makeRef(id, options))),\n Type: type,\n Provider: ProviderTag,\n Self: self,\n };\n const ResourceClass = Object.assign((...args) => typeof args[0] === \"object\"\n ? Object.assign(ResourceClass, args[0])\n : constructor(...args), Service);\n return ResourceClass;\n}\n//# sourceMappingURL=Resource.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Option from \"effect/Option\";\n/**\n * Canonicalize a logical key into a key that is safe to use as the name of an\n * environment variable / binding (`[a-zA-Z][a-zA-Z0-9_]*`).\n *\n * `RuntimeContext.set`/`get` are dumb key/value stores: they read and write the\n * key **verbatim**. It is the *caller's* responsibility to hand them a\n * canonical key, since the caller is the one that knows the logical key may\n * contain `.`/`-` (e.g. a dotted config name from `Platform`, or an\n * `Output.toString()` like `\"QueueSinkQueue.queueUrl\"`). Callers run the key\n * through this before calling `set`/`get` so both sides agree.\n */\nexport const sanitizeKey = (key) => key.replaceAll(/[^a-zA-Z0-9]/g, \"_\");\n/**\n * Context of the runtime environment.\n *\n * E.g. the context of a running Worker, Task, Process, Function\n */\nexport class RuntimeContext extends Context.Service()(\"RuntimeContext\") {\n}\nexport const CurrentRuntimeContext = Effect.serviceOption(RuntimeContext).pipe(Effect.map(Option.getOrUndefined));\n//# sourceMappingURL=RuntimeContext.js.map","import * as Context from \"effect/Context\";\nexport class Stage extends Context.Service()(\"Stage\") {\n}\n//# sourceMappingURL=Stage.js.map","import * as Context from \"effect/Context\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\nexport const isActionState = (s) => !!s && s.kind === \"action\";\nexport const isResourceState = (s) => !!s && s.kind !== \"task\";\nexport class StateStoreError extends Data.TaggedError(\"StateStoreError\") {\n}\nexport class State extends Context.Service()(\"alchemy/State\") {\n}\n//# sourceMappingURL=State.js.map","import * as Predicate from \"effect/Predicate\";\nimport * as EffectRecord from \"effect/Record\";\nimport * as Redacted from \"effect/Redacted\";\nexport const isPrimitive = (value) => value === undefined ||\n value === null ||\n typeof value === \"boolean\" ||\n typeof value === \"number\" ||\n typeof value === \"string\" ||\n typeof value === \"symbol\" ||\n typeof value === \"bigint\";\nexport const isPlainObject = (value) => {\n if (!Predicate.isObject(value))\n return false;\n return Object.getPrototypeOf(value) === Object.prototype;\n};\nexport const stripFields = (value, empty) => {\n if (Array.isArray(value)) {\n return value.map((item) => stripFields(item, empty));\n }\n if (!isPlainObject(value))\n return value;\n return EffectRecord.map(EffectRecord.filter(value, (entry) => entry !== empty), (entry) => stripFields(entry, empty));\n};\nexport const stripNullFields = (value) => stripFields(value, null);\nexport const stripUndefinedFields = (value) => stripFields(value, undefined);\nexport const unwrapRedacted = (value) => {\n if (Redacted.isRedacted(value)) {\n return Redacted.value(value);\n }\n if (Array.isArray(value)) {\n return value.map(unwrapRedacted);\n }\n if (!isPlainObject(value))\n return value;\n return EffectRecord.map(value, unwrapRedacted);\n};\n//# sourceMappingURL=data.js.map","import * as Data from \"effect/Data\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport { pipe } from \"effect/Function\";\nimport * as Redacted from \"effect/Redacted\";\nimport { SingleShotGen } from \"effect/Utils\";\nimport { getRefMetadata, isRef } from \"./Ref.js\";\nimport { isResource } from \"./Resource.js\";\nimport { RuntimeContext, sanitizeKey } from \"./RuntimeContext.js\";\nimport { Stack } from \"./Stack.js\";\nimport { Stage } from \"./Stage.js\";\nimport * as State from \"./State/State.js\";\nimport { isPrimitive } from \"./Util/data.js\";\nconst inspect = Symbol.for(\"nodejs.util.inspect.custom\");\nexport const of = (resource) => {\n if (isRef(resource)) {\n const metadata = getRefMetadata(resource);\n return new RefExpr(metadata.stack, metadata.stage, metadata.id);\n }\n return new ResourceExpr(resource);\n};\nexport const asOutput = (t) => isOutput(t)\n ? t\n : Effect.isEffect(t)\n ? new EffectExpr(VoidExpr, () => t)\n : new LiteralExpr(t);\nexport const isOutput = (value) => value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n ExprSymbol in value;\nexport const ExprSymbol = Symbol.for(\"alchemy/Expr\");\nexport const isExpr = (value) => value &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n ExprSymbol in value;\nexport class BaseExpr {\n // we use a kind tag instead of instanceof to protect ourselves from duplicate alchemy module imports\n constructor() { }\n as() {\n return this;\n }\n [Symbol.iterator]() {\n // @ts-expect-error - TODO(sam): fix this (works at runtime, but maybe indicates a bad assumption)\n return new SingleShotGen(this.asEffect());\n }\n asEffect() {\n return this.bind(this.toString());\n }\n bind(id) {\n // `set`/`get` store keys verbatim, so canonicalize here (the caller's job).\n const key = sanitizeKey(id);\n return RuntimeContext.pipe(Effect.flatMap((ctx) => Effect.map(ctx.set(key, this), (k) => ctx.get(k))));\n }\n pipe(...fns) {\n // @ts-expect-error\n return pipe(this, ...fns);\n }\n toString() {\n return this[inspect]();\n }\n}\nexport const isResourceExpr = (node) => node?.kind === \"ResourceExpr\";\nexport class ResourceExpr extends BaseExpr {\n src;\n stables;\n kind = \"ResourceExpr\";\n constructor(src, stables) {\n super();\n this.src = src;\n this.stables = stables;\n return proxy(this);\n }\n [inspect]() {\n return this.src.LogicalId;\n }\n}\nexport const isPropExpr = (node) => node?.kind === \"PropExpr\";\nexport class PropExpr extends BaseExpr {\n expr;\n identifier;\n kind = \"PropExpr\";\n constructor(expr, identifier) {\n super();\n this.expr = expr;\n this.identifier = identifier;\n return proxy(this);\n }\n [inspect]() {\n return `${this.expr[inspect]()}.${this.identifier.toString()}`;\n }\n}\nexport const literal = (value) => new LiteralExpr(value);\nexport const isLiteralExpr = (node) => node?.kind === \"LiteralExpr\";\nexport class LiteralExpr extends BaseExpr {\n value;\n kind = \"LiteralExpr\";\n constructor(value) {\n super();\n this.value = value;\n return proxy(this);\n }\n [inspect]() {\n return String(this.value);\n }\n}\nexport const VoidExpr = new LiteralExpr(void 0);\nexport const map = ((...args) => args.length === 1\n ? (output) => new ApplyExpr(output, args[0])\n : new ApplyExpr(args[0], args[1]));\n//Output.ApplyExpr<any, any, ResourceLike, any>\nexport const isApplyExpr = (node) => node?.kind === \"ApplyExpr\";\nexport class ApplyExpr extends BaseExpr {\n expr;\n f;\n kind = \"ApplyExpr\";\n constructor(expr, f) {\n super();\n this.expr = expr;\n this.f = f;\n return proxy(this);\n }\n [inspect]() {\n return `${this.expr[inspect]()}.map(${this.f.toString()})`;\n }\n}\nexport const mapEffect = (fn) => (output) => new EffectExpr(output, fn);\nexport const isEffectExpr = (node) => node?.kind === \"EffectExpr\";\nexport class EffectExpr extends BaseExpr {\n expr;\n f;\n kind = \"EffectExpr\";\n constructor(expr, f) {\n super();\n this.expr = expr;\n this.f = f;\n return proxy(this);\n }\n [inspect]() {\n return `${this.expr[inspect]()}.mapEffect(${this.f.toString()})`;\n }\n}\nexport const isNamedExpr = (node) => node?.kind === \"NamedExpr\";\n/**\n * Wraps another `Expr` and overrides its `toString()` / inspect output.\n *\n * `BaseExpr` derives the binding id from `this.toString()`, so\n * wrapping an expression in `NamedExpr` makes that derived id stable and\n * caller-controlled (e.g. an env var name like `\"API_KEY\"`).\n */\nexport class NamedExpr extends BaseExpr {\n expr;\n bindingName;\n kind = \"NamedExpr\";\n constructor(expr, bindingName) {\n super();\n this.expr = expr;\n this.bindingName = bindingName;\n return proxy(this);\n }\n [inspect]() {\n return this.bindingName;\n }\n}\nexport const named = (expr, name) => new NamedExpr(expr, name);\nexport const all = (...outs) => new AllExpr(outs);\nexport const isAllExpr = (node) => node?.kind === \"AllExpr\";\nexport class AllExpr extends BaseExpr {\n outs;\n kind = \"AllExpr\";\n constructor(outs) {\n super();\n this.outs = outs;\n return proxy(this);\n }\n [inspect]() {\n return `all(${this.outs.map((out) => out[inspect]()).join(\", \")})`;\n }\n}\nexport const isRefExpr = (node) => node?.kind === \"RefExpr\";\nexport class RefExpr extends BaseExpr {\n stack;\n stage;\n resourceId;\n kind = \"RefExpr\";\n constructor(stack, stage, resourceId) {\n super();\n this.stack = stack;\n this.stage = stage;\n this.resourceId = resourceId;\n return proxy(this);\n }\n [inspect]() {\n return `ref(${this.resourceId}, { stack: ${this.stack}, stage: ${this.stage} })`;\n }\n}\nexport const isStackRefExpr = (node) => node?.kind === \"StackRefExpr\";\n/**\n * A reference to the persisted output of a Stack at `(stack, stage)`.\n *\n * Resolved at evaluation time by reading `state.getOutput({ stack,\n * stage })`. Distinct from {@link RefExpr}, which references a\n * single resource's attributes within a stack/stage. `stage` may be\n * `undefined`, in which case it falls back to the current stage.\n */\nexport class StackRefExpr extends BaseExpr {\n stack;\n stage;\n kind = \"StackRefExpr\";\n constructor(stack, stage) {\n super();\n this.stack = stack;\n this.stage = stage;\n return proxy(this);\n }\n [inspect]() {\n return `stackRef(${this.stack}${this.stage ? `, { stage: ${this.stage} }` : \"\"})`;\n }\n}\n/**\n * Build an `Output<A>` referencing the persisted output of another\n * Stack. The returned Effect resolves to a lazy `Output<A>` whose\n * value is read from the state store at plan/apply time.\n *\n * Returns `Effect<Output<A>>` (not `Output<A>` directly) so that\n * `yield* Output.stackRef(...)` reads ergonomically inside an Effect\n * generator and lines up with `Resource.ref` and `Stack.stage.<name>`.\n */\nexport const stackRef = (stack, options = {}) => Effect.succeed(new StackRefExpr(stack, options.stage));\nexport const filter = (...outs) => outs.filter(isOutput);\nexport const interpolate = (template, ...args) => all(...args.map((arg) => (isOutput(arg) ? arg : literal(arg)))).pipe(map((args) => template\n .map((str, i) => str + (args[i] == null ? \"\" : String(args[i])))\n .join(\"\")));\nfunction proxy(self) {\n const target = Object.assign(() => { }, self);\n if (inspect in self) {\n Object.defineProperty(target, inspect, {\n value: self[inspect].bind(self),\n configurable: true,\n });\n }\n const proxy = new Proxy(target, {\n has: (_, prop) => prop === ExprSymbol || prop === inspect ? true : prop in self,\n get: (target, prop) => prop === Symbol.toPrimitive\n ? (hint) => {\n // Any JS-level coercion of an unresolved Output produces a\n // placeholder that *looks* like a real value but isn't:\n //\n // - `string` / `default` hints (`${output}`, `output + \"\"`,\n // `==` against a primitive) previously fell through to\n // `self.toString()` and returned the inspect form\n // (e.g. \"tunnel.tunnelId\"). The bogus string flowed\n // into resource props and into the cloud — only\n // surfacing as an opaque downstream error (see PR\n // description for a real Cloudflare DNS landing).\n //\n // - `number` hint (`+output`, `output * 2`,\n // `Math.max(0, output)`) previously returned NaN, which\n // propagates silently through arithmetic and lands as\n // \"the API rejected a NaN field\" much later.\n //\n // All three hints fail loud at the coercion site with a\n // pointer to the right composition API.\n throw new Error(`Cannot coerce Output<${self[inspect]()}> to a ` +\n `${hint === \"number\" ? \"number\" : \"string\"} via JS coercion. ` +\n `Use Output.interpolate\\`...\\` or Output.map(output, fn) ` +\n `to compose Outputs — the value isn't known until deploy time.`);\n }\n : prop === ExprSymbol\n ? self\n : prop === inspect\n ? target[inspect]\n : isResourceExpr(self) && self.stables && prop in self.stables\n ? self.stables[prop]\n : prop === \"apply\"\n ? self[prop]\n : prop in self\n ? typeof self[prop] === \"function\" &&\n !(\"kind\" in self)\n ? new PropExpr(proxy, prop)\n : self[prop]\n : new PropExpr(proxy, prop),\n apply: (_, thisArg, args) => {\n if (isPropExpr(self)) {\n if (self.identifier === \"apply\") {\n return new ApplyExpr(self.expr, args[0]);\n }\n else if (self.identifier === \"effect\") {\n return new EffectExpr(self.expr, args[0]);\n }\n }\n return undefined;\n },\n });\n return proxy;\n}\n/// Evaluation\nexport class MissingSourceError extends Data.TaggedError(\"MissingSourceError\") {\n}\nexport class InvalidReferenceError extends Data.TaggedError(\"InvalidReferenceError\") {\n}\nexport const evaluate = (expr, upstream) => Effect.gen(function* () {\n if (isResource(expr)) {\n const srcId = expr.FQN;\n const src = upstream[srcId];\n if (!src) {\n // type-safety should prevent this but let the caller decide how to handle it\n return yield* new MissingSourceError({\n message: `Source ${srcId} not found`,\n srcId,\n });\n }\n return src;\n }\n else if (isOutput(expr)) {\n if (isResourceExpr(expr)) {\n const srcId = expr.src.FQN;\n const src = upstream[srcId];\n if (!src) {\n // type-safety should prevent this but let the caller decide how to handle it\n return yield* new MissingSourceError({\n message: `Source ${srcId} not found`,\n srcId,\n });\n }\n return src;\n }\n else if (isLiteralExpr(expr)) {\n return expr.value;\n }\n else if (isApplyExpr(expr)) {\n return expr.f(yield* evaluate(expr.expr, upstream));\n }\n else if (isEffectExpr(expr)) {\n // TODO(sam): the same effect shoudl be memoized so that it's not run multiple times\n return yield* expr.f(yield* evaluate(expr.expr, upstream));\n }\n else if (isAllExpr(expr)) {\n return yield* Effect.all(expr.outs.map((out) => evaluate(out, upstream)));\n }\n else if (isPropExpr(expr)) {\n return (yield* evaluate(expr.expr, upstream))?.[expr.identifier];\n }\n else if (isNamedExpr(expr)) {\n return yield* evaluate(expr.expr, upstream);\n }\n else if (isRefExpr(expr)) {\n const state = yield* State.State;\n const stack = expr.stack ?? (yield* Stack).name;\n const stage = expr.stage ?? (yield* Stage);\n const resource = yield* state.get({\n stack,\n stage,\n fqn: expr.resourceId,\n });\n if (!resource) {\n return yield* Effect.fail(new InvalidReferenceError({\n message: `Reference to '${expr.resourceId}' in stack '${stack}' and stage '${stage}' not found. Have you deployed '${stage}' or '${stack}'?`,\n stack,\n stage,\n resourceId: expr.resourceId,\n }));\n }\n // RefExpr targets persisted resources; tasks aren't cross-stack\n // referenceable. Return the resource's output attrs, otherwise the\n // task's output value, otherwise undefined.\n return resource.attr ?? resource.output;\n }\n else if (isStackRefExpr(expr)) {\n const state = yield* State.State;\n const stack = expr.stack;\n const stage = expr.stage ?? (yield* Stage);\n const output = yield* state.getOutput({ stack, stage });\n if (output == null) {\n return yield* Effect.fail(new InvalidReferenceError({\n message: `Reference to stack '${stack}' at stage '${stage}' not found. Have you deployed stage '${stage}' of '${stack}'?`,\n stack,\n stage,\n resourceId: stack,\n }));\n }\n return output;\n }\n }\n if (Array.isArray(expr)) {\n return yield* Effect.all(expr.map((item) => evaluate(item, upstream)));\n }\n else if (Redacted.isRedacted(expr)) {\n return expr;\n }\n else if (Duration.isDuration(expr)) {\n // Opaque value — see resolveInput in Plan.ts for rationale.\n return expr;\n }\n else if (typeof expr === \"object\" && expr !== null) {\n return Object.fromEntries(yield* Effect.all(Object.entries(expr).map(([key, value]) => evaluate(value, upstream).pipe(Effect.map((value) => [key, value])))));\n }\n return expr;\n});\nexport const hasOutputs = (value) => Object.keys(upstreamAny(value)).length > 0;\nexport const upstreamAny = (value) => {\n if (isResource(value)) {\n return { [value.FQN]: value };\n }\n else if (isExpr(value)) {\n return upstream(value);\n }\n else if (Array.isArray(value)) {\n return Object.assign({}, ...value.map(resolveUpstream));\n }\n else if (value &&\n (typeof value === \"object\" || typeof value === \"function\")) {\n return Object.assign({}, ...Object.values(value).map((value) => resolveUpstream(value)));\n }\n return {};\n};\n// TODO(sam): add a type\nexport const upstream = (expr) => {\n if (isResource(expr)) {\n return {\n [expr.FQN]: expr,\n };\n }\n else if (isResourceExpr(expr)) {\n return {\n [expr.src.FQN]: expr.src,\n };\n }\n else if (isPropExpr(expr)) {\n return upstream(expr.expr);\n }\n else if (isAllExpr(expr)) {\n return Object.assign({}, ...expr.outs.map((out) => upstream(out)));\n }\n else if (isEffectExpr(expr) || isApplyExpr(expr) || isNamedExpr(expr)) {\n return upstream(expr.expr);\n }\n else if (Array.isArray(expr)) {\n return expr.map(upstream).reduce(toObject, {});\n }\n else if (typeof expr === \"object\" && expr !== null) {\n return Object.values(expr)\n .map((v) => upstream(v))\n .reduce(toObject, {});\n }\n return {};\n};\n// TODO(sam): add a type\nexport const resolveUpstream = (value) => {\n if (isPrimitive(value)) {\n return {};\n }\n else if (isResource(value)) {\n return { [value.FQN]: value };\n }\n else if (isOutput(value)) {\n return upstream(value);\n }\n else if (Array.isArray(value)) {\n return Object.fromEntries(value.map((v) => resolveUpstream(v)).flatMap(Object.entries));\n }\n else if (typeof value === \"object\" || typeof value === \"function\") {\n return Object.fromEntries(Object.values(value)\n .map(resolveUpstream)\n .flatMap(Object.entries));\n }\n return {};\n};\nconst toObject = (acc, v) => ({\n ...acc,\n ...v,\n});\nexport const log = (_value) => Effect.gen(function* () {\n // TODO(sam): implement a log effect\n});\nexport const toEnvKey = (id, suffix) => `${replace(toUpper(id))}_${replace(toUpper(suffix))}`;\nexport const toUpper = (str) => str.toUpperCase();\nconst replace = (str) => str.replace(/-/g, \"_\");\n//# sourceMappingURL=Output.js.map","import * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Option from \"effect/Option\";\nexport const loadConfigProvider = (envFile) => {\n if (Option.isSome(envFile)) {\n return ConfigProvider.fromDotEnv({ path: envFile.value }).pipe(Effect.map((dotEnv) => ConfigProvider.orElse(dotEnv, ConfigProvider.fromEnv())));\n }\n return Effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const exists = yield* fs.exists(\".env\");\n if (!exists) {\n return ConfigProvider.fromEnv();\n }\n return ConfigProvider.orElse(yield* ConfigProvider.fromDotEnv({ path: \".env\" }), ConfigProvider.fromEnv());\n });\n};\n//# sourceMappingURL=ConfigProvider.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport { pipeArguments } from \"effect/Pipeable\";\nimport { SingleShotGen } from \"effect/Utils\";\nexport const effectClass = ((impl) => impl === undefined\n ? (innerImpl) => effectClass(innerImpl)\n : Object.assign(class {\n static asEffect() {\n return impl;\n }\n static [Symbol.iterator]() {\n return new SingleShotGen(this.asEffect());\n }\n static pipe(...fns) {\n return pipeArguments(this, fns);\n }\n }, impl));\nexport const taggedFunction = (tag, fn) => {\n const overrides = {\n asEffect: () => tag,\n [Symbol.iterator]: () => tag[Symbol.iterator](),\n pipe: (...fns) => pipeArguments(tag, fns),\n toString: () => `${tag.toString()}.${fn.name}`,\n };\n return new Proxy(fn, {\n get: (target, prop, receiver) => Reflect.has(overrides, prop)\n ? Reflect.get(overrides, prop, receiver)\n : Reflect.has(target, prop)\n ? Reflect.get(target, prop, receiver)\n : Reflect.get(tag, prop, tag),\n has: (target, prop) => Reflect.has(overrides, prop) ||\n Reflect.has(target, prop) ||\n Reflect.has(tag, prop),\n });\n};\nexport const isYieldableEffect = (value) => Effect.isEffect(value) &&\n typeof value[Symbol.iterator] ===\n \"function\";\nexport const isEffectClassLike = (value) => typeof value === \"function\" &&\n typeof value.asEffect === \"function\";\nexport const isYieldableEffectLike = (value) => isYieldableEffect(value) || isEffectClassLike(value);\nexport const toEffectInterface = (raw) => ({\n raw,\n ...Object.fromEntries(Object.entries(raw).map(([key, value]) => [\n key,\n typeof value === \"function\"\n ? (...args) => Effect.tryPromise(async () => value(...args))\n : value,\n ])),\n});\n//# sourceMappingURL=effect.js.map","import * as Effect from \"effect/Effect\";\nimport * as FileSystem from \"effect/FileSystem\";\nimport * as Logger from \"effect/Logger\";\nimport { Path } from \"effect/Path\";\nimport { AlchemyContext } from \"../AlchemyContext.js\";\nexport const fileLogger = Effect.fnUntraced(function* (...segments) {\n const { dotAlchemy } = yield* AlchemyContext;\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path;\n const logFile = path.join(dotAlchemy, \"log\", ...segments);\n yield* fs.makeDirectory(path.dirname(logFile), { recursive: true });\n return yield* Logger.formatLogFmt.pipe(Logger.toFile(logFile, {\n flag: \"a\",\n }));\n});\n//# sourceMappingURL=FileLogger.js.map","import * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nconst isBun = typeof Bun !== \"undefined\";\n/**\n * Constructs a layer with different implementations for Bun and Node.\n */\nexport const platformLayer = (constructors) => Layer.unwrap(Effect.promise(async () => {\n if (isBun) {\n return await constructors.bun();\n }\n else {\n return await constructors.node();\n }\n}));\nexport const PlatformServices = platformLayer({\n bun: async () => {\n const [BunServices, BunSocket] = await Promise.all([\n import(\"@effect/platform-bun/BunServices\"),\n import(\"@effect/platform-bun/BunSocket\"),\n ]);\n return Layer.merge(BunServices.layer, BunSocket.layerWebSocketConstructor);\n },\n node: async () => {\n const [NodeServices, NodeSocket] = await Promise.all([\n import(\"@effect/platform-node/NodeServices\"),\n import(\"@effect/platform-node/NodeSocket\"),\n ]);\n return Layer.merge(NodeServices.layer, NodeSocket.layerWebSocketConstructor);\n },\n});\nexport const runMain = (effect, options) => {\n if (isBun) {\n void import(\"@effect/platform-bun/BunRuntime\").then((BunRuntime) => BunRuntime.runMain(effect, options));\n }\n else {\n void import(\"@effect/platform-node/NodeRuntime\").then((NodeRuntime) => NodeRuntime.runMain(effect, options));\n }\n};\nexport const httpServer = (port = 0, host = \"127.0.0.1\") => platformLayer({\n bun: async () => {\n const BunHttpServer = await import(\"@effect/platform-bun/BunHttpServer\");\n return BunHttpServer.layer({ hostname: host, port });\n },\n node: async () => {\n const [NodeHttpServer, Http] = await Promise.all([\n import(\"@effect/platform-node/NodeHttpServer\"),\n import(\"node:http\"),\n ]);\n return NodeHttpServer.layerServer(Http.createServer, { host, port });\n },\n});\n//# sourceMappingURL=PlatformServices.js.map","import { ConfigProvider } from \"effect/ConfigProvider\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport { FileSystem } from \"effect/FileSystem\";\nimport * as Layer from \"effect/Layer\";\nimport * as Logger from \"effect/Logger\";\nimport * as Option from \"effect/Option\";\nimport { Path } from \"effect/Path\";\nimport * as Scope from \"effect/Scope\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport { AlchemyContext, AlchemyContextLive } from \"./AlchemyContext.js\";\nimport { provideFreshArtifactStore } from \"./Artifacts.js\";\nimport { AuthProviders } from \"./Auth/AuthProvider.js\";\nimport { CredentialsStore, CredentialsStoreLive } from \"./Auth/Credentials.js\";\nimport { Profile, ProfileLive } from \"./Auth/Profile.js\";\nimport { Cli } from \"./Cli/Cli.js\";\nimport * as Output from \"./Output.js\";\nimport { Stage } from \"./Stage.js\";\nimport { loadConfigProvider } from \"./Util/ConfigProvider.js\";\nimport { effectClass, taggedFunction } from \"./Util/effect.js\";\nimport { fileLogger } from \"./Util/FileLogger.js\";\nimport { PlatformServices } from \"./Util/PlatformServices.js\";\nexport const Stack = Object.assign(taggedFunction(Context.Service()(\"Stack\"), (stackName, options, eff) => {\n if (!stackName) {\n return (stackName) => Object.assign(\n // by default, reference the stack at the \"current\" stage of the importer\n Output.stackRef(stackName).pipe(effectClass), {\n stage: createStageProxy(stackName),\n make: (options, eff) => Stack(stackName, options, eff),\n });\n }\n return eff.pipe(make({\n name: stackName,\n ...options,\n }), (eff) => Object.assign(eff, {\n stage: createStageProxy(stackName),\n }));\n}));\nconst createStageProxy = (stackName) => new Proxy({}, {\n get: (_, stage) => Output.stackRef(stackName, { stage }),\n});\nexport const StackName = Stack.use((stack) => Effect.succeed(stack.name));\nexport const make = (options) => (effect) => Effect.scope.pipe(Effect.flatMap((scope) => {\n if (options.state == null) {\n return Effect.die(new Error(`Stack \"${options.name}\" is missing a state store. ` +\n `Add a \\`state\\` layer to the stack options, e.g.:\\n` +\n ` Alchemy.Stack(\"${options.name}\", {\\n` +\n ` providers: Cloudflare.providers(),\\n` +\n ` state: Cloudflare.state(), // <-- required\\n` +\n ` }, ...)\\n` +\n `See https://v2.alchemy.run/concepts/state-store for available state stores.`));\n }\n if (options.providers == null) {\n return Effect.die(new Error(`Stack \"${options.name}\" is missing a providers layer. ` +\n `Add a \\`providers\\` layer to the stack options, e.g.:\\n` +\n ` Alchemy.Stack(\"${options.name}\", {\\n` +\n ` providers: Cloudflare.providers(), // <-- required\\n` +\n ` state: Cloudflare.state(),\\n` +\n ` }, ...)`));\n }\n return options.providers.pipe(Layer.provideMerge(options.state), Layer.provideMerge(Layer.effect(Stack, Stage.pipe(Effect.map((stage) => options.stack ?? {\n name: options.name,\n stage,\n resources: {},\n bindings: {},\n actions: {},\n })))), Layer.buildWithScope(scope));\n}), Effect.flatMap((context) => Effect.all([\n effect,\n Stack,\n Effect.context(),\n]).pipe(Effect.map(([output, stack, services]) => ({\n ...stack,\n output,\n services: Context.merge(services, context),\n})), Effect.provideContext(context))));\nexport const CurrentStack = Effect.serviceOption(Stack)\n .pipe(Effect.map(Option.getOrUndefined));\nconst platform = Layer.mergeAll(PlatformServices, FetchHttpClient.layer, Logger.layer([fileLogger(\"out\")], { mergeWithExisting: true }), Layer.provide(ProfileLive, PlatformServices), Layer.provide(CredentialsStoreLive, PlatformServices));\n// override alchemy state store, CLI/reporting, state, and Config\nconst alchemy = (overrides) => Layer.mergeAll(\n// CLI.inkCLI(),\n// optional\noverrides?.dev\n ? Layer.provide(Layer.effect(AlchemyContext, AlchemyContext.useSync((ctx) => ({ ...ctx, dev: overrides.dev }))), AlchemyContextLive)\n : AlchemyContextLive);\nexport const evalStack = (effect, fn, options) => {\n const body = Effect.gen(function* () {\n const stack = yield* effect;\n const configProvider = yield* loadConfigProvider(Option.none());\n return yield* fn(stack).pipe(provideFreshArtifactStore, Effect.provide(stack.services), Effect.provide(Layer.succeed(ConfigProvider, configProvider)));\n }).pipe(Effect.provide(Layer.effect(AuthProviders, Effect.serviceOption(AuthProviders).pipe(Effect.map(Option.getOrElse(() => ({})))))), Effect.provide(Layer.succeed(Stage, options.stage)), Effect.provide(Layer.provideMerge(alchemy({ dev: options.dev }), platform)));\n return options.scope === undefined\n ? Effect.scoped(body)\n : Scope.provide(body, options.scope);\n};\n//# sourceMappingURL=Stack.js.map","import * as Cause from \"effect/Cause\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport { flow } from \"effect/Function\";\nimport * as Redacted from \"effect/Redacted\";\nimport * as Schema from \"effect/Schema\";\nimport * as Stream from \"effect/Stream\";\nimport * as NodeUtil from \"node:util\";\nimport * as Output from \"../Output.js\";\nexport const wrapRpcHandlers = (handlers, streamKeys) => {\n return Object.fromEntries(Object.entries(handlers).map(([key, value]) => [\n key,\n typeof value === \"function\"\n ? streamKeys?.includes(key)\n ? wrapRpcStreamHandler(value)\n : wrapRpcEffectHandler(value)\n : typeof value === \"object\" && value !== null\n ? wrapRpcHandlers(value)\n : value,\n ]));\n};\nexport const unwrapRpcHandlers = (handlers, streamKeys) => {\n return Object.fromEntries(Object.entries(handlers).map(([key, value]) => [\n key,\n typeof value === \"function\"\n ? streamKeys?.includes(key)\n ? unwrapRpcStreamHandler(value)\n : unwrapRpcEffectHandler(value)\n : typeof value === \"object\" && value !== null\n ? unwrapRpcHandlers(value)\n : value,\n ]));\n};\nconst serializeError = Schema.encodeSync(Schema.Defect);\nconst wrapRpcEffectHandler = (handler) => flow((args) => deserializeRpcArgs(args), (args) => handler(...args), Effect.exit, Effect.map((exit) => {\n if (exit._tag === \"Success\") {\n return { _tag: \"Success\", value: exit.value };\n }\n return {\n _tag: \"Failure\",\n cause: exit.cause.reasons.map((reason) => {\n switch (reason._tag) {\n case \"Fail\":\n return { _tag: \"Fail\", error: serializeError(reason.error) };\n case \"Die\":\n return { _tag: \"Die\", defect: serializeError(reason.defect) };\n case \"Interrupt\":\n return { _tag: \"Interrupt\", fiberId: reason.fiberId };\n }\n }),\n };\n}), Effect.runPromise);\nconst wrapRpcStreamHandler = (handler) => flow((args) => deserializeRpcArgs(args), (args) => handler(...args), (stream) => Stream.toReadableStream(stream));\nconst unwrapRpcEffectHandler = (handler) => flow((...args) => serializeRpcArgs(args), (args) => Effect.promise(() => handler(args)), Effect.flatMap((exit) => {\n if (exit._tag === \"Success\") {\n return Exit.succeed(exit.value);\n }\n return Exit.failCause(Cause.fromReasons(exit.cause.map((reason) => {\n switch (reason._tag) {\n case \"Fail\":\n return Cause.makeFailReason(reason.error);\n case \"Die\":\n return Cause.makeDieReason(reason.defect);\n case \"Interrupt\":\n return Cause.makeInterruptReason(reason.fiberId);\n }\n })));\n}));\nconst unwrapRpcStreamHandler = (handler) => flow((...args) => serializeRpcArgs(args), (args) => handler(args), (stream) => Stream.fromReadableStream({\n evaluate: () => stream,\n onError: (error) => error,\n}));\nconst serializeRpcArgs = (value) => {\n if (Redacted.isRedacted(value)) {\n return { _tag: \"Redacted\", value: Redacted.value(value) };\n }\n if (Output.isOutput(value)) {\n return {\n _tag: \"Output\",\n description: NodeUtil.inspect(value),\n };\n }\n if (typeof value === \"function\") {\n return null;\n }\n if (Array.isArray(value)) {\n return value.map(serializeRpcArgs);\n }\n if (value && typeof value === \"object\" && !(\"toJSON\" in value)) {\n return Object.fromEntries(Object.entries(value).map(([key, child]) => [\n key,\n serializeRpcArgs(child),\n ]));\n }\n return value;\n};\nconst deserializeRpcArgs = (value) => {\n if (Array.isArray(value)) {\n return value.map(deserializeRpcArgs);\n }\n else if (typeof value === \"object\" && value !== null) {\n // These values are serialized as `{_tag: \"Redacted\", value: ...}` and `{_tag: \"Output\", description: ...}`,\n // so we need to detect them manually - Redacted.isRedacted and Output.isOutput do not work.\n if (\"_tag\" in value && value._tag === \"Redacted\" && \"value\" in value) {\n return Redacted.make(value.value);\n }\n else if (\"_tag\" in value &&\n value._tag === \"Output\" &&\n \"description\" in value &&\n typeof value.description === \"string\") {\n return new Output.NamedExpr(new Output.EffectExpr(Output.VoidExpr, () => Effect.never), value.description);\n }\n return Object.fromEntries(Object.entries(value).map(([key, child]) => [\n key,\n deserializeRpcArgs(child),\n ]));\n }\n return value;\n};\n//# sourceMappingURL=RpcSerialization.js.map","import { newWebSocketRpcSession } from \"capnweb\";\nimport * as Cache from \"effect/Cache\";\nimport * as Config from \"effect/Config\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as HttpBody from \"effect/unstable/http/HttpBody\";\nimport * as HttpClient from \"effect/unstable/http/HttpClient\";\nimport { AlchemyContext } from \"../AlchemyContext.js\";\nimport { Stack } from \"../Stack.js\";\nimport { unwrapRpcHandlers } from \"./RpcSerialization.js\";\nexport class RpcProviderProxy extends Context.Service()(\"alchemy/Local/RpcProviderProxy\") {\n}\nexport const SPAWNER_URL_ENV_KEY = \"ALCHEMY_RPC_SPAWNER_URL\";\nconst make = Effect.fnUntraced(function* (spawnerUrl) {\n const client = yield* HttpClient.HttpClient;\n const getSession = Effect.fnUntraced(function* (serverEntryUrl) {\n const alchemyContext = yield* AlchemyContext;\n const stack = yield* Stack;\n const payload = {\n serverEntryUrl,\n alchemyContext,\n stack: { name: stack.name, stage: stack.stage },\n };\n const response = yield* client.post(spawnerUrl, {\n body: yield* HttpBody.json(payload),\n });\n const websocketUrl = yield* response.text;\n return newWebSocketRpcSession(websocketUrl);\n }, (effect, serverEntryUrl) => Effect.catch(effect, (error) => Effect.die(new Error(`Failed to create provider RPC session for \"${serverEntryUrl}\"`, {\n cause: error,\n }))));\n const cache = yield* Cache.make({\n lookup: getSession,\n capacity: Infinity,\n requireServicesAt: \"lookup\",\n });\n return RpcProviderProxy.of({\n get: Effect.fnUntraced(function* (mainUrl, providerName) {\n const session = yield* cache.lookup(mainUrl);\n const provider = yield* Effect.promise(() => session.getProvider(providerName));\n return unwrapRpcHandlers(provider, [\"tail\"]);\n }),\n });\n});\nexport const layer = (url) => Layer.effect(RpcProviderProxy, make(url));\nexport const fromEnv = () => Layer.effect(RpcProviderProxy, Config.string(SPAWNER_URL_ENV_KEY).pipe(Effect.flatMap(make)));\n//# sourceMappingURL=RpcProviderProxy.js.map","import * as Context from \"effect/Context\";\nimport * as Data from \"effect/Data\";\nimport * as Effect from \"effect/Effect\";\n/**\n * AdoptPolicy controls whether the engine should \"adopt\" pre-existing cloud\n * resources that conflict with this stack instead of failing.\n *\n * The engine always calls a provider's `read` lifecycle operation when there\n * is no prior state and `read` is implemented. The provider's job is to\n * report two things:\n *\n * 1. Whether the resource exists (returns attributes vs. `undefined`).\n * 2. Whether *we* own it (plain attributes vs. {@link Unowned}-branded).\n *\n * The engine then routes:\n *\n * | `read` outcome | `adopt: false` | `adopt: true` |\n * | ------------------- | -------------- | ----------------- |\n * | undefined | create | create |\n * | owned (plain attrs) | silent adopt | silent adopt |\n * | {@link Unowned} | fail | takeover (adopt) |\n *\n * \"Owned\" means a provider has affirmatively determined the resource was\n * created by this stack/stage/logical-id (typically by inspecting tags or\n * naming conventions). Resources without ownership semantics simply always\n * return plain attrs — they are treated as owned by default, so silent\n * adoption is the norm and `--adopt` is unnecessary.\n *\n * The policy can be overridden per-effect via {@link adopt} — most commonly\n * applied at the resource or stack scope.\n */\nexport class AdoptPolicy extends Context.Service()(\"AdoptPolicy\") {\n}\n/**\n * Engine-raised failure produced when `read` reports an existing resource\n * marked as {@link Unowned} and `adopt` is `false`. Surface this to the user\n * to indicate they should either re-tag the cloud resource, pick a different\n * physical name, or re-run with `--adopt` (or `adopt(true)`) to force a\n * takeover.\n */\nexport class OwnedBySomeoneElse extends Data.TaggedError(\"OwnedBySomeoneElse\") {\n}\n/**\n * Private symbol used to brand attribute objects returned by `read` as\n * \"exists in cloud, but not owned by this stack/stage/logical-id\".\n *\n * Deliberately *not* registered via `Symbol.for` — the brand is an\n * engine-internal routing hint and must not be observable or\n * forgeable from outside this module. The engine strips it before any\n * state persistence (see {@link stripUnowned}) so it never leaks into\n * the state store, JSON serialization, or downstream `Output`s.\n */\nconst UnownedTag = Symbol(\"alchemy/Unowned\");\n/**\n * Brand a `read` return value as belonging to a different owner.\n *\n * Use this in a provider's `read` implementation when the resource exists in\n * the cloud but a positive ownership check (e.g. tag inspection) shows it\n * was *not* created by this stack/stage/logical-id:\n *\n * ```ts\n * read: Effect.fnUntraced(function* ({ id, output, olds }) {\n * const settings = yield* getScriptSettings({ ... }).pipe(\n * Effect.catchTag(\"WorkerNotFound\", () => Effect.succeed(undefined)),\n * );\n * if (!settings) return undefined;\n *\n * const attrs = { workerName, ...buildAttrs(settings) };\n * return hasAlchemyWorkerTags(id, settings.tags) ? attrs : Unowned(attrs);\n * }),\n * ```\n *\n * The returned value is structurally still `T` — there is no wrapper to\n * unwrap. The brand is a non-enumerable symbol that the engine inspects\n * during planning to decide whether to take over (`adopt: true`) or fail\n * loudly (`adopt: false`).\n *\n * Resources without ownership semantics should simply return plain attrs —\n * the engine treats them as owned and silent adoption is the default.\n */\nexport const Unowned = Object.assign((attrs) => {\n const cloned = { ...attrs };\n Object.defineProperty(cloned, UnownedTag, {\n value: true,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n return cloned;\n}, {\n is: (value) => typeof value === \"object\" &&\n value !== null &&\n value[UnownedTag] === true,\n});\n/**\n * Strip the {@link Unowned} brand from an attributes object before persisting\n * it — state should not carry per-deploy ownership-routing metadata.\n *\n * The brand is intentionally non-enumerable, so a plain spread already\n * drops it; the additional `delete` is defense-in-depth in case a future\n * change makes the descriptor enumerable. Always returns a fresh object\n * (never mutates the input).\n */\nexport const stripUnowned = (attrs) => {\n const out = { ...attrs };\n if (UnownedTag in out)\n delete out[UnownedTag];\n return out;\n};\nexport const adopt = ((enabled) => (eff) => eff.pipe(typeof enabled === \"boolean\"\n ? Effect.provideService(AdoptPolicy, enabled ?? true)\n : Effect.provideServiceEffect(AdoptPolicy, enabled)));\n//# sourceMappingURL=AdoptPolicy.js.map","import * as Effect from \"effect/Effect\";\nimport * as Output from \"./Output.js\";\nimport { isPrimitive } from \"./Util/data.js\";\n/**\n * Returns true when `value` (or any nested leaf) is still an unresolved\n * plan-time expression — i.e. an `Output`/`Expr` or an `Effect` that was\n * not fully evaluated by `resolveInput` in Plan.ts.\n *\n * Use at the top of a provider `diff` to short-circuit before field access:\n *\n * ```ts\n * if (!isResolved(news)) return undefined;\n * const resolved = news as MyProps;\n * ```\n */\nexport const hasUnresolvedInputs = (value) => _hasUnresolved(value);\nexport const isResolved = (value) => !_hasUnresolved(value);\nconst _hasUnresolved = (value) => {\n if (value == null || isPrimitive(value))\n return false;\n if (Output.isExpr(value) || Effect.isEffect(value))\n return true;\n if (Array.isArray(value))\n return value.some(_hasUnresolved);\n if (typeof value === \"object\") {\n return Object.values(value).some(_hasUnresolved);\n }\n return false;\n};\nexport const somePropsAreDifferent = (olds, news, props) => {\n for (const prop of props) {\n if (olds[prop] !== news[prop]) {\n return true;\n }\n }\n return false;\n};\nexport const anyPropsAreDifferent = (olds, news) => {\n for (const prop in olds) {\n if (olds[prop] !== news[prop]) {\n return true;\n }\n }\n for (const prop in news) {\n if (!(prop in olds)) {\n return true;\n }\n }\n return false;\n};\nexport const havePropsChanged = (oldProps, newProps) => Output.hasOutputs(newProps) ||\n JSON.stringify(canonicalize(oldProps ?? {}, false)) !==\n JSON.stringify(canonicalize(newProps ?? {}, false));\n/**\n * Sort-keys deep equality for plain data (objects, arrays, primitives).\n * Use in provider `diff` handlers instead of ad-hoc `JSON.stringify` comparisons.\n *\n * By default, `null` and `undefined` are treated as distinct. Pass\n * `{ stripNullish: true }` to opt into treating them as equivalent.\n */\nexport const deepEqual = (a, b, options) => JSON.stringify(canonicalize(a, options?.stripNullish ?? false)) ===\n JSON.stringify(canonicalize(b, options?.stripNullish ?? false));\nconst canonicalize = (value, stripNullish) => {\n if (stripNullish && value == null)\n return undefined;\n if (Array.isArray(value)) {\n return value.map((v) => canonicalize(v, stripNullish));\n }\n if (value && typeof value === \"object\") {\n return Object.fromEntries(Object.entries(value)\n .filter(([, nested]) => !stripNullish || nested != null)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, nested]) => [key, canonicalize(nested, stripNullish)]));\n }\n return value;\n};\n/**\n * Collapse bindings that share the same `sid`, keeping the last occurrence.\n *\n * The same binding can be recorded more than once on a target resource — e.g.\n * a KV namespace bound to both a Worker and a Workflow ends up pushed twice to\n * `stack.bindings[fqn]`. `diffBindings` already collapses these implicitly via\n * its `Map` keyed by `sid`, so the `reconcile` path never observes duplicates.\n * Use this helper to give a provider's `diff` handler the same de-duplicated\n * binding set, keeping plan-time hashing consistent with deploy-time.\n */\nexport const dedupeBindings = (bindings) => Array.from(new Map(bindings.map((b) => [b.sid, b])).values());\nexport const diffBindings = (oldBindings, newBindings) => {\n const oldMap = new Map(oldBindings.map((b) => [b.sid, b]));\n const newMap = new Map(newBindings.map((b) => [b.sid, b]));\n return [\n ...Array.from(oldMap)\n .filter(([sid]) => !newMap.has(sid))\n .map(([sid, old]) => ({\n sid,\n action: \"delete\",\n data: old.data,\n })),\n ...Array.from(newMap).map(([sid, binding]) => {\n const old = oldMap.get(sid);\n return {\n sid,\n action: (!old\n ? \"create\"\n : havePropsChanged(old.data, binding.data)\n ? \"update\"\n : \"noop\"),\n data: binding.data,\n };\n }),\n ];\n};\n//# sourceMappingURL=Diff.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\n/** A 16-byte (128-bit) random hex-encoded string representing an physical instance of a logical resource */\nexport class InstanceId extends Context.Service()(\"instance-id\") {\n}\n/**\n * @returns Hex-encoded instance ID (16 random bytes)\n */\nexport const generateInstanceId = () => Effect.sync(() => {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n return Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n});\n//# sourceMappingURL=InstanceId.js.map","import * as Effect from \"effect/Effect\";\nexport const assertDefined = (value, message) => {\n if (!value) {\n throw new Error(message);\n }\n return value;\n};\nexport const asEffect = (effect) => typeof effect?.asEffect === \"function\"\n ? effect.asEffect()\n : Effect.isEffect(effect)\n ? effect\n : Effect.succeed(effect);\n//# sourceMappingURL=types.js.map","import * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Metric from \"effect/Metric\";\n/**\n * Counter for resource lifecycle operations. Tagged per call with\n * `resource_type`, `op` (`precreate`/`create`/`update`/`delete`/`read`),\n * and `status` (`success`/`error`).\n */\nexport const resourceCounter = Metric.counter(\"alchemy.resource.operations\", {\n description: \"Number of resource lifecycle operations dispatched by alchemy apply.\",\n incremental: true,\n});\n/**\n * Histogram of how long each lifecycle operation takes.\n */\nexport const resourceDuration = Metric.timer(\"alchemy.resource.duration\", {\n description: \"Wall-clock duration of resource lifecycle operations dispatched by alchemy apply.\",\n});\n/**\n * Counter for CLI command invocations.\n */\nexport const cliCounter = Metric.counter(\"alchemy.cli.invocations\", {\n description: \"Number of alchemy CLI command invocations.\",\n incremental: true,\n});\n/**\n * Counter for Cloudflare State Store bootstrap/deploy operations.\n * Tagged per call with `op` (e.g. `deploy`) and `status`\n * (`success`/`error`) so that the deploy success rate of the\n * state store itself can be tracked separately from regular\n * resource lifecycle ops.\n */\nexport const stateStoreCounter = Metric.counter(\"alchemy.state_store.operations\", {\n description: \"Number of Cloudflare State Store deploy/bootstrap operations dispatched by alchemy.\",\n incremental: true,\n});\n/**\n * Counter for State store layer construction. Tagged with `id` (the\n * `StateService.id` slug) so we can answer \"how many distinct projects\n * are using each backend\" from the corresponding `state_store.init`\n * spans. Open-ended on purpose: third-party state stores get counted\n * automatically by setting their `StateService.id`.\n */\nexport const stateStoreInitCounter = Metric.counter(\"alchemy.state_store.inits\", {\n description: \"Number of times a State store layer is constructed.\",\n incremental: true,\n});\n/**\n * Wraps a resource lifecycle Effect to record a counter + timer entry,\n * tagged with `resource_type`, `op`, and `status` (`success`/`error`).\n *\n * Usage:\n * ```ts\n * provider.reconcile(input).pipe(recordResourceOp(node.resource.Type, \"create\"))\n * ```\n */\nexport const recordResourceOp = (resourceType, op) => (self) => Effect.suspend(() => {\n const startNs = process.hrtime.bigint();\n const baseAttrs = { resource_type: resourceType, op };\n return self.pipe(Effect.onExit((exit) => recordOutcome(baseAttrs, Exit.isSuccess(exit) ? \"success\" : \"error\", elapsed(startNs))));\n});\n/**\n * Wraps a CLI command Effect to bump {@link cliCounter} with the\n * outcome (`success`/`error`).\n */\nexport const recordCli = (command) => (self) => self.pipe(Effect.onExit((exit) => Metric.update(Metric.withAttributes(cliCounter, {\n command,\n status: Exit.isSuccess(exit) ? \"success\" : \"error\",\n}), 1)));\n/**\n * Wraps a Cloudflare State Store deploy/bootstrap Effect to bump\n * {@link stateStoreCounter} with the outcome (`success`/`error`),\n * tagged with the given `op`.\n */\nexport const recordStateStoreOp = (op) => (self) => self.pipe(Effect.onExit((exit) => Metric.update(Metric.withAttributes(stateStoreCounter, {\n op,\n status: Exit.isSuccess(exit) ? \"success\" : \"error\",\n}), 1)));\n/**\n * Wraps a State store construction Effect to:\n *\n * 1. Bump {@link stateStoreInitCounter} tagged with `id`.\n * 2. Open a `state_store.init` span carrying\n * `alchemy.state_store.id` so Axiom (which can't query metric\n * datasets via APL) can group projects by backend.\n *\n * The `id` is read off the constructed `StateService.id` field, so any\n * third-party state-store implementation gets tracked just by setting\n * a stable slug there. Apply at every `Layer.effect(State, …)` site\n * exactly once.\n */\nexport const recordStateStoreInit = (self) => self.pipe(Effect.tap((service) => Effect.all([\n Metric.update(Metric.withAttributes(stateStoreInitCounter, { id: service.id }), 1),\n Effect.annotateCurrentSpan(\"alchemy.state_store.id\", service.id),\n], { discard: true })), Effect.withSpan(\"state_store.init\"));\nconst elapsed = (startNs) => Duration.nanos(process.hrtime.bigint() - startNs);\nconst recordOutcome = (baseAttrs, status, duration) => {\n const attrs = { ...baseAttrs, status };\n return Effect.all([\n Metric.update(Metric.withAttributes(resourceCounter, attrs), 1),\n Metric.update(Metric.withAttributes(resourceDuration, attrs), duration),\n ], { discard: true });\n};\n//# sourceMappingURL=Metrics.js.map","import * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { toFqn } from \"./FQN.js\";\nimport { CurrentNamespace } from \"./Namespace.js\";\nimport * as Output from \"./Output.js\";\nimport { Stack } from \"./Stack.js\";\nexport const isAction = (value) => typeof value === \"object\" && value !== null && value?.Kind === \"action\";\nexport function Action(...args) {\n if (args.length === 0) {\n // Tagged form: Action<Self, In, Out>()(type)\n return (type) => makeActionClass(type, undefined);\n }\n // Inline form: Action(type, runnerOrInit)\n const [type, initOrRun] = args;\n return makeActionClass(type, initOrRun);\n}\nconst isRunnerEffect = (v) => Effect.isEffect(v);\nconst makeActionClass = (type, baked) => {\n // Pre-resolve baked init/runner into a single Effect<Runner, _, Req>. Use\n // Effect.cached so the init's body runs at most once per process — every\n // action instance after the first reuses the resolved runner without paying\n // the init cost (or re-yielding its dependencies).\n let resolveRunner;\n if (baked !== undefined) {\n resolveRunner = isRunnerEffect(baked)\n ? Effect.runSync(Effect.cached(baked))\n : Effect.succeed(baked);\n }\n // Tagged form needs a Context tag so the user can supply the runner\n // through a Layer. Inline form bakes the runner in and skips the tag.\n const SelfTag = baked\n ? undefined\n : Context.Service(`alchemy/Action<${type}>`);\n const constructor = (...args) => {\n const [id, input] = args.length === 1 ? [type, args[0]] : args;\n return Effect.gen(function* () {\n const run = resolveRunner\n ? yield* resolveRunner\n : (yield* SelfTag);\n return yield* registerAction(type, id, input, run);\n });\n };\n const extra = { Type: type };\n if (SelfTag) {\n extra.Self = SelfTag;\n // `.make(initOrRun)` — accepts either a direct runner or an init Effect.\n // For init form we use `Layer.effect` so the init's Req surfaces on the\n // Layer; for runners we use `Layer.succeed`.\n extra.make = (initOrRun) => isRunnerEffect(initOrRun)\n ? Layer.effect(SelfTag, initOrRun)\n : Layer.succeed(SelfTag, initOrRun);\n }\n return Object.assign(constructor, extra);\n};\nconst registerAction = (type, id, input, run) => Effect.gen(function* () {\n const stack = yield* Stack;\n const namespace = yield* CurrentNamespace;\n const fqn = toFqn(namespace, id);\n const actions = (stack.actions ??= {});\n const existing = actions[fqn];\n if (existing)\n return Output.of(existing);\n // FQN collision check: actions share the same FQN namespace as resources\n // so the dependency graph stays unified. Rejecting overlaps here makes\n // the constraint obvious at registration time.\n if (stack.resources[fqn]) {\n return yield* Effect.die(new Error(`Action '${fqn}' collides with a Resource of the same logical id`));\n }\n const target = {\n Kind: \"action\",\n Type: type,\n Namespace: namespace,\n FQN: fqn,\n LogicalId: id,\n Input: input,\n Run: run,\n Output: undefined,\n };\n target.toString = () => `Action<${type}>(${id})`;\n actions[fqn] = target;\n // `yield* Sync({...})` returns `Output<Out>`. The engine writes the\n // materialized value into `tracker[fqn]` during apply; `Output.of(action)`\n // resolves a ResourceExpr by looking up `outputs[fqn]` — which is\n // precisely that materialized value. Property access into the returned\n // Output chains through the standard PropExpr proxy.\n return Output.of(target);\n});\n//# sourceMappingURL=Action.js.map","import { createHash } from \"node:crypto\";\nimport * as Effect from \"effect/Effect\";\n/**\n * Stable hash of a resolved Task input. Wrapped in `Effect.sync` so the\n * call participates in the Effect runtime (tracing/interruption) per the\n * Effect-platform conventions.\n */\nexport const hashInput = (input) => Effect.sync(() => createHash(\"sha256\")\n .update(JSON.stringify(input ?? null))\n .digest(\"hex\"));\n//# sourceMappingURL=hash.js.map","/**\n * Compute the set of graph nodes that participate in a dependency cycle.\n *\n * A node is considered \"in a cycle\" iff it sits in a strongly-connected\n * component (SCC) of size > 1, or has a self-edge (size-1 SCC that loops\n * back to itself).\n *\n * Implementation is iterative Tarjan's algorithm to avoid blowing the JS\n * call stack on very wide graphs.\n */\nexport const findCycleMembers = (edges) => {\n const cycleMembers = new Set();\n let index = 0;\n const indexOf = new Map();\n const lowlink = new Map();\n const onStack = new Set();\n const stack = [];\n const callStack = [];\n const startNode = (node) => {\n indexOf.set(node, index);\n lowlink.set(node, index);\n index += 1;\n stack.push(node);\n onStack.add(node);\n callStack.push({ node, childIdx: 0 });\n };\n for (const root of Object.keys(edges)) {\n if (indexOf.has(root))\n continue;\n startNode(root);\n while (callStack.length > 0) {\n const frame = callStack[callStack.length - 1];\n const children = edges[frame.node] ?? [];\n if (frame.childIdx < children.length) {\n const child = children[frame.childIdx];\n frame.childIdx += 1;\n if (!indexOf.has(child)) {\n startNode(child);\n continue;\n }\n if (onStack.has(child)) {\n lowlink.set(frame.node, Math.min(lowlink.get(frame.node), indexOf.get(child)));\n }\n continue;\n }\n // All children processed: maybe close an SCC.\n if (lowlink.get(frame.node) === indexOf.get(frame.node)) {\n const scc = [];\n for (;;) {\n const w = stack.pop();\n onStack.delete(w);\n scc.push(w);\n if (w === frame.node)\n break;\n }\n if (scc.length > 1) {\n for (const fqn of scc)\n cycleMembers.add(fqn);\n }\n else {\n // Size-1 SCC: only counts as a cycle if it has a self-edge.\n const only = scc[0];\n if ((edges[only] ?? []).includes(only)) {\n cycleMembers.add(only);\n }\n }\n }\n // Pop frame and propagate lowlink up to the parent.\n callStack.pop();\n const parent = callStack[callStack.length - 1];\n if (parent) {\n const cur = lowlink.get(parent.node);\n const childLow = lowlink.get(frame.node);\n if (childLow < cur)\n lowlink.set(parent.node, childLow);\n }\n }\n }\n return cycleMembers;\n};\n//# sourceMappingURL=scc.js.map","import * as Data from \"effect/Data\";\nimport * as Duration from \"effect/Duration\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Redacted from \"effect/Redacted\";\nimport { asEffect } from \".//Util/types.js\";\nimport { AdoptPolicy, OwnedBySomeoneElse, stripUnowned, Unowned, } from \"./AdoptPolicy.js\";\nimport { AlchemyContext } from \"./AlchemyContext.js\";\nimport { Artifacts, ArtifactStore, createArtifactStore, ensureArtifactStore, makeScopedArtifacts, } from \"./Artifacts.js\";\nimport { dedupeBindings, diffBindings, havePropsChanged, isResolved, } from \"./Diff.js\";\nimport { parseFqn } from \"./FQN.js\";\nimport { generateInstanceId, InstanceId } from \"./InstanceId.js\";\nimport * as Output from \"./Output.js\";\nimport { findProviderByType, Provider, } from \"./Provider.js\";\nimport { isResource, } from \"./Resource.js\";\nimport {} from \"./Stack.js\";\nimport { State, isActionState, } from \"./State/index.js\";\nimport { isAction } from \"./Action.js\";\nimport { hashInput } from \"./Util/hash.js\";\nimport { findCycleMembers } from \"./Util/scc.js\";\nexport const isCRUD = (node) => {\n return (node &&\n typeof node === \"object\" &&\n (node.action === \"create\" ||\n node.action === \"update\" ||\n node.action === \"replace\" ||\n node.action === \"noop\"));\n};\nexport const make = (stack, options = {}) => \n// @ts-expect-error\nEffect.gen(function* () {\n const state = yield* State;\n const resources = Object.values(stack.resources);\n const actions = Object.values(stack.actions ?? {});\n // TODO(sam): rename terminology to Stack\n const stackName = stack.name;\n const stage = stack.stage;\n // Resolve the effective adoption setting for this plan. AdoptPolicy\n // (provided by the CLI or scoped via `adopt(...)`) takes precedence; if\n // unset, fall back to the AlchemyContext's `adopt` default; otherwise\n // adoption is disabled.\n const shouldAdopt = Effect.gen(function* () {\n const fromService = yield* Effect.serviceOption(AdoptPolicy);\n if (Option.isSome(fromService))\n return fromService.value;\n const ctx = yield* Effect.serviceOption(AlchemyContext);\n return Option.match(ctx, {\n onNone: () => false,\n onSome: (c) => c.adopt,\n });\n });\n const resourceFqns = yield* state.list({\n stack: stackName,\n stage: stage,\n });\n const oldResources = yield* Effect.all(resourceFqns.map((fqn) => state.get({ stack: stackName, stage: stage, fqn })), { concurrency: \"unbounded\" });\n const resolvedResources = {};\n const resolveResource = (resourceExpr) => Effect.gen(function* () {\n // Tasks share the ResourceExpr machinery but have no provider /\n // stable-properties story at plan time. Leave the expression\n // unsubstituted — Apply resolves it from the tracker at run time.\n if (isAction(resourceExpr.src)) {\n return resourceExpr;\n }\n // @ts-expect-error\n return yield* (resolvedResources[resourceExpr.src.FQN] ??=\n yield* Effect.cached(Effect.gen(function* () {\n const resource = resourceExpr.src;\n const provider = yield* findProviderByType(resource.Type);\n const props = yield* resolveInput(resource.Props);\n const persisted = yield* state.get({\n stack: stackName,\n stage: stage,\n fqn: resource.FQN,\n });\n const oldState = isActionState(persisted)\n ? undefined\n : persisted;\n if (!oldState || oldState.status === \"creating\") {\n return resourceExpr;\n }\n const oldProps = oldState.status === \"updating\"\n ? oldState.old.props\n : oldState.props;\n const oldBindings = oldState.bindings ?? [];\n // Collapse duplicate bindings by sid so the binding set handed to\n // `diff` matches what `reconcile` receives (see `dedupeBindings`).\n const newBindings = dedupeBindings(stack.bindings[resource.FQN] ?? []);\n const diff = yield* provider.diff\n ? provider\n .diff({\n id: resource.LogicalId,\n olds: oldProps,\n instanceId: oldState.instanceId,\n news: props,\n output: oldState.attr,\n oldBindings,\n newBindings,\n })\n .pipe(providePlanScope(resource.FQN, oldState.instanceId))\n : Effect.succeed(undefined);\n const stables = [\n ...(provider.stables ?? []),\n ...(diff?.stables ?? []),\n ];\n const withStables = (output) => stables.length > 0\n ? new Output.ResourceExpr(resourceExpr.src, Object.fromEntries(stables.map((stable) => [stable, output?.[stable]])))\n : // if there are no stable properties, treat every property as changed\n resourceExpr;\n if (diff == null) {\n if (havePropsChanged(oldProps, props)) {\n // the props have changed but the provider did not provide any hints as to what is stable\n // so we must assume everything has changed\n return withStables(oldState?.attr);\n }\n }\n else if (diff.action === \"update\") {\n return withStables(oldState?.attr);\n }\n else if (diff.action === \"replace\") {\n return resourceExpr;\n }\n if (oldState.status === \"created\" ||\n oldState.status === \"updated\" ||\n oldState.status === \"replaced\") {\n // we can safely return the attributes if we know they have stabilized\n return oldState?.attr;\n }\n else {\n // we must assume the resource doesn't exist if it hasn't stabilized\n return resourceExpr;\n }\n })));\n });\n const resolveInput = (input) => Effect.gen(function* () {\n if (!input) {\n return input;\n }\n else if (Output.isExpr(input)) {\n return yield* resolveOutput(input);\n }\n else if (Redacted.isRedacted(input)) {\n return input;\n }\n else if (Duration.isDuration(input)) {\n // Duration is an opaque value; walking its internal `.value`\n // would destroy the prototype and produce a plain `{ value: ... }`\n // object that downstream consumers can't interpret.\n return input;\n }\n else if (Array.isArray(input)) {\n return yield* Effect.all(input.map(resolveInput), {\n concurrency: \"unbounded\",\n });\n }\n else if (isResource(input)) {\n // Resource objects have dynamic properties (path, hash, etc.) that are\n // created on-demand by a Proxy getter and aren't enumerable via Object.entries.\n // Resolve the ResourceExpr to get the actual resource output, then continue\n // resolving any nested outputs in the result.\n const resourceExpr = Output.of(input);\n const resolved = yield* resolveOutput(resourceExpr);\n return yield* resolveInput(resolved);\n }\n else if (typeof input === \"object\") {\n return Object.fromEntries(yield* Effect.all(Object.entries(input).map(([key, value]) => resolveInput(value).pipe(Effect.map((value) => [key, value]))), { concurrency: \"unbounded\" }));\n }\n return input;\n });\n const resolveOutput = (expr) => Effect.gen(function* () {\n if (Output.isResourceExpr(expr)) {\n return yield* resolveResource(expr);\n }\n else if (Output.isPropExpr(expr)) {\n const upstream = yield* resolveOutput(expr.expr);\n return upstream?.[expr.identifier];\n }\n else if (Output.isApplyExpr(expr)) {\n const upstream = yield* resolveOutput(expr.expr);\n return Output.hasOutputs(upstream) ? expr : expr.f(upstream);\n }\n else if (Output.isEffectExpr(expr)) {\n const upstream = yield* resolveOutput(expr.expr);\n return Output.hasOutputs(upstream) ? expr : yield* expr.f(upstream);\n }\n else if (Output.isAllExpr(expr)) {\n return yield* Effect.all(expr.outs.map(resolveOutput), {\n concurrency: \"unbounded\",\n });\n }\n else if (Output.isLiteralExpr(expr)) {\n return expr.value;\n }\n else if (Output.isRefExpr(expr)) {\n const refStack = expr.stack ?? stackName;\n const refStage = expr.stage ?? stage;\n const refState = yield* state\n .get({\n stack: refStack,\n stage: refStage,\n fqn: expr.resourceId,\n })\n .pipe(Effect.orDie);\n if (!refState) {\n return yield* Effect.die(new Output.InvalidReferenceError({\n message: `Reference to '${expr.resourceId}' in stack '${refStack}' and stage '${refStage}' not found. Have you deployed '${refStage}' of '${refStack}'?`,\n stack: refStack,\n stage: refStage,\n resourceId: expr.resourceId,\n }));\n }\n return refState.attr ?? refState.output;\n }\n else if (Output.isStackRefExpr(expr)) {\n const refStack = expr.stack;\n const refStage = expr.stage ?? stage;\n const output = yield* state\n .getOutput({\n stack: refStack,\n stage: refStage,\n })\n .pipe(Effect.orDie);\n if (output == null) {\n return yield* Effect.die(new Output.InvalidReferenceError({\n message: `Reference to stack '${refStack}' at stage '${refStage}' not found. Have you deployed stage '${refStage}' of '${refStack}'?`,\n stack: refStack,\n stage: refStage,\n resourceId: refStack,\n }));\n }\n return output;\n }\n else if (Output.isNamedExpr(expr)) {\n return yield* resolveOutput(expr.expr);\n }\n return yield* Effect.die(new Error(\"Not implemented yet\" + expr.kind));\n });\n // map of resource FQN -> its downstream dependencies (resources that depend on it)\n const oldDownstreamDependencies = Object.fromEntries(oldResources\n .filter((resource) => !!resource)\n .map((resource) => [resource.fqn, resource.downstream]));\n // Build a set of FQNs for the new resources to detect orphans\n const newResourceFqns = new Set(resources.map((r) => r.FQN));\n const newActionFqns = new Set(actions.map((t) => t.FQN));\n // Unified set used wherever the DAG must include both kinds.\n const newNodeFqns = new Set([...newResourceFqns, ...newActionFqns]);\n // Map FQN -> list of upstream FQNs (resources this one depends on via props).\n // Tasks contribute upstream edges through their `Input` expression.\n const newUpstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => [\n resource.FQN,\n Object.values(Output.upstreamAny(resource.Props)).map((r) => r.FQN),\n ]),\n ...actions.map((action) => [\n action.FQN,\n Object.values(Output.upstreamAny(action.Input)).map((r) => r.FQN),\n ]),\n ]);\n // Map FQN -> list of upstream FQNs from bindings\n const bindingUpstreamDependencies = Object.fromEntries(resources.map((resource) => [\n resource.FQN,\n Object.values(Output.upstreamAny(stack.bindings[resource.FQN] ?? [])).map((r) => r.FQN),\n ]));\n // Combined prop + binding upstream for the desired graph, including\n // references to resources outside the current graph so delete validation can\n // tell whether any surviving resource still points at an orphan.\n const rawUpstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => {\n const fqn = resource.FQN;\n const propDeps = newUpstreamDependencies[fqn] ?? [];\n const bindDeps = bindingUpstreamDependencies[fqn] ?? [];\n return [fqn, [...new Set([...propDeps, ...bindDeps])]];\n }),\n // Actions have no bindings — their upstream is purely their input.\n ...actions.map((action) => {\n const fqn = action.FQN;\n return [fqn, newUpstreamDependencies[fqn] ?? []];\n }),\n ]);\n // Combined prop + binding upstream, filtered to resources/tasks in this\n // graph for scheduling and cycle detection.\n const allUpstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => {\n const fqn = resource.FQN;\n const deps = rawUpstreamDependencies[fqn] ?? [];\n return [fqn, deps.filter((dep) => newNodeFqns.has(dep))];\n }),\n ...actions.map((action) => {\n const fqn = action.FQN;\n const deps = newUpstreamDependencies[fqn] ?? [];\n return [fqn, deps.filter((dep) => newNodeFqns.has(dep))];\n }),\n ]);\n // Resources that participate in a cycle when both prop and binding\n // edges are considered. Used below to decide whether an acyclic\n // binding edge should also become a downstream edge.\n const combinedCycleMembers = findCycleMembers(allUpstreamDependencies);\n // Map FQN -> list of downstream FQNs (resources/actions that depend on\n // this one).\n //\n // Prop edges always become downstream edges — they can't form cycles\n // (the resource graph is a DAG by construction once props are fully\n // resolved). Binding edges become downstream edges too, except when\n // they participate in a cycle in the combined graph: mutual bindings\n // (A binds to B's data, B binds to A's data) intentionally do not\n // create downstream edges, so deletion does not deadlock waiting on\n // each other (see the \"binding-only cycles inside a construct\" test\n // in `plan.test.ts`).\n //\n // Including acyclic binding edges is required for cloud APIs that\n // enforce the binding at the provider level — e.g. a Cloudflare\n // Worker with a `service` binding to another Worker cannot delete\n // the upstream worker until the downstream worker's binding has been\n // removed. Without the binding edge in `downstream`, the two delete\n // concurrently and the upstream delete fails with\n // `ServiceBindingConflict`.\n //\n // Actions don't have bindings, so for action upstreams we use only\n // prop edges (which collapse to `newUpstreamDependencies` lookups).\n const computeDownstream = (upFqn) => {\n const downstream = [];\n for (const [downFqn, upstreams] of Object.entries(rawUpstreamDependencies)) {\n if (downFqn === upFqn)\n continue;\n if (!upstreams.includes(upFqn))\n continue;\n const isPropEdge = (newUpstreamDependencies[downFqn] ?? []).includes(upFqn);\n if (isPropEdge) {\n downstream.push(downFqn);\n continue;\n }\n // Binding-only edge — exclude when both endpoints sit inside\n // the same SCC of the combined graph.\n if (combinedCycleMembers.has(upFqn) &&\n combinedCycleMembers.has(downFqn)) {\n continue;\n }\n downstream.push(downFqn);\n }\n return downstream;\n };\n const newDownstreamDependencies = Object.fromEntries([\n ...resources.map((resource) => [resource.FQN, computeDownstream(resource.FQN)]),\n ...actions.map((action) => [action.FQN, computeDownstream(action.FQN)]),\n ]);\n const resourceGraph = Object.fromEntries((yield* Effect.all(resources.map(Effect.fn(\"plan.diff.resource\")(function* (resource) {\n const provider = yield* findProviderByType(resource.Type);\n const id = resource.LogicalId;\n const fqn = resource.FQN;\n const news = yield* resolveInput(resource.Props);\n const downstream = newDownstreamDependencies[fqn] ?? [];\n // Collapse duplicate bindings by sid so the binding set handed to\n // `diff` matches what `reconcile` receives (see `dedupeBindings`).\n const newBindings = dedupeBindings(yield* resolveInput(stack.bindings[fqn] ?? []));\n const persisted = yield* state.get({\n stack: stackName,\n stage: stage,\n fqn,\n });\n // A Task previously held this FQN. Treat as if there were no\n // prior state — the Task's row will be reaped by `actionDeletions`\n // below and the resource starts from scratch.\n let oldState = isActionState(persisted)\n ? undefined\n : persisted;\n // Engine-level adoption. When there is no prior state, always\n // consult `provider.read` (if implemented) so the engine — not\n // each lifecycle method — owns the existence/ownership decision.\n //\n // The provider returns one of:\n // - `undefined` → resource doesn't exist; create it\n // - plain attrs → exists and is owned by us; silent adopt\n // - `Unowned(attrs)` → exists but is *not* ours\n //\n // Routing:\n // - owned → persist `created` state\n // from attrs and continue\n // through the normal diff\n // path (so subsequent props\n // drift produces an update).\n // - unowned + adopt enabled → take over: persist `created`\n // state and let the next\n // update overwrite tags / etc.\n // - unowned + adopt disabled → fail with\n // `OwnedBySomeoneElse`.\n // After a cold-start adoption (engine just discovered an\n // existing cloud resource via `read`), force the engine's\n // normal `update` path so the provider can re-sync ownership\n // tags, configuration, etc. against the desired props.\n // Adoption persists state with `props: news`, so the default\n // diff sees no drift and would noop — which would leave any\n // foreign-owned tags / divergent config in place. Forcing\n // update keeps the deploy idempotent: if cloud state already\n // matches news, the provider's update is a no-op write.\n //\n // Skip the adoption probe entirely when `news` still contains\n // unresolved upstream Outputs (e.g. a `streamArn` referencing\n // a stream being created in the same plan). Calling `read` with\n // an unresolved value would surface as `ParseError` from the\n // SDK protocol layer. Resources whose props depend on\n // not-yet-created upstreams cannot themselves be pre-existing\n // — there's nothing to adopt.\n let forceUpdateAfterAdoption = false;\n if (oldState === undefined && provider.read && isResolved(news)) {\n const adoptInstanceId = yield* generateInstanceId();\n const readResult = yield* provider\n .read({\n id,\n instanceId: adoptInstanceId,\n olds: news,\n output: undefined,\n })\n .pipe(providePlanScope(fqn, adoptInstanceId));\n if (readResult !== undefined) {\n const isUnowned = Unowned.is(readResult);\n if (isUnowned && !(yield* shouldAdopt)) {\n return yield* new OwnedBySomeoneElse({\n message: `Cannot adopt resource '${fqn}' (${resource.Type}): ` +\n \"it exists in the cloud but is not owned by this \" +\n \"stack/stage/logical-id. Re-run with `--adopt` (or \" +\n \"wrap the effect in `adopt(true)`) to take it over.\",\n resourceType: resource.Type,\n logicalId: id,\n });\n }\n const adoptedState = {\n status: \"created\",\n fqn,\n logicalId: id,\n instanceId: adoptInstanceId,\n namespace: resource.Namespace,\n resourceType: resource.Type,\n props: news,\n attr: stripUnowned(readResult),\n providerVersion: provider.version ?? 0,\n bindings: [],\n downstream,\n removalPolicy: resource.RemovalPolicy,\n };\n yield* state.set({\n stack: stackName,\n stage: stage,\n fqn,\n value: adoptedState,\n });\n oldState = adoptedState;\n forceUpdateAfterAdoption = true;\n }\n }\n const oldBindings = oldState?.bindings ?? [];\n const bindingDiffs = diffBindings(oldBindings, newBindings);\n const Node = (node) => ({\n ...node,\n provider,\n resource,\n bindings: bindingDiffs,\n downstream,\n });\n // Plan against the persisted state we have, not the ideal final state we\n // hoped to reach last time. Recovery is expressed by mapping each\n // intermediate state back onto a fresh CRUD action.\n if (oldState === undefined) {\n return Node({\n action: \"create\",\n props: news,\n state: oldState,\n });\n }\n else if (oldState.status === \"creating\" &&\n oldState.attr === undefined) {\n // A create may have succeeded before state persistence failed. If the\n // provider can recover an attribute snapshot, keep driving the same\n // create instead of starting over blindly.\n if (provider.read) {\n const attr = yield* provider\n .read({\n id,\n instanceId: oldState.instanceId,\n olds: oldState.props,\n output: oldState.attr,\n })\n .pipe(providePlanScope(fqn, oldState.instanceId));\n if (attr) {\n return Node({\n action: \"create\",\n props: news,\n state: { ...oldState, attr },\n });\n }\n }\n }\n // Diff against whatever props represent the best-known current attempt.\n // For replacement recovery that means the top-level replacement props,\n // not the older generations stored under `old`.\n const oldProps = oldState.props;\n const diff = yield* asEffect(provider\n ?.diff?.({\n id,\n olds: oldProps,\n instanceId: oldState.instanceId,\n output: oldState.attr,\n news,\n oldBindings,\n newBindings,\n })\n .pipe(providePlanScope(fqn, oldState.instanceId))).pipe(Effect.map((diff) => diff ??\n {\n action: havePropsChanged(oldProps, news) ||\n bindingDiffs.some((b) => b.action !== \"noop\")\n ? \"update\"\n : \"noop\",\n }), Effect.map((diff) => options.force && diff.action === \"noop\"\n ? {\n action: \"update\",\n }\n : diff), \n // After a cold-start adoption (silent or takeover), force at\n // least an update so the provider re-syncs ownership tags /\n // config against the desired props (otherwise the engine\n // would noop and any drift between the existing cloud\n // resource and `news` — including foreign-owned tags after a\n // takeover — would persist).\n Effect.map((diff) => forceUpdateAfterAdoption && diff.action === \"noop\"\n ? { action: \"update\" }\n : diff));\n if (oldState.status === \"creating\") {\n if (diff.action === \"noop\") {\n // we're in the creating state and props are un-changed\n // let's just continue where we left off\n return Node({\n action: \"create\",\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"update\") {\n // props have changed in a way that is updatable\n // again, just continue with the create\n // TODO(sam): should we maybe try an update instead?\n return Node({\n action: \"create\",\n props: news,\n state: oldState,\n });\n }\n else {\n // props have changed in an incompatible way\n // because it's possible that an un-updatable resource has already been created\n // we must use a replace step to create a new one and delete the potential old one\n return Node({\n action: \"replace\",\n props: news,\n deleteFirst: diff.deleteFirst ?? false,\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"updating\") {\n // Updating already targets the live resource, so noop/update both mean\n // \"finish the interrupted update\". Only a replace diff escalates it\n // into a fresh replacement.\n if (diff.action === \"update\" || diff.action === \"noop\") {\n // we can continue where we left off\n return Node({\n action: \"update\",\n props: news,\n state: oldState,\n });\n }\n else {\n // we started to update a resource but now believe we should replace it\n return Node({\n action: \"replace\",\n deleteFirst: diff.deleteFirst ?? false,\n props: news,\n // TODO(sam): can Apply handle replacements when the oldState is UpdatingResourceState?\n // -> or should we do a provider.read to try and reconcile back to UpdatedResourceState?\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"replacing\") {\n // The replacement candidate is still being created. Noop/update keep\n // driving the same generation; replace means that candidate itself is\n // now obsolete and must be wrapped in a new outer generation.\n if (diff.action === \"noop\") {\n // this is the stable case - noop means just continue with the replacement\n return Node({\n action: \"replace\",\n deleteFirst: oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"update\") {\n // potential problem here - the props have changed since we tried to replace,\n // but not enough to trigger another replacement. the resource provider should\n // be designed as idempotent to converge to the right state when creating the new resource\n // the newly generated instanceId is intended to assist with this\n return Node({\n action: \"replace\",\n deleteFirst: oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n else {\n // The in-flight replacement candidate itself now needs replacement.\n // Mark this as a restart so Apply creates a fresh generation instead\n // of resuming the old replacement instance.\n return Node({\n restart: true,\n action: \"replace\",\n deleteFirst: diff.deleteFirst ?? oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"replaced\") {\n // The new resource already exists. Noop means \"just let GC finish\",\n // update means \"mutate the current replacement before GC finishes\",\n // and replace means \"the current replacement also became obsolete\".\n if (diff.action === \"noop\") {\n // this is the stable case - noop means just continue cleaning up the replacement\n return Node({\n action: \"replace\",\n deleteFirst: oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"update\") {\n // the replacement has been created but now also needs to be updated\n // the resource provider should:\n // 1. Update the newly created replacement resource\n // 2. Then proceed as normal to delete the replaced resources (after all downstream references are updated)\n return Node({\n action: \"update\",\n props: news,\n state: oldState,\n });\n }\n else {\n // Cleanup is still pending, but the current \"new\" resource has already\n // become obsolete. Start another replacement generation and preserve\n // the existing replaced node as part of the recursive old chain.\n return Node({\n restart: true,\n action: \"replace\",\n deleteFirst: diff.deleteFirst ?? oldState.deleteFirst,\n props: news,\n state: oldState,\n });\n }\n }\n else if (oldState.status === \"deleting\") {\n // we're in a partially deleted state, it is unclear whether it was or was not deleted\n // so continue by re-creating it with the same instanceId and desired props\n return Node({\n action: \"create\",\n props: news,\n state: {\n ...oldState,\n status: \"creating\",\n props: news,\n },\n });\n }\n else if (diff.action === \"update\") {\n // Stable created/updated resources follow the normal CRUD mapping.\n return Node({\n action: \"update\",\n props: news,\n state: oldState,\n });\n }\n else if (diff.action === \"replace\") {\n return Node({\n action: \"replace\",\n props: news,\n state: oldState,\n deleteFirst: diff?.deleteFirst ?? false,\n });\n }\n else {\n return Node({\n action: \"noop\",\n state: oldState,\n });\n }\n })), { concurrency: \"unbounded\" })).map((update) => [update.resource.FQN, update]));\n // ── Action plan nodes ────────────────────────────────────────────────\n const actionGraph = Object.fromEntries((yield* Effect.all(actions.map(Effect.fn(\"plan.diff.action\")(function* (action) {\n const fqn = action.FQN;\n const downstream = newDownstreamDependencies[fqn] ?? [];\n const resolvedInput = yield* resolveInput(action.Input);\n const inputHash = yield* hashInput(resolvedInput);\n const oldState = yield* state.get({\n stack: stackName,\n stage,\n fqn,\n });\n if (oldState && !isActionState(oldState)) {\n // FQN collision with a resource — surface as a fatal error so\n // the user resolves it before we touch anything.\n return [\n fqn,\n {\n kind: \"action\",\n action: \"run\",\n def: action,\n input: action.Input,\n state: undefined,\n downstream,\n forced: false,\n },\n ];\n }\n const prior = oldState;\n const sameInput = prior?.status === \"ran\" && prior.inputHash === inputHash;\n if (sameInput && !options.force) {\n return [\n fqn,\n {\n kind: \"action\",\n action: \"noop\",\n def: action,\n state: prior,\n downstream,\n },\n ];\n }\n return [\n fqn,\n {\n kind: \"action\",\n action: \"run\",\n def: action,\n input: action.Input,\n state: prior,\n downstream,\n forced: !!options.force,\n },\n ];\n })), { concurrency: \"unbounded\" })));\n // SCC membership of the combined upstream graph. Apply uses it to\n // decide whether an update node must publish its prior attr early to\n // break a cycle, or can simply wait for upstreams like a DAG node\n // (the common case). Computed once, above, for the downstream graph.\n const cycleMembers = combinedCycleMembers;\n // Detect unsatisfiable dependency cycles among create/replace nodes.\n // Update/noop nodes signal their Deferred before waitForDeps when in a\n // cycle so they cannot deadlock. Create/replace nodes only signal\n // early when they have a precreate handler. Simulate the concurrent\n // execution: precreate nodes are immediately \"resolved\", then\n // iteratively resolve any node whose deps are all resolved. Remaining\n // nodes would deadlock.\n {\n const createReplaceNodes = new Set(Object.entries(resourceGraph)\n .filter(([_, node]) => node.action === \"create\" || node.action === \"replace\")\n .map(([fqn]) => fqn));\n if (createReplaceNodes.size > 0) {\n const hasPrecreate = new Set([...createReplaceNodes].filter((fqn) => !!resourceGraph[fqn]?.provider?.precreate));\n const resolved = new Set(hasPrecreate);\n let changed = true;\n while (changed) {\n changed = false;\n for (const fqn of createReplaceNodes) {\n if (resolved.has(fqn))\n continue;\n const deps = (allUpstreamDependencies[fqn] ?? []).filter((dep) => createReplaceNodes.has(dep));\n if (deps.every((dep) => resolved.has(dep))) {\n resolved.add(fqn);\n changed = true;\n }\n }\n }\n const deadlocked = [...createReplaceNodes].filter((fqn) => !resolved.has(fqn));\n if (deadlocked.length > 0) {\n const missingPrecreate = deadlocked.filter((fqn) => !hasPrecreate.has(fqn));\n return yield* Effect.die(new UnsatisfiedResourceCycle({\n message: `Circular dependency detected that cannot be resolved: [${deadlocked.join(\", \")}]. ` +\n `Resources lacking a precreate handler: [${missingPrecreate.join(\", \")}]. ` +\n `All resources in a dependency cycle must implement precreate to allow early signaling.`,\n cycle: deadlocked,\n missingPrecreate,\n }));\n }\n }\n }\n // Task deletions: state rows previously written by tasks that no\n // longer appear in the stack. The body is NOT invoked — we just drop\n // the row.\n const actionDeletions = Object.fromEntries((yield* Effect.all((yield* state.list({ stack: stackName, stage })).map(Effect.fn(\"plan.diff.actionDeletion\")(function* (fqn) {\n if (newActionFqns.has(fqn) || newResourceFqns.has(fqn))\n return;\n const persisted = yield* state.get({\n stack: stackName,\n stage,\n fqn,\n });\n if (!isActionState(persisted))\n return;\n const { logicalId } = parseFqn(fqn);\n return [\n fqn,\n {\n kind: \"action\",\n action: \"delete\",\n state: persisted,\n downstream: persisted.downstream ?? [],\n def: {\n Kind: \"action\",\n Namespace: persisted.namespace,\n FQN: fqn,\n LogicalId: logicalId,\n Type: persisted.actionType,\n Input: persisted.input,\n Run: () => undefined,\n Output: undefined,\n },\n },\n ];\n })), { concurrency: \"unbounded\" })).filter((v) => !!v));\n const deletions = Object.fromEntries((yield* Effect.all((yield* state.list({ stack: stackName, stage: stage })).map(Effect.fn(\"plan.diff.deletion\")(function* (fqn) {\n if (newResourceFqns.has(fqn) || newActionFqns.has(fqn)) {\n return;\n }\n const persisted = yield* state.get({\n stack: stackName,\n stage: stage,\n fqn,\n });\n // Tasks are routed through `actionDeletions` above.\n if (isActionState(persisted))\n return;\n const oldState = persisted;\n let attr = oldState?.attr;\n if (oldState) {\n const { logicalId } = parseFqn(fqn);\n const resourceType = oldState.resourceType;\n const provider = yield* findProviderByType(resourceType);\n if (oldState.attr === undefined) {\n if (provider.read) {\n attr = yield* provider\n .read({\n id: logicalId,\n instanceId: oldState.instanceId,\n olds: oldState.props,\n output: oldState.attr,\n })\n .pipe(providePlanScope(fqn, oldState.instanceId));\n }\n }\n return [\n fqn,\n {\n action: \"delete\",\n state: { ...oldState, attr },\n provider: provider,\n resource: {\n Namespace: oldState.namespace,\n FQN: fqn,\n LogicalId: logicalId,\n Type: oldState.resourceType,\n Attributes: attr,\n Props: oldState.props,\n Binding: undefined,\n Provider: Provider(resourceType),\n RemovalPolicy: oldState.removalPolicy,\n RuntimeContext: undefined,\n Providers: undefined,\n },\n downstream: oldDownstreamDependencies[fqn] ?? [],\n bindings: oldState.bindings.map((binding) => ({\n sid: binding.sid,\n action: \"delete\",\n data: binding.data,\n })),\n },\n ];\n }\n })), { concurrency: \"unbounded\" })).filter((v) => !!v));\n for (const resourceFqn of Object.keys(deletions)) {\n const dependencies = Object.entries(rawUpstreamDependencies)\n .filter(([survivorFqn, upstream]) => survivorFqn in resourceGraph && upstream.includes(resourceFqn))\n .map(([survivorFqn]) => survivorFqn);\n if (dependencies.length > 0) {\n return yield* new DeleteResourceHasDownstreamDependencies({\n message: `Resource ${resourceFqn} has downstream dependencies`,\n resourceId: resourceFqn,\n dependencies,\n });\n }\n }\n return {\n resources: resourceGraph,\n actions: actionGraph,\n deletions,\n actionDeletions,\n output: stack.output,\n cycleMembers,\n };\n}).pipe(ensureArtifactStore, Effect.withSpan(\"plan.make\", {\n attributes: {\n \"alchemy.stack\": stack.name,\n \"alchemy.stage\": stack.stage,\n \"alchemy.resources.count\": Object.keys(stack.resources).length,\n \"alchemy.force\": !!options.force,\n },\n}));\nconst providePlanScope = (fqn, instanceId) => (effect) => Effect.serviceOption(ArtifactStore).pipe(Effect.map(Option.getOrElse(createArtifactStore)), Effect.flatMap((store) => effect.pipe(Effect.provideService(Artifacts, makeScopedArtifacts(store, fqn)), Effect.provideService(InstanceId, instanceId))));\nexport class DeleteResourceHasDownstreamDependencies extends Data.TaggedError(\"DeleteResourceHasDownstreamDependencies\") {\n}\nexport class UnsatisfiedResourceCycle extends Data.TaggedError(\"UnsatisfiedResourceCycle\") {\n}\n// TODO(sam): compare props\n// oldBinding.props !== newBinding.props;\n/**\n * Print a plan in a human-readable format that shows the graph topology.\n */\nexport const printPlan = (plan) => {\n const lines = [];\n const allNodes = { ...plan.resources, ...plan.deletions };\n // Build reverse mapping: upstream -> downstream\n const upstreamMap = {};\n for (const [id] of Object.entries(allNodes)) {\n upstreamMap[id] = [];\n }\n for (const [id, node] of Object.entries(allNodes)) {\n if (!node)\n continue;\n for (const downstreamId of node.state?.downstream ?? []) {\n if (upstreamMap[downstreamId]) {\n upstreamMap[downstreamId].push(id);\n }\n }\n }\n // Action symbols\n const actionSymbol = (action) => {\n switch (action) {\n case \"create\":\n return \"+\";\n case \"update\":\n return \"~\";\n case \"delete\":\n return \"-\";\n case \"replace\":\n return \"±\";\n case \"noop\":\n return \"=\";\n default:\n return \"?\";\n }\n };\n // Print header\n lines.push(\"╔════════════════════════════════════════════════════════════════╗\");\n lines.push(\"║ PLAN ║\");\n lines.push(\"╠════════════════════════════════════════════════════════════════╣\");\n lines.push(\"║ Legend: + create, ~ update, - delete, ± replace, = noop, ║\");\n lines.push(\"║ λ run task, · skip task ║\");\n lines.push(\"╚════════════════════════════════════════════════════════════════╝\");\n lines.push(\"\");\n // Print resources section\n lines.push(\"┌─ Resources ────────────────────────────────────────────────────┐\");\n const resourceIds = Object.keys(plan.resources).sort();\n for (const id of resourceIds) {\n const node = plan.resources[id];\n const symbol = actionSymbol(node.action);\n const type = node.resource?.type ?? \"unknown\";\n const downstream = node.state?.downstream?.length\n ? ` → [${node.state?.downstream.join(\", \")}]`\n : \"\";\n lines.push(`│ [${symbol}] ${id} (${type})${downstream}`);\n }\n if (resourceIds.length === 0) {\n lines.push(\"│ (none)\");\n }\n lines.push(\"└────────────────────────────────────────────────────────────────┘\");\n lines.push(\"\");\n // Print tasks section\n lines.push(\"┌─ Tasks ────────────────────────────────────────────────────────┐\");\n const taskIds = Object.keys(plan.actions ?? {}).sort();\n for (const id of taskIds) {\n const node = plan.actions[id];\n const symbol = node.action === \"run\" ? \"λ\" : \"·\";\n const type = node.def.Type;\n const downstream = node.downstream.length\n ? ` → [${node.downstream.join(\", \")}]`\n : \"\";\n lines.push(`│ [${symbol}] ${id} (${type})${downstream}`);\n }\n if (taskIds.length === 0) {\n lines.push(\"│ (none)\");\n }\n lines.push(\"└────────────────────────────────────────────────────────────────┘\");\n lines.push(\"\");\n // Print deletions section\n lines.push(\"┌─ Deletions ────────────────────────────────────────────────────┐\");\n const deletionIds = Object.keys(plan.deletions).sort();\n for (const id of deletionIds) {\n const node = plan.deletions[id];\n const type = node.resource?.Type ?? \"unknown\";\n const downstream = node.state.downstream?.length\n ? ` → [${node.state.downstream.join(\", \")}]`\n : \"\";\n lines.push(`│ [-] ${id} (${type})${downstream}`);\n }\n const taskDeletionIds = Object.keys(plan.actionDeletions ?? {}).sort();\n for (const id of taskDeletionIds) {\n const node = plan.actionDeletions[id];\n lines.push(`│ [-] ${id} (${node.def.Type}) [action]`);\n }\n if (deletionIds.length === 0 && taskDeletionIds.length === 0) {\n lines.push(\"│ (none)\");\n }\n lines.push(\"└────────────────────────────────────────────────────────────────┘\");\n lines.push(\"\");\n return lines.join(\"\\n\");\n};\n//# sourceMappingURL=Plan.js.map","import * as Cause from \"effect/Cause\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport { Artifacts, ArtifactStore, createArtifactStore, ensureArtifactStore, makeScopedArtifacts, } from \"./Artifacts.js\";\nimport { Cli, } from \"./Cli/Cli.js\";\nimport { havePropsChanged } from \"./Diff.js\";\nimport { toFqn } from \"./FQN.js\";\nimport { generateInstanceId, InstanceId } from \"./InstanceId.js\";\nimport * as Output from \"./Output.js\";\nimport {} from \"./Plan.js\";\nimport { findProviderByType } from \"./Provider.js\";\nimport { Stack } from \"./Stack.js\";\nimport { Stage } from \"./Stage.js\";\nimport { State, StateStoreError, } from \"./State/index.js\";\nimport { recordResourceOp } from \"./Telemetry/Metrics.js\";\nimport { hashInput } from \"./Util/hash.js\";\nconst provideLifecycleScope = (fqn, instanceId) => (effect) => Effect.serviceOption(ArtifactStore).pipe(Effect.map(Option.getOrElse(createArtifactStore)), Effect.flatMap((store) => effect.pipe(Effect.provideService(Artifacts, makeScopedArtifacts(store, fqn)), Effect.provideService(InstanceId, instanceId))));\n/**\n * Instruments a single provider lifecycle call with an OTel span\n * (`provider.<op>`), the resource counter / duration histogram, and the\n * scoped artifacts/instance services normally supplied by\n * {@link provideLifecycleScope}.\n *\n * This is the only call site through which provider lifecycle methods\n * are dispatched, so wrapping it here gives us a fully-instrumented\n * toolchain without touching any individual provider implementation.\n */\nconst instrumentLifecycle = (op, fqn, resourceType, logicalId, instanceId) => (effect) => effect.pipe(provideLifecycleScope(fqn, instanceId), recordResourceOp(resourceType, op), Effect.withSpan(`provider.${op}`, {\n attributes: {\n \"alchemy.resource.fqn\": fqn,\n \"alchemy.resource.type\": resourceType,\n \"alchemy.resource.logical_id\": logicalId,\n \"alchemy.resource.instance_id\": instanceId,\n \"alchemy.resource.op\": op,\n },\n}));\nexport const apply = (plan) => Effect.gen(function* () {\n const cli = yield* Cli;\n const session = yield* cli.startApplySession(plan);\n const state = yield* State;\n const stack = yield* Stack;\n const stage = yield* Stage;\n const stackName = stack.name;\n const tracker = {};\n const terminalStatuses = new Map();\n yield* executePlan(plan, tracker, terminalStatuses, session, state, stackName, stage);\n // TODO(sam): support roll back to previous state if errors occur during expansion\n // -> RISK: some UPDATEs may not be reversible (i.e. trigger replacements)\n // TODO(sam): should pivot be done separately? E.g shift traffic?\n yield* collectGarbage(plan, session);\n yield* converge(plan, tracker, terminalStatuses, session, state, stackName, stage);\n yield* Effect.forEach(Array.from(terminalStatuses.values()), ({ id, type, status }) => session.emit({ kind: \"status-change\", id, type, status }), { concurrency: \"unbounded\" });\n yield* session.done();\n if (!plan.output) {\n return undefined;\n }\n const outputs = Object.fromEntries(Object.entries(tracker).map(([fqn, t]) => [fqn, t.output]));\n const resolved = yield* Output.evaluate(plan.output, outputs);\n // Persist the stack's evaluated outputs so cross-stack references\n // (`yield* OtherStack` / `OtherStack.stage.<name>` / `Output.stackRef`)\n // can read them back out of the state store.\n yield* state.setOutput({ stack: stackName, stage, value: resolved });\n return resolved;\n}).pipe(ensureArtifactStore, Effect.withSpan(\"apply\", {\n attributes: {\n \"alchemy.resources.count\": Object.keys(plan.resources).length,\n \"alchemy.deletions.count\": Object.keys(plan.deletions).length,\n },\n}));\n// ── Phase 1: concurrent initial execution ──────────────────────────────────\n//\n// Each resource gets a Deferred<void> that signals \"I have some output\n// available in `tracker`.\" Resources with `precreate` signal early so that\n// downstream resources can resolve stable identifiers without deadlocking.\n// The actual output lives in the mutable `tracker` map, not in the Deferred.\nconst executePlan = Effect.fnUntraced(function* (plan, tracker, terminalStatuses, session, state, stackName, stage) {\n // Resources and tasks share the same FQN namespace and DAG, so the\n // scheduler tracks them together. Each entry gets a single Deferred that\n // signals \"my output is available in `tracker`.\"\n const allNodes = {\n ...plan.resources,\n ...plan.actions,\n };\n const ready = Object.fromEntries(yield* Effect.all(Object.keys(allNodes).map((fqn) => Effect.map(Deferred.make(), (d) => [fqn, d]))));\n // `readyStable` fires only when a node has reached its TERMINAL output —\n // resources after `reconcile`, tasks after the body completes. Resource\n // precreate stubs do NOT signal `readyStable`, so any consumer that\n // requires stable inputs (e.g. Tasks) waits past the precreate phase.\n const readyStable = Object.fromEntries(yield* Effect.all(Object.keys(allNodes).map((fqn) => Effect.map(Deferred.make(), (d) => [fqn, d]))));\n const getOutputs = () => Object.fromEntries(Object.entries(tracker).map(([fqn, t]) => [fqn, t.output]));\n const waitForDeps = (fqns) => Effect.all(fqns\n .filter((fqn) => fqn in ready)\n .map((fqn) => \n // Non-cycle upstreams must be observed at their TERMINAL output\n // (`readyStable`), not their early precreate signal (`ready`). This\n // is what makes a failed upstream actually interrupt its downstream:\n // a resource with `precreate` resolves `ready` before its real\n // `reconcile` runs, so a downstream waiting on `ready` would proceed\n // (and even finish) even though the upstream's reconcile later\n // failed. Waiting on `readyStable` means the downstream's\n // `waitForDeps` short-circuits with the upstream's failure cause.\n //\n // Cycle members are the exception: peers in an SCC depend on each\n // other, so they must rendezvous on the early `ready`/precreate\n // signal to break the deadlock. Phase 3 (`converge`) re-runs them\n // against final outputs once the cycle settles.\n plan.cycleMembers.has(fqn)\n ? Deferred.await(ready[fqn])\n : Deferred.await(readyStable[fqn])), { concurrency: \"unbounded\" });\n const waitForStableDeps = (fqns) => Effect.all(fqns\n .filter((fqn) => fqn in readyStable)\n .map((fqn) => Deferred.await(readyStable[fqn])), { concurrency: \"unbounded\" });\n const failures = [];\n yield* Effect.all(Object.entries(allNodes).map(([fqn, node]) => node.kind === \"action\"\n ? executeActionNode(fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForStableDeps, failures)\n : executeNode(fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForDeps, failures, plan.cycleMembers.has(fqn))), { concurrency: \"unbounded\" });\n if (failures.length > 0) {\n // Aggregate every collected lifecycle failure into a single parallel Cause\n // so the apply ends with one combined error containing every distinct\n // failure / defect that occurred across the concurrent fibers.\n yield* Effect.failCause(failures.map((f) => f.cause).reduce(Cause.combine));\n }\n});\nconst executeNode = (fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForDeps, failures, inCycle) => Effect.gen(function* () {\n const logicalId = node.resource.LogicalId;\n const namespace = node.resource.Namespace;\n const commit = (value) => state.set({\n stack: stackName,\n stage,\n fqn,\n value: { ...value, namespace },\n });\n const scopedSession = {\n ...session,\n note: (note) => session.emit({ id: logicalId, kind: \"annotate\", message: note }),\n };\n const report = (status) => session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: node.resource.Type,\n status,\n });\n const markTerminal = (status) => Effect.gen(function* () {\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: node.resource.Type,\n status,\n });\n // Emit immediately so the CLI surfaces the terminal status as soon\n // as the resource is actually done — instead of batching every\n // resource's \"created\"/\"updated\" event to the end of apply(), which\n // makes long-running siblings appear stuck in \"creating\" until the\n // entire deploy finishes.\n //\n // Cycle members are exempt: their initial pass produces an\n // intermediate result that Phase 3 (`converge`) will overwrite once\n // the SCC reaches a fixed point. Emitting \"created\"/\"updated\" here\n // would surface that intermediate state to the CLI before the real\n // terminal status is known. Their final status is flushed from\n // `terminalStatuses` after `converge` completes.\n if (inCycle)\n return;\n yield* session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: node.resource.Type,\n status,\n });\n });\n const signalReady = Deferred.succeed(ready[fqn], void 0);\n // Signal only after reconcile completes — never during precreate. Tasks\n // (and any other consumer that calls `waitForStableDeps`) block on this\n // so they observe the resource's final attrs rather than a stub.\n const signalReadyStable = Deferred.succeed(readyStable[fqn], void 0);\n const storeAndSignal = (t) => Effect.gen(function* () {\n tracker[fqn] = t;\n yield* signalReady;\n });\n // ── noop ──\n if (node.action === \"noop\") {\n // No work to do — the persisted attr is already stable.\n yield* signalReadyStable;\n yield* storeAndSignal({\n output: node.state.attr,\n props: node.state.props,\n bindings: node.state.bindings ?? [],\n instanceId: node.state.instanceId,\n });\n return;\n }\n const allUpstreamFqns = () => {\n const propDeps = Object.keys(Output.resolveUpstream(node.props));\n const bindingDeps = Object.keys(Output.resolveUpstream(node.bindings));\n return [...new Set([...propDeps, ...bindingDeps])];\n };\n // ── instance ID ──\n const instanceId = yield* Effect.gen(function* () {\n if (node.action === \"create\" && !node.state?.instanceId) {\n const id = yield* generateInstanceId();\n yield* commit({\n status: \"creating\",\n fqn,\n logicalId,\n instanceId: id,\n downstream: node.downstream,\n props: node.props,\n providerVersion: node.provider.version ?? 0,\n resourceType: node.resource.Type,\n bindings: excludeDeletedBindings(node.bindings),\n removalPolicy: node.resource.RemovalPolicy,\n });\n return id;\n }\n else if (node.action === \"replace\") {\n if ((node.state.status === \"replaced\" ||\n node.state.status === \"replacing\") &&\n !node.restart) {\n // Ordinary replacement recovery keeps using the same replacement\n // generation. Only `restart` is allowed to mint a new instance id.\n return node.state.instanceId;\n }\n const id = yield* generateInstanceId();\n yield* commit({\n status: \"replacing\",\n fqn,\n logicalId,\n instanceId: id,\n downstream: node.downstream,\n props: node.props,\n providerVersion: node.provider.version ?? 0,\n resourceType: node.resource.Type,\n bindings: excludeDeletedBindings(node.bindings),\n old: node.state,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.resource.RemovalPolicy,\n });\n return id;\n }\n else if (node.state?.instanceId) {\n return node.state.instanceId;\n }\n return yield* Effect.die(`Instance ID not found for resource '${logicalId}' and action is '${node.action}'`);\n });\n // ── lifecycle ──\n yield* Effect.gen(function* () {\n // ── create ──\n if (node.action === \"create\") {\n if (!node.state) {\n // First persistence point for a brand new logical resource. Once this is\n // written, retries know they should resume creation instead of planning\n // another fresh create from scratch.\n yield* commit({\n status: \"creating\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n attr: undefined,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n let attr = node.state?.attr;\n if (attr !== undefined) {\n // Precreate/read may already have produced a usable output snapshot. Publish\n // it early so downstream resources can start resolving against it.\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n if (node.provider.precreate && attr === undefined) {\n // Some resources need a placeholder physical resource before their real\n // create can finish. Persist that stub so downstream evaluation can proceed.\n yield* report(\"pre-creating\");\n attr = yield* node.provider\n .precreate({\n id: logicalId,\n news: node.props,\n session: scopedSession,\n instanceId,\n bindings: excludeDeletedBindings(node.bindings),\n })\n .pipe(instrumentLifecycle(\"precreate\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n status: \"creating\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n // While we're waiting on upstream outputs the resource isn't actually\n // creating anything yet — surface that as \"pending\" so the CLI doesn't\n // look stuck in \"creating\" for slow-upstream deploys.\n yield* report(\"pending\");\n // Create runs against fully resolved upstream outputs and bindings, not the\n // raw Output expressions stored in the plan.\n yield* waitForDeps(allUpstreamFqns());\n yield* report(\"creating\");\n const outputs = getOutputs();\n const news = (yield* Output.evaluate(node.props, outputs));\n const bindingOutputs = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news,\n instanceId,\n bindings: bindingOutputs,\n session: scopedSession,\n olds: undefined,\n output: attr,\n })\n .pipe(instrumentLifecycle(\"create\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n status: \"created\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr,\n bindings: excludeDeletedBindings(node.bindings),\n providerVersion: node.provider.version ?? 0,\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n tracker[fqn] = {\n output: attr,\n props: news,\n bindings: bindingOutputs,\n instanceId,\n };\n yield* signalReady;\n yield* signalReadyStable;\n yield* markTerminal(\"created\");\n return;\n }\n // ── update ──\n if (node.action === \"update\") {\n // Cycle members publish their previous live attr *before* waiting on\n // upstreams so the SCC can converge — peers in the cycle would\n // otherwise deadlock waiting on each other. Phase 3 (`converge`)\n // re-runs each peer's update against fresh outputs once everyone\n // has settled.\n //\n // Linear (DAG) update nodes skip this entirely and simply wait for\n // fresh upstream outputs, mirroring the create flow. This is the\n // important property: a downstream of a non-cycle update never\n // observes the upstream's stale attr, which prevents wasted/\n // destructive intermediate updates (e.g. a Worker deploying with\n // stale Build assets).\n if (inCycle) {\n yield* storeAndSignal({\n output: node.state.attr,\n props: node.state.props,\n bindings: node.state.bindings ?? [],\n instanceId,\n });\n }\n // See create-flow note: while we're waiting on upstream outputs\n // this resource isn't actually updating yet.\n yield* report(\"pending\");\n yield* waitForDeps(allUpstreamFqns());\n const outputs = getOutputs();\n const news = (yield* Output.evaluate(node.props, outputs));\n yield* node.state.status === \"replaced\"\n ? commit({\n // Keep the replacement wrapper intact while changing the live\n // replacement props; GC still has older generations to delete.\n ...node.state,\n attr: node.state.attr,\n props: news,\n })\n : commit({\n // For ordinary updates we snapshot the previously stable props/attrs\n // once, so retries can continue from the same baseline.\n status: \"updating\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr: node.state.attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n old: node.state.status === \"updating\" ? node.state.old : node.state,\n removalPolicy: node.resource.RemovalPolicy,\n });\n yield* report(\"updating\");\n const previousProps = node.state.status === \"created\" ||\n node.state.status === \"updated\" ||\n node.state.status === \"replaced\"\n ? node.state.props\n : node.state.old.props;\n // Providers receive the resolved binding payload for this exact pass, while\n // `previousProps` tells them what state the live resource is being updated from.\n const bindingOutputs = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n const attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news,\n instanceId,\n bindings: bindingOutputs,\n session: scopedSession,\n olds: previousProps,\n output: node.state.attr,\n })\n .pipe(instrumentLifecycle(\"update\", fqn, node.resource.Type, logicalId, instanceId));\n if (node.state.status === \"replaced\") {\n yield* commit({\n // The live replacement changed, but cleanup of older generations still\n // has to continue afterwards.\n ...node.state,\n attr,\n props: news,\n });\n }\n else {\n yield* commit({\n status: \"updated\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr,\n bindings: excludeDeletedBindings(node.bindings),\n providerVersion: node.provider.version ?? 0,\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n tracker[fqn] = {\n output: attr,\n props: news,\n bindings: bindingOutputs,\n instanceId,\n };\n // Signal here for the linear (non-cycle) path. For in-cycle updates\n // the deferred has already been resolved by the early `storeAndSignal`\n // above and `signalReady` is a no-op the second time.\n yield* signalReady;\n yield* signalReadyStable;\n yield* markTerminal(\"updated\");\n return;\n }\n // ── replace ──\n if (node.action === \"replace\") {\n if (node.state.status === \"replaced\" && !node.restart) {\n // The replacement already exists; this pass only needs GC to clean up\n // older generations, so expose the current replacement and stop here.\n tracker[fqn] = {\n output: node.state.attr,\n props: node.state.props,\n bindings: node.state.bindings ?? [],\n instanceId,\n };\n yield* signalReady;\n yield* signalReadyStable;\n yield* markTerminal(\"created\");\n return;\n }\n let replState;\n if (node.state.status !== \"replacing\" || node.restart) {\n // `restart` deliberately nests the previous top-level replacement state\n // into `old`, creating a new outer generation to replace it.\n replState = yield* commit({\n status: \"replacing\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n bindings: excludeDeletedBindings(node.bindings),\n attr: undefined,\n providerVersion: node.provider.version ?? 0,\n deleteFirst: node.deleteFirst,\n old: node.state,\n downstream: node.downstream,\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n else {\n // Resume the same replacement generation after an interrupted apply.\n replState = node.state;\n }\n let attr = replState.attr;\n if (attr !== undefined) {\n // If precreate already ran, expose that intermediate output immediately so\n // downstream resources can resolve against the same in-flight replacement.\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n if (node.provider.precreate && attr === undefined) {\n yield* report(\"pre-creating\");\n attr = yield* node.provider\n .precreate({\n id: logicalId,\n news: node.props,\n session: scopedSession,\n instanceId,\n bindings: excludeDeletedBindings(node.bindings),\n })\n .pipe(instrumentLifecycle(\"precreate\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n status: \"replacing\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: node.props,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n old: replState.old,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.resource.RemovalPolicy,\n });\n yield* storeAndSignal({\n output: attr,\n props: {},\n bindings: [],\n instanceId,\n });\n }\n // See create-flow note: while we're waiting on upstream outputs\n // the replacement isn't actually being created yet.\n yield* report(\"pending\");\n // Replacement create is evaluated exactly like create, but against the new\n // generation's instance id and with the previous generations preserved in `old`.\n yield* waitForDeps(allUpstreamFqns());\n yield* report(\"creating replacement\");\n const outputs = getOutputs();\n const news = (yield* Output.evaluate(node.props, outputs));\n const bindingOutputs = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news,\n instanceId,\n bindings: bindingOutputs,\n session: scopedSession,\n olds: undefined,\n output: attr,\n })\n .pipe(instrumentLifecycle(\"create\", fqn, node.resource.Type, logicalId, instanceId));\n yield* commit({\n // Creation of the new generation succeeded; from here on the only remaining\n // work is draining the old chain via garbage collection.\n status: \"replaced\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: news,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n // Preserve the remaining backlog exactly as-is. GC is responsible for\n // popping one generation at a time until the chain is exhausted.\n old: replState.old,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.resource.RemovalPolicy,\n });\n tracker[fqn] = {\n output: attr,\n props: news,\n bindings: bindingOutputs,\n instanceId,\n };\n yield* signalReady;\n yield* signalReadyStable;\n // Keep progress anchored to the live replacement while GC drains the\n // previous generation(s) in the background.\n yield* markTerminal(\"created\");\n return;\n }\n // @ts-expect-error - node is never, this should be unreachable\n return yield* Effect.die(`Unknown action: ${node.action}`);\n });\n}).pipe(Effect.catchCause((cause) => \n// Record the failure, propagate it to any downstream resources waiting on\n// our Deferred (so their waitForDeps short-circuits instead of deadlocking),\n// emit a \"fail\" status to the session, and resolve to void so Effect.all\n// does not interrupt sibling fibers. The aggregated cause is raised at\n// the end of executePlan.\nEffect.gen(function* () {\n failures.push({\n fqn,\n logicalId: node.resource.LogicalId,\n type: node.resource.Type,\n cause,\n });\n yield* Deferred.failCause(ready[fqn], cause);\n yield* Deferred.failCause(readyStable[fqn], cause);\n yield* session.emit({\n kind: \"status-change\",\n id: node.resource.LogicalId,\n type: node.resource.Type,\n status: \"fail\",\n });\n})), Effect.withSpan(\"apply.resource\", {\n attributes: {\n \"alchemy.resource.fqn\": fqn,\n \"alchemy.resource.type\": node.resource.Type,\n \"alchemy.resource.logical_id\": node.resource.LogicalId,\n \"alchemy.resource.action\": node.action,\n },\n}));\n// ── Task execution ─────────────────────────────────────────────────────────\n//\n// Tasks slot into the same scheduler as resources. They have no provider\n// lifecycle — just a single Effect that runs when inputs change (or when\n// `--force` is set). The output value is written to `tracker[fqn].output`\n// so downstream Output evaluation works identically to resource attrs.\nconst executeActionNode = (fqn, node, tracker, ready, readyStable, terminalStatuses, session, state, stackName, stage, getOutputs, waitForDeps, failures) => Effect.gen(function* () {\n const task = node.def;\n const logicalId = task.LogicalId;\n const namespace = task.Namespace;\n const commit = (value) => state.set({\n stack: stackName,\n stage,\n fqn,\n value: { ...value, namespace },\n });\n const report = (status) => session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: task.Type,\n status,\n });\n const signalReady = Deferred.succeed(ready[fqn], void 0);\n const signalReadyStable = Deferred.succeed(readyStable[fqn], void 0);\n if (node.action === \"noop\") {\n tracker[fqn] = {\n output: node.state.output,\n props: { __input: node.state.input },\n bindings: [],\n instanceId: fqn,\n };\n yield* signalReady;\n yield* signalReadyStable;\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: task.Type,\n status: \"skipped\",\n });\n yield* report(\"skipped\");\n return;\n }\n // ── run ──\n // Tasks wait on `waitForStableDeps` (post-reconcile attrs) for their\n // upstreams, which is often the slowest dep chain in the deploy.\n // Surface that as \"pending\" instead of having the task show no status\n // until its run actually starts.\n yield* report(\"pending\");\n yield* waitForDeps(Object.keys(Output.resolveUpstream(node.input)).filter((f) => f in readyStable));\n const outputs = getOutputs();\n const resolvedInput = (yield* Output.evaluate(node.input, outputs));\n const inputHashValue = yield* hashInput(resolvedInput);\n yield* commit({\n kind: \"action\",\n status: \"running\",\n fqn,\n logicalId,\n actionType: task.Type,\n inputHash: inputHashValue,\n input: resolvedInput,\n downstream: node.downstream,\n });\n yield* report(\"running\");\n const result = yield* task.Run(resolvedInput);\n yield* commit({\n kind: \"action\",\n status: \"ran\",\n fqn,\n logicalId,\n actionType: task.Type,\n inputHash: inputHashValue,\n input: resolvedInput,\n output: result,\n downstream: node.downstream,\n });\n tracker[fqn] = {\n output: result,\n props: { __input: resolvedInput },\n bindings: [],\n instanceId: fqn,\n };\n yield* signalReady;\n yield* signalReadyStable;\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: task.Type,\n status: \"ran\",\n });\n yield* report(\"ran\");\n}).pipe(Effect.catchCause((cause) => Effect.gen(function* () {\n failures.push({\n fqn,\n logicalId: node.def.LogicalId,\n type: node.def.Type,\n cause,\n });\n yield* Deferred.failCause(ready[fqn], cause);\n yield* Deferred.failCause(readyStable[fqn], cause);\n yield* session.emit({\n kind: \"status-change\",\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"fail\",\n });\n})), Effect.withSpan(\"apply.action\", {\n attributes: {\n \"alchemy.action.fqn\": fqn,\n \"alchemy.action.type\": node.def.Type,\n \"alchemy.action.logical_id\": node.def.LogicalId,\n \"alchemy.action.verb\": node.action,\n },\n}));\n// ── Phase 3: imperative convergence loop ───────────────────────────────────\n//\n// After the initial concurrent pass, some resources may have been created\n// with stale upstream values (e.g. a precreate stub instead of the final\n// output). Walk the plan and re-evaluate each resource's props/bindings\n// against the current tracker outputs. Call provider.reconcile for any\n// resource whose resolved inputs differ from what it was last applied with.\n// Repeat until no resource needs updating.\nconst converge = Effect.fnUntraced(function* (plan, tracker, terminalStatuses, session, state, stackName, stage) {\n for (;;) {\n let anyUpdated = false;\n for (const [fqn, node] of Object.entries(plan.resources)) {\n if (node.action === \"noop\")\n continue;\n if (!tracker[fqn])\n continue;\n const outputs = Object.fromEntries(Object.entries(tracker).map(([k, t]) => [k, t.output]));\n const newProps = (yield* Output.evaluate(node.props, outputs));\n const newBindings = excludeDeletedBindings(yield* Output.evaluate(node.bindings, outputs));\n const oldProps = tracker[fqn].props;\n const oldBindings = tracker[fqn].bindings;\n const propsChanged = havePropsChanged(oldProps, newProps);\n const bindingsChanged = JSON.stringify(oldBindings) !== JSON.stringify(newBindings);\n if (!propsChanged && !bindingsChanged)\n continue;\n anyUpdated = true;\n const logicalId = node.resource.LogicalId;\n const namespace = node.resource.Namespace;\n const instanceId = tracker[fqn].instanceId;\n const scopedSession = {\n ...session,\n note: (note) => session.emit({ id: logicalId, kind: \"annotate\", message: note }),\n };\n const attr = yield* node.provider\n .reconcile({\n id: logicalId,\n news: newProps,\n instanceId,\n bindings: newBindings,\n session: scopedSession,\n olds: oldProps,\n output: tracker[fqn].output,\n })\n .pipe(instrumentLifecycle(\"update\", fqn, node.resource.Type, logicalId, instanceId));\n tracker[fqn] = {\n output: attr,\n props: newProps,\n bindings: newBindings,\n instanceId,\n };\n yield* state.set({\n stack: stackName,\n stage,\n fqn,\n value: {\n status: \"updated\",\n fqn,\n logicalId,\n instanceId,\n resourceType: node.resource.Type,\n props: newProps,\n attr,\n providerVersion: node.provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n downstream: node.downstream,\n namespace,\n removalPolicy: node.resource.RemovalPolicy,\n },\n });\n terminalStatuses.set(fqn, {\n id: logicalId,\n type: node.resource.Type,\n status: \"updated\",\n });\n }\n // Tasks: re-run when their resolved input drifts vs. the value they\n // last applied with (e.g. an upstream resource produced new attrs in\n // this pass). Skipped (noop) tasks are not re-checked here — their\n // recorded inputHash is authoritative until the next plan.\n for (const [fqn, node] of Object.entries(plan.actions)) {\n if (node.action !== \"run\")\n continue;\n if (!tracker[fqn])\n continue;\n const outputs = Object.fromEntries(Object.entries(tracker).map(([k, t]) => [k, t.output]));\n const newInput = (yield* Output.evaluate(node.input, outputs));\n const newHash = yield* hashInput(newInput);\n const oldInput = tracker[fqn].props?.__input;\n const oldHash = yield* hashInput(oldInput);\n if (newHash === oldHash)\n continue;\n anyUpdated = true;\n yield* state.set({\n stack: stackName,\n stage,\n fqn,\n value: {\n kind: \"action\",\n status: \"running\",\n fqn,\n logicalId: node.def.LogicalId,\n namespace: node.def.Namespace,\n actionType: node.def.Type,\n inputHash: newHash,\n input: newInput,\n downstream: node.downstream,\n },\n });\n const result = yield* node.def.Run(newInput);\n yield* state.set({\n stack: stackName,\n stage,\n fqn,\n value: {\n kind: \"action\",\n status: \"ran\",\n fqn,\n logicalId: node.def.LogicalId,\n namespace: node.def.Namespace,\n actionType: node.def.Type,\n inputHash: newHash,\n input: newInput,\n output: result,\n downstream: node.downstream,\n },\n });\n tracker[fqn] = {\n output: result,\n props: { __input: newInput },\n bindings: [],\n instanceId: fqn,\n };\n terminalStatuses.set(fqn, {\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"ran\",\n });\n }\n if (!anyUpdated)\n break;\n }\n});\n// ── Phase 2: delete orphans and old replaced resources ─────────────────────\nconst collectGarbage = Effect.fnUntraced(function* (plan, session) {\n const state = yield* State;\n const stack = yield* Stack;\n const stackName = stack.name;\n const stage = yield* Stage;\n // Task deletions are pure state drops — no body is invoked. Run them in\n // parallel before resource GC; tasks never have provider-side dependencies\n // to wait on.\n yield* Effect.all(Object.entries(plan.actionDeletions ?? {}).map(([fqn, node]) => node === undefined\n ? Effect.void\n : Effect.gen(function* () {\n yield* session.emit({\n kind: \"status-change\",\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"deleting\",\n });\n yield* state.delete({ stack: stackName, stage, fqn });\n yield* session.emit({\n kind: \"status-change\",\n id: node.def.LogicalId,\n type: node.def.Type,\n status: \"deleted\",\n });\n })), { concurrency: \"unbounded\" });\n const deleteGraph = Effect.fnUntraced(function* (deletionGraph) {\n const deletions = {};\n const deleteResource = (node, ancestors = new Set()) => Effect.gen(function* () {\n const isDeleteNode = (node) => \"action\" in node;\n const { logicalId, namespace, resourceType, instanceId, downstream, props, attr, provider, } = isDeleteNode(node)\n ? {\n logicalId: node.resource.LogicalId,\n namespace: node.resource.Namespace,\n resourceType: node.resource.Type,\n instanceId: node.state.instanceId,\n downstream: node.downstream,\n props: node.state.props,\n attr: node.state.attr,\n provider: node.provider,\n }\n : {\n logicalId: node.logicalId,\n namespace: node.namespace,\n resourceType: node.old.resourceType,\n instanceId: node.old.instanceId,\n downstream: node.old.downstream,\n props: node.old.props,\n attr: node.old.attr,\n provider: yield* findProviderByType(node.old.resourceType),\n };\n const fqn = toFqn(namespace, logicalId);\n const nextAncestors = new Set(ancestors).add(fqn);\n const commit = (value) => state.set({\n stack: stackName,\n stage,\n fqn,\n value: { ...value, namespace },\n });\n const report = (status) => session.emit({\n kind: \"status-change\",\n id: logicalId,\n type: resourceType,\n status,\n });\n const scopedSession = {\n ...session,\n note: (note) => session.emit({\n id: logicalId,\n kind: \"annotate\",\n message: note,\n }),\n };\n return yield* (deletions[fqn] ??= yield* Effect.cached(Effect.gen(function* () {\n yield* Effect.all(downstream.map((dep) => dep !== fqn && dep in deletionGraph && !ancestors.has(dep)\n ? deleteResource(deletionGraph[dep], nextAncestors)\n : Effect.void), { concurrency: \"unbounded\" });\n if (isDeleteNode(node)) {\n yield* report(\"deleting\");\n if (node.resource.RemovalPolicy === \"retain\") {\n yield* state.delete({\n stack: stackName,\n stage,\n fqn,\n });\n yield* report(\"deleted\");\n return;\n }\n yield* commit({\n status: \"deleting\",\n fqn,\n logicalId,\n instanceId,\n resourceType,\n props,\n attr,\n downstream,\n providerVersion: provider.version ?? 0,\n bindings: excludeDeletedBindings(node.bindings),\n removalPolicy: node.resource.RemovalPolicy,\n });\n }\n if (attr !== undefined) {\n yield* provider\n .delete({\n id: logicalId,\n instanceId,\n olds: props,\n output: attr,\n session: scopedSession,\n bindings: [],\n })\n .pipe(instrumentLifecycle(\"delete\", fqn, resourceType, logicalId, instanceId));\n }\n if (isDeleteNode(node)) {\n yield* state.delete({\n stack: stackName,\n stage,\n fqn,\n });\n yield* report(\"deleted\");\n }\n else {\n yield* scopedSession.note(\"Cleaning up replaced resource...\");\n if (node.old.status === \"replacing\" ||\n node.old.status === \"replaced\") {\n // We only deleted the outermost old generation. A nested replacement\n // chain still exists, so stay in `replaced` and pop the chain forward\n // one level. The outer loop will pick this resource up again.\n yield* commit({\n status: \"replaced\",\n fqn,\n logicalId: node.logicalId,\n instanceId: node.instanceId,\n resourceType: node.resourceType,\n props: node.props,\n attr: node.attr,\n providerVersion: node.providerVersion,\n downstream: node.downstream,\n bindings: excludeDeletedBindings(node.bindings),\n old: node.old.old,\n deleteFirst: node.deleteFirst,\n removalPolicy: node.removalPolicy,\n });\n }\n else {\n // The old chain is fully drained, so the current replacement is now\n // the stable resource and we can collapse back to a terminal state.\n yield* commit({\n status: \"created\",\n fqn,\n logicalId: node.logicalId,\n instanceId: node.instanceId,\n resourceType: node.resourceType,\n props: node.props,\n attr: node.attr,\n providerVersion: node.providerVersion,\n downstream: node.downstream,\n bindings: excludeDeletedBindings(node.bindings),\n removalPolicy: node.removalPolicy,\n });\n }\n yield* scopedSession.note(\"Replaced resource cleanup complete.\");\n }\n })));\n });\n yield* Effect.all(Object.values(deletionGraph)\n .filter((node) => node !== undefined)\n .map((node) => deleteResource(node)), { concurrency: \"unbounded\" });\n });\n // The first pass handles both planned deletions and any top-level replaced\n // resources already present in state. Later passes only drain replacement\n // chains that were re-committed as `replaced` while deleting older generations.\n let first = true;\n while (true) {\n const remainingReplacedResources = yield* state.getReplacedResources({\n stack: stackName,\n stage,\n });\n if (!first && remainingReplacedResources.length === 0) {\n break;\n }\n yield* deleteGraph({\n // Orphan/resource deletions from the current plan should only run once.\n ...(first ? plan.deletions : {}),\n ...Object.fromEntries(remainingReplacedResources.map((replaced) => [\n toFqn(replaced.namespace, replaced.logicalId),\n replaced,\n ])),\n });\n first = false;\n }\n});\nconst excludeDeletedBindings = (bindings) => bindings.flatMap(({ action, sid, data }) => action === \"delete\" ? [] : [{ sid, data }]);\n//# sourceMappingURL=Apply.js.map","var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\n });\n }\n return path;\n};\nimport * as Cause from \"effect/Cause\";\nimport * as Config from \"effect/Config\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Option from \"effect/Option\";\nimport * as Path from \"effect/Path\";\nimport * as S from \"effect/Schema\";\nimport * as Argument from \"effect/unstable/cli/Argument\";\nimport * as CliError from \"effect/unstable/cli/CliError\";\nimport * as Flag from \"effect/unstable/cli/Flag\";\nimport { AuthError, AuthProviders, } from \"../../Auth/AuthProvider.js\";\nimport { recordCli } from \"../../Telemetry/Metrics.js\";\nimport { PromptCancelled } from \"../../Util/Clank.js\";\nexport const USER = Config.string(\"USER\").pipe(Config.orElse(() => Config.string(\"USERNAME\")), Config.withDefault(\"unknown\"));\nexport const STAGE = Config.string(\"stage\").pipe(Config.option, (a) => a, Effect.map(Option.getOrUndefined));\n/**\n * `true` if `e` is a {@link PromptCancelled}, or an {@link AuthError} whose\n * `cause` chain bottoms out in one. Schema-tagged errors don't always\n * survive `instanceof` across module boundaries, so we also accept any\n * object whose `_tag` matches.\n */\nconst isPromptCancellation = (e) => {\n for (let cur = e, i = 0; cur != null && i < 16; i++) {\n if (cur instanceof PromptCancelled)\n return true;\n if (typeof cur === \"object\" &&\n cur._tag === \"PromptCancelled\") {\n return true;\n }\n if (cur instanceof AuthError ||\n (typeof cur === \"object\" &&\n cur._tag === \"AuthError\")) {\n cur = cur.cause;\n continue;\n }\n return false;\n }\n return false;\n};\n/**\n * Catches user cancellations (Ctrl+C inside a prompt, surfaced as\n * {@link PromptCancelled} or wrapped in an {@link AuthError}) and exits\n * the CLI cleanly with a friendly message instead of dumping a stack\n * trace.\n */\nexport const handleCancellation = (self) => self.pipe(Effect.catchCause((cause) => {\n const cancelled = cause.reasons.some((r) => {\n if (Cause.isFailReason(r))\n return isPromptCancellation(r.error);\n if (Cause.isDieReason(r))\n return isPromptCancellation(r.defect);\n return false;\n });\n return cancelled\n ? Console.log(\"\\nCancelled.\")\n : Effect.failCause(cause);\n}), \n// A bare fiber interrupt (Ctrl+C while not inside a prompt) shouldn't\n// dump a stack trace either.\nEffect.onInterrupt(() => Console.log(\"\\nInterrupted.\")));\nexport const stage = Flag.string(\"stage\").pipe(Flag.withSchema(S.String.check(S.isPattern(/^[a-z0-9]+([-_a-z0-9]+)*$/gi))), Flag.withDescription(\"Stage to deploy to, defaults to dev_${USER}\"), Flag.optional, Flag.map(Option.getOrUndefined), Flag.mapEffect(Effect.fn(function* (stage) {\n if (stage) {\n return stage;\n }\n return yield* STAGE.pipe(Effect.catch(() => Effect.fail(new CliError.MissingOption({\n option: \"stage\",\n }))), Effect.flatMap((s) => s === undefined\n ? USER.pipe(Effect.map((user) => `dev_${user}`), Effect.catch(() => Effect.succeed(\"unknown\")))\n : Effect.succeed(s)));\n})));\nexport const envFile = Flag.file(\"env-file\").pipe(Flag.optional, Flag.withDescription(\"File to load environment variables from, defaults to .env\"));\nexport const dryRun = Flag.boolean(\"dry-run\").pipe(Flag.withDescription(\"Dry run the deployment, do not actually deploy\"), Flag.withDefault(false));\nexport const yes = Flag.boolean(\"yes\").pipe(Flag.withDescription(\"Yes to all prompts\"), Flag.withDefault(false));\nexport const force = Flag.boolean(\"force\").pipe(Flag.withDescription(\"Force updates for resources that would otherwise no-op\"), Flag.withDefault(false));\nexport const script = Argument.file(\"main\", {\n mustExist: true,\n}).pipe(Argument.withDescription(\"Main file to deploy, defaults to alchemy.run.ts\"), Argument.withDefault(\"alchemy.run.ts\"));\nexport const profile = Flag.string(\"profile\").pipe(Flag.withDescription(\"Auth profile to use (~/.alchemy/profiles.json). Defaults to 'default' or $ALCHEMY_PROFILE.\"), Flag.optional, Flag.map(Option.getOrElse(() => \"default\")));\nexport const resourceFilter = Flag.string(\"filter\").pipe(Flag.withDescription(\"Comma-separated logical resource IDs (e.g. Api,Sandbox). Only those resources are included.\"), Flag.optional, Flag.map(Option.getOrUndefined));\nexport const TAIL_COLORS = [\n \"\\x1b[36m\", // cyan\n \"\\x1b[35m\", // magenta\n \"\\x1b[33m\", // yellow\n \"\\x1b[32m\", // green\n \"\\x1b[34m\", // blue\n \"\\x1b[91m\", // bright red\n \"\\x1b[96m\", // bright cyan\n \"\\x1b[95m\", // bright magenta\n \"\\x1b[93m\", // bright yellow\n \"\\x1b[92m\", // bright green\n];\nexport const TAIL_RESET = \"\\x1b[0m\";\nexport const formatLocalTimestamp = (date) => {\n const y = date.getFullYear();\n const mo = String(date.getMonth() + 1).padStart(2, \"0\");\n const d = String(date.getDate()).padStart(2, \"0\");\n const h = String(date.getHours()).padStart(2, \"0\");\n const mi = String(date.getMinutes()).padStart(2, \"0\");\n const s = String(date.getSeconds()).padStart(2, \"0\");\n const ms = String(date.getMilliseconds()).padStart(3, \"0\");\n const tz = new Intl.DateTimeFormat(\"en-US\", { timeZoneName: \"short\" })\n .formatToParts(date)\n .find((p) => p.type === \"timeZoneName\")?.value ?? \"\";\n return `${y}-${mo}-${d} ${h}:${mi}:${s}.${ms} ${tz}`;\n};\nexport const parseResourceFilter = (filter) => {\n if (filter === undefined)\n return undefined;\n const ids = filter\n .split(\",\")\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n if (ids.length === 0)\n return undefined;\n return new Set(ids);\n};\nexport const parseSince = (value) => {\n const match = value.match(/^(\\d+)([smhd])$/);\n if (match) {\n const num = parseInt(match[1], 10);\n const unit = match[2];\n const ms = unit === \"s\"\n ? num * 1000\n : unit === \"m\"\n ? num * 60_000\n : unit === \"h\"\n ? num * 3_600_000\n : num * 86_400_000;\n return new Date(Date.now() - ms);\n }\n const parsed = new Date(value);\n if (isNaN(parsed.getTime())) {\n throw new Error(`Invalid --since value: '${value}'. Use a duration (e.g. '1h', '30m') or ISO date.`);\n }\n return parsed;\n};\n/**\n * Wraps a CLI command handler with a top-level OpenTelemetry span\n * (`cli.<command>`) and bumps the `alchemy.cli.invocations` counter.\n *\n * `attrs` runs against the parsed command args and contributes\n * additional attributes to the span (e.g. stage, profile, dry-run flag).\n *\n * Usage:\n * ```ts\n * Command.make(\n * \"deploy\",\n * { ...flags },\n * instrumentCommand(\"deploy\", (a) => ({\n * \"alchemy.stage\": a.stage,\n * \"alchemy.profile\": a.profile,\n * }))(execStack),\n * );\n * ```\n */\nexport const instrumentCommand = (command, attrs) => (handler) => (args) => handler(args).pipe(Effect.withSpan(`cli.${command}`, {\n attributes: attrs ? attrs(args) : {},\n}), recordCli(command));\n/**\n * Render a profile's stored credential entries the same way across\n * `alchemy login` and `alchemy profile show`: one `── Provider ──`\n * header per entry, then either the provider's own `prettyPrint` block\n * (preferred) or a JSON-style fallback when the provider isn't\n * registered in the supplied {@link AuthProviders} registry.\n */\nexport const printProfile = Effect.fn(function* (profile, stored, registry) {\n yield* Console.log(`Profile: ${profile}`);\n const names = Object.keys(stored).sort();\n if (names.length === 0) {\n yield* Console.log(\"(no providers configured)\");\n return;\n }\n for (const name of names) {\n const cfg = stored[name];\n yield* Console.log(\"\");\n yield* Console.log(`── ${name} ──`);\n const provider = registry[name];\n if (provider == null) {\n yield* Console.log(` method: ${cfg.method}`);\n const { method: _method, ...rest } = cfg;\n for (const [k, v] of Object.entries(rest)) {\n yield* Console.log(` ${k}: ${typeof v === \"string\" ? v : JSON.stringify(v)}`);\n }\n continue;\n }\n yield* provider.prettyPrint(profile, cfg);\n }\n});\nexport const importStack = Effect.fn(function* (main) {\n const path = yield* Path.Path;\n const url = import.meta.resolve(path.resolve(main));\n const module = yield* Effect.promise(() => import(__rewriteRelativeImportExtension(url)));\n const stackEffect = module.default;\n if (!Effect.isEffect(stackEffect)) {\n return yield* Effect.die(new Error(`Main file '${main}' must export a default stack definition (export default Alchemy.Stack({...}))`));\n }\n return stackEffect;\n});\n//# sourceMappingURL=_shared.js.map","import * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Logger from \"effect/Logger\";\nimport * as Option from \"effect/Option\";\nimport * as Schema from \"effect/Schema\";\nimport * as Command from \"effect/unstable/cli/Command\";\nimport * as Flag from \"effect/unstable/cli/Flag\";\nimport { AdoptPolicy } from \"../../AdoptPolicy.js\";\nimport { AlchemyContext } from \"../../AlchemyContext.js\";\nimport { apply } from \"../../Apply.js\";\nimport { ArtifactStore, createArtifactStore } from \"../../Artifacts.js\";\nimport { AuthProviders } from \"../../Auth/AuthProvider.js\";\nimport { withProfileOverride } from \"../../Auth/Profile.js\";\nimport * as CLI from \"../../Cli/Cli.js\";\nimport * as Plan from \"../../Plan.js\";\nimport { Stage } from \"../../Stage.js\";\nimport { loadConfigProvider } from \"../../Util/ConfigProvider.js\";\nimport { fileLogger } from \"../../Util/FileLogger.js\";\nimport { dryRun as dryRunFlag, envFile, force, importStack, instrumentCommand, profile, script, stage, yes, } from \"./_shared.js\";\nexport const ExecStackOptions = Schema.Struct({\n main: Schema.String,\n stage: Schema.String,\n envFile: Schema.OptionFromOptional(Schema.String),\n profile: Schema.optional(Schema.String),\n dryRun: Schema.optional(Schema.Boolean),\n force: Schema.optional(Schema.Boolean),\n yes: Schema.optional(Schema.Boolean),\n destroy: Schema.optional(Schema.Boolean),\n dev: Schema.optional(Schema.Boolean),\n adopt: Schema.optional(Schema.Boolean),\n});\nconst stackSpanAttrs = (args) => ({\n \"alchemy.stage\": args.stage,\n \"alchemy.profile\": args.profile,\n \"alchemy.main\": args.main,\n \"alchemy.dry_run\": !!args.dryRun,\n \"alchemy.force\": !!args.force,\n \"alchemy.destroy\": !!args.destroy,\n \"alchemy.dev\": !!args.dev,\n \"alchemy.adopt\": !!args.adopt,\n});\nconst adopt = Flag.boolean(\"adopt\").pipe(Flag.withDescription(\"Adopt pre-existing cloud resources that conflict with this stack instead of failing. \" +\n \"Useful for re-importing infrastructure into a fresh state store.\"), Flag.withDefault(false));\nexport const execStack = Effect.fn(function* ({ main, stage, envFile, profile, dryRun = false, force = false, yes = false, destroy = false, dev = false, adopt = false, }) {\n const stackEffect = yield* importStack(main);\n const services = Layer.mergeAll(Layer.effect(AlchemyContext, AlchemyContext.pipe(Effect.map((ctx) => ({\n ...ctx,\n dev,\n adopt,\n })))), \n // `--adopt` opts the entire deploy in to adoption-on-conflict.\n // Resource providers that wire `AdoptPolicy` (Worker domains,\n // Cloudflare.SecretsStore, etc.) will reconcile against\n // pre-existing cloud resources instead of failing on duplicates.\n // Default is `false` so an unintentional collision still surfaces\n // loudly.\n Layer.succeed(AdoptPolicy, adopt), Layer.succeed(ArtifactStore, createArtifactStore()), Layer.succeed(AuthProviders, yield* Effect.serviceOption(AuthProviders).pipe(Effect.map(Option.getOrElse(() => ({}))))), ConfigProvider.layer(withProfileOverride(yield* loadConfigProvider(envFile), profile)), Logger.layer([fileLogger(\"out\")], { mergeWithExisting: true }), Layer.succeed(Stage, stage));\n yield* Effect.gen(function* () {\n const cli = yield* CLI.Cli;\n const stack = yield* stackEffect;\n yield* Effect.gen(function* () {\n const updatePlan = yield* Plan.make(destroy\n ? {\n ...stack,\n // zero these out (destroy will treat all as orphans)\n // TODO(sam): probably better to have Plan.destroy and Plan.update\n resources: {},\n bindings: {},\n actions: {},\n output: {},\n }\n : stack, { force });\n if (dryRun) {\n yield* cli.displayPlan(updatePlan);\n }\n else {\n const hasChanges = Object.keys(updatePlan.deletions).length > 0 ||\n Object.values(updatePlan.resources).some((node) => node.action !== \"noop\" ||\n node.bindings.some((b) => b.action !== \"noop\"));\n if (!yes && hasChanges) {\n const approved = yield* cli.approvePlan(updatePlan);\n if (!approved) {\n return;\n }\n }\n const outputs = yield* apply(updatePlan);\n if (outputs !== undefined) {\n yield* Console.log(outputs);\n }\n if (dev) {\n yield* Effect.never;\n }\n }\n }).pipe(Effect.provide(stack.services));\n }).pipe(Effect.provide(services));\n});\nexport const deployCommand = Command.make(\"deploy\", {\n dryRun: dryRunFlag,\n force,\n main: script,\n envFile,\n stage,\n yes,\n profile,\n adopt,\n}, instrumentCommand(\"deploy\", stackSpanAttrs)(execStack));\nexport const destroyCommand = Command.make(\"destroy\", {\n dryRun: dryRunFlag,\n main: script,\n envFile,\n stage,\n yes,\n profile,\n}, instrumentCommand(\"destroy\", stackSpanAttrs)((args) => execStack({\n ...args,\n destroy: true,\n})));\nexport const planCommand = Command.make(\"plan\", {\n main: script,\n envFile,\n stage,\n profile,\n}, instrumentCommand(\"plan\", stackSpanAttrs)((args) => execStack({\n ...args,\n // plan is the same as deploy with dryRun always set to true\n dryRun: true,\n})));\n//# sourceMappingURL=deploy.js.map","import * as Console from \"effect/Console\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { Cli } from \"./Cli.js\";\nconst ESC = \"\\x1b[\";\nconst RESET = `${ESC}0m`;\nconst useColor = process.stdout.hasColors?.() ?? !!process.stdout.isTTY;\nconst c = (code, s) => useColor ? `${ESC}${code}m${s}${RESET}` : s;\nconst dim = (s) => c(\"2\", s);\nconst bold = (s) => c(\"1\", s);\nconst red = (s) => c(\"31\", s);\nconst green = (s) => c(\"32\", s);\nconst yellow = (s) => c(\"33\", s);\nconst blue = (s) => c(\"34\", s);\nconst magenta = (s) => c(\"35\", s);\nconst cyan = (s) => c(\"36\", s);\nconst actionColor = {\n create: green,\n update: yellow,\n replace: magenta,\n delete: red,\n noop: dim,\n};\nconst statusColor = (status) => {\n switch (status) {\n case \"created\":\n case \"updated\":\n case \"replaced\":\n return green;\n case \"deleted\":\n return dim;\n case \"fail\":\n return red;\n case \"attaching\":\n case \"post-attach\":\n return cyan;\n default:\n return yellow;\n }\n};\nconst tag = (id) => bold(`[${id}]`);\nconst isTerminal = (status) => status === \"created\" ||\n status === \"updated\" ||\n status === \"deleted\" ||\n status === \"replaced\" ||\n status === \"fail\";\nconst formatPlanLines = (plan) => {\n const items = [\n ...Object.values(plan.resources),\n ...Object.values(plan.deletions),\n ];\n if (items.length === 0)\n return [bold(\"Plan:\") + \" no changes\"];\n const counts = items.reduce((acc, item) => ((acc[item.action] = (acc[item.action] ?? 0) + 1), acc), {});\n const summary = [\"create\", \"update\", \"replace\", \"delete\", \"noop\"]\n .filter((a) => counts[a])\n .map((a) => actionColor[a](`${counts[a]} to ${a}`))\n .join(dim(\", \"));\n const sorted = [...items].sort((a, b) => a.resource.LogicalId.localeCompare(b.resource.LogicalId));\n const lines = [`${bold(\"Plan:\")} ${summary}`];\n for (const item of sorted) {\n const action = actionColor[item.action](item.action);\n lines.push(`${tag(item.resource.LogicalId)} ${action}`);\n for (const binding of item.bindings) {\n if (binding.action === \"noop\")\n continue;\n const bindingAction = actionColor[binding.action](binding.action);\n lines.push(`${tag(`${item.resource.LogicalId}/${binding.sid}`)} ${bindingAction}`);\n }\n }\n return lines;\n};\nexport const LoggingCli = Layer.succeed(Cli, Cli.of({\n approvePlan: (plan) => Effect.gen(function* () {\n for (const line of formatPlanLines(plan))\n yield* Console.log(line);\n yield* Console.log(`\\n${yellow(\"Non-interactive terminal detected.\")} Pass ${bold(\"--yes\")} to approve, or set ${bold(\"ALCHEMY_TUI=1\")} for the interactive UI.`);\n return false;\n }),\n displayPlan: (plan) => Effect.gen(function* () {\n for (const line of formatPlanLines(plan))\n yield* Console.log(line);\n }),\n startApplySession: (plan) => Effect.gen(function* () {\n for (const line of formatPlanLines(plan))\n yield* Console.log(line);\n yield* Console.log(\"\");\n const counts = { ok: 0, fail: 0 };\n return {\n emit: (event) => Effect.sync(() => {\n if (event.kind === \"annotate\") {\n console.log(`${tag(event.id)} ${blue(event.message)}`);\n return;\n }\n const id = event.bindingId\n ? `${event.id}/${event.bindingId}`\n : event.id;\n const status = statusColor(event.status)(event.status);\n const msg = event.message ? ` ${dim(\"—\")} ${event.message}` : \"\";\n console.log(`${tag(id)} ${status}${msg}`);\n if (isTerminal(event.status)) {\n if (event.status === \"fail\")\n counts.fail++;\n else\n counts.ok++;\n }\n }),\n done: () => Console.log(`\\n${bold(\"Done:\")} ${green(`${counts.ok} succeeded`)}${counts.fail ? dim(\", \") + red(`${counts.fail} failed`) : \"\"}`),\n };\n }),\n}));\n//# sourceMappingURL=LoggingCli.js.map","import { toPath } from \"../FQN.js\";\nexport function buildNamespaceTree(items, actions = []) {\n const root = {\n id: \"\",\n path: [],\n children: new Map(),\n resources: [],\n actions: [],\n };\n const getNode = (path) => {\n let current = root;\n for (let i = 0; i < path.length; i++) {\n const segment = path[i];\n let child = current.children.get(segment);\n if (!child) {\n child = {\n id: segment,\n path: path.slice(0, i + 1),\n children: new Map(),\n resources: [],\n actions: [],\n };\n current.children.set(segment, child);\n }\n current = child;\n }\n return current;\n };\n for (const item of items) {\n getNode(toPath(item.resource.Namespace)).resources.push(item);\n }\n for (const action of actions) {\n getNode(toPath(action.def.Namespace)).actions.push(action);\n }\n return root;\n}\nexport function deriveNamespaceAction(node) {\n const actions = new Set();\n for (const resource of node.resources) {\n actions.add(deriveResourceChildrenAction(resource, node));\n }\n for (const action of node.actions) {\n // Map task actions onto the resource action space for the rollup:\n // run → create, delete → delete, noop → noop.\n actions.add(action.action === \"run\"\n ? \"create\"\n : action.action === \"delete\"\n ? \"delete\"\n : \"noop\");\n }\n for (const child of node.children.values()) {\n const childAction = deriveNamespaceAction(child);\n if (childAction === \"mixed\") {\n return \"mixed\";\n }\n actions.add(childAction);\n }\n return deriveAction(actions);\n}\nexport function flattenTree(node, depth = 0, result = []) {\n flattenNamespace(node, depth, result);\n return result;\n}\nconst flattenNamespace = (node, depth, result) => {\n const sortedResources = [...node.resources].sort((a, b) => a.resource.LogicalId.localeCompare(b.resource.LogicalId));\n const sortedChildren = Array.from(node.children.entries()).sort(([a], [b]) => a.localeCompare(b));\n const resourceIds = new Set(sortedResources.map((resource) => resource.resource.LogicalId));\n for (const [id, child] of sortedChildren) {\n if (resourceIds.has(id) || isEmpty(child)) {\n continue;\n }\n result.push({\n type: \"namespace\",\n depth,\n id,\n path: child.path,\n action: deriveNamespaceAction(child),\n hasChildren: true,\n });\n flattenNamespace(child, depth + 1, result);\n }\n for (const resource of sortedResources) {\n const childNamespace = node.children.get(resource.resource.LogicalId);\n result.push({\n type: \"resource\",\n depth,\n id: resource.resource.LogicalId,\n path: [...node.path, resource.resource.LogicalId],\n action: resource.action,\n resourceType: resource.resource.Type,\n bindingCount: resource.bindings.length,\n });\n for (const binding of [...resource.bindings].sort((a, b) => a.sid.localeCompare(b.sid))) {\n result.push({\n type: \"binding\",\n depth: depth + 1,\n id: binding.sid,\n path: [...node.path, resource.resource.LogicalId, binding.sid],\n action: binding.action,\n bindingSid: binding.sid,\n });\n }\n if (childNamespace) {\n flattenNamespace(childNamespace, depth + 1, result);\n }\n }\n // Actions are listed after resources at the same depth.\n const sortedActions = [...node.actions].sort((a, b) => a.def.LogicalId.localeCompare(b.def.LogicalId));\n for (const action of sortedActions) {\n result.push({\n type: \"action\",\n depth,\n id: action.def.LogicalId,\n path: [...node.path, action.def.LogicalId],\n action: action.action,\n actionType: action.def.Type,\n });\n }\n};\nconst isEmpty = (node) => node.resources.length === 0 &&\n node.actions.length === 0 &&\n Array.from(node.children.values()).every(isEmpty);\nconst countVisibleChildren = (node) => {\n const resourceIds = new Set(node.resources.map((resource) => resource.resource.LogicalId));\n return (node.resources.length +\n Array.from(node.children.keys()).filter((id) => !resourceIds.has(id)).length);\n};\nconst deriveResourceChildrenAction = (resource, node) => {\n const actions = new Set([\n resource.action,\n ]);\n for (const binding of resource.bindings) {\n actions.add(binding.action);\n }\n const childNamespace = node.children.get(resource.resource.LogicalId);\n if (childNamespace) {\n actions.add(deriveNamespaceAction(childNamespace));\n }\n return deriveAction(actions);\n};\nconst deriveAction = (actions) => {\n if (actions.size === 0)\n return \"noop\";\n if (actions.has(\"replace\"))\n return actions.size === 1 ? \"replace\" : \"mixed\";\n if (actions.has(\"delete\"))\n return actions.size === 1 ? \"delete\" : \"mixed\";\n if (actions.has(\"create\"))\n return actions.size === 1 ? \"create\" : \"mixed\";\n if (actions.has(\"update\"))\n return actions.size === 1 ? \"update\" : \"mixed\";\n return \"noop\";\n};\n//# sourceMappingURL=NamespaceTree.js.map","import { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport { useMemo } from \"react\";\nimport { Box, Text } from \"ink\";\nimport { buildNamespaceTree, flattenTree, } from \"../../NamespaceTree.js\";\nexport function Plan({ plan }) {\n const items = useMemo(() => [\n ...Object.values(plan.resources),\n ...Object.values(plan.deletions),\n ], [plan]);\n const taskItems = useMemo(() => [\n ...Object.values(plan.actions ?? {}),\n ...Object.values(plan.actionDeletions ?? {}),\n ].filter((t) => t !== undefined), [plan]);\n const flatItems = useMemo(() => {\n const tree = buildNamespaceTree(items, taskItems);\n return flattenTree(tree);\n }, [items, taskItems]);\n if (items.length === 0 && taskItems.length === 0) {\n return _jsx(Text, { color: \"gray\", children: \"No changes planned\" });\n }\n const counts = items.reduce((acc, item) => (acc[item.action]++, acc), {\n create: 0,\n update: 0,\n delete: 0,\n noop: 0,\n replace: 0,\n });\n const taskCounts = taskItems.reduce((acc, item) => (acc[item.action]++, acc), { run: 0, noop: 0, delete: 0 });\n const actions = [\"create\", \"update\", \"delete\", \"replace\"].filter((action) => counts[action] > 0);\n const taskHeaderEntries = [\n taskCounts.run > 0 ? `${taskCounts.run} to run` : undefined,\n taskCounts.delete > 0 ? `${taskCounts.delete} to drop` : undefined,\n ].filter((s) => !!s);\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsxs(Box, { marginTop: 1, children: [_jsx(Text, { underline: true, children: \"Plan\" }), _jsx(Text, { children: \": \" }), [\n ...actions.map((action) => {\n const count = counts[action];\n const color = actionColor(action);\n return (_jsx(Box, { children: _jsxs(Text, { color: color, children: [count, \" to \", action] }) }, action));\n }),\n ...taskHeaderEntries.map((label, i) => (_jsx(Box, { children: _jsx(Text, { color: \"cyan\", children: label }) }, `task-${i}`))),\n ].flatMap((box, i, arr) => i === arr.length - 1\n ? [box]\n : [box, _jsx(Text, { children: \" | \" }, `sep-${i}`)])] }), _jsx(Box, { flexDirection: \"column\", marginTop: 1, children: flatItems.map((item) => {\n const indent = \" \".repeat(item.depth);\n const color = getActionColor(item.action);\n const icon = getActionIcon(item.action);\n const key = item.path.join(\"/\");\n if (item.type === \"namespace\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { color: \"blueBright\", children: item.id })] }, key));\n }\n if (item.type === \"binding\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { color: \"cyan\", children: item.bindingSid })] }, key));\n }\n if (item.type === \"action\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Box, { children: _jsx(Text, { bold: true, children: item.id }) }), _jsx(Box, { marginLeft: 1, children: _jsxs(Text, { color: \"blackBright\", children: [\"(\", item.actionType, \")\"] }) }), _jsx(Box, { marginLeft: 1, children: _jsx(Text, { color: \"cyan\", children: \"[action]\" }) })] }, key));\n }\n // Resource item\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Box, { children: _jsx(Text, { bold: true, children: item.id }) }), _jsx(Box, { marginLeft: 1, children: _jsxs(Text, { color: \"blackBright\", children: [\"(\", item.resourceType, \")\"] }) }), item.bindingCount !== undefined && item.bindingCount > 0 && (_jsx(Box, { marginLeft: 1, children: _jsxs(Text, { color: \"cyan\", children: [\"(\", item.bindingCount, \" bindings)\"] }) }))] }, key));\n }) })] }));\n}\nconst getActionColor = (action) => ({\n noop: \"gray\",\n create: \"green\",\n update: \"yellow\",\n delete: \"red\",\n replace: \"magenta\",\n mixed: \"cyan\",\n run: \"cyan\",\n})[action] ?? \"gray\";\nconst getActionIcon = (action) => ({\n create: \"+\",\n update: \"~\",\n delete: \"-\",\n noop: \"•\",\n replace: \"!\",\n mixed: \"*\",\n run: \"λ\",\n})[action] ?? \"?\";\nconst actionColor = (action) => getActionColor(action);\n//# sourceMappingURL=Plan.js.map","import { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport { useState } from \"react\";\nimport { Box, Text, useApp, useInput } from \"ink\";\nimport { Plan } from \"./Plan.js\";\nexport function ApprovePlan(props) {\n const { plan, approve } = props;\n const [selected, setSelected] = useState(0);\n const { exit } = useApp();\n useInput((_input, key) => {\n if (key.leftArrow || key.rightArrow) {\n setSelected((prev) => (prev === 0 ? 1 : 0));\n }\n else if (key.return) {\n approve(selected === 0);\n exit();\n }\n });\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsx(Plan, { plan: plan }), _jsx(Box, { marginTop: 1, children: _jsx(Text, { children: \"Proceed?\" }) }), _jsxs(Box, { gap: 1, children: [_jsxs(Text, { color: selected === 0 ? \"green\" : \"gray\", children: [selected === 0 ? \"◉\" : \"○\", \" Yes\"] }), _jsxs(Text, { color: selected === 1 ? \"red\" : \"gray\", children: [selected === 1 ? \"◉\" : \"○\", \" No\"] })] })] }));\n}\n//# sourceMappingURL=ApprovePlan.js.map","import { jsx as _jsx, jsxs as _jsxs } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport { useEffect, useMemo, useRef, useState } from \"react\";\nimport { Box, Text } from \"ink\";\nimport { buildNamespaceTree, flattenTree, } from \"../../NamespaceTree.js\";\nconst getTaskKey = (item) => item.path.join(\"/\");\nexport const buildProgressRows = (plan) => {\n const items = [\n ...Object.values(plan.resources),\n ...Object.values(plan.deletions).filter((item) => item !== undefined),\n ];\n const taskItems = [\n ...Object.values(plan.actions ?? {}),\n ...Object.values(plan.actionDeletions ?? {}),\n ].filter((t) => t !== undefined);\n const tree = buildNamespaceTree(items, taskItems);\n return flattenTree(tree)\n .filter((item) => item.type !== \"binding\")\n .map((item) => {\n if (item.type === \"namespace\") {\n return {\n key: getTaskKey(item),\n type: \"namespace\",\n id: item.id,\n depth: item.depth,\n action: item.action,\n };\n }\n if (item.type === \"action\") {\n return {\n key: getTaskKey(item),\n type: \"task\",\n id: item.id,\n depth: item.depth,\n actionType: item.actionType ?? \"unknown\",\n action: item.action,\n };\n }\n return {\n key: getTaskKey(item),\n type: \"resource\",\n id: item.id,\n depth: item.depth,\n resourceType: item.resourceType ?? \"unknown\",\n action: item.action,\n persistedApplyStatus: item.action === \"noop\"\n ? (() => {\n const crud = findCrudByLogicalId(plan, item.id);\n return crud?.action === \"noop\" ? crud.state.status : undefined;\n })()\n : undefined,\n };\n });\n};\nconst buildLogicalIdIndex = (rows) => {\n const index = new Map();\n for (const row of rows) {\n if (row.type !== \"resource\" && row.type !== \"task\")\n continue;\n const keys = index.get(row.id);\n if (keys) {\n keys.push(row.key);\n }\n else {\n index.set(row.id, [row.key]);\n }\n }\n return index;\n};\nexport function toPlanTask(rowOrId, planItem) {\n if (typeof rowOrId === \"string\") {\n return {\n key: rowOrId,\n id: rowOrId,\n type: planItem.resource.Type,\n status: planItem.action === \"noop\" ? planItem.state.status : \"pending\",\n updatedAt: Date.now(),\n };\n }\n return {\n key: rowOrId.key,\n id: rowOrId.id,\n type: rowOrId.resourceType,\n status: rowOrId.action === \"noop\"\n ? (rowOrId.persistedApplyStatus ?? \"created\")\n : \"pending\",\n updatedAt: Date.now(),\n };\n}\nconst buildInitialTasks = (rows) => new Map(rows.flatMap((row) => row.type === \"resource\"\n ? [[row.key, toPlanTask(row)]]\n : row.type === \"task\"\n ? [\n [\n row.key,\n {\n key: row.key,\n id: row.id,\n type: row.actionType,\n // `noop` tasks are skipped — render as gray `•` from the start\n // rather than briefly flashing the `ran` cyan styling.\n status: row.action === \"noop\"\n ? \"skipped\"\n : \"pending\",\n updatedAt: Date.now(),\n },\n ],\n ]\n : []));\nexport function PlanProgress(props) {\n const { source, plan } = props;\n const spinner = useGlobalSpinner();\n const rows = useMemo(() => buildProgressRows(plan), [plan]);\n const logicalIdIndex = useMemo(() => buildLogicalIdIndex(rows), [rows]);\n const [tasks, setTasks] = useState(() => buildInitialTasks(rows));\n const unsubscribeRef = useRef(null);\n useEffect(() => {\n unsubscribeRef.current?.();\n unsubscribeRef.current = source.subscribe((event) => {\n setTasks((prev) => {\n const next = new Map(prev);\n const keys = logicalIdIndex.get(event.id) ?? [];\n if (event.kind === \"status-change\") {\n if (!event.bindingId) {\n for (const key of keys) {\n const current = next.get(key);\n next.set(key, {\n key,\n id: event.id,\n type: event.type,\n status: event.status,\n message: event.message ?? current?.message,\n updatedAt: Date.now(),\n });\n }\n }\n }\n else {\n for (const key of keys) {\n const current = next.get(key);\n if (!current)\n continue;\n next.set(key, {\n ...current,\n message: event.message,\n updatedAt: Date.now(),\n });\n }\n }\n return next;\n });\n });\n return () => {\n unsubscribeRef.current?.();\n unsubscribeRef.current = null;\n };\n }, [logicalIdIndex, source]);\n useEffect(() => {\n setTasks(buildInitialTasks(rows));\n }, [rows]);\n return (_jsx(Box, { flexDirection: \"column\", children: rows.map((row) => {\n const indent = \" \".repeat(row.depth);\n if (row.type === \"namespace\") {\n return (_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsx(Text, { color: \"blueBright\", children: \"\\u21B3 \" }) }), _jsx(Text, { color: \"blueBright\", children: row.id })] }, row.key));\n }\n if (row.type === \"task\") {\n const t = tasks.get(row.key);\n const status = t?.status ?? (row.action === \"noop\" ? \"ran\" : \"pending\");\n const color = statusColor(status);\n const icon = taskIcon(row.action, status, spinner);\n const label = row.action === \"delete\"\n ? status === \"deleted\"\n ? \"deleted\"\n : \"drop\"\n : status === \"ran\"\n ? row.action === \"noop\"\n ? \"skip\"\n : \"ran\"\n : status === \"running\"\n ? \"running\"\n : status === \"fail\"\n ? \"fail\"\n : row.action === \"noop\"\n ? \"skip\"\n : \"run\";\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { bold: true, children: row.id }), _jsxs(Text, { dimColor: true, children: [\" (\", row.actionType, \")\"] }), _jsxs(Text, { color: color, children: [\" \", label] }), _jsxs(Text, { color: \"cyan\", dimColor: true, children: [\" \", \"[action]\"] })] }), t?.message ? (_jsx(Box, { paddingLeft: row.depth * 2 + 2, children: _jsxs(Text, { dimColor: true, children: [\"\\u2022 \", t.message] }) })) : null] }, row.key));\n }\n const task = tasks.get(row.key) ?? toPlanTask(row);\n const displayStatus = getDisplayStatus(row, task.status);\n const color = statusColor(displayStatus);\n const icon = statusIcon(task.status, spinner);\n return (_jsxs(Box, { flexDirection: \"column\", children: [_jsxs(Box, { flexDirection: \"row\", children: [_jsx(Text, { children: indent }), _jsx(Box, { width: 2, children: _jsxs(Text, { color: color, children: [icon, \" \"] }) }), _jsx(Text, { bold: true, children: task.id }), _jsxs(Text, { dimColor: true, children: [\" (\", task.type, \")\"] }), _jsxs(Text, { color: color, children: [\" \", displayStatus] })] }), task.message ? (_jsx(Box, { paddingLeft: row.depth * 2 + 2, children: _jsxs(Text, { dimColor: true, children: [\"\\u2022 \", task.message] }) })) : null] }, row.key));\n }) }));\n}\nfunction getDisplayStatus(row, status) {\n if (row.action === \"noop\" && (status === \"created\" || status === \"updated\")) {\n return \"no change\";\n }\n return status;\n}\nfunction statusColor(status) {\n switch (status) {\n case \"no change\":\n return \"gray\";\n case \"pending\":\n return \"gray\";\n case \"creating\":\n case \"created\":\n return \"green\";\n case \"updating\":\n case \"updated\":\n return \"yellow\";\n case \"deleting\":\n case \"deleted\":\n return \"red\";\n case \"running\":\n case \"ran\":\n return \"cyan\";\n case \"skipped\":\n return \"gray\";\n case \"fail\":\n return \"redBright\";\n default:\n return undefined;\n }\n}\nfunction taskIcon(action, status, spinnerChar) {\n if (status === \"running\")\n return spinnerChar;\n if (status === \"fail\")\n return \"✗\";\n if (status === \"skipped\")\n return \"•\";\n if (status === \"ran\")\n return action === \"noop\" ? \"•\" : \"✓\";\n if (status === \"deleted\")\n return \"✓\";\n if (action === \"delete\")\n return \"-\";\n if (action === \"noop\")\n return \"•\";\n return \"λ\";\n}\nfunction statusIcon(status, spinnerChar) {\n if (isInProgress(status))\n return spinnerChar;\n if (status === \"fail\")\n return \"✗\";\n return \"✓\"; // created/updated/deleted/replaced/etc.\n}\nfunction isInProgress(status) {\n return (status === \"pending\" ||\n status === \"creating\" ||\n status === \"updating\" ||\n status === \"deleting\" ||\n status === \"running\");\n}\nconst spinnerFrames = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"];\nfunction useGlobalSpinner(intervalMs = 80) {\n const [index, setIndex] = useState(0);\n useEffect(() => {\n const timer = setInterval(() => {\n setIndex((i) => (i + 1) % spinnerFrames.length);\n }, intervalMs);\n return () => clearInterval(timer);\n }, [intervalMs]);\n return spinnerFrames[index];\n}\nconst findCrudByLogicalId = (plan, logicalId) => {\n for (const node of Object.values(plan.resources)) {\n if (node.resource.LogicalId === logicalId) {\n return node;\n }\n }\n for (const node of Object.values(plan.deletions)) {\n if (node?.resource.LogicalId === logicalId) {\n return node;\n }\n }\n return undefined;\n};\n//# sourceMappingURL=PlanProgress.js.map","import { jsx as _jsx } from \"react/jsx-runtime\";\n/** @jsxImportSource react */\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport { render } from \"ink\";\nimport { Cli } from \"../Cli.js\";\nimport { ApprovePlan } from \"./components/ApprovePlan.js\";\nimport { Plan as PlanComponent } from \"./components/Plan.js\";\nimport { PlanProgress } from \"./components/PlanProgress.js\";\nexport const inkCLI = () => Layer.succeed(Cli, Cli.of({\n approvePlan,\n displayPlan,\n startApplySession,\n}));\nconst approvePlan = Effect.fn(function* (plan) {\n let approved = false;\n const { waitUntilExit } = render(_jsx(ApprovePlan, { plan: plan, approve: (a) => (approved = a) }));\n yield* Effect.promise(waitUntilExit);\n return approved;\n});\nconst displayPlan = (plan) => Effect.sync(() => {\n const { unmount } = render(_jsx(PlanComponent, { plan: plan }));\n unmount();\n});\nconst startApplySession = Effect.fn(function* (plan) {\n const listeners = new Set();\n const { unmount } = render(_jsx(PlanProgress, { plan: plan, source: {\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n } }));\n return {\n done: Effect.fn(function* () {\n yield* Effect.sleep(10); // give the react event loop time to re-render\n yield* Effect.sync(() => unmount());\n }),\n emit: (event) => Effect.sync(() => {\n for (const listener of listeners)\n listener(event);\n }),\n };\n});\n//# sourceMappingURL=InkCLI.js.map","import * as Layer from \"effect/Layer\";\nimport { LoggingCli } from \"./LoggingCli.js\";\nimport { inkCLI } from \"./tui/InkCLI.js\";\n/**\n * Returns true when the current process looks like it's being driven by a\n * coding agent, CI runner, or anything else that won't render an interactive\n * TUI well. The Ink renderer repaints the screen on every event, which floods\n * agent transcripts with redundant frames; LoggingCli emits one line per\n * status change instead.\n */\nexport const isNonInteractive = () => {\n const env = process.env;\n if (env.ALCHEMY_PLAIN === \"1\" || env.ALCHEMY_NO_TUI === \"1\")\n return true;\n if (env.ALCHEMY_TUI === \"1\")\n return false;\n if (!process.stdout.isTTY)\n return true;\n if (env.CI)\n return true;\n // Known coding-agent env vars. These are best-effort — the isTTY check\n // above already catches most cases since agents typically pipe stdout.\n if (env.CLAUDECODE ||\n env.CLAUDE_CODE_ENTRYPOINT ||\n env.CURSOR_AGENT ||\n env.AIDER_MODEL ||\n env.CODEX_CLI)\n return true;\n return false;\n};\nexport const selectCli = () => isNonInteractive() ? LoggingCli : inkCLI();\n//# sourceMappingURL=selectCli.js.map","import * as ConfigProvider from \"effect/ConfigProvider\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Schema from \"effect/Schema\";\nimport * as FetchHttpClient from \"effect/unstable/http/FetchHttpClient\";\nimport { AlchemyContextLive } from \"../AlchemyContext.js\";\nimport { CredentialsStoreLive } from \"../Auth/Credentials.js\";\nimport { ProfileLive } from \"../Auth/Profile.js\";\nimport * as RpcProviderProxy from \"../Local/RpcProviderProxy.js\";\nimport { PlatformServices } from \"../Util/PlatformServices.js\";\nimport { execStack, ExecStackOptions } from \"./commands/deploy.js\";\nimport { selectCli } from \"./selectCli.js\";\nconst services = Layer.merge(selectCli(), RpcProviderProxy.fromEnv()).pipe(Layer.provideMerge(Layer.mergeAll(AlchemyContextLive, ProfileLive, CredentialsStoreLive)), Layer.provideMerge(Layer.mergeAll(PlatformServices, FetchHttpClient.layer, ConfigProvider.layer(ConfigProvider.fromEnv()))));\nexport const exec = () => execStack(Schema.decodeSync(ExecStackOptions)(JSON.parse(process.env.ALCHEMY_EXEC_OPTIONS))).pipe(Effect.provide(services), Effect.scoped);\n//# sourceMappingURL=exec.js.map","import { exec } from \"alchemy/Cli\";\nimport { runMain } from \"alchemy/Util/PlatformServices\";\n\nexec().pipe(runMain);\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAa,iBAAb,cAAoC,cAAc,SAAS,CAAC,kBAAkB,CAAC;AAE/E,MAAa,qBAAqB,MAAM,OAAO,gBAAgB,OAAO,IAAI,aAAa;CACnF,MAA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