sailfork / t3code-github / .repos/ alchemy-effect/ packages/ frontend-frameworks/ src/ sveltekit/ test/ Adapter.test.ts

import { describe, expect, it } from "vitest";
import {
  appendHeaders,
  generateAssetsIgnore,
  generateHeaders,
  generateRedirects,
  generateWorkerShim,
  makeCloudflareAdapter,
  makeDevPlatformEmulator,
  type DevPlatformProxy,
  type OpenDevPlatformProxy,
  type OpenDevPlatformProxyOptions,
} from "../cloudflare.ts";

describe("generateWorkerShim", () => {
  const shim = generateWorkerShim({
    serverImport: "./../output/server/index.js",
    manifestImport: "./../cloudflare-tmp/manifest.js",
    assetsBinding: "ASSETS",
  });

  it("imports the server and manifest through real relative paths", () => {
    expect(shim).toContain(`import { server } from "./../output/server/index.js";`);
    expect(shim).toContain(
      `import { assets, app_path, prerendered, base_path, routes } from "./../cloudflare-tmp/manifest.js";`,
    );
  });

  it("uses module-level env from cloudflare:workers", () => {
    expect(shim).toContain(`import { env } from 'cloudflare:workers';`);
  });

  it("serves static and prerendered files through the assets binding", () => {
    expect(shim).toContain("env.ASSETS.fetch(req)");
    expect(shim).toContain("env.ASSETS.fetch(url)");
  });

  it("respects a custom assets binding name", () => {
    const custom = generateWorkerShim({
      serverImport: "./server/index.js",
      manifestImport: "./manifest.js",
      assetsBinding: "STATIC",
    });
    expect(custom).toContain("env.STATIC.fetch(req)");
    expect(custom).not.toContain("env.ASSETS.fetch");
  });

  it("replaces worktop with a caches.default pragma cache", () => {
    expect(shim).not.toContain("worktop");
    expect(shim).toContain("caches.default");
    expect(shim).toContain("cache_lookup");
    expect(shim).toContain("cache_save");
  });

  it("exposes the platform to server.respond", () => {
    expect(shim).toContain("platform: { env, ctx, caches, cf: req.cf }");
  });

  describe("SPA not-found deferral", () => {
    const spa = generateWorkerShim({
      serverImport: "./../output/server/index.js",
      manifestImport: "./../cloudflare-tmp/manifest.js",
      assetsBinding: "ASSETS",
      notFoundHandling: "single-page-application",
    });

    it("emits no deferral by default (upstream parity)", () => {
      expect(shim).not.toContain("matches_kit_route");
      expect(shim).not.toContain("res.status === 404");
    });

    it("emits no deferral for 404-page (upstream parity)", () => {
      const fourOhFour = generateWorkerShim({
        serverImport: "./server/index.js",
        manifestImport: "./manifest.js",
        assetsBinding: "ASSETS",
        notFoundHandling: "404-page",
      });
      expect(fourOhFour).not.toContain("matches_kit_route");
      expect(fourOhFour).not.toContain("res.status === 404");
    });

    it("defers router-level 404s to the assets binding for SPA builds", () => {
      expect(spa).toContain("const matches_kit_route = (pathname)");
      expect(spa).toContain("res.status === 404");
      expect(spa).toContain("!matches_kit_route(pathname)");
    });

    it("only defers navigation-shaped requests (GET/HEAD accepting text/html)", () => {
      expect(spa).toContain("(req.method === 'GET' || req.method === 'HEAD')");
      expect(spa).toContain("(req.headers.get('accept') || '').includes('text/html')");
    });

    it("probes kit's route patterns with the base path stripped", () => {
      expect(spa).toContain("path.slice(base_path.length) || '/'");
      expect(spa).toContain("route.pattern.test(path)");
      expect(spa).toContain("for (const route of routes)");
    });

    it("defers through the configured assets binding", () => {
      const custom = generateWorkerShim({
        serverImport: "./server/index.js",
        manifestImport: "./manifest.js",
        assetsBinding: "STATIC",
        notFoundHandling: "single-page-application",
      });
      expect(custom).toContain("res = await env.STATIC.fetch(req);");
      expect(custom).not.toContain("env.ASSETS.fetch");
    });
  });
});

describe("appendHeaders", () => {
  it("adds a new rule block", () => {
    const content = appendHeaders("/_app/*", ["X-Robots-Tag: noindex"], "");
    expect(content).toContain("/_app/*\n  X-Robots-Tag: noindex");
    expect(content).toContain("AUTOGENERATED SVELTE IMMUTABLE HEADERS");
  });

  it("merges into an existing block for the same URL", () => {
    const existing = "/_app/*\n  X-Existing: yes";
    const content = appendHeaders("/_app/*", ["X-Robots-Tag: noindex"], existing);
    expect(content).toBe("/_app/*\n  X-Robots-Tag: noindex\n  X-Existing: yes");
  });
});

describe("generateHeaders", () => {
  it("emits noindex and immutable cache rules for the app dir", () => {
    const content = generateHeaders("_app");
    expect(content).toContain("/_app/*\n  X-Robots-Tag: noindex\n  Cache-Control: no-cache");
    expect(content).toContain(
      "/_app/immutable/*\n  ! Cache-Control\n  Cache-Control: public, immutable, max-age=31536000",
    );
  });

  it("preserves user-authored headers", () => {
    const content = generateHeaders("_app", "/api/*\n  X-Fixture: yes");
    expect(content).toContain("/api/*\n  X-Fixture: yes");
    expect(content).toContain("/_app/immutable/*");
  });
});

describe("generateRedirects", () => {
  it("returns undefined when there is nothing to write", () => {
    expect(generateRedirects(new Map())).toBeUndefined();
  });

  it("emits prerendered redirect rules", () => {
    const content = generateRedirects(new Map([["/old", { status: 301, location: "/new" }]]));
    expect(content).toContain("/old /new 301");
    expect(content).toContain("AUTOGENERATED SVELTE PRERENDERED REDIRECTS");
  });

  it("prepends user-authored redirects", () => {
    const content = generateRedirects(
      new Map([["/old", { status: 301, location: "/new" }]]),
      "/legacy /modern 302",
    );
    expect(content?.startsWith("/legacy /modern 302")).toBe(true);
    expect(content).toContain("/old /new 301");
  });
});

describe("generateAssetsIgnore", () => {
  it("excludes the worker entry and metadata files from assets", () => {
    const content = generateAssetsIgnore();
    expect(content.split("\n").filter(Boolean)).toEqual([
      "_worker.js",
      "_routes.json",
      "_headers",
      "_redirects",
    ]);
  });
});

interface FakeProxyHarness {
  readonly openProxy: OpenDevPlatformProxy;
  readonly opens: Array<OpenDevPlatformProxyOptions>;
  readonly disposals: () => number;
}

const makeFakeProxy = (env: Record<string, unknown>): FakeProxyHarness => {
  const opens: Array<OpenDevPlatformProxyOptions> = [];
  let disposed = 0;
  const proxy: DevPlatformProxy = {
    env,
    cf: { colo: "TST", country: "US" },
    ctx: { waitUntil: (_promise: Promise<unknown>) => {} },
    caches: { default: "fake-cache" },
    dispose: async () => {
      disposed += 1;
    },
  };
  return {
    openProxy: async (options) => {
      opens.push(options);
      return proxy;
    },
    opens,
    disposals: () => disposed,
  };
};

type PlatformShape = {
  env: Record<string, unknown>;
  ctx: { waitUntil: (promise: Promise<unknown>) => void };
  caches: unknown;
  cf: Record<string, unknown>;
};

describe("makeDevPlatformEmulator", () => {
  it("opens the proxy lazily and serves env, ctx, caches, and cf from it", async () => {
    const fake = makeFakeProxy({ FROM_PROXY: "proxied" });
    const emulator = makeDevPlatformEmulator({
      bindings: ["binding-hook"],
      compatibilityDate: "2026-03-10",
      compatibilityFlags: ["nodejs_compat"],
      openProxy: fake.openProxy,
    });
    // nothing opened until the first platform() call
    expect(fake.opens).toHaveLength(0);
    const platform = (await emulator.platform?.({
      config: {},
      prerender: false,
    })) as PlatformShape;
    expect(fake.opens).toHaveLength(1);
    expect(fake.opens[0]).toMatchObject({
      name: "sveltekit-dev-platform-proxy",
      compatibilityDate: "2026-03-10",
      compatibilityFlags: ["nodejs_compat"],
      bindings: ["binding-hook"],
    });
    expect(platform.env["FROM_PROXY"]).toBe("proxied");
    expect(platform.cf["colo"]).toBe("TST");
    expect(platform.caches).toEqual({ default: "fake-cache" });
    expect(() => platform.ctx.waitUntil(Promise.resolve())).not.toThrow();
  });

  it("opens a single proxy across platform() calls", async () => {
    const fake = makeFakeProxy({});
    const emulator = makeDevPlatformEmulator({ openProxy: fake.openProxy });
    await emulator.platform?.({ config: {}, prerender: false });
    await emulator.platform?.({ config: {}, prerender: true });
    await emulator.platform?.({ config: {}, prerender: false });
    expect(fake.opens).toHaveLength(1);
  });

  it("applies literal env overrides on top of proxied values", async () => {
    const fake = makeFakeProxy({ SHARED: "proxied", FROM_PROXY: "proxied" });
    const emulator = makeDevPlatformEmulator({
      env: { SHARED: "literal-wins", LITERAL_ONLY: "literal" },
      openProxy: fake.openProxy,
    });
    const platform = (await emulator.platform?.({
      config: {},
      prerender: false,
    })) as PlatformShape;
    expect(platform.env).toEqual({
      FROM_PROXY: "proxied",
      SHARED: "literal-wins",
      LITERAL_ONLY: "literal",
    });
  });

  it("throws on env access in prerenderable routes", async () => {
    const fake = makeFakeProxy({ FROM_PROXY: "proxied" });
    const emulator = makeDevPlatformEmulator({
      env: { LITERAL: "value" },
      openProxy: fake.openProxy,
    });
    const platform = (await emulator.platform?.({
      config: {},
      prerender: true,
    })) as PlatformShape;
    expect(() => platform.env["FROM_PROXY"]).toThrow(
      "Cannot access platform.env.FROM_PROXY in a prerenderable route",
    );
    expect(() => platform.env["LITERAL"]).toThrow(
      "Cannot access platform.env.LITERAL in a prerenderable route",
    );
  });

  it("dispose tears down an opened proxy and is a no-op before open", async () => {
    const untouched = makeFakeProxy({});
    const idle = makeDevPlatformEmulator({ openProxy: untouched.openProxy });
    await idle.dispose();
    expect(untouched.opens).toHaveLength(0);
    expect(untouched.disposals()).toBe(0);

    const fake = makeFakeProxy({});
    const emulator = makeDevPlatformEmulator({ openProxy: fake.openProxy });
    await emulator.platform?.({ config: {}, prerender: false });
    await emulator.dispose();
    expect(fake.disposals()).toBe(1);
  });
});

describe("makeCloudflareAdapter emulation", () => {
  it("serves the proxy-backed platform when dev platform options are present", async () => {
    const fake = makeFakeProxy({ FROM_PROXY: "proxied" });
    const adapter = makeCloudflareAdapter({
      platform: { bindings: ["hook"], openProxy: fake.openProxy },
    });
    const emulator = await adapter.emulate?.();
    const platform = (await emulator?.platform?.({
      config: {},
      prerender: false,
    })) as PlatformShape;
    expect(platform.env["FROM_PROXY"]).toBe("proxied");
    await adapter.dispose();
    expect(fake.disposals()).toBe(1);
  });

  it("memoizes the emulator across emulate() calls", async () => {
    const fake = makeFakeProxy({});
    const adapter = makeCloudflareAdapter({
      platform: { openProxy: fake.openProxy },
    });
    const first = await adapter.emulate?.();
    const second = await adapter.emulate?.();
    expect(first).toBe(second);
    await first?.platform?.({ config: {}, prerender: false });
    await second?.platform?.({ config: {}, prerender: false });
    expect(fake.opens).toHaveLength(1);
  });

  it("serves an inert empty platform for production builds (no proxy)", async () => {
    const adapter = makeCloudflareAdapter({});
    const emulator = await adapter.emulate?.();
    const platform = (await emulator?.platform?.({
      config: {},
      prerender: false,
    })) as PlatformShape & {
      caches: { default: { match: () => Promise<undefined> } };
    };
    expect(platform.env).toEqual({});
    expect(platform.cf).toEqual({});
    await expect(platform.caches.default.match()).resolves.toBeUndefined();
    // disposing without a proxy is a no-op
    await adapter.dispose();
  });
});