# Adapter API

By using the Adapter API available in `@lazarv/react-server/adapters/core`, you can easily create a deployment adapter for any deployment target.

## Define the adapter handler

The adapter handler is a function that you need to implement to handle the deployment of your application. It will be called by the build process and it will receive the information needed to prepare the application for deployment.

An example of an adapter handler implementation can be found in the [Vercel adapter implementation](https://github.com/lazarv/react-server/blob/main/packages/react-server/adapters/vercel/index.mjs).

You can start by copying the Vercel adapter implementation and then modify it to fit your needs.

You need to export the adapter handler function from the file and then use the `createAdapter` function to create the adapter instance.

You also need to export default a function that will be used to create the adapter instance when adapter options are provided by the user in the `react-server.config.js` file.

```js
import { createAdapter } from "@lazarv/react-server/adapters/core";

export const adapter = createAdapter({
  name: "Vercel",
  outDir: ".vercel",
  outStaticDir: "static",
  handler: async ({ adapterOptions, files, copy, config, reactServerDir, reactServerOutDir, root, options }) => {
    // Your adapter handler implementation
  },
  deploy: {
    command: "vercel",
    args: ["deploy", "--prebuilt"],
  },
});

export default function defineConfig(adapterOptions) {
  return async (_, root, options) => adapter(adapterOptions, root, options);
}
```

You need to pass adapter properties to the `createAdapter` function to configure the adapter. These properties are:

`name`: The name of the adapter.

`outDir`: The directory where the adapter will output the deployment configuration.

`outStaticDir`: The directory where the static files will be output. This is optional. When provided, the adapter will copy the static files to the output directory.

`outServerDir`: The directory where the server files will be output. This is optional. When provided, the adapter will copy the server files to the output directory.

`handler`: The adapter handler function.

`deploy`: The deployment command and arguments. This is optional. When provided, the adapter will show what command the developer needs to run to deploy the application after it has been built. If the `--deploy` flag is provided during the build, the adapter will run this command. You can also pass a JSON string to `--deploy` (e.g. `--deploy '{"project": "my-project"}'`) to provide additional adapter options at deploy time — these are merged into `adapterOptions` with CLI values taking precedence. The `deploy` property can also be a function that will be called with the adapter options, CLI options and the handler result. This is useful if you need to customize the deployment command based on the adapter options or the handler result. If you don't provide a result with `command` and `args`, the default deployment handling spawning the command will be skipped. This is useful if you want to implement a custom deployment workflow in the adapter.

The deploy descriptor supports the following properties:

- [ ] `command`: The CLI command to run.
- [ ] `args`: The command arguments.
- [ ] `cwd`: The working directory for the command. Defaults to the project root.
- [ ] `message`: Help text shown to the user when `--deploy` is not used.
- [ ] `afterDeploy`: A callback invoked after successful deployment (e.g., to print the deployment URL).

```js
export const adapter = createAdapter({
  // ...
  handler: async ({ adapterOptions, files, copy, config, reactServerDir, reactServerOutDir, root, options }) => {
    // Your adapter handler implementation
    return {
      // Your handler result, this will be passed to the deploy function
    };
  },
  async deploy({ adapterOptions, options, handlerResult }) {
    // customize the deployment command based on the adapter options, CLI options or handler result
    return {
      command: "vercel",
      args: ["deploy", "--prebuilt"],
      cwd: outDir,
      afterDeploy: () => {
        console.log("Deployment complete!");
      },
    };
  },
});
```

## Adapter handler

The adapter handler function will receive the following properties:

- [ ] `adapterOptions`: The adapter options passed from the `react-server.config.js` file.
- [ ] `files`: The files object contains the static files, assets, client files, public files, server files and the dependencies.
- [ ] `copy`: The copy object contains the functions to copy the files to the output directory.
- [ ] `config`: The configuration object contains the configuration of the application.
- [ ] `reactServerDir`: The absolute path to the directory where the build output is located.
- [ ] `reactServerOutDir`: The relative directory name where the build output is located (default `.react-server`, configurable via `outDir` in config).
- [ ] `root`: The entry point of the application.
- [ ] `options`: The options object contains the options passed from the CLI.

> **Important:** When referencing server files in generated code (e.g., import paths), always use `reactServerOutDir` instead of hardcoding `.react-server`. This ensures your adapter works when users customize the build output directory.

The `files` object contains the following functions:

- [ ] `static`: The function to get the static files.
- [ ] `compressed`: The function to get the compressed static files.
- [ ] `assets`: The function to get the assets files.
- [ ] `client`: The function to get the client files.
- [ ] `public`: The function to get the public files.
- [ ] `server`: The function to get the server files.
- [ ] `dependencies`: The function to get the dependencies.
- [ ] `all`: The function to get all the static files (static + assets + client + public).

```js
const staticFiles = await files.static();
```

The `copy` object contains the following functions:

- [ ] `static`: The function to copy the static files.
- [ ] `compressed`: The function to copy the compressed static files.
- [ ] `assets`: The function to copy the assets files.
- [ ] `client`: The function to copy the client files.
- [ ] `public`: The function to copy the public files.
- [ ] `server`: The function to copy the server files.
- [ ] `dependencies`: The function to copy the dependencies.

```js
await copy.server(outServerDir);
```

## Helper functions

### banner

Shows a banner in the console.

```js
banner("building serverless functions");
```

### message

Shows a message in the console. Primary and secondary colors used to show the action and the message.

```js
message("creating", "index.func module");
```

### success

Shows a success message in the console.

```js
success("index.func serverless function initialized.");
```

### clearDirectory

Clears a directory.

```js
await clearDirectory(outServerDir);
```

### writeJSON

Writes a JSON file.

```js
await writeJSON(join(outServerDir, ".vc-config.json"), {
  runtime: "nodejs20.x",
  handler: "index.mjs",
  launcherType: "Nodejs",
  shouldAddHelpers: true,
  supportsResponseStreaming: true,
  ...adapterOptions?.serverlessFunctions?.index,
});
```

### clearProgress

Clears any active progress indicator.

```js
clearProgress();
```

### getConfig

Returns the application configuration from the `react-server.config.js` file.

```js
const config = getConfig();
```

### getPublicDir

Returns the path to the public directory.

```js
const publicDir = getPublicDir();
```

### getFiles

Returns a list of files matching the provided glob pattern.

```js
const files = await getFiles("**/*.mjs", srcDir);
```

### getDependencies

Returns the list of dependencies for the adapter files. This uses `@vercel/nft` to trace file dependencies.

```js
const dependencies = await getDependencies(adapterFiles, reactServerDir);
```

### spawnCommand

Spawns a command. Accepts an optional options object with `cwd` to set the working directory.

```js
await spawnCommand("vercel", ["deploy", "--prebuilt"]);
await spawnCommand("func", ["azure", "functionapp", "publish", appName], { cwd: outDir });
```

### deepMerge

Deep merges two objects. Target (adapter config) takes precedence for primitive values. For arrays, target items are used with unique source items prepended.

```js
const merged = deepMerge(sourceConfig, adapterConfig);
```

### readToml

Reads and parses a TOML file, returning `null` if parsing fails or the file doesn't exist.

```js
const config = readToml("wrangler.toml");
```

### writeToml

Writes a TOML file.

```js
await writeToml("wrangler.toml", config);
```

### mergeTomlConfig

Reads an existing TOML file and merges it with the adapter config. Returns the merged config.

```js
const config = mergeTomlConfig("wrangler.toml", adapterConfig);
```