# @botmock/export

> ## Overview

Latest version **0.55.0** (published 2021-11-23) · MIT license · 0 weekly downloads

## Install

```sh
npm install @botmock/export
pnpm add @botmock/export
yarn add @botmock/export
bun add @botmock/export
```

## Health

**Score 25/100 (F)** — status: abandoned.

Positive: has types; no vulnerabilities; high quality score.

Warnings: low downloads; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.55.0 |
| Published | 2021-11-23 |
| First published | 2020-05-01 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | bundled |
| Module format | CommonJS |
| Dependencies | 10 |
| Unpacked size | 812.5 KB |
| Known vulnerabilities | 0 (+1 in 1 direct dependencies) |
| Install scripts | no |
| Maintainers | obaidahmed, gauharshakeel, calledrahul |

## Links

- npm: https://www.npmjs.com/package/@botmock/export
- Homepage: https://github.com/Botmock/sdk/packages/export#readme
- npm.io page: https://npm.io/package/@botmock/export

## Dependencies (10)

- [uuid](https://npm.io/package/uuid.md) 8.3.2
- [yaml](https://npm.io/package/yaml.md) ^1.9.2
- [write](https://npm.io/package/write.md) ^2.0.0
- [dotenv](https://npm.io/package/dotenv.md) ^8.2.0
- [fs-extra](https://npm.io/package/fs-extra.md) 10.0.0
- [handlebars](https://npm.io/package/handlebars.md) ^4.7.6
- [@types/uuid](https://npm.io/package/@types/uuid.md) 8.3.1
- [@botmock/utils](https://npm.io/package/@botmock/utils.md) 0.1.6
- [@botmock/client](https://npm.io/package/@botmock/client.md) 0.6.0
- [@types/fs-extra](https://npm.io/package/@types/fs-extra.md) ^9.0.5

## Recent versions

- 0.55.0 (latest) — 2021-11-23
- 0.38.0 (beta) — 2021-04-20
- 0.53.0 — 2021-09-22
- 0.52.0 — 2021-09-08
- 0.51.0 — 2021-09-01
- 0.50.0 — 2021-08-31
- 0.49.0 — 2021-08-30
- 0.48.0 — 2021-08-17
- 0.47.1 — 2021-08-17
- 0.47.0 — 2021-08-11
- 0.46.0 — 2021-08-11
- 0.45.0 — 2021-07-22
- 0.44.0 — 2021-06-23
- 0.43.0 — 2021-05-26
- 0.42.0 — 2021-05-14
- … 62 more at https://npm.io/package/@botmock/export/versions

## README

# `@botmock/export`

## Overview

This package is used to **export data into development platforms** from Botmock projects.

### Install

The package is available to install on npm.

```bash
npm install @botmock/export

```

### Guides

The following guides assumes a [TypeScript](https://www.typescriptlang.org/v2/docs/handbook/typescript-in-5-minutes-func.html) environment with [LTS Node.js](https://nodejs.org/en/) installed.

> **Note**: You can bootstrap such an environment by running `npx @botmock/cli`

> **Note**: Tokens and ids are [created and accessed using the Botmock dashboard](http://help.botmock.com/en/articles/2334581-developer-api)

- [Platform exporter guide](#platform-exporter)
- [Custom exporter guide](#custom-exporter)

#### Platform Exporter

`@botmock/export` ships with a number of platform exporters, which generate file structures necessary for importing Botmock projects in popular development platforms.

Listed below are the named exports corresponding to development platforms currently supported by `@botmock/export`.

- `BotFrameworkExporter`
- `DialogflowExporter`
- `LexExporter`
- `LuisExporter`
- `RasaExporter`
- `SkillsKitExporter`
- `WatsonExporter`

Each can be accessed by through the following pattern.

```typescript
import { BotFrameworkExporter } from "@botmock/export";

```

Let's walk through using the package's `DialogflowExporter`.

We begin by adding an entry point to `index.ts`.

```typescript
// index.ts
import {
  FileWriter,
  Kind,
  ProjectReference,
  DialogflowExporter,
} from "@botmock/export";

const projectReference: ProjectReference = {
  teamId: "YOUR_TEAM_ID",
  projectId: "YOUR_PROJECT_ID",
  boardId: "YOUR_BOARD_ID",
};

async function main(): Promise<void> {
  const exporter = new DialogflowExporter({ token: "YOUR_TOKEN" });
}

main().catch((err: Error) => {
  console.error(err);
});

```

The `main` function creates a new instance of the `DialogflowExporter`, and expects a valid `token`.

If we add to this file, we can generate the file structure that the Dialogflow dashboard requires in order to restore a project.

```typescript
// index.ts
async function main(): Promise<void> {
  const exporter = new DialogflowExporter({ token: "YOUR_TOKEN" });
  // The `data` property of the object returned by this method can be used by `FileWriter`, as we will see in the next step.
  const { data } = await exporter.exportProjectUnderDataTransformations({ projectReference });

  // Calling `writeAllResourcesToFiles` with `data` writes the files specificed in `data` to the filesystem.
  const writeResult = await (new FileWriter({ directoryRoot: "./output" })).writeAllResourcesToFiles({ data });
  if (writeResult.kind !== Kind.OK) {
    console.error(writeResult.value);
  } else {
    console.log("done");
  }
}

```

Running `ts-node index.ts` should generate the `.json` files that the Dialogflow dashboard requries to restore a project.

In the case that there is an error writing the files, an error value will be written to the console.

#### Custom Exporter

Let's walk through building a **custom exporter** by extending `BaseExporter` in the package.

Extending the `BaseExporter` is the approach taken by all **platform exporters** in the package.

We begin by adding an entry point to `index.ts`.

```typescript
// index.ts
const projectReference: ProjectReference = {
  teamId: "YOUR_TEAM_ID",
  projectId: "YOUR_PROJECT_ID",
  boardId: "YOUR_BOARD_ID",
};

async function main() { }

main().catch(err => {
  console.error(err);
});

```

Now, in a file named `exporter.ts

```typescript
// exporter.ts
import {
  BaseExporter,
  Resources,
  DataTransformation,
} from "@botmock/export";

export default class CustomExporter extends BaseExporter {
  #rootTransformation = (resources: Resources): DataTransformation => {
    return {
      // Suppose our platform requires a file named `response-structure.json`
      filename: "response-structure.json",
      data: {},
    }
  };
  dataTransformations = new Map([
    ["./path/to/output", this.#rootTransformation],
  ]);
}

```

`exporter.ts` now exports `CustomExporter`, which has `dataTransformation` and `#rootTransformation`.

##### `dataTransformation`

This public property must be a `Map`. It is responsible for mapping relative output paths to functions that can turn Botmock project data into a specific object format.

##### `#rootTransformation`

This private field must return an object (or an array of objects) with the following structure.

```typescript
{
  // `filename` must be the name of a file with a `.json`, `.yml`, or `.md` extension.
  filename: string;
  // `data` can be an object that will later be mapped to `.json`, `.yml`, or `.md` file contents.
  data: object;
}

```

Let's see how to make the `#rootTransformation` do something useful.

The `resources` parameter that is passed to this function is an object with the following properties.

> Each of the following keys contains an object with payloads for each of the key names beloning to the project referenced in `index.ts`.

```typescript
{
  project,
  team,
  board,
  intents,
  entities,
  variables,
}

```

In the transformation function itself, **we have access to this entire `resources` object**, to say how the Botmock data should be transformed for the use of our platform.

Below, we assume our platform expects a nested object structure in `response-structure.json`.

```typescript
// exporter.ts
#rootTransformation = (resources: Resources): DataTransformation => {
  const {
    project,
    board,
    intents,
    entities,
  } = resources;
  return {
    filename: "response-structure.json",
    data: {
      name: resources.project.name,
      responses: Object.values(board.board.messages).reduce((responses, response) => {
        // Because the response block data is kept in a twice-nested object, the following code unpacks the underlying data to a flat array, for use in our platform.
        const responseDataPerLocale = Object.values(response);
        const responseDataPerPlatform = responseDataPerLocale.flatMap(data => Object.values(data).flatMap(value => value.blocks))
        return {
          ...responses,
          ...responseDataPerPlatform,
        }
      }, {})
    },
  }
};

```

Jumping back to `index.ts`, we can now do the following.

```typescript
// index.ts
import {
  FileWriter,
  Kind,
  ProjectReference,
} from "@botmock/export";
import { default as CustomExporter } from "./exporter.ts";

const projectReference: ProjectReference = {
  teamId: "YOUR_TEAM_ID",
  projectId: "YOUR_PROJECT_ID",
  boardId: "YOUR_BOARD_ID",
};

async function main() {
  const exporter = new CustomExporter({ token: "YOUR_TOKEN" });
  // The `data` property of the object returned by this method can be used by `FileWriter`, as we will see in the next step.
  const { data } = await exporter.exportProjectUnderDataTransformations({ projectReference });
}

main().catch(err => {
  console.error(err);
});

```

Calling `exporter.exportProjectUnderDataTransformations({ projectReference })` allows us to have access to the `data` object, which can be used to write files to the local filesystem in a predictable way.

Let's see how `FileWriter` works.

```typescript
// index.ts
async function main() {
  const exporter = new CustomExporter({ token: "YOUR_TOKEN" });
  const { data } = await exporter.exportProjectUnderDataTransformations({ projectReference });

  // Calling `writeAllResourcesToFiles` with `data` from the previous step writes the files specificed in `data` to the filesystem.
  const writeResult = await (new FileWriter()).writeAllResourcesToFiles({ data });
  // `writeResult` is an object with `kind` and `value` properties based on the success of the writes.
  if (writeResult.kind !== Kind.OK) {
    console.error(writeResult.value);
  } else {
    console.log("done");
  }
}

```

Running `ts-node index.ts` should generate the single `response-structure.json` we outlined in our `CustomExporter`.

## API

#### `BaseExporter`

`class` extended by platform exporters and custom exporters.

##### `exportProjectUnderDataTransformations`

Returns `Promise` which resolves an object containing the `data` property consumable by `FileWriter`.

##### `data`

The `data` property returned by `exportProjectUnderDataTransformations` has the following shape.

| Key name      | Type | Description |
| ----------- | ----------- | ----------- |
| [_directoryPath_]      | `array`       | an array of objects containing `{ filename: "file.json", data: {}, }`, where `data` property in this object is a description of file contents that should belong in `filename`.  |

This means that `data` property can look like the following.

```
{
  './': [
    { filename: 'some-project.json', data: {} },
  ]
}

```

`exportProjectUnderDataTransformations` takes a single options object as an argument.

The options object contains the following.

| Key name      | Type | Description |
| ----------- | ----------- | ----------- |
| projectReference      | `object`       | object containing key, value pairs for "teamId", "projectId", and optionally, "boardId"  |

#### `dataTransformations`

**Required** property on any `BaseExporter`. This property should be a `Map` that describes how Botmock project resources should be transformed for a given path.

```typescript
import { BaseExporter, Resources, DataTransformation } from "@botmock/export";

class MyExporter extends BaseExporter {
  #rootTransformation = (resources: Resources): DataTransformation => {
    return {
      filename: "file.json",
      data: {
        intents: resources.intents.map(intent => Object.values(intent.utterances)),
      }
    }
  };
  dataTransformations = new Map([
    ["../../some/relative/path", this.#rootTransformation],
  ]);
}

```

#### `FileWriter`

`class` for parsing `data` property generated by `exportProjectUnderDataTransformations` and writing the files specified there to the correct locations in the local filesystem.

It can optionally take an options object, which has the following form.

| Key name      | Type | Description |
| ----------- | ----------- | ----------- |
| directoryRoot      | `string`       | relative path to a path from which all paths in the `dataTransformation` should be joined |
| jsonWriteOptions      | `object`       | object which is passed down to the [fs-extra `writeJSON` method options](https://github.com/jprichardson/node-fs-extra/blob/master/docs/writeJson.md#writejsonfile-object-options-callback) |

```typescript
import { FileWriter } from "@botmock/export";
import { MyExporter } from "./my-exporter";

(async () => {
  const exporter = new MyExporter({ token: "YOUR_TOKEN" });
  const { data } = await exporter.exportProjectUnderDataTransformations({ projectReference });

  const writer = new FileWriter();
})();

```

##### `writeAllResourcesToFiles`

Returns a `Promise` which resolves an object describing the success or failure of the file writing.

It takes a options argument with the following structure.

| Key name      | Type | Description |
| ----------- | ----------- | ----------- |
| data      | `object`       | [data property](#data) |

```typescript
import { FileWriter } from "@botmock/export";
import { MyExporter } from "./my-exporter";

(async () => {
  const exporter = new MyExporter({ token: "YOUR_TOKEN" });
  const { data } = await exporter.exportProjectUnderDataTransformations({ projectReference });

  const writer = new FileWriter();
  const writeResult = await writer.writeAllResourcesToFiles({ data });
})();

```

---
_Source: https://npm.io/package/@botmock/export · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
