The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Output from "./Output.ts"; |
| 2 | import type { ResourceLike } from "./Resource.ts"; |
| 3 | |
| 4 | // special runtime-only symbol for probing the Ref proxy for its metadata |
| 5 | const RefMetadata = Symbol.for("alchemy/RefMetadata"); |
| 6 | |
| 7 | export const isRef = (s: any): s is Ref<any> => s && s[RefMetadata] !== undefined; |
| 8 | |
| 9 | export const getRefMetadata = <R extends ResourceLike>(ref: Ref<R>): RefMetadata<R> => |
| 10 | (ref as any)[RefMetadata]; |
| 11 | |
| 12 | export interface Ref<R extends ResourceLike = ResourceLike> { |
| 13 | /** @internal phantom */ |
| 14 | Ref: R; |
| 15 | } |
| 16 | |
| 17 | export interface RefMetadata<R extends ResourceLike> { |
| 18 | id: R["LogicalId"]; |
| 19 | stack?: string; |
| 20 | stage?: string; |
| 21 | /** |
| 22 | * The resource type of the ref's target (e.g. |
| 23 | * `"Cloudflare.KV.Namespace"`). Known statically — `MyResource.ref` |
| 24 | * carries its own type — so duck-typing classifiers (Worker env |
| 25 | * bindings, capability helpers) that read `.Type` can identify a ref |
| 26 | * exactly like a locally-declared resource. |
| 27 | */ |
| 28 | type?: string; |
| 29 | } |
| 30 | |
| 31 | export const ref = <R extends ResourceLike>( |
| 32 | id: string, |
| 33 | { |
| 34 | stack, |
| 35 | stage, |
| 36 | }: { |
| 37 | stack?: string; |
| 38 | stage?: string; |
| 39 | } = {}, |
| 40 | type?: string, |
| 41 | ): Ref<R> => { |
| 42 | const ref = new Proxy( |
| 43 | {}, |
| 44 | { |
| 45 | get: (_, prop) => { |
| 46 | if (prop === RefMetadata) { |
| 47 | return { |
| 48 | stack, |
| 49 | stage, |
| 50 | id, |
| 51 | type, |
| 52 | } satisfies RefMetadata<R>; |
| 53 | } |
| 54 | return (Output.of(ref) as any)[prop]; |
| 55 | }, |
| 56 | }, |
| 57 | ) as Ref<R>; |
| 58 | return ref; |
| 59 | }; |