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

main
ts 558 lines 21.6 KB
Raw
1 import * as Data from "effect/Data";
2 import * as Effect from "effect/Effect";
3 import * as Effectable from "effect/Effectable";
4 import * as Layer from "effect/Layer";
5 import * as Option from "effect/Option";
6 import type { Pipeable } from "effect/Pipeable";
7 import { AdoptPolicy } from "./AdoptPolicy.ts";
8 import { toFqn } from "./FQN.ts";
9 import type { Input, InputProps, PropsInput } from "./Input.ts";
10 import { CurrentNamespace, type NamespaceNode } from "./Namespace.ts";
11 import * as Output from "./Output.ts";
12 import { Provider } from "./Provider.ts";
13 import {
14 ConflictingProviderModeError,
15 ProviderModePolicy,
16 type ProviderMode,
17 } from "./ProviderMode.ts";
18 import { ref as makeRef } from "./Ref.ts";
19 import { RemovalPolicy } from "./RemovalPolicy.ts";
20 import { RenamePolicy } from "./Rename.ts";
21 import { Self } from "./Self.ts";
22 import { StackContext } from "./StackContext.ts";
23
24 export type ResourceConstructor<R extends ResourceLike, Req = never> = {
25 Type: R["Type"];
26 Props: R["Props"];
27 <const Methods extends { [key: string]: any }>(
28 methods: Methods,
29 ): ResourceClassWithMethods<R, Methods>;
30 (
31 id: string,
32 // PropsInput distributes over union Props so discriminated-union
33 // resources keep the correlation between discriminant and payload.
34 ...args: {} extends R["Props"]
35 ? [props?: PropsInput<R["Props"]>]
36 : [props: PropsInput<R["Props"]>]
37 ): Effect.Effect<R, never, Req>;
38 <PropsReq = never>(
39 id: string,
40 props: Effect.Effect<InputProps<R["Props"]>, never, PropsReq>,
41 ): Effect.Effect<R, never, PropsReq | Req>;
42 };
43
44 export interface ResourceClassLike<R extends ResourceLike> {
45 Type: R["Type"];
46 Props: R["Props"];
47 Self: Self<R>;
48 Provider: Provider<R>;
49 /**
50 * Legacy type names this resource was previously registered under
51 * (see {@link ResourceOptions.aliases}). Copied onto the
52 * `ProviderService` by `Provider.succeed`/`Provider.effect` so provider
53 * lookup can resolve state persisted under a pre-rename type.
54 *
55 * `undefined` is accepted explicitly so `ResourceClass` (whose `Aliases`
56 * is `readonly string[] | undefined`) stays assignable to
57 * `ResourceClassLike` under `exactOptionalPropertyTypes`.
58 */
59 Aliases?: readonly string[] | undefined;
60 }
61
62 export type ResourceClass<R extends ResourceLike> = ResourceConstructor<
63 R,
64 R["Providers"] extends undefined ? Provider<R> : R["Providers"]
65 > &
66 Effect.Effect<ResourceConstructor<R>> & {
67 Self: Self<R>;
68 Provider: Provider<R>;
69 Aliases: readonly string[] | undefined;
70 ref(id: string, options?: { stage?: string; stack?: string }): Effect.Effect<R>;
71 };
72
73 export type ResourceClassWithMethods<
74 R extends ResourceLike,
75 Methods extends { [key: string]: any },
76 > = ResourceConstructor<R, R["Providers"] extends undefined ? Provider<R> : R["Providers"]> &
77 Effect.Effect<ResourceConstructor<R>> & {
78 Self: Self<R>;
79 Provider: Provider<R>;
80 Aliases: readonly string[] | undefined;
81 ref(id: string, options?: { stage?: string; stack?: string }): Effect.Effect<R>;
82 } & Methods;
83
84 export type LogicalId = string;
85
86 export interface ResourceBinding<Data = any> {
87 sid: string;
88 data: Data;
89 }
90
91 export interface ResourceLike<
92 Type extends string = string,
93 Props extends object | undefined = any,
94 Attributes extends object = object,
95 Binding = any,
96 Providers = any,
97 > {
98 /**
99 * Namespace containing this Resource.
100 */
101 Namespace: NamespaceNode | undefined;
102 /**
103 * Fully Qualified Name (namespace path + logical ID).
104 * Used as the unique key for state storage.
105 */
106 FQN: string;
107 /**
108 * Type of the Resource (e.g. AWS.Lambda.Function)
109 */
110 Type: Type;
111 /**
112 * Logical ID of the Resource (e.g. MyFunction)
113 */
114 LogicalId: LogicalId;
115 /**
116 * Properties of the Resource.
117 */
118 Props: Props;
119 /**
120 * Removal Policy of the Resource.
121 */
122 RemovalPolicy: RemovalPolicy["Service"];
123 /**
124 * Per-resource adoption policy captured from the ambient {@link AdoptPolicy}
125 * at registration time (e.g. via `.pipe(adopt(true))`). `undefined` means no
126 * resource-scoped override — the planner falls back to the stack/CLI default.
127 */
128 Adopt: boolean | undefined;
129 /**
130 * Per-resource provider mode captured from the ambient
131 * {@link ProviderModePolicy} at registration time. `"live"` when the
132 * resource was pinned via `.pipe(remote())` (opting out of local emulation
133 * during dev); `undefined` means the run default (`AlchemyContext.dev`).
134 */
135 Mode: ProviderMode | undefined;
136 /**
137 * Copied from {@link ResourceOptions.requiresImplementation} at
138 * registration: `true` for platform-typed resources, whose registrations
139 * must have resolved {@link Props} by plan time. `Plan.make` fails fast
140 * with {@link MissingImplementationError} when this is set and `Props`
141 * are still `undefined` after the whole program has evaluated — a bare
142 * tag was yielded but its `.make(props, impl)` Layer was never provided.
143 */
144 RequiresImplementation: boolean | undefined;
145 /**
146 * Former FQNs this resource's state may still be persisted under,
147 * captured from the ambient {@link RenamePolicy} at registration (via
148 * `.pipe(renamedFrom("OldId"))`) and resolved against the same namespace
149 * as the resource's own FQN. The planner migrates a state row found at a
150 * former FQN to {@link FQN} instead of planning a create+delete
151 * replacement — see `renamedFrom` in Rename.ts for the full semantics.
152 */
153 FormerFqns: readonly string[] | undefined;
154 /** @internal phantom */
155 Attributes: Attributes;
156 /** @internal phantom */
157 Binding: Binding;
158 /** @internal phantom */
159 Providers: Providers;
160 }
161
162 // Require the full resource identity (Type AND FQN), not just `Type`:
163 // user-authored prop objects legitimately carry a `Type` field (e.g.
164 // Amazon States Language states like `{ Type: "Pass", End: true }` in a
165 // Step Functions definition) and must not be mistaken for resources.
166 // Locally-declared resources always expose both as own keys; refs
167 // (`Resource.ref(...)`) deliberately report neither via `in` so they keep
168 // routing through Output resolution.
169 export const isResource = (value: any): value is ResourceLike =>
170 typeof value === "object" && value !== null && "Type" in value && "FQN" in value;
171
172 /**
173 * Does `value` reference an instance of the resource type `type` —
174 * either a locally-declared resource or a `Resource.ref(...)` to one?
175 *
176 * Two constraints that ad-hoc guards get wrong for refs, which resolve
177 * to Output-expression proxies:
178 *
179 * - Read `.Type` via property access (never `in`): the proxy answers
180 * property reads with statically-known values but deliberately does
181 * not report key existence (so {@link isResource} keeps routing refs
182 * through Output resolution instead of the upstream-node lookup).
183 * - Accept `typeof value === "function"`: the proxy's target is
184 * callable (it needs an `apply` trap), so refs are not `"object"`.
185 *
186 * Either mistake silently rejects refs — in a Worker `env` that
187 * degrades the binding to a plain JSON var.
188 */
189 export const isResourceOfType = (value: unknown, type: string): boolean =>
190 (typeof value === "object" || typeof value === "function") &&
191 value !== null &&
192 (value as { Type?: unknown }).Type === type;
193
194 export type Resource<
195 Type extends string = any,
196 Props extends object | undefined = any,
197 Attributes extends object = any,
198 Binding = never,
199 Providers = undefined,
200 > = Pipeable &
201 ResourceLike<Type, Props, Attributes, Binding, Providers> & {
202 bind(sid: Input<string>, binding: Input<Binding>): Effect.Effect<void>;
203 bind(
204 template: TemplateStringsArray,
205 ...args: any[]
206 ): (binding: Input<Binding>) => Effect.Effect<void>;
207 } & {
208 [attr in keyof Attributes]-?: AttrOutput<Attributes[attr]>;
209 };
210
211 /**
212 * Accessor type for one attribute. Pure object attributes upgrade to
213 * {@link Output.ObjectExpr} so nested access is typed —
214 * `hyperpod.instanceGroups.workers` — while primitives, unions with
215 * `undefined`, branded string unions (`"a" | (string & {})`), and arrays
216 * stay plain {@link Output.Output} (running them through `ToOutput` would
217 * classify the `string & {}` branch as an object and explode into
218 * String-method mapped types).
219 */
220 type AttrOutput<A> = [A] extends [
221 string | number | boolean | bigint | null | undefined | Date | any[],
222 ]
223 ? Output.Output<A, never>
224 : [A] extends [Record<string, any>]
225 ? Output.ObjectExpr<A, never>
226 : Output.Output<A, never>;
227
228 export interface ResourceOptions {
229 /**
230 * Default removal policy for this resource type when the caller has not
231 * explicitly provided one via `RemovalPolicy` / `destroy()` / `retain()`.
232 *
233 * Useful for resources that wrap unrecoverable real-world identifiers
234 * (DNS zones, customer accounts, etc.) where the safe default is to
235 * leave the cloud object alone on stack destroy.
236 *
237 * @default "destroy"
238 */
239 defaultRemovalPolicy?: RemovalPolicy["Service"];
240 /**
241 * Legacy type names this resource was previously registered under.
242 *
243 * When a resource type is renamed (e.g. `"Cloudflare.Queue"` →
244 * `"Cloudflare.Queues.Queue"`), state persisted under the old name must
245 * still resolve to this resource's provider. Listing the old names here
246 * makes provider lookup fall back from the legacy name to this type, so
247 * existing stacks keep planning, updating, and deleting cleanly across
248 * the rename. The state row migrates to the new type on its next write.
249 *
250 * ```ts
251 * export const Queue = Resource<Queue>("Cloudflare.Queues.Queue", {
252 * aliases: ["Cloudflare.Queue"],
253 * });
254 * ```
255 */
256 aliases?: string[];
257 /**
258 * Marks every registration of this type as requiring resolved props by
259 * plan time. Set by `Platform(...)` on its resource class: every
260 * legitimate platform construction (a `.make(props, impl)` Layer build,
261 * a tag declared with props, a plain `Worker("id", props)` call) produces
262 * defined `Props` — the only way a platform-typed registration reaches
263 * the planner with `Props === undefined` is a bare-tag FORWARD REFERENCE
264 * whose `.make` Layer never built. `Plan.make` fails fast with
265 * {@link MissingImplementationError} in that case, instead of letting a
266 * provider read `undefined` props. Plain (non-platform) resources leave
267 * this unset so a no-props reference yield (`yield* Queue("MyQueue")`)
268 * keeps planning as a noop.
269 */
270 requiresImplementation?: boolean;
271 }
272
273 /**
274 * A tagged platform resource declared with neither props nor an inline
275 * implementation was `yield*`ed, but its `.make(props, impl)` Layer never
276 * built.
277 *
278 * Such a tag carries no configuration on its own — props AND impl both live
279 * on the Layer — so its registration is a forward reference with `undefined`
280 * props that the Layer's build repairs (in either order; see the #874
281 * circular env-tag pattern). Props still `undefined` once the whole program
282 * has evaluated means the Layer was never provided; `Plan.make` fails fast
283 * with this error instead of letting the failure surface deep inside
284 * whichever provider first reads a prop (e.g. `TypeError: undefined is not
285 * an object (evaluating 'news.name')` in the Cloudflare Worker pre-create).
286 */
287 export class MissingImplementationError extends Data.TaggedError("MissingImplementationError")<{
288 message: string;
289 /** Resource type of the platform, e.g. `Cloudflare.Worker`. */
290 type: string;
291 /** Logical id of the tagged resource (its class name by convention). */
292 id: string;
293 }> {}
294
295 /**
296 * A logical id was declared again as a different resource type.
297 *
298 * A logical id names one resource in the stack. Yielding that id again
299 * returns the resource already registered, so one declaration can be shared
300 * by the stack program and a service init. A different type is a different
301 * resource. Returning the first one would drop the second declaration while
302 * TypeScript still typed the result as the second type.
303 */
304 export class DuplicateLogicalIdError extends Data.TaggedError("DuplicateLogicalIdError")<{
305 message: string;
306 /** Fully qualified logical id already present on the stack. */
307 fqn: string;
308 /** Type registered under {@link fqn}. */
309 existingType: string;
310 /** Type of the declaration that collided with {@link fqn}. */
311 conflictingType: string;
312 }> {}
313
314 export const missingImplementation = (type: string, id: string) =>
315 new MissingImplementationError({
316 type,
317 id,
318 message: [
319 `${type}<${id}> was yielded without its implementation.`,
320 "",
321 `\`${id}\` is declared as a bare tag — no props, no inline implementation — so both come from its \`.make(...)\` Layer:`,
322 "",
323 ` export class ${id} extends ${type}<${id}>()("${id}") {}`,
324 ` export const ${id}Live = ${id}.make({ /* props */ }, Effect.gen(function* () { /* ... */ }));`,
325 "",
326 `That Layer is not in scope where \`${id}\` is yielded. Provide it to the Stack's program:`,
327 "",
328 " Alchemy.Stack(",
329 ` "my-stack",`,
330 " { providers, state },",
331 " Effect.gen(function* () {",
332 ` const instance = yield* ${id};`,
333 ` }).pipe(Effect.provide([${id}Live])),`,
334 " )",
335 "",
336 `If \`${id}\` is not Effect-native, declare it with props instead: \`()("${id}", { /* props */ })\`.`,
337 ].join("\n"),
338 });
339
340 /**
341 * Creates a resource constructor for a concrete resource type.
342 *
343 * The returned constructor registers the resource on the current stack,
344 * resolves input props, exposes output attributes as `Output` expressions, and
345 * records bindings contributed by policies and event sources. Resource
346 * providers are attached separately through `.provider`.
347 */
348 export function Resource<R extends ResourceLike>(
349 type: R["Type"],
350 options?: ResourceOptions,
351 ): ResourceClass<R> {
352 const defaultRemovalPolicy = options?.defaultRemovalPolicy ?? "destroy";
353 type Props = Input<R["Props"]>;
354 const self = Self<R>(type);
355 const constructor = (id: string, props: Props | Effect.Effect<Props> | undefined) =>
356 Effect.gen(function* () {
357 const stack = yield* StackContext;
358 const namespace = yield* CurrentNamespace;
359 const fqn = toFqn(namespace, id);
360
361 // `remote()` opts resources out of local emulation during dev. The
362 // captured Mode is either "live" (pinned) or undefined (run default).
363 // The Reference default is `undefined` — "no explicit decoration" —
364 // which is distinct from an explicit `remote(false)`.
365 const ambientPolicy = yield* ProviderModePolicy;
366 const ambientMode: ProviderMode | undefined = ambientPolicy ? "live" : undefined;
367
368 const existing = stack.resources[fqn];
369 if (existing) {
370 if (existing.Type !== type) {
371 return yield* Effect.die(
372 new DuplicateLogicalIdError({
373 message:
374 `Resource '${fqn}' is already registered as '${existing.Type}' ` +
375 `and cannot be declared as '${type}'. A logical id names one ` +
376 `resource in the stack. Yield the existing resource, or give ` +
377 `this declaration its own id.`,
378 fqn,
379 existingType: existing.Type,
380 conflictingType: type,
381 }),
382 );
383 }
384 // A resource may be `yield*`ed from several places (idempotent
385 // registration). If a later site carries an *explicit* ambient
386 // ProviderModePolicy that disagrees with what the resource was
387 // registered with, the decorations are conflicting — fail loudly
388 // instead of silently picking one. A later site with NO ambient
389 // policy simply inherits the registered resource (the common
390 // "reference it from elsewhere" pattern).
391 if (ambientPolicy !== undefined && existing.Mode !== ambientMode) {
392 return yield* Effect.die(
393 new ConflictingProviderModeError({
394 message:
395 `Resource '${fqn}' was registered with provider mode ` +
396 `'${existing.Mode ?? "default"}' but is now being registered ` +
397 `with conflicting mode '${ambientMode ?? "default"}'. A ` +
398 "resource must resolve to a single provider mode: register " +
399 "it once and close over the returned value, or make both " +
400 "registration sites agree (e.g. wrap both in the same " +
401 "`remote()` scope).",
402 fqn,
403 existingMode: existing.Mode,
404 conflictingMode: ambientMode,
405 }),
406 );
407 }
408 // TODO(sam): check if props are different and die
409 return existing;
410 }
411 const bind = (
412 ...args:
413 | [sid: string, data: R["Binding"]]
414 | [template: TemplateStringsArray, ...args: any[]]
415 ) =>
416 typeof args[0] === "string"
417 ? Effect.gen(function* () {
418 const [sid, data] = args as [sid: string, data: R["Binding"]];
419 (stack.bindings[fqn] ??= []).push({
420 sid,
421 data,
422 });
423 return undefined;
424 })
425 : (data: R["Binding"]) => {
426 const stringifyBindArg = (arg: any): string | undefined => {
427 if (arg === undefined) {
428 return undefined;
429 }
430
431 if (Array.isArray(arg)) {
432 return arg
433 .flatMap((item) => {
434 const stringified = stringifyBindArg(item);
435 return stringified === undefined ? [] : [stringified];
436 })
437 .join(", ");
438 }
439
440 if (arg && (typeof arg === "object" || typeof arg === "function")) {
441 if ("LogicalId" in arg && typeof arg.LogicalId === "string") {
442 return arg.LogicalId;
443 }
444
445 if ("id" in arg && typeof arg.id === "string") {
446 return arg.id;
447 }
448 }
449
450 return String(arg);
451 };
452
453 return bind(
454 `${(args[0] as TemplateStringsArray)
455 .flatMap((text, i) => {
456 const stringified = stringifyBindArg(args[i + 1]);
457 return stringified !== undefined ? [text, stringified] : [text];
458 })
459 .join("")}`,
460 data,
461 );
462 };
463
464 const target: any = {
465 Type: type,
466 Namespace: namespace,
467 FQN: fqn,
468 LogicalId: id,
469 Props: props,
470 Provider: ProviderTag as Provider<any>,
471 RemovalPolicy: yield* Effect.serviceOption(RemovalPolicy).pipe(
472 Effect.map(Option.getOrElse(() => defaultRemovalPolicy)),
473 ),
474 Adopt: yield* Effect.serviceOption(AdoptPolicy).pipe(Effect.map(Option.getOrUndefined)),
475 Mode: ambientMode,
476 RequiresImplementation: options?.requiresImplementation || undefined,
477 // Bare-string former ids resolve against the SAME namespace as the
478 // resource's own id, so `renamedFrom("Site/Worker")` declared at the
479 // caller's level claims `<callerNs>/Site/Worker`; the `{ fqn }` form
480 // is absolute (cross-namespace moves).
481 FormerFqns: yield* Effect.serviceOption(RenamePolicy).pipe(
482 Effect.map(
483 Option.match({
484 onNone: () => undefined,
485 onSome: (formerIds) =>
486 formerIds.map((formerId) =>
487 typeof formerId === "string" ? toFqn(namespace, formerId) : formerId.fqn,
488 ),
489 }),
490 ),
491 ),
492 bind,
493 toString(this: typeof target) {
494 return `Resource<${this.Type}>(${this.LogicalId})`;
495 },
496 [Symbol.toPrimitive](this: typeof target, hint: string) {
497 return hint === "number" ? NaN : this.toString();
498 },
499 };
500
501 const Resource: R = (stack.resources[fqn] = new Proxy(target, {
502 set: (t, prop, value) => {
503 t[prop as keyof typeof t] = value;
504 return true;
505 },
506 get: (t, prop) =>
507 typeof prop === "symbol" || prop in t
508 ? t[prop as keyof typeof t]
509 : new Output.PropExpr<any, string>(Output.of(Resource), prop),
510 })) as R;
511 Resource.Props = Effect.isEffect(props)
512 ? // @effect-diagnostics-next-line anyUnknownInErrorContext:off
513 yield* props.pipe(
514 Effect.provide(
515 Layer.mergeAll(Layer.succeed(Self, Resource), Layer.succeed(Self(type), Resource)),
516 ),
517 )
518 : props;
519 return Resource;
520 });
521
522 const ProviderTag = Provider(type);
523
524 const Service = {
525 /**
526 * Build a typed reference to a deployed instance of this resource
527 * — in the current stack/stage by default, or in another via
528 * `options`. Resolves to the same shape as `yield*
529 * MyResource("id", props)` so downstream code can read attributes
530 * (`ref.someAttr`) exactly the way it would for a locally-declared
531 * resource.
532 */
533 ref: (id: string, options?: { stage?: string; stack?: string }): Effect.Effect<R> =>
534 Effect.succeed(Output.of(makeRef<R>(id, options, type)) as unknown as R),
535
536 Type: type,
537 Provider: ProviderTag,
538 Self: self,
539 Aliases: options?.aliases,
540 };
541
542 const ResourceClass = Object.assign(
543 (...args: [id: string, props: R["Props"]] | [methods: object]) =>
544 typeof args[0] === "object"
545 ? Object.assign(ResourceClass, args[0])
546 : constructor(...(args as [string, R["Props"]])),
547 Service,
548 // Make the constructor itself a real Effect: `yield* MyResource` resolves
549 // to the constructor function (same as the old `asEffect()`), and
550 // `Effect.isEffect(MyResource)` is now true so `Effect.all`/`forEach` work.
551 Effectable.Prototype({
552 label: `Resource<${type}>`,
553 evaluate: () => Effect.succeed((id: string, props: R["Props"]) => constructor(id, props)),
554 }),
555 ) as any;
556
557 return ResourceClass;
558 }