This file provides guidance to Gemini CLI or other coding agents when working with code in this repository. It focuses on key conventions and best practices. For a comprehensive guide on the development setup and contribution process, see CONTRIBUTING.md.
# Build the project
npm run build
# Link the package - once this is run, you can manually test changes in your terminal
npm link
npm test # Full test suite with linting and compilation
npm run mocha:fast # Quick unit tests only
npx mocha {testfile} # Quick unit test for a specific file
# Linting and formatting
npm run lint # Check all code
npm run lint:changed-files # Lint changed files only (much faster)
npm run format # Auto-fix formatting issues- Survey prior art & harmonize utilities: When implementing logic that is or could be shared across callers (e.g., retries, backoff, string parsing, path containment, domain transformations):
- Reuse or extend existing utilities: Check imported modules, the immediate subsystem, and
src/utils.tsfirst; reuse or extend existing helpers rather than writing bespoke inline logic. - Extract and unify shared helpers: When logic is duplicated across modules or warrants a new common utility, place it in the appropriate shared module and unify existing custom implementations immediately rather than leaving parallel implementations.
- Reuse or extend existing utilities: Check imported modules, the immediate subsystem, and
- Use the central
logger(src/logger.ts); never useconsole.log()for user-facing output. - Throw
FirebaseError(src/error.ts) for expected, user-facing errors. If the error is due to a violation of a precondition (e.g. something that is null but should never be), specify a non-zero exit code ({ exit: 1 }). Error messages should clearly explain what failed and why; when actionable, provide concrete remediation guidance using documented CLI flags, commands, or configuration options (e.g., the expected format, a--forceflag, or a discovery command likefirebase <entity>:list—never undocumented or legacy internal fields). - Extract magic numbers and static constants: Define static IDs, default timeouts, millisecond offsets, and repeated strings as top-level constants (
UPPER_SNAKE_CASE) instead of inlining magic values inside functions. Mark static configuration arrays and lookup tables asreadonlyoras const. - Write high-signal comments that explain why, not what: Reserve comments and JSDoc for non-obvious rationale (protocol quirks, OS/platform edge cases, intentional trade-offs). Do not narrate self-evident code, attach multi-paragraph docblocks to small helpers, or repeat the same architectural explanation across multiple functions and tests—redundant commentary drifts out of sync and obscures control flow.
- API calls must use
apiv2.tsfor authenticated requests. - Reduce nesting as much as possible: Code should avoid unnecessarily deep nesting or long periods of nesting. Use early returns,
continue, andbreakstatements in functions and loops to handle edge cases early and keep main logic flat. Consider helper functions to encapsulate complex branching.
- Keep CLI commands thin: Code in
src/commands/should handle argument parsing, option declaration, and validation only; move business logic, multi-step orchestration, and API calls to dedicated modules insrc/(outside ofsrc/commands/). - Standardize command options and hooks:
- Use
.before()hooks for standard prerequisite gating (e.g.requireAuth,needProjectId,requirePermissions) rather than manual ad-hoc checks inside command actions. - Use
Command.withForce()for destructive or confirmable actions so-f, --forceis consistently supported across commands.
- Use
- Machine-composable output & stream discipline:
stdout: Reserved exclusively for machine-parseable data when--jsonis enabled, or primary command output in human mode. Actions should return data so the runner can serialize it under--json.stderr: Used for interactive spinners (ora), diagnostic logging (logger.debug), and warnings.- Stream isolation: Never interleave active
oraspinners with un-bufferedlogger.infoorlogLabeledBulletcalls; stop or complete spinners before printing sequential step logs.
- Never use
anyorunknownas an escape hatch. Define proper interfaces/types or use type guards. - Use union type literals over
enum: Never use TypeScriptenum. Use union literals (e.g.,type Platform = "web" | "ios" | "android"). - Prefer
for..ofover.forEach: Usefor..ofloops when iterating, especially for asynchronous operations or where early returns are needed. - Prefer options objects: Functions accepting more than three arguments should accept a single options object (
{ project, force }). - Standardize on
undefinedovernull: Avoidnullreturns in new functions and omit redundant= undefinedinitializers. Use plain object maps (Record<string, T>) or arrays instead ofMaporSetin public interface contracts. - Use strict null checks and handle
undefined/nullexplicitly. - Prefer falsy checks over explicit boolean comparisons: Use
!somethinginstead ofsomething === falseunless you explicitly need to distinguish betweenfalseand other falsy values likeundefinedornull.
- Avoid excessive mocking in unit tests. If a test requires many mocks, it might be better as an integration test in
/scripts/[feature]-tests/. - Clean up mocks in
afterEach: Always restore stubs and clean intercepts inafterEach(sinon.restore(),nock.cleanAll()), never in suite-levelafter(). Mock verifications and assertions (e.g.expect(nock.isDone()).to.be.true) belong in individual tests or suite-levelafterEach(), never in suite-levelafter()where global cleanup hooks have already cleared active mocks. - Test public interfaces: Exercise public entry points and exported module functions rather than testing or stubbing private internal helpers.
- Unit tests (
*.spec.ts) should be co-located with their source files. - Test error cases and recovery mechanisms: Exercise failure paths and edge conditions, asserting both the specific error type/message and the underlying mechanism (e.g., retry attempt counts or state cleanup) rather than a bare rejection.
- Lint and Test Before Committing: Run
npm run lint:changed-filesfor a quick check, and run the fullnpm testbefore submitting your PR to catch any issues. - Structure Commit Messages for Pull Requests: To streamline PR creation, format your commit messages to serve as both the commit and the PR description:
- Subject Line: A concise, imperative summary (e.g.,
feat: add frobnicator support). This will become the PR title. - Body: After a blank line, structure the commit body to match the PR template. This will pre-populate the PR description. Include:
### Description### Scenarios Tested### Sample Commands- Reference issues with "Fixes #123" in the description.
- Subject Line: A concise, imperative summary (e.g.,
- Update Changelog: For any user-facing change (new features, bug fixes, deprecations), add a corresponding entry to
CHANGELOG.md.