perf(bundle): drop the BAS chart and the Node crypto polyfill from the shared client baseline (#1942)

* perf(bundle): drop the BAS chart and the Node crypto polyfill from the shared client baseline

Two chunks rode along in the first-load JS of almost every dashboard route:
the full BAS 2026 chart (315 KB uncompressed, in 81 route manifests) and
the browser polyfill for Node's crypto/vm/Buffer (327 KB, in 26 routes
incl. login and register). Neither was needed on first paint; both got
there through static imports of helpers that happen to live next to code
that needs the data or the builtin.

Node polyfill (4 pure splits, behaviour unchanged, re-exported from the
original modules for server callers):
- lib/auth/bankid-flags.ts: isBankIdEnabled (login, register, security
  settings imported it from bankid.ts, which imports crypto).
- lib/import/bank-file/formats.ts: the format registry + detection (the
  import history imported getFormat from parser.ts, which hashes).
- lib/salary/personnummer-format.ts: parsing/validation/formatting (the
  employee forms reached the encrypting personnummer.ts via tax-column).
- lib/auth/api-key-scopes.ts: scope catalogue, groups, tool map, helpers
  (the API key panel imported STAGING_SCOPES from the key generator).

BAS chart:
- lib/bookkeeping/bas-lazy.ts + use-bas-reference.ts: the chart becomes a
  dynamic import, fetched once per session after first paint; components
  that show BAS names/descriptions call useBasReference() and re-render
  when it lands. Until then (and on the server) only the hardcoded
  account-descriptions answer, so SSR and hydration agree.
- lib/bookkeeping/bas-labels.ts: class/group labels out of bas-reference.ts
  (account-descriptions needed a label and paid for the whole chart).
- lib/bookkeeping/bas-account-numbers.ts (generated, ~11 KB) +
  scripts/generate-bas-account-numbers.ts (--check) + parity test:
  isStandardBASAccountNumber for AddAccountDialog/ChartOfAccountsManager.
- lib/bookkeeping/account-classifier-{heuristic,client}.ts: the BAS-aligned
  heuristic shared by the server classifier and a client variant that uses
  the lazy chart.
- lib/bookkeeping/invoice-accounts.ts: INVOICE_FX_RATE_MISSING,
  InvoiceFxRateMissingError, getRevenueAccount, getOutputVatAccount out of
  invoice-entries.ts, whose engine import pulled account-backfill and the
  chart into SendInvoiceDialog/PaymentBookingDialog.
- CorrectOpeningBalanceDialog re-seeds names when the chart lands;
  OpeningBalanceRowEditor builds its Fuse indexes lazily; the
  ChartOfAccountsManager BAS-katalog tab awaits the chunk.

Tooling:
- scripts/perf/client-import-closure.mjs: static import closure of every
  'use client' module with the shortest chain to a target (file or bare
  specifier); found every path above without a build.
- scripts/checks/client-node-builtin.mjs wired into check:guards: a client
  module reaching a Node builtin is a hard failure (0 today).

Left as is: invoices/[id], its credit page and SendInvoiceDialog still
reach the chart through lib/invoices/issue-credit-note -> invoice-entries
-> engine -> account-backfill; splitting the engine is out of scope here.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(perf): unambiguous import-edge regex in the closure walker (CodeQL js/redos)

One quantifier per span: a greedy [^'"]* up to the specifier quote, which it
cannot cross, so a run of whitespace has a single parse. Same edges as
before (multi-line named imports, re-exports, side-effect imports; type-only
imports still skipped).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Jakob Wennberg <311770904+jakobwennberg-oss@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Jakob Wennberg
2026-08-26 15:07:49 +02:00
committed by GitHub
co-authored by Claude Fable 5 Jakob Wennberg
parent e7e4efbfbc
commit 1a41119682
38 changed files with 1235 additions and 533 deletions
@@ -0,0 +1,58 @@
/**
* Proof that the client-node-builtin guard follows static imports from a
* 'use client' module to a Node builtin, and only those. Fixtures live in an
* OS temp directory the test creates and deletes.
*/
import { describe, it, expect, afterAll } from 'vitest'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { findClientNodeBuiltins } from '../client-node-builtin.mjs'
const tempDirs: string[] = []
afterAll(() => {
for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
})
function fixture(files: Record<string, string>) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'client-builtin-'))
tempDirs.push(root)
for (const [rel, content] of Object.entries(files)) {
const full = path.join(root, rel)
fs.mkdirSync(path.dirname(full), { recursive: true })
fs.writeFileSync(full, content)
}
return root
}
describe('client-node-builtin guard', () => {
it('flags a client component whose lib import chain reaches crypto, with the chain', () => {
const root = fixture({
'lib/auth/hashing.ts': `import crypto from 'crypto'\nexport const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex')\nexport const isEnabled = () => true\n`,
'components/Login.tsx': `'use client'\nimport { isEnabled } from '@/lib/auth/hashing'\nexport default function Login() { return isEnabled() ? null : null }\n`,
})
const findings = findClientNodeBuiltins(root)
expect(findings).toHaveLength(1)
expect(findings[0]).toMatchObject({ file: 'components/Login.tsx', builtin: 'crypto' })
expect(findings[0].chain).toEqual(['components/Login.tsx', 'lib/auth/hashing.ts', 'bare:crypto'])
})
it('ignores server modules, type-only imports and dynamic imports', () => {
const root = fixture({
'lib/auth/hashing.ts': `import crypto from 'crypto'\nexport type Digest = string\nexport const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex')\n`,
'lib/server-only.ts': `import { hash } from './auth/hashing'\nexport const h = hash\n`,
'components/TypeOnly.tsx': `'use client'\nimport type { Digest } from '@/lib/auth/hashing'\nexport const d: Digest = ''\n`,
'components/Lazy.tsx': `'use client'\nexport async function load() { const m = await import('@/lib/auth/hashing'); return m.hash('x') }\n`,
})
expect(findClientNodeBuiltins(root)).toEqual([])
})
it('resolves the pure sibling pattern as clean', () => {
const root = fixture({
'lib/auth/flags.ts': `export const isEnabled = () => true\n`,
'lib/auth/hashing.ts': `import crypto from 'crypto'\nexport { isEnabled } from './flags'\nexport const hash = (s: string) => crypto.createHash('sha256').update(s).digest('hex')\n`,
'components/Login.tsx': `'use client'\nimport { isEnabled } from '@/lib/auth/flags'\nexport default function Login() { return isEnabled() ? null : null }\n`,
})
expect(findClientNodeBuiltins(root)).toEqual([])
})
})
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env node
/**
* Guard: a 'use client' module whose static import closure reaches a Node
* builtin (crypto, buffer, vm, stream, fs, ...).
*
* Turbopack polyfills those for the browser (crypto-browserify, vm-browserify,
* Buffer: ~327 KB uncompressed) the moment ANY client module can reach them,
* and the polyfill chunk then ships with every route that renders the
* component. Before the 2026-08-26 split, lib/auth/bankid.ts (login,
* register, security settings), lib/import/bank-file/parser.ts (bank import
* history), lib/salary/personnummer.ts (via tax-column, the employee forms)
* and lib/auth/api-keys.ts (the API key panel) each did this for a function
* that never touched crypto. The fix is always the same: move the pure part
* into a sibling module without the Node import and import that from the
* client (see bankid-flags.ts, bank-file/formats.ts, personnummer-format.ts,
* api-key-scopes.ts).
*
* No baseline: the count is 0, any new reacher is a hard failure. The walk
* is the same static closure scripts/perf/client-import-closure.mjs prints.
*/
import path from 'node:path'
import { fileURLToPath } from 'node:url'
import { buildGraph, clientReachers } from '../perf/client-import-closure.mjs'
export const NODE_BUILTINS = ['crypto', 'node:crypto', 'buffer', 'node:buffer', 'vm', 'node:vm', 'stream', 'node:stream', 'fs', 'node:fs', 'path', 'node:path', 'child_process', 'node:child_process']
/** [{ file, builtin, chain }] for every client file reaching a builtin. */
export function findClientNodeBuiltins(root) {
const graph = buildGraph(root)
const findings = []
for (const builtin of NODE_BUILTINS) {
for (const [file, chain] of clientReachers(graph, `bare:${builtin}`, root)) {
findings.push({ file, builtin, chain })
}
}
return findings.sort((a, b) => a.file.localeCompare(b.file) || a.builtin.localeCompare(b.builtin))
}
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
if (isMain) {
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const findings = findClientNodeBuiltins(root)
for (const f of findings) console.log(`${f.file} -> ${f.builtin}\n ${f.chain.join('\n > ')}`)
console.log(`${findings.length} client file(s) reach a Node builtin`)
process.exit(findings.length ? 1 : 0)
}
+23 -1
View File
@@ -122,6 +122,7 @@ import { fileURLToPath } from 'node:url'
import ts from 'typescript'
import { findSekLabelledFxAmounts } from './format-currency-sek-label.mjs'
import { findRawReferenceFetches } from './raw-reference-fetch.mjs'
import { findClientNodeBuiltins } from './client-node-builtin.mjs'
import {
findExtensionRouteFindings,
UNGATED_EXTENSION_ROUTES,
@@ -1018,6 +1019,7 @@ const current = {
dialogOverflowRisk: findDialogOverflowRisks(),
directAiClients: findDirectAiClients(),
rawReferenceFetch: findRawReferenceFetches(ROOT),
clientNodeBuiltins: findClientNodeBuiltins(ROOT),
}
const dialogOverflowFiles = [...new Set(current.dialogOverflowRisk.map((f) => f.file))].sort()
@@ -1089,6 +1091,26 @@ if (current.directJelInsert.length) {
)
}
// 1b3. client-node-builtin: a 'use client' module whose static import closure
// reaches a Node builtin ships the browser polyfill chunk (~327 KB) with every
// route that renders it. No baseline: 0 today, any reacher is a hard failure.
if (current.clientNodeBuiltins.length) {
failed = true
console.error(
`\n✗ client-node-builtin: ${current.clientNodeBuiltins.length} client module(s) reach a Node builtin ` +
`through their static imports (this ships crypto-browserify/Buffer/vm polyfills to the browser):`,
)
current.clientNodeBuiltins.forEach((f) =>
console.error(` ${f.file} -> ${f.builtin}\n ${f.chain.join('\n > ')}`),
)
console.error(
' → move the pure part the client needs into a sibling module without the Node import\n' +
' (see lib/auth/bankid-flags.ts, lib/import/bank-file/formats.ts, lib/salary/personnummer-format.ts,\n' +
' lib/auth/api-key-scopes.ts) and import that from the client. scripts/perf/client-import-closure.mjs\n' +
' prints the full chain for any module.',
)
}
// 1b2. leaky-supabase-client: server code must construct clients through
// createServiceRoleClient(). No baseline: the count is 0 today.
if (current.leakySupabaseClients.length) {
@@ -1381,5 +1403,5 @@ if (failed) {
process.exit(1)
}
console.log(
`\n✓ Antipattern guard passed (raw-route-auth: ${current.rawRouteAuth.length}, naive-ore-round: ${current.naiveOreRound}, hand-rolled-invariant: ${current.handRolledInvariants}, ledger-scanning-report: ${current.ledgerScanningReports.length}, direct-jel-insert: 0, leaky-supabase-client: 0, pinned-dep: 0, raw-user-error: 0, sek-labelled-amount: 0, off-ladder-radius: 0, folded-public-flag: 0, cross-extension-import: 0, ungated-extension-route: ${current.extensionRoutes.ungated.length}/${UNGATED_EXTENSION_ROUTES.size} allowlisted, dialog-overflow-risk: ${dialogOverflowFiles.length} file(s), raw-reference-fetch: ${current.rawReferenceFetch.length} file(s), direct-ai-client: ${current.directAiClients.length}/${DIRECT_AI_CLIENT_ALLOWED.size} allowlisted).`,
`\n✓ Antipattern guard passed (raw-route-auth: ${current.rawRouteAuth.length}, naive-ore-round: ${current.naiveOreRound}, hand-rolled-invariant: ${current.handRolledInvariants}, ledger-scanning-report: ${current.ledgerScanningReports.length}, direct-jel-insert: 0, leaky-supabase-client: 0, pinned-dep: 0, raw-user-error: 0, sek-labelled-amount: 0, off-ladder-radius: 0, folded-public-flag: 0, cross-extension-import: 0, ungated-extension-route: ${current.extensionRoutes.ungated.length}/${UNGATED_EXTENSION_ROUTES.size} allowlisted, dialog-overflow-risk: ${dialogOverflowFiles.length} file(s), raw-reference-fetch: ${current.rawReferenceFetch.length} file(s), client-node-builtin: ${current.clientNodeBuiltins.length}, direct-ai-client: ${current.directAiClients.length}/${DIRECT_AI_CLIENT_ALLOWED.size} allowlisted).`,
)
+56
View File
@@ -0,0 +1,56 @@
/**
* Regenerates lib/bookkeeping/bas-account-numbers.ts from the BAS chart.
*
* npx tsx scripts/generate-bas-account-numbers.ts # write
* npx tsx scripts/generate-bas-account-numbers.ts --check # exit 1 if stale
*
* The generated module is a sorted list of the ~1,276 standard account
* numbers (~9 KB) so client components can answer "is this a standard BAS
* account?" without the 315 KB data chunk. A unit test pins parity too.
*/
import fs from 'node:fs'
import path from 'node:path'
import { BAS_REFERENCE } from '../lib/bookkeeping/bas-data'
const OUT = path.resolve(__dirname, '..', 'lib', 'bookkeeping', 'bas-account-numbers.ts')
export function renderBasAccountNumbers(numbers: readonly string[]): string {
const sorted = [...new Set(numbers)].sort()
const rows: string[] = []
for (let i = 0; i < sorted.length; i += 12) {
rows.push(' ' + sorted.slice(i, i + 12).map((n) => `'${n}'`).join(', ') + ',')
}
return `// GENERATED by scripts/generate-bas-account-numbers.ts from lib/bookkeeping/bas-data.
// Do not edit by hand: run \`npx tsx scripts/generate-bas-account-numbers.ts\`.
//
// The sorted list of standard BAS account numbers (~9 KB) so client code can
// check membership without importing the full chart (315 KB uncompressed).
// lib/bookkeeping/__tests__/bas-account-numbers.test.ts pins parity.
export const BAS_ACCOUNT_NUMBERS: readonly string[] = [
${rows.join('\n')}
]
const BAS_ACCOUNT_NUMBER_SET: ReadonlySet<string> = new Set(BAS_ACCOUNT_NUMBERS)
/** Whether the number exists in the BAS chart (same answer as isStandardBASAccount). */
export function isStandardBASAccountNumber(accountNumber: string): boolean {
return BAS_ACCOUNT_NUMBER_SET.has(accountNumber)
}
`
}
if (require.main === module) {
const rendered = renderBasAccountNumbers(BAS_REFERENCE.map((a) => a.account_number))
if (process.argv.includes('--check')) {
const current = fs.existsSync(OUT) ? fs.readFileSync(OUT, 'utf8') : ''
if (current !== rendered) {
console.error('lib/bookkeeping/bas-account-numbers.ts is stale: run npx tsx scripts/generate-bas-account-numbers.ts')
process.exit(1)
}
console.log('bas-account-numbers.ts is up to date')
} else {
fs.writeFileSync(OUT, rendered)
console.log(`wrote ${OUT}`)
}
}
+139
View File
@@ -0,0 +1,139 @@
#!/usr/bin/env node
/**
* Static import closure of every 'use client' module.
*
* Answers "which client components pull module X into the browser bundle,
* and through which path?" without running `next build`. Walks static
* `import ... from` / `export ... from` edges (NOT dynamic `import()`, which
* splits a chunk, and NOT `import type`, which is erased), resolving `@/`
* and relative specifiers to .ts/.tsx/.js/.mjs files or directory indexes.
* Bare specifiers (packages, Node builtins) are recorded as leaves.
*
* node scripts/perf/client-import-closure.mjs lib/bookkeeping/bas-data/index.ts
* node scripts/perf/client-import-closure.mjs crypto node:crypto buffer vm
*
* Prints, per target, the client files whose closure reaches it and the
* shortest import path for each. Used by the responsiveness plan (B7) and
* by the client-node-builtin guard in scripts/checks.
*/
import fs from 'node:fs'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
const SCAN_DIRS = ['app', 'components', 'contexts', 'extensions', 'lib', 'i18n']
const IGNORE_DIRS = new Set(['node_modules', '.next', '.git', 'dist', 'build', 'coverage', '__tests__'])
const EXTS = ['.ts', '.tsx', '.js', '.mjs', '.jsx']
// Block comment bodies are `(?:[^*]|\*(?!\/))*` so an unclosed `/*` cannot be
// re-split at every later `/*` (CodeQL js/redos on the lazy form).
// Single-character whitespace alternative (not \s+): a `+` inside the outer
// `*` is a nested quantifier on the same character, which CodeQL js/redos
// flags as exponential on long runs of spaces.
const USE_CLIENT_RE = /^(?:\s|\/\/[^\n]*\n|\/\*(?:[^*]|\*(?!\/))*\*\/)*['"]use client['"]/
// Static edges only. `import type {...} from` and `export type {...} from`
// are skipped; `import x, { type Y } from` still counts (x is a value).
// One quantifier per span (a greedy `[^'"]*` up to the specifier's opening
// quote, which it cannot cross) so a run of whitespace has a single parse:
// the earlier `\s+ ... [^'"]*? ... \s` shape backtracked exponentially
// (CodeQL js/redos).
const EDGE_RE = /^[ \t]*(?:import|export) (?!type\b)[^'"]*from[ \t]*['"]([^'"]+)['"]/gm
const SIDE_EFFECT_IMPORT_RE = /^\s*import\s+['"]([^'"]+)['"]/gm
export function walkFiles(root = ROOT) {
const out = []
const visit = (dir) => {
if (!fs.existsSync(dir)) return
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (IGNORE_DIRS.has(entry.name)) continue
const full = path.join(dir, entry.name)
if (entry.isDirectory()) visit(full)
else if (/\.(?:ts|tsx|js|mjs|jsx)$/.test(entry.name) && !/\.(?:test|pg\.test)\.tsx?$/.test(entry.name)) out.push(full)
}
}
for (const d of SCAN_DIRS) visit(path.join(root, d))
return out
}
export function resolveSpecifier(spec, fromFile, root = ROOT) {
let base
if (spec.startsWith('@/')) base = path.join(root, spec.slice(2))
else if (spec.startsWith('.')) base = path.resolve(path.dirname(fromFile), spec)
else return { bare: spec }
const candidates = [base, ...EXTS.map((e) => base + e), ...EXTS.map((e) => path.join(base, 'index' + e))]
for (const c of candidates) {
if (fs.existsSync(c) && fs.statSync(c).isFile()) return { file: c }
}
return { missing: spec }
}
export function importsOf(source) {
const specs = new Set()
for (const m of source.matchAll(EDGE_RE)) specs.add(m[1])
for (const m of source.matchAll(SIDE_EFFECT_IMPORT_RE)) specs.add(m[1])
return [...specs]
}
/** Build the graph once: file -> { edges: [file|bare], client: boolean }. */
export function buildGraph(root = ROOT) {
const graph = new Map()
for (const file of walkFiles(root)) {
const source = fs.readFileSync(file, 'utf8')
const edges = []
for (const spec of importsOf(source)) {
const r = resolveSpecifier(spec, file, root)
if (r.file) edges.push(r.file)
else if (r.bare) edges.push(`bare:${r.bare}`)
}
graph.set(file, { edges, client: USE_CLIENT_RE.test(source) })
}
return graph
}
/**
* For each client file, BFS its closure; return { clientFile -> path[] } for
* closures that contain `target` (a repo-relative file path or `bare:<spec>`).
*/
export function clientReachers(graph, target, root = ROOT) {
const targetKey = target.startsWith('bare:') ? target : path.join(root, target)
const hits = new Map()
for (const [file, node] of graph) {
if (!node.client) continue
const prev = new Map([[file, null]])
const queue = [file]
let found = null
while (queue.length && !found) {
const cur = queue.shift()
const edges = graph.get(cur)?.edges ?? []
for (const next of edges) {
if (prev.has(next)) continue
prev.set(next, cur)
if (next === targetKey) { found = next; break }
if (!next.startsWith('bare:')) queue.push(next)
}
}
if (found) {
const chain = []
for (let n = found; n; n = prev.get(n)) chain.unshift(n)
hits.set(path.relative(root, file), chain.map((n) => (n.startsWith('bare:') ? n : path.relative(root, n))))
}
}
return hits
}
const isMain = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
if (isMain) {
const targets = process.argv.slice(2)
if (!targets.length) {
console.error('usage: node scripts/perf/client-import-closure.mjs <repo-relative file | bare specifier> ...')
process.exit(1)
}
const graph = buildGraph()
for (const t of targets) {
const key = t.includes('/') || t.endsWith('.ts') || t.endsWith('.tsx') ? t : `bare:${t}`
const hits = clientReachers(graph, key)
console.log(`\n== ${t}: ${hits.size} client file(s) reach it`)
for (const [file, chain] of [...hits].sort()) console.log(` ${file}\n ${chain.join('\n > ')}`)
}
}