sailfork / t3code-github / .repos/ alchemy-effect/ packages/ cloudflare/ src/ Workers/ ViteChildRunner.ts

import * as NodeV8 from "node:v8";
import { layerRuntime, registerHttpServer } from "@alchemy.run/cloudflare-runtime/core";
import { Artifacts, createArtifactStore, makeScopedArtifacts } from "alchemy/Artifacts";
import * as RpcServerEnvironment from "alchemy/Local/RpcServerEnvironment";
import { PlatformServices, runMain } from "alchemy/Util/PlatformServices";
import * as Effect from "effect/Effect";
import * as FetchHttpClient from "effect/http/FetchHttpClient";
import * as Layer from "effect/Layer";
import * as Match from "effect/Match";
import * as Stdio from "effect/Stdio";
import * as Stream from "effect/Stream";
import { CloudflareAuth } from "../Auth/AuthProvider.ts";
import * as CloudflareEnvironment from "../CloudflareEnvironment.ts";
import * as Credentials from "../Credentials.ts";
import { materializeRuntimeBindings } from "./RuntimeBindings.ts";
import { loadSource, SourceProviderError } from "./Source.ts";
import * as Vite from "./Sources/Vite.ts";
import {
  type ViteChildConfig,
  VITE_CHILD_READY_PREFIX,
  VITE_CHILD_READY_SUFFIX,
} from "./ViteChild.shared.ts";

const readConfig = Effect.gen(function* () {
  const stdio = yield* Stdio.Stdio;
  const chunks = yield* Stream.runCollect(stdio.stdin);
  const bytes = Buffer.concat(chunks);
  // A cross-runtime spawn (bun engine → node child) sends JSON because
  // bun's `v8.serialize` output is unreadable by real V8. Sniff the
  // encoding by the JSON marker: only JSON starts with `{` — node's V8
  // payloads start with 0xFF and bun's JSC serialization with its own
  // binary header, so same-runtime spawns fall through to deserialize.
  return (
    bytes[0] === 0x7b // "{"
      ? JSON.parse(bytes.toString("utf8"))
      : NodeV8.deserialize(bytes)
  ) as ViteChildConfig;
});

const program = Effect.scoped(
  Effect.gen(function* () {
    const config = yield* readConfig;
    const credentials = Credentials.fromAuthProvider().pipe(
      Layer.provideMerge(CloudflareEnvironment.fromProfile()),
      Layer.provide(CloudflareAuth),
    );
    const runtimeContext = yield* Layer.unwrap(
      Effect.gen(function* () {
        const environment = yield* CloudflareEnvironment.CloudflareEnvironment;
        return layerRuntime({
          api: { accountId: Effect.map(environment, (env) => env.accountId) },
          storage: { directory: config.storageDirectory },
        });
      }),
    ).pipe(Layer.provide(Layer.mergeAll(credentials, FetchHttpClient.layer)), Layer.build);
    // The non-runtime fields are consumed here; everything else in
    // `config.worker` is the runtime worker shape `viteDev` expects, so new
    // runtime fields flow through without being re-listed.
    const {
      compatibility,
      main,
      viteEnvironments,
      hasAssets,
      bindingDescriptors,
      devRemote,
      devAccess,
      ...runtimeWorker
    } = config.worker;
    const source = config.source;
    const provider = source
      ? yield* loadSource(source.descriptor).pipe(
          // `loadSource` is typed against the full `SourceServices` union
          // (which includes the per-run Artifacts cache the live provider
          // supplies); the dev child has no run-scoped cache, so hand the
          // module a fresh one.
          Effect.provideService(Artifacts, makeScopedArtifacts(createArtifactStore(), source.fqn)),
        )
      : undefined;
    const bindings = yield* materializeRuntimeBindings(
      {
        name: config.worker.name,
        env: config.env,
        hasAssets: hasAssets || provider?.devAssetsBinding === true,
        bindingDescriptors,
        devRemote,
        devAccess,
      },
      { accountId: config.accountId, selfUrl: config.publicUrl, stack: config.stack },
    );
    const viteHost = "127.0.0.1";
    // `viteDev` resolves `port: 0` per the loaded Vite: a true OS-assigned
    // random port on Vite >= 8.2.1 (vitejs/vite#23158), a probed ephemeral
    // port on older Vite.
    const vitePort = source ? undefined : 0;
    const url =
      source && provider
        ? yield* provider
            .dev({
              id: source.id,
              fqn: source.fqn,
              workerName: config.worker.name,
              compatibility,
              entry: { kind: "external" },
              stack: config.stack,
              env: config.env,
              // Dev hands `env` to the source unresolved; the Worker's own
              // URL is only substituted into a build's inlined env on deploy.
              selfUrl: undefined,
              extraOptions: undefined,
              assets: source.assets,
              worker: {
                bindings,
                durableObjectNamespaces: config.worker.durableObjectNamespaces,
                hyperdrives: config.worker.hyperdrives,
                queueConsumers: Effect.succeed(config.worker.queueConsumers),
                assets: config.worker.assets,
                options: {
                  workflows: runtimeWorker.workflows,
                  crons: runtimeWorker.crons,
                  tails: runtimeWorker.tails,
                  streamingTails: runtimeWorker.streamingTails,
                  cache: runtimeWorker.cache,
                  cf: runtimeWorker.cf,
                  zone: runtimeWorker.zone,
                  access: devAccess,
                  workerd: runtimeWorker.workerd,
                },
              },
              runtimeContext,
            })
            .pipe(
              Effect.flatMap((handle) =>
                Match.value(handle).pipe(
                  Match.when({ mode: "server" }, (handle) =>
                    (handle.serviceBinding === "http"
                      ? registerHttpServer(config.worker.name, handle.url).pipe(
                          Effect.provideContext(runtimeContext),
                        )
                      : Effect.void
                    ).pipe(Effect.as(handle.url.toString())),
                  ),
                  Match.when({ mode: "bundle" }, () =>
                    Effect.fail(
                      new SourceProviderError({
                        provider: source.descriptor.provider,
                        message:
                          "A source declared devMode 'server' but returned a bundle-mode dev handle.",
                      }),
                    ),
                  ),
                  Match.exhaustive,
                ),
              ),
            )
        : yield* Vite.viteDev(
            config.rootDir,
            config.env,
            {
              main,
              compatibilityDate: compatibility.date,
              compatibilityFlags: compatibility.flags,
              viteEnvironments,
              // `dev.access` populates the Worker's native `ctx.access`.
              worker: {
                ...runtimeWorker,
                bindings,
                publicUrl: config.publicUrl,
                access: devAccess,
              },
              context: runtimeContext,
              entrypoints: bindingDescriptors.flatMap((binding) =>
                binding.type === "self_service" && binding.entrypoint ? [binding.entrypoint] : [],
              ),
            },
            { host: viteHost, port: vitePort, strictPort: false },
          ).pipe(Effect.map((server) => server.resolvedUrls?.local[0]));
    if (!url) {
      return yield* Effect.die("Dev server child started without a local URL");
    }
    yield* Effect.sync(() => {
      process.stdout.write(`${VITE_CHILD_READY_PREFIX}${url}${VITE_CHILD_READY_SUFFIX}\n`);
    });
    return yield* Effect.never;
  }),
);

runMain(
  program.pipe(
    Effect.provide(RpcServerEnvironment.fromEnv().pipe(Layer.provideMerge(PlatformServices))),
  ),
);