sailfork / t3code-github / .repos/ alchemy-effect/ packages/ alchemy-test/ src/ Vitest.ts

/** @effect-diagnostics anyUnknownInErrorContext:off */
import { it } from "@effect/vitest";
import type { AlchemyContext } from "alchemy/AlchemyContext";
import type { CompiledStack, StackDefinition } from "alchemy/Stack";
import type { Stage } from "alchemy/Stage";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
import * as Scope from "effect/Scope";
import {
  afterAll as vitestAfterAll,
  afterEach as vitestAfterEach,
  beforeAll as vitestBeforeAll,
  beforeEach as vitestBeforeEach,
} from "vitest";
import * as Core from "./Core.ts";

export {
  executeWhenReady,
  getWhenReady,
  guardContentType,
  guardedFetchLayer,
  rpcClientLayer,
  WorkerNotReady,
  type EdgeGuardOptions,
  type WhenReadyOptions,
} from "./Http.ts";

export type MakeOptions<ROut = any> = Core.MakeOptions<ROut>;
export type ScratchStack = Core.ScratchStack;
export type TestEffect<A, R = never> = Core.TestEffect<A, R>;
export const defaultStage = Core.defaultStage;
export const resolveStage = Core.resolveStage;

type TestOptions = number | { timeout?: number };

const timeoutOf = (opts: TestOptions | undefined): number | undefined =>
  typeof opts === "number" ? opts : opts?.timeout;

interface TestFn {
  (name: string, eff: TestEffect<void>, options?: TestOptions): void;
  skip: (name: string, eff: TestEffect<void>, options?: TestOptions) => void;
  skipIf: (
    condition: boolean,
  ) => (name: string, eff: TestEffect<void>, options?: TestOptions) => void;
  only: (name: string, eff: TestEffect<void>, options?: TestOptions) => void;
  todo: (name: string, eff: TestEffect<void>, options?: TestOptions) => void;
  provider: ProviderFn;
}

interface ProviderFn {
  (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
    options?: TestOptions,
  ): void;
  skip: (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
    options?: TestOptions,
  ) => void;
  skipIf: (
    condition: boolean,
  ) => (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
    options?: TestOptions,
  ) => void;
}

interface BeforeAllFn {
  <A>(eff: TestEffect<A>, options?: TestOptions): Effect.Effect<A>;
}

interface BeforeEachFn {
  (eff: TestEffect<void>, options?: TestOptions): void;
}

interface AfterAllFn {
  (eff: TestEffect<any>, options?: TestOptions): void;
  skipIf: (predicate: boolean) => (eff: TestEffect<any>, options?: TestOptions) => void;
}

interface AfterEachFn {
  (eff: TestEffect<void>, options?: TestOptions): void;
}

export interface TestApi {
  test: TestFn;
  beforeAll: BeforeAllFn;
  beforeEach: BeforeEachFn;
  afterAll: AfterAllFn;
  afterEach: AfterEachFn;
  deploy: Core.Deploy;
  destroy: <ROut>(
    stack: StackDefinition<ROut>,
    options?: { stage?: string; include?: never; exclude?: never },
  ) => ReturnType<typeof Core.destroy>;
}

const DEFAULT_TIMEOUT = 120_000;

/**
 * Build the per-file test API. See {@link "./Bun.ts"} for the same shape
 * over `bun:test`. Vitest variant uses `@effect/vitest`'s `it.live` so
 * Effect-aware tests stay first-class.
 */
export const make = <ROut = any>(options: MakeOptions<ROut>): TestApi => {
  // See `Test/Bun.ts` for the rationale: the dev sidecar must outlive a
  // single `runPromise` boundary, so all hooks share one scope that's only
  // closed after `destroy(...)` runs.
  const sharedScope = Scope.makeUnsafe("sequential");
  // In dev mode, run local providers behind one file-scoped RPC sidecar
  // (the `alchemy dev` topology). Lives in its own scope — NOT sharedScope,
  // which `destroy(Stack)` closes mid-file in self-contained tests — and is
  // closed by the fallback afterAll below.
  const sidecar = Core.makeSidecarHandle(options);
  const wrap = <A>(eff: TestEffect<A>) => Core.toEffect(eff, options, sharedScope, sidecar);
  const runEff = <A>(eff: TestEffect<A>) => Core.run(eff, options, sharedScope, sidecar);

  const test = ((name, eff, opts) => {
    it.live(name, () => wrap(eff), timeoutOf(opts));
  }) as TestFn;

  test.skip = (name, _eff, opts) => {
    it.skip(name, () => {}, timeoutOf(opts));
  };
  test.skipIf = (condition) => (name, eff, opts) => {
    if (condition) {
      it.skip(name, () => {}, timeoutOf(opts));
    } else {
      it.live(name, () => wrap(eff), timeoutOf(opts));
    }
  };
  test.only = (name, eff, opts) => {
    it.live.only(name, () => wrap(eff), timeoutOf(opts));
  };
  test.todo = (name, _eff, _opts) => {
    it.todo(name);
  };

  const wrapProvider = (
    name: string,
    fn: (stack: ScratchStack) => Effect.Effect<void, any, any>,
  ) => {
    const scratch = Core.scratchStack(options, name);
    // Guarantee teardown. `test.provider` has no built-in cleanup, so a body
    // that fails (assertion, API error like a 409/Unauthorized) or is
    // interrupted (vitest timeout) BEFORE its trailing `stack.destroy()` would
    // otherwise leak every cloud resource it deployed: the scratch's in-memory
    // state is discarded with the process, so no later run can reclaim the
    // orphan (only an account-wide `nuke` can). `scratch.destroy()` is
    // idempotent (empty-plan apply against the shared scratch state) — a no-op
    // when the body already destroyed, and it reclaims the orphans otherwise.
    // `Effect.ensuring` runs the finalizer on success, failure, AND interruption.
    const body = Core.withProviders(fn(scratch), options, scratch.name).pipe(
      Effect.ensuring(scratch.destroy().pipe(Effect.ignore)),
    );
    return Core.toEffect(body, { ...options, state: scratch.state }, sharedScope, sidecar);
  };

  const provider = ((name, fn, opts) => {
    it.live(name, () => wrapProvider(name, fn), timeoutOf(opts));
  }) as ProviderFn;
  provider.skip = (name, _fn, opts) => {
    it.skip(name, () => {}, timeoutOf(opts));
  };
  provider.skipIf = (condition) => (name, fn, opts) => {
    if (condition) {
      it.skip(name, () => {}, timeoutOf(opts));
    } else {
      it.live(name, () => wrapProvider(name, fn), timeoutOf(opts));
    }
  };
  test.provider = provider;

  const beforeAll: BeforeAllFn = <A>(eff: TestEffect<A>, hookOptions?: TestOptions) => {
    let result: A;
    vitestBeforeAll(
      () => runEff(eff).then((v) => (result = v)),
      timeoutOf(hookOptions) ?? DEFAULT_TIMEOUT,
    );
    return Effect.sync(() => result);
  };

  const beforeEach: BeforeEachFn = (eff, hookOptions) => {
    vitestBeforeEach(() => runEff(eff), timeoutOf(hookOptions));
  };

  const afterAll = ((eff, hookOptions) => {
    vitestAfterAll(() => runEff(eff), timeoutOf(hookOptions) ?? DEFAULT_TIMEOUT);
  }) as AfterAllFn;
  afterAll.skipIf = (predicate) => (eff, hookOptions) => {
    if (predicate) return;
    vitestAfterAll(() => runEff(eff), timeoutOf(hookOptions) ?? DEFAULT_TIMEOUT);
  };

  const afterEach: AfterEachFn = (eff, hookOptions) => {
    vitestAfterEach(() => runEff(eff), timeoutOf(hookOptions));
  };

  // `destroy(Stack)` needs the dev sidecar alive so it can call `sidecar.stop`.
  // `Scope.close` on an already-closed scope is a no-op, so the destroy
  // wrapper AND the fallback cleanup hook below can both call it safely.
  const closeScope = Effect.suspend(() => Scope.close(sharedScope, Exit.void)).pipe(Effect.ignore);

  // Fallback cleanup: if the user never calls `destroy(Stack)` (e.g.
  // `NO_DESTROY=1`), nothing else closes the shared scope and the sidecar
  // child process leaks past the test process. The RPC sidecar lives in its
  // own scope so that mid-file `destroy(Stack)` calls can't kill it for later
  // tests.
  //
  // The cleanup must run after every user `afterAll` (including
  // `destroy(Stack)`, which needs the sidecar). Vitest's default
  // `sequence.hooks: "stack"` runs `afterAll` hooks in reverse registration
  // order and `"list"` runs them in registration order, so register the
  // cleanup both before (now) and after (next microtask) the file's
  // `afterAll` calls, and only close on the second invocation: whichever
  // order is configured, that one runs last.
  const closeAll = sidecar ? Effect.andThen(closeScope, sidecar.close) : closeScope;
  let cleanupCalls = 0;
  const cleanup = () => (++cleanupCalls === 2 ? Effect.runPromise(closeAll) : undefined);
  vitestAfterAll(cleanup, DEFAULT_TIMEOUT);
  queueMicrotask(() => {
    vitestAfterAll(cleanup, DEFAULT_TIMEOUT);
  });

  return {
    test,
    beforeAll,
    beforeEach,
    afterAll,
    afterEach,
    deploy: Core.makeDeploy(options, sharedScope),
    destroy: (stack, callOpts) =>
      Core.destroy(options, stack, { ...callOpts, scope: sharedScope }).pipe(
        Effect.ensuring(closeScope),
      ),
  };
};