NEW @W-23659201@ Add uibundle engine to Code Analyzer Core - #499
NEW @W-23659201@ Add uibundle engine to Code Analyzer Core#499amritmishra-sf wants to merge 11 commits into
Conversation
Introduces `@salesforce/code-analyzer-uibundle-engine`, a new SFCA v5 engine plugin that validates UI Bundle build output. Named generically so additional UI-bundle rule families can be added later without a package rename. Initial ruleset (8 rules) covers sourcemap-integrity: missing sourcemap, path leakage, invalid source references, VLQ integrity, source content verification, coverage analysis, structural coherence, token consistency. Whitelists the new package in .node-scripts/validate-changed-package-versions.js since it has not yet been published to the registry.
|
Git2Gus App is installed but the |
Covers what the engine is for, when to use it, how bundle targets are detected, and a per-rule reference for all 8 rules including how each one works, why it matters, and the constants/thresholds involved.
Adds the new @salesforce/code-analyzer-uibundle-engine plugin to the CLI's EnginePluginsFactoryImpl so it runs alongside the other engines with `sf code-analyzer run`. Depends on forcedotcom/code-analyzer-core#499 being merged and the engine package being published before this PR's CI can go green.
aruntyagiTutu
left a comment
There was a problem hiding this comment.
Reviewed the new code-analyzer-uibundle-engine package (engine.ts, plugin.ts, messages.ts, rules.ts, all 8 validators, and tests). Solid first cut — async I/O throughout (no sync fs calls), good use of caching (sourceAstCache, embeddedCache), tests have real assertions and cover error paths (missing sourcemap, bad VLQ, leaked paths, missing source refs), and the PR description accurately matches what's implemented (8 rules, goldfile test, companion PR sequencing noted).
A few non-blocking suggestions:
-
Redundant source-tree indexing across validators (perf).
source-content-verification.ts,structural-coherence.ts, andtoken-consistency.tseach independently walk + read + index the entire source tree via their ownindexSourceFiles(). When all three rules run together (the default), the source tree gets walked and every file re-read/re-indexed 3x. Per the team's "minimize passes over data" guideline, consider hoisting the source index intorunOnTarget()inengine.tsand passing a shared index into each validator, so it's built once per target regardless of how many source-dependent rules are selected. -
Duplicated helper code.
indexSourceFiles,expandIndexWithBase, andINDEX_IGNORE_PREFIXESare copy-pasted verbatim betweenstructural-coherence.tsandtoken-consistency.ts(and a near-identical variant lives insource-content-verification.ts). Worth extracting intosourcemap-io.tsas a shared utility — would also make suggestion #1 easier to implement in one place. -
findNodeAtOffset's early break (source-content-verification.ts) assumesnodes[]is sorted bybyteOffset. That holds today becausecollectSignificantNodesrelies on Babel's enter-order traversal producing non-decreasing start offsets, but it's an implicit invariant, not asserted or documented at the call site. If that ever changes (e.g. a traversal tweak), thebreakwould silently drop valid matches rather than erroring. A short comment noting the sortedness assumption (or an explicit sort before this loop) would make it safer to modify later. -
Minor:
DANGEROUS_API_PATTERNSbuilds"eval("and"Function("via["ev","al","("].join("")style construction with no comment explaining why — presumably to avoid this scanner's own dangerous-pattern list from tripping other static-analysis tools on itself. A one-line comment would save the next reader some head-scratching.
None of these block merge — nice addition to the engine lineup.
| @@ -0,0 +1,14 @@ | |||
| BSD 3-Clause License | |||
There was a problem hiding this comment.
is the license file present for all engines ?
There was a problem hiding this comment.
yes, it seems like other engines have this too
Automated review — Code Analyzer team standardsReviewed against the team's PR review standards (performance, naming, validation, logging, testing, compatibility, cross-platform, dependencies). Checked out the PR branch and read every changed source/test/doc file directly. Overall verdict: Changes RequestedPer this team's own trigger list, two things independently qualify: a performance-sensitive hot path shipped with zero large-project measurement, and a correctness bug in the Critical-severity rule that causes false positives. 🔴 BlockingPerformance —
Correctness —
Performance —
Correctness — Windows path separators (duplicated bug in both files)
Math bug —
Test suite — vacuous assertions
Architecture — DRY violation
🟡 Medium (worth resolving before merge)
🟢 Low / nits
✅ Clean
Bottom line: solid first cut of a new engine with good structural conventions (sibling-package parity, message catalog pattern, async I/O throughout), but the three biggest sourcemap-analysis validators ( Generated via automated review against the Code Analyzer team's PR standards (604 review comments / 339 merged PRs analysis). |
…ce-content-verification severity Skips webpack/vite/?raw virtual pseudo-sources when checking whether a mapped AST node's source is present on disk, matching the existing byte-equal gate. Fixes false-positive "not present in the submitted source tree" findings for GraphQL ?raw imports and other bundler virtuals in clean bundles. Also drops source-content-verification from Critical to High so all Layer-1 gating rules share the same severity, and updates the goldfile to reflect the reduced tag set (UIBundleIntegrity only).
aruntyagiTutu
left a comment
There was a problem hiding this comment.
Thanks for the fix — mirroring the Layer-1 virtual-source skip (isVirtualSource/isDependency/isAsset) into the AST orphan check in runAstChecks makes sense, and the comment explaining why (bundler pseudo-sources like ?raw/webpack/vite internals aren't part of the submitted tree, with the ratio gate still catching abuse) is clear. Severity alignment (Critical→High for source-content-verification, matching the other Layer-1 rules) also seems reasonable.
One non-blocking gap: I don't see a new test that exercises this specific AST-path fix — e.g. a mapped node whose orig.source resolves to a virtual/dependency/asset path, asserting no "not present in the submitted source tree" (orphan) finding is raised. The existing virtual-source tests (does not flag virtual or relative sources, skips virtual and remote sources, `flags a virtual-source ratio above threshold") cover other validators/the Layer-1 byte-equal gate, but not this AST branch specifically. Since this was a real false-positive bug, a regression test would help guard against it recurring.
Not blocking — happy to approve once tests pass in CI.
- Normalize CRLF/CR to LF before byte-equal sourcesContent comparison so CRLF checkouts on Windows don't spuriously trip source-content-verification. - Normalize path.relative output to forward-slash when indexing source trees in source-content-verification, structural-coherence, and token-consistency so lookups against sourcemap sources[] entries succeed on Windows. - Fix structural-coherence whitespace-ratio denominator: track actual sample fires instead of dividing by floor(totalMappings/10). Previously the ratio could exceed 100% because sample count exceeded floor(N/10) for N not divisible by 10. - Replace vacuous Array.isArray / length>=0 assertions in validators-integration.test.ts with meaningful behavioral checks. - Remove MIGRATION.md — no sibling engine ships one and there is no precursor to migrate from now that this is the canonical location.
CI runs `tsc --build tsconfig.json && jest`. The tsc pass has been failing
across all platforms because:
- `encode()` expects `SourceMapSegment[][]` where each segment is a fixed-
length tuple (`[number, number, number, number]` etc.). Test helpers
declared their input as `number[][]` / `number[][][]`, which no longer
narrows to the tuple union in `@jridgewell/sourcemap-codec@1.5.5`.
- `new TraceMap({...})` inputs need to be typed as `SourceMapInput`
because the object literal's `mappings: string` field otherwise fails
to select the `EncodedSourceMapXInput` branch of the union.
Tighten the test helpers and cast the constructor inputs. Behavior
unchanged; jest was already green — this only fixes the pre-jest tsc gate.
aruntyagiTutu
left a comment
There was a problem hiding this comment.
Thanks for these fixes — all look correct:
- CRLF/CR normalization before byte-equal comparison and forward-slash normalization on
path.relativeoutput resolve real Windows correctness bugs (source indexing/lookup would otherwise fail on Windows checkouts). - The whitespace-ratio fix in
structural-coherence.tsis right —whitespaceSampleCountnow tracks actual sample fires (matching thesampleIndex % INTERVAL === 0condition) instead offloor(total/10), which could previously push the ratio over 100%. - The strengthened test assertions (replacing
Array.isArray(...)/length >= 0with real checks for byte-mismatch, unloadable-sourcemap, whitespace, and cross-file-jump findings) are a solid improvement — these now actually verify behavior instead of trivially passing. - Removing
MIGRATION.mdand fixing the tsc tuple-typing issues in test helpers are sensible cleanup.
LGTM.
| return [ | ||
| "packages/ENGINE-TEMPLATE" | ||
| "packages/ENGINE-TEMPLATE", | ||
| "packages/code-analyzer-uibundle-engine" |
There was a problem hiding this comment.
remember to revert this piece of code post PR merge
There was a problem hiding this comment.
I accidentally, removed this now. It seems to have broken the build. I will add it back and revert it post merge
Drop cross-repo and section-header comments so only WHY comments remain, keeping the validator source readable standalone.
The validate-changed-package-versions script had a temporary bypass for packages/code-analyzer-uibundle-engine while the package was unpublished.
…ource Drop section-header comments, inline what-comments, and jsdoc that only described obvious behavior. Well-named identifiers already carry the meaning.
aruntyagiTutu
left a comment
There was a problem hiding this comment.
Commit 299ceccc removes packages/code-analyzer-uibundle-engine from the unpublished-package whitelist in .node-scripts/validate-changed-package-versions.js, but the package still isn't published to npm (confirmed: npm view @salesforce/code-analyzer-uibundle-engine version → 404).
This will crash the verify-pr.yml version-check step for this PR itself (and any future PR touching this package) — not just fail a check, but throw an uncaught exception:
getLatestReleasedVersioncatches thenpm view404 and returnsundefined(handled fine).- But then
semver.parse(undefined)returnsnull(not a throw), and the subsequentsemver.lte(semver.parse(currentVersion), null)throwsInvalid version. Must be a string. Got type "object"— uncaught, crashing the script with a nonzero exit.
I verified this locally against the repo's actual semver dependency:
semver.parse(undefined) // => null
semver.lte(semver.parse('0.1.0'), null) // throws "Invalid version. Must be a string. Got type \"object\""
Since this same commit still touches files under packages/code-analyzer-uibundle-engine, the next CI run for this PR should hit this path. Recommend keeping the whitelist entry until the package is actually published (revert this piece of 299ceccc), or hardening identifyIncorrectlyVersionedPackages to treat an unresolvable releasedPackageVersion as "not yet published → skip" rather than assuming npm view failing implies a comparable prior version exists.
The rest of this push (comment trimming across the uibundle validators, dropping the // Babel columns are 0-based / // SFCA requires... type comments) is a reasonable readability cleanup with no functional change — no concerns there.
The uibundle package is not yet published to npm, so npm view returns 404 and the version-check crashes. Restore the whitelist entry until first publish.
Rule descriptions in messages.ts already document each rule's behavior; a separate README duplicates that content and drifts out of sync.
aruntyagiTutu
left a comment
There was a problem hiding this comment.
Confirmed — the whitelist entry for packages/code-analyzer-uibundle-engine is restored in 7b6b7f9e, resolving the version-check crash from my previous review. The uibundle README removal (e91cbdc7) is also reasonable since messages.ts already documents each rule's behavior and a separate README would drift out of sync.
The remaining files in this diff (apexguru-engine changes) came in via the merge from dev (PR #500), not new work on this branch — no action needed there.
LGTM.
ankitsinghkuntal09
left a comment
There was a problem hiding this comment.
Verified sanity plus regression:
W-23659201-Testing-Scenarios: https://docs.google.com/document/d/1amoe4NyOCJZVK3RAjZy23jJX9W1TLVhJ/edit
nikhil-mittal-165
left a comment
There was a problem hiding this comment.
Updated review — tracking what's still open (posting for the record; please read past the green state)
Re-reviewed the current branch head against the team's PR standards after the fix commits. The correctness + CI-integrity blockers from the earlier round are genuinely resolved — credit where due. This comment intentionally tracks only what's still open so it doesn't get buried under the approvals.
✅ Confirmed fixed (no action needed)
- CRLF/CR normalization before the byte-equal check (
normalizeLineEndings) —source-content-verification.ts:216 - Windows path separators normalized (
toPosixPath(path.relative(...))) in all three source indexers - Whitespace-ratio denominator now tracks actual sample fires —
structural-coherence.ts:85 - The four vacuous integration tests (
length >= 0/Array.isArray) replaced with real behavioral assertions - Whitelist entry restored — the
verify-pr.ymlversion-check crash is resolved MIGRATION.md/README.mdremoved, comment bloat trimmed, severityCritical → High
🔴 Still open — please address or explicitly defer with a GUS follow-up
1. Missing regression test for the AST virtual-source skip (commit 35cd871).
This was flagged on 08-18 and never added. The false-positive fix in runAstChecks (source-content-verification.ts:277) shipped with no test — nothing asserts that a mapped node whose orig.source resolves to a virtual/dependency/asset path raises no orphan finding. It was a real false-positive bug; it needs a guard so it can't silently regress.
2. Performance / DRY cluster — never addressed (my earlier review + the two non-blocking suggestions on 08-17).
Mitigated only by removing the engine from default scans, not fixed in code:
source-content-verification,structural-coherence, andtoken-consistencyeach independently walk + read + index the entire source tree —indexSourceFiles(plusexpandIndexWithBase/INDEX_IGNORE_PREFIXES) is copy-pasted verbatim across all three. When all three run (the default selection), the tree is read and re-indexed 3×. Hoist a single shared index intorunOnTarget()inengine.tsand pass it into each validator.analyzeCoherencere-splits every source into line-lengths per dist file, andclassifyTokenAt/nameExistsNearcallsplit("\n")on the full source on every sampled mapping. Precompute once per file.findNodeAtOffset(source-content-verification.ts:421) scans from index 0 on every call — O(N·M) on large files — and its earlybreaksilently assumesnodes[]is byte-offset-sorted (an undocumented invariant). Binary search + a comment, or at minimum document the invariant.- No large-project measurement was done. Per our own standard, this path needs before/after numbers on a project with thousands of files before it's ever enabled by default.
3. coverage-analysis under-reports on the realistic case.
It credits everything from the first mapped column to end-of-line as "covered" (coverage-analysis.ts:129-133), so a single-line minified bundle — the common shipped shape — reads ~100% coverage regardless of internal gaps.
🟡 Medium
4. Column convention is inconsistent and off-by-one in places.
toViolation treats validator columns as 0-based and adds 1 (engine.ts:180). But:
coverage-analysis.ts:63emitsstartCol + 1(already 1-based) → double-incremented, reports the column one too highpath-leakage/missing-sourcemap/invalid-source-referencesemit hardcodedstartColumn: 1→ reported as column 2- only
source-content-verification(raw 0-based) round-trips correctly
Pick one convention (validators emit 0-based, engine converts) and make all validators follow it.
5. path-leakage misses common CI/container roots.
isLeaking (path-leakage.ts:7-9) only catches /Users|home|root, drive letters, UNC, and file://. It misses /app, /build, /opt, /tmp, /var — exactly the absolute paths CI and Docker builds tend to leak, which is the rule's stated purpose.
6. Dead message-catalog entries + drift risk.
NoBundleTargetsFound, SkippedForTarget, and SkippedNoSourceTree exist in messages.ts but the engine hardcodes the same strings inline (engine.ts:71,116,137). Wire them up or delete them so the two copies can't drift.
7. collectSourceMaps silently drops malformed JSON (sourcemap-io.ts:29, "vlq-integrity surfaces malformed JSON") — breaks if vlq-integrity is deselected while path-leakage / invalid-source-references still run.
8. Test temp dirs are never cleaned up.
makeTmpDir is called ~40× with no afterEach/afterAll; the docstring itself concedes cleanup is left to the caller. These accumulate in CI over time.
9. Missing error-path tests — VlqDecodingFailed (corrupt VLQ) and the token-consistency malformed-map path are untested. Branch coverage sits at 81.7% vs 91–99% for statements, and this is where the gap is.
10. Whitelist has no in-code "remove once published" marker.
The revert is tracked only in a PR comment thread. Add a // TODO: remove once @salesforce/code-analyzer-uibundle-engine is published (W-23659201) next to the entry in validate-changed-package-versions.js so it isn't silently left disabling version-bump checks forever.
🟢 Nits
- Per-target
Warnlogs aren't aggregated (engine.ts) — consolidate per the logging standard. describeRulesreturns the shared mutableRULESarray by reference (engine.ts:60) — return a copy.- Ambiguous
idxinengine.ts:200(it's the lastdistsegment index). messages.tsuses "does not" / "do not" — team style prefers contractions.engine.test.tsrule cases areit.each()candidates.
Net: the merge-blockers are cleared, but items 1–3 are the ones I'd want resolved — or consciously deferred with a GUS follow-up — before this engine is ever switched into a default scan. Happy to pair on the shared-index refactor, since it collapses most of item 2 into one change.


Summary
Adds a new SFCA v5 engine plugin
@salesforce/code-analyzer-uibundle-enginethat validates UI Bundle build output.The engine is named generically (
uibundle) so additional UI-bundle rule families can be added later without a package rename. The initial ruleset ships 8 sourcemap-integrity rules.What's included
packages/code-analyzer-uibundle-engine/— engine classUIBundleEngine(NAME =uibundle), pluginUIBundleEnginePlugin, following the sibling-engine layout.missing-sourcemap,path-leakage,invalid-source-references,vlq-integrity,source-content-verification(Critical),coverage-analysis,structural-coherence,token-consistency.getMessageFromCatalog, goldfile-tested attest/test-data/uibundle-engine-goldfile.json..node-scripts/validate-changed-package-versions.jsfor the not-yet-published package.Test plan
npm run build— cleannpm run lint— cleannpx jest --coverage— 69/69 pass, 4 suitesCompanion PR
CLI-side registration: forcedotcom/code-analyzer#2080 — pins
@salesforce/code-analyzer-uibundle-engine@0.1.0-SNAPSHOT, so it can only go green once this engine is published. Sequence the merge accordingly.Related