npm package: @nebius/js-sdk
Description: Nebius AI SDK
Author: Nebius
Latest version: 0.1.51

# Nebius AI SDK for TypeScript and ECMAScript environments

This repository contains the Nebius SDK for interacting with Nebius AI services from Node.js and other TypeScript and ECMAScript environments.

## Quick links

- [API reference, generated by TypeDoc](https://nebius.github.io/js-sdk/documents/SERVICES.html)
- Generated TypeScript sources from protos: `src/api/` (not committed, one has to generate themselves)

## Installation

Install from npm (if published):

```bash
npm install @nebius/js-sdk
```

Or, when developing locally from this repository:

```bash
git clone git@github.com:nebius/js-sdk.git
cd js-sdk
npm install
npm run build
```

When developing inside the repo you can import from the `src/` path directly (examples below use local imports for clarity).

## Importing (ESM and CJS)

This package publishes dual outputs and an exports map so you can use either syntax:

- ESM:

```ts
import { SDK } from '@nebius/js-sdk';
```

- CommonJS:

```js
const { SDK } = require('@nebius/js-sdk');
```

Under the hood:

- `dist/esm` contains the ESM entry facade targeting Node ESM.
- `dist/cjs` contains the CommonJS build compiled by TypeScript.

## How-tos (TypeScript)

This section collects practical how-to recipes. They show common initialization and usage patterns for the TypeScript SDK. For full API details open the TypeDoc pages linked below.

### Initialize the SDK

The [`SDK`](https://nebius.github.io/js-sdk/classes/sdk.SDK.html) is the base.

Here is the simplest way to initialize it:

```ts
import { SDK } from '@nebius/js-sdk';
const sdk = new SDK({});
```

#### Initialize using an IAM token from the environment (Static/Env bearer):

```ts
import { SDK } from '@nebius/js-sdk';
import { StaticBearer, EnvBearer } from '@nebius/js-sdk/runtime/token/static';

const sdk = new SDK({ credentials: process.env.NEBIUS_IAM_TOKEN });

const sdk = new SDK({ credentials: new StaticBearer(process.env.NEBIUS_IAM_TOKEN) });

const sdk = new SDK({ credentials: new EnvBearer('NEBIUS_IAM_TOKEN') });
// or there are several other ways
```

#### Using Config Reader:

```ts
import { Config } from '@nebius/js-sdk/runtime/cli_config';
import { SDK } from '@nebius/js-sdk/sdk';

const cfg = new Config({ clientId: 'my-client' });
const sdk = new SDK({ configReader: cfg });
```

- Using a service account (private key / credentials file):

```ts
import { SDK } from '@nebius/js-sdk';

// pass a service account object (id + key) directly
const sdk = new SDK({
  serviceAccount: {
    serviceAccountId: 'serviceaccount-xxxxx',
    publicKeyId: 'public-key-id',
    privateKeyPem: '-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----',
  },
});
```

or use a [credentials file reader](https://nebius.github.io/js-sdk/classes/runtime_service_account_credentials_file.CredentialsFileReader.html)

Refer to TypeDoc for all the constructor options: [SDK class](https://nebius.github.io/js-sdk/classes/sdk.SDK.html) and [Config class](https://nebius.github.io/js-sdk/classes/runtime_cli_config.Config.html).

### Test credentials and SDK lifecycle

Use the `whoami()` helper to validate credentials quickly and `sdk.close()` to gracefully shutdown.

```ts
const { SDK } = require('@nebius/js-sdk');

const sdk = new SDK({
  /* ... */
});
const profileReq = sdk.whoami();
const profile = await profileReq;
console.log('Signed-in profile:', profile);

await sdk.close();
```

### Calling services and operations

Generated service clients take the `sdk` instance as the first parameter. Many RPCs return an [`Operation`](https://nebius.github.io/js-sdk/classes/runtime_operation.Operation.html) object — use `.result` to access a helper that exposes `.wait()` and `.resourceId()`.

```ts
import { SDK } from '@nebius/js-sdk';
import {
  BucketService as BucketServiceClient,
  CreateBucketRequest,
} from '@nebius/js-sdk/api/nebius/storage/v1/index';

const sdk = new SDK({
  /* ... */
});
const bucketSvc = new BucketServiceClient(sdk);

const op = await bucketSvc.create(
  CreateBucketRequest.create({
    /* ... */
  }),
).result;
await op.wait();
console.log('created id=', op.resourceId());

await sdk.close();
```

Per-request call options (deadlines and per-retry timeouts) can be passed as the request options, including operation's `wait()`.

#### Progress tracker

Some operations expose a progress tracker with ETA, work completion, and step details. You can access it via
[`Operation.progressTracker()`](https://nebius.github.io/js-sdk/classes/runtime_operation.Operation.html#progressTracker).
For operations that do not provide progress details (or v1alpha1 operations), this returns `undefined`.

Example of polling with a single-line progress display:

```ts
while (!op.done()) {
  await op.update();
  const tracker = op.progressTracker();
  const parts = [`waiting for operation ${op.id()} to complete:`];

  if (tracker) {
    const work = tracker.workFraction();
    if (work !== undefined) parts.push(`${Math.round(work * 100)}%`);

    const desc = tracker.description();
    if (desc) parts.push(desc);

    const started = tracker.startedAt();
    if (started) {
      const elapsedMs = Date.now() - started.valueOf();
      parts.push(`${Math.round(elapsedMs / 1000)}s`);
    }

    const eta = tracker.estimatedFinishedAt();
    if (eta) parts.push(`eta ${eta.toISOString()}`);
  }

  process.stdout.write(parts.join(' ') + '\r');
  await new Promise((resolve) => setTimeout(resolve, 1000));
}

process.stdout.write('\n');
```

### Parent IDs and resource scoping

Some methods may include `parentId` in the requests, for certain methods this field is populated automatically:

- Methods `list` and `getByName` with an empty `parentId`
- All other methods, except `update`, with an empty `metadata.parentId`

The `parentId` will only be set if it was preset at the initialization, either from the [CLI `Config`](https://nebius.github.io/js-sdk/classes/runtime_cli_config.Config.html) or from the `parentId` attribute from the [SDK](https://nebius.github.io/js-sdk/classes/sdk.SDK.html).

### Error handling and request metadata

RPC errors are surfaced as normal thrown errors. The runtime [`Request`](https://nebius.github.io/js-sdk/classes/runtime_request.Request.html) and [`Operation`](https://nebius.github.io/js-sdk/classes/runtime_operation.Operation.html) helpers expose metadata and status information, as well as request and trace IDs.

#### Retrieve request id / trace id

You can obtain request-level metadata from the returned `Request` object without awaiting the response immediately. The `Request` exposes helpers to read `requestId` and `traceId`.

```ts
const req = bucketSvc.get(GetBucketRequest.create({ id: '...' }));
const response = await req;
const requestId = await req.requestId();
const traceId = await req.traceId();
console.log({ requestId, traceId });
```

#### Token renewal options

When using renewable bearers (service accounts or other long-lived credentials), the SDK can perform token renewal on-demand for a specific request and surface renewal errors to that call. In TypeScript you express these hints by passing `authorizationOptions` on the gRPC call options object. See the runtime token docs for general behaviour: [runtime token docs](https://nebius.github.io/js-sdk/classes/runtime_token.Token.html) and the authorization options interface: [AuthorizationOptions](https://nebius.github.io/js-sdk/interfaces/runtime_authorization_provider.AuthorizationOptions.html).

Preferred TypeScript pattern — pass `authorizationOptions` in the call options:

```ts
// Example: force synchronous renewal and report renewal errors to the request
const callOptions = {
  authorizationOptions: {
    renewRequired: true,
    renewSynchronous: true,
    // timeout in milliseconds for the synchronous renewal
    renewRequestTimeoutMs: 900,
  },
};

// whoami accepts (metadata?, options?) so pass the options directly
await sdk.whoami(undefined, callOptions);

// For normal RPCs provide metadata and callOptions as the second and third args
const md = new (require('@grpc/grpc-js').Metadata)();
const op = await bucketSvc.update(updateReq, md, callOptions);
await op.wait();
```

#### Operations service

Some generated RPCs return an `Operation` wrapper. To list or fetch operations you should use the `getOperationService()` helper available on generated service clients (not the standalone `OperationServiceClient` import). Example:

```ts
const svc = new BucketServiceClient(sdk);
const opService = svc.getOperationService();
const listResp = await opService.list({ resourceId: '...' } as any);
// listResp.operations contains OperationWrapper elements; call opService.get(opId) to fetch real Operation
```

See [OperationService](https://nebius.github.io/js-sdk/classes/api_nebius_common_v1.OperationService.html) and the service `getOperationService()` docs (for example: [BucketService](https://nebius.github.io/js-sdk/classes/api_nebius_storage_v1.BucketService.html#getoperationservice)).

### Update / reset-mask helpers

When performing partial updates, the generated types and helpers follow the usual pattern: construct an update request and provide update masks where required. See the generated service docs (for example [BucketService](https://nebius.github.io/js-sdk/classes/api_nebius_storage_v1.BucketService.html)) for the exact request shapes and helper methods.

#### Updating with manually set `X-ResetMask`

If you need to send a partial update that should explicitly reset certain fields to defaults, set the `x-resetmask` metadata header. The runtime provides helpers to compute and ensure the header is present.

```ts
import { ensureResetMaskInMetadata } from '@nebius/js-sdk/runtime/resetmask';

const updateReq = UpdateBucketRequest.create({
  metadata: bucket.metadata,
  spec: {
    /* partial spec */
  },
});
const md = ensureResetMaskInMetadata(updateReq);
const op = await bucketSvc.update(updateReq, undefined as any, md);
await op.wait();
```

See [ensureResetMaskInMetadata](https://nebius.github.io/js-sdk/functions/runtime_resetmask.ensureResetMaskInMetadata.html) and [resetMaskFromMessage](https://nebius.github.io/js-sdk/functions/runtime_resetmask.resetMaskFromMessage.html) for details on how the mask is derived.

### Timeouts, retries and long-running operations

Tune per-call deadlines and per-retry timeouts using call options passed to RPCs. Long-running operations expose `.wait()`; prefer bounding waits in examples/tests with your own timeout helper to avoid indefinite hangs in CI.

#### Deadlines and timeouts (Node.js)

The SDK applies two layers of timing when making a unary RPC:

- Overall deadline: `deadline` (gRPC CallOptions)
  - Covers the entire request, including authorization (token acquisition/renewal) and all request retries.
  - Accepts a JavaScript `Date` or an absolute epoch timestamp in milliseconds (number).
  - If omitted, the SDK uses a default overall timeout of 15 minutes.

- Authorized request window: `RequestTimeout` (SDK retry option)
  - Starts after a successful authorization attempt and bounds the inner retry cycle for the actual RPC.
  - Defaults to 60 seconds when not provided.

- Per-retry timeout: `PerRetryTimeout` (SDK retry option)
  - Timeout for each individual retry attempt inside the authorized window.
  - Defaults to `RequestTimeout / RetryCount` when not provided. With defaults (`RequestTimeout = 60s`, `RetryCount = 3`) this is 20 seconds.

- Retry count: `RetryCount` (SDK retry option)
  - Maximum number of inner retries after a failed attempt (network/transient errors, selected gRPC codes).
  - Defaults to 3.

Behavior highlights:

- The authorization phase is retried according to the provider’s `canRetry` policy, but is always bounded by the overall `deadline`.
- After a successful authorization, the SDK runs the actual RPC with internal retries within a single “authorized window” limited by `RequestTimeout` (clipped by the overall `deadline`).
- Retriable conditions include common transient system errors (e.g., ECONNRESET, ETIMEDOUT) and gRPC status codes `UNAVAILABLE` and `RESOURCE_EXHAUSTED`, as well as SDK and API-specific retry conditions.

Minimal example:

```ts
import { Metadata } from '@grpc/grpc-js';

const md = new Metadata();
const options = {
  // Overall wall-clock cap (auth + request + retries)
  deadline: new Date(Date.now() + 30_000), // 30 seconds, if we know, that we don't need a browser authorization for instance

  // Inner retry window after successful authorization
  RequestTimeout: 10_000, // 10 seconds
  RetryCount: 2, // up to 2 retries
  PerRetryTimeout: 5_000, // 5 seconds per attempt (optional; otherwise derives from RequestTimeout/RetryCount)

  // Optional: authorization hints (for renewable credentials)
  authorizationOptions: {
    renewRequired: true,
    renewSynchronous: true,
    renewRequestTimeoutMs: 900,
  },
} as const;

const resp = await bucketSvc.get({ id: '...' } as any, md, options);
```

Notes:

- If you provide a numeric `deadline`, it is interpreted as an absolute epoch time in milliseconds.
- If `authorizationOptions` are set and renewal is needed, renewal will be attempted synchronously within the overall `deadline`. If renewal cannot succeed before the deadline (or is non-retriable), the SDK returns an `UNAUTHENTICATED` error.

### Where to look for types and detailed API

- SDK overview and constructor options: [SDK class](https://nebius.github.io/js-sdk/classes/sdk.SDK.html).
- CLI config reader: [Config class](https://nebius.github.io/js-sdk/classes/runtime_cli_config.Config.html).
- Token/bearer implementations: [Token](https://nebius.github.io/js-sdk/classes/runtime_token.Token.html) and specific classes like [`StaticBearer`](https://nebius.github.io/js-sdk/classes/runtime_token_static.StaticBearer.html), [`EnvBearer`](https://nebius.github.io/js-sdk/classes/runtime_token_static.EnvBearer.html), [`FileBearer`](https://nebius.github.io/js-sdk/classes/runtime_token_file.FileBearer.html), [`ServiceAccountBearer`](https://nebius.github.io/js-sdk/classes/runtime_token_service_account.ServiceAccountBearer.html).

## API reference / types

Type definitions and the full API reference are generated by TypeDoc and written to `docs/api`. [List of all available services](https://nebius.github.io/js-sdk/documents/SERVICES.html).

## Notes & tips

- Generated code in `src/api/` is ignored by the linters. Do not edit generated files by hand.
- If you need type-level documentation, [see API reference](https://nebius.github.io/js-sdk/modules/api_nebius.html).
- For CI and automated docs publishing, the project includes `typedoc` config and build scripts under `package.json`.

### Contributing

Contributions are welcome! Please refer to the [contributing guidelines](CONTRIBUTING.md) for more information.

### License

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

Copyright (c) 2025 Nebius B.V.