@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 183 lines 7.72 KB
Raw
1 /** @effect-diagnostics anyUnknownInErrorContext:off */
2
3 import { Endpoint } from "@distilled.cloud/aws";
4 import { Credentials } from "@distilled.cloud/aws/Credentials";
5 import { Region } from "@distilled.cloud/aws/Region";
6 import type { ProviderService } from "alchemy/Provider";
7 import type { ResourceLike } from "alchemy/Resource";
8 import * as Context from "effect/Context";
9 import * as Effect from "effect/Effect";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Predicate from "effect/Predicate";
13 import * as Stream from "effect/Stream";
14 import { AWSEnvironment } from "../Environment.ts";
15
16 /**
17 * Wraps a {@link ProviderService} so that EVERY lifecycle method
18 * (`reconcile`, `diff`, `read`, `delete`, `list`, `precreate`, `tail`,
19 * `logs`, ...) runs with the given services provided. The services are
20 * provided *closest* to the lifecycle effect, so they override anything the
21 * engine's ambient context supplies (credentials, region, endpoint,
22 * environment).
23 *
24 * Method identity/shape is preserved exactly — the Provider interface is
25 * structural, and the Proxy forwards non-function members (`version`,
26 * `stables`, `aliases`, `nuke`, ...) untouched. Modeled on the lifecycle
27 * Proxy in [Local/RpcProvider.ts](../../Local/RpcProvider.ts).
28 */
29 export const withProviderContext = <R extends ResourceLike>(
30 provider: ProviderService<R>,
31 services: Layer.Layer<any, never, never>,
32 ): ProviderService<R> =>
33 new Proxy(provider, {
34 get: (target, prop) => {
35 const value = (target as any)[prop];
36 if (prop === "modes" && value !== undefined) {
37 // Mode-resolved variants (`findProviderByType(type, mode)`, used for
38 // stamped-mode deletes and `Alchemy.remote()`) bypass this Proxy —
39 // wrap the services THEY resolve to as well, so a live variant's
40 // ops carry the same context. A local variant's own data-plane
41 // override is provided closer and still wins.
42 return Object.fromEntries(
43 Object.entries(value as Record<string, Effect.Effect<any>>).map(([mode, build]) => [
44 mode,
45 Effect.map(build, (resolved) =>
46 withProviderContext(resolved as ProviderService<R>, services),
47 ),
48 ]),
49 );
50 }
51 if (!Predicate.isFunction(value)) return value;
52 return (...args: any[]) => {
53 const result: unknown = value(...args);
54 if (Stream.isStream(result)) {
55 return Stream.provide(result, services);
56 }
57 if (Effect.isEffect(result)) {
58 return Effect.provide(result, services);
59 }
60 return result;
61 };
62 },
63 });
64
65 /**
66 * Capture the ambient AWS environment — the exact tag set a local data
67 * plane overrides: {@link Endpoint}, {@link Region}, {@link Credentials},
68 * {@link AWSEnvironment} — as a layer that reproduces it verbatim. An
69 * absent Endpoint is pinned as `undefined` (the SDK default resolver), so
70 * a later ambient override cannot leak in.
71 */
72 export const captureAwsEnvironment: Effect.Effect<Layer.Layer<any, never, never>> = Effect.gen(
73 function* () {
74 let ctx = Context.empty();
75 const endpoint = yield* Effect.serviceOption(Endpoint.Endpoint);
76 ctx = Context.add(
77 ctx,
78 Endpoint.Endpoint,
79 Option.getOrElse(endpoint, () => Effect.undefined),
80 );
81 const region = yield* Effect.serviceOption(Region);
82 if (Option.isSome(region)) ctx = Context.add(ctx, Region, region.value);
83 const credentials = yield* Effect.serviceOption(Credentials);
84 if (Option.isSome(credentials)) {
85 ctx = Context.add(ctx, Credentials, credentials.value);
86 }
87 const environment = yield* Effect.serviceOption(AWSEnvironment);
88 if (Option.isSome(environment)) {
89 ctx = Context.add(ctx, AWSEnvironment, environment.value);
90 }
91 return Layer.succeedContext(ctx) as Layer.Layer<any, never, never>;
92 },
93 );
94
95 /**
96 * Pin every provider in a collection (and every mode variant it lazily
97 * resolves) to the AWS environment captured at REGISTRATION, provided
98 * closest around each lifecycle effect. Providers therefore always run
99 * against the environment they were registered with, regardless of the
100 * caller's ambient context — which in an `alchemy dev` run is the emulator
101 * (see AWS/Providers.ts): composition-time lookups get the emulator for
102 * free while live-mode and mode-agnostic providers keep hitting the real
103 * cloud. Local variants still win — their own data-plane override is
104 * provided closer.
105 */
106 export const pinCollectionEnvironment = <
107 A extends {
108 readonly kind: "ProviderCollection";
109 get(service: string): ProviderService<any> | undefined;
110 readonly providers: Record<string, ProviderService>;
111 },
112 >(
113 collection: A,
114 environment: Layer.Layer<any, never, never>,
115 ): A => {
116 const wrap = (provider: ProviderService | undefined) => {
117 if (provider === undefined) return undefined;
118 // Stamp the registration-captured live environment so Binding clients
119 // for `Alchemy.remote()` resources can provide it closest — in a
120 // `dev` run ambient is the emulator, and an unwrapped live client
121 // would miss the real cloud.
122 Object.assign(provider, { liveDataPlane: () => environment });
123 return withProviderContext(provider, environment);
124 };
125 const wrapped: Record<string, ProviderService> = {};
126 for (const [type, provider] of Object.entries(collection.providers)) {
127 wrapped[type] = wrap(provider)!;
128 }
129 return {
130 ...collection,
131 get: (service: string) => wrapped[service] ?? wrap(collection.get(service)),
132 providers: wrapped,
133 } as A;
134 };
135
136 const isProviderService = (value: unknown): value is ProviderService<any> =>
137 Predicate.hasProperty(value, "reconcile") && Predicate.isFunction(value.reconcile);
138
139 /**
140 * Layer-level companion to {@link withProviderContext}: given a provider
141 * layer (e.g. `S3.BucketProvider()`) and a layer of override services,
142 * returns a layer that builds both and re-registers every provider service
143 * with its lifecycle methods wrapped in the override context.
144 *
145 * Built with `Layer.fromBuildMemo` (like `ProviderLayer.dual`) so the
146 * `services` layer is built through the ambient `MemoMap`: pass a
147 * **module-memoized layer reference** and it is constructed exactly once per
148 * stack build no matter how many providers are wrapped with it.
149 *
150 * The services are also provided to the provider layer's *build* (winning
151 * over the ambient context), so providers that resolve environment services
152 * at layer construction see the override too.
153 */
154 export const provideProviderContext = <ROut, E, RIn, ServicesE>(
155 providerLayer: Layer.Layer<ROut, E, RIn>,
156 services: Layer.Layer<any, ServicesE, never>,
157 ): Layer.Layer<ROut, E | ServicesE, RIn> =>
158 Layer.fromBuildMemo((memoMap, scope) =>
159 Effect.gen(function* () {
160 const ambient = yield* Effect.context<never>();
161 // Built via the shared MemoMap: a module-memoized `services` reference
162 // is deduped to a single instance across every wrapped provider.
163 const servicesCtx = yield* Layer.buildWithMemoMap(services, memoMap, scope);
164 const servicesLayer = Layer.succeedContext(servicesCtx);
165 const built = yield* Layer.buildWithMemoMap(
166 providerLayer.pipe(
167 // Closest wins: overrides first, then the ambient build context.
168 Layer.provide(servicesLayer),
169 Layer.provide(Layer.succeedContext(ambient)),
170 ) as Layer.Layer<any, any, never>,
171 memoMap,
172 scope,
173 );
174 const wrapped = new Map<string, any>();
175 for (const [key, value] of built.mapUnsafe) {
176 wrapped.set(
177 key,
178 isProviderService(value) ? withProviderContext(value, servicesLayer) : value,
179 );
180 }
181 return Context.makeUnsafe(wrapped) as Context.Context<ROut>;
182 }),
183 ) as Layer.Layer<ROut, E | ServicesE, RIn>;