Skip to content
Myr

production-bundle.test.ts

This file

Path

apps/web/test/production-bundle.test.ts

437 lines · 13.6 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1// The Cloudflare plugin rewrites `.wrangler/deploy/config.json` at each build to point at its output;2// the redirect is put back as it was, so a deploy never follows it into a folder this test removed.3import { NodeServices } from "@effect/platform-node";4import { expect, layer } from "@effect/vitest";5import { Brand } from "@repo/brand";6import {7  Context,8  Effect,9  FileSystem,10  Layer,11  Option,12  Path,13  Schema,14  Stream,15} from "effect";16import { ChildProcess, ChildProcessSpawner } from "effect/process";1718const BUILD = 180_000;1920const DEV_STRINGS = [21  "src/dev/",22  "devWorld",23  "seedDev",24  "devSessions",25  "RepoHostMemory",26  "MemorySessions",27  "/auth/dev",28  "@repo/testkit",29  "isomorphic-git",30] as const;3132const DEV_MODULES = [33  "packages/project/src/project-store/memory",34  "packages/artifacts/src/repo-host/memory",35] as const;3637// About 10% above what the root's preloads weighed once the landing read its projects on the server.38// A route's `head`, `loader` and server functions ride in the route tree every page loads, so what they import counts here.39const ROOT_PRELOADS_GZIP = 268_000;4041const GRAMMAR = /node_modules\/@shikijs\/langs\/dist\/(?<name>[\w-]+)\.mjs$/u;4243// By Shiki's module names: HTML brings JavaScript and CSS with it.44const SERVER_GRAMMARS = [45  "css",46  "html",47  "javascript",48  "json",49  "jsx",50  "markdown",51  "shellscript",52  "toml",53  "tsx",54  "typescript",55  "yaml",56];5758const drawing = (held: readonly string[]) =>59  held.some((module) => module.endsWith("features/code/prerender-server.ts"));6061const BINARY = /\.(?:ico|png|woff2)$/u;6263const decodeSourceMap = Schema.decodeUnknownEffect(64  Schema.fromJsonString(Schema.Struct({ sources: Schema.Array(Schema.String) }))65);6667const decodeManifest = Schema.decodeUnknownEffect(68  Schema.fromJsonString(69    Schema.Struct({70      display: Schema.String,71      icons: Schema.Array(Schema.Struct({ src: Schema.String })),72      name: Schema.String,73      start_url: Schema.String,74    })75  )76);7778interface Output {79  readonly texts: ReadonlyMap<string, string>;80  readonly paths: ReadonlySet<string>;81  readonly modules: ReadonlySet<string>;82  readonly holding: ReadonlyMap<string, readonly string[]>;83}8485const where = Effect.gen(function* () {86  const path = yield* Path.Path;87  const web = yield* path.fromFileUrl(new URL("..", import.meta.url));8889  return { repo: path.resolve(web, "../.."), web };90});9192const keepDeployRedirect = (web: string) =>93  Effect.gen(function* () {94    const fs = yield* FileSystem.FileSystem;95    const path = yield* Path.Path;96    const redirect = path.join(web, ".wrangler/deploy/config.json");97    const before = yield* Effect.option(fs.readFileString(redirect));9899    yield* Effect.addFinalizer(() =>100      Option.match(before, {101        onNone: () => fs.remove(redirect, { force: true }),102        onSome: (text) => fs.writeFileString(redirect, text),103      }).pipe(Effect.orDie)104    );105  });106107const modulesIn = (map: string, text: string, repo: string) =>108  Effect.gen(function* () {109    const path = yield* Path.Path;110    const { sources } = yield* decodeSourceMap(text);111112    return sources.map((source) =>113      path.relative(114        repo,115        path.resolve(path.dirname(map), source.replace(/\?.*$/u, ""))116      )117    );118  });119120const readOutput = (out: string, repo: string) =>121  Effect.gen(function* () {122    const fs = yield* FileSystem.FileSystem;123    const path = yield* Path.Path;124    const entries = yield* fs.readDirectory(out, { recursive: true });125    const texts = new Map<string, string>();126    const modules = new Set<string>();127    const paths = new Set<string>();128    const holding = new Map<string, readonly string[]>();129130    for (const entry of entries) {131      const at = path.join(out, entry);132133      if ((yield* fs.stat(at)).type !== "File") {134        continue;135      }136137      paths.add(entry);138139      if (entry.endsWith(".map")) {140        const held = yield* modulesIn(at, yield* fs.readFileString(at), repo);141142        holding.set(entry.replace(/\.map$/u, ""), held);143144        for (const module of held) {145          modules.add(module);146        }147      } else if (!BINARY.test(entry)) {148        texts.set(entry, yield* fs.readFileString(at));149      }150    }151152    return { holding, modules, paths, texts } satisfies Output;153  });154155const productionBuild = Effect.gen(function* () {156  const fs = yield* FileSystem.FileSystem;157  const path = yield* Path.Path;158  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;159  const { repo, web } = yield* where;160  const out = yield* fs.makeTempDirectoryScoped({ prefix: "web-bundle-" });161162  yield* keepDeployRedirect(web);163164  const child = yield* spawner.spawn(165    ChildProcess.make(166      path.join(web, "node_modules/.bin/vite"),167      ["build", "--sourcemap", "--outDir", out, "--logLevel", "error"],168      {169        cwd: web,170        env: { NODE_ENV: "production", WRANGLER_SEND_METRICS: "false" },171        extendEnv: true,172        stdout: "ignore",173      }174    )175  );176177  const [stderr, exitCode] = yield* Effect.all(178    [child.stderr.pipe(Stream.decodeText(), Stream.mkString), child.exitCode],179    { concurrency: "unbounded" }180  );181182  if (exitCode !== 0) {183    return yield* Effect.die(`vite build exited ${exitCode}:\n${stderr}`);184  }185186  return yield* readOutput(out, repo);187}).pipe(Effect.scoped, Effect.orDie, Effect.provide(NodeServices.layer));188189class Built extends Context.Service<Built, Output>()("test/Built") {}190191const textsUnder = (output: Output, folder: "client" | "server") =>192  [...output.texts].filter(([at]) => at.startsWith(`${folder}/`));193194const holds = (output: Output, folder: "client" | "server", pattern: RegExp) =>195  textsUnder(output, folder).some(([, text]) => pattern.test(text));196197const routePath = (path: string) =>198  new RegExp(199    `(?<quote>["'\`])${path.replaceAll(/[$.]/gu, "\\$&")}\\k<quote>`,200    "u"201  );202203const rootPreloads = (output: Output) => {204  const manifest = textsUnder(output, "server").find(([at]) =>205    at.includes("tanstack-start-manifest")206  )?.[1];207208  // Lazily up to the first `preloads`, the root's own: a child route's path209  // may hold a brace (`/$owner/$project/asks/{$ask}.md`). The minified server210  // build writes the list as one string it splits on commas211  // (`` `/assets/a.js,/assets/b.js`.split(`,`) ``), an unminified one as an array.212  const preloads =213    /__root__:\s*\{[\s\S]*?preloads:\s*(?<list>\[[^\]]*\]|`[^`]*`)/u.exec(214      manifest ?? ""215    )?.groups?.list;216217  return [...(preloads ?? "").matchAll(/\/assets\/[^"`,\s]+/gu)].map(218    ([chunk]) => chunk219  );220};221222const gzipped = (text: string) =>223  Stream.fromReadableStream({224    evaluate: () =>225      new Blob([text]).stream().pipeThrough(new CompressionStream("gzip")),226    onError: (cause) => cause,227  }).pipe(228    Stream.runFold(229      () => 0,230      (size, chunk: Uint8Array) => size + chunk.byteLength231    ),232    Effect.orDie233  );234235layer(Layer.effect(Built, productionBuild), { timeout: BUILD })(236  "the web's production build",237  (it) => {238    it.effect(239      "carries the web app manifest, which opens the inbox, and every icon it names",240      () =>241        Effect.gen(function* () {242          const output = yield* Built;243          const manifest = output.texts.get("client/manifest.webmanifest");244245          expect(manifest, "client/manifest.webmanifest").toBeDefined();246247          const { icons, ...installs } = yield* decodeManifest(manifest);248249          expect(installs).toStrictEqual({250            display: "standalone",251            name: Brand.name,252            start_url: "/inbox",253          });254          expect(icons.length).toBeGreaterThan(0);255          expect(256            icons.flatMap(({ src }) =>257              output.paths.has(`client${src}`) ? [] : [src]258            )259          ).toStrictEqual([]);260        })261    );262263    it.effect(264      "serves llms.txt and the MCP card, and passes the skills, the install script and the releases on",265      () =>266        Effect.gen(function* () {267          const output = yield* Built;268269          expect(270            [271              "/llms.txt",272              "/$owner/$project/llms.txt",273              "/.well-known/mcp.json",274              "/.well-known/agent-skills/$",275              "/install.sh",276              "/releases/$",277            ].filter((path) => !holds(output, "server", routePath(path)))278          ).toStrictEqual([]);279        })280    );281282    // A build that resolves `#backend` to `src/dev/backend.ts` fails here and in the next case.283    it.effect("resolves #backend to the forward to PLATFORM", () =>284      Effect.gen(function* () {285        const output = yield* Built;286287        expect({288          devBackend: output.modules.has("apps/web/src/dev/backend.ts"),289          forwards: holds(output, "server", /\bPLATFORM\.fetch\(/u),290          serverBackend: output.modules.has("apps/web/src/server/backend.ts"),291        }).toStrictEqual({292          devBackend: false,293          forwards: true,294          serverBackend: true,295        });296      })297    );298299    it.effect(300      "carries no dev module, no memory adapter, no seed, no dev sign-in and no test kit",301      () =>302        Effect.gen(function* () {303          const output = yield* Built;304305          expect(output.modules.size).toBeGreaterThan(10);306          expect(307            [...output.modules].filter(308              (module) =>309                module.startsWith("apps/web/src/dev/") ||310                DEV_MODULES.some((folder) => module.startsWith(folder))311            )312          ).toStrictEqual([]);313          expect(314            [...output.texts].flatMap(([at, text]) =>315              DEV_STRINGS.flatMap((dev) =>316                text.includes(dev) ? [`${at}: ${dev}`] : []317              )318            )319          ).toStrictEqual([]);320        })321    );322323    it.effect(324      "preloads on every page no chunk that holds the Markdown renderer, and stays under its ceiling",325      () =>326        Effect.gen(function* () {327          const output = yield* Built;328          const preloads = rootPreloads(output);329330          expect(preloads.length).toBeGreaterThan(0);331332          const sizes = yield* Effect.forEach(preloads, (chunk) =>333            gzipped(output.texts.get(`client${chunk}`) ?? "")334          );335336          const total = sizes.reduce((sum, size) => sum + size, 0);337338          expect({339            markdown: preloads.filter((chunk) =>340              (output.holding.get(`client${chunk}`) ?? []).some((module) =>341                module.includes("node_modules/react-markdown/")342              )343            ),344            missing: preloads.filter(345              (chunk) => !output.texts.has(`client${chunk}`)346            ),347          }).toStrictEqual({ markdown: [], missing: [] });348          // The weight itself, so a failure says how far over it is.349          expect(350            total,351            `${preloads.length} root preloads, gzipped`352          ).toBeLessThanOrEqual(ROOT_PRELOADS_GZIP);353        })354    );355356    it.effect(357      "preloads on every page no grammar, nothing of the server's highlighting, and neither the landing's view, Explore's nor the import page's",358      () =>359        Effect.gen(function* () {360          const output = yield* Built;361362          // Nor the landing's view, Explore's or the import page's: a route's head or363          // loader that imported one would carry the whole page into every364          // page's preloads.365          expect(366            rootPreloads(output).flatMap((chunk) =>367              (output.holding.get(`client${chunk}`) ?? []).filter(368                (module) =>369                  GRAMMAR.test(module) ||370                  module.includes("prerender") ||371                  module.endsWith("features/landing/landing-page.tsx") ||372                  module.endsWith("features/explore/explore-page.tsx") ||373                  module.includes("features/import/")374              )375            )376          ).toStrictEqual([]);377378          // The server's highlighting is the Worker's alone.379          expect({380            browser: [...output.holding].flatMap(([at, held]) =>381              at.startsWith("client/") && drawing(held) ? [at] : []382            ),383            worker: [...output.holding].some(384              ([at, held]) => at.startsWith("server/") && drawing(held)385            ),386          }).toStrictEqual({ browser: [], worker: true });387        })388    );389390    it.effect(391      "bundles into the Worker its few grammars alone, off its entry, and no theme collection or WebAssembly",392      () =>393        Effect.gen(function* () {394          const output = yield* Built;395396          const server = [...output.holding].filter(([at]) =>397            at.startsWith("server/")398          );399400          const grammars = new Set(401            server.flatMap(([, held]) =>402              held.flatMap((module) => {403                const name = GRAMMAR.exec(module)?.groups?.name;404405                return name === undefined ? [] : [name];406              })407            )408          );409410          expect([...grammars].toSorted()).toStrictEqual(SERVER_GRAMMARS);411          expect(412            server.flatMap(([at, held]) =>413              held.filter(414                (module) =>415                  module.includes("node_modules/@shikijs/themes/") ||416                  module.includes("node_modules/@pierre/theme/") ||417                  module.includes("node_modules/@shikijs/engine-oniguruma/") ||418                  (at === "server/index.js" &&419                    (GRAMMAR.test(module) ||420                      module.includes("features/code/prerender-server.ts")))421              )422            )423          ).toStrictEqual([]);424        })425    );426427    it.effect("tells browsers to keep the hashed assets for good", () =>428      Effect.gen(function* () {429        const output = yield* Built;430431        expect(output.texts.get("client/_headers")).toMatch(432          /^\/assets\/\*\n {2}Cache-Control: public, max-age=31536000, immutable$/mu433        );434      })435    );436  }437);