sailfork / t3code-github / .repos/ alchemy-effect/ packages/ frontend-frameworks/ src/ vinext/ source.ts

import * as NodeCrypto from "node:crypto";
import { createRequire } from "node:module";
import nodePath from "node:path";
import { pathToFileURL } from "node:url";
import type {
  BindingHook,
  BindingServices,
  HyperdriveOrigin,
  Assets as RuntimeAssets,
  DurableObjectNamespace as RuntimeDurableObject,
  QueueConsumer as RuntimeQueueConsumer,
  RuntimeServices,
  RuntimeWorker,
} from "@alchemy.run/cloudflare-runtime/core";
/**
 * `@alchemy.run/frontend-frameworks/vinext/source` — alchemy Worker
 * source provider for vinext. Implements the `WorkerSourceModule`
 * contract structurally (no alchemy import).
 *
 * `build()` runs Vite's `createBuilder` in a child process with
 * `@alchemy.run/cloudflare-runtime/vite` injected (the
 * `vite-plugin-cloudflare:alchemy` presence plugin), then vinext prerender
 * and a platform-agnostic cache seed (`putText` into KV HTTP).
 * `hash()` is a project-tree memo. `dev()` is Vite's own server with
 * the same plugin stack.
 */
import cloudflare from "@alchemy.run/cloudflare-runtime/vite";
import type * as Context from "effect/Context";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import type { PlatformError } from "effect/PlatformError";
import * as Redacted from "effect/Redacted";
import type * as Scope from "effect/Scope";
import { resolveBuildEnv, runBuildChild } from "../core/BuildChild.ts";
import { toOutputFile, type BuildOutput } from "../core/BuildOutput.ts";
import { WORKER_ENTRY_PREFIX } from "../core/Collector.ts";
import { resolveViteDevPort } from "../core/DevPort.ts";
import { ModuleLoadError } from "../core/Loader.ts";
import { kvHttpNamespaceFromEnv, kvHttpSink } from "./cache/kv-http.ts";
import { makeVinextCachePlugin } from "./cache/plugin.ts";
import { seedPrerenderTo } from "./cache/seed.ts";
import {
  ALCHEMY_CLOUDFLARE_VITE_INJECTED,
  DEFAULT_WORKER_ENTRY,
  makeVinextPluginOptions,
} from "./cloudflare.ts";
import { runVinextPrerenderIfConfigured } from "./Prerender.ts";
import { VINEXT_CACHE_BINDING, VINEXT_KV_CACHE_BINDING } from "./PrerenderCache.ts";

const PROVIDER = "@alchemy.run/frontend-frameworks/vinext/source";

const VINEXT_SERVER_ENTRIES = ["dist/server/index.js", "dist/server/ssr/index.js"] as const;

const RSC_MANIFEST = {
  "virtual:vite-rsc/assets-manifest": "__vite_rsc_assets_manifest.js",
  "virtual:vite-rsc/environment-imports": "__vite_rsc_env_imports_manifest.js",
} as const;

const PACKAGE_VERSION: string = (
  createRequire(import.meta.url)("../../package.json") as { version: string }
).version;

// ─────────────────────────────────────────────────────────────────────
// Structural mirror of alchemy's Worker source contract
// ─────────────────────────────────────────────────────────────────────

export interface SourceHash {
  readonly bundle: string | undefined;
  readonly assets: string | undefined;
  readonly input: string | undefined;
  readonly additionalWorkspaces: Array<string> | undefined;
}

export interface BundleFile {
  readonly path: string;
  readonly content: string | Uint8Array;
  readonly hash: string;
}

export interface BundleOutput {
  readonly files: [BundleFile, ...Array<BundleFile>];
  readonly hash: string;
}

export interface AssetReadResult {
  directory: string;
  config: Record<string, unknown> | undefined;
  manifest: Record<string, { hash: string; size: number }>;
  _headers: string | undefined;
  _redirects: string | undefined;
  hash: string;
}

export interface SourceBuildOutput {
  readonly bundle: BundleOutput | undefined;
  readonly assets: AssetReadResult | undefined;
  readonly hash: SourceHash;
}

export interface SourceContext {
  readonly id: string;
  readonly workerName: string;
  readonly compatibility: {
    readonly date: string;
    readonly flags: Array<string>;
  };
  readonly entry:
    | { readonly kind: "external" }
    | { readonly kind: "effect"; readonly exports: Record<string, unknown> };
  readonly stack: { readonly name: string; readonly stage: string };
  readonly env: Record<string, unknown> | undefined;
  readonly extraOptions: unknown;
  readonly assets: unknown;
}

export interface DevContext extends SourceContext {
  readonly worker: {
    readonly bindings: Array<BindingHook<BindingServices>>;
    readonly durableObjectNamespaces: Array<RuntimeDurableObject & { uniqueKey: string }>;
    readonly hyperdrives: Record<string, Required<HyperdriveOrigin>>;
    readonly queueConsumers: Effect.Effect<Array<RuntimeQueueConsumer>>;
    readonly assets: RuntimeAssets | undefined;
    /**
     * The Worker's other runtime settings (crons, Workflows, tail consumers,
     * Cache API, `request.cf`, zone, Access), spread whole into the runtime
     * Worker.
     */
    readonly options: Pick<
      RuntimeWorker,
      "workflows" | "crons" | "tails" | "streamingTails" | "cache" | "cf" | "zone" | "access"
    >;
  };
  readonly runtimeContext: Context.Context<RuntimeServices>;
}

export interface ServerDevHandle {
  readonly mode: "server";
  readonly url: URL;
}

export class SourceProviderError extends Data.TaggedError(
  "Cloudflare.Workers.SourceProviderError",
)<{
  readonly provider: string;
  readonly message: string;
  readonly cause?: unknown;
}> {}

export type VinextSourceError = SourceProviderError | PlatformError | ModuleLoadError;
export type SourceRequirements = FileSystem.FileSystem | Path.Path;

export interface SourceProvider {
  readonly ownsAssets: boolean;
  readonly devAssetsBinding?: boolean;
  readonly build: (
    ctx: SourceContext,
  ) => Effect.Effect<SourceBuildOutput, VinextSourceError, SourceRequirements>;
  readonly hash: (
    ctx: SourceContext,
    previous: SourceHash | undefined,
  ) => Effect.Effect<Partial<SourceHash>, VinextSourceError, SourceRequirements>;
  readonly dev: (
    ctx: DevContext,
  ) => Effect.Effect<ServerDevHandle, VinextSourceError, SourceRequirements | Scope.Scope>;
}

export interface VinextMemoOptions {
  readonly include?: Array<string> | undefined;
  readonly exclude?: Array<string> | undefined;
  readonly lockfile?: boolean | undefined;
}

export interface VinextSourceOptions {
  readonly rootDir?: string | undefined;
  readonly main?: string | undefined;
  readonly memo?: VinextMemoOptions | undefined;
  readonly viteEnvironments?: {
    readonly entry?: string;
    readonly children?: ReadonlyArray<string>;
  };
}

export interface VinextBuildChildConfig {
  readonly rootDir: string;
  readonly main: string | undefined;
  readonly compatibilityDate: string;
  readonly compatibilityFlags: Array<string>;
  readonly viteEnvironments: { entry?: string; children?: ReadonlyArray<string> } | undefined;
}

const sha256 = (input: string | Uint8Array): string =>
  NodeCrypto.createHash("sha256").update(input).digest("hex");

const stableValue = (value: unknown): unknown => {
  if (Array.isArray(value)) return value.map(stableValue);
  if (value !== null && typeof value === "object" && value.constructor === Object) {
    return Object.fromEntries(
      Object.entries(value as Record<string, unknown>)
        .sort(([a], [b]) => a.localeCompare(b))
        .map(([key, nested]) => [key, stableValue(nested)]),
    );
  }
  return value;
};

const sha256Object = (value: unknown): string => sha256(JSON.stringify(stableValue(value)));

const isBindingMarker = (value: unknown): boolean =>
  typeof value === "object" && value !== null && "~alchemy/Kind" in value;

// ─────────────────────────────────────────────────────────────────────
// Hash / assets (same contract as waku/source)
// ─────────────────────────────────────────────────────────────────────

const LOCKFILE_NAMES = [
  "bun.lock",
  "bun.lockb",
  "package-lock.json",
  "pnpm-lock.yaml",
  "yarn.lock",
];

const escapeRegExpChar = (char: string): string =>
  /[.*+?^${}()|[\]\\]/.test(char) ? `\\${char}` : char;

const globBodyToRegExpSource = (glob: string): string => {
  let source = "";
  let i = 0;
  while (i < glob.length) {
    const char = glob[i]!;
    if (char === "*") {
      if (glob[i + 1] === "*") {
        if (glob[i + 2] === "/") {
          source += "(?:[^/]+/)*";
          i += 3;
        } else {
          source += ".*";
          i += 2;
        }
      } else {
        source += "[^/]*";
        i += 1;
      }
    } else if (char === "?") {
      source += "[^/]";
      i += 1;
    } else {
      source += escapeRegExpChar(char);
      i += 1;
    }
  }
  return source;
};

const compileIgnoreRule = (raw: string): RegExp | undefined => {
  let rule = raw.trim();
  if (rule.length === 0 || rule.startsWith("#") || rule.startsWith("!")) {
    return undefined;
  }
  if (rule.endsWith("/")) rule = rule.slice(0, -1);
  if (rule.length === 0) return undefined;
  const anchored = rule.includes("/");
  if (rule.startsWith("/")) rule = rule.slice(1);
  const body = globBodyToRegExpSource(rule);
  const prefix = anchored ? "^" : "^(?:.*/)?";
  return new RegExp(`${prefix}${body}(?:/.*)?

	
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	.repos/alchemy-effect/packages/frontend-frameworks/src/vinext/source.ts at main · sailfork/t3code-github · Sailfork
	
		
); }; const compileIgnoreRules = (rules: ReadonlyArray<string>): Array<RegExp> => rules.map(compileIgnoreRule).filter((regex): regex is RegExp => regex !== undefined); const compileIncludeGlobs = (globs: ReadonlyArray<string>): Array<RegExp> => globs.map((glob) => new RegExp(`^${globBodyToRegExpSource(glob)} .repos/alchemy-effect/packages/frontend-frameworks/src/vinext/source.ts at main · sailfork/t3code-github · Sailfork
)); const matchesAny = (regexes: ReadonlyArray<RegExp>, path: string): boolean => regexes.some((regex) => regex.test(path)); const findUp = Effect.fn(function* (startDir: string, filenames: ReadonlyArray<string>) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; let dir = startDir; for (;;) { for (const filename of filenames) { const candidate = path.join(dir, filename); if (yield* fs.exists(candidate)) return candidate; } const parent = path.dirname(dir); if (parent === dir) return undefined; dir = parent; } }); const readGitIgnoreRules = Effect.fn(function* (rootDir: string) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const chain: Array<Array<string>> = []; let dir = rootDir; for (;;) { const gitignore = path.join(dir, ".gitignore"); if (yield* fs.exists(gitignore)) { chain.unshift((yield* fs.readFileString(gitignore)).split("\n")); } if (yield* fs.exists(path.join(dir, ".git"))) break; const parent = path.dirname(dir); if (parent === dir) break; dir = parent; } return chain.flat(); }); interface ResolvedMemo { readonly include: Array<RegExp> | undefined; readonly exclude: Array<RegExp>; readonly lockfile: boolean; } const resolveMemo = Effect.fn(function* ( rootDir: string, distDir: string, memo: VinextMemoOptions | undefined, ) { const exclude = memo?.exclude !== undefined ? compileIgnoreRules(memo.exclude) : compileIgnoreRules(yield* readGitIgnoreRules(rootDir)); return { include: memo?.include !== undefined ? compileIncludeGlobs(memo.include) : undefined, exclude: [...compileIgnoreRules(["node_modules", ".git", `/${distDir}`]), ...exclude], lockfile: memo?.lockfile ?? !(memo?.include || memo?.exclude), } satisfies ResolvedMemo; }); const hashDirectory = Effect.fn(function* (rootDir: string, memo: ResolvedMemo) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const files: Array<string> = []; const walk: (dir: string, rel: string) => Effect.Effect<void, PlatformError> = Effect.fn( function* (dir: string, rel: string) { const entries = (yield* fs.readDirectory(dir)).sort(); for (const entry of entries) { const relPath = rel === "" ? entry : `${rel}/${entry}`; if (matchesAny(memo.exclude, relPath)) continue; const absPath = path.join(dir, entry); const stat = yield* fs.stat(absPath); if (stat.type === "Directory") { yield* walk(absPath, relPath); } else if (stat.type === "File") { if (memo.include !== undefined && !matchesAny(memo.include, relPath)) { continue; } files.push(relPath); } } }, ); yield* walk(rootDir, ""); if (memo.lockfile) { const lockfile = yield* findUp(rootDir, LOCKFILE_NAMES); if (lockfile !== undefined) { const relative = path.relative(rootDir, lockfile).replaceAll("\\", "/"); if (!files.includes(relative)) files.push(relative); } } const hashes = yield* Effect.forEach( files.sort(), Effect.fn(function* (file) { return `${file}:${sha256(yield* fs.readFile(path.join(rootDir, file)))}`; }), { concurrency: 16 }, ); return sha256Object(hashes); }); const hashVinextInput = Effect.fn(function* (params: { rootDir: string; memo: VinextMemoOptions | undefined; options: VinextSourceOptions; workspaces: Iterable<string>; }) { const path = yield* Path.Path; const memo = yield* resolveMemo(params.rootDir, "dist", params.memo); const workspaceMemo = yield* resolveMemo(params.rootDir, "dist", undefined); const [root, ...workspaceHashes] = yield* Effect.all( [ hashDirectory(params.rootDir, memo), ...Array.from(params.workspaces).map((workspace) => Effect.gen(function* () { const resolved = path.resolve(params.rootDir, workspace); const rules = yield* readGitIgnoreRules(resolved); const hash = yield* hashDirectory(resolved, { ...workspaceMemo, exclude: [...workspaceMemo.exclude, ...compileIgnoreRules(rules)], }); return `${path.relative(params.rootDir, resolved).replaceAll("\\", "/")}:${hash}`; }), ), ], { concurrency: 4 }, ); return { hash: sha256Object({ version: PACKAGE_VERSION, root, workspaces: workspaceHashes.sort(), options: { main: params.options.main, viteEnvironments: params.options.viteEnvironments, }, }), workspaces: Array.from(params.workspaces).map((workspace) => path.relative(params.rootDir, path.resolve(params.rootDir, workspace)).replaceAll("\\", "/"), ), }; }); const SPECIAL_ASSET_FILES = [".assetsignore", "_headers", "_redirects"]; const maybeReadString = Effect.fn(function* (file: string) { const fs = yield* FileSystem.FileSystem; return yield* fs.readFileString(file).pipe( Effect.catchIf( (error) => error._tag === "PlatformError" && error.reason._tag === "NotFound", () => Effect.undefined, ), ); }); const readClientAssets = Effect.fn(function* ( directory: string, config: Record<string, unknown> | undefined, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const [entries, ignoreFile, _headers, _redirects] = yield* Effect.all([ fs.readDirectory(directory, { recursive: true }), maybeReadString(path.join(directory, ".assetsignore")), maybeReadString(path.join(directory, "_headers")), maybeReadString(path.join(directory, "_redirects")), ]); const ignores = compileIgnoreRules([...SPECIAL_ASSET_FILES, ...(ignoreFile?.split("\n") ?? [])]); const manifest = new Map<string, { hash: string; size: number }>(); yield* Effect.forEach( entries, Effect.fn(function* (name) { const relPath = name.replaceAll("\\", "/"); if (matchesAny(ignores, relPath)) return; const file = path.join(directory, name); const stat = yield* fs.stat(file); if (stat.type !== "File") return; const content = yield* fs.readFile(file); manifest.set(relPath.startsWith("/") ? relPath : `/${relPath}`, { hash: sha256(content).slice(0, 32), size: Number(stat.size), }); }), { concurrency: 16 }, ); const sortedManifest = Object.fromEntries( Array.from(manifest.entries()).sort((a, b) => a[0].localeCompare(b[0])), ); return { directory, config, manifest: sortedManifest, _headers, _redirects, hash: sha256Object({ config, manifest: sortedManifest, _headers, _redirects, }), } satisfies AssetReadResult; }); const assetsConfigOf = (assets: unknown): Record<string, unknown> | undefined => { if (assets === undefined || assets === null || typeof assets !== "object") { return undefined; } const { directory: _d, hash: _h, ...config } = assets as Record<string, unknown>; return Object.keys(config).length > 0 ? config : undefined; }; // ───────────────────────────────────────────────────────────────────── // Vite createBuilder + output collection // ───────────────────────────────────────────────────────────────────── type ViteModule = typeof import("vite"); const loadVite = async (projectRoot: string): Promise<ViteModule> => { try { const require = createRequire(nodePath.join(projectRoot, "package.json")); return await import(/* @vite-ignore */ pathToFileURL(require.resolve("vite")).href); } catch { return await import("vite"); } }; const getDefine = (env: Record<string, unknown>) => Object.fromEntries( Object.entries(env).flatMap(([key, raw]) => { if (!key.startsWith("VITE_")) return []; const value = Redacted.isRedacted(raw) ? Redacted.value(raw) : raw; return [[`import.meta.env.${key}`, JSON.stringify(value)] as const]; }), ); const relativeJsImports = (code: string): readonly string[] => { const specs = new Set<string>(); for (const match of code.matchAll(/(?:from|import)\s*["'](\.\.?\/[^"']+\.js)["']/g)) { specs.add(match[1]!); } return [...specs]; }; interface EnvironmentLike { readonly name: string; readonly config: { readonly base: string; readonly root: string; readonly build: { readonly outDir: string }; }; } const makeOutputCollector = (entryEnvironment: string) => { let clientDirectory: string | undefined; let serverEntry: string | undefined; const serverChunks = new Map<string, { content: string | Uint8Array }>(); const maybeExternalWorkspaces = new Set<string>(); const fileName = (name: string, environment: EnvironmentLike) => { const outDir = environment.config.build.outDir; const relativeOutDir = nodePath.isAbsolute(outDir) ? nodePath.relative(environment.config.root, outDir) : outDir; return `${relativeOutDir.replaceAll("\\", "/")}/${name}`; }; const plugin = { name: "alchemy:vinext-build-output", sharedDuringBuild: true, async writeBundle( this: { environment: EnvironmentLike; getModuleIds: () => Iterable<string>; }, _opts: unknown, bundle: Record< string, { type: string; fileName: string; isEntry?: boolean; facadeModuleId?: string | null; code?: string; source?: string | Uint8Array; imports?: Array<string>; } >, ) { const root = nodePath.resolve(this.environment.config.root); for (const id of this.getModuleIds()) { if (!nodePath.isAbsolute(id) || id.includes("node_modules") || id.startsWith(root)) { continue; } maybeExternalWorkspaces.add(nodePath.dirname(id)); } if (this.environment.name === "client") { clientDirectory = nodePath.resolve(root, this.environment.config.build.outDir); return; } const files = Object.values(bundle); if (this.environment.name === entryEnvironment) { // Vinext's rsc environment can emit its own app entry alongside the // wrapped Worker main; only the latter is a valid Worker module. const entryChunk = files.find( (file) => file.type === "chunk" && file.isEntry && file.facadeModuleId?.startsWith(WORKER_ENTRY_PREFIX), ) ?? files.find((file) => file.type === "chunk" && file.isEntry); if (entryChunk) { serverEntry = fileName(entryChunk.fileName, this.environment); } } for (const file of files) { if (file.type === "chunk") { for (const spec of file.imports ?? []) { if (spec in RSC_MANIFEST) { const manifest = RSC_MANIFEST[spec as keyof typeof RSC_MANIFEST]; serverChunks.set(fileName(manifest, this.environment), { content: "", }); } } } // Vite's build metadata (`.vite/manifest.json`), not a Worker module. if (file.fileName.startsWith(".vite/")) continue; const name = fileName(file.fileName, this.environment); const content = file.type === "chunk" ? (file.code ?? "") : (file.source ?? ""); serverChunks.set(name, { content }); } }, }; return { plugin, snapshot: () => ({ clientDirectory, serverEntry, serverChunks, externalWorkspaces: maybeExternalWorkspaces, }), }; }; const readRscManifestsFromDisk = Effect.fn(function* ( root: string, chunks: Map<string, { content: string | Uint8Array }>, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; for (const [name, chunk] of chunks) { if (chunk.content !== "") continue; const filePath = path.join(root, name); if (yield* fs.exists(filePath)) { chunks.set(name, { content: yield* fs.readFile(filePath) }); } else { chunks.delete(name); } } }); /** * Vinext rewrites server chunks and writes sidecar modules (the action-owner * manifest, `vinext-client-assets.js`) after `writeBundle`, so re-read every * captured JS chunk from disk and follow its relative imports to pick up * modules that were never part of a bundle. */ const syncVinextServerModules = Effect.fn(function* ( root: string, chunks: Map<string, { content: string | Uint8Array }>, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const pending: string[] = [ ...VINEXT_SERVER_ENTRIES, ...[...chunks.keys()].filter((name) => /\.[mc]?js$/.test(name)), ]; const seen = new Set<string>(); while (pending.length > 0) { const bundlePath = pending.pop()!; if (seen.has(bundlePath)) continue; seen.add(bundlePath); const filePath = path.join(root, bundlePath); if (!(yield* fs.exists(filePath))) continue; const content = yield* fs.readFileString(filePath); chunks.set(bundlePath, { content }); const dir = nodePath.posix.dirname(bundlePath); for (const spec of relativeJsImports(content)) { const next = nodePath.posix.normalize(nodePath.posix.join(dir, spec)); if (!next.startsWith("dist/server/") || chunks.has(next)) continue; pending.push(next); } } }); const collectExternalWorkspaces = Effect.fn(function* (dirs: Iterable<string>) { const path = yield* Path.Path; const found = yield* Effect.forEach( dirs, (directory) => findUp(directory, ["package.json"]).pipe( Effect.map((file) => (file !== undefined ? path.dirname(file) : undefined)), ), { concurrency: "unbounded" }, ); return new Set(found.filter((dir): dir is string => dir !== undefined)); }); /** * Child-process vinext production build. `runBuildChild` sets cwd to the * project root before importing this module. */ export const buildInChild = (config: VinextBuildChildConfig) => Effect.gen(function* () { const path = yield* Path.Path; const root = path.resolve(config.rootDir); process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = "1"; const cachePlugin = yield* makeVinextCachePlugin(root, "kv"); const pluginOptions = makeVinextPluginOptions({ root, main: config.main, compatibilityDate: config.compatibilityDate, compatibilityFlags: config.compatibilityFlags, viteEnvironments: config.viteEnvironments, }); const collector = makeOutputCollector(pluginOptions.viteEnvironments?.entry ?? "rsc"); const vite = yield* Effect.promise(() => loadVite(root)); yield* Effect.promise(async () => { const builder = await vite.createBuilder( { root, plugins: [cachePlugin, cloudflare(pluginOptions), collector.plugin as never], logLevel: "warn", }, null, ); await builder.buildApp(); }); yield* runVinextPrerenderIfConfigured(root); const snap = collector.snapshot(); yield* readRscManifestsFromDisk(root, snap.serverChunks); yield* syncVinextServerModules(root, snap.serverChunks); if (snap.serverChunks.size === 0) { return { distDirectory: path.join(root, "dist"), clientDirectory: snap.clientDirectory, serverModules: undefined, externalWorkspaces: yield* collectExternalWorkspaces(snap.externalWorkspaces), } satisfies BuildOutput; } const names = Array.from(snap.serverChunks.keys()).sort((a, b) => { if (a === snap.serverEntry) return -1; if (b === snap.serverEntry) return 1; return a.localeCompare(b); }); const serverModules = yield* Effect.forEach(names, (name) => { const chunk = snap.serverChunks.get(name)!; return toOutputFile(name, chunk.content); }); return { distDirectory: path.join(root, "dist"), clientDirectory: snap.clientDirectory, serverModules, externalWorkspaces: yield* collectExternalWorkspaces(snap.externalWorkspaces), } satisfies BuildOutput; }); const resolveVinextCacheEnv = (env: Record<string, unknown>) => Effect.gen(function* () { const resolved = { ...env }; for (const key of [VINEXT_KV_CACHE_BINDING, VINEXT_CACHE_BINDING]) { const value = env[key]; if (value == null || isBindingMarker(value)) continue; // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- cache bindings are pre-resolved resource Effects resolved[key] = Effect.isEffect(value) ? yield* value as Effect.Effect<unknown> : value; } return resolved; }); /** * Same `seedPrerenderTo(sink.putText)` as Redis / S3. The Worker provider * layer supplies the distilled KV HTTP client. Closed as `Effect<void>` * so the source contract stays `SourceRequirements`. */ const seedVinextPrerenderCache = ( rootDir: string, env: Record<string, unknown>, ): Effect.Effect<void> => // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- closed so the source contract stays SourceRequirements, see JSDoc Effect.gen(function* () { const namespace = kvHttpNamespaceFromEnv(env); if (namespace === undefined) return; const path = yield* Path.Path; yield* seedPrerenderTo(kvHttpSink(namespace), { rootDir: path.resolve(rootDir), label: "Cloudflare KV", }).pipe( Effect.mapError( (cause) => new SourceProviderError({ provider: PROVIDER, message: "Failed to seed the vinext prerender cache.", cause, }), ), ); }) as Effect.Effect<void>; export const makeVinextSourceProvider = (options: VinextSourceOptions): SourceProvider => { const rootDirOf = (path: Path.Path): string => options.rootDir !== undefined ? path.resolve(options.rootDir) : process.cwd(); return { ownsAssets: true, // Dev runs the Worker in workerd with the Vite plugin's assets service. devAssetsBinding: true, build: Effect.fn(function* (ctx) { const path = yield* Path.Path; const rootDir = rootDirOf(path); const output = yield* runBuildChild({ runtime: "node", module: import.meta.url, rootDir, framework: "vinext", env: resolveBuildEnv(ctx.env), config: { rootDir, main: options.main, compatibilityDate: ctx.compatibility.date, compatibilityFlags: ctx.compatibility.flags, viteEnvironments: options.viteEnvironments, } satisfies VinextBuildChildConfig, }).pipe( Effect.mapError( (error) => new SourceProviderError({ provider: PROVIDER, message: "vinext build failed", cause: error.cause ?? error, }), ), ); if (output.serverModules === undefined || output.serverModules.length === 0) { return yield* new SourceProviderError({ provider: PROVIDER, message: "vinext build produced no server modules", }); } const files = output.serverModules.map((file) => ({ path: file.name.replaceAll("\\", "/"), content: file.content, hash: file.hash, })) as [BundleFile, ...Array<BundleFile>]; const bundle: BundleOutput = { files, hash: sha256Object(files.map((file) => [file.path, file.hash])), }; const [assets, input] = yield* Effect.all( [ output.clientDirectory !== undefined ? readClientAssets(output.clientDirectory, assetsConfigOf(ctx.assets)) : Effect.undefined, hashVinextInput({ rootDir, memo: options.memo, options, workspaces: output.externalWorkspaces, }), ], { concurrency: "unbounded" }, ); yield* seedVinextPrerenderCache(rootDir, yield* resolveVinextCacheEnv(ctx.env ?? {})); return { bundle, assets, hash: { bundle: bundle.hash, assets: assets?.hash, input: input.hash, additionalWorkspaces: input.workspaces, }, }; }), hash: Effect.fn(function* (_ctx, previous) { const path = yield* Path.Path; const input = yield* hashVinextInput({ rootDir: rootDirOf(path), memo: options.memo, options, workspaces: previous?.additionalWorkspaces ?? [], }); return { input: input.hash, additionalWorkspaces: input.workspaces }; }), dev: Effect.fn(function* (ctx) { const path = yield* Path.Path; const rootDir = rootDirOf(path); process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = "1"; const cachePlugin = yield* makeVinextCachePlugin(rootDir, "kv"); const vite = yield* Effect.promise(() => loadVite(rootDir)); const port = yield* resolveViteDevPort(vite.version).pipe( Effect.mapError( (error) => new SourceProviderError({ provider: PROVIDER, message: "Failed to allocate a vinext dev port", cause: error, }), ), ); const pluginOptions = makeVinextPluginOptions({ root: rootDir, main: options.main ?? DEFAULT_WORKER_ENTRY, compatibilityDate: ctx.compatibility.date, compatibilityFlags: ctx.compatibility.flags, viteEnvironments: options.viteEnvironments, worker: { ...ctx.worker.options, name: ctx.workerName, bindings: ctx.worker.bindings, durableObjectNamespaces: ctx.worker.durableObjectNamespaces, hyperdrives: ctx.worker.hyperdrives, queueConsumers: yield* ctx.worker.queueConsumers, assets: ctx.worker.assets, }, context: ctx.runtimeContext, }); const server = yield* Effect.acquireRelease( Effect.promise(async () => { const devServer = await vite.createServer({ root: rootDir, define: getDefine(ctx.env ?? {}), plugins: [cachePlugin, cloudflare(pluginOptions)], server: { port, strictPort: false }, }); await devServer.listen(); return devServer; }), (devServer) => Effect.promise(() => devServer.close()), ); const local = server.resolvedUrls?.local[0]; if (!local) { return yield* new SourceProviderError({ provider: PROVIDER, message: "vinext dev server started without a local URL", }); } return { mode: "server", url: new URL(local) } satisfies ServerDevHandle; }), }; }; const sourceModule = { make: (options: unknown): Effect.Effect<SourceProvider, SourceProviderError> => { if (options !== undefined && (typeof options !== "object" || options === null)) { return Effect.fail( new SourceProviderError({ provider: PROVIDER, message: `Invalid options for ${PROVIDER}: expected an object, got ${typeof options}`, }), ); } return Effect.succeed(makeVinextSourceProvider((options ?? {}) as VinextSourceOptions)); }, }; export default sourceModule;
.repos/alchemy-effect/packages/frontend-frameworks/src/vinext/source.ts at main · sailfork/t3code-github · Sailfork
);\n};\n\nconst compileIgnoreRules = (rules: ReadonlyArray\u003cstring>): Array\u003cRegExp> =>\n rules.map(compileIgnoreRule).filter((regex): regex is RegExp => regex !== undefined);\n\nconst compileIncludeGlobs = (globs: ReadonlyArray\u003cstring>): Array\u003cRegExp> =>\n globs.map((glob) => new RegExp(`^${globBodyToRegExpSource(glob)} .repos/alchemy-effect/packages/frontend-frameworks/src/vinext/source.ts at main · sailfork/t3code-github · Sailfork
));\n\nconst matchesAny = (regexes: ReadonlyArray\u003cRegExp>, path: string): boolean =>\n regexes.some((regex) => regex.test(path));\n\nconst findUp = Effect.fn(function* (startDir: string, filenames: ReadonlyArray\u003cstring>) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n let dir = startDir;\n for (;;) {\n for (const filename of filenames) {\n const candidate = path.join(dir, filename);\n if (yield* fs.exists(candidate)) return candidate;\n }\n const parent = path.dirname(dir);\n if (parent === dir) return undefined;\n dir = parent;\n }\n});\n\nconst readGitIgnoreRules = Effect.fn(function* (rootDir: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const chain: Array\u003cArray\u003cstring>> = [];\n let dir = rootDir;\n for (;;) {\n const gitignore = path.join(dir, \".gitignore\");\n if (yield* fs.exists(gitignore)) {\n chain.unshift((yield* fs.readFileString(gitignore)).split(\"\\n\"));\n }\n if (yield* fs.exists(path.join(dir, \".git\"))) break;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return chain.flat();\n});\n\ninterface ResolvedMemo {\n readonly include: Array\u003cRegExp> | undefined;\n readonly exclude: Array\u003cRegExp>;\n readonly lockfile: boolean;\n}\n\nconst resolveMemo = Effect.fn(function* (\n rootDir: string,\n distDir: string,\n memo: VinextMemoOptions | undefined,\n) {\n const exclude =\n memo?.exclude !== undefined\n ? compileIgnoreRules(memo.exclude)\n : compileIgnoreRules(yield* readGitIgnoreRules(rootDir));\n return {\n include: memo?.include !== undefined ? compileIncludeGlobs(memo.include) : undefined,\n exclude: [...compileIgnoreRules([\"node_modules\", \".git\", `/${distDir}`]), ...exclude],\n lockfile: memo?.lockfile ?? !(memo?.include || memo?.exclude),\n } satisfies ResolvedMemo;\n});\n\nconst hashDirectory = Effect.fn(function* (rootDir: string, memo: ResolvedMemo) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const files: Array\u003cstring> = [];\n const walk: (dir: string, rel: string) => Effect.Effect\u003cvoid, PlatformError> = Effect.fn(\n function* (dir: string, rel: string) {\n const entries = (yield* fs.readDirectory(dir)).sort();\n for (const entry of entries) {\n const relPath = rel === \"\" ? entry : `${rel}/${entry}`;\n if (matchesAny(memo.exclude, relPath)) continue;\n const absPath = path.join(dir, entry);\n const stat = yield* fs.stat(absPath);\n if (stat.type === \"Directory\") {\n yield* walk(absPath, relPath);\n } else if (stat.type === \"File\") {\n if (memo.include !== undefined && !matchesAny(memo.include, relPath)) {\n continue;\n }\n files.push(relPath);\n }\n }\n },\n );\n yield* walk(rootDir, \"\");\n if (memo.lockfile) {\n const lockfile = yield* findUp(rootDir, LOCKFILE_NAMES);\n if (lockfile !== undefined) {\n const relative = path.relative(rootDir, lockfile).replaceAll(\"\\\\\", \"/\");\n if (!files.includes(relative)) files.push(relative);\n }\n }\n const hashes = yield* Effect.forEach(\n files.sort(),\n Effect.fn(function* (file) {\n return `${file}:${sha256(yield* fs.readFile(path.join(rootDir, file)))}`;\n }),\n { concurrency: 16 },\n );\n return sha256Object(hashes);\n});\n\nconst hashVinextInput = Effect.fn(function* (params: {\n rootDir: string;\n memo: VinextMemoOptions | undefined;\n options: VinextSourceOptions;\n workspaces: Iterable\u003cstring>;\n}) {\n const path = yield* Path.Path;\n const memo = yield* resolveMemo(params.rootDir, \"dist\", params.memo);\n const workspaceMemo = yield* resolveMemo(params.rootDir, \"dist\", undefined);\n const [root, ...workspaceHashes] = yield* Effect.all(\n [\n hashDirectory(params.rootDir, memo),\n ...Array.from(params.workspaces).map((workspace) =>\n Effect.gen(function* () {\n const resolved = path.resolve(params.rootDir, workspace);\n const rules = yield* readGitIgnoreRules(resolved);\n const hash = yield* hashDirectory(resolved, {\n ...workspaceMemo,\n exclude: [...workspaceMemo.exclude, ...compileIgnoreRules(rules)],\n });\n return `${path.relative(params.rootDir, resolved).replaceAll(\"\\\\\", \"/\")}:${hash}`;\n }),\n ),\n ],\n { concurrency: 4 },\n );\n return {\n hash: sha256Object({\n version: PACKAGE_VERSION,\n root,\n workspaces: workspaceHashes.sort(),\n options: {\n main: params.options.main,\n viteEnvironments: params.options.viteEnvironments,\n },\n }),\n workspaces: Array.from(params.workspaces).map((workspace) =>\n path.relative(params.rootDir, path.resolve(params.rootDir, workspace)).replaceAll(\"\\\\\", \"/\"),\n ),\n };\n});\n\nconst SPECIAL_ASSET_FILES = [\".assetsignore\", \"_headers\", \"_redirects\"];\n\nconst maybeReadString = Effect.fn(function* (file: string) {\n const fs = yield* FileSystem.FileSystem;\n return yield* fs.readFileString(file).pipe(\n Effect.catchIf(\n (error) => error._tag === \"PlatformError\" && error.reason._tag === \"NotFound\",\n () => Effect.undefined,\n ),\n );\n});\n\nconst readClientAssets = Effect.fn(function* (\n directory: string,\n config: Record\u003cstring, unknown> | undefined,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const [entries, ignoreFile, _headers, _redirects] = yield* Effect.all([\n fs.readDirectory(directory, { recursive: true }),\n maybeReadString(path.join(directory, \".assetsignore\")),\n maybeReadString(path.join(directory, \"_headers\")),\n maybeReadString(path.join(directory, \"_redirects\")),\n ]);\n const ignores = compileIgnoreRules([...SPECIAL_ASSET_FILES, ...(ignoreFile?.split(\"\\n\") ?? [])]);\n const manifest = new Map\u003cstring, { hash: string; size: number }>();\n yield* Effect.forEach(\n entries,\n Effect.fn(function* (name) {\n const relPath = name.replaceAll(\"\\\\\", \"/\");\n if (matchesAny(ignores, relPath)) return;\n const file = path.join(directory, name);\n const stat = yield* fs.stat(file);\n if (stat.type !== \"File\") return;\n const content = yield* fs.readFile(file);\n manifest.set(relPath.startsWith(\"/\") ? relPath : `/${relPath}`, {\n hash: sha256(content).slice(0, 32),\n size: Number(stat.size),\n });\n }),\n { concurrency: 16 },\n );\n const sortedManifest = Object.fromEntries(\n Array.from(manifest.entries()).sort((a, b) => a[0].localeCompare(b[0])),\n );\n return {\n directory,\n config,\n manifest: sortedManifest,\n _headers,\n _redirects,\n hash: sha256Object({\n config,\n manifest: sortedManifest,\n _headers,\n _redirects,\n }),\n } satisfies AssetReadResult;\n});\n\nconst assetsConfigOf = (assets: unknown): Record\u003cstring, unknown> | undefined => {\n if (assets === undefined || assets === null || typeof assets !== \"object\") {\n return undefined;\n }\n const { directory: _d, hash: _h, ...config } = assets as Record\u003cstring, unknown>;\n return Object.keys(config).length > 0 ? config : undefined;\n};\n\n// ─────────────────────────────────────────────────────────────────────\n// Vite createBuilder + output collection\n// ─────────────────────────────────────────────────────────────────────\n\ntype ViteModule = typeof import(\"vite\");\n\nconst loadVite = async (projectRoot: string): Promise\u003cViteModule> => {\n try {\n const require = createRequire(nodePath.join(projectRoot, \"package.json\"));\n return await import(/* @vite-ignore */ pathToFileURL(require.resolve(\"vite\")).href);\n } catch {\n return await import(\"vite\");\n }\n};\n\nconst getDefine = (env: Record\u003cstring, unknown>) =>\n Object.fromEntries(\n Object.entries(env).flatMap(([key, raw]) => {\n if (!key.startsWith(\"VITE_\")) return [];\n const value = Redacted.isRedacted(raw) ? Redacted.value(raw) : raw;\n return [[`import.meta.env.${key}`, JSON.stringify(value)] as const];\n }),\n );\n\nconst relativeJsImports = (code: string): readonly string[] => {\n const specs = new Set\u003cstring>();\n for (const match of code.matchAll(/(?:from|import)\\s*[\"'](\\.\\.?\\/[^\"']+\\.js)[\"']/g)) {\n specs.add(match[1]!);\n }\n return [...specs];\n};\n\ninterface EnvironmentLike {\n readonly name: string;\n readonly config: {\n readonly base: string;\n readonly root: string;\n readonly build: { readonly outDir: string };\n };\n}\n\nconst makeOutputCollector = (entryEnvironment: string) => {\n let clientDirectory: string | undefined;\n let serverEntry: string | undefined;\n const serverChunks = new Map\u003cstring, { content: string | Uint8Array }>();\n const maybeExternalWorkspaces = new Set\u003cstring>();\n\n const fileName = (name: string, environment: EnvironmentLike) => {\n const outDir = environment.config.build.outDir;\n const relativeOutDir = nodePath.isAbsolute(outDir)\n ? nodePath.relative(environment.config.root, outDir)\n : outDir;\n return `${relativeOutDir.replaceAll(\"\\\\\", \"/\")}/${name}`;\n };\n\n const plugin = {\n name: \"alchemy:vinext-build-output\",\n sharedDuringBuild: true,\n async writeBundle(\n this: {\n environment: EnvironmentLike;\n getModuleIds: () => Iterable\u003cstring>;\n },\n _opts: unknown,\n bundle: Record\u003c\n string,\n {\n type: string;\n fileName: string;\n isEntry?: boolean;\n facadeModuleId?: string | null;\n code?: string;\n source?: string | Uint8Array;\n imports?: Array\u003cstring>;\n }\n >,\n ) {\n const root = nodePath.resolve(this.environment.config.root);\n for (const id of this.getModuleIds()) {\n if (!nodePath.isAbsolute(id) || id.includes(\"node_modules\") || id.startsWith(root)) {\n continue;\n }\n maybeExternalWorkspaces.add(nodePath.dirname(id));\n }\n if (this.environment.name === \"client\") {\n clientDirectory = nodePath.resolve(root, this.environment.config.build.outDir);\n return;\n }\n const files = Object.values(bundle);\n if (this.environment.name === entryEnvironment) {\n // Vinext's rsc environment can emit its own app entry alongside the\n // wrapped Worker main; only the latter is a valid Worker module.\n const entryChunk =\n files.find(\n (file) =>\n file.type === \"chunk\" &&\n file.isEntry &&\n file.facadeModuleId?.startsWith(WORKER_ENTRY_PREFIX),\n ) ?? files.find((file) => file.type === \"chunk\" && file.isEntry);\n if (entryChunk) {\n serverEntry = fileName(entryChunk.fileName, this.environment);\n }\n }\n for (const file of files) {\n if (file.type === \"chunk\") {\n for (const spec of file.imports ?? []) {\n if (spec in RSC_MANIFEST) {\n const manifest = RSC_MANIFEST[spec as keyof typeof RSC_MANIFEST];\n serverChunks.set(fileName(manifest, this.environment), {\n content: \"\",\n });\n }\n }\n }\n // Vite's build metadata (`.vite/manifest.json`), not a Worker module.\n if (file.fileName.startsWith(\".vite/\")) continue;\n const name = fileName(file.fileName, this.environment);\n const content = file.type === \"chunk\" ? (file.code ?? \"\") : (file.source ?? \"\");\n serverChunks.set(name, { content });\n }\n },\n };\n\n return {\n plugin,\n snapshot: () => ({\n clientDirectory,\n serverEntry,\n serverChunks,\n externalWorkspaces: maybeExternalWorkspaces,\n }),\n };\n};\n\nconst readRscManifestsFromDisk = Effect.fn(function* (\n root: string,\n chunks: Map\u003cstring, { content: string | Uint8Array }>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n for (const [name, chunk] of chunks) {\n if (chunk.content !== \"\") continue;\n const filePath = path.join(root, name);\n if (yield* fs.exists(filePath)) {\n chunks.set(name, { content: yield* fs.readFile(filePath) });\n } else {\n chunks.delete(name);\n }\n }\n});\n\n/**\n * Vinext rewrites server chunks and writes sidecar modules (the action-owner\n * manifest, `vinext-client-assets.js`) after `writeBundle`, so re-read every\n * captured JS chunk from disk and follow its relative imports to pick up\n * modules that were never part of a bundle.\n */\nconst syncVinextServerModules = Effect.fn(function* (\n root: string,\n chunks: Map\u003cstring, { content: string | Uint8Array }>,\n) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const pending: string[] = [\n ...VINEXT_SERVER_ENTRIES,\n ...[...chunks.keys()].filter((name) => /\\.[mc]?js$/.test(name)),\n ];\n const seen = new Set\u003cstring>();\n while (pending.length > 0) {\n const bundlePath = pending.pop()!;\n if (seen.has(bundlePath)) continue;\n seen.add(bundlePath);\n const filePath = path.join(root, bundlePath);\n if (!(yield* fs.exists(filePath))) continue;\n const content = yield* fs.readFileString(filePath);\n chunks.set(bundlePath, { content });\n const dir = nodePath.posix.dirname(bundlePath);\n for (const spec of relativeJsImports(content)) {\n const next = nodePath.posix.normalize(nodePath.posix.join(dir, spec));\n if (!next.startsWith(\"dist/server/\") || chunks.has(next)) continue;\n pending.push(next);\n }\n }\n});\n\nconst collectExternalWorkspaces = Effect.fn(function* (dirs: Iterable\u003cstring>) {\n const path = yield* Path.Path;\n const found = yield* Effect.forEach(\n dirs,\n (directory) =>\n findUp(directory, [\"package.json\"]).pipe(\n Effect.map((file) => (file !== undefined ? path.dirname(file) : undefined)),\n ),\n { concurrency: \"unbounded\" },\n );\n return new Set(found.filter((dir): dir is string => dir !== undefined));\n});\n\n/**\n * Child-process vinext production build. `runBuildChild` sets cwd to the\n * project root before importing this module.\n */\nexport const buildInChild = (config: VinextBuildChildConfig) =>\n Effect.gen(function* () {\n const path = yield* Path.Path;\n const root = path.resolve(config.rootDir);\n process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = \"1\";\n const cachePlugin = yield* makeVinextCachePlugin(root, \"kv\");\n const pluginOptions = makeVinextPluginOptions({\n root,\n main: config.main,\n compatibilityDate: config.compatibilityDate,\n compatibilityFlags: config.compatibilityFlags,\n viteEnvironments: config.viteEnvironments,\n });\n const collector = makeOutputCollector(pluginOptions.viteEnvironments?.entry ?? \"rsc\");\n const vite = yield* Effect.promise(() => loadVite(root));\n yield* Effect.promise(async () => {\n const builder = await vite.createBuilder(\n {\n root,\n plugins: [cachePlugin, cloudflare(pluginOptions), collector.plugin as never],\n logLevel: \"warn\",\n },\n null,\n );\n await builder.buildApp();\n });\n yield* runVinextPrerenderIfConfigured(root);\n const snap = collector.snapshot();\n yield* readRscManifestsFromDisk(root, snap.serverChunks);\n yield* syncVinextServerModules(root, snap.serverChunks);\n if (snap.serverChunks.size === 0) {\n return {\n distDirectory: path.join(root, \"dist\"),\n clientDirectory: snap.clientDirectory,\n serverModules: undefined,\n externalWorkspaces: yield* collectExternalWorkspaces(snap.externalWorkspaces),\n } satisfies BuildOutput;\n }\n const names = Array.from(snap.serverChunks.keys()).sort((a, b) => {\n if (a === snap.serverEntry) return -1;\n if (b === snap.serverEntry) return 1;\n return a.localeCompare(b);\n });\n const serverModules = yield* Effect.forEach(names, (name) => {\n const chunk = snap.serverChunks.get(name)!;\n return toOutputFile(name, chunk.content);\n });\n return {\n distDirectory: path.join(root, \"dist\"),\n clientDirectory: snap.clientDirectory,\n serverModules,\n externalWorkspaces: yield* collectExternalWorkspaces(snap.externalWorkspaces),\n } satisfies BuildOutput;\n });\n\nconst resolveVinextCacheEnv = (env: Record\u003cstring, unknown>) =>\n Effect.gen(function* () {\n const resolved = { ...env };\n for (const key of [VINEXT_KV_CACHE_BINDING, VINEXT_CACHE_BINDING]) {\n const value = env[key];\n if (value == null || isBindingMarker(value)) continue;\n // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- cache bindings are pre-resolved resource Effects\n resolved[key] = Effect.isEffect(value) ? yield* value as Effect.Effect\u003cunknown> : value;\n }\n return resolved;\n });\n\n/**\n * Same `seedPrerenderTo(sink.putText)` as Redis / S3. The Worker provider\n * layer supplies the distilled KV HTTP client. Closed as `Effect\u003cvoid>`\n * so the source contract stays `SourceRequirements`.\n */\nconst seedVinextPrerenderCache = (\n rootDir: string,\n env: Record\u003cstring, unknown>,\n): Effect.Effect\u003cvoid> =>\n // oxlint-disable-next-line effecttsgo/unsafe-effect-type-assertion -- closed so the source contract stays SourceRequirements, see JSDoc\n Effect.gen(function* () {\n const namespace = kvHttpNamespaceFromEnv(env);\n if (namespace === undefined) return;\n const path = yield* Path.Path;\n yield* seedPrerenderTo(kvHttpSink(namespace), {\n rootDir: path.resolve(rootDir),\n label: \"Cloudflare KV\",\n }).pipe(\n Effect.mapError(\n (cause) =>\n new SourceProviderError({\n provider: PROVIDER,\n message: \"Failed to seed the vinext prerender cache.\",\n cause,\n }),\n ),\n );\n }) as Effect.Effect\u003cvoid>;\n\nexport const makeVinextSourceProvider = (options: VinextSourceOptions): SourceProvider => {\n const rootDirOf = (path: Path.Path): string =>\n options.rootDir !== undefined ? path.resolve(options.rootDir) : process.cwd();\n\n return {\n ownsAssets: true,\n // Dev runs the Worker in workerd with the Vite plugin's assets service.\n devAssetsBinding: true,\n build: Effect.fn(function* (ctx) {\n const path = yield* Path.Path;\n const rootDir = rootDirOf(path);\n const output = yield* runBuildChild({\n runtime: \"node\",\n module: import.meta.url,\n rootDir,\n framework: \"vinext\",\n env: resolveBuildEnv(ctx.env),\n config: {\n rootDir,\n main: options.main,\n compatibilityDate: ctx.compatibility.date,\n compatibilityFlags: ctx.compatibility.flags,\n viteEnvironments: options.viteEnvironments,\n } satisfies VinextBuildChildConfig,\n }).pipe(\n Effect.mapError(\n (error) =>\n new SourceProviderError({\n provider: PROVIDER,\n message: \"vinext build failed\",\n cause: error.cause ?? error,\n }),\n ),\n );\n if (output.serverModules === undefined || output.serverModules.length === 0) {\n return yield* new SourceProviderError({\n provider: PROVIDER,\n message: \"vinext build produced no server modules\",\n });\n }\n const files = output.serverModules.map((file) => ({\n path: file.name.replaceAll(\"\\\\\", \"/\"),\n content: file.content,\n hash: file.hash,\n })) as [BundleFile, ...Array\u003cBundleFile>];\n const bundle: BundleOutput = {\n files,\n hash: sha256Object(files.map((file) => [file.path, file.hash])),\n };\n const [assets, input] = yield* Effect.all(\n [\n output.clientDirectory !== undefined\n ? readClientAssets(output.clientDirectory, assetsConfigOf(ctx.assets))\n : Effect.undefined,\n hashVinextInput({\n rootDir,\n memo: options.memo,\n options,\n workspaces: output.externalWorkspaces,\n }),\n ],\n { concurrency: \"unbounded\" },\n );\n yield* seedVinextPrerenderCache(rootDir, yield* resolveVinextCacheEnv(ctx.env ?? {}));\n return {\n bundle,\n assets,\n hash: {\n bundle: bundle.hash,\n assets: assets?.hash,\n input: input.hash,\n additionalWorkspaces: input.workspaces,\n },\n };\n }),\n hash: Effect.fn(function* (_ctx, previous) {\n const path = yield* Path.Path;\n const input = yield* hashVinextInput({\n rootDir: rootDirOf(path),\n memo: options.memo,\n options,\n workspaces: previous?.additionalWorkspaces ?? [],\n });\n return { input: input.hash, additionalWorkspaces: input.workspaces };\n }),\n dev: Effect.fn(function* (ctx) {\n const path = yield* Path.Path;\n const rootDir = rootDirOf(path);\n process.env[ALCHEMY_CLOUDFLARE_VITE_INJECTED] = \"1\";\n const cachePlugin = yield* makeVinextCachePlugin(rootDir, \"kv\");\n const vite = yield* Effect.promise(() => loadVite(rootDir));\n const port = yield* resolveViteDevPort(vite.version).pipe(\n Effect.mapError(\n (error) =>\n new SourceProviderError({\n provider: PROVIDER,\n message: \"Failed to allocate a vinext dev port\",\n cause: error,\n }),\n ),\n );\n const pluginOptions = makeVinextPluginOptions({\n root: rootDir,\n main: options.main ?? DEFAULT_WORKER_ENTRY,\n compatibilityDate: ctx.compatibility.date,\n compatibilityFlags: ctx.compatibility.flags,\n viteEnvironments: options.viteEnvironments,\n worker: {\n ...ctx.worker.options,\n name: ctx.workerName,\n bindings: ctx.worker.bindings,\n durableObjectNamespaces: ctx.worker.durableObjectNamespaces,\n hyperdrives: ctx.worker.hyperdrives,\n queueConsumers: yield* ctx.worker.queueConsumers,\n assets: ctx.worker.assets,\n },\n context: ctx.runtimeContext,\n });\n const server = yield* Effect.acquireRelease(\n Effect.promise(async () => {\n const devServer = await vite.createServer({\n root: rootDir,\n define: getDefine(ctx.env ?? {}),\n plugins: [cachePlugin, cloudflare(pluginOptions)],\n server: { port, strictPort: false },\n });\n await devServer.listen();\n return devServer;\n }),\n (devServer) => Effect.promise(() => devServer.close()),\n );\n const local = server.resolvedUrls?.local[0];\n if (!local) {\n return yield* new SourceProviderError({\n provider: PROVIDER,\n message: \"vinext dev server started without a local URL\",\n });\n }\n return { mode: \"server\", url: new URL(local) } satisfies ServerDevHandle;\n }),\n };\n};\n\nconst sourceModule = {\n make: (options: unknown): Effect.Effect\u003cSourceProvider, SourceProviderError> => {\n if (options !== undefined && (typeof options !== \"object\" || options === null)) {\n return Effect.fail(\n new SourceProviderError({\n provider: PROVIDER,\n message: `Invalid options for ${PROVIDER}: expected an object, got ${typeof options}`,\n }),\n );\n }\n return Effect.succeed(makeVinextSourceProvider((options ?? {}) as VinextSourceOptions));\n },\n};\n\nexport default sourceModule;\n","preview":null,"history":null,"version":"92b7af32b22dc133331fe1f538a5c46e6626c60a"},"/_session?shell=1":null}