ReviewOS

stacks/stx

client-script-bundler: cache key omits transitive imports — helper edits don't invalidate

#1723
Closed glennmichael123 opened this 23 days ago · 0 comments
23 days ago

Summary

packages/stx/src/client-script-bundler.ts:203 computes the cache key from code + filePath:

const hash = new Bun.CryptoHasher('md5').update(code + filePath).digest('hex')

If a <script client> block imports from ./helpers/format.ts and the helper file changes (but the script block itself doesn't), the cache key stays the same → cached bundle is served → the change never appears in the browser.

Reproducer

  1. Create a component:

    <!-- components/Foo.stx -->
    <script client>
      import { formatPrice } from '@/functions/format'
      const result = state('')
      onMount(async () => result.set(formatPrice(10)))
    </script>
    <p x-text="result()"></p>
  2. functions/format.ts:

    export function formatPrice(n: number) { return `$${n}.00` }
  3. Build, observe page renders $10.00. Cache is populated.

  4. Edit functions/format.ts: change to return `${n} dollars` .

  5. Rebuild without clearing .stx/cache. Page still renders $10.00 because cache hit on the unchanged <script client> text.

Root cause

packages/stx/src/client-script-bundler.ts:202-203:

const hashInput = code + filePath
const hash = new Bun.CryptoHasher('md5').update(hashInput).digest('hex')

Only the script source + the host file path go into the hash. The actual bundled output (which depends on all transitively-imported files) is not part of the cache key.

CLAUDE.md item 10 documents this is opt-in based on hasUserImports() — once it opts in, the cache logic doesn't track what was imported.

Impact

Confusing: editing a helper file appears to do nothing. Workaround is to also touch the consuming .stx file or rm -rf .stx/cache. Especially painful with shared functions (@/functions/...) imported by many components.

Suggested fix

After Bun.build completes, walk the resolved input file list and include their mtimes in the cache key:

const result = await Bun.build({ /* ... */ })
const inputFiles = result.outputs.flatMap(o => o.imports.map(i => i.path))
const mtimes = await Promise.all(inputFiles.map(async f => {
  try { return (await Bun.file(f).stat()).mtimeMs }
  catch { return 0 }
}))
const hashInput = code + filePath + inputFiles.join('|') + mtimes.join('|')
const hash = new Bun.CryptoHasher('md5').update(hashInput).digest('hex')

Then cache the bundled output indexed by that fuller hash. Alternative: hash the bundled OUTPUT (not the input) and use that for invalidation; same effect, simpler to compute.

Workaround

rm -rf .stx/cache between builds when editing transitively-imported files. Or touch (touch components/Foo.stx) the consuming script's host file so its mtime changes.

Environment

  • stx main
  • Bun 1.3.13

Sign in to comment on this issue.