/** * The per-file and per-root static checks `addon:gate` runs on an addon in its * own repository (planning#842). Pure: text in, findings out. The rules that * already exist in `scripts/` (secret fields, raw secret reads, client secrets) * are imported by the gate, never copied; what lives here is new. */ import * as fs from 'node:fs' import * as path from 'node:path' import ts from 'typescript' export interface GateFinding { readonly file: string readonly line: number readonly message: string } function parse(file: string, text: string): ts.SourceFile { const kind = file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS return ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, kind) } function lineOf(sf: ts.SourceFile, node: ts.Node): number { return sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1 } function visitAll(sf: ts.SourceFile, fn: (node: ts.Node) => void): void { const walk = (n: ts.Node): void => { fn(n) ts.forEachChild(n, walk) } walk(sf) } /** `as any`, `x`, `as never`, `as unknown as X`. `as const` and a plain `as X` pass. */ export function castFindings(file: string, text: string): readonly GateFinding[] { const sf = parse(file, text) const out: GateFinding[] = [] visitAll(sf, (n) => { if (ts.isAsExpression(n) || ts.isTypeAssertionExpression(n)) { const kind = n.type.kind if (kind === ts.SyntaxKind.AnyKeyword) { out.push({ file, line: lineOf(sf, n), message: '`as any` — use a type guard or a generic' }) } else if (kind === ts.SyntaxKind.NeverKeyword) { out.push({ file, line: lineOf(sf, n), message: '`as never` — use a type guard or a generic', }) } } if (ts.isAsExpression(n) && ts.isAsExpression(n.expression)) { if (n.expression.type.kind === ts.SyntaxKind.UnknownKeyword) { out.push({ file, line: lineOf(sf, n), message: '`as unknown as X` — narrow with a type guard or parse with Zod', }) } } }) return out } /** Any `console.` call in product source: the injected scoped logger is the only channel. */ export function consoleFindings(file: string, text: string): readonly GateFinding[] { const sf = parse(file, text) const out: GateFinding[] = [] visitAll(sf, (n) => { if ( ts.isPropertyAccessExpression(n) && ts.isIdentifier(n.expression) && n.expression.text === 'console' ) { out.push({ file, line: lineOf(sf, n), message: `console.${n.name.text} — log through the injected IScopedLogger`, }) } }) return out } const LOG_METHODS: ReadonlySet = new Set([ 'trace', 'debug', 'info', 'warn', 'error', 'log', 'verbose', ]) const LOGGER_RECEIVER = /(?:^|\.)(?:logger|log|scopedLogger)$/i const DEVICE_ID = /\bdeviceId\b/ function carriesDeviceTag(arg: ts.Expression, sf: ts.SourceFile): boolean { if (!ts.isObjectLiteralExpression(arg)) return false return arg.properties.some( (p) => ts.isPropertyAssignment(p) && p.name.getText(sf) === 'tags' && DEVICE_ID.test(p.initializer.getText(sf)), ) } /** * A logger call whose arguments mention `deviceId` but carry no `tags: { deviceId }`. * * CONSERVATIVE on purpose: it only sees a call on a receiver named `logger` / `log` / * `scopedLogger` (also `this.logger`, `ctx.logger`) that spells the word `deviceId` * in its own arguments. A device line whose id arrives through a variable named * otherwise (`id`, `camera.id`) or through a pre-built meta object is NOT seen: * the repo rule ("every device log line carries tags: { deviceId }") stays a * review item there. */ export function loggerTagFindings(file: string, text: string): readonly GateFinding[] { const sf = parse(file, text) const out: GateFinding[] = [] visitAll(sf, (n) => { if (!ts.isCallExpression(n) || !ts.isPropertyAccessExpression(n.expression)) return const callee = n.expression if (!LOG_METHODS.has(callee.name.text)) return if (!LOGGER_RECEIVER.test(callee.expression.getText(sf))) return if (!n.arguments.some((a) => DEVICE_ID.test(a.getText(sf)))) return if (n.arguments.some((a) => carriesDeviceTag(a, sf))) return out.push({ file, line: lineOf(sf, n), message: `logger.${callee.name.text} about a device without tags: { deviceId }`, }) }) return out } const BARREL = '@dominevo/types' const VALUE_NAME = /^(?:BaseAddon|ALL_CAPABILITY_DEFINITIONS|[a-z]\w*Capability)$/ /** * A VALUE import of `BaseAddon` or a capability definition from the * `@dominevo/types` barrel pulls the whole contract graph into the addon bundle * (megabytes). `leanExports` is what `@dominevo/types/addon` exports; a name in * it is told the subpath, any other names the barrel cost only. */ export function barrelImportFindings( file: string, text: string, leanExports: ReadonlySet, ): readonly GateFinding[] { const sf = parse(file, text) const out: GateFinding[] = [] for (const stmt of sf.statements) { if (!ts.isImportDeclaration(stmt) || !ts.isStringLiteral(stmt.moduleSpecifier)) continue if (stmt.moduleSpecifier.text !== BARREL) continue const clause = stmt.importClause if (clause === undefined || clause.isTypeOnly) continue const bindings = clause.namedBindings if (bindings === undefined || !ts.isNamedImports(bindings)) continue for (const el of bindings.elements) { if (el.isTypeOnly) continue const name = (el.propertyName ?? el.name).text if (!VALUE_NAME.test(name)) continue const fix = leanExports.has(name) ? `import it from '@dominevo/types/addon'` : `no lean subpath exports it — resolve the capability through ctx.api instead of importing its definition` out.push({ file, line: lineOf(sf, el), message: `value import { ${name} } from '${BARREL}' pulls the whole barrel into the bundle — ${fix}`, }) } } return out } /** The names `@dominevo/types/addon` exports, read from this checkout's `addon.ts`. */ export function leanAddonExports(addonTsText: string): ReadonlySet { const names = new Set() for (const m of addonTsText.matchAll(/export\s+(?:type\s+)?\{([^}]*)\}/g)) { for (const part of (m[1] ?? '').split(',')) { const name = (part.split(/\sas\s/).pop() ?? '').replace(/^type\s+/, '').trim() if (name) names.add(name) } } return names } /** Entries of `packagesDir` (and their direct children) that are, or resolve into, `root`. */ export function linksIntoRoot(packagesDir: string, root: string): readonly string[] { if (!fs.existsSync(packagesDir)) return [] const real = fs.realpathSync(root) const inside = (p: string): boolean => { try { const target = fs.realpathSync(p) return target === real || target.startsWith(`${real}${path.sep}`) } catch { return false } } const out: string[] = [] for (const name of fs.readdirSync(packagesDir)) { const first = path.join(packagesDir, name) if (inside(first)) out.push(first) let stat: fs.Stats try { stat = fs.lstatSync(first) } catch { continue } if (!stat.isDirectory() || stat.isSymbolicLink()) continue for (const child of fs.readdirSync(first)) { if (child === 'node_modules') continue const second = path.join(first, child) if (inside(second)) out.push(second) } } return out } /** Product source of an external addon: `.ts` / `.tsx` under `src`, no tests, no declarations. */ export function sourceFilesOf(root: string): readonly string[] { const out: string[] = [] const walk = (dir: string): void => { if (!fs.existsSync(dir)) return for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { const full = path.join(dir, entry.name) if (entry.isDirectory()) { if (!['node_modules', 'dist', '__tests__', '__mocks__'].includes(entry.name)) walk(full) } else if ( /\.tsx?$/.test(entry.name) && !entry.name.endsWith('.d.ts') && !/\.(spec|test)\.tsx?$/.test(entry.name) ) { out.push(full) } } } walk(path.join(root, 'src')) return out } /** True when `[Unreleased]` holds at least one `- ` entry. */ export function hasUnreleasedEntry(changelog: string): boolean { const start = changelog.search(/^## \[Unreleased\]/m) if (start === -1) return false const after = changelog.slice(start).split('\n').slice(1) for (const line of after) { if (line.startsWith('## ')) break if (/^-\s+\S/.test(line)) return true } return false }