sailfork / t3code-github / .repos/ alchemy-effect/ packages/ alchemy/ src/ Bundle/ TempRoot.ts

import * as crypto from "node:crypto";
import { fileURLToPath } from "node:url";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Path from "effect/Path";
import { Stack } from "../Stack.ts";
import { Stage } from "../Stage.ts";

/**
 * Resolve a bundle entrypoint (`main`) to a real filesystem path.
 *
 * `main` is user-supplied and is very commonly `import.meta.url` — a
 * `file://` URL — which `FileSystem.realPath` cannot `lstat` directly
 * (it would try to stat a literal `file:` path). Convert any `file://`
 * URL to a path first, then resolve to the canonical real path.
 */
export const resolveMainPath = Effect.fn(function* (main: string) {
  const fs = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  const asPath = yield* Effect.sync(() => {
    try {
      return fileURLToPath(main);
    } catch {
      return main;
    }
  });
  return path.resolve(yield* fs.realPath(asPath));
});

/**
 * Creates a unique bundle staging directory under the configured runtime directory's
 * `tmp` root. Each invocation gets its own directory (via a random
 * nonce) so concurrent bundle operations for the same resource never collide.
 * Stale directories from previous crashed runs are cleaned up best-effort.
 */
export const createTempBundleDir = (_entry: string, dotAlchemy: string, id: string) =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const stack = yield* Stack;
    const stage = yield* Stage;
    const tempRoot = path.join(dotAlchemy, "tmp");
    yield* fs.makeDirectory(tempRoot, { recursive: true });

    const nonce = crypto.randomUUID().slice(0, 8);
    const bundleId = `${stack.name}-${stage}-${id}-${nonce}`;
    const tempDir = path.join(tempRoot, bundleId);
    yield* fs.makeDirectory(tempDir, { recursive: true });

    return tempDir;
  });

/**
 * Returns a deterministic bundle staging directory without clearing it first.
 * Useful for Docker build contexts where keeping the directory stable avoids
 * unnecessary file churn between builds.
 */
export const getStableContextDir = (_entry: string, dotAlchemy: string, id: string) =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    const path = yield* Path.Path;
    const stack = yield* Stack;
    const stage = yield* Stage;
    const tempRoot = path.join(dotAlchemy, "tmp");
    const bundleId = `${stack.name}-${stage}-${id}`;
    const tempDir = path.join(tempRoot, bundleId);

    yield* fs.makeDirectory(tempDir, { recursive: true });

    return tempDir;
  });

/**
 * Cleans up a bundle's private temp directory.
 */
export const cleanupBundleTempDir = (tempDir: string) =>
  Effect.gen(function* () {
    const fs = yield* FileSystem.FileSystem;
    yield* fs.remove(tempDir, { recursive: true }).pipe(Effect.ignore);
  });

export const findCwdForBundle = Effect.fn(function* (entry: string) {
  const fs = yield* FileSystem.FileSystem;
  const path = yield* Path.Path;
  let current = path.dirname(entry);
  while (true) {
    if (yield* fs.exists(path.join(current, "package.json"))) {
      return current;
    }
    const parent = path.dirname(current);
    if (parent === current) {
      return process.cwd();
    }
    current = parent;
  }
});