# Coding Conventions

**Analysis Date:** 2026-05-21

## Naming Patterns

**Files:**
- React components live in named folders with an `index.js` (PascalCase folder name). Example: `src/components/Header/index.js`, `src/components/Card/index.js`, `src/screens/Home/index.js`.
- Component-local stylesheets co-locate with the component as `ComponentName.module.sass` (PascalCase). Example: `src/components/Header/Header.module.sass`.
- Standalone single-file components and pages use PascalCase `.js` (no folder). Examples: `src/components/Icon.js`, `src/components/Image.js`, `src/components/ScrollParallax.js`, `src/scans/ScanStartPage.js`, `src/bigOrders/BigOrders.js`.
- Utility modules use lowercase, single-word filenames in `src/utils/`. Examples: `src/utils/formatters.js`, `src/utils/errorget.js`, `src/utils/countryformat.js`, `src/utils/languagecodeformat.js`.
- Mock data and trainers use lowercase. Example: `src/mocks/trainers.js`.
- Top-level app entry files use PascalCase: `src/App.js`, `src/BeyondApp.js`. Lowercase entry/config files: `src/index.js`, `src/api.js`, `src/config.js`.
- Test files use `.test.js` suffix and live next to the file they test (Create React App default). Example: `src/App.test.js`.

**Functions:**
- camelCase for regular functions and arrow functions. Examples: `getAccount`, `fetchRdcUrl`, `onLogout`, `loadBigOrders`, `safariCheck`, `iosCheck`.
- Event handlers prefix with `on`: `onLogout`, `onChangeIpd`, `onRescan`, `onCancel`.
- Async setup functions inside `useEffect` are typically named `load*` or `fetch*`: `loadScans`, `loadBigOrders`, `fetchRdcUrl`.

**Variables:**
- camelCase for locals, props and `useState` pairs: `const [account, setAccount] = useState()`, `const [visibleNav, setVisibleNav] = useState(false)`, `const [loginBtnText, setLoginBtnText] = useState('Login')`.
- React state setters always prefixed with `set`: `setScans`, `setBigOrders`, `setLoading`, `setRdcUrl`.
- Refs use camelCase ending in `Ref` or descriptive nouns: `rootEl`, `retryTag`.
- Constants at module scope use camelCase (not SCREAMING_SNAKE_CASE) in most files. Examples: `navLinks`, `socials`, `formatters`, `downloads` in `src/components/Header/index.js` and `src/screens/Home/Hero/index.js`.
- A few class-level constants in `src/api.js` use SCREAMING_SNAKE_CASE: `REFRESH_TOKEN_KEY`, `ACCESS_TOKEN_KEY`, `USE_COOKIES_FOR_TOKENS`.

**Components / Classes:**
- React components are PascalCase function components: `Header`, `Page`, `Hero`, `BigOrders`, `ScanStartPage`, `Redirect`.
- Classes use PascalCase: `BigApi`, `BigApiError`.
- Enum-like objects use PascalCase keys: `AuthenticationErrorCode.RefreshTokenNeedsRenewal`, `BigApiAuthenticationGuard.AuthenticationRequired` (`src/api.js`).

**Environment variables:**
- All env reads are prefixed `REACT_APP_` (CRA convention): `REACT_APP_API_SERVER_URL`, `REACT_APP_CLOUD_API_URL`, `REACT_APP_API_KEY`, `REACT_APP_RDC_SERVER_HOST` (`src/config.js`, `src/api.js`).

## Code Style

**Formatting:**
- No Prettier config and no `.editorconfig` detected. Formatting is by convention, not enforced.
- Indentation is mixed: 2 spaces is dominant in component files (`src/components/Header/index.js`, `src/App.js`), but 4 spaces appears in `src/api.js`, `src/bigOrders/BigOrders.js`, `src/scans/ScanStartPage.js`, and the `src/utils/*.js` helpers. Match the surrounding file's indentation when editing.
- Quotes are mixed within and across files; double quotes are most common for JSX attributes and JS string literals, but single quotes appear frequently for short literals (`'login'`, `'/'`, `'classnames'`). No enforcement; do not reformat existing strings.
- Trailing semicolons are generally used. JSX attributes use double quotes.

**Linting:**
- ESLint is configured via `package.json` `eslintConfig` only, extending `react-app` and `react-app/jest` (the Create React App defaults). No custom rules.
- No `.eslintrc.*`, `.prettierrc.*`, `biome.json`, or standalone `eslint.config.*` file.

**Babel:**
- `.babelrc` adds only `@babel/plugin-proposal-optional-chaining`. Everything else is CRA defaults via `react-scripts@5.0.1`.

**Module syntax mix (important):**
- The application source is primarily ES modules: `import` / `export default` / `export class` (used throughout `src/components`, `src/screens`, `src/App.js`, `src/api.js`).
- Utility modules in `src/utils/` use CommonJS-style `exports.foo = ...` (e.g., `src/utils/formatters.js`, `src/utils/errorget.js`, `src/utils/countryformat.js`). New utilities should follow this same `exports.fnName = ...` pattern to stay consistent with the existing files, OR migrate the whole `utils/` tree at once.

## Import Organization

**Order observed across files (e.g., `src/components/Header/index.js`, `src/screens/Home/Hero/index.js`):**
1. `react` and React-ecosystem packages (`react-router-dom`, `react-dom`).
2. Other third-party packages (`classnames as cn`, `lodash as _`, `superagent`, `body-scroll-lock`, `@builder.io/react`, `react-outside-click-handler`).
3. Local stylesheet: `import styles from "./Component.module.sass"`.
4. Sibling/child component imports (relative paths).
5. Cross-tree component imports (`../../components/...`).
6. API / utility imports (`../../api`, `../../utils/...`).

**Path style:**
- All internal imports use **relative paths** (`./`, `../`, `../../`). No path aliases (`@/`, `~/`) are configured; CRA's `jsconfig.json` / `tsconfig.json` is not present.
- The `.js` extension is sometimes included (`../api.js`, `./api.js`, `./SocialBrowser.js`, `./screens/Api/ApiPages.js`) and sometimes omitted (`"../Overlay"`, `"./Header"`). Either works; prefer omitting for component folders that have an `index.js`.

**Common aliases:**
- `import cn from "classnames"` — used everywhere for conditional className composition.
- `import * as _ from "lodash"` — used in `src/api.js`, `src/components/BuilderIoPage/index.js`, `src/bigOrders/BigOrders.js`.
- `import * as superagent from "superagent"` in `src/api.js`.

## Error Handling

**API layer (`src/api.js`):**
- All HTTP methods are wrapped in `try` / `catch`. Errors are converted with `BigApiError.getApiError(err, defaultMessage)` and re-thrown so callers see a `BigApiError` with `code`, `status`, `errors`, and `message` populated from `err.response.body`.
- `BigApiError` extends `Error` and carries structured fields (`code`, `status`, `errors`). Use it for all API failures.
- Some auth helpers swallow errors and return `null`/`false` (`fetchLocalAccountProfile`, `isAuthenticated`, `logout`) — by design, so the UI can degrade to logged-out state.

**Component layer (typical pattern, e.g., `src/App.js`, `src/components/Header/index.js`, `src/bigOrders/BigOrders.js`):**
```js
useEffect(() => {
  const loadX = async () => {
    try {
      const res = await BigApi.get('/some/endpoint');
      setX(res.body);
    } catch (e) {
      console.error(e); // or console.log(e)
      setX(undefined);  // or setX([]) for list state
    }
  };
  loadX();
}, []);
```
- On failure, set the local state to an empty/undefined value and log to console. There is no global toast / error-boundary system.
- `src/utils/errorget.js` exports `superagentError(error, response, defaultMsg)` for extracting human-readable messages from superagent failure bodies. Use it when surfacing errors to users.

**Do NOT:**
- Re-throw raw superagent errors at the UI layer. Always funnel through `BigApi.*` (which wraps with `BigApiError`) or `superagentError(...)`.
- Throw error strings inside callers (`throw "..."`). Throw `BigApiError` or `Error` instances.

## Logging

**Framework:** Browser `console` only. There is no logging library (no Winston/pino/Sentry SDK in deps).

**Patterns:**
- `console.log(...)` is used liberally for debugging during async flows and to dump response bodies — e.g. `console.log("Setting account to: ", res.body)` (`src/App.js:99`), `console.log(res.body)` (`src/bigOrders/BigOrders.js:23,38`).
- `console.error(e)` for caught exceptions in component effects (e.g., `src/App.js:102`, `src/components/Header/index.js:119`).
- `console.warn(...)` for missing-token soft failures in `src/api.js` (`fetchLocalAccountProfile`, `isAuthenticated`).
- `// console.log('...'); //debug` style commented-out debug lines are common — keep them when editing nearby code, do not delete on sight.

## Comments

**When to comment:**
- Section dividers in routing/rendering blocks use `//--- LABEL ---//` style (`src/App.js`).
- Multi-line block comments explain WHY for non-obvious workarounds, often with `HACK HACK HACK` headers — see `src/api.js:245-256` (Safari token caching) and `// HACK` notes in `BigApi.loginWithToken2`.
- `TODO` and `FIXME` markers appear as single-line `//` comments. Examples: `src/App.js:274 (// TODO)`, `src/api.js:125 (TODO: handle different browser storage mechanisms)`, `src/api.js:251 (TODO: the token2 login MUST BE READONLY.)`.
- Large blocks of commented-out imports/routes are intentionally preserved (see top of `src/App.js`) — they document deferred features. Do not remove them as cleanup.

**JSDoc / TSDoc:**
- Used sparingly. `src/api.js` has occasional JSDoc-lite blocks (file header at line 4-8, `loginWithToken2` at line 219-223). No project-wide JSDoc policy.
- `src/api.js:4-8` warns: "don't edit the .js version of this file directly. Edit the .ts version and then run `tsc` to generate the .js version" — **the `.ts` source for `api.js` is not in the repo**. Treat the file as hand-maintained until a `.ts` source appears.

## Function Design

**Components:**
- All components are function components using hooks (`useState`, `useEffect`, `useRef`, `useNavigate`, `useParams`, `useSearchParams`, `useLocation`). No class components.
- Props are destructured in the signature: `const Header = ({ account }) => { ... }`, `const Page = ({ showInfoState, account, children }) => { ... }`.
- State that needs to be passed down as a tuple uses the "state pair" pattern: `const showInfoState = useState();` then `<Component showInfoState={showInfoState} />` and inside the child `const [showInfo, setShowInfo] = showInfoState;` (`src/App.js:89-90`, `src/screens/Home/Hero/index.js:14-15`).
- Async effect work is wrapped in a named inner function and immediately invoked:
  ```js
  useEffect(() => {
    const getAccount = async function() { ... };
    getAccount();
  }, []);
  ```

**PropTypes:**
- `prop-types` is in `package.json` dependencies but **no component declares `PropTypes`**. Prop validation is not enforced. Do not add PropTypes to existing components unless you're prepared to add them everywhere.

**Size:** Components routinely exceed 200 lines (e.g., `src/App.js` ~325 lines, `src/components/Header/index.js` ~213 lines, `src/bigOrders/BigOrders.js` ~214 lines). No enforced size limit. Prefer extracting sub-components into sibling folders when adding new functionality.

**Parameters:** Use object destructuring for React props and for option-style function arguments. The `BigApi` static methods take positional args, with auth guard as last param (e.g., `BigApi.get(url, authenticationGuard = BigApiAuthenticationGuard.AuthenticationRequired)`).

**Return values:** Components return JSX or `null`. Service helpers return either the `res.body` payload (`fetchLocalAccountProfile`), the raw superagent response (`BigApi.get/post/put/delete`), or a primitive (`true`/`false`/`null`). Match the surrounding pattern.

## Module Design

**Exports:**
- Components use `export default Component` at the bottom of the file.
- API code uses named exports for classes/enums (`export class BigApi`, `export class BigApiError`, `export var BigApiAuthenticationGuard`) and a default export for config (`export default CloudConfig` in `src/config.js`).
- Utility modules use CommonJS `exports.fnName = ...` (see `src/utils/formatters.js`, `src/utils/errorget.js`, `src/utils/countryformat.js`).
- `src/screens/Api/ApiPages.js` is imported as a namespace: `import * as ApiPages from './screens/Api/ApiPages.js'`, then `<ApiPages.EmailVerifier />`. Use this pattern when you want to group several small page components under one file.

**Barrel files:**
- Each component folder has an `index.js` that exports the component as default. Imports rely on the folder name (`import Header from "../Header"`). Do not put multiple unrelated components in one `index.js`.

**Style files:**
- `*.module.sass` for component-scoped CSS Modules, imported as `import styles from "./Component.module.sass"` and applied via `className={styles.foo}` or `cn(styles.foo, "global-class")`.
- Global styles are imported once from `src/components/Page/index.js` via `import "../../styles/app.sass"`. Builder.io and Standalone layouts intentionally skip this import.
- Shared/global SASS lives in `src/styles/` (`app.sass`, `common.sass`, `helpers.sass`, `reset.sass`, and `src/styles/blocks/`).
- All `.module.sass` files start with `@import ../../styles/helpers` (or deeper `../../../styles/helpers` from `src/screens/*/Subcomponent/`).

## React Conventions

- React Router v6 is used throughout (`Routes` / `Route` / `useNavigate` / `useSearchParams` / `useParams` / `useLocation`). `Route` uses `element={...}` not `component={...}`. Some legacy `exact` props remain (no-op in v6) — keep them on existing routes to match style; new routes can omit `exact`.
- `classnames` is always imported as `cn`. Conditional classes: `cn(styles.foo, { [styles.active]: isActive })`.
- Inline event handlers in JSX are common (`onClick={() => setX(!x)}`). Extract to named functions when they do more than one thing.
- Strict Mode is enabled at the root (`src/index.js`).

---

*Convention analysis: 2026-05-21*
