@systemfsoftware/alchemy-stack-layer 0.0.0-stage → 0.0.0

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/LICENSE ADDED
@@ -0,0 +1,203 @@
1
+ Copyright (c) 2026 Ryan Lee (systemfsoftware)
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright 2026 Ryan Lee (systemfsoftware)
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,93 @@
1
- # Temporary Holding Version
1
+ # @systemfsoftware/alchemy-stack-layer
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Deploy an [Alchemy](https://alchemy.run) stack as an [Effect](https://effect.website) layer, so a Gherkin Feature reads a deployed stack's outputs as a service.
4
+
5
+ `alchemyStack(name, config)` returns a service tag, distinct for each stack name, whose service is the stack's outputs. Its `layer` deploys the stack when acquired and destroys it when released, on `@alchemy.run/test`'s engine. You declare no service class and no output mapping:
6
+
7
+ ```ts
8
+ import { alchemyStack } from '@systemfsoftware/alchemy-stack-layer'
9
+ import { Gherkin, Given, it, makeFeature, Then } from '@systemfsoftware/effect-gherkin-spec'
10
+ import SignInStack from '../alchemy.run.ts'
11
+
12
+ const Feature = makeFeature({ it })
13
+
14
+ const SignIn = alchemyStack('SignIn', { deploy: SignInStack })
15
+
16
+ Feature('signing in')
17
+ .live('the sign-in worker answers over the network')
18
+ .withLayer(SignIn.layer)
19
+ .body(({ scenario }) => {
20
+ scenario(
21
+ 'the deployed worker has a URL',
22
+ Gherkin.Do.pipe(
23
+ Given('the sign-in stack')('stack', () => SignIn),
24
+ Then('it serves from a URL')((s, expect) => expect(s.stack.url.startsWith('https://')).toBe(true)),
25
+ ),
26
+ )
27
+ })
28
+ ```
29
+
30
+ Passed to `.withLayer`, the stack deploys once for the Feature. Passed through `sharedLayer` from `@systemfsoftware/effect-gherkin-spec`, it deploys once for the whole file, and every Feature in the file reads the same deployment:
31
+
32
+ ```ts
33
+ const Shared = sharedLayer(SignIn.layer)
34
+
35
+ Feature('signing in').withLayer(Shared).body() /* ... */
36
+ ```
37
+
38
+ A stack's deploy runs in the shared layer's setup, which has no time limit, so a slow deploy needs no `.live` or timeout of its own. Give stacks to `.withLayer`, not `.withScenarioLayer`: a scenario layer is built for every scenario, and every scenario would deploy. Scenarios that share one deployment must not depend on each other's writes to it.
39
+
40
+ ## Deploying more than one stack
41
+
42
+ `config.deploy` takes a stack definition with its own `providers` and `state`, as `Alchemy.Stack(name, { providers, state }, effect)` returns. It also takes a function that receives `deploy` and returns the outputs, for a setup that deploys several stacks or provisions a dependency first. A `setup` layer provides what that function needs:
43
+
44
+ ```ts
45
+ const Billing = alchemyStack('Billing', {
46
+ setup: PaymentsSandbox.layer,
47
+ deploy: (deploy) =>
48
+ Effect.gen(function*() {
49
+ const sandbox = yield* PaymentsSandbox
50
+ const api = yield* deploy(BillingApiStack)
51
+ const worker = yield* deploy(BillingWorkerStack)
52
+ return { api: api.url, worker: worker.url, sandbox: sandbox.id }
53
+ }),
54
+ })
55
+ ```
56
+
57
+ Stacks are destroyed in reverse deploy order. A stack is registered for destroy before its deploy starts, so a deploy that fails part-way still has what it created destroyed.
58
+
59
+ ## Dev or cloud
60
+
61
+ Dev mode, the sidecar and the stage resolve exactly as `@alchemy.run/test` resolves them, from one code path:
62
+
63
+ - **Dev:** `ALCHEMY_TEST_DEV`, then the config's `dev`, then `ALCHEMY_DEV`. A local run starts the dev sidecar and deploys to the local Workers runtime; `ALCHEMY_TEST_DEV=0` deploys the same file to the cloud.
64
+ - **Stage:** the config's `stage` is used as given. Without one, the stage is a non-empty `ALCHEMY_TEST_STAGE`; else, when the working directory is inside a linked git worktree, `test_$USER_<worktree>`, as `@alchemy.run/test`'s runner names it, so two worktrees running the same file at once never share a deployment; else the per-user test stage. It is followed by `_` and 8 hex digits of the SHA-256 of the test file's Vitest project name, root directory name and path from the root (see `fileStage` below). Two files that deploy the same stack never share a deployment either.
65
+ - **State:** where a deployment records its state is the stack definition's own `state`. A cloud run over local or in-memory state fails before it deploys, with `DurableStateRequired`: a cloud deployment recorded only on one machine cannot be found or destroyed from another.
66
+
67
+ The config's `dev`, `stage`, `sidecar` and `profile` are forwarded to the engine unchanged.
68
+
69
+ `fileStage({ baseStage, testFile })` is exported for scripts that need the stage a test file deploys under, such as a CI job that checks a stage is empty. `testFile` is effect-spec-runtime's `TestFileInfo`: the file's path from the Vitest root, the root directory's name, and the Vitest project name. The suffix is 8 hex digits of the SHA-256 of those three joined by NUL bytes, so a file keeps its stage across checkouts and machines, and two packages with the same test path get different stages. `fileStage` needs a `Digest` service, such as `Digest.layerWebCrypto` from `effect/crypto/Digest`.
70
+
71
+ ## Teardown
72
+
73
+ - Before deploying, the layer destroys any deployment left at the resolved stage, so a run killed before its teardown is cleaned up by the next run at that stage. If that destroy fails, acquiring fails with `StackDestroyFailed` and nothing new is deployed. Give each CI job slot a stage that repeats, and run one job at a time per stage.
74
+ - A failed destroy fails the run with `StackDestroyFailed`, naming the stack and the stage. It is never swallowed and never retried.
75
+ - A failed deploy fails with `StackDeployFailed`, naming the stack and the stage, after what it created has been destroyed.
76
+ - A stack built with no configured stage outside a running test file fails with `StageUnresolved`.
77
+
78
+ ## Checking against real Cloudflare
79
+
80
+ `test:cloud` runs a one-worker stack against a real Cloudflare account: it deploys, fetches the worker over HTTP, destroys it, and checks that the stage holds no state rows and the worker is gone. It needs `CLOUDFLARE_API_TOKEN`, `CLOUDFLARE_ACCOUNT_ID`, `ALCHEMY_TEST_DEV=0` and an `ALCHEMY_TEST_STAGE`:
81
+
82
+ ```bash
83
+ ALCHEMY_TEST_DEV=0 ALCHEMY_TEST_STAGE=<stage> pnpm --filter @systemfsoftware/alchemy-stack-layer test:cloud
84
+ ```
85
+
86
+ ## Install
87
+
88
+ ```bash
89
+ pnpm add -D @systemfsoftware/alchemy-stack-layer alchemy effect
90
+ ```
91
+
92
+ > [!NOTE]
93
+ > `alchemy` and `effect` are peer dependencies — you bring your own.
@@ -0,0 +1,81 @@
1
+ import * as Core from "@alchemy.run/test/Core";
2
+ import { TestFileInfo } from "@systemfsoftware/effect-spec-runtime";
3
+ import { Context, Effect, Layer, Scope } from "effect";
4
+ import * as Digest from "effect/crypto/Digest";
5
+ import * as Schema from "effect/Schema";
6
+ import { CompiledStack, StackDefinition } from "alchemy/Stack";
7
+ import { Input } from "alchemy/Input";
8
+ import { ConfigError } from "effect/Config";
9
+ declare const StackDeployFailed_base: Schema.Class<StackDeployFailed, Schema.TaggedStruct<"StackDeployFailed", {
10
+ readonly stack: Schema.String;
11
+ readonly stage: Schema.String;
12
+ readonly reason: Schema.String;
13
+ }>, import("effect/Cause").YieldableError & {
14
+ readonly brand: unique symbol;
15
+ }>;
16
+ export declare class StackDeployFailed extends StackDeployFailed_base {
17
+ get message(): string;
18
+ }
19
+ declare const StackDestroyFailed_base: Schema.Class<StackDestroyFailed, Schema.TaggedStruct<"StackDestroyFailed", {
20
+ readonly stack: Schema.String;
21
+ readonly stage: Schema.String;
22
+ readonly reason: Schema.String;
23
+ }>, import("effect/Cause").YieldableError & {
24
+ readonly brand: unique symbol;
25
+ }>;
26
+ export declare class StackDestroyFailed extends StackDestroyFailed_base {
27
+ get message(): string;
28
+ }
29
+ declare const DurableStateRequired_base: Schema.Class<DurableStateRequired, Schema.TaggedStruct<"DurableStateRequired", {
30
+ readonly stack: Schema.String;
31
+ readonly stage: Schema.String;
32
+ readonly store: Schema.String;
33
+ }>, import("effect/Cause").YieldableError & {
34
+ readonly brand: unique symbol;
35
+ }>;
36
+ export declare class DurableStateRequired extends DurableStateRequired_base {
37
+ get message(): string;
38
+ }
39
+ declare const StageUnresolved_base: Schema.Class<StageUnresolved, Schema.TaggedStruct<"StageUnresolved", {
40
+ readonly stack: Schema.String;
41
+ }>, import("effect/Cause").YieldableError & {
42
+ readonly brand: unique symbol;
43
+ }>;
44
+ export declare class StageUnresolved extends StageUnresolved_base {
45
+ get message(): string;
46
+ }
47
+ type StackProgram<A> = Effect.Effect<CompiledStack<A>, ConfigError> & StackDefinition<never> & Required<Pick<StackDefinition<never>, 'providers' | 'state'>>;
48
+ type Deploy = <A>(stack: StackProgram<A>) => Effect.Effect<Input.Resolve<A>, StackDeployFailed | StackDestroyFailed | DurableStateRequired>;
49
+ type StackKey<Name extends string> = `@systemfsoftware/alchemy-stack-layer/${Name}`;
50
+ interface AlchemyStack<Name extends string, Outputs> extends Context.ServiceClass.Shape<StackKey<Name>, Outputs> {}
51
+ interface EngineConfig {
52
+ readonly dev?: boolean;
53
+ readonly stage?: string;
54
+ readonly sidecar?: boolean | Core.SidecarOptions;
55
+ readonly profile?: string;
56
+ }
57
+ type StackSetup<Outputs, E, R> = (deploy: Deploy) => Effect.Effect<Outputs, E, R>;
58
+ interface StandaloneConfig<A, Outputs, E> extends EngineConfig {
59
+ readonly deploy: StackProgram<A> | StackSetup<Outputs, E, Scope.Scope>;
60
+ readonly setup?: undefined;
61
+ }
62
+ interface SetupLayerConfig<Outputs, E, R, ESetup> extends EngineConfig {
63
+ readonly deploy: StackSetup<Outputs, E, R | Scope.Scope>;
64
+ readonly setup: Layer.Layer<R, ESetup>;
65
+ }
66
+ type StackLayerError = StackDeployFailed | StackDestroyFailed | DurableStateRequired | StageUnresolved;
67
+ interface AlchemyStackTag<Name extends string, Outputs, E> extends Context.ServiceClass<AlchemyStack<Name, Outputs>, StackKey<Name>, Outputs> {
68
+ readonly layer: Layer.Layer<AlchemyStack<Name, Outputs>, E>;
69
+ }
70
+ export declare const alchemyStack: {
71
+ <A = never, Outputs = never, E = never>(config: StandaloneConfig<A, Outputs, E>): <const Name extends string>(name: Name) => AlchemyStackTag<Name, Input.Resolve<A> | Outputs, StackLayerError | E>;
72
+ <Outputs, E, R, ESetup>(config: SetupLayerConfig<Outputs, E, R, ESetup>): <const Name extends string>(name: Name) => AlchemyStackTag<Name, Outputs, StackLayerError | E | ESetup>;
73
+ <const Name extends string, A = never, Outputs = never, E = never>(name: Name, config: StandaloneConfig<A, Outputs, E>): AlchemyStackTag<Name, Input.Resolve<A> | Outputs, StackLayerError | E>;
74
+ <const Name extends string, Outputs, E, R, ESetup>(name: Name, config: SetupLayerConfig<Outputs, E, R, ESetup>): AlchemyStackTag<Name, Outputs, StackLayerError | E | ESetup>;
75
+ };
76
+ interface FileStageInput {
77
+ readonly baseStage: string;
78
+ readonly testFile: TestFileInfo;
79
+ }
80
+ export declare const fileStage: (input: FileStageInput) => Effect.Effect<string, never, Digest.Digest>;
81
+ export type { AlchemyStack, AlchemyStackTag, Deploy, EngineConfig, FileStageInput, SetupLayerConfig, StackKey, StackLayerError, StackProgram, StackSetup, StandaloneConfig };
package/dist/index.mjs ADDED
@@ -0,0 +1,177 @@
1
+ import * as Core from "@alchemy.run/test/Core";
2
+ import { worktreeStage } from "@alchemy.run/test/WorktreeStage";
3
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
4
+ import * as NodePath from "@effect/platform-node/NodePath";
5
+ import { TestFile } from "@systemfsoftware/effect-spec-runtime";
6
+ import { Cause, Config, Context, Effect, Exit, Layer, Option, Scope } from "effect";
7
+ import * as Digest from "effect/crypto/Digest";
8
+ import { dual } from "effect/Function";
9
+ import * as Schema from "effect/Schema";
10
+ import { evalStack } from "alchemy/EvalStack";
11
+ import { build } from "alchemy/Stack";
12
+ import * as State from "alchemy/State";
13
+ // src/StackErrors.schema.ts
14
+ var StackDeployFailed = class extends Schema.TaggedError()("StackDeployFailed", {
15
+ stack: Schema.String,
16
+ stage: Schema.String,
17
+ reason: Schema.String
18
+ }) {
19
+ get message() {
20
+ return `Deploying stack "${this.stack}" at stage "${this.stage}" failed: ${this.reason}`;
21
+ }
22
+ };
23
+ var StackDestroyFailed = class extends Schema.TaggedError()("StackDestroyFailed", {
24
+ stack: Schema.String,
25
+ stage: Schema.String,
26
+ reason: Schema.String
27
+ }) {
28
+ get message() {
29
+ return `Destroying stack "${this.stack}" at stage "${this.stage}" failed: ${this.reason}`;
30
+ }
31
+ };
32
+ var DurableStateRequired = class extends Schema.TaggedError()("DurableStateRequired", {
33
+ stack: Schema.String,
34
+ stage: Schema.String,
35
+ store: Schema.String
36
+ }) {
37
+ get message() {
38
+ return `Stack "${this.stack}" at stage "${this.stage}" deploys to the cloud, so durable state is required, but its state store is "${this.store}"`;
39
+ }
40
+ };
41
+ var StageUnresolved = class extends Schema.TaggedError()("StageUnresolved", { stack: Schema.String }) {
42
+ get message() {
43
+ return `Stack "${this.stack}" has no stage: give its config a stage, or build its layer inside a test file`;
44
+ }
45
+ };
46
+ // src/StackLifecycle.ts
47
+ const NON_DURABLE_STORES = Object.freeze(["local", "inmemory"]);
48
+ const engineEffect = Core.toEffect;
49
+ const inEngine = (call) => (effect) => Effect.catchCause(engineEffect(effect, call.engine.options, call.scope, call.engine.sidecar), (cause) => Effect.fail(call.onFailure(Cause.pretty(cause))));
50
+ const deployFailure = (engine, stack) => (reason) => new StackDeployFailed({
51
+ stack,
52
+ stage: engine.stage,
53
+ reason
54
+ });
55
+ const destroyFailure = (engine, stack) => (reason) => new StackDestroyFailed({
56
+ stack,
57
+ stage: engine.stage,
58
+ reason
59
+ });
60
+ const storeIdOf = (engine, stack) => {
61
+ const built = build({
62
+ name: stack.stackName,
63
+ state: stack.state,
64
+ providers: stack.providers
65
+ }).pipe(Effect.map((services) => ({ services })));
66
+ const call = {
67
+ engine,
68
+ scope: void 0,
69
+ onFailure: deployFailure(engine, stack.stackName)
70
+ };
71
+ return inEngine(call)(evalStack(built, ({ services }) => Effect.map(Context.get(services, State.State), (store) => store.id), {
72
+ stage: engine.stage,
73
+ dev: engine.dev
74
+ }));
75
+ };
76
+ const requireDurable = (engine, stack) => Effect.flatMap(storeIdOf(engine, stack), (store) => NON_DURABLE_STORES.includes(store) ? Effect.fail(new DurableStateRequired({
77
+ stack: stack.stackName,
78
+ stage: engine.stage,
79
+ store
80
+ })) : Effect.void);
81
+ const checkDurability = (engine, stack) => engine.dev ? Effect.void : requireDurable(engine, stack);
82
+ const destroyIn = (call, stack, child) => inEngine(call)(Core.destroy(call.engine.options, stack, {
83
+ stage: call.engine.stage,
84
+ scope: child
85
+ }));
86
+ const destroyThenClose = (destroy, child) => destroy.pipe(Effect.orDie, Effect.ensuring(Scope.close(child, Exit.void)));
87
+ const deployStack = (engine) => (stack) => Effect.gen(function* () {
88
+ yield* checkDurability(engine, stack);
89
+ const child = yield* Scope.fork(engine.scope, "sequential");
90
+ const destroy = destroyIn({
91
+ engine,
92
+ scope: child,
93
+ onFailure: destroyFailure(engine, stack.stackName)
94
+ }, stack, child);
95
+ yield* Scope.addFinalizer(engine.scope, destroyThenClose(destroy, child));
96
+ yield* destroy;
97
+ return yield* inEngine({
98
+ engine,
99
+ scope: child,
100
+ onFailure: deployFailure(engine, stack.stackName)
101
+ })(Core.deploy(engine.options, stack, {
102
+ stage: engine.stage,
103
+ scope: child
104
+ }));
105
+ });
106
+ const openSidecar = (scope) => (options) => Effect.suspend(() => {
107
+ const sidecar = Core.makeSidecarHandle(options);
108
+ if (sidecar === void 0) return Effect.succeed(sidecar);
109
+ return Scope.addFinalizer(scope, sidecar.close).pipe(Effect.as(sidecar));
110
+ });
111
+ // src/StageName.ts
112
+ const SUFFIX_LENGTH = 8;
113
+ const encoder = new TextEncoder();
114
+ const identityOf = (testFile) => [
115
+ testFile.projectName ?? "",
116
+ testFile.rootName,
117
+ testFile.name
118
+ ].join("\0");
119
+ const fileSuffix = (testFile) => Digest.Digest.use((digest) => digest.digestHex(Digest.sha256, encoder.encode(identityOf(testFile)))).pipe(Effect.map((hex) => hex.slice(0, SUFFIX_LENGTH)));
120
+ const fileStage = (input) => Effect.map(fileSuffix(input.testFile), (suffix) => `${input.baseStage}_${suffix}`);
121
+ // src/AlchemyStack.ts
122
+ var StackOwnProviders = class extends Context.Service()("@systemfsoftware/alchemy-stack-layer/StackOwnProviders") {};
123
+ const stackOwnProviders = Layer.succeed(StackOwnProviders, true);
124
+ const configuredTestStage = Config.option(Config.String("ALCHEMY_TEST_STAGE"));
125
+ const worktreeOrUserStage = Effect.gen(function* () {
126
+ const cwd = yield* Effect.sync(() => process.cwd());
127
+ return (yield* worktreeStage(cwd)) ?? Core.resolveStage({});
128
+ }).pipe(Effect.provide(Layer.merge(NodeFileSystem.layer, NodePath.layer)));
129
+ const checkoutStage = (name) => Effect.flatMap(configuredTestStage, (configured) => Option.match(Option.filter(configured, (stage) => stage !== ""), {
130
+ onNone: () => worktreeOrUserStage,
131
+ onSome: Effect.succeed
132
+ })).pipe(Effect.mapError(() => new StageUnresolved({ stack: name })));
133
+ const stageOfRunningFile = (name) => Effect.flatMap(TestFile, (file) => Option.match(file, {
134
+ onNone: () => Effect.fail(new StageUnresolved({ stack: name })),
135
+ onSome: (testFile) => Effect.flatMap(checkoutStage(name), (baseStage) => fileStage({
136
+ baseStage,
137
+ testFile
138
+ }).pipe(Effect.provide(Digest.layerWebCrypto)))
139
+ }));
140
+ const resolveStage = (name, configured) => configured === void 0 ? stageOfRunningFile(name) : Effect.succeed(configured);
141
+ const engineOptionsOf = (config) => {
142
+ const { stage: _stage, ...engine } = config;
143
+ return engine;
144
+ };
145
+ const makeEngine = (name, config) => Effect.gen(function* () {
146
+ const scope = yield* Effect.scope;
147
+ const stage = yield* resolveStage(name, config.stage);
148
+ const options = {
149
+ ...engineOptionsOf(config),
150
+ providers: stackOwnProviders,
151
+ stage
152
+ };
153
+ return {
154
+ options,
155
+ sidecar: yield* openSidecar(scope)(options),
156
+ stage,
157
+ dev: Core.resolveDev(config),
158
+ scope
159
+ };
160
+ });
161
+ const setupOf = (deploy) => {
162
+ if (typeof deploy === "function") return deploy;
163
+ return (run) => run(deploy);
164
+ };
165
+ const acquireOf = (name, config, setup) => Effect.flatMap(makeEngine(name, config), (engine) => setup(deployStack(engine)));
166
+ const keyOf = (name) => `@systemfsoftware/alchemy-stack-layer/${name}`;
167
+ const standaloneImpl = (name, config) => {
168
+ class Tag extends Context.Service()(keyOf(name)) {}
169
+ return Object.assign(Tag, { layer: Layer.effect(Tag, acquireOf(name, config, setupOf(config.deploy))) });
170
+ };
171
+ const withSetupImpl = (name, config) => {
172
+ class Tag extends Context.Service()(keyOf(name)) {}
173
+ return Object.assign(Tag, { layer: Layer.provide(Layer.effect(Tag, acquireOf(name, config, config.deploy)), config.setup) });
174
+ };
175
+ const alchemyStackImpl = (name, config) => config.setup === void 0 ? standaloneImpl(name, config) : withSetupImpl(name, config);
176
+ const alchemyStack = dual(2, alchemyStackImpl);
177
+ export { DurableStateRequired, StackDeployFailed, StackDestroyFailed, StageUnresolved, alchemyStack, fileStage };
package/package.json CHANGED
@@ -1,6 +1,81 @@
1
1
  {
2
2
  "name": "@systemfsoftware/alchemy-stack-layer",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "license": "Apache-2.0",
4
+ "version": "0.0.0",
5
+ "author": "Ryan Lee <drdgvhbh@gmail.com>",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/systemfsoftware/systemfsoftware.git",
9
+ "directory": "packages/alchemy-stack-layer"
10
+ },
11
+ "homepage": "https://github.com/systemfsoftware/systemfsoftware/tree/main/packages/alchemy-stack-layer#readme",
12
+ "bugs": "https://github.com/systemfsoftware/systemfsoftware/issues",
13
+ "description": "An alchemy stack as a scoped Effect layer: deploys on acquire, destroys on release, and runs against the local Workers runtime or real Cloudflare by alchemy's own toggle.",
14
+ "keywords": [
15
+ "alchemy",
16
+ "cloudflare",
17
+ "effect",
18
+ "effect-ts",
19
+ "layer",
20
+ "integration-testing",
21
+ "gherkin",
22
+ "typescript"
23
+ ],
24
+ "type": "module",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.mjs"
29
+ },
30
+ "./package.json": "./package.json"
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "dependencies": {
36
+ "@alchemy.run/test": "2.0.0-beta.87",
37
+ "@systemfsoftware/effect-spec-runtime": "^1.3.3"
38
+ },
39
+ "devDependencies": {
40
+ "@alchemy.run/cloudflare": "2.0.0-beta.87",
41
+ "@effect/platform-node": "^4.1.4",
42
+ "@microsoft/api-extractor": "^7.60.1",
43
+ "@systemfsoftware/arethetypeswrong-cli": "^4.2.0",
44
+ "@systemfsoftware/effect-gherkin-spec": "^8.3.4",
45
+ "@systemfsoftware/oxlint-config-recommended": "^9.0.2",
46
+ "@systemfsoftware/tsconfig": "^2.1.0",
47
+ "@systemfsoftware/tsdown-config": "^0.1.3",
48
+ "@systemfsoftware/vitest": "^4.2.1",
49
+ "@systemfsoftware/vitest-config": "^0.1.4",
50
+ "@types/node": "^26.6.6",
51
+ "alchemy": "2.0.0-beta.87",
52
+ "effect": "^4.1.4",
53
+ "fast-check": "^4.10.2",
54
+ "oxlint": "~1.93.0",
55
+ "rimraf": "^6.1.4",
56
+ "tsdown": "^0.23.7",
57
+ "tstyche": "^7.2.5",
58
+ "vitest": "^5.1.0"
59
+ },
60
+ "peerDependencies": {
61
+ "@effect/platform-node": "^4.1.4",
62
+ "alchemy": "2.0.0-beta.87",
63
+ "effect": "^4.1.4"
64
+ },
65
+ "publishConfig": {
66
+ "access": "public",
67
+ "provenance": true
68
+ },
69
+ "scripts": {
70
+ "clean": "rimraf dist",
71
+ "build": "tsdown -l warn && pnpm api:check",
72
+ "typecheck": "tsc -b",
73
+ "test": "vitest run && vitest run --config vitest.toggle.config.ts",
74
+ "test:cloud": "vitest run --config vitest.cloud.config.ts",
75
+ "test:types": "TSTYCHE_TYPESCRIPT_MODULE=tstyche-typescript tstyche",
76
+ "lint": "f=${OXLINT_FORMAT:-${AGENT:+agent}}; effect-tsgo oxlint . --format=${f:-default}",
77
+ "attw": "attw --pack .",
78
+ "api:check": "api-extractor-quiet run",
79
+ "api:update": "api-extractor run --local"
80
+ }
6
81
  }