Skip to content

fix: guard against the script bootstrapping twice on a page#63

Merged
timzatko merged 1 commit into
mainfrom
fix/double-injection-guard
Jun 29, 2026
Merged

fix: guard against the script bootstrapping twice on a page#63
timzatko merged 1 commit into
mainfrom
fix/double-injection-guard

Conversation

@timzatko

Copy link
Copy Markdown
Member

Why

Reported in production: Initializer.registerApi | given parameter ('tw-calc') is already registered!

The game's TheWestApi.register('tw-calc', …) throws when that key is already registered. Since the key is a constant, the only way to hit it is the script bootstrapping twice in the same window: index.ts starts a setInterval that bootstraps once the game is ready, with no guard against the bundle being injected more than once (re-injection or a same-origin iframe). The register collision is the visible symptom of everything initializing twice.

Note: this was originally part of #62 but didn't make it into that squash merge, so it's split out here.

What

  • Extract the injection logic into src/inject.ts and skip bootstrapping when window.TW_Calc is already set, making injection idempotent. This fixes the root cause (all double-init), not just the API-register symptom.
  • Slim src/index.ts down to wiring + the inject(...) call.

Tests

New inject.spec.ts (5 tests, driven with jasmine's clock): the game-ready guard, bootstraps exactly once when ready, and does not bootstrap again when already injected. Full suite green (npm test → 18/18); tsc and eslint clean.

🤖 Generated with Claude Code

When the userscript was injected more than once into the same page (re-injection
or a same-origin iframe), bootstrap ran twice and TheWestApi.register threw
"given parameter ('tw-calc') is already registered!" on the second run — the
visible symptom of everything initializing twice.

Extract the injection logic into src/inject.ts and skip bootstrapping when
window.TW_Calc is already set, making injection idempotent. Add tests for the
ready/already-injected guards.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@timzatko timzatko merged commit 79587ff into main Jun 29, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant