@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, 06:00 UTC

main
ts 449 lines 15.3 KB
Raw
1 import { AlchemyContext } from "alchemy/AlchemyContext";
2 import type { MemoOptions } from "alchemy/Command/Memo";
3 import * as DNS from "alchemy/DNS/Adapter";
4 import type { Input } from "alchemy/Input";
5 import * as Namespace from "alchemy/Namespace";
6 import * as Output from "alchemy/Output";
7 import { ProviderModePolicy } from "alchemy/ProviderMode";
8 import { initialCwd } from "alchemy/Util/Node";
9 import {
10 staticConfigFromAssets,
11 type WebsiteAssetsProps,
12 type WebsiteNotFoundHandling,
13 } from "alchemy/Website/assets";
14 import { packSiteExtraFiles } from "alchemy/Website/packExtraFiles";
15 import { Server as FrameworkServer, type ServerDevProps } from "alchemy/Website/Server";
16 import * as Data from "effect/Data";
17 import * as Effect from "effect/Effect";
18 import * as FileSystem from "effect/FileSystem";
19 import * as Path from "effect/Path";
20 import * as Redacted from "effect/Redacted";
21 import { App } from "../App.ts";
22 import { Bucket } from "../Bucket.ts";
23 import { Certificate, type CertificateDnsRequirements } from "../Certificate.ts";
24 import { IpAssignment } from "../IpAssignment.ts";
25 import type { Providers } from "../Providers.ts";
26 import { Service, type ServiceProps } from "../Service.ts";
27 import { AssetDeployment } from "./AssetDeployment.ts";
28
29 /**
30 * A resource-valued prop: the resource itself, or an Effect that produces
31 * it (so `yield* App(...)` and `App(...)` both type-check).
32 */
33 export type Ref<T> = T | Effect.Effect<T, never, Providers>;
34
35 export type { ServerDevProps, WebsiteAssetsProps, WebsiteNotFoundHandling };
36 export { staticConfigFromAssets };
37
38 /**
39 * Custom hostname of a Fly website: the hostname itself, or
40 * `{ name, dns }` to also publish its DNS records.
41 */
42 export type WebsiteDomain =
43 | string
44 | {
45 /** Hostname, e.g. `www.example.com`. */
46 name: string;
47 /**
48 * DNS host that publishes the hostname's records (see
49 * [DNS Adapters](/infrastructure-as-code/dns-adapters)), e.g.
50 * `Cloudflare.DNS.Adapter()`: the ACME challenge `CNAME` Fly lists in
51 * the Certificate's `dnsRequirements`, and `A` / `AAAA` records at
52 * the site's addresses. Omitted: publish the records yourself.
53 */
54 dns?: DNS.DnsConfig;
55 };
56
57 /** The hostname of a {@link WebsiteDomain}. */
58 export const websiteDomainName = (domain: WebsiteDomain | undefined): string | undefined =>
59 domain === undefined || typeof domain === "string" ? domain : domain.name;
60
61 const acmeChallengeRecords = (
62 hostname: string,
63 requirements: CertificateDnsRequirements | undefined,
64 ): DNS.DnsRecord[] => {
65 const challenge = requirements?.acmeChallenge;
66 if (challenge?.target === undefined || challenge.target.length === 0) {
67 return [];
68 }
69 const expected = `_acme-challenge.${hostname}`;
70 const name =
71 challenge.name !== undefined &&
72 DNS.normalizeDnsName(challenge.name).endsWith(DNS.normalizeDnsName(hostname))
73 ? challenge.name
74 : expected;
75 return [{ name, type: "CNAME", value: challenge.target }];
76 };
77
78 /**
79 * Publish a Fly website's records through `domain.dns`: the Certificate's
80 * ACME challenge `CNAME` (`CertificateValidation`) and `A` / `AAAA`
81 * records at the site's shared IPv4 plus any IPv6 Fly lists for the
82 * hostname (`Domain`). No-op for a plain hostname or an object without
83 * `dns`.
84 */
85 export const publishWebsiteDomainDns = Effect.fn("Fly.Website.publishDomainDns")(function* (args: {
86 readonly domain: WebsiteDomain;
87 readonly certificate: Certificate;
88 readonly ip: IpAssignment;
89 }) {
90 if (typeof args.domain === "string" || args.domain.dns === undefined) {
91 return;
92 }
93 const dns = yield* DNS.resolve(args.domain.dns);
94 const name = args.domain.name;
95 yield* dns.records("CertificateValidation", {
96 records: Output.map(args.certificate.dnsRequirements, (requirements) =>
97 acmeChallengeRecords(name, requirements),
98 ) as unknown as Input<DNS.DnsRecord[]>,
99 });
100 yield* dns.alias("Domain", {
101 name,
102 target: {
103 ipv4: Output.map(args.ip.ip, (ip) => [ip]) as unknown as Input<string[]>,
104 ipv6: Output.map(
105 args.certificate.dnsRequirements,
106 (requirements) => requirements?.aaaa ?? [],
107 ) as unknown as Input<string[]>,
108 },
109 });
110 });
111
112 /**
113 * Props shared by every Fly framework website composite.
114 */
115 export interface FrameworkSiteProps {
116 /** Deployment strategy forwarded to the hosted Fly Service. */
117 deploy?: ServiceProps["deploy"];
118 /** Process shutdown policy. The framework server must handle the signal. */
119 shutdown?: ServiceProps["shutdown"];
120 /** Named Machine readiness checks. */
121 checks?: ServiceProps["checks"];
122 /** Override proxy services and their routing health checks. */
123 services?: ServiceProps["services"];
124 /**
125 * Project root directory (the directory containing `package.json`).
126 * @default "."
127 */
128 rootDir?: string;
129 /**
130 * Controls which files are hashed to decide whether the build re-runs.
131 * @default true
132 */
133 memo?: MemoOptions | boolean;
134 /**
135 * Parent Fly App. Accepts a `Fly.App` or an Effect that produces one.
136 * When omitted, a `Fly.App` is created under this site's namespace.
137 */
138 app?: Ref<App>;
139 /**
140 * Process environment for the hosted server. Not Cloudflare Worker
141 * bindings — values become Machine env vars. Accepts `Output`s
142 * (e.g. `VITE_API_URL: api.url`).
143 */
144 env?: Record<string, string | Redacted.Redacted<string> | Output.Output<string | undefined>>;
145 /**
146 * Static-asset routing (`notFoundHandling`, `htmlHandling`). Hashed
147 * client files are uploaded to Tigris regardless of this bag.
148 */
149 assets?: WebsiteAssetsProps;
150 /**
151 * Options for the local dev server that runs this site under
152 * `alchemy dev`.
153 */
154 dev?: ServerDevProps;
155 /**
156 * Optional custom hostname. Requests ACME (`Fly.Certificate`) on the
157 * App and `url` becomes `https://<domain>`.
158 *
159 * A string (or `{ name }`) leaves DNS to you. Set `dns` (e.g.
160 * `{ name: "www.example.com", dns: Cloudflare.DNS.Adapter() }`) to
161 * publish the ACME challenge `CNAME` and the `A` / `AAAA` records
162 * through that DNS host. See
163 * [DNS Adapters](/infrastructure-as-code/dns-adapters).
164 */
165 domain?: WebsiteDomain;
166 /**
167 * User-defined tags. Accepted for API parity; Fly Services do not
168 * surface resource tags.
169 */
170 tags?: Record<string, string>;
171 }
172
173 /** Per-framework wiring for {@link makeFrameworkSite}. */
174 export interface FrameworkSiteConfig {
175 /** Display name used in error messages (e.g. `"SvelteKit"`). */
176 name: string;
177 /** Framework-integration module specifier. */
178 framework: string;
179 /** Node deploy-target module specifier. */
180 target: string;
181 /**
182 * Framework-specific build options forwarded to the integration (e.g.
183 * `{ kit }`, `{ nuxt }`, `{ astro }`). Must be JSON-serializable.
184 */
185 options?: Record<string, unknown> | undefined;
186 /**
187 * Assets-only routing forwarded to the Node target (Vite SPA fallback).
188 * `spa` also publishes client files to Tigris at `/`.
189 */
190 static?: { spa?: boolean; errorPage?: string } | undefined;
191 /**
192 * Vocs/Waku: serve `about/index.html` at `/about`.
193 * @default "none"
194 */
195 htmlHandling?: "none" | "drop-trailing-slash";
196 /**
197 * Packages installed into the Machine image with `npm install` instead
198 * of bundling (Next.js needs `next`).
199 */
200 install?: string[] | undefined;
201 /**
202 * Skip baking `clientDirectory` at `/app/dist`. Next.js serves `.next`
203 * from the image root instead.
204 */
205 skipClientAssets?: boolean | undefined;
206 }
207
208 export interface FrameworkSite {
209 /**
210 * Public site URL. Local framework URL under `alchemy dev`;
211 * `https://{app}.fly.dev` (or `https://{domain}`) on deploy.
212 */
213 url: string | Output.Output<string | undefined> | undefined;
214 /** Parent Fly App. `undefined` during `alchemy dev`. */
215 app: App | undefined;
216 /** Hosted Fly Service. `undefined` during `alchemy dev`. */
217 service: Service | undefined;
218 /** Shared Anycast IPv4 so `{app}.fly.dev` answers. */
219 ip: IpAssignment | undefined;
220 /** ACME certificate when {@link FrameworkSiteProps.domain} is set. */
221 certificate: Certificate | undefined;
222 }
223
224 export class FrameworkSiteError extends Data.TaggedError("FrameworkSiteError")<{
225 readonly framework: string;
226 readonly message: string;
227 readonly cause?: unknown;
228 }> {}
229
230 const DEFAULT_PORT = 3000;
231
232 const resolveRef = <T>(ref: Ref<T>): Effect.Effect<T, never, Providers> =>
233 Effect.isEffect(ref) ? ref : Effect.succeed(ref);
234
235 const envRecord = (
236 env:
237 | Record<string, string | Redacted.Redacted<string> | Output.Output<string | undefined>>
238 | undefined,
239 ): Record<string, string | Output.Output<string | undefined>> | undefined => {
240 if (env === undefined) return undefined;
241 return Object.fromEntries(
242 Object.entries(env).map(([key, value]) => [
243 key,
244 Redacted.isRedacted(value) ? Redacted.value(value) : value,
245 ]),
246 );
247 };
248
249 const runFrameworkSite = Effect.fn("Fly.Website.FrameworkSite")(function* (
250 _id: string,
251 props: FrameworkSiteProps,
252 config: FrameworkSiteConfig,
253 ) {
254 const ctx = yield* AlchemyContext;
255 const remoted = yield* ProviderModePolicy;
256 const isLocal = ctx.dev && remoted !== true;
257 const path = yield* Path.Path;
258 const fs = yield* FileSystem.FileSystem;
259
260 const build = yield* FrameworkServer("Build", {
261 framework: config.framework,
262 target: config.target,
263 root: props.rootDir,
264 env: envRecord(props.env),
265 options: config.options,
266 memo: props.memo,
267 dev: props.dev,
268 });
269
270 if (isLocal) {
271 return {
272 url: build.url,
273 app: undefined,
274 service: undefined,
275 ip: undefined,
276 certificate: undefined,
277 } satisfies FrameworkSite;
278 }
279
280 // The build runs at APPLY time (`Website.Server` is a resource), so its
281 // attributes are Outputs here — derive every deploy input lazily and let
282 // the engine resolve them once the build has produced real paths. Reading
283 // `build.distDir` eagerly in the composite body would observe an Output
284 // proxy, not a string.
285 const buildOut = Output.mapEffect(
286 ([serverEntry, distDir]: [string | undefined, string | undefined]) =>
287 Effect.gen(function* () {
288 if (serverEntry === undefined || distDir === undefined) {
289 return yield* Effect.die(
290 new FrameworkSiteError({
291 framework: config.framework,
292 message: `The ${config.name} build produced no Node serve entry (serverModules[0]). The Node deploy target should write serve-node.mjs.`,
293 }),
294 );
295 }
296 const main = path.resolve(initialCwd, serverEntry);
297 if (!(yield* fs.exists(main).pipe(Effect.orElseSucceed(() => false)))) {
298 return yield* Effect.die(
299 new FrameworkSiteError({
300 framework: config.framework,
301 message: `The ${config.name} build produced no server entry at ${main}`,
302 }),
303 );
304 }
305 return { distDir: path.resolve(initialCwd, distDir), main };
306 }),
307 )(
308 Output.all(
309 build.serverEntry as unknown as Output.Output<string | undefined>,
310 build.distDir as unknown as Output.Output<string | undefined>,
311 ) as unknown as Output.Output<[string | undefined, string | undefined]>,
312 );
313 const main = Output.map(buildOut, (out) => out.main);
314
315 const extraFiles = Output.mapEffect((out: { distDir: string; main: string }) =>
316 packSiteExtraFiles(out.distDir, config.skipClientAssets === true ? "next" : "client"),
317 )(buildOut);
318
319 const app = props.app !== undefined ? yield* resolveRef(props.app) : yield* App("App");
320
321 const ip = yield* IpAssignment("Shared", {
322 app,
323 type: "shared_v4",
324 });
325
326 // SPA: hashed `/assets` at Tigris. HTML and unknown paths stay on
327 // origin (NodeServe `notFoundHandling: "spa"`). Intercepting `/` with
328 // Tigris hangs SPA fallbacks — Fly does not rewrite `/counter/42` to
329 // `index.html`.
330 let statics:
331 | Output.Output<
332 | Array<{
333 guestPath: string;
334 urlPrefix: string;
335 tigrisBucket?: string;
336 indexDocument?: string;
337 }>
338 | undefined
339 >
340 | undefined;
341 if (config.static?.spa === true) {
342 const clientDir = Output.map(
343 build.clientDir as unknown as Output.Output<string | undefined>,
344 (dir) => {
345 if (dir === undefined) {
346 throw new FrameworkSiteError({
347 framework: config.framework,
348 message: `The ${config.name} build produced no client assets directory`,
349 });
350 }
351 return path.resolve(initialCwd, dir);
352 },
353 );
354 const bucket = yield* Bucket("Assets", { public: true });
355 yield* AssetDeployment("Files", {
356 bucket,
357 sourcePath: clientDir as unknown as string,
358 purge: true,
359 });
360 statics = Output.mapEffect(([clientDir, bucketName]: [string, string]) =>
361 Effect.gen(function* () {
362 const assetsDir = path.join(clientDir, "assets");
363 const exists = yield* fs.exists(assetsDir).pipe(Effect.orElseSucceed(() => false));
364 return exists
365 ? [
366 {
367 guestPath: "/assets",
368 urlPrefix: "/assets",
369 tigrisBucket: bucketName,
370 },
371 ]
372 : undefined;
373 }),
374 )(
375 Output.all(
376 clientDir,
377 bucket.name as unknown as Output.Output<string>,
378 ) as unknown as Output.Output<[string, string]>,
379 );
380 }
381
382 const service = yield* Service("Service", {
383 app,
384 deploy: props.deploy,
385 shutdown: props.shutdown,
386 checks: props.checks,
387 services: props.services,
388 main: main as unknown as string,
389 port: DEFAULT_PORT,
390 // Node + nitro SSR needs more than the Machine default 256MB.
391 guest: { memoryMb: 512 },
392 isExternal: true,
393 env: props.env,
394 extraFiles: extraFiles as unknown as Array<{
395 source: string;
396 dest: string;
397 }>,
398 statics: statics as unknown as
399 | Array<{
400 guestPath: string;
401 urlPrefix: string;
402 tigrisBucket?: string;
403 indexDocument?: string;
404 }>
405 | undefined,
406 build:
407 config.install !== undefined && config.install.length > 0
408 ? { install: config.install }
409 : undefined,
410 });
411
412 const domainName = websiteDomainName(props.domain);
413 const certificate =
414 domainName !== undefined
415 ? yield* Certificate("Certificate", {
416 app,
417 hostname: domainName,
418 kind: "acme",
419 })
420 : undefined;
421 if (props.domain !== undefined && certificate !== undefined) {
422 yield* publishWebsiteDomainDns({ domain: props.domain, certificate, ip });
423 }
424
425 const url = domainName !== undefined ? `https://${domainName}` : app.url;
426
427 return { url, app, service, ip, certificate };
428 });
429
430 /**
431 * Shared implementation behind the Fly framework website composites:
432 * `Website.Server` runs the framework toolchain (dev sidecar / production
433 * build), then a live deploy hosts `serve-node.mjs` on a Fly.Service.
434 *
435 * Callers pipe `Namespace.push(id)` themselves (the composites do).
436 *
437 * Composite-level tagged errors (`FrameworkSiteError`, filesystem) are
438 * defects — `Alchemy.Stack` only admits `ConfigError` on the user
439 * effect, same as Cloudflare/AWS Website composites.
440 */
441 export const makeFrameworkSite = (
442 id: string,
443 props: FrameworkSiteProps,
444 config: FrameworkSiteConfig,
445 ) => runFrameworkSite(id, props, config).pipe(Effect.orDie);
446
447 /** Push {@link id} then run {@link makeFrameworkSite}. */
448 export const frameworkSite = (id: string, props: FrameworkSiteProps, config: FrameworkSiteConfig) =>
449 makeFrameworkSite(id, props, config).pipe(Namespace.push(id));