@commercelayer/provisioning-sdk

中文文档
3.0.2发布于 2026/11/10MITTypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 2073

Commerce Layer Provisioning API Javascript SDK

原始使用文档
文档目录19 节
  1. Table of contents
  2. Getting started
  3. Installation
  4. Authentication
  5. Import
  6. Options
  7. API version
  8. SDK usage
  9. Create
  10. Retrieve / List
  11. Update
  12. Delete
  13. Overriding credentials
  14. Handling validation errors
  15. Using interceptors
  16. Refreshing access token
  17. Contributors guide
  18. Need help?
  19. License

Commerce Layer Provisioning SDK

Version Downloads/week License Verify CodeQL TypeScript

A JavaScript Library wrapper that makes it quick and easy to interact with the Commerce Layer Provisioning API.

This package is generated and released from the commercelayer-sdk monorepo, alongside @commercelayer/sdk. Both are produced by the same generator from the API’s own published schema.

Table of contents


Getting started

To get started with Commerce Layer Provisioning SDK you need to install it, get the credentials that will allow you to perform your API calls, and import the SDK into your application's code. The sections below explain how to achieve this.

Installation

Commerce Layer Provisioning SDK is available as an npm and yarn package that you can install with the command below:

npm install @commercelayer/provisioning-sdk

// or

yarn add @commercelayer/provisioning-sdk

Authentication

All requests to Commerce Layer API must be authenticated with an OAuth2 bearer token. Hence, before starting to use this SDK you need to get a valid access token. Kindly check our documentation for more information about the available authorization flows.

Feel free to use Commerce Layer JS Auth, a JavaScript library that helps you wrap our authentication API.

Import

You can use the ES6 default import with the SDK like so:

import CommerceLayerProvisioning from '@commercelayer/provisioning-sdk'

const clp = CommerceLayerProvisioning({
  accessToken: 'your-access-token',
  apiVersion: '2026-05'
})

Options

When instantiating a new SDK client you can pass some options to initialize it:

{
  accessToken: string         // A valid API access token
  apiVersion: ApiVersion      // The API version to target, e.g. '2026-05' — required, see API version below
  timeout?: number            // A custom request timout (<= 15 secs [default])
  headers?: RequestHeaders    // Custom request headers
  userAgent?: string          // Custom user-agent useful in certaing contexts but often not allowed by browsers
  fetch?: Fetch               // A specific fetch implementation 
  refreshToken?: RefreshToken // A function responsible for token refresh
}

Same options can be changed after SDK initialization or passed at runtime while executing an API call:

  const options = { ... }

  // Instantiate the client using desired options
  const clp = CommerceLayerProvisioning(options)

  // Change configuration after client cteation
  clp.config(options)

  // Use runtime configuration without persisting settings
  clp.organizations.list({}, options)

API version

The Provisioning API is versioned, and every request targets a single version. apiVersion is therefore required when creating a client, and becomes part of each request URL — /api/2026-05/organizations.

Only the versions this release of the SDK was generated for are accepted; any other value is a type error. Both are exported:

import { API_SCHEMA_VERSION, API_SUPPORTED_VERSIONS } from '@commercelayer/provisioning-sdk'

API_SUPPORTED_VERSIONS // ['2026-05'] — the versions you can target
API_SCHEMA_VERSION     // '2026-05' — the version the types describe

[!IMPORTANT] Upgrading from 2.x: apiVersion is new and required, so every CommerceLayerProvisioning(...) call needs it.

SDK usage

The JavaScript Provisioning SDK is a wrapper around Commerce Layer Provisioning API which means you would still be making API requests but with a different syntax. For now, we don't have comprehensive SDK documentation for every single resource our API supports, hence you will need to rely on our comprehensive Provisioning API Reference as you go about using this SDK. So for example, if you want to create a role, take a look at the Role object or the Create a role documentation to see the required attributes and/or relationships. The same goes for every other supported resource.

The code snippets below show how to use the SDK when performing the standard CRUD operations provided by our REST API. Kindly check our Provisioning API reference for the complete list of available resources and their attributes.

Create

How to create a Role
  // Select the organization (it's a required relationship for the SKU resource)
  const organizations = await clp.organizations.list({ filters: { name_eq: 'Test Org' } })

  const attributes = {
    name: 'Test Role',
    organization: clp.organizations.relationship(organizations.first().id), // assigns the relationship
  }

  const newRole = await clp.roles.create(attributes)

ℹ️ Check our API reference for more information on how to create a Role.

Retrieve / List

How to fetch a single organization
  // Fetch the organization by ID
  const org = await clp.organizations.retrieve('BxAkSVqKEn')

  // Fetch all organizations and filter by name
  const orgs = await clp.organizations.list({ filters: { name_start: 'TestOrg_' } })

  // Fetch the first organization of the list
  const org = (await clp.organizations.list()).first()

  // Fetch the last organization of the list
  const org = (await clp.organizations.list()).last()

ℹ️ Check our API reference for more information on how to retrieve an organization.

How to fetch a collection of organizations
  // Fetch all the organizations
  const orgs = await clp.organizations.list()

When fetching a collection of resources you can leverage the meta attribute to get its meta information like so:

  const orgs = await clp.organizations.list()
  const meta = orgs.meta

ℹ️ Check our API reference for more information on how to list all SKUs.

How to fetch a collection of organizations and sort the results
  // Sort the results by creation date in ascending order (default)
  const orgs = await clp.organizations.list({ sort: { created_at: 'asc' } })

  // Sort the results by creation date in descending order
  const orgs = await clp.organizations.list({ sort: { created_at: 'desc' } })

ℹ️ Check our API reference for more information on how to sort results.

How to fetch a collection of Memberships and include associations
  // Include an association (organization)
  const mships = await clp.memberships.list({ include: [ 'organization' ] })

  // Include an association (stock role)
  const mships = await clp.memberships.list({ include: [ 'role' ] })

ℹ️ Check our API reference for more information on how to include associations.

How to fetch a collection of Permissions and return specific fields (sparse fieldsets)
  // Request the API to return only specific fields
  const perms = await clp.permissions.list({ fields: { permissions: [ 'can_create', 'can_update' ] } })

  // Request the API to return only specific fields of the included resource
  const mships = await clp.memberships.list({ include: [ 'organization' ], fields: { organizations: [ 'name' ] } })

ℹ️ Check our API reference for more information on how to use sparse fieldsets.

How to fetch a collection of organizations and filter data
  // Filter all the organizations fetching only the ones whose name starts with the string "ORG"
  const orgs = await clp.organizations .list({ filters: { name_start: 'ORG' } })

  // Filter all the organizations fetching only the ones whose name ends with the string "Brand"
  const orgs = await clp.organizations.list({ filters: { name_end: 'Brand' } })

  // Filter all the organizations fetching only the ones whose name contains the string "Test"
  const orgs = await clp.organizations.list({ filters: { name_cont: 'Test' } })

  // Filter all the organizations fetching only the ones created between two specific dates
  // (filters combined according to the AND logic)
  const orgs = await clp.organizations.list({ filters: { created_at_gt: '2018-01-01', created_at_lt: '2018-01-31'} })

  // Filters all the organizations fetching only the ones created or updated after a specific date
  // (attributes combined according to the OR logic)
  const orgs = await clp.organizations.list({ filters: { updated_at_or_created_at_gt: '2019-10-10' } })

  // Filters all the Roles fetching only the ones whose name contains the string "Admin"
  // and whose organization name starts with the string "ORG"
  const roles = await clp.roles.list({ filters: { name_cont: 'Admin', organization_name_start: 'ORG'} })

ℹ️ Check our API reference for more information on how to filter data.

How to paginate a collection of organizations

When you fetch a collection of resources, you get paginated results. You can request specific pages or items in a page like so:

  // Fetch the organizations, setting the page number to 3 and the page size to 5
  const skorgsus = await clp.organizations.list({ pageNumber: 3, pageSize: 5 })

  // Get the total number of organizations in the collection
  const orgCount = orgs.meta.recordCount

  // Get the total number of pages
  const pageCount = orgs.meta.pageCount

PS: the default page number is 1, the default page size is 10, and the maximum page size allowed is 25.

ℹ️ Check our API reference for more information on how pagination works.

How to iterate through a collection of Organizations

To execute a function for every item of a collection, use the map() method like so:

  // Fetch the whole list of organizations (1st page) and print their ids and names to console
  const orgs = await clp.organizations.list()
  orgs.map(o => console.log('ID: ' + o.id + ' - Name: ' + o.name))
How to fetch resource relationships

Many resources have relationships with other resources and instead of including these associations as seen above, you can fetch them directly. This way, in the case of 1-to-N relationships, you can filter or sort the resulting collection as standard resources.

// Fetch 1-to-1 related resource: billing address of an order
const org = await clp.memberships.organization('xYZkjABcde')

// Fetch 1-to-N related resources: orders associated to a customer
const perms = await clp.roles.permissions('XyzKjAbCDe', { fields: ['can_create', 'can_update'] })

In general:

  • An API endpoint like /api/organizations or /api/organization/<organizationId> translates to clp.organizations or clp.organizations('<organizationId>') with the SDK.
  • 1-to-1 relationship API endpoints like /api/roles/<roleId>/organization translates to clp.roles('<roleId>', { include: ['organization'] }} with the SDK.
  • 1-to-N relationship API endpoints like /api/roles/<roleId>?include=versions or /api/roles/<roleId>/permissions translates to clp.roles.retrieve('<roleId>', { include: ['versions'] }) or clp.roles.permissions('<roleId>') with the SDK.

ℹ️ Check our API reference for more information on how to fetch relationships.

How to count resources

Many times you simply need to count how many resources exist with certain characteristics. You can then call the special count function passing a filter to get as result the total number of resources.

// Get the total number of sales_channel credentials
const credentials = await clp.api_credentials.count({ filters: { kind_eq: 'sales_channel' } })

Update

How to update an existing organization
  const org = {
    id: 'xYZkjABcde',
    reference: '<new-reference>',
    reference_origin: '<new-reference-origin>'
  }

  clp.organizations.update(org) // updates the SKU on the server

ℹ️ Check our API reference for more information on how to update an organization.

Delete

How to delete an existing membership
  clp.memberships.delete('xYZkjABcde') // persisted deletion

ℹ️ Check our API reference for more information on how to delete a membership.

Overriding credentials

If needed, Commerce Layer Provisioning SDK lets you change the client configuration and set it at a request level. To do that, just use the config() method or pass the options parameter and authenticate the API call with the desired credentials:

  // Permanently change configuration at client level
  clp.config({ accessToken: 'your-access-token' })
  const roles = await clp.roles.list()

  or

  // Use configuration at request level
  clp.roles.list({}, { accessToken: 'your-access-token' })

Handling validation errors

Commerce Layer Provisioning API returns specific errors (with extra information) on each attribute of a single resource. You can inspect them to properly handle validation errors (if any). To do that, use the errors attribute of the catched error:

  // Log error messages to console:
  const attributes = { name: '' }

  const newRole = await clp.roles.create(attributes).catch(error => console.log(error.errors))

  // Logged errors
  /*
  [
    {
      title: "can't be blank",
      detail: "name - can't be blank",
      code: 'VALIDATION_ERROR',
      source: { pointer: '/data/attributes/name' },
      status: '422',
      meta: { error: 'blank' }
    },
    {
      title: "can't be blank",
      detail: "organization - can't be blank",
      code: 'VALIDATION_ERROR',
      source: { pointer: '/data/relationships/organization' },
      status: '422',
      meta: { error: 'blank' }
    }
  ]
  */

ℹ️ Check our API reference for more information about the errors returned by the API.

Using interceptors

You can use interceptors to intercept SDK messages and modify them on the fly before the request is sent to the API or before the response is parsed and returned by the client. You can also access the error object before it is thrown by the SDK.

Interceptors are special functions that are able to handle SDK messages and return a (eventually) modified version of them for use by the client.

  const requestInterceptor = (request: RequestObj): RequestObj => {
    console.log(request)
    return request
  }

  const responseInterceptor = (response: ResponseObj): ResponseObj => {
    console.log(response)
    return response
  }

  const errorInterceptor = (error: ErrorObj): ErrorObj => {
    console.log(error)
    return error
  }

Here an example of how to use them:

  // Add the interceptors (only one or all if needed)
  clp.addRequestInterceptor(requestInterceptor)
  clp.addResponseInterceptor(responseInterceptor, errorInterceptor)

  const organizations = await clp.organizations.list()

  // Remove interceptors
  // Tt is possible to remove only a specific interceptor: cl.removeInterceptor('request')
  cl.removeInterceptors()

Raw Response Reader

The RawResponseReader is a special interceptor that allows to catch the original message coming frome the API before it is parsed and translated in SDK objects.

  // Add a RawResponseReader capable of capturing also response headers
  const rrr = clp.addRawResponseReader({ headers: true })
  
  const organizations = await clp.organizations.list()

  cl.removeRawResponseReader()

  console.log(rrr.rawResponse)
  console.log(rrr.headers)

Refreshing access token

It is possible that you are using an access token that is about to expire especially if it has been used for many API calls. In this case you can define a special function that takes care of refreshing the token when a call fails because it has expired.

  async function myRefreshTokenFunction(espiredToken: string): Promise<string> {
    // Get a new access token using for example our js-auth library
    return (await getAccessToken()).accessToken
  }

  cl.config({ refreshToken: myRefreshTokenFunction })

  // If needed you can later retrieve the new access token
  const newToken = cl.currentAccessToken

Contributors guide

  1. Fork this repository (learn how to do this by reading the GitHub documentation).

  2. Clone the forked repository like so:

    git clone https://github.com/<your username>/commercelayer-sdk.git && cd commercelayer-sdk
    
  3. Install the workspace from the repository root:

    pnpm install
    
  4. Make your changes. Most of this package is generated from the API schema — anything you edit under gen/ will be overwritten. Change the generator or sdk.config.ts instead, then run pnpm generate and commit the result.

  5. Create a pull request (learn how to do this). Lint, types, both test suites and a check that generated output is reproducible run automatically.

  6. Someone will attend to your pull request and provide some feedback.

Need help?

License

This repository is published under the MIT license.

版本与发布记录

@commercelayer/provisioning-sdk 共发布 72 个版本,首次发布于 2023/10/31;过去 12 个月发布了 12 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
3.0.2latest2026/11/104 天前
3.0.2-beta.0beta2026/11/094 天前
3.0.12026/10/071 个月前
3.0.02026/10/061 个月前
3.0.0-beta.32026/10/031 个月前
3.0.0-beta.22026/09/301 个月前

其他发布通道:prerelease → 2.0.0-rc.2,sdk1 → 1.1.0,sdk2 → 2.10.2,beta → 3.0.2-beta.0。

关于 @commercelayer/provisioning-sdk 的常见问题

@commercelayer/provisioning-sdk 是什么?

Commerce Layer Provisioning API Javascript SDK

如何安装 @commercelayer/provisioning-sdk?

在项目目录运行 npm install @commercelayer/provisioning-sdk,或使用 pnpm add / yarn add / bun add。

@commercelayer/provisioning-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@commercelayer/provisioning-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@commercelayer/provisioning-sdk 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@commercelayer/provisioning-sdk 可以商用吗?

@commercelayer/provisioning-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@commercelayer/provisioning-sdk 的下载量有多少?

根据 npm 官方下载统计,@commercelayer/provisioning-sdk 在 2026/10/11 – 2026/11/09 这 30 天内被下载 2,073 次,日均约 69 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@commercelayer/provisioning-sdk 还在维护吗?

最新版本 3.0.2 发布于 2026/11/10(4 天前);至今共发布 72 个版本,其中过去 12 个月发布了 12 个;首次发布于 2023/10/31。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。