@devicechain/client

中文文档
1.4.0发布于 2026/11/12Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 5112

DeviceChain client SDK — two-tier auth, typed GraphQL operations, and graphql-ws subscriptions over the client wire.

原始使用文档
文档目录7 节
  1. Where the requests go
  2. Queries and mutations
  3. Authentication
  4. Subscriptions
  5. Also in here
  6. Compatibility
  7. License

@devicechain/client

The DeviceChain client SDK: a small, framework-agnostic core for talking to a DeviceChain instance from the browser. Typed GraphQL over fetch, live subscriptions over graphql-ws, and a token seam your app fills in.

There is no Apollo, no store and no React in here. It owns the wire; your app owns state and UI.

npm install @devicechain/client graphql

graphql is a peer dependency — you almost certainly have it already, since the typed documents this SDK accepts come from GraphQL Code Generator.

Where the requests go

Each DeviceChain functional area serves its own GraphQL endpoint, and the SDK addresses them relative to the page, as /api/<area>/graphql. That is the contract a DeviceChain ingress serves: the SPA at /, each area behind /api/<area>.

So an app served from the same origin as the instance needs no configuration at all. An app served from somewhere else needs a dev-server proxy or a reverse proxy that forwards /api/<area>/... to the instance — the same shape the DeviceChain console's own vite.config.ts uses.

Queries and mutations

import { gql } from '@devicechain/client';
import { DeviceListDocument } from './gql/graphql'; // your generated documents

const { devices } = await gql('device-management', DeviceListDocument, {
  first: 25,
});

The area is the first argument, and it is a checked union — AREAS is exported as a real runtime array, not just a type, so you can enumerate it.

The result and variable types are inferred from the document. If the operation takes no variables, the argument is optional.

Failures arrive as a GraphQLRequestError carrying the HTTP status and the GraphQL error list. isForbiddenError(err) is the one classification worth special-casing, because "you may not do that" is a different thing to show a user than "the request did not arrive".

Authentication

DeviceChain uses two tokens: a tenant access token for ordinary work, and an identity token for instance-scoped admin endpoints. You register a getter for each, and the SDK attaches the right one per request — admin areas are detected from the area name, so a new admin call cannot quietly ride the tenant token.

import { setAuthTokenGetter, setIdentityTokenGetter } from '@devicechain/client';

setAuthTokenGetter(async () => store.accessToken); // refresh inside if near expiry
setIdentityTokenGetter(async () => store.identityToken);

Login and refresh calls run without a token; pass { anonymous: true } for those.

createSessionTokens supplies the refresh logic for that getter. You tell it where the token pair lives and how to call refresh. It refreshes shortly before the access token expires, shares one in-flight refresh among concurrent callers (refresh tokens rotate), and drops a result that arrives after the session was replaced:

import { createSessionTokens, gql, setAuthTokenGetter } from '@devicechain/client';

const session = createSessionTokens({
  read: () => store.pair, // { accessToken, refreshToken } | null
  apply: (pair) => { store.pair = pair; },
  refresh: async (refreshToken) =>
    (await gql('user-management', REFRESH, { refreshToken }, { anonymous: true })).refresh,
  onEnd: (err) => showSignIn(err), // refused, lapsed, or offline past expiry
});
setAuthTokenGetter(session.getAccessToken);
const stop = session.startAutoRefresh(); // optional: refresh on a timer, not only on demand

A refusal from the server, such as an invalid or revoked refresh token, ends the session at once. A transient failure does not: no response, a 5xx, or a 429. While the access token is still valid, callers keep getting it, and startAutoRefresh retries with jittered backoff. The session ends only when the access token actually expires.

decodeToken, isExpired and hasAuthority are exported for reading claims client-side. They decode, they do not verify — the server is the authority.

Subscriptions

import { subscribe, disposeSubscriptions } from '@devicechain/client';

const unsubscribe = subscribe(
  'event-management',
  MeasurementStreamDocument,
  { deviceToken: 'sensor-01' },
  {
    next: (data) => render(data),
    error: (err) => report(err),
    connected: (wasRetry) => setLive(true, wasRetry),
    closed: () => setLive(false),
  },
);

// on sign-out, drop every area socket so a stale token's connection cannot linger
disposeSubscriptions();

One socket is shared per area and reused across subscriptions. connected and closed are connection-level signals, which is what lets a UI tell "connected but idle" apart from "offline" — a distinction a data-only sink cannot make.

The socket carries subscriptions only; send queries and mutations over HTTP. The server closes it with code 4401 when the access token it opened with expires. subscribe handles that close for you: it reconnects once with a freshly resolved token, subscribes again, and reports the reconnect as connected(true), so re-query anything you must not miss when you see it.

Also in here

  • Basemap resolution (resolveBasemap, renderableBasemap) — the client half of the map-tile cascade, so every surface that draws a map resolves a per-surface override over the tenant default the same way.
  • Token masks (generateToken, conformsToMask, parseMask, …) — the device-token vocabulary, validated client-side before a round trip.

Compatibility

ESM only, built for bundler resolution (Vite, webpack, Rollup, esbuild). The emitted declarations use extensionless specifiers, which resolve under TypeScript's bundler module resolution and not under node16/nodenext.

License

Apache-2.0. See LICENSE.

版本与发布记录

@devicechain/client 共发布 48 个版本,首次发布于 2026/09/02;过去 12 个月发布了 48 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.4.0latest2026/11/12今天
1.4.0-rc.2next2026/11/11今天
1.4.0-rc.12026/11/111 天前
1.3.02026/11/092 天前
1.3.0-rc.12026/11/092 天前
1.2.02026/11/083 天前

关于 @devicechain/client 的常见问题

@devicechain/client 是什么?

DeviceChain client SDK — two-tier auth, typed GraphQL operations, and graphql-ws subscriptions over the client wire.

如何安装 @devicechain/client?

在项目目录运行 npm install @devicechain/client,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:graphql(^16.0.0 || ^17.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@devicechain/client 支持 TypeScript 吗?

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

@devicechain/client 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@devicechain/client 可以商用吗?

@devicechain/client 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@devicechain/client 的下载量有多少?

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

@devicechain/client 还在维护吗?

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