diff --git a/scripts/lib/feature-residue.ts b/scripts/lib/feature-residue.ts index 2d533f0a..0dbae38c 100644 --- a/scripts/lib/feature-residue.ts +++ b/scripts/lib/feature-residue.ts @@ -40,12 +40,17 @@ import path from "node:path"; * a test title), and no text rule tells that from a reference. * - 0925 FOLLOW-UP 09-07. A spec that opens the feature by its URL alone * (`page.goto("/invoices")`) failed only in FE-GATE-008, after the drill - * passed. `routePaths` are the removed feature's route paths: a spec with a - * string that starts with one, up to its first parameter (`/invoices` of - * `/invoices/:id`) and followed by the string's end or `/`, `?`, `#`, is - * residue. A path that is `/` up to its first parameter is not searched. - * What is still not found: a spec that names only a one-word ID, or builds - * the URL from parts. 03's hand list removes the feature's specs. + * passed. `routes.paths` are the removed feature's route paths: a spec, or + * another file in a Playwright `testDir` that is not a vitest test (a page + * object), with a string that opens one is residue. A string opens a route + * when it starts with the route's fixed prefix (`/invoices` of + * `/invoices/:id` or `/invoices/edit?`) followed by the string's end, `/`, + * `?`, `#` or `${`, and no route left behind (`routes.remainingPaths`) has + * a longer prefix that fits it. A prefix that is `/` is not searched. + * `routes.ids`, the feature's route IDs, are searched in `src` text by the + * whole-name rule. What is still not found: a spec that names only a + * one-word ID, or builds the URL from parts. 03's hand list removes the + * feature's specs. * * The drill applies the same rule to a sample a project lists in * scripts/lib/removable-template-features.ts. @@ -77,25 +82,69 @@ async function filesUnder(directory: string): Promise { return nested.flat(); } -/** The part of a route path before its first parameter or wildcard, or null for `/`. */ +/** + * The part of a route path before its first parameter, wildcard or optional + * segment (`/invoices` of `/invoices/:id` or `/invoices/edit?`), or null when + * that is `/`. + */ function staticRoutePrefix(routePath: string): string | null { const segments: string[] = []; for (const segment of routePath.split("/").filter(Boolean)) { - if (segment.startsWith(":") || segment.includes("*")) break; + if (segment.startsWith(":") || segment.includes("*") || segment.endsWith("?")) break; segments.push(segment); } return segments.length === 0 ? null : `/${segments.join("/")}`; } +const prefixesOf = (routePaths: readonly string[]) => + new Set(routePaths.map(staticRoutePrefix).filter((prefix): prefix is string => prefix !== null)); + +/** `/invoices`, `/invoices/7`, `/invoices?tab=1`, `/invoices#x`, `/invoices${query}` open `/invoices`. */ +function opens(value: string, prefix: string): boolean { + if (!value.startsWith(prefix)) return false; + const rest = value.slice(prefix.length); + return rest === "" || /^[/?#]/u.test(rest) || rest.startsWith("${"); +} + +/** The Playwright `testDir`s the repository's `playwright*.config.ts` files name. */ +async function browserTestDirectories(root: string): Promise { + const configs = (await readdir(root).catch(() => [])).filter((name) => + /^playwright(?:\.[\w-]+)?\.config\.[cm]?[jt]s$/u.test(name), + ); + const directories = await Promise.all( + configs.map(async (config) => + /testDir:\s*["']\.?\/?([^"']+)["']/u.exec(await readFile(path.join(root, config), "utf8"))?.[1] + ?.replace(/\/$/u, ""), + ), + ); + return directories.filter((directory): directory is string => directory !== undefined); +} + +export type FeatureRoutes = Readonly<{ + /** The removed feature's route paths. */ + paths?: readonly string[]; + /** Every route path left after the removal, platform routes included. */ + remainingPaths?: readonly string[]; + /** The removed feature's route IDs, platform IDs it took over left out. */ + ids?: readonly string[]; +}>; + export async function productFeatureResidue( root: string, featureId: string, directory: string, - routePaths: readonly string[] = [], + routes: FeatureRoutes = {}, ): Promise { const nameSet = new Set([featureId, directory]); const names = [...nameSet].map(escapeRegExp).join("|"); const wholeAnyName = featureNamePattern(featureId, directory); + // A route ID left in platform source (a catalog key, `route.INVOICES_LIST`) + // is found by its whole name too. + const routeIds = [...new Set(routes.ids ?? [])].map(escapeRegExp); + const wholeRouteId = + routeIds.length === 0 + ? null + : new RegExp(`(? relativePath .split("/") @@ -111,20 +160,38 @@ export async function productFeatureResidue( specNames.length === 0 ? null : new RegExp(`(? prefix !== null)), - ].map(escapeRegExp); - const routeString = - prefixes.length === 0 - ? null - : new RegExp(`["'\`](?:${prefixes.join("|")})(?=["'\`/?#])`, "u"); + // A URL opens the route whose fixed prefix is the longest that fits it, so + // a sibling feature's `/invoices/lines` in the same context is not the + // removed `/invoices`. When a route left behind has the same prefix + // (`/invoices` beside a removed `/invoices/:id`), the URL is not counted. + const removed = prefixesOf(routes.paths ?? []); + const remaining = prefixesOf(routes.remainingPaths ?? []); + const candidates = [...new Set([...removed, ...remaining])].sort((a, b) => b.length - a.length); + const opensRemovedRoute = (text: string) => { + if (removed.size === 0) return false; + for (const match of text.matchAll(/["'`](\/[^"'`\s]*)/gu)) { + const best = candidates.find((prefix) => opens(match[1]!, prefix)); + if (best !== undefined && removed.has(best) && !remaining.has(best)) return true; + } + return false; + }; + const browserDirectories = await browserTestDirectories(root); const playwrightSpec = /\.spec\.[cm]?[jt]sx?$/u; + // A page object or helper beside the specs (`tests/e2e/support/*.ts`) runs + // only in a browser too; a vitest test (`*.test.*`) does not. + const browserFile = (name: string) => + playwrightSpec.test(name) || + (!/\.test\.[cm]?[jt]sx?$/u.test(name) && + browserDirectories.some((directory) => name.startsWith(`${directory}/`))); const residue: string[] = []; const relative = (file: string) => path.relative(root, file).split(path.sep).join("/"); for (const file of await filesUnder(path.join(root, "src"))) { const name = relative(file); if (name.startsWith("src/.generated/")) continue; - if (pathNames(name) || wholeAnyName.test(await readFile(file, "utf8"))) residue.push(name); + const text = await readFile(file, "utf8"); + if (pathNames(name) || wholeAnyName.test(text) || (wholeRouteId !== null && wholeRouteId.test(text))) { + residue.push(name); + } } for (const file of await filesUnder(path.join(root, "tests"))) { const name = relative(file); @@ -132,9 +199,8 @@ export async function productFeatureResidue( if ( pathNames(name) || imported.test(text) || - (playwrightSpec.test(name) && - ((wholeName !== null && wholeName.test(text)) || - (routeString !== null && routeString.test(text)))) + (playwrightSpec.test(name) && wholeName !== null && wholeName.test(text)) || + (browserFile(name) && opensRemovedRoute(text)) ) { residue.push(name); } diff --git a/scripts/test-sample-removal.ts b/scripts/test-sample-removal.ts index db54a02a..b84178be 100644 --- a/scripts/test-sample-removal.ts +++ b/scripts/test-sample-removal.ts @@ -14,7 +14,7 @@ import { PLATFORM_ROUTE_REGISTRY } from "../src/contracts/routes.ts"; import { ROUTE_FEATURE_OWNER, routePath } from "../src/features/installed-feature-contracts.ts"; import { loadCiGateContract } from "./contracts/ci-gates.ts"; import { createFileSystemDeclarationSource } from "./generate-product-feature-index.ts"; -import { featureNamePattern, productFeatureResidue } from "./lib/feature-residue.ts"; +import { featureNamePattern, type FeatureRoutes, productFeatureResidue } from "./lib/feature-residue.ts"; import { isProductionModulePath } from "./lib/risk-coverage.ts"; import { createRemovalFixtureRoot, @@ -164,15 +164,22 @@ const located = await locateFeature(featureId); const featureRouteIds = Object.entries(ROUTE_FEATURE_OWNER) .filter(([, owner]) => owner === featureId) .map(([routeId]) => routeId); -// 0925 FOLLOW-UP 09-07. A spec that opens the feature by one of these paths is -// residue (scripts/lib/feature-residue.ts). A platform path the feature took -// over (its home) goes back to the platform with the removal. +// 0925 FOLLOW-UP 09-07. A browser test that opens the feature by one of these +// paths is residue (scripts/lib/feature-residue.ts). A platform route the +// feature took over (its home) goes back to the platform with the removal. const platformRoutePaths = new Set( Object.values(PLATFORM_ROUTE_REGISTRY).map((route) => route.path), ); -const featureRoutePaths = featureRouteIds - .map(routePath) - .filter((candidate) => !platformRoutePaths.has(candidate)); +const featureRoutes: FeatureRoutes = Object.freeze({ + paths: featureRouteIds.map(routePath).filter((candidate) => !platformRoutePaths.has(candidate)), + remainingPaths: [ + ...platformRoutePaths, + ...Object.keys(ROUTE_FEATURE_OWNER) + .filter((routeId) => !featureRouteIds.includes(routeId)) + .map(routePath), + ], + ids: featureRouteIds.filter((routeId) => !Object.hasOwn(PLATFORM_ROUTE_REGISTRY, routeId)), +}); const fixtureRoot = await createRemovalFixtureRoot(`${featureId}-removal`); const pnpmCli = requireRemovalFixtureEnvironment("npm_execpath"); @@ -470,7 +477,7 @@ try { fixtureRoot, featureId, located.directory, - featureRoutePaths, + featureRoutes, ); // 1105/16-04. The same whole-name rule as `src`: the template's bundle // holds `data-product-feature`, which a substring search counted. diff --git a/tests/unit/feature-residue.test.ts b/tests/unit/feature-residue.test.ts index 53a1cbd8..01352019 100644 --- a/tests/unit/feature-residue.test.ts +++ b/tests/unit/feature-residue.test.ts @@ -99,31 +99,95 @@ describe("product feature residue (1105/16-04)", () => { "tests/unit/route.test.ts": 'const target = "/invoice";\n', }); - expect(await productFeatureResidue(root, ID, ID, ["/invoice", "/invoice/:invoiceId"])).toEqual([ + expect(await productFeatureResidue(root, ID, ID, { paths: ["/invoice", "/invoice/:invoiceId"] })).toEqual([ "tests/e2e/detail.spec.ts", "tests/e2e/route-only.spec.ts", "tests/visual/hash.visual.spec.ts", ]); }); + // Diff review of 09-07. The first feature of a context takes the context's + // path (`/invoice`) and a later one a path under it (`/invoice/line`), and + // the context stays while another feature is in it. + it("leaves a URL to a route still there with a longer prefix, such as a sibling feature's", async () => { + const root = await fixture({ + "tests/e2e/lines.spec.ts": 'await page.goto("/invoice/line");\nawait page.goto("/invoice/line/7");\n', + "tests/e2e/detail.spec.ts": 'await page.goto("/invoice/7");\n', + "tests/e2e/shared-prefix.spec.ts": 'await page.goto("/report/2026");\n', + }); + + expect( + await productFeatureResidue(root, ID, ID, { + paths: ["/invoice", "/report/:year"], + remainingPaths: ["/", "/invoice/line", "/report"], + }), + ).toEqual(["tests/e2e/detail.spec.ts"]); + }); + + it("stops a route prefix at an optional segment and finds a URL built with a template", async () => { + const root = await fixture({ + "tests/e2e/edit.spec.ts": 'await page.goto("/invoice/edit");\n', + "tests/e2e/query.spec.ts": "await page.goto(`/invoice${query}`);\n", + }); + + expect(await productFeatureResidue(root, ID, ID, { paths: ["/invoice/edit?"] })).toEqual([ + "tests/e2e/edit.spec.ts", + "tests/e2e/query.spec.ts", + ]); + }); + + it("searches a page object in a Playwright testDir, not a mock or a vitest test", async () => { + const root = await fixture({ + "playwright.config.ts": 'export default defineConfig({ testDir: "./tests/e2e" });\n', + "tests/e2e/support/invoice-page.ts": 'export const open = (page) => page.goto("/invoice");\n', + "tests/e2e/support/route.test.ts": 'const target = "/invoice";\n', + "tests/mocks/handlers/routes.ts": 'export const PAGE = "/invoice";\n', + }); + + expect(await productFeatureResidue(root, ID, ID, { paths: ["/invoice"] })).toEqual([ + "tests/e2e/support/invoice-page.ts", + ]); + }); + + it("finds the feature's route IDs in source by their whole name", async () => { + const root = await fixture({ + "src/contracts/titles.ts": "export const TITLE = messages.route.INVOICE_LIST.title;\n", + "src/contracts/longer.ts": 'export const KEY = "INVOICE_LIST_V2";\n', + }); + + expect(await productFeatureResidue(root, ID, ID, { ids: ["INVOICE_LIST"] })).toEqual([ + "src/contracts/titles.ts", + ]); + }); + it("does not search a route path that is the root before its first parameter", async () => { const root = await fixture({ "tests/e2e/home.spec.ts": 'await page.goto("/");\nawait page.goto("/?lang=ko");\n', }); - expect(await productFeatureResidue(root, ID, ID, ["/", "/:invoiceId", "*"])).toEqual([]); + expect(await productFeatureResidue(root, ID, ID, { paths: ["/", "/:invoiceId", "*"] })).toEqual([]); }); - it("does not count the template's own specs for the route paths of a generated feature", async () => { - const specs: Record = {}; - for (const entry of await readdir("tests", { recursive: true })) { - const file = path.join("tests", entry).split(path.sep).join("/"); - if (/\.spec\.[cm]?[jt]sx?$/u.test(file)) specs[file] = await readFile(file, "utf8"); + it("does not count the template's own browser tests for the route paths of a generated feature", async () => { + const files: Record = {}; + for (const entry of await readdir(".")) { + if (/^playwright.*\.config\.ts$/u.test(entry)) files[entry] = await readFile(entry, "utf8"); } - const root = await fixture(specs); + expect(Object.keys(files)).toContain("playwright.config.ts"); + for (const entry of await readdir("tests", { recursive: true, withFileTypes: true })) { + if (!entry.isFile()) continue; + const file = path.join(entry.parentPath, entry.name).split(path.sep).join("/"); + if (!/\.[cm]?[jt]sx?$/u.test(file)) continue; + if (/^tests\/(?:e2e|visual|storybook|browser-capabilities)\//u.test(file) || /\.spec\./u.test(file)) { + files[file] = await readFile(file, "utf8"); + } + } + const root = await fixture(files); // create:feature product-feature declares PRODUCT_LIST at /product. - expect(await productFeatureResidue(root, "product-feature", "product-feature", ["/product"])).toEqual([]); + expect( + await productFeatureResidue(root, "product-feature", "product-feature", { paths: ["/product"] }), + ).toEqual([]); }); it("does not count a spec whose longer names only contain the ID", async () => {