<!-- refreshed: 2026-05-21 -->
# Architecture

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

## System Overview

```text
┌─────────────────────────────────────────────────────────────┐
│                  Browser (Create-React-App SPA)             │
│   `public/index.html` (root div, third-party pixels)        │
└──────────────────────────────┬──────────────────────────────┘
                               │ ReactDOM.render
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                Bootstrap + Router                           │
│   `src/index.js` — initializes Builder.io, wraps <App/>     │
│   in <BrowserRouter>                                        │
└──────────────────────────────┬──────────────────────────────┘
                               ▼
┌─────────────────────────────────────────────────────────────┐
│                Path-Dispatcher Root (`src/App.js`)          │
│  Regex-based filter selects ONE of six layout branches:     │
│  Builder.io | Scan | Browser | BigOrder | EtClient | React  │
└────┬──────────┬──────────┬─────────┬─────────┬──────────────┘
     ▼          ▼          ▼         ▼         ▼          ▼
┌─────────┐┌─────────┐┌──────────┐┌──────────┐┌──────────┐┌─────────┐
│ Builder ││ Scan    ││ Social   ││ BigOrder ││ EtClient ││ React   │
│ Layout  ││ Layout  ││ Browser  ││ Layout   ││ (Stand-  ││ Page    │
│         ││ (Stand- ││ (no      ││          ││  alone)  ││ Layout  │
│ Beyond  ││  alone) ││  chrome) ││          ││          ││ Header/ │
│ Backend ││         ││          ││          ││          ││ Footer  │
└────┬────┘└────┬────┘└────┬─────┘└────┬─────┘└────┬─────┘└────┬────┘
     ▼          ▼          ▼           ▼           ▼           ▼
┌─────────────────────────────────────────────────────────────┐
│                Screen / Page Components                     │
│   `src/screens/*`, `src/scans/*`, `src/bigOrders/*`         │
└──────────────────────────────┬──────────────────────────────┘
                               ▼
┌─────────────────────────────────────────────────────────────┐
│              BigApi Static Client (`src/api.js`)            │
│   superagent + cookie/localStorage tokens + Bearer API key  │
└────────┬────────────────────────┬───────────────────────────┘
         ▼                        ▼
┌──────────────────────┐ ┌────────────────────────────────────┐
│  Bigscreen REST API  │ │  Builder.io Visual CMS             │
│  (`apiServerUrl`,    │ │  `@builder.io/react` BuilderComponent│
│   `cloudApiServerUrl`│ │  models: `non-shopify`, `page`     │
│   `rdcServerHost`)   │ │                                    │
└──────────────────────┘ └────────────────────────────────────┘
```

## Component Responsibilities

| Component | Responsibility | File |
|-----------|----------------|------|
| Entry bootstrap | Initialize Builder.io key, mount `<App/>` inside `<BrowserRouter>` | `src/index.js` |
| Path dispatcher | Evaluate regex filters and pick one of six layout branches | `src/App.js` |
| API client | All HTTP I/O, token cookies, access-token renewal, error wrapping | `src/api.js` |
| Config | Bind `REACT_APP_*` env vars to a single config object | `src/config.js` |
| React layout | Renders Header + children + Footer for "marketing/react" branch | `src/components/Page/index.js` |
| Builder layout | Locale fetch + scroll reset for Builder.io branch | `src/components/BeyondBackend/index.js` |
| Builder renderer | Maps URL path to a Builder.io model + injects API helpers | `src/components/BuilderIoPage/index.js` |
| Standalone layout | Minimal header (logo only) for scan/et-client flows | `src/components/Standalone/index.js` |
| BigOrder layout | Minimal header for `/account/order/*` and token2 login | `src/bigOrders/BigOrderLayout.js` |
| Marketing screens | Section composition for `/software` home page | `src/screens/Home/*` |
| Auth screens | Login / signup / forgot / reset / verify modes | `src/screens/Access/*` |
| API-token screens | Token-based redirect handlers (email verify, reset, login) | `src/screens/Api/ApiPages.js` |
| Long copy constants | Embedded ToS / Privacy / Ticket HTML strings | `src/long_constants/*.js` |
| Beyond Cloud Browser | Separate hyperbeam-based bundle, built independently | `cloud-browser-static/src/*` |
| Shopify ops notebooks | Out-of-band Jupyter scripts for checkout + Klaviyo | `ipynb_shopify/*` |

## Pattern Overview

**Overall:** Create-React-App single-page application with a path-regex dispatcher in the root component that switches between six mutually exclusive layout branches. Content for marketing URLs is delegated to Builder.io; transactional/auth URLs are rendered by hand-coded React screens.

**Key Characteristics:**
- Single shared HTTP client (`BigApi` static class) used by every screen
- No global state library (no Redux/Zustand/Context) — `account` is fetched once in `App.js` and prop-drilled
- Layout selection is URL-pattern based, not nested-route based; only one `<Routes>` block renders at a time
- Builder.io CMS owns most marketing pages; React owns auth, purchase, scans, big orders, account, and remote-desktop
- Styling is SASS modules per component (`*.module.sass`) plus global SASS partials under `src/styles/`

## Layers

**Bootstrap layer:**
- Purpose: Mount React into DOM, configure third-party SDKs
- Location: `src/index.js`, `public/index.html`
- Contains: ReactDOM render call, Builder.io `init`, marketing pixels (Reddit, Twitter, Meta, AdSense), dark-mode pre-paint script
- Depends on: `App`, `react-router-dom`, `@builder.io/react`
- Used by: Browser

**Dispatcher / routing layer:**
- Purpose: Decide which layout + `<Routes>` block to render for the current pathname
- Location: `src/App.js` (production), `src/BeyondApp.js` (alternate/unused entry)
- Contains: `getComposedRegex`, six filter regexes, conditional returns
- Depends on: All layout components, all top-level screens, `BigApi`
- Used by: Bootstrap layer

**Layout layer:**
- Purpose: Provide chrome (header/footer/styles) appropriate to each branch
- Location: `src/components/Page/`, `src/components/BeyondBackend/`, `src/components/Standalone/`, `src/bigOrders/BigOrderLayout.js`
- Contains: Layout wrappers that inject CSS, set `body.style`, call `clearAllBodyScrollLocks`
- Depends on: `body-scroll-lock`, Header/Footer components, `BigApi` (for locale)
- Used by: Dispatcher

**Screen layer:**
- Purpose: Top-level routable pages
- Location: `src/screens/*`, `src/scans/*`, `src/bigOrders/*`
- Contains: Page-level components that orchestrate sub-components and API calls
- Depends on: Component layer, `BigApi`, `src/utils/*`
- Used by: Layout

**Component layer:**
- Purpose: Reusable UI building blocks
- Location: `src/components/*`
- Contains: Header, Footer, Modal, Overlay, Card, VideoOverlay, Icon, SimpleLoader, etc.
- Depends on: SASS modules, `classnames`, third-party UI libs (react-slick, react-player, react-parallax-tilt)
- Used by: Screens and other components

**API / data layer:**
- Purpose: Encapsulate all HTTP, token management, and error normalization
- Location: `src/api.js`, `src/config.js`
- Contains: `BigApi` static class, `BigApiError`, `BigApiAuthenticationGuard` enum
- Depends on: `superagent`, `lodash`, `process.env.REACT_APP_*`
- Used by: Every screen and most layout components

**Style layer:**
- Purpose: Global SASS and per-component SASS modules
- Location: `src/styles/`, `src/components/**/*.module.sass`, `public/css/`
- Contains: Reset, helpers, common, blocks (button/title/section/etc.), plus `public/css/beyond-*.css` for Builder.io / standalone branches
- Used by: All visual components

## Data Flow

### Primary Request Path (marketing page render)

1. Browser navigates to `/` (`public/index.html` loads, third-party pixels fire) (`public/index.html:6-44`)
2. `ReactDOM.render` mounts `<App/>` under `<Router>` (`src/index.js:13-20`)
3. `App` calls `BigApi.get('/auth/account')` and `BigApi.getRdcUrl()` once on mount (`src/App.js:96-112`)
4. `App` evaluates `builderIoFilter` against `useLocation().pathname`; for `/` this returns true (`src/App.js:115-160`)
5. `App` returns `<BeyondBackend><BuilderIoPage/></BeyondBackend>` (`src/App.js:174-184`)
6. `BeyondBackend` calls `/info/region` to set locale (`src/components/BeyondBackend/index.js:14-37`)
7. `BuilderIoPage` rewrites pathname to `/nspages/home` and renders `<BuilderComponent model="non-shopify" />` (`src/components/BuilderIoPage/index.js:33-44, 117-122`)
8. Builder.io fetches the page model and renders into the React tree

### Authentication Path (token login v2)

1. User visits `/token2/login/:token` — matches `orderFilter` (`src/App.js:149-154`)
2. `App` renders `<BigOrderLayout><Routes><Route ".../token" element={<ApiPages.TokenLogin2/>}/></Routes></BigOrderLayout>` (`src/App.js:218-237`)
3. `TokenLogin2` calls `BigApi.loginWithToken2(token)` (`src/screens/Api/ApiPages.js:99-129`)
4. `BigApi.loginWithToken2` POSTs to `${apiServerUrl}/auth/token2/login/...`, stores `x-refresh-token` + `x-access-token` cookies, optionally caches `retry_token` cookie (`src/api.js:224-256`)
5. On success, navigate to `res.body.redirectUrl` or `/`

### Authenticated API Call Path

1. Caller invokes e.g. `BigApi.get('/auth/account')` (`src/api.js:406-426`)
2. `checkAccessTokenStatus` runs first; if access token missing/expired it triggers `renewAccessToken` with the nonce returned from the server (`src/api.js:323-405`)
3. Renewal sets fresh cookies, then the original request is sent with `Authorization: Bearer ${apiKey}` and `x-access-token` headers
4. Errors are funneled through `BigApiError.getApiError(err)` which extracts `code`, `status`, `errors`, `message` from the response body (`src/api.js:33-69`)

**State Management:**
- No global store. Per-component `useState` and prop-drilling.
- `account` is fetched in `App.js` and passed down to every branch.
- `localeState` is also a `useState` tuple created in `App.js` and passed into `BeyondBackend` and `BuilderIoPage`.
- Tokens persist in cookies (default) via `BigApi.setCookie` / `getCookie`; `BigApi.USE_COOKIES_FOR_TOKENS = true` toggles between cookie and localStorage backends (`src/api.js:100-164`).
- Dark mode is bootstrapped from `localStorage.darkMode` by an inline script in `public/index.html` (`public/index.html:90-131`); `use-dark-mode` hook is available but not heavily used.

## Key Abstractions

**`BigApi` (static class):**
- Purpose: Single facade for all backend HTTP, token lifecycle, and error normalization
- Examples: `src/api.js:71-540`
- Pattern: Static methods on a class; configuration loaded from `process.env` at class definition time; auth guarded by `BigApiAuthenticationGuard` enum (`SkipAuthentication` / `AuthenticationOptional` / `AuthenticationRequired`)

**`BigApiError` (Error subclass):**
- Purpose: Carry HTTP `status`, error `code`, and `errors[]` array alongside the message
- Examples: `src/api.js:29-70`
- Pattern: Static `getApiError(err, defaultMessage)` factory converts superagent errors into `BigApiError` instances

**Layout wrapper components:**
- Purpose: Provide branch-specific chrome and side effects (`window.scrollTo`, `clearAllBodyScrollLocks`)
- Examples: `src/components/Page/index.js`, `src/components/Standalone/index.js`, `src/bigOrders/BigOrderLayout.js`, `src/components/BeyondBackend/index.js`
- Pattern: Receive `children` plus shared props (`account`, `localeState`); wrap with header/CSS links

**Filter regex composition:**
- Purpose: Compose multiple URL regexes into a single dispatch test
- Examples: `src/App.js:114-160`, `src/components/BuilderIoPage/index.js:15-29`
- Pattern: `getComposedRegex(...regexes) => new RegExp(regexes.map(r => r.source).join("|"))`

**SASS module per component:**
- Purpose: Locally scoped class names
- Examples: every `src/components/<Name>/<Name>.module.sass`, every `src/screens/<Name>/<Name>.module.sass`
- Pattern: `import styles from "./Name.module.sass"; <div className={styles.x}>`

## Entry Points

**Production SPA:**
- Location: `src/index.js`
- Triggers: `react-scripts start` / `react-scripts build` resolves it as the CRA entry
- Responsibilities: Initialize Builder.io API key, wrap `App` in `<BrowserRouter>`, mount into `#root`

**Alternate / unused entry:**
- Location: `src/BeyondApp.js`
- Triggers: Not currently referenced by `src/index.js`; appears to be a stripped-down Builder.io-only variant
- Responsibilities: Same as `App` but only renders the Builder.io branch
- Note: Imports `./src/api.js` (broken path — would not resolve)

**Cloud Browser bundle:**
- Location: `cloud-browser-static/src/browser.js`, built via `cloud-browser-static/build.js`
- Triggers: `yarn build` inside `cloud-browser-static/`
- Responsibilities: Standalone hyperbeam-powered cloud browser; output is consumed by the main app at `/browser/:activityId` route

**Shopify ops scripts:**
- Location: `ipynb_shopify/api.py`, `ipynb_shopify/*.ipynb`
- Triggers: Manual Jupyter execution
- Responsibilities: Out-of-band Shopify checkout customization + Klaviyo function deployment; not part of the web build

## Architectural Constraints

- **Threading:** Single-threaded browser JS; no web workers used.
- **Global state:** `BigApi` is a static class — its `config` and token cookies are process-wide singletons. `builder.init(BUILDER_IO_API_KEY)` is called once at module load in `src/index.js`. `ReactGA.initialize('UA-154139246-1')` is called at module load in `src/App.js` and `src/BeyondApp.js`.
- **Hardcoded keys:** `BUILDER_IO_API_KEY` (`src/index.js:8`), `ReactGA` UA ID (`src/App.js:61`), Builder.io API key, Meta Pixel ID, Twitter pixel, Reddit pixel, AdSense client ID (all in `public/index.html`) are committed in source. Backend API key is env-var driven (`REACT_APP_API_KEY`).
- **Dev proxy:** `package.json:41` sets `"proxy": "http://localhost:3001"` for CRA dev server.
- **Node compatibility:** README + commit `7f83139 "Fixme website build errors in Node 22"` indicate Node 22 fixes; CRA 5.0.1 in use. `SKIP_PREFLIGHT_CHECK=true` required by the dev start command.
- **No TypeScript build:** `src/api.js` is hand-edited but the comment at line 7 says "don't edit the .js version directly. Edit the .ts version and then run `tsc`" — no `.ts` source is present in the repo, so this instruction is stale.
- **Circular imports:** None observed at a glance. `App.js` imports leaf screens; screens import `api.js`; no screen imports `App.js`.
- **Strict mode:** `<React.StrictMode>` is enabled (`src/index.js:14`).
- **Router version mismatch risk:** Uses `react-router-dom@^6.0.2` but mixes `exact path=` (a v5 prop that v6 ignores). All routes still match correctly because v6 matches exactly by default, but the `exact` prop is dead code.

## Anti-Patterns

### Hard-coded Builder.io API key

**What happens:** `BUILDER_IO_API_KEY = '64dd5478e25746bf9db3b6c0319905f6'` is a literal in `src/index.js:8`.
**Why it's wrong:** Rotating the key requires a code edit and rebuild; cannot vary by environment.
**Do this instead:** Move to `process.env.REACT_APP_BUILDER_IO_API_KEY` and read it through `src/config.js` like `REACT_APP_API_KEY`.

### Path-regex dispatcher returns different `<Routes>` blocks

**What happens:** `src/App.js:174-322` returns one of six top-level branches based on regex tests against `pathname`. Each branch has its own `<Routes>` element.
**Why it's wrong:** React Router 6 is designed to compose routes; nested layouts via `<Outlet/>` would let you express layout-per-route declaratively, get correct active-link styling, and avoid double-evaluating filters on every render. The current approach also means adding a known URL to `/enrollprivacy` requires editing a regex in `App.js` (see commit `37d2020`).
**Do this instead:** Use `react-router-dom` v6 layout routes with `<Outlet/>`: a parent `<Route element={<BuilderLayout/>}>` containing children for each known Builder path, similar parents for Scan/BigOrder/Standalone. Keep one top-level `<Routes>`.

### `BigApi` as a static class

**What happens:** Every method is `static`, including config and token state (`src/api.js:71-540`).
**Why it's wrong:** Untestable (cannot inject a mock client), cannot have multiple configurations (e.g., for SSR), cannot easily reset state between tests. The TODO comment at `src/api.js:124-126` hints at this.
**Do this instead:** Convert to an instance class and expose a default singleton; inject via React context for tests.

### Dead-code comments at scale

**What happens:** `src/App.js` has ~30 lines of `// import` and `// <Route ... />` lines (lines 16-39, 269-289, 311-313). `src/screens/Home/index.js` has 10+ commented imports/components (lines 6-21, 33-43). `src/components/Header/index.js` and `src/components/Footer/index.js` carry large commented navigation/info structures.
**Why it's wrong:** Obscures actual routes/components in effect; signals that git is being treated as a notebook.
**Do this instead:** Delete; rely on git history. Where a feature is genuinely planned, leave a single `TODO` line referencing an issue.

### Inline alternate entry `src/BeyondApp.js`

**What happens:** Parallel root component with a broken import path (`./src/api.js`) and no caller. Drifts from `App.js`.
**Why it's wrong:** Confusing; appears live but is dead.
**Do this instead:** Delete or move under a clearly-named `experiments/` folder.

### Builder.io filter list duplicates routing knowledge

**What happens:** `builderIoFilter` in `src/App.js:115-137` enumerates every known Builder.io URL (`/software`, `/about`, `/termsofservice`, `/privacypolicy`, `/enrollprivacy`, `/hardwareterms`, etc.). Adding a Builder.io page requires editing this regex (commits `37d2020`, `bd4b0a6`).
**Why it's wrong:** Builder.io page existence is data, not code. A 404 from Builder.io should be the source of truth.
**Do this instead:** Use a catch-all that asks Builder.io for content first, falls back to React routes if no content. Or push the URL list into a JSON config / env var.

## Error Handling

**Strategy:** Centralized in `BigApiError.getApiError` (`src/api.js:33-69`). Every `BigApi` method `catch`es and re-throws a `BigApiError`. Screens then `catch` and either `console.error` (most common) or `setErrorMsg` for user-facing display.

**Patterns:**
- `try/catch` around every `BigApi.*` call in screens
- `e instanceof BigApiError` check to switch on `e.errors[0].msg` vs `e.message` (`src/screens/Api/ApiPages.js:81-90`)
- `console.error(e)` as default fallback; many screens swallow errors silently
- HTTP 401 with `AccessTokenNeedsRenewal` code triggers automatic `renewAccessToken` via nonce header (`src/api.js:348-360`)

## Cross-Cutting Concerns

**Logging:** `console.log` / `console.warn` / `console.error` everywhere. No structured logger.
**Validation:** Per-screen ad-hoc string checks; no shared validator. `prop-types` is in `package.json` but rarely used.
**Authentication:** `BigApi` cookies (`x-access-token`, `x-refresh-token`) + Bearer `apiKey` header on every request. `BigApiAuthenticationGuard` enum lets callers opt out of auth for public endpoints (e.g., `/info/region`, `/info/currency`, `/auth/email/verify/:token`).
**Analytics:** `react-ga` initialized in `App.js`; client-side pixels (Reddit, Twitter, Meta, AdSense) injected directly in `public/index.html`.
**i18n:** Locale (`en` / `jp`) determined from `?locale=` / `?builder.options.locale=` query string or `/info/region` API call (`src/components/BeyondBackend/index.js:14-34`); passed only to Builder.io. React-owned screens are English-only.

---

*Architecture analysis: 2026-05-21*
