npm package: @orbytapp/orbyt-sdk
Description: SDK ufficiale per integrare le feature flag di Orbyt nei tuoi progetti
Author: SpaceDesign
Latest version: 1.0.1

# Orbyt SDK

Official SDK for integrating Orbyt feature flags into your JavaScript/TypeScript projects.

## Installation

```bash
npm i @orbytapp/orbyt-sdk
```

or

```bash
yarn add @orbytapp/orbyt-sdk
```

## Using OrbytProvider

### React

#### Setup Provider

```tsx
// main.tsx
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { OrbytProvider } from "@orbytapp/orbyt-sdk/react";

const ORBYT_APP_KEY = import.meta.env.VITE_ORBYT_APP_KEY || "your-app-key-here";

createRoot(document.getElementById("root")!).render(
  <StrictMode>
    <OrbytProvider
      app_key={ORBYT_APP_KEY}
      environment={import.meta.env.VITE_ORBYT_ENVIRONMENT || "Production"}
    >
      <App />
    </OrbytProvider>
  </StrictMode>
);
```

#### Using getFeatureFlag

```tsx
import { useEffect, useState } from "react";
import { useOrbyt } from "@orbytapp/orbyt-sdk/react";

export default function MyComponent() {
  const { getFeatureFlag } = useOrbyt();
  const [enableFeature, setEnableFeature] = useState(false);

  useEffect(() => {
    const checkFeature = async () => {
      const result = await getFeatureFlag("enable_create_app");
      setEnableFeature(result.value);
    };
    checkFeature();
  }, [getFeatureFlag]);

  return <div>{enableFeature && <Button>Create App</Button>}</div>;
}
```

#### Using getFeatureFlag with Context

```tsx
import { useEffect, useState } from "react";
import { useOrbyt } from "@orbytapp/orbyt-sdk/react";

function MyComponent({ userId }: { userId: string }) {
  const { getFeatureFlag } = useOrbyt();
  const [showFeature, setShowFeature] = useState(false);

  useEffect(() => {
    async function checkFeature() {
      const result = await getFeatureFlag("new-feature", {
        user_id: userId,
      });
      setShowFeature(result.value);
    }
    checkFeature();
  }, [getFeatureFlag, userId]);

  return <div>{showFeature && <NewFeature />}</div>;
}
```

#### Using getDynamicFile

```tsx
import { useEffect, useState } from "react";
import { useOrbyt } from "@orbytapp/orbyt-sdk/react";

export default function MyComponent() {
  const { getDynamicFile } = useOrbyt();
  const [logoUrl, setLogoUrl] = useState("");

  useEffect(() => {
    const loadFile = async () => {
      const result = await getDynamicFile("logo");
      setLogoUrl(result.file_url);
    };
    loadFile();
  }, [getDynamicFile]);

  return <img src={logoUrl} alt="Logo" />;
}
```

### Vue 3

#### Setup Provider

```vue
<!-- App.vue -->
<template>
  <div id="app">
    <OrbytProvider app_key="your-app-key-here" environment="development">
      <router-view />
    </OrbytProvider>
  </div>
</template>

<script setup>
import { OrbytProvider } from "@orbytapp/orbyt-sdk/vue";
</script>
```

#### Using getFeatureFlag with Composition API

```vue
<template>
  <div>
    <div v-if="welcome_enabled">
      <h1>Welcome!</h1>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useOrbyt } from "@orbytapp/orbyt-sdk/vue";

const { getFeatureFlag } = useOrbyt();
const welcome_enabled = ref(false);

onMounted(async () => {
  const result = await getFeatureFlag("welcome_enabled");
  welcome_enabled.value = result.value;
});
</script>
```

#### Using getFeatureFlag with Options API

```vue
<template>
  <div>
    <div v-if="welcome_enabled">
      <h1>Welcome, {{ userData.first_name }}!</h1>
    </div>
  </div>
</template>

<script>
import { useOrbyt } from "@orbytapp/orbyt-sdk/vue";

export default {
  name: "Home_Trainer",
  setup() {
    const { getFeatureFlag } = useOrbyt();
    return {
      getFeatureFlag,
    };
  },
  data() {
    return {
      welcome_enabled: null,
      userData: {
        first_name: "",
      },
    };
  },
  async mounted() {
    const result = await this.getFeatureFlag("welcome_enabled");
    this.welcome_enabled = result.value;
  },
};
</script>
```

#### Using getFeatureFlag with Context

```vue
<template>
  <div>
    <NewFeature v-if="showFeature" />
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useOrbyt } from "@orbytapp/orbyt-sdk/vue";

const props = defineProps({
  userId: String,
});

const { getFeatureFlag } = useOrbyt();
const showFeature = ref(false);

onMounted(async () => {
  const result = await getFeatureFlag("new-feature", {
    user_id: props.userId,
  });
  showFeature.value = result.value;
});
</script>
```

#### Using getDynamicFile

```vue
<template>
  <img v-if="logoUrl" :src="logoUrl" alt="Logo" />
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useOrbyt } from "@orbytapp/orbyt-sdk/vue";

const { getDynamicFile } = useOrbyt();
const logoUrl = ref("");

onMounted(async () => {
  const result = await getDynamicFile("logo");
  logoUrl.value = result.file_url;
});
</script>
```

### Express

#### Setup

```typescript
// app.js or server.js
import express from "express";
import {
  createOrbytClient,
  featureFlagMiddleware,
} from "@orbytapp/orbyt-sdk/express";

const app = express();
const orbyt = createOrbytClient({
  app_key: process.env.ORBYT_APP_KEY || "your-app-key-here",
  environment: process.env.NODE_ENV || "production",
  // Optional: override baseUrl and timeout
  baseUrl: process.env.ORBYT_API_URL,
  timeout: 5000,
});
```

#### Using featureFlagMiddleware

```typescript
// Simple usage - check feature flag before route handler
app.post(
  "/register",
  featureFlagMiddleware(orbyt, {
    flag_key: "enable_registration",
  }),
  async (req, res) => {
    // This handler only runs if feature flag is enabled
    res.json({ message: "Registration successful" });
  }
);
```

#### Using with Custom Context

```typescript
app.post(
  "/register",
  featureFlagMiddleware(orbyt, {
    flag_key: "enable_registration",
    buildContext: (req) => ({
      user_id: req.user?.id,
      email: req.body.email,
    }),
  }),
  async (req, res) => {
    res.json({ message: "Registration successful" });
  }
);
```

#### Using with Custom Deny Handler

```typescript
app.post(
  "/register",
  featureFlagMiddleware(orbyt, {
    flag_key: "enable_registration",
    onDeny: (req, res, result) => {
      return res.status(403).json({
        error: "Registration is currently disabled",
        reason: result.reason,
      });
    },
  }),
  async (req, res) => {
    res.json({ message: "Registration successful" });
  }
);
```

#### Using getFeatureFlag Directly

```typescript
import { createOrbytClient } from "@orbytapp/orbyt-sdk/express";

const orbyt = createOrbytClient({
  app_key: "my-app",
  environment: "production",
});

app.post("/register", async (req, res) => {
  try {
    // app_key and environment are already configured in the client
    const result = await orbyt.getFeatureFlag("enable_registration", {
      user_id: req.user?.id,
      email: req.body.email,
    });

    if (result.matched && result.value === true) {
      // Registration logic here
      res.json({ message: "Registration successful" });
    } else {
      res.status(403).json({
        error: "Registration is currently disabled",
        reason: result.reason,
      });
    }
  } catch (error) {
    res.status(500).json({ error: "Feature flag check failed" });
  }
});
```

#### Using getDynamicFile

```typescript
import { createOrbytClient } from "@orbytapp/orbyt-sdk/express";

const orbyt = createOrbytClient({
  app_key: "my-app",
  environment: "production",
});

app.get("/logo", async (req, res) => {
  try {
    // app_key and environment are already configured in the client
    const result = await orbyt.getDynamicFile("logo");

    res.redirect(result.file_url);
  } catch (error) {
    res.status(500).json({ error: "Failed to retrieve dynamic file" });
  }
});
```

## API Reference

### getFeatureFlag(flag_key, context?, environment?)

Returns a complete feature flag result.

**Parameters:**

- `flag_key` (string): The feature flag key
- `context` (object, optional): Additional context (e.g., `{ user_id: "123" }`)
- `environment` (string, optional): Override the provider environment

**Returns:**

```typescript
{
  value: any,              // Feature flag value
  matched: boolean,        // true if a condition matched
  matched_condition?: any, // The matched condition (if present)
  reason?: string          // Reason why the flag wasn't enabled
}
```

### getDynamicFile(name, environment_name?)

Retrieves a dynamic file by name.

**Parameters:**

- `name` (string): The file name
- `environment_name` (string, optional): Override the provider environment

**Returns:**

```typescript
{
  file_url: string; // URL of the dynamic file
}
```

## License

MIT