@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 338 lines 14.1 KB
Raw
1 import type { AstroInlineConfig, AstroIntegration } from "astro";
2 import type * as AstroNamespace from "astro";
3 import * as Effect from "effect/Effect";
4 import * as FileSystem from "effect/FileSystem";
5 import * as Layer from "effect/Layer";
6 import * as Path from "effect/Path";
7 import type * as ViteModule from "vite";
8 import * as FrameworkCore from "../core/index.ts";
9 import { NODE_ENVIRONMENTS } from "./environments.ts";
10 import {
11 DEFAULT_TARGET_SPECIFIER,
12 isAstroTarget,
13 type AstroTarget,
14 type AstroTargetInput,
15 } from "./Target.ts";
16
17 type AstroModule = typeof AstroNamespace;
18
19 /**
20 * Options for the Astro `Framework` integration. The deploy target is passed
21 * as a value (`target`), keeping this module platform-neutral: all
22 * platform-specific behavior (adapter/integration selection, bundler plugin
23 * injection, dev SSR execution) lives in the target module.
24 */
25 export interface AstroFrameworkOptions<TargetConfig = unknown> {
26 /**
27 * The deploy target: an `AstroTarget` value, a `(config) => AstroTarget`
28 * factory, or a module specifier resolved from the project's own
29 * `node_modules`. Defaults to this package's Cloudflare target module
30 * (`"@alchemy.run/frontend-frameworks/astro/cloudflare"`). Factories and specifiers are
31 * applied to {@link targetConfig}.
32 */
33 readonly target?: AstroTargetInput<TargetConfig> | undefined;
34 /**
35 * Target configuration passed to a target factory or specifier-loaded
36 * target module. Opaque to this module — its shape belongs to the target
37 * (Cloudflare: `{ worker?: CloudflareVitePluginOptions,
38 * sessionKVBindingName?: string }`). Unused when {@link target} is already
39 * a target *value*.
40 */
41 readonly targetConfig?: TargetConfig | undefined;
42 /**
43 * Extra Astro config merged into the in-memory `AstroInlineConfig`
44 * (`site`, `base`, `integrations`, `devToolbar`, `vite`, ...). The
45 * project's own `astro.config.*` file loads natively; this inline config
46 * is merged OVER it by astro (arrays like `integrations`/`vite.plugins`
47 * concatenate, scalars override). `root` is pinned; `output` is only set
48 * when passed here (so a config file's `output` — or astro's `"static"`
49 * default — is honored). Do not pass `adapter` — the deploy target
50 * provides it, and a user-declared adapter fails the build with an
51 * actionable error.
52 */
53 readonly astro?: AstroInlineConfig | undefined;
54 /**
55 * Path to an alternate Astro config file, resolved against {@link root}
56 * when relative (astro itself resolves a relative `configFile` against
57 * the process cwd, so this module anchors it to the project root before
58 * handing it over). Defaults to astro's own config discovery
59 * (`astro.config.*` in the project root).
60 */
61 readonly config?: string | undefined;
62 /** Project root. Defaults to the process working directory. */
63 readonly root?: string | undefined;
64 }
65
66 /** Inputs for {@link makeAstroInlineConfig} (exported for testing). */
67 export interface AstroConfigInputs {
68 /** Absolute project root. */
69 readonly root: string;
70 /**
71 * The deploy target's integration. Injected via `integrations` (after the
72 * user's) rather than `adapter`: it registers itself as the adapter at
73 * `astro:config:done`, where it also rejects a user-declared adapter with
74 * an actionable error.
75 */
76 readonly integration: AstroIntegration;
77 /** User Astro config merged in (its `vite.plugins` are preserved). */
78 readonly userConfig?: AstroInlineConfig | undefined;
79 /** Dev-server port (merged into `server.port`). */
80 readonly port?: number | undefined;
81 /** Dev-server host (merged into `server.host`). */
82 readonly host?: string | undefined;
83 /**
84 * Extra Vite plugins appended after the user's (e.g. the build-output
85 * collector).
86 */
87 readonly extraVitePlugins?: ReadonlyArray<ViteModule.Plugin> | undefined;
88 }
89
90 /**
91 * Build the in-memory `AstroInlineConfig` — the overlay astro merges OVER
92 * the project's own `astro.config.*` (which loads natively; `configFile`
93 * is left undiscovered-default unless the user overlay carries one, so a
94 * project without a config file falls back to a purely programmatic
95 * config). Astro's `resolveConfig` merge
96 * gives this inline config precedence: arrays (`integrations`,
97 * `vite.plugins`) concatenate after the file's, scalars override.
98 *
99 * - The deploy target's integration is appended to `integrations` (it
100 * registers itself as the adapter at `astro:config:done` and fails the
101 * build if the user config already declares an `adapter`).
102 * - `output` is NOT set unless the caller passes it explicitly: the inline
103 * config merges OVER the project's `astro.config.*`, so a default here
104 * would clobber the file's `output` (e.g. an explicit `"static"`). With
105 * neither source setting it, astro's own default (`"static"`, with
106 * per-route `prerender = false` opt-outs enabled by the adapter) applies.
107 * - User `vite.plugins` are preserved ahead of the collector.
108 */
109 export const makeAstroInlineConfig = (inputs: AstroConfigInputs): AstroInlineConfig => {
110 const user = inputs.userConfig;
111 const serverOverrides = {
112 ...(inputs.port !== undefined ? { port: inputs.port } : {}),
113 ...(inputs.host !== undefined ? { host: inputs.host } : {}),
114 };
115 const server: AstroInlineConfig["server"] =
116 Object.keys(serverOverrides).length === 0
117 ? user?.server
118 : typeof user?.server === "function"
119 ? (options) => ({
120 ...(user.server as (options: unknown) => object)(options),
121 ...serverOverrides,
122 })
123 : { ...user?.server, ...serverOverrides };
124 return {
125 logLevel: "warn",
126 ...user,
127 root: inputs.root,
128 integrations: [...(user?.integrations ?? []), inputs.integration],
129 server,
130 vite: {
131 ...user?.vite,
132 plugins: [...(user?.vite?.plugins ?? []), ...(inputs.extraVitePlugins ?? [])],
133 },
134 };
135 };
136
137 /**
138 * The Astro implementation of framework-core's `Framework` service.
139 *
140 * - `build` resolves the deploy target, then either delegates wholesale to
141 * `target.build` (when the target defines one) or runs astro's programmatic
142 * `build(AstroInlineConfig)` with the target's adapter integration and the
143 * shared build-output collector on the `ssr` environment (skipping astro's
144 * node-side `astro`/`prerender` environments), finishing with
145 * `applyDeployTargetFinish`. `serverModules[0]` is the ssr entry chunk
146 * (`server/entry.mjs`); `clientDirectory` is `dist/client`, captured as a
147 * path so prerendered HTML written after the Vite build rides along.
148 * - `dev` runs astro's `dev()` with the target's adapter integration; with
149 * the Cloudflare target the `ssr` environment executes inside workerd via
150 * the cloudflare-vite-plugin module runner, with in-memory bindings — no
151 * wrangler config anywhere. Closing the Scope stops the server.
152 *
153 * Returns the service implementation as an Effect (the alchemy-side
154 * `FrameworkModule` contract); use {@link layer} for the `Layer` form the
155 * e2e harness consumes.
156 */
157 export const make = <TargetConfig = unknown>(
158 options?: AstroFrameworkOptions<TargetConfig>,
159 ): Effect.Effect<FrameworkCore.Framework["Service"], never, FileSystem.FileSystem | Path.Path> =>
160 Effect.gen(function* () {
161 const fs = yield* FileSystem.FileSystem;
162 const path = yield* Path.Path;
163
164 const fail = (message: string) => (cause: unknown) =>
165 new FrameworkCore.FrameworkError({
166 framework: "astro",
167 message,
168 cause,
169 });
170
171 const failTarget = (error: FrameworkCore.DeployTargetError) =>
172 new FrameworkCore.FrameworkError({
173 framework: "astro",
174 message: error.message,
175 cause: error.cause ?? error,
176 });
177
178 // Astro's dev()/build() record telemetry events by default.
179 yield* Effect.sync(() => {
180 process.env.ASTRO_TELEMETRY_DISABLED ??= "1";
181 });
182
183 const resolveRoot = (override: string | undefined) =>
184 Effect.sync(() => path.resolve(override ?? options?.root ?? process.cwd()));
185
186 /**
187 * The user's inline Astro overlay with `config` resolved into
188 * `configFile`, anchored to the project root (astro resolves a
189 * relative `configFile` against the process cwd, not `root`).
190 */
191 const resolveUserAstro = (root: string): AstroInlineConfig | undefined =>
192 options?.config === undefined
193 ? options?.astro
194 : { ...options?.astro, configFile: path.resolve(root, options.config) };
195
196 const resolveTarget = (
197 root: string,
198 ): Effect.Effect<AstroTarget, FrameworkCore.FrameworkError> =>
199 FrameworkCore.resolveDeployTarget<AstroTarget, TargetConfig | undefined>(
200 root,
201 (options?.target ?? DEFAULT_TARGET_SPECIFIER) as FrameworkCore.DeployTargetInput<
202 AstroTarget,
203 TargetConfig | undefined
204 >,
205 options?.targetConfig,
206 ).pipe(
207 Effect.mapError(failTarget),
208 Effect.flatMap((target) =>
209 isAstroTarget(target)
210 ? Effect.succeed(target)
211 : Effect.fail(
212 fail(
213 "The resolved deploy target is not an AstroTarget: it must provide an " +
214 "`integration: () => AstroIntegration` hook",
215 )(undefined),
216 ),
217 ),
218 );
219
220 const loadAstro = (root: string): Effect.Effect<AstroModule, FrameworkCore.FrameworkError> =>
221 FrameworkCore.loadProjectModule<AstroModule>(root, "astro").pipe(
222 Effect.mapError(fail("Failed to load the project's astro")),
223 );
224
225 const makeConfig = (
226 root: string,
227 target: AstroTarget,
228 overrides?: Pick<AstroConfigInputs, "port" | "host" | "extraVitePlugins">,
229 ): AstroInlineConfig =>
230 makeAstroInlineConfig({
231 root,
232 integration: target.integration(),
233 userConfig: resolveUserAstro(root),
234 ...overrides,
235 });
236
237 return FrameworkCore.Framework.of({
238 build: Effect.fn(function* (buildOptions) {
239 const root = yield* resolveRoot(buildOptions?.root);
240 const target = yield* resolveTarget(root);
241 if (target.build !== undefined) {
242 // Wholesale build takeover: the target owns the entire
243 // production build (the OpenNext-style case). The inline Astro
244 // overlay rides along (with `config` already resolved into an
245 // absolute `configFile`) so a child-process build can
246 // reconstruct the framework with the same options.
247 return yield* target
248 .build({
249 root,
250 framework: "astro",
251 env: buildOptions?.env,
252 astro: resolveUserAstro(root),
253 })
254 .pipe(
255 Effect.provideService(FileSystem.FileSystem, fs),
256 Effect.provideService(Path.Path, path),
257 Effect.mapError(failTarget),
258 );
259 }
260 const astro = yield* loadAstro(root);
261 const collector = yield* FrameworkCore.makeBuildOutputCollector({
262 entryEnvironment: "ssr",
263 skipEnvironments: NODE_ENVIRONMENTS,
264 selectEntry: target.selectServerEntry,
265 }).pipe(Effect.provideService(FileSystem.FileSystem, fs));
266 const config = makeConfig(root, target, {
267 extraVitePlugins: [collector.plugin],
268 });
269 yield* Effect.tryPromise({
270 try: async () => await astro.build(config),
271 catch: fail("Failed to build"),
272 });
273 // Disk re-read: astro injects the serialized SSR manifest into the
274 // entry chunk on disk *after* the bundler finishes (the in-memory
275 // capture still contains the `@@ASTRO_MANIFEST_REPLACE@@`
276 // placeholder), and prunes the prerender-only chunks.
277 const output = yield* collector
278 .collect({ fromDisk: true })
279 .pipe(Effect.mapError((error) => fail(error.message)(error.cause)));
280 // The astro build is delivered in-memory (no on-disk entry handed
281 // over), so the finish context carries no `entry`.
282 return yield* FrameworkCore.applyDeployTargetFinish(target, output, {
283 root,
284 framework: "astro",
285 }).pipe(
286 Effect.provideService(FileSystem.FileSystem, fs),
287 Effect.provideService(Path.Path, path),
288 Effect.mapError(failTarget),
289 );
290 }),
291 dev: Effect.fn(function* (devOptions) {
292 const root = yield* resolveRoot(devOptions?.root);
293 const target = yield* resolveTarget(root);
294 const astro = yield* loadAstro(root);
295 // `port: 0` (true OS-assigned) when the Vite under Astro is
296 // >= 8.2.1, probed ephemeral port otherwise — see
297 // `resolveViteDevPort`. Astro's dev server runs on Astro's own
298 // Vite dependency, so the version is resolved from the astro
299 // package's directory, not the project root.
300 const viteVersion = yield* FrameworkCore.resolveProjectPackageDirectory(root, "astro").pipe(
301 Effect.flatMap((astroDirectory) =>
302 FrameworkCore.resolveInstalledPackageVersion(astroDirectory, "vite"),
303 ),
304 Effect.orElseSucceed(() => undefined),
305 );
306 const port = yield* FrameworkCore.resolveViteDevPort(viteVersion, devOptions?.port);
307 const config = makeConfig(root, target, {
308 port,
309 host: devOptions?.host,
310 });
311 const server = yield* Effect.acquireRelease(
312 Effect.tryPromise({
313 try: async () => await astro.dev(config),
314 catch: fail("Failed to start the astro dev server"),
315 }),
316 (server) => Effect.promise(async () => await server.stop()),
317 );
318 const url =
319 server.resolvedUrls?.local[0] ??
320 (typeof server.address.port === "number"
321 ? `http://localhost:${server.address.port}/`
322 : undefined);
323 if (url === undefined) {
324 return yield* fail("Could not determine the URL of the astro dev server")(undefined);
325 }
326 return { url };
327 }),
328 });
329 });
330
331 /**
332 * The `Layer` form of {@link make} — the shape the e2e harness's framework
333 * factory contract expects (`(options) => Layer<Framework>`).
334 */
335 export const layer = <TargetConfig = unknown>(
336 options?: AstroFrameworkOptions<TargetConfig>,
337 ): Layer.Layer<FrameworkCore.Framework, never, FileSystem.FileSystem | Path.Path> =>
338 Layer.effect(FrameworkCore.Framework, make(options));