# @dtechph/wayfinding-sdk

TypeScript SDK for Duon indoor wayfinding. Use it from a React Native / Expo app to talk to [DuonWayfindingEngine](https://github.com/marx-wil/DuonWayfindingEngine) — types, REST client, 3D floor viewer, and pathfinding helpers.

The Engine is already deployed on Cloud Run. The SDK only needs the Engine **HTTPS origin** as `baseUrl`. It never talks to Cloud SQL or GCS; floor GLBs are downloaded from the Engine (`GET /uploads/...`), which proxies the bucket.

| | Staging | Production |
|---|---|---|
| Cloud Run service | `duon-wayfinding-engine-staging` | `duon-wayfinding-engine` |
| Git branch that deploys it | `staging` | `main` |
| Database / GCS | staging instance + bucket | production instance + bucket |
| Base URL | `https://duon-wayfinding-engine-staging-gljf7yb6va-uc.a.run.app` | `https://duon-wayfinding-engine-682585392363.us-central1.run.app` |
| npm package | `@dtechph/wayfinding-sdk-staging` | `@dtechph/wayfinding-sdk` |

Confirm the API is up:

```bash
curl https://duon-wayfinding-engine-staging-gljf7yb6va-uc.a.run.app/health
# {"status":"ok"}

curl https://duon-wayfinding-engine-682585392363.us-central1.run.app/health
# {"status":"ok"}
```

If a URL changes after a redeploy, look it up:

```bash
gcloud run services describe duon-wayfinding-engine-staging \
  --region us-central1 --project snappy-charge-488307-q4 \
  --format='value(status.url)'

gcloud run services describe duon-wayfinding-engine \
  --region us-central1 --project snappy-charge-488307-q4 \
  --format='value(status.url)'
```

## Install

Staging and production are **separate npm packages**, published automatically from the matching git branch. Use the package that matches the Engine you point `baseUrl` at.

| | Staging | Production |
|---|---|---|
| Git branch | `staging` | `main` |
| npm package | `@dtechph/wayfinding-sdk-staging` | `@dtechph/wayfinding-sdk` |
| Install | `npm install @dtechph/wayfinding-sdk-staging axios` | `npm install @dtechph/wayfinding-sdk axios` |

```ts
// staging app
import { createDuonClient } from '@dtechph/wayfinding-sdk-staging';

// production app
import { createDuonClient } from '@dtechph/wayfinding-sdk';
```

`axios` is a peer dependency of the API client. For the 3D viewer, also install the peers your app already uses with Expo:

```bash
npx expo install react react-native @react-three/fiber three \
  react-native-gesture-handler @expo/vector-icons
```

## Connect to staging or production

Create one client per environment. Pass the Engine origin only — no trailing slash, no `/api` suffix.

```ts
import { createDuonClient } from '@dtechph/wayfinding-sdk';

const STAGING =
  'https://duon-wayfinding-engine-staging-gljf7yb6va-uc.a.run.app';
const PRODUCTION =
  'https://duon-wayfinding-engine-682585392363.us-central1.run.app';

export const duonClient = createDuonClient({
  baseUrl: __DEV__ ? STAGING : PRODUCTION,
});
```

In Expo, prefer an env var so you can switch without a code change. `EXPO_PUBLIC_*` is inlined at bundle time.

```bash
# .env — staging (default for day-to-day work)
EXPO_PUBLIC_API_URL=https://duon-wayfinding-engine-staging-gljf7yb6va-uc.a.run.app

# production release
# EXPO_PUBLIC_API_URL=https://duon-wayfinding-engine-682585392363.us-central1.run.app
```

```ts
import { createDuonClient } from '@dtechph/wayfinding-sdk';

const baseUrl = process.env.EXPO_PUBLIC_API_URL;
if (!baseUrl) {
  throw new Error('Set EXPO_PUBLIC_API_URL to the Engine Cloud Run origin');
}

export const duonClient = createDuonClient({ baseUrl });
```

Staging and production are **separate databases**. Buildings, floors, and GLBs you create in the staging CMS are not in production, and the reverse.

### Native vs web (CORS)

- **React Native (iOS / Android):** no browser CORS. Point `baseUrl` at staging or production and it works.
- **Expo web or a browser app:** the Engine only allows origins listed in `CORS_ORIGIN`. Staging/production currently allow `http://localhost:3000`. Add your web origin there and redeploy Engine if you call the API from a browser.

Do **not** point `baseUrl` at a `storage.googleapis.com` bucket URL. Assets must go through the Engine.

## Fetch buildings, floors, and a floor GLB

```ts
import { createDuonClient } from '@dtechph/wayfinding-sdk';
import type { Building, FloorWithPois, POI, WalkableGraph } from '@dtechph/wayfinding-sdk';

const client = createDuonClient({
  baseUrl: process.env.EXPO_PUBLIC_API_URL!,
});

const buildings: Building[] = await client.getBuildings();
const building = await client.getBuilding(buildings[0].id);

const floor: FloorWithPois = await client.getFloor(building.floors[0].id);
const pois: POI[] = await client.getFloorPois(floor.id);
const graph: WalkableGraph = await client.getWalkableGraph(floor.id);
const beacons = await client.getBeacons(floor.id);

// file_path is like "/uploads/<folder>/<file>.glb" — resolve it against the Engine:
const glbUrl = client.buildAssetUrl(floor.file_path);
// → https://duon-wayfinding-engine-staging-….run.app/uploads/…/floor.glb
```

`buildAssetUrl` percent-encodes path segments, so filenames with spaces still download.

### Client methods

| Method | Engine route |
|---|---|
| `getBuildings()` | `GET /api/buildings` |
| `getBuilding(id)` | `GET /api/buildings/:id` |
| `getBuildingFloors(buildingId)` | `GET /api/buildings/:id/floors` |
| `getFloor(id)` | `GET /api/floors/:id` |
| `getFloorPois(floorId)` | `GET /api/floors/:id/pois` |
| `getWalkableGraph(floorId)` | `GET /api/floors/:id/walkable-graph` |
| `getBeacons(floorId)` | `GET /api/floors/:id/beacons` |
| `buildAssetUrl(file_path)` | `GET /uploads/...` (proxied GCS) |

Optional: `{ timeout: 30_000 }` on `createDuonClient` (milliseconds, default 30s).

## Render a floor (React Native)

```tsx
import { FloorViewer3D } from '@dtechph/wayfinding-sdk';
import { findPath, nearestNode } from '@dtechph/wayfinding-sdk';

<FloorViewer3D
  glbUrl={glbUrl}
  pois={pois}
  walkableGraph={graph}
  onSelectPoi={setSelectedPoi}
/>
```

Pathfinding is computed in the app, then passed in as `routeNodes`:

```ts
const start = nearestNode(graph, { x, y, z });
const path = findPath(graph, start.id, destinationNodeId);
```

`NullPositioningProvider` is a no-op BLE stub for testing without beacons.

### BLE Beacon Positioning (`BleBeaconProvider`)

`BleBeaconProvider` takes a list of beacons from the API and a platform-specific BLE scanner function, then emits real-time position estimates using weighted-centroid trilateration.

```ts
import {
  BleBeaconProvider,
  type BleScannerFn,
  type BeaconReading,
} from '@dtechph/wayfinding-sdk';

// 1. Fetch beacons for the current floor
const beacons = await client.getBeacons(floorId);

// 2. Provide a scanner function (e.g. using react-native-ble-plx)
const scannerFn: BleScannerFn = (onReading) => {
  // Start your BLE scan here, call onReading() for each beacon detected:
  //   onReading({ uuid, major, minor, rssi });
  // Return a cleanup function that stops scanning:
  return () => { /* stop scan */ };
};

// 3. Create the provider and subscribe to position updates
const provider = new BleBeaconProvider(beacons, scannerFn);

const unsubscribe = provider.onPosition((position) => {
  // position: { x, z, floorId, accuracy: 'low'|'medium'|'high', timestamp }
  setBlueDot({ x: position.x, z: position.z });
});

provider.start();

// On cleanup:
provider.stop();
unsubscribe();
```

Each beacon's `tx_power` and `path_loss_n` are read from the database automatically. The SDK converts RSSI → distance using the log-distance path loss model with these per-beacon calibration values.

## Local Engine (optional)

For Engine development only, run DuonWayfindingEngine on your machine (`http://localhost:5000`, or `http://10.0.2.2:5000` on the Android emulator) and set `EXPO_PUBLIC_API_URL` to that host. Cloud Run staging/production stay the default for apps that are not iterating on the API itself.

## CI / npm publish

Pushes to `staging` and `main` run tests. npm publish runs **only** when `version` in `package.json` is higher than the version already on npm for that environment’s package.

1. **One-time:** create an npm [granular access token](https://www.npmjs.com/settings/~/tokens) with write access to the `@dtechph` org. Add it as the repo secret `NPM_TOKEN` (Settings → Secrets and variables → Actions). The existing `SLACK_WEBHOOK_URL` secret is reused for publish notifications.
2. **Release:** bump `version` in `package.json` (`1.0.0` → `1.0.1`) on `staging` or `main` and push. If the version is unchanged or already published, CI skips npm and does not Slack-notify a deploy.
3. **Local dry-run:**

```bash
./scripts/prepare-publish.sh staging    # or production
npm publish --dry-run
```

Do not run `npm publish` from a laptop unless you intend to skip CI — the workflow is the release path.

## Troubleshooting

| Symptom | Check |
|---|---|
| Network error / no response | `curl $EXPO_PUBLIC_API_URL/health` must return `{"status":"ok"}`. No trailing slash on `baseUrl`. |
| Empty buildings list | You are on the other environment. Staging and production do not share data — add buildings in that environment’s CMS. |
| GLB fails to load | Use `client.buildAssetUrl(floor.file_path)`, not the raw `file_path` and not a GCS URL. |
| CORS error in Expo web | Native apps are fine. For web, add the page origin to Engine `CORS_ORIGIN` and redeploy. |
| `axios` module not found | Install the peer: `npm install axios`. |
