Skip to content

Commit c8f244d

Browse files
dmealingclaude
andcommitted
feat(verify): advise when a provider drops apiPrefix silently
1.0 moved `$apiPrefix` out of the entity descriptor, and the migration note rests its safety argument on `<EntityFetcherProvider value={…}>` no longer typechecking. That argument has two unstated preconditions, and a real adopter tree falsified both. *It only protects a project that runs `tsc`.* On an estate whose web app had no typecheck script, no turbo task and no CI job, the unmigrated tree passed `turbo run build` (vite transpiles, it does not typecheck), 150 tests, and every `meta verify` gate. `tsc --noEmit`, run by hand, was the only signal in the building. *And `tsc` cannot see the half that compiles.* `baseUrl` is optional with default `""`, so reading the note, renaming `value` → `fetcher` and stopping there is type-correct and silently drops the prefix from every generated hook: | leave `value={fetcher}` | tsc (TS2322), if anything runs it | | rename to `fetcher={fetcher}`, stop | nothing at the type level | The likelier outcome is the second, because it compiles. On that estate it would have shipped eleven objects × five hooks plus six grids 404ing across a public storefront and an admin app. A project whose apiPrefix is `""` is unaffected — which is exactly why the trap is easy to ship: `meta init` scaffolds `apiPrefix: ""`, so the default-configured project is the one the design was reasoned about. So `meta verify` now advises when apiPrefix is non-empty and a source file mounts a provider with no baseUrl. It rides in the existing verify-as-teacher pass (same suppression flag, same structured row shape, never an exit code) and covers both tiers — the JSX provider and Angular's `provideEntityFetcher`. The JSX match spans the whole opening tag rather than one line, because real providers are written multi-line and a `>` inside an attribute would otherwise cut the tag in half. The migration note now states the precondition out loud instead of asserting the `tsc` guarantee as a fact. Gate: both directions of the multi-line match, both tiers, the empty-apiPrefix silence, and build output excluded — proved by breaking the tag scanner. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NTcEKXTQMYt84fAjuw5A2M
1 parent a7e2a2e commit c8f244d

5 files changed

Lines changed: 306 additions & 8 deletions

File tree

‎docs/features/migrations/api-base-url-leaves-the-entity-descriptor.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,26 @@ The `value` prop is **gone**, not deprecated, so an unmigrated app fails `tsc` r
4747
than 404ing in a browser. That is deliberate: a missing base is otherwise invisible
4848
until a request runs.
4949

50+
**Two cautions on that, both found in a real adopter tree.**
51+
52+
*It only protects you if something runs `tsc`.* `vite build` and `next build` transpile;
53+
they do not typecheck. On an estate whose web app had no `typecheck` script, no turbo
54+
task and no CI job, the unmigrated tree passed `build`, 150 tests, and every `meta
55+
verify` gate — `tsc --noEmit`, run by hand, was the only signal in the building.
56+
57+
*And it does not cover the half that compiles.* `baseUrl` is optional and defaults to
58+
`""`, so renaming `value` → `fetcher` and stopping there is type-correct and silently
59+
drops the prefix from every generated hook:
60+
61+
| what you do | caught by |
62+
|---|---|
63+
| leave `value={fetcher}` | `tsc` (TS2322) — if anything runs it |
64+
| rename to `fetcher={fetcher}` and stop | **nothing at the type level** |
65+
66+
`meta verify` now emits an advisory for exactly that shape — a non-empty `apiPrefix` and
67+
a provider mounted with no `baseUrl`. It is a warning, never an exit code, and it is the
68+
only gate that can see this half.
69+
5070
If your own code read `<Entity>.$apiPrefix`, it no longer compiles. Take the base from
5171
the same config your provider does.
5272

‎server/typescript/packages/cli/src/commands/verify.ts‎

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@ import { parseVerifyArgs, type MigrateFlags } from "../lib/args.js";
1212
import { log } from "../lib/log.js";
1313
import { emitStructured, type OutputFormat } from "../lib/format.js";
1414
import {
15-
antiPatternRows, ranSection, skippedSection, warnCapped,
15+
antiPatternRows, missingBaseUrlRows, ranSection, skippedSection, warnCapped,
1616
type AdvisoryDiagnosticRow, type AdvisoryFindingRow, type AdvisorySection,
1717
} from "../lib/advisory.js";
1818
import { warnIfAgentContextStale } from "../lib/agent-context-staleness.js";
1919
import { warnIfManifestIgnored } from "../lib/manifest-ignored-check.js";
2020
import { scanSourceForAntiPatterns } from "../lib/anti-patterns.js";
21+
import { scanForMissingBaseUrl, type BaseUrlFinding } from "../lib/base-url-advisory.js";
2122
import { replayRemedy } from "../lib/replay-remedy.js";
2223
import { FileProvider } from "../lib/file-provider.js";
2324
import { derivePayloadFieldTree } from "../lib/payload-field-tree.js";
@@ -720,13 +721,33 @@ export async function verifyCommand(
720721
antiPatternSection = skippedSection(`the scan failed: ${(err as Error).message}`);
721722
return;
722723
}
723-
antiPatternSection = ranSection(antiPatternRows(findings));
724-
if (findings.length === 0) return;
725-
log.warn(
726-
`meta verify — ${findings.length} place(s) hand-roll what MetaObjects can model ` +
727-
`(advisory — does not fail the build):`,
728-
);
729-
warnCapped(findings.map((f) => ` ${f.message}`), flags.limit, { structured });
724+
// F52 — the one gate that can see a provider silently missing its base. Folded into
725+
// this pass rather than given its own, because it is the same KIND of finding (a
726+
// teachable warning that never touches the exit code) and one --no-antipatterns
727+
// should suppress the whole advisory tier, not half of it.
728+
let baseUrl: BaseUrlFinding[] = [];
729+
try {
730+
baseUrl = scanForMissingBaseUrl(projectRoot, forgeConfig?.apiPrefix ?? "");
731+
} catch {
732+
// Same discipline as above: an advisory scan never breaks verify. The anti-pattern
733+
// half already ran, so its rows are still reported rather than lost to this catch.
734+
}
735+
736+
antiPatternSection = ranSection([...antiPatternRows(findings), ...missingBaseUrlRows(baseUrl)]);
737+
if (findings.length > 0) {
738+
log.warn(
739+
`meta verify — ${findings.length} place(s) hand-roll what MetaObjects can model ` +
740+
`(advisory — does not fail the build):`,
741+
);
742+
warnCapped(findings.map((f) => ` ${f.message}`), flags.limit, { structured });
743+
}
744+
if (baseUrl.length > 0) {
745+
log.warn(
746+
`meta verify — ${baseUrl.length} entity-fetcher provider(s) mounted with no baseUrl ` +
747+
`while apiPrefix is "${forgeConfig?.apiPrefix ?? ""}" (advisory — does not fail the build):`,
748+
);
749+
warnCapped(baseUrl.map((f) => ` ${f.message}`), flags.limit, { structured });
750+
}
730751
}
731752

732753
// -- template (prompt / output) drift --------------------------------------

‎server/typescript/packages/cli/src/lib/advisory.ts‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222

2323
import { log } from "./log.js";
2424
import type { AntiPatternFinding } from "./anti-patterns.js";
25+
import type { BaseUrlFinding } from "./base-url-advisory.js";
2526

2627
/**
2728
* How many advisory lines TEXT output prints before it truncates.
@@ -119,6 +120,20 @@ export function antiPatternRows(findings: readonly AntiPatternFinding[]): Adviso
119120
}));
120121
}
121122

123+
/**
124+
* F52 findings in the same row shape, so the structured payload has ONE advisory list
125+
* rather than a second one a consumer has to learn about. `rule` is the discriminator.
126+
*/
127+
export function missingBaseUrlRows(findings: readonly BaseUrlFinding[]): AdvisoryFindingRow[] {
128+
return findings.map((f) => ({
129+
file: f.file,
130+
line: f.line,
131+
rule: "missing-base-url",
132+
construct: f.construct,
133+
message: f.message,
134+
}));
135+
}
136+
122137
// ---------------------------------------------------------------------------
123138
// text output
124139
// ---------------------------------------------------------------------------
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
import { readdirSync, readFileSync, statSync } from "node:fs";
2+
import { join, relative, sep } from "node:path";
3+
4+
/**
5+
* F52 — a provider mounted with no `baseUrl` on a project whose `apiPrefix` is not empty.
6+
*
7+
* 1.0 moved `$apiPrefix` out of the entity descriptor: a browser's base URL is a
8+
* DEPLOYMENT fact, so the provider supplies it at runtime. The migration note argues the
9+
* rename is safe because `<EntityFetcherProvider value={…}>` no longer typechecks — and
10+
* that is true for the adopter who leaves `value` alone. It says nothing about the
11+
* adopter who reads the note, renames `value` → `fetcher`, and stops: `baseUrl` is
12+
* OPTIONAL with default `""`, so that tree compiles clean and every generated hook has
13+
* quietly lost its `/api` segment. Nothing at the type level can see it, and on the
14+
* estate where this was found nothing else could either — `vite build` transpiles without
15+
* typechecking, so `build`, 150 tests and every `meta verify` gate were green over a
16+
* storefront and an admin app whose entire generated CRUD surface would have 404'd.
17+
*
18+
* So this is the only gate that can catch it, and it is a WARNING: `baseUrl` is genuinely
19+
* optional, a project may serve its API at the origin root, and a prefix can legitimately
20+
* come from somewhere this scan cannot read. It never touches an exit code.
21+
*
22+
* It fires ONLY when `apiPrefix` is non-empty — the `meta init` scaffold sets `""`, which
23+
* is exactly why the trap is easy to ship: the default-configured project is the one the
24+
* design was reasoned about.
25+
*/
26+
export interface BaseUrlFinding {
27+
file: string;
28+
line: number;
29+
/** The provider construct found without a base. */
30+
construct: string;
31+
message: string;
32+
}
33+
34+
const IGNORE_SEGMENTS = new Set([
35+
"node_modules", ".git", "dist", "build", ".next", ".turbo", ".output",
36+
"coverage", ".metaobjects", ".wrangler",
37+
]);
38+
const SCAN_EXT = /\.(?:ts|tsx|js|jsx|mjs)$/;
39+
const SKIP_FILE = /(?:\.d\.ts$|\.test\.|\.spec\.)/;
40+
41+
/**
42+
* The two ways a base is supplied, one per client tier.
43+
*
44+
* Matched across the WHOLE opening construct rather than a single line, because a JSX
45+
* provider is nearly always written multi-line — a per-line rule (which is what the
46+
* anti-pattern scan uses) would miss the formatting every real codebase has.
47+
*/
48+
const PROVIDERS: readonly { construct: string; open: RegExp; kind: "jsx" | "call" }[] = [
49+
{ construct: "<EntityFetcherProvider>", open: /<EntityFetcherProvider\b/g, kind: "jsx" },
50+
{ construct: "provideEntityFetcher()", open: /provideEntityFetcher\s*\(/g, kind: "call" },
51+
];
52+
53+
/** Nesting introduced by `c`: +1 for an opener, -1 for a closer, 0 otherwise. */
54+
function nesting(c: string): number {
55+
if (c === "{" || c === "(" || c === "[") return 1;
56+
if (c === "}" || c === ")" || c === "]") return -1;
57+
return 0;
58+
}
59+
60+
/**
61+
* The text of the opening construct that begins at `start`.
62+
*
63+
* JSX: up to the `>` that closes the opening TAG — tracked by nesting depth, because
64+
* `onSomething={() => x}` puts a `>` inside an attribute and a naive first-`>` search
65+
* would cut the tag in half and miss a `baseUrl` written after it.
66+
*
67+
* Call: to the `)` balancing the argument list, so a nested object or arrow does not end
68+
* it early.
69+
*
70+
* Both bail after a generous cap rather than scanning a whole minified file when a
71+
* construct is unterminated.
72+
*/
73+
function constructText(src: string, start: number, kind: "jsx" | "call"): string {
74+
const limit = Math.min(src.length, start + 4000);
75+
let depth = 0;
76+
for (let i = start; i < limit; i++) {
77+
const c = src[i]!;
78+
if (kind === "jsx" && c === ">" && depth === 0) return src.slice(start, i + 1);
79+
depth += nesting(c);
80+
if (kind === "call" && depth === 0 && c === ")") return src.slice(start, i + 1);
81+
}
82+
return src.slice(start, limit);
83+
}
84+
85+
function scanFile(rel: string, src: string, apiPrefix: string): BaseUrlFinding[] {
86+
const out: BaseUrlFinding[] = [];
87+
for (const { construct, open, kind } of PROVIDERS) {
88+
open.lastIndex = 0;
89+
let m: RegExpExecArray | null;
90+
while ((m = open.exec(src)) !== null) {
91+
const text = constructText(src, m.index, kind);
92+
if (/\bbaseUrl\b/.test(text)) continue;
93+
const line = src.slice(0, m.index).split("\n").length;
94+
out.push({
95+
file: rel, line, construct,
96+
message:
97+
`${rel}:${line} — ${construct} is mounted with no baseUrl, but this project's ` +
98+
`apiPrefix is "${apiPrefix}". Every generated hook fetches a path RELATIVE to ` +
99+
`baseUrl, which defaults to "", so those requests go to the origin root and miss ` +
100+
`"${apiPrefix}". Pass baseUrl (a literal, or your build's env var). If the API ` +
101+
`really is served at the root here, this is a false positive — ignore it.`,
102+
});
103+
}
104+
}
105+
return out;
106+
}
107+
108+
function walk(dir: string, root: string, acc: BaseUrlFinding[], apiPrefix: string): void {
109+
let entries;
110+
try { entries = readdirSync(dir, { withFileTypes: true }); } catch { return; }
111+
for (const e of entries) {
112+
if (e.name.startsWith(".") && e.name !== ".") { if (IGNORE_SEGMENTS.has(e.name)) continue; }
113+
if (IGNORE_SEGMENTS.has(e.name)) continue;
114+
const abs = join(dir, e.name);
115+
// Follow directories through symlinks the way the anti-pattern scan does not need to,
116+
// but never re-enter one: statSync on a broken link throws, which is caught here.
117+
let isDir: boolean;
118+
try { isDir = e.isDirectory() || (e.isSymbolicLink() && statSync(abs).isDirectory()); }
119+
catch { continue; }
120+
if (isDir) { walk(abs, root, acc, apiPrefix); continue; }
121+
if (!SCAN_EXT.test(e.name) || SKIP_FILE.test(e.name)) continue;
122+
let src: string;
123+
try { src = readFileSync(abs, "utf8"); } catch { continue; }
124+
if (!src.includes("EntityFetcher")) continue;
125+
acc.push(...scanFile(relative(root, abs).split(sep).join("/"), src, apiPrefix));
126+
}
127+
}
128+
129+
/**
130+
* Scan a project tree for providers mounted without a base.
131+
*
132+
* Returns [] when `apiPrefix` is empty — there is nothing to lose then, and warning would
133+
* fire on every scaffolded project.
134+
*/
135+
export function scanForMissingBaseUrl(root: string, apiPrefix: string): BaseUrlFinding[] {
136+
if (apiPrefix === "") return [];
137+
const acc: BaseUrlFinding[] = [];
138+
walk(root, root, acc, apiPrefix);
139+
return acc;
140+
}
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
// F52 — the half of the 1.0 base-URL migration that nothing else can see.
2+
//
3+
// `<EntityFetcherProvider value={fetcher}>` no longer typechecks, and the migration note
4+
// rests its safety argument on that. But `baseUrl` is OPTIONAL, defaulting to "", so an
5+
// adopter who reads the note, renames `value` → `fetcher` and stops has a tree that
6+
// compiles clean while every generated hook has quietly lost its `/api` segment. On the
7+
// estate where this was found, `vite build`, 150 tests and every `meta verify` gate were
8+
// green over two apps whose entire generated CRUD surface would have 404'd; `tsc --noEmit`
9+
// run by hand was the only signal in the building, and it cannot see this half at all.
10+
11+
import { describe, test, expect, afterAll } from "bun:test";
12+
import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
13+
import { tmpdir } from "node:os";
14+
import { join } from "node:path";
15+
import { scanForMissingBaseUrl } from "../src/lib/base-url-advisory.js";
16+
17+
const dirs: string[] = [];
18+
afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); });
19+
20+
async function project(files: Record<string, string>): Promise<string> {
21+
const root = await mkdtemp(join(tmpdir(), "meta-baseurl-"));
22+
dirs.push(root);
23+
for (const [rel, content] of Object.entries(files)) {
24+
await mkdir(join(root, rel, ".."), { recursive: true });
25+
await writeFile(join(root, rel), content, "utf8");
26+
}
27+
return root;
28+
}
29+
30+
describe("scanForMissingBaseUrl", () => {
31+
test("the half that compiles — renamed to fetcher, no baseUrl", async () => {
32+
const root = await project({
33+
"src/main.tsx": `<EntityFetcherProvider fetcher={fetcher}>\n <App />\n</EntityFetcherProvider>`,
34+
});
35+
const found = scanForMissingBaseUrl(root, "/api");
36+
expect(found).toHaveLength(1);
37+
expect(found[0]!.file).toBe("src/main.tsx");
38+
expect(found[0]!.message).toContain("/api");
39+
});
40+
41+
test("silent when the provider passes a base", async () => {
42+
const root = await project({
43+
"src/main.tsx": `<EntityFetcherProvider fetcher={fetcher} baseUrl="/api">`,
44+
});
45+
expect(scanForMissingBaseUrl(root, "/api")).toEqual([]);
46+
});
47+
48+
test("silent when apiPrefix is empty — what `meta init` scaffolds", async () => {
49+
// The trap ships easily precisely because the DEFAULT-configured project is the one
50+
// the design was reasoned about. Firing here would nag every scaffolded project.
51+
const root = await project({ "src/main.tsx": `<EntityFetcherProvider fetcher={fetcher}>` });
52+
expect(scanForMissingBaseUrl(root, "")).toEqual([]);
53+
});
54+
55+
test("multi-line JSX with a `>` inside an attribute is still matched", async () => {
56+
// A per-line rule (which is what the anti-pattern scan uses) sees neither the
57+
// provider and its props together nor past an arrow function. Real code is written
58+
// this way, so a scan that only handled one line would report clean on the estate.
59+
const root = await project({
60+
"src/main.tsx": [
61+
`<EntityFetcherProvider`,
62+
` fetcher={fetcher}`,
63+
` onError={(e) => report(e)}`,
64+
`>`,
65+
].join("\n"),
66+
});
67+
expect(scanForMissingBaseUrl(root, "/api")).toHaveLength(1);
68+
});
69+
70+
test("multi-line JSX that DOES pass a base after an arrow attribute is silent", async () => {
71+
// The other half of the same mechanism: cutting the tag at the first `>` would end it
72+
// inside `onError` and report a false positive on a correct file.
73+
const root = await project({
74+
"src/main.tsx": [
75+
`<EntityFetcherProvider`,
76+
` fetcher={fetcher}`,
77+
` onError={(e) => report(e)}`,
78+
` baseUrl={import.meta.env.VITE_API_BASE}`,
79+
`>`,
80+
].join("\n"),
81+
});
82+
expect(scanForMissingBaseUrl(root, "/api")).toEqual([]);
83+
});
84+
85+
test("the Angular provider is covered too", async () => {
86+
const bare = await project({ "src/app.config.ts": `provideEntityFetcher({ fetcher })` });
87+
expect(scanForMissingBaseUrl(bare, "/api")).toHaveLength(1);
88+
const full = await project({
89+
"src/app.config.ts": `provideEntityFetcher({ fetcher, baseUrl: "/api" })`,
90+
});
91+
expect(scanForMissingBaseUrl(full, "/api")).toEqual([]);
92+
});
93+
94+
test("build output and dependencies are not scanned", async () => {
95+
const root = await project({
96+
"node_modules/pkg/index.js": `<EntityFetcherProvider fetcher={f}>`,
97+
"dist/main.js": `<EntityFetcherProvider fetcher={f}>`,
98+
"src/x.test.tsx": `<EntityFetcherProvider fetcher={f}>`,
99+
});
100+
expect(scanForMissingBaseUrl(root, "/api")).toEqual([]);
101+
});
102+
});

0 commit comments

Comments
 (0)