@alchemy.run/test 0.0.0 → 2.0.0-beta.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/LICENSE +201 -0
  2. package/bin/alchemy-test.ts +2 -0
  3. package/lib/Alchemy.d.ts +77 -0
  4. package/lib/Alchemy.d.ts.map +1 -0
  5. package/lib/Alchemy.js +195 -0
  6. package/lib/Alchemy.js.map +1 -0
  7. package/lib/Api.d.ts +135 -0
  8. package/lib/Api.d.ts.map +1 -0
  9. package/lib/Api.js +245 -0
  10. package/lib/Api.js.map +1 -0
  11. package/lib/Bun.d.ts +66 -0
  12. package/lib/Bun.d.ts.map +1 -0
  13. package/lib/Bun.js +142 -0
  14. package/lib/Bun.js.map +1 -0
  15. package/lib/Capture.d.ts +10 -0
  16. package/lib/Capture.d.ts.map +1 -0
  17. package/lib/Capture.js +68 -0
  18. package/lib/Capture.js.map +1 -0
  19. package/lib/Core.d.ts +301 -0
  20. package/lib/Core.d.ts.map +1 -0
  21. package/lib/Core.js +442 -0
  22. package/lib/Core.js.map +1 -0
  23. package/lib/DevCli.d.ts +47 -0
  24. package/lib/DevCli.d.ts.map +1 -0
  25. package/lib/DevCli.js +181 -0
  26. package/lib/DevCli.js.map +1 -0
  27. package/lib/Expect.d.ts +84 -0
  28. package/lib/Expect.d.ts.map +1 -0
  29. package/lib/Expect.js +518 -0
  30. package/lib/Expect.js.map +1 -0
  31. package/lib/FileLog.d.ts +27 -0
  32. package/lib/FileLog.d.ts.map +1 -0
  33. package/lib/FileLog.js +136 -0
  34. package/lib/FileLog.js.map +1 -0
  35. package/lib/Http.d.ts +109 -0
  36. package/lib/Http.d.ts.map +1 -0
  37. package/lib/Http.js +123 -0
  38. package/lib/Http.js.map +1 -0
  39. package/lib/Model.d.ts +111 -0
  40. package/lib/Model.d.ts.map +1 -0
  41. package/lib/Model.js +59 -0
  42. package/lib/Model.js.map +1 -0
  43. package/lib/PlainReporter.d.ts +18 -0
  44. package/lib/PlainReporter.d.ts.map +1 -0
  45. package/lib/PlainReporter.js +274 -0
  46. package/lib/PlainReporter.js.map +1 -0
  47. package/lib/Plan.d.ts +19 -0
  48. package/lib/Plan.d.ts.map +1 -0
  49. package/lib/Plan.js +32 -0
  50. package/lib/Plan.js.map +1 -0
  51. package/lib/Registry.d.ts +34 -0
  52. package/lib/Registry.d.ts.map +1 -0
  53. package/lib/Registry.js +80 -0
  54. package/lib/Registry.js.map +1 -0
  55. package/lib/Reporter.d.ts +160 -0
  56. package/lib/Reporter.d.ts.map +1 -0
  57. package/lib/Reporter.js +9 -0
  58. package/lib/Reporter.js.map +1 -0
  59. package/lib/Runner.d.ts +51 -0
  60. package/lib/Runner.d.ts.map +1 -0
  61. package/lib/Runner.js +1075 -0
  62. package/lib/Runner.js.map +1 -0
  63. package/lib/StrayOutput.d.ts +8 -0
  64. package/lib/StrayOutput.d.ts.map +1 -0
  65. package/lib/StrayOutput.js +259 -0
  66. package/lib/StrayOutput.js.map +1 -0
  67. package/lib/Tags.d.ts +17 -0
  68. package/lib/Tags.d.ts.map +1 -0
  69. package/lib/Tags.js +84 -0
  70. package/lib/Tags.js.map +1 -0
  71. package/lib/TestState.d.ts +12 -0
  72. package/lib/TestState.d.ts.map +1 -0
  73. package/lib/TestState.js +15 -0
  74. package/lib/TestState.js.map +1 -0
  75. package/lib/Tui.d.ts +4 -0
  76. package/lib/Tui.d.ts.map +1 -0
  77. package/lib/Tui.js +1137 -0
  78. package/lib/Tui.js.map +1 -0
  79. package/lib/Vitest.d.ts +58 -0
  80. package/lib/Vitest.d.ts.map +1 -0
  81. package/lib/Vitest.js +131 -0
  82. package/lib/Vitest.js.map +1 -0
  83. package/lib/WorktreeStage.d.ts +17 -0
  84. package/lib/WorktreeStage.d.ts.map +1 -0
  85. package/lib/WorktreeStage.js +48 -0
  86. package/lib/WorktreeStage.js.map +1 -0
  87. package/lib/cli.d.ts +2 -0
  88. package/lib/cli.d.ts.map +1 -0
  89. package/lib/cli.js +222 -0
  90. package/lib/cli.js.map +1 -0
  91. package/lib/index.d.ts +14 -0
  92. package/lib/index.d.ts.map +1 -0
  93. package/lib/index.js +12 -0
  94. package/lib/index.js.map +1 -0
  95. package/package.json +73 -3
  96. package/src/Alchemy.ts +337 -0
  97. package/src/Api.ts +522 -0
  98. package/src/Bun.ts +254 -0
  99. package/src/Capture.ts +72 -0
  100. package/src/Core.ts +906 -0
  101. package/src/DevCli.ts +229 -0
  102. package/src/Expect.ts +763 -0
  103. package/src/FileLog.ts +158 -0
  104. package/src/Http.ts +201 -0
  105. package/src/Model.ts +178 -0
  106. package/src/PlainReporter.ts +338 -0
  107. package/src/Plan.ts +45 -0
  108. package/src/Registry.ts +101 -0
  109. package/src/Reporter.ts +171 -0
  110. package/src/Runner.ts +1361 -0
  111. package/src/StrayOutput.ts +283 -0
  112. package/src/Tags.ts +100 -0
  113. package/src/TestState.ts +35 -0
  114. package/src/Tui.ts +1272 -0
  115. package/src/Vitest.ts +238 -0
  116. package/src/WorktreeStage.ts +45 -0
  117. package/src/cli.ts +330 -0
  118. package/src/index.ts +58 -0
  119. package/README.md +0 -9
package/src/Core.ts ADDED
@@ -0,0 +1,906 @@
1
+ import { stripVTControlCharacters } from "node:util";
2
+ import { AdoptPolicy } from "alchemy/AdoptPolicy";
3
+ import { AlchemyContext, AlchemyContextLive } from "alchemy/AlchemyContext";
4
+ import { ArtifactStore, provideFreshArtifactStore } from "alchemy/Artifacts";
5
+ import { AuthProviders } from "alchemy/Auth/AuthProvider";
6
+ import { CredentialsStoreLive } from "alchemy/Auth/Credentials";
7
+ import { ProfileStoreLive } from "alchemy/Auth/Profile";
8
+ import { withProfileOverride } from "alchemy/Auth/Resolve";
9
+ import { userStage } from "alchemy/Cli/commands/flags";
10
+ import { LoggingCli } from "alchemy/Cli/LoggingCli";
11
+ import * as Contributions from "alchemy/Contributions";
12
+ import * as AlchemyDeploy from "alchemy/Deploy";
13
+ import * as AlchemyDestroy from "alchemy/Destroy";
14
+ import type { Input } from "alchemy/Input";
15
+ import * as Interaction from "alchemy/Interaction";
16
+ import * as RpcProviderProxy from "alchemy/Local/RpcProviderProxy";
17
+ import * as RpcSpawner from "alchemy/Local/RpcSpawner";
18
+ import { ALCHEMY_DEV } from "alchemy/Phase";
19
+ import * as Plan from "alchemy/Plan";
20
+ import type { ResourceSelection, SelectionOutput } from "alchemy/ResourceSelection";
21
+ import {
22
+ type CompiledStack,
23
+ make as makeStack,
24
+ Stack,
25
+ type StackDefinition,
26
+ type StackEffect,
27
+ type StackServices,
28
+ } from "alchemy/Stack";
29
+ import { Stage } from "alchemy/Stage";
30
+ import * as State from "alchemy/State";
31
+ import { TelemetryLive } from "alchemy/Telemetry/Layer";
32
+ import { loadConfigProvider, StackConfigOverrides } from "alchemy/Util/ConfigProvider";
33
+ import { kindOf, recordOf } from "alchemy/Util/LogRecord";
34
+ import { PlatformServices } from "alchemy/Util/PlatformServices";
35
+ import * as Config from "effect/Config";
36
+ import { ConfigProvider } from "effect/ConfigProvider";
37
+ import * as Context from "effect/Context";
38
+ import * as Effect from "effect/Effect";
39
+ import * as Exit from "effect/Exit";
40
+ import * as FetchHttpClient from "effect/http/FetchHttpClient";
41
+ import * as HttpClient from "effect/http/HttpClient";
42
+ import * as Layer from "effect/Layer";
43
+ import * as Logger from "effect/Logger";
44
+ import * as Option from "effect/Option";
45
+ import * as Scope from "effect/Scope";
46
+ import type { Limit } from "./Model.ts";
47
+
48
+ /**
49
+ * Configuration shared by every test in a file. Pass to `Test.make(...)`.
50
+ */
51
+ export interface MakeOptions<ROut = any> {
52
+ /** Provider layer for the stack — e.g. `AWS.providers()`, `Cloudflare.providers()`. */
53
+ providers: Layer.Layer<ROut, never, StackServices>;
54
+ /** State store for top-level `deploy(Stack)` / `destroy(Stack)`; defaults to {@link State.localState}. */
55
+ state?: Layer.Layer<State.State, never, StackServices>;
56
+ /** Override the current profile; otherwise resolved from env or the built-in `default`. */
57
+ profile?: string;
58
+ /**
59
+ * A counted lock every test and `beforeAll`/`afterAll` hook of this file
60
+ * holds, on top of its own `exclusive`. Files that pass the same label
61
+ * share its permits, so a suite caps its load on a rate-limited cloud API
62
+ * in one place while every test stays independently schedulable.
63
+ */
64
+ limit?: Limit;
65
+ /**
66
+ * Default stage for deploy/destroy. Defaults to `test_$USER` (or
67
+ * `test_$USERNAME` on Windows, `test_unknown` if neither is set) so two
68
+ * people running the same suite against one account don't collide.
69
+ * Does **not** read `$ALCHEMY_STAGE` — that is the CLI deploy/dev stage.
70
+ */
71
+ stage?: string;
72
+ /**
73
+ * Engine-level adoption policy for this test run. When `true`, resources
74
+ * without prior state will be adopted from the cloud via `provider.read`
75
+ * (matching the CLI's `--adopt` flag). Defaults to `false`.
76
+ */
77
+ adopt?: boolean;
78
+ /**
79
+ * Run providers in local-dev mode (matching the CLI's `alchemy dev` flag).
80
+ * When `true`, resources like Cloudflare Workers run locally via workerd
81
+ * instead of being deployed to the cloud. When omitted, falls back to the
82
+ * `ALCHEMY_DEV` environment variable (`"1"` / `"true"` enable it).
83
+ *
84
+ * {@link ALCHEMY_TEST_DEV} (`ALCHEMY_TEST_DEV=1`) overrides this — use it
85
+ * to force an entire existing live suite through local providers without
86
+ * editing each `Test.make({ dev: true })`.
87
+ */
88
+ dev?: boolean;
89
+ /**
90
+ * Run local providers behind the RPC sidecar proxy, matching the process
91
+ * topology of the real `alchemy dev` command: an {@link RpcProviderProxy}
92
+ * is installed, so `RpcProvider.providerServicesEffect` layers (e.g.
93
+ * Cloudflare's `localRuntimeServices()`) are EMPTY in the test process and
94
+ * RPC-backed providers run their lifecycle in a spawned sidecar process.
95
+ *
96
+ * Defaults to the resolved `dev` flag — dev tests run the real `alchemy
97
+ * dev` topology unless they opt out. In-process dev (`sidecar: false`)
98
+ * masks missing main-process lifecycle dependencies (the class of bug
99
+ * behind #1007, where D1's local migrations only failed under `alchemy
100
+ * dev`); it remains available because it IS still a real production path —
101
+ * a plain `alchemy deploy` deleting a `providerMode: "local"` state row
102
+ * runs the local provider in-process — and because in-process runs are
103
+ * easier to debug.
104
+ *
105
+ * Fully lazy: only the proxy facade is installed up front. The spawner
106
+ * HTTP server starts — and a sidecar child process is forked — on the
107
+ * first provider session request (a deploy/destroy building an RPC-backed
108
+ * local provider); a dev file that never does starts no processes at all.
109
+ * Once started, the sidecar lives for the whole test file (its own scope,
110
+ * closed by the adapter's final cleanup hook), so `beforeAll(deploy(Stack))`
111
+ * + per-test requests work the same way they do under a real `alchemy dev`
112
+ * session.
113
+ *
114
+ * Pass an object to run the sidecar with options: `omitEnv` lists prefixes
115
+ * of environment variables the sidecar must not inherit (e.g.
116
+ * `["CLOUDFLARE_"]` to exercise credential-free dev while the shell
117
+ * exports credentials).
118
+ */
119
+ sidecar?: boolean | SidecarOptions;
120
+ /**
121
+ * Directory for Alchemy's runtime data (logs, local state) for every
122
+ * deploy in the file, sidecar included — the `.alchemy` the CLI uses.
123
+ * Set it to put `.alchemy` somewhere a test controls, e.g. inside a
124
+ * container build context. Defaults to `.alchemy` under the cwd.
125
+ */
126
+ dotAlchemy?: string;
127
+ }
128
+
129
+ /** Options for the dev sidecar process — see {@link MakeOptions.sidecar}. */
130
+ export interface SidecarOptions {
131
+ /** Prefixes of environment variables withheld from the sidecar. */
132
+ readonly omitEnv?: ReadonlyArray<string>;
133
+ }
134
+
135
+ /**
136
+ * The RPC sidecar topology used by the real `alchemy dev` command, in one
137
+ * process-local layer: an {@link RpcSpawner} HTTP server that forks sidecar
138
+ * processes on demand, and an {@link RpcProviderProxy} pointed at it.
139
+ */
140
+ export const sidecarProxy = (options: { profile?: string; omitEnv?: ReadonlyArray<string> }) =>
141
+ Layer.unwrap(
142
+ Effect.map(RpcSpawner.RpcSpawner, (spawner) => RpcProviderProxy.layer(spawner.url)),
143
+ ).pipe(
144
+ Layer.provideMerge(
145
+ RpcSpawner.layerServer({
146
+ profile: options.profile ?? process.env.ALCHEMY_PROFILE,
147
+ envFile: undefined,
148
+ omitEnv: options.omitEnv,
149
+ }),
150
+ ),
151
+ );
152
+
153
+ /**
154
+ * Force every `Test.make` into (or out of) local-dev mode, regardless of
155
+ * the file's `dev` option. Unset leaves the option / `ALCHEMY_DEV` fallback
156
+ * in place. Accepts the usual truthy/falsey strings (`true`/`1`/`yes`/`on`,
157
+ * `false`/`0`/`no`/`off`).
158
+ */
159
+ export const ALCHEMY_TEST_DEV = Config.Boolean("ALCHEMY_TEST_DEV").pipe(Config.option);
160
+
161
+ /** The `ALCHEMY_TEST_DEV` override, if the env var is set. */
162
+ export const alchemyTestDevOverride = (): Option.Option<boolean> =>
163
+ Effect.runSync(ALCHEMY_TEST_DEV);
164
+
165
+ /** Resolve the effective `dev` flag: `ALCHEMY_TEST_DEV`, then options, then `ALCHEMY_DEV`. */
166
+ export const resolveDev = (options: { dev?: boolean }): boolean => {
167
+ const override = alchemyTestDevOverride();
168
+ if (Option.isSome(override)) return override.value;
169
+ if (options.dev !== undefined) return options.dev;
170
+ return Effect.runSync(ALCHEMY_DEV);
171
+ };
172
+
173
+ /** Resolve the effective `sidecar` flag: defaults to the resolved `dev` flag. */
174
+ export const resolveSidecar = (options: MakeOptions): boolean =>
175
+ options.sidecar === undefined ? resolveDev(options) : options.sidecar !== false;
176
+
177
+ /** The sidecar's withheld env prefixes, sorted so equal sets share a key. */
178
+ const sidecarOmitEnv = (options: MakeOptions): ReadonlyArray<string> =>
179
+ typeof options.sidecar === "object" ? [...(options.sidecar.omitEnv ?? [])].sort() : [];
180
+
181
+ /**
182
+ * Default test stage: `ALCHEMY_TEST_STAGE`, then `test_$USER` (or
183
+ * `test_$USERNAME` / `test_unknown`). The runner sets ALCHEMY_TEST_STAGE to
184
+ * `test_$USER_<worktree>` in a linked git worktree, so concurrent worktrees
185
+ * sharing a cloud account stay isolated.
186
+ * Matches the CLI's `live_$USER` / `dev_$USER` per-developer isolation.
187
+ */
188
+ export const defaultStage = (): string =>
189
+ process.env.ALCHEMY_TEST_STAGE || Effect.runSync(userStage("test"));
190
+
191
+ /** File-level stage: a string override, otherwise {@link defaultStage}. */
192
+ export const resolveStage = (options: { stage?: string }): string =>
193
+ // Configured stacks carry a cross-stack reference proxy, not a stage override.
194
+ typeof options.stage === "string" ? options.stage : defaultStage();
195
+
196
+ /**
197
+ * The sidecar runtime handed to each adapter's `make(...)`.
198
+ *
199
+ * `provide` installs a lazy {@link RpcProviderProxy} facade into an effect.
200
+ * Installing the facade is free: the spawner HTTP server only starts (and,
201
+ * downstream of it, a sidecar child process is only forked) when a provider
202
+ * actually requests a session — i.e. when a deploy/destroy builds an
203
+ * RPC-backed local provider. A dev file that never does starts nothing.
204
+ *
205
+ * The spawner (and the sidecar children it forks) is a PROCESS-WIDE
206
+ * SINGLETON shared by every test file, refcounted per handle: all files run
207
+ * in one bun process, and a per-file sidecar means a per-file bun child that
208
+ * imports the entire alchemy + distilled module graph — dozens of concurrent
209
+ * files at hundreds of MB each OOMs the machine. Stack isolation is
210
+ * preserved because each RPC session carries its own stack environment (see
211
+ * `SESSION_ENV_PARAM` in Local/RpcServerEnvironment.ts) and the child builds
212
+ * a provider context per stack. The singleton's scope closes when the LAST
213
+ * handle closes; `Test.make` runs at collection time (before any test), so
214
+ * the refcount cannot dip to zero while later files still need it. Adapters
215
+ * run `close` from the same final cleanup hook that closes the shared scope.
216
+ */
217
+ export interface SidecarHandle {
218
+ readonly provide: <A, E, R>(eff: Effect.Effect<A, E, R>) => Effect.Effect<A, any, any>;
219
+ readonly close: Effect.Effect<void>;
220
+ }
221
+
222
+ interface SidecarSingleton {
223
+ readonly real: ReturnType<typeof sidecarProxy>;
224
+ readonly memoMap: Layer.MemoMap;
225
+ readonly scope: Scope.Closeable;
226
+ proxy?: RpcProviderProxy.RpcProviderProxy["Service"];
227
+ refs: number;
228
+ }
229
+
230
+ const sidecarSingletons = new Map<string, SidecarSingleton>();
231
+
232
+ /** Payload-free counts; observing them never starts the singleton. */
233
+ export const sidecarDiagnostics = Effect.gen(function* () {
234
+ const instances = [...sidecarSingletons.values()];
235
+ const counts = { sessions: 0, testSessions: 0, owners: 0, connections: 0 };
236
+ for (const instance of instances) {
237
+ if (instance.proxy === undefined) continue;
238
+ const current = yield* instance.proxy.diagnostics;
239
+ counts.sessions += current.sessions;
240
+ counts.testSessions += current.testSessions;
241
+ counts.owners += current.owners;
242
+ counts.connections += current.connections;
243
+ }
244
+ return {
245
+ singletons: instances.length,
246
+ reservations: instances.reduce((sum, instance) => sum + instance.refs, 0),
247
+ started: instances.filter((instance) => instance.proxy !== undefined).length,
248
+ ...counts,
249
+ };
250
+ });
251
+
252
+ export const makeSidecarHandle = <ROut = any>(
253
+ options: MakeOptions<ROut>,
254
+ ): SidecarHandle | undefined => {
255
+ if (!resolveSidecar(options)) return undefined;
256
+ const profile = options.profile ?? process.env.ALCHEMY_PROFILE ?? "";
257
+ const omitEnv = sidecarOmitEnv(options);
258
+ // Files only share a sidecar when it was started with the same environment.
259
+ const key = JSON.stringify([profile, omitEnv]);
260
+ let singleton = sidecarSingletons.get(key);
261
+ if (singleton === undefined) {
262
+ singleton = {
263
+ real: sidecarProxy({ profile: options.profile, omitEnv }),
264
+ memoMap: Layer.makeMemoMapUnsafe(),
265
+ scope: Scope.makeUnsafe("sequential"),
266
+ refs: 0,
267
+ };
268
+ sidecarSingletons.set(key, singleton);
269
+ }
270
+ singleton.refs += 1;
271
+ let runtime:
272
+ | {
273
+ instance: SidecarSingleton;
274
+ owner: RpcProviderProxy.SessionOwner;
275
+ contexts: Set<{ ambient?: Context.Context<any> }>;
276
+ }
277
+ | undefined = {
278
+ instance: singleton,
279
+ owner: RpcProviderProxy.makeSessionOwner(),
280
+ contexts: new Set(),
281
+ };
282
+ const lazy = Layer.effect(
283
+ RpcProviderProxy.RpcProviderProxy,
284
+ Effect.gen(function* () {
285
+ if (runtime === undefined) {
286
+ return yield* Effect.die("Test sidecar handle is closed");
287
+ }
288
+ // Never pin the singleton to a file's scope, artifacts, or layer builds.
289
+ const context = {
290
+ ambient: Context.omit(
291
+ Scope.Scope,
292
+ ArtifactStore,
293
+ Layer.CurrentMemoMap,
294
+ )(yield* Effect.context<never>()) as Context.Context<any> | undefined,
295
+ };
296
+ if (runtime === undefined) {
297
+ return yield* Effect.die("Test sidecar handle is closed");
298
+ }
299
+ runtime.contexts.add(context);
300
+ return RpcProviderProxy.RpcProviderProxy.of({
301
+ diagnostics: Effect.suspend(
302
+ () =>
303
+ runtime?.instance.proxy?.diagnostics ??
304
+ Effect.succeed({
305
+ sessions: 0,
306
+ testSessions: 0,
307
+ owners: 0,
308
+ connections: 0,
309
+ }),
310
+ ),
311
+ serverDiagnostics: Effect.suspend(
312
+ () => runtime?.instance.proxy?.serverDiagnostics ?? Effect.succeed(undefined),
313
+ ),
314
+ get: Effect.fn(function* (providersUrl, providerName) {
315
+ if (runtime === undefined) {
316
+ return yield* Effect.die("Test sidecar handle is closed");
317
+ }
318
+ const { instance, owner } = runtime;
319
+ let proxy = instance.proxy;
320
+ if (proxy === undefined) {
321
+ const built = yield* Layer.buildWithMemoMap(
322
+ instance.real,
323
+ instance.memoMap,
324
+ instance.scope,
325
+ ).pipe(
326
+ Effect.provideContext(context.ambient!),
327
+ Scope.provide(instance.scope),
328
+ Effect.orDie,
329
+ );
330
+ proxy = Context.get(built, RpcProviderProxy.RpcProviderProxy);
331
+ instance.proxy = proxy;
332
+ }
333
+ context.ambient = undefined;
334
+ runtime?.contexts.delete(context);
335
+ // A handle may have closed while the singleton was building.
336
+ return yield* proxy.get(providersUrl, providerName, owner);
337
+ }),
338
+ });
339
+ }),
340
+ );
341
+ return {
342
+ provide: (eff) => Effect.provide(eff, lazy),
343
+ close: Effect.suspend(() => {
344
+ if (runtime === undefined) return Effect.void;
345
+ const { instance, owner, contexts } = runtime;
346
+ runtime = undefined;
347
+ for (const context of contexts) context.ambient = undefined;
348
+ contexts.clear();
349
+ return RpcProviderProxy.closeSessionOwner(owner).pipe(
350
+ Effect.ensuring(
351
+ Effect.suspend(() => {
352
+ instance.refs -= 1;
353
+ if (instance.refs > 0) return Effect.void;
354
+ if (sidecarSingletons.get(key) === instance) sidecarSingletons.delete(key);
355
+ instance.proxy = undefined;
356
+ return Scope.close(instance.scope, Exit.void);
357
+ }),
358
+ ),
359
+ );
360
+ }).pipe(Effect.uninterruptible, Effect.ignore),
361
+ };
362
+ };
363
+
364
+ const overrideAlchemyContext = (overrides: { dev: boolean; dotAlchemy?: string }) =>
365
+ Layer.effect(
366
+ AlchemyContext,
367
+ AlchemyContext.pipe(
368
+ Effect.map((ctx) => ({
369
+ ...ctx,
370
+ dev: overrides.dev,
371
+ dotAlchemy: overrides.dotAlchemy ?? ctx.dotAlchemy,
372
+ })),
373
+ ),
374
+ );
375
+
376
+ export type TestEffect<A, Req = never> = StackEffect<A, any, Req>;
377
+
378
+ const testDev = Option.getOrElse(alchemyTestDevOverride(), () => false);
379
+
380
+ /**
381
+ * Every provider's test services (e.g. AWS's Floci emulator), applied under
382
+ * {@link ALCHEMY_TEST_DEV} only.
383
+ */
384
+ const testServices: ReadonlyArray<Contributions.TestServices> = testDev
385
+ ? await Effect.runPromise(
386
+ Contributions.load().pipe(
387
+ Effect.flatMap((providers) =>
388
+ Effect.forEach(providers, (provider) =>
389
+ provider.testServices
390
+ ? Contributions.resolve(provider, "testServices", provider.testServices)
391
+ : Effect.succeed(undefined),
392
+ ),
393
+ ),
394
+ Effect.map((services) => services.filter((service) => service !== undefined)),
395
+ Effect.provide(PlatformServices),
396
+ ),
397
+ )
398
+ : [];
399
+
400
+ if (testDev) {
401
+ // Emulators rewrite WebSocket invoke URLs onto their self-signed gateway;
402
+ // Bun/Node would otherwise reject the upgrade. Scoped to ALCHEMY_TEST_DEV
403
+ // only.
404
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
405
+ // Set here — before the RPC spawner or any vite child forks — so the whole
406
+ // dev process tree inherits it.
407
+ for (const services of testServices) {
408
+ for (const [key, value] of Object.entries(services.env ?? {})) process.env[key] ??= value;
409
+ }
410
+ }
411
+
412
+ /** The test services' layers, closest wins over the stack's own. */
413
+ const testServicesLayer =
414
+ testServices.length === 0
415
+ ? undefined
416
+ : testServices
417
+ .map((services) => services.layer)
418
+ .reduce((merged, layer) => Layer.merge(merged, layer));
419
+
420
+ /**
421
+ * The stack's state store under the emulator: a store that reads the cloud
422
+ * environment (an AWS S3 store) gets the test services too, so its bucket
423
+ * lives in the emulator alongside the stack's resources instead of needing
424
+ * live credentials.
425
+ */
426
+ const testStateLayer = <E, R>(state: Layer.Layer<State.State, E, R>) =>
427
+ testServicesLayer === undefined
428
+ ? state
429
+ : // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- the layer overrides services the store would otherwise resolve itself
430
+ (state.pipe(Layer.provide(testServicesLayer)) as Layer.Layer<State.State, E, R>);
431
+
432
+ const provideTestServices = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
433
+ // Test services override services already present in R.
434
+ testServicesLayer === undefined
435
+ ? effect
436
+ : // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- the layer overrides services already present in R
437
+ (Effect.provide(effect, testServicesLayer) as Effect.Effect<A, E, R>);
438
+
439
+ const testHttp = Layer.effect(
440
+ HttpClient.HttpClient,
441
+ Effect.map(HttpClient.HttpClient, (client) =>
442
+ testServices.reduce(
443
+ (mapped, services) =>
444
+ services.mapRequest ? HttpClient.mapRequest(mapped, services.mapRequest) : mapped,
445
+ client,
446
+ ),
447
+ ),
448
+ ).pipe(Layer.provide(FetchHttpClient.layer));
449
+
450
+ const platformLayer = () =>
451
+ Layer.mergeAll(
452
+ PlatformServices,
453
+ testDev ? testHttp : FetchHttpClient.layer,
454
+ Layer.provide(ProfileStoreLive, PlatformServices),
455
+ Layer.provide(CredentialsStoreLive, PlatformServices),
456
+ );
457
+
458
+ const alchemyLayer = Layer.mergeAll(
459
+ LoggingCli,
460
+ Interaction.layerNonInteractive(),
461
+ AlchemyContextLive,
462
+ );
463
+
464
+ /** Most lines one capture keeps; older ones are dropped first. */
465
+ const RESOURCE_LOG_LIMIT = 5_000;
466
+
467
+ /** The open {@link captureResourceLog} buffers, by resource fqn. */
468
+ const resourceCaptures = new Map<string, Set<Array<string>>>();
469
+
470
+ /**
471
+ * Copies each record tagged with a captured resource (`fqn`) into its open
472
+ * captures. Installed beside the runner's loggers, so it also sees the shared
473
+ * sidecar's records, which the spawner logs in whichever file started the
474
+ * sidecar rather than in the test that deployed the resource.
475
+ */
476
+ const resourceRecorder = Logger.make<unknown, void>((options) => {
477
+ if (resourceCaptures.size === 0) return;
478
+ const record = recordOf(options);
479
+ const fqn = record.attributes.fqn;
480
+ const captures = typeof fqn === "string" ? resourceCaptures.get(fqn) : undefined;
481
+ if (captures === undefined || (record.kind !== "log" && record.kind !== "output")) return;
482
+ const line = stripVTControlCharacters(
483
+ record.kind === "log" ? record.data.message : record.data.text,
484
+ );
485
+ for (const lines of captures) {
486
+ lines.push(line);
487
+ if (lines.length > RESOURCE_LOG_LIMIT) lines.splice(0, lines.length - RESOURCE_LOG_LIMIT);
488
+ }
489
+ });
490
+
491
+ /**
492
+ * Start capturing what the resource `fqn` logs — its processes' output (a dev
493
+ * Worker's console, a Vite dev server) and alchemy's lines about it — whether
494
+ * its provider runs in the dev sidecar or in-process. Start it before the
495
+ * deploy; the returned effect reads every line since, without ANSI styling.
496
+ * The capture ends with the enclosing scope.
497
+ */
498
+ export const captureResourceLog = (
499
+ fqn: string,
500
+ ): Effect.Effect<Effect.Effect<string>, never, Scope.Scope> =>
501
+ Effect.acquireRelease(
502
+ Effect.sync(() => {
503
+ const lines: Array<string> = [];
504
+ let captures = resourceCaptures.get(fqn);
505
+ if (captures === undefined) resourceCaptures.set(fqn, (captures = new Set()));
506
+ captures.add(lines);
507
+ return lines;
508
+ }),
509
+ (lines) =>
510
+ Effect.sync(() => {
511
+ const captures = resourceCaptures.get(fqn);
512
+ captures?.delete(lines);
513
+ if (captures?.size === 0) resourceCaptures.delete(fqn);
514
+ }),
515
+ ).pipe(Effect.map((lines) => Effect.sync(() => lines.join("\n"))));
516
+
517
+ /**
518
+ * The runner's loggers, minus typed event records: deploys draw their
519
+ * progress through `AlchemyDeploy.applyAndRender` (the `LoggingCli` lines), so printing each
520
+ * event object too would only repeat it. `onEvent` subscribers installed
521
+ * inside still see every event. Adds the {@link resourceRecorder}.
522
+ */
523
+ const withoutEventRecords = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
524
+ Effect.flatMap(Logger.CurrentLoggers, (loggers) =>
525
+ effect.pipe(
526
+ Effect.provideService(
527
+ Logger.CurrentLoggers,
528
+ new Set([
529
+ ...[...loggers]
530
+ .filter((logger) => logger !== resourceRecorder)
531
+ .map((logger) =>
532
+ Logger.make<unknown, void>((options) => {
533
+ if (kindOf(options) !== "event") logger.log(options);
534
+ }),
535
+ ),
536
+ resourceRecorder,
537
+ ]),
538
+ ),
539
+ ),
540
+ );
541
+
542
+ /**
543
+ * Build the per-test runtime and return a self-contained Effect.
544
+ *
545
+ * Mirrors {@link "../bin/alchemy.js"} composition: ConfigProvider via
546
+ * `loadConfigProvider` + `withProfileOverride`, an empty `AuthProviders`
547
+ * registry that the user's `providers` layer populates, the platform layers,
548
+ * and the configured state store. Adapters wrap this into runner-specific
549
+ * thunks (`bun.test` -> `runPromise`, `it.live` -> as-is).
550
+ *
551
+ * When `scope` is provided, scoped resources (like the Cloudflare dev
552
+ * sidecar) survive past this effect and are tied to the lifetime of the
553
+ * provided scope instead. The runner is responsible for closing it.
554
+ *
555
+ * When `scope` is omitted, the effect runs with `Effect.scoped` and any
556
+ * scoped resources are torn down as soon as it resolves.
557
+ */
558
+ export const toEffect = <A, ROut = any>(
559
+ effect: TestEffect<A>,
560
+ options: MakeOptions<ROut>,
561
+ scope?: Scope.Scope,
562
+ sidecar?: SidecarHandle,
563
+ ): Effect.Effect<A, any, never> => {
564
+ const base = Effect.gen(function* () {
565
+ const cfg = yield* loadConfigProvider(Option.none());
566
+ const configProvider = withProfileOverride(cfg, options.profile);
567
+ // `ALCHEMY_TEST_DEV=1` forces local providers AND points the test
568
+ // process's distilled AWS clients at the emulator. Otherwise
569
+ // out-of-band `describeTable` / `getFunction` calls still hit the
570
+ // live account and fail with ResourceNotFound. Existing
571
+ // `Test.make({ dev: true })` files are unchanged (mixed
572
+ // `Alchemy.remote()` suites keep their live SDK).
573
+ const body = sidecar ? sidecar.provide(effect) : effect;
574
+ const locally = testDev ? provideTestServices(body) : body;
575
+ return yield* locally.pipe(
576
+ withoutEventRecords,
577
+ provideFreshArtifactStore,
578
+ Effect.provideService(ConfigProvider, configProvider),
579
+ Effect.provideService(StackConfigOverrides, { profile: options.profile }),
580
+ );
581
+ }).pipe(
582
+ Effect.provideService(AdoptPolicy, options.adopt ?? false),
583
+ Effect.provide(
584
+ overrideAlchemyContext({ dev: resolveDev(options), dotAlchemy: options.dotAlchemy }),
585
+ ),
586
+ // `options.state` (e.g. `Cloudflare.state()`) itself requires
587
+ // `AuthProviders` to read credentials, so AuthProviders must be provided
588
+ // AFTER the state layer or the state layer's requirement is never
589
+ // satisfied — which surfaces as `Service not found: AuthProviders`.
590
+ Effect.provide(testStateLayer(options.state ?? State.localState())),
591
+ Effect.provideService(AuthProviders, {}),
592
+ Effect.provide(Layer.provideMerge(alchemyLayer, platformLayer())),
593
+ );
594
+
595
+ return (scope === undefined ? Effect.scoped(base) : Scope.provide(base, scope)) as Effect.Effect<
596
+ A,
597
+ any,
598
+ never
599
+ >;
600
+ };
601
+
602
+ /** Promise wrapper around {@link toEffect} for `bun.test`-style runners. */
603
+ export const run = <A, ROut = any>(
604
+ effect: TestEffect<A>,
605
+ options: MakeOptions<ROut>,
606
+ scope?: Scope.Scope,
607
+ sidecar?: SidecarHandle,
608
+ ): Promise<A> => Effect.runPromise(toEffect(effect, options, scope, sidecar));
609
+
610
+ /**
611
+ * Wrap an effect so it runs with `options.providers` + a placeholder Stack +
612
+ * Stage in scope. Used by `test.provider` so user code can call provider SDK
613
+ * APIs (e.g. `DynamoDB.describeTable`) directly inside the test body.
614
+ */
615
+ export const withProviders = <A, E, R, ROut>(
616
+ effect: Effect.Effect<A, E, R>,
617
+ options: MakeOptions<ROut>,
618
+ stackName: string,
619
+ ): Effect.Effect<A, E, Exclude<R, ROut | Stack | Stage>> => {
620
+ // Closest wins: when `ALCHEMY_TEST_DEV=1`, pin the test body's
621
+ // distilled AWS clients to the emulator BEFORE `options.providers`
622
+ // (which still carries the live `AWSEnvironment`).
623
+ const body = testDev ? provideTestServices(effect) : effect;
624
+ const stage = resolveStage(options);
625
+ // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- providers layer is typed `any`; requirements are satisfied by it
626
+ return body.pipe(
627
+ Effect.provide(
628
+ (options.providers as Layer.Layer<any, never, any>).pipe(
629
+ Layer.provideMerge(
630
+ Layer.succeed(Stack, {
631
+ name: stackName,
632
+ stage,
633
+ resources: {},
634
+ bindings: {},
635
+ actions: {},
636
+ }),
637
+ ),
638
+ Layer.provideMerge(Layer.succeed(Stage, stage)),
639
+ ),
640
+ ),
641
+ ) as Effect.Effect<A, E, Exclude<R, ROut | Stack | Stage>>;
642
+ };
643
+
644
+ /**
645
+ * Curried `deploy` for the test factory: bakes in the configured stage and
646
+ * adds the telemetry layer the CLI uses, so `beforeAll(deploy(Stack))` works
647
+ * the same way as `alchemy deploy`.
648
+ *
649
+ * `scope`, when supplied, is forwarded down so the dev sidecar (and other
650
+ * scoped resources) lives until the caller closes it instead of dying as
651
+ * soon as `deploy` resolves. The test harness uses this to keep workerd
652
+ * alive across `beforeAll` → tests → `afterAll`.
653
+ */
654
+ export interface DeployCallOptions extends Plan.MakePlanOptions {
655
+ stage?: string;
656
+ scope?: Scope.Scope;
657
+ }
658
+
659
+ export type DeployResult<A> = Effect.Effect<
660
+ Input.Resolve<A>,
661
+ Effect.Error<ReturnType<typeof deployStack<A>>>,
662
+ Effect.Services<ReturnType<typeof deployStack<A>>>
663
+ >;
664
+
665
+ export interface FilteredDeployCallOptions
666
+ extends Omit<DeployCallOptions, keyof ResourceSelection>, ResourceSelection {}
667
+
668
+ type FullDeployCall = [options?: DeployCallOptions];
669
+
670
+ /**
671
+ * Filtered deploys return void; the whole declaration still evaluates.
672
+ * With an explicit output type, filtering also requires the Call tuple type.
673
+ */
674
+ export interface Deploy {
675
+ <A, Call extends [options?: FilteredDeployCallOptions] = FullDeployCall>(
676
+ stack: TestEffect<CompiledStack<A>, Stage | AlchemyContext>,
677
+ ...call: Call
678
+ ): DeployResult<SelectionOutput<A, Call[0]>>;
679
+ }
680
+
681
+ export function deploy<A, Call extends [options?: FilteredDeployCallOptions] = FullDeployCall>(
682
+ options: MakeOptions,
683
+ stack: TestEffect<CompiledStack<A>, Stage | AlchemyContext>,
684
+ ...call: Call
685
+ ): DeployResult<SelectionOutput<A, Call[0]>>;
686
+ export function deploy<A>(
687
+ options: MakeOptions,
688
+ stack: TestEffect<CompiledStack<A>, Stage | AlchemyContext>,
689
+ callOptions?: FilteredDeployCallOptions,
690
+ ) {
691
+ return deployStack(options, stack, callOptions);
692
+ }
693
+
694
+ const deployStack = <A>(
695
+ options: MakeOptions,
696
+ stack: TestEffect<CompiledStack<A>, Stage | AlchemyContext>,
697
+ callOptions?: FilteredDeployCallOptions,
698
+ ) =>
699
+ AlchemyDeploy.deploy({
700
+ stack: stack as Effect.Effect<CompiledStack<A>, never, any>,
701
+ stage: callOptions?.stage ?? resolveStage(options),
702
+ dev: resolveDev(options),
703
+ scope: callOptions?.scope,
704
+ force: callOptions?.force,
705
+ include: callOptions?.include,
706
+ exclude: callOptions?.exclude,
707
+ }).pipe(Effect.provide(TelemetryLive));
708
+
709
+ /** Bind test-file options and the shared runtime scope without erasing output types. */
710
+ export const makeDeploy = (options: MakeOptions, scope: Scope.Scope): Deploy => {
711
+ function run<A, Call extends [options?: FilteredDeployCallOptions] = FullDeployCall>(
712
+ stack: TestEffect<CompiledStack<A>, Stage | AlchemyContext>,
713
+ ...call: Call
714
+ ): DeployResult<SelectionOutput<A, Call[0]>>;
715
+ function run<A>(
716
+ stack: TestEffect<CompiledStack<A>, Stage | AlchemyContext>,
717
+ callOptions?: FilteredDeployCallOptions,
718
+ ) {
719
+ return deployStack(options, stack, { ...callOptions, scope });
720
+ }
721
+ return run;
722
+ };
723
+
724
+ export const destroy = <ROut>(
725
+ options: MakeOptions,
726
+ stack: StackDefinition<ROut>,
727
+ callOptions?: { stage?: string; scope?: Scope.Scope; include?: never; exclude?: never },
728
+ ) =>
729
+ AlchemyDestroy.destroy({
730
+ include: callOptions?.include,
731
+ exclude: callOptions?.exclude,
732
+ stack,
733
+ stage: callOptions?.stage ?? resolveStage(options),
734
+ dev: resolveDev(options),
735
+ scope: callOptions?.scope,
736
+ }).pipe(Effect.provide(TelemetryLive));
737
+
738
+ /**
739
+ * In-test scratch stack handed to `test.provider(name, (stack) => ...)`.
740
+ *
741
+ * Each scratch stack owns a private state store that is shared between
742
+ * successive `deploy`/`destroy` calls AND visible to the user's test body
743
+ * (so `yield* State` / `state.get(...)` see the same store the deploys
744
+ * mutated). This makes create / update / replace / delete paths exercisable
745
+ * without polluting other tests in the same file.
746
+ *
747
+ * When the adapter can name the test file (the alchemy-test runner), the
748
+ * store is DURABLE — rows live under `.alchemy/state/{file}-{test}/{stage}`
749
+ * on disk. Durability is what makes an interrupted destroy recoverable: the
750
+ * engine persists a `deleting` row before every `provider.delete` and only
751
+ * drops it on success, so a run killed mid-delete (e.g. the runner's
752
+ * teardown-abandonment after a test timeout) leaves resumable rows that the
753
+ * NEXT run's leading `stack.destroy()` (or the `Effect.ensuring` teardown)
754
+ * picks up and drains. An in-memory scratch dies with the process, silently
755
+ * orphaning every cloud resource whose delete was still in flight.
756
+ */
757
+ export interface ScratchStack<ROut = any> {
758
+ readonly name: string;
759
+ /** Stage this scratch deploys to ({@link resolveStage} of the file options). */
760
+ readonly stage: string;
761
+ /** The shared in-memory state Layer for this scratch. @internal */
762
+ readonly state: Layer.Layer<State.State, never, never>;
763
+ /** Filters leave other rows and stack outputs untouched; declaration still runs. */
764
+ deploy<A, E, R, Call extends [options?: Plan.FilteredPlanOptions] = []>(
765
+ effect: Effect.Effect<A, E, R>,
766
+ ...call: Call
767
+ ): Effect.Effect<
768
+ SelectionOutput<Input.Resolve<A>, Call[0]>,
769
+ any,
770
+ Exclude<R, ROut | StackServices>
771
+ >;
772
+ /**
773
+ * Build a plan against the scratch's shared state WITHOUT applying it.
774
+ *
775
+ * Use this to assert on the planned action for a resource (e.g. that a
776
+ * downstream dependency stays `noop` when only an upstream resource
777
+ * changes) without mutating the cloud. Plans run against whatever state
778
+ * prior `deploy(...)` calls persisted.
779
+ */
780
+ plan<A, E, R, Call extends [options?: Plan.FilteredPlanOptions] = []>(
781
+ effect: Effect.Effect<A, E, R>,
782
+ ...call: Call
783
+ ): Effect.Effect<Plan.Plan<SelectionOutput<A, Call[0]>>, any, Exclude<R, ROut | StackServices>>;
784
+ destroy(options?: { include?: never; exclude?: never }): Effect.Effect<void, any, never>;
785
+ }
786
+
787
+ const sanitizeStackName = (name: string) =>
788
+ name.replaceAll(/[^a-zA-Z0-9_]/g, "-").replace(/-+/g, "-");
789
+
790
+ /**
791
+ * Turn a test-file path (relative to the run root) into a stack-name
792
+ * namespace: `test/AWS/Website/Router.test.ts` -> `AWS/Website/Router`.
793
+ * Test names repeat across files (e.g. "create and delete bucket with
794
+ * default props"), so the durable per-test store MUST be namespaced by file
795
+ * or two concurrently-running same-named tests would read, write and — far
796
+ * worse — destroy each other's rows.
797
+ */
798
+ const scratchNamespace = (file: string) =>
799
+ file.replace(/^test[/\\]/, "").replace(/\.test\.ts$/, "");
800
+
801
+ /**
802
+ * Build a fresh `ScratchStack` for `test.provider`.
803
+ *
804
+ * With `file` (the registration-time test file, supplied by the
805
+ * alchemy-test adapter): the store is the durable `.alchemy/state` local
806
+ * store and the stack name is namespaced by file so interrupted destroys
807
+ * leave resumable rows for the next run (see {@link ScratchStack}).
808
+ *
809
+ * Without `file` (bun/vitest adapters, which cannot name their file at
810
+ * registration time): falls back to a private in-memory store — isolated,
811
+ * but discarded with the process.
812
+ */
813
+ export const scratchStack = <ROut>(
814
+ options: MakeOptions<ROut>,
815
+ name: string,
816
+ file?: string,
817
+ ): ScratchStack<ROut> => {
818
+ const stage = resolveStage(options);
819
+ const stackName = sanitizeStackName(
820
+ file === undefined ? name : `${scratchNamespace(file)}-${name}`,
821
+ );
822
+ const stateLayer: Layer.Layer<State.State> =
823
+ file === undefined
824
+ ? Layer.succeed(State.State, State.InMemoryService({}))
825
+ : Layer.provide(State.localState(), PlatformServices);
826
+
827
+ // `withProviders` already pins the test body to the test services, but the
828
+ // stack program and its later plan/apply phase run under the providers'
829
+ // live services. Pin both phases separately: Actions execute during apply,
830
+ // after the stack program has finished. This override must be inside
831
+ // `compiled.services` so Effect's closest-layer precedence selects the test
832
+ // services for Action data-plane calls.
833
+ const pinToTestServices = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
834
+ testDev ? provideTestServices(effect) : effect;
835
+
836
+ // TODO(unify stack builds): build scratch stacks through `Alchemist.plan` /
837
+ // `Alchemist.apply` instead of `makeStack` and the hand-built destroy layers
838
+ // below (which skip the stack's secrets and auth providers); see the TODO in
839
+ // `alchemy/src/EvalStack.ts`.
840
+ const buildAndApply = (
841
+ effect: Effect.Effect<any, any, any>,
842
+ planOptions?: Plan.FilteredPlanOptions,
843
+ ) =>
844
+ (pinToTestServices(effect) as Effect.Effect<any, any, never>).pipe(
845
+ makeStack({ name: stackName, providers: options.providers, state: stateLayer } as any) as any,
846
+ Effect.flatMap((compiled: any) =>
847
+ Plan.make(compiled, planOptions ?? {}).pipe(
848
+ Effect.flatMap(AlchemyDeploy.applyAndRender),
849
+ pinToTestServices,
850
+ Effect.provide(compiled.services),
851
+ ),
852
+ ),
853
+ Effect.provideService(Stage, stage),
854
+ provideFreshArtifactStore,
855
+ );
856
+
857
+ const buildPlan = (
858
+ effect: Effect.Effect<any, any, any>,
859
+ planOptions?: Plan.FilteredPlanOptions,
860
+ ) =>
861
+ (pinToTestServices(effect) as Effect.Effect<any, any, never>).pipe(
862
+ makeStack({ name: stackName, providers: options.providers, state: stateLayer } as any) as any,
863
+ Effect.flatMap((compiled: any) =>
864
+ pinToTestServices(Plan.make(compiled, planOptions ?? {})).pipe(
865
+ Effect.provide(compiled.services),
866
+ ),
867
+ ),
868
+ Effect.provideService(Stage, stage),
869
+ provideFreshArtifactStore,
870
+ );
871
+
872
+ return {
873
+ name: stackName,
874
+ stage,
875
+ state: stateLayer,
876
+ deploy: ((effect: Effect.Effect<any, any, any>, planOptions?: Plan.FilteredPlanOptions) =>
877
+ buildAndApply(effect, planOptions)) as ScratchStack<ROut>["deploy"],
878
+ plan: ((effect: Effect.Effect<any, any, any>, planOptions?: Plan.FilteredPlanOptions) =>
879
+ buildPlan(effect, planOptions)) as ScratchStack<ROut>["plan"],
880
+ destroy: (callOptions) =>
881
+ callOptions?.include !== undefined || callOptions?.exclude !== undefined
882
+ ? Effect.die(
883
+ new Plan.InvalidResourceSelection({ message: "Filtered destroy is not supported." }),
884
+ )
885
+ : (Plan.destroy({ name: stackName, stage }).pipe(
886
+ Effect.flatMap(AlchemyDeploy.applyAndRender),
887
+ Effect.asVoid,
888
+ Effect.provide(
889
+ stateLayer.pipe(
890
+ Layer.provideMerge(options.providers as Layer.Layer<any, never, any>),
891
+ Layer.provideMerge(
892
+ Layer.succeed(Stack, {
893
+ name: stackName,
894
+ stage,
895
+ resources: {},
896
+ bindings: {},
897
+ actions: {},
898
+ }),
899
+ ),
900
+ Layer.provideMerge(Layer.succeed(Stage, stage)),
901
+ ),
902
+ ),
903
+ provideFreshArtifactStore,
904
+ ) as Effect.Effect<void, any, never>),
905
+ };
906
+ };