# Source Code Structure - Firebase Implementation

Firebase-specific implementation of the principles defined in [SOURCE_STRUCTURE.md](../core/SOURCE_STRUCTURE.md).

## Vertical Flow

- **Cloud Function File Order:** Within a Cloud Function file, follow a consistent order: (1) imports, (2) type definitions, (3) dependency initialization, (4) helper functions, (5) the exported function handler. The handler should be the last thing in the file -- a reader scans the setup, understands the context, and then reads the main logic.
- **Security Rules Flow:** Organize Firestore Security Rules top-down: (1) global helper functions at the top, (2) collection-level matches ordered by importance (auth-related first, then core entities, then supporting collections), (3) subcollection rules nested under their parents. A reviewer should be able to scan from top to bottom and understand the access model.
- **Proximity in Triggers:** Keep related trigger logic close together. If `onOrderCreated` and `onOrderUpdated` share helper functions, keep them in the same file or adjacent files. Do not scatter related triggers across distant directories.

## Formatting

- **Consistent TypeScript Style:** Enforce a consistent code style across all Cloud Function code using ESLint with a shared config and Prettier for formatting. Run linting in CI. Use the Firebase-recommended TypeScript settings as a baseline.
- **Security Rules Formatting:** Indent Security Rules consistently (2 spaces). Align `allow` statements within a `match` block. Keep helper function definitions visually separated from match blocks. While there is no official formatter, maintain consistency manually and enforce via PR review.
- **Import Organization:** In Cloud Function files, group imports: (1) Node.js built-ins (`path`, `crypto`), (2) Firebase Admin SDK and Functions SDK, (3) third-party packages, (4) project-relative imports. Separate groups with a blank line.
- **Line Length:** Configure Prettier for 100-character line length in Cloud Function code. Security Rules have no formatter, but keep lines under 120 characters for readability in PR diffs.

## Project Structure

- **Monorepo for Firebase Projects:**
  ```
  project-root/
    firebase.json             (Firebase project configuration)
    firestore.rules           (Firestore Security Rules)
    firestore.indexes.json    (Firestore composite indexes)
    storage.rules             (Storage Security Rules)
    remoteconfig.template.json (Remote Config template)
    functions/
      src/
        index.ts              (Function exports entry point)
        triggers/
          auth/               (Auth event triggers)
          firestore/          (Firestore document triggers)
          storage/            (Storage object triggers)
          pubsub/             (Pub/Sub topic triggers)
          scheduled/          (Scheduled functions)
        callables/            (Callable function handlers)
        http/                 (HTTP function handlers)
        services/             (Business logic layer)
        repositories/         (Firestore data access layer)
        models/               (TypeScript interfaces and converters)
        middleware/           (Shared middleware: auth, validation, logging)
        shared/               (Constants, utilities, error classes)
      test/                   (Mirrors src/ structure)
      package.json
      tsconfig.json
    hosting/                  (Web app source if using Firebase Hosting)
    tests/
      rules/                  (Security Rules tests)
    scripts/                  (Migration scripts, seed data, utilities)
  ```
- **Index File as Table of Contents:** The `functions/src/index.ts` file should export all Cloud Functions. Keep it clean -- import and re-export from organized modules. It should read as a table of contents for your backend:
  ```typescript
  // Auth triggers
  export { onUserCreated } from './triggers/auth/onUserCreated';
  export { onUserDeleted } from './triggers/auth/onUserDeleted';

  // Firestore triggers
  export { onOrderCreated } from './triggers/firestore/onOrderCreated';

  // Callables
  export { submitOrder } from './callables/submitOrder';
  ```
- **One Function Per File:** Each Cloud Function gets its own file, named to match the exported function. `onOrderCreated.ts` exports `onOrderCreated`. Small helper functions may live in the same file, but shared logic belongs in `services/` or `shared/`.
- **Test Mirroring:** Mirror the `src/` structure in `test/`. If the source is `src/triggers/firestore/onOrderCreated.ts`, the test is `test/triggers/firestore/onOrderCreated.test.ts`. Security Rules tests live in `tests/rules/` mirroring collection structure.
- **Environment Configuration Files:** Keep environment-specific configuration in clearly named files: `.env.local`, `.env.staging`, `.env.production`. Never commit production secrets. Use `.env.example` as a template documenting all required variables.
- **Security Rules Modularity:** For large projects, Firestore Security Rules in a single file become unwieldy. Use a build step (with a tool like `firestore-rules-bundler` or a custom script) to compose rules from modular files per collection, then output a single `firestore.rules` for deployment.
