# Regional Registry — Developer Guide

This MFE uses the **regional registry pattern** to vary components, business logic, and add-ons per region — with build-time code exclusion and TypeScript-enforced governance.

---

## How it works

```
src/regional/types.ts               ← governance contract (single source of truth)
src/regional/context.tsx            ← RegionalProvider + useRegional() hook
src/regional/useRegionalFeature.ts  ← convenience hook for reading feature flags
src/regional/decorators.ts          ← composable logic wrappers
src/regional/withRegionalConfig.tsx ← HOC for class/third-party components
src/regional/FeatureGate.tsx        ← declarative feature flag component
src/regional/registry.ts            ← createRegistry() composition utility

src/components/ErrorBoundary.tsx    ← catches tab render errors (region-agnostic)
src/components/ui/PricingWidget.tsx ← ExplicitPricingWidget — Pattern 3 demo (no provider needed)
src/components/tabs/SettingsTab.tsx ← withRegionalConfig HOC — Pattern 2 demo

src/config/regions/
  default/   ← base implementations (inherited by all regions)
  uk/        ← UK overrides (GDPR banner, GBP+VAT formatting, restricted features)
  us/        ← US overrides (USD formatting)
  sg/        ← SG overrides (SGD formatting — minimal override example)
```

**Quick workflow:**

```bash
# Start dev for UK — IDE and bundler both resolve @regional → uk/index.ts
daas dev --target uk-myproduct-myplatform-dev

# Switch to US — tsconfig.daas.json is regenerated, IDE updates automatically
daas dev --target us-myproduct-myplatform-dev
```

When you run `daas dev --target uk-product-platform-dev`:
1. rsbuild resolves `@regional` → `src/config/regions/uk/index.ts`
2. The CLI writes `tsconfig.daas.json` with matching TypeScript paths
3. IDE go-to-definition follows the active region
4. Only `uk/` + the `default/` files it imports are bundled

---

## Adding a new region

### 1. Create the region folder

```
src/config/regions/my-region/
  config.ts   ← RegionConfig (must export name `regionConfig`)
  logic.ts    ← createLogic(config): RegionalLogic factory
  index.ts    ← assembles RegionalRegistry (default export)
```

Add `components.tsx` and `addons.tsx` only if the region needs UI or compliance overrides.

### 2. `config.ts` — required fields

```ts
import type { RegionConfig } from "../../../regional/types"

export const regionConfig: RegionConfig = {
  id: "my-region",
  locale: "en-MY",
  currency: "MYR",
  dateFormat: "DD/MM/YYYY",
  numberFormat: { decimal: ".", thousands: "," },
  features: {
    showDetailsTab: true,
    showAnalyticsTab: false,
    enableExport: true,
  },
}
```

Set `showDetailsTab` and `showAnalyticsTab` (and any other feature flags) to match what this region should expose. Tabs declared in `src/config/tabs.ts` with a matching `featureFlag` will automatically show or hide based on these values — no changes to `tabs.ts` are needed.

### 3. `logic.ts` — factory pattern

```ts
import type { RegionConfig, RegionalLogic } from "../../../regional/types"
import { withCurrencySymbol } from "../../../regional/decorators"
import { baseFormatAmount, baseValidateAmount } from "../default/logic"

export const createLogic = (_config: RegionConfig): RegionalLogic => ({
  formatAmount: withCurrencySymbol("MYR ")(baseFormatAmount),
  validateAmount: (n) => baseValidateAmount(n),
})
```

### 4. `index.ts` — assembly with createRegistry

```ts
import { createRegistry } from "../../../regional"
import { defaultRegistry } from "../default"
import { regionConfig as myConfig } from "./config"
import { createLogic } from "./logic"

// createRegistry deep-merges components and inherits addons — no manual spread needed
const myRegistry = createRegistry(defaultRegistry, {
  config: myConfig,
  logic: createLogic(myConfig),
})

export default myRegistry
```

### 5. Run with your new region

```bash
daas dev --target my-region-product-platform-dev
```

---

## Adding an extension point

To add a new customizable slot (e.g. a `TaxBadge` component):

1. Add to `src/regional/types.ts`:

```ts
export interface RegionalComponents {
  PricingWidget: ComponentType<PricingWidgetProps>
  TaxBadge: ComponentType<{ rate: number }>   // ← add here
}
```

TypeScript immediately surfaces compile errors in every `region/index.ts` that doesn't implement `TaxBadge`. This is the governance enforcement mechanism.

2. Implement in `default/components.tsx` (the base version)
3. Override in region-specific `components.tsx` files as needed

---

## Three component injection patterns

### Pattern 1 — Hook (recommended)

```tsx
import { useRegional } from "../../regional"

export function MyWidget({ amount }: PricingWidgetProps) {
  const { logic, config } = useRegional()
  return <span>{logic.formatAmount(amount)} ({config.currency})</span>
}
```

### Pattern 2 — HOC (for class or third-party components)

```tsx
import { withRegionalConfig } from "../../regional"
import type { RegionalRegistry } from "../../regional"

// Define at module level — never inside a render function
const MyWidget = withRegionalConfig(BaseWidget)
// BaseWidget receives { registry: RegionalRegistry, ...ownProps }
// React DevTools shows: withRegionalConfig(BaseWidget)
```

Prefer this pattern when hooks aren't available: class components, third-party wrapper libraries, or any component where calling `useRegional()` directly is not an option.

Concrete scaffold example: `src/components/tabs/SettingsTab.tsx`.
`SettingsTabBase` receives `{ registry: RegionalRegistry }` injected by the HOC and renders
region ID, currency, and feature flags. Callers use `<SettingsTab />` with no registry prop.

### Pattern 3 — Explicit props (maximum testability)

```tsx
import type { RegionalLogic } from "../../regional"

function MyWidget({ amount, logic }: { amount: number; logic: RegionalLogic }) {
  return <span>{logic.formatAmount(amount)}</span>
}
// Wire it: <MyWidget amount={99} logic={useRegional().logic} />
// Test it: const logic = createLogic(ukConfig); render(<MyWidget amount={99} logic={logic} />)
```

**Scaffold example:** `src/config/regions/default/components.tsx` — `ExplicitPricingWidget` receives `logic` as a prop. `OverviewTab.tsx` wires it: `<ExplicitPricingWidget amount={99.99} logic={logic} />` (where `logic` comes from `useRegional()` in the parent). The same component can be tested with `createLogic(anyConfig)` and no provider.

---

## Utilities

### `createRegistry()` — type-safe registry composition

Instead of manually spreading `defaultRegistry`, use `createRegistry(base, overrides)`:

```ts
import { createRegistry } from "../../regional"
import { defaultRegistry } from "../config/regions/default"
import { regionConfig as myConfig } from "./config"
import { createLogic } from "./logic"

// Only specify what changes — everything else inherits from base
const myRegistry = createRegistry(defaultRegistry, {
  config: myConfig,
  logic: createLogic(myConfig),
})
export default myRegistry
```

`createRegistry` deep-merges `components` (only override the slots that change) and `addons.wrappers` (replace entirely when provided). TypeScript ensures the result satisfies `RegionalRegistry`.

**Wrapper ordering note:** The `reduceRight` pattern ensures `wrappers[0]` becomes the outermost DOM element. To assert wrapper order in tests, use `compareDocumentPosition` rather than text-based checks:

```ts
const outer = screen.getByTestId("outer-banner")
const inner = screen.getByTestId("inner-banner")
// Node.DOCUMENT_POSITION_FOLLOWING means inner appears after outer in the DOM tree
expect(outer.compareDocumentPosition(inner)).toBe(Node.DOCUMENT_POSITION_FOLLOWING)
```

This is the recommended way to assert wrapper nesting order in MFE tests — it is unambiguous and does not depend on rendered text content.

---

### `FeatureGate` — declarative feature flag rendering

Prefer `<FeatureGate>` over inline `config.features` checks:

```tsx
import { FeatureGate } from "../../regional"

// Renders children only when enableExport is true in the active region
<FeatureGate feature="enableExport">
  <ExportButton />
</FeatureGate>

// Optional fallback when disabled
<FeatureGate feature="showAnalyticsTab" fallback={<p>Not available in your region.</p>}>
  <AnalyticsWidget />
</FeatureGate>
```

`FeatureGate` reads `config.features[feature]` from the registry context. It must be rendered inside a `<RegionalProvider>`.

---

### `useRegionalFeature(key)` — convenience hook for feature flags

A typed shorthand for `useRegional().config.features[key]`:

```tsx
import { useRegionalFeature } from "../../regional"

function ExportButton() {
  const isEnabled = useRegionalFeature("enableExport")
  if (!isEnabled) return null
  return <button>Export</button>
}
```

Prefer `FeatureGate` for render-tree gating (simpler, declarative). Use `useRegionalFeature` when you need the boolean value for logic — e.g. conditionally calling an API, adjusting form validation, or passing a prop.

---

### Tab visibility — `featureFlag` in `TabConfig`

Tab visibility is controlled by the `featureFlag` field in `src/config/tabs.ts`. When set, the tab is shown only when the named flag is `true` in the active region's `config.features`.

```ts
// src/config/tabs.ts
{ id: "details",   label: "Details",   component: DetailsTab,   order: 1, featureFlag: "showDetailsTab" },
{ id: "analytics", label: "Analytics", component: AnalyticsTab, order: 2, featureFlag: "showAnalyticsTab" },
```

Omit `featureFlag` entirely to show a tab in every region.

The legacy `regions` allowlist field is still supported for backwards compatibility, but new tabs should use `featureFlag` instead — it keeps visibility logic co-located with the region's feature contract in `RegionConfig`.

---

### `ErrorBoundary` — catch tab render errors

`src/components/App.tsx` wraps `<TabLayout>` in `<ErrorBoundary>` by default. Use the `fallback` prop to customize the error UI:

```tsx
import { ErrorBoundary } from "./ErrorBoundary"

<ErrorBoundary fallback={(err) => <p>Failed to load: {err.message}</p>}>
  <TabLayout tabs={tabs} region={region} />
</ErrorBoundary>
```

`componentDidCatch` logs to console by default — replace with your error reporting service (Sentry, Datadog, etc.) in production.

---

### Dev debug overlay — runtime region switching

`src/containers/AppContainer.tsx` renders a fixed bar at the bottom of the screen with a button for each registered region. It only renders when `process.env.NODE_ENV !== "production"` — the dead-code eliminator removes it entirely from production bundles.

Use it to preview any region in development without changing env vars or restarting the dev server. Switching a region via the overlay triggers a full context re-render: every `useRegional()` consumer updates instantly, exactly as if you had restarted with a different `--target`.

To add more registries to the switcher (e.g. a platform registry), edit `AppContainer.tsx` directly.

---

## Testing

### Logic factories — no React needed

```ts
import { createLogic } from "../config/regions/uk/logic"

test("UK formats with £ and VAT", () => {
  const logic = createLogic(ukConfig)
  expect(logic.formatAmount(99)).toBe("£99 inc. VAT")
})
```

### Components — mock registry

```tsx
import { RegionalProvider } from "../regional"

const mockRegistry = {
  config: { id: "test", locale: "en-US", ... },
  components: { PricingWidget: ({ amount }) => <span>${amount}</span> },
  logic: { formatAmount: (n) => `$${n}`, validateAmount: (n) => n > 0 },
  addons: { wrappers: [] },
}

render(
  <RegionalProvider registry={mockRegistry}>
    <MyComponent />
  </RegionalProvider>
)
```

See `src/regional/regional.test.ts` and `src/regional/context.test.tsx` for complete examples.

---

## Governance rules

| Rule | Why |
|---|---|
| Never import a specific region directly in a component | Breaks build-time exclusion — all regions would be bundled |
| Shared components must not import from `src/config/regions/` | One-way dependency: `components/` → `regional/`, never the reverse |
| Logic factories receive config as parameter | Keeps logic files free of static config imports; enables isolated unit tests |
| `createRegistry` for region assembly (except `default/` — it is the root) | Ensures all component slots merge correctly; prevents accidental spread omissions |
| All `config.ts` files export the name `regionConfig` | `@region-config` alias consumers depend on this exact name |
| `addons.tsx` files use `.tsx` extension | Files containing JSX must use `.tsx` for TypeScript to parse them |
| `FeatureGate` for render-tree feature checks; `useRegionalFeature` for logic checks | `FeatureGate` is declarative and co-located with JSX; hook is for boolean values needed in logic |
| Tab visibility uses `featureFlag` in `TabConfig`, not the deprecated `regions` field | Single source of truth: feature flags live in `RegionConfig`, not scattered across tab configs |

---

## Common pitfalls

### "All regions are being bundled" — build exclusion not working

**Cause:** A component imports `regionConfig` directly from `@region-config` (or worse, imports from a specific region folder like `../../config/regions/uk`).

```ts
// ❌ Breaks build-time exclusion — all three regions end up in the bundle
import { regionConfig } from "@region-config"

// ✅ Correct — only the active region's registry is imported at build time
const { config } = useRegional()
```

The `@regional` alias is the single entry point the bundler sees. Everything outside that entry is tree-shaken. Any additional region import bypasses that exclusion.

---

### "TypeScript says `@regional` can't be found"

Check `tsconfig.daas.json` exists in your MFE root. It's generated by `daas dev` / `daas build` — you must have a `daas` command running. If working without a target (e.g. in CI type-checking without a region), `tsconfig.json` has static fallback paths pointing to `default/`.

---

### "`addons.tsx` gives a JSX error"

Files containing JSX must use `.tsx` extension. The `addons.ts` extension works only if the file exports plain data (no JSX). The moment you write `<div>…</div>` in an addon file, rename it `addons.tsx`.

---

### "New region compiles but runtime crashes"

Each region's `index.ts` must export a complete `RegionalRegistry`. If you added a new field to `RegionalComponents` in `types.ts` but didn't implement it in every region, TypeScript will catch it at compile time — but only if your editor and CI run `tsc`. The compile error surfaces as: *"Property X is missing in type …"*

---

### "Logic imports config statically instead of using the factory parameter"

```ts
// ❌ Static import — config is bound at module load, not at assembly time
import { regionConfig } from "./config"
export const createLogic = (): RegionalLogic => ({
  formatAmount: withCurrencySymbol(regionConfig.currency)(baseFormatAmount),
})

// ✅ Factory parameter — config injected at assembly time
export const createLogic = (config: RegionConfig): RegionalLogic => ({
  formatAmount: withCurrencySymbol(config.currency)(baseFormatAmount),
})
```

The factory pattern enables isolated unit tests: `createLogic(testConfig)` with no module mocking required.

---

### "Shared component imports from a region folder"

The dependency flow is one-way: `src/components/` may import from `src/regional/`, but must **not** import from `src/config/regions/<name>/`. Regions may import from components — not the reverse.

```ts
// ❌ Breaks layering — shared tab imports from a specific region's folder
import { SomeWidget } from "../../config/regions/default/components"

// ✅ Move region-agnostic utilities to src/components/ui/ and import from there
import { SomeWidget } from "../ui/SomeWidget"
```

If a component has no region-specific logic (i.e. it receives logic/config as props), it belongs in `src/components/ui/`, not inside a region folder. `ExplicitPricingWidget` is the scaffold example of this — it lives in `src/components/ui/PricingWidget.tsx` and is re-exported from `default/components.tsx` for discoverability alongside the other patterns.

---

## How `tsconfig.daas.json` works

When you run `daas dev --target uk-product-platform-dev`, the CLI writes:

```json
// tsconfig.daas.json (gitignored — regenerated on every run)
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "paths": {
      "@region-config": ["./src/config/regions/uk/config"],
      "@platform-config": ["./src/config/platforms/platform"],
      "@product-config": ["./src/config/products/product"],
      "@regional": ["./src/config/regions/uk/index"]
    }
  }
}
```

Your IDE reads `tsconfig.daas.json` and resolves `@regional` to `uk/index.ts`. Go-to-definition, hover types, and IntelliSense all reflect the active region automatically.

The committed `tsconfig.json` contains static fallback paths pointing to `default/` for when no `daas` command is running.
