@gizmodata/hardcharger

中文文档
2.5.0发布于 2026/11/15Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 3192

JavaScript/TypeScript client for Hardcharger™, GizmoData™'s DuckDB 2.0 server: hardcharger:// URLs on the Chargewire client, for Node, browsers, Deno, Bun and edge runtimes.

原始使用文档
文档目录16 节
  1. Query Hardcharger™ from JavaScript and TypeScript: hardchar…
  2. 🔌 What is it?
  3. 🚀 Quick start
  4. 📦 Installing
  5. 🔗 URLs
  6. ⚙️ Options
  7. 🔒 Read-only connections
  8. 🪪 Client certificate sign-in (mutual TLS)
  9. 🌐 Browser sign-in (SSO)
  10. 🖥️ Browsers, Deno, Bun and Workers
  11. 🧭 API
  12. ⚠️ Errors
  13. 🛠️ Building and testing
  14. 📦 Releasing
  15. 📄 License
  16. Query progress and statement metadata

Hardcharger™

npm: @gizmodata/hardcharger version TypeScript, ESM and CJS Supported Node.js versions Browsers, Deno, Bun, Workers Chargewire protocol Built on the Chargewire JavaScript client Hardcharger Apache 2.0 license GizmoData™

Query Hardcharger™ from JavaScript and TypeScript: hardcharger:// URLs, Arrow back.


🔌 What is it?

The JavaScript/TypeScript client for Hardcharger™, GizmoData™'s DuckDB 2.0 server. Hardcharger speaks Chargewire, so this package is a thin layer on the Chargewire JavaScript client (@gizmodata/chargewire), which it depends on and re-exports, the way adbc-driver-hardcharger sits on the Chargewire ADBC driver and hardcharger-jdbc on the Chargewire JDBC driver. It adds:

  • 🏎️ hardcharger:// URLs, with Hardcharger's port 31337 as the default (443 for a GizmoData Cloud host), meaning exactly what they mean in the ADBC driver;
  • 🪪 authType: "mtls", the ADBC and JDBC drivers' name for client certificate sign-in;
  • 🏷️ Hardcharger names for the Chargewire client's classes (HardchargerError, HardchargerConnection, HardchargerErrorCode): the same objects, so instanceof works with either name.

Everything else, from Arrow results and bind parameters to split results, ingest, transactions, cancel, TLS and client certificates, is the Chargewire client's: Node, browsers, Deno, Bun and Cloudflare Workers, no native code. Its whole API comes through this package, so you never import @gizmodata/chargewire yourself. For a Chargewire server other than Hardcharger, use @gizmodata/chargewire directly.

Status: 2.5.0, with Hardcharger 2.13.0. Built on @gizmodata/chargewire 2.4.0 (chargewire-js 30ed33b, Chargewire protocol 1.0.0); tested against hardcharger-server from Hardcharger's main branch.

PackageWhat it is
@gizmodata/hardchargerthis client: hardcharger:// URLs, Hardcharger names, everything below
@gizmodata/chargewirethe generic Chargewire client it is built on, for any Chargewire server
pip install adbc-driver-hardchargerthe ADBC driver: Python, C/C++, Go, R, Rust
hardcharger-jdbcthe JDBC driver: Java, DBeaver and other JDBC tools

🚀 Quick start

Start a server (the Hardcharger README has Docker and the installers):

HARDCHARGER_ADMIN_PASSWORD=change-me hardcharger-server

Then, from examples/quickstart.mjs:

import { tableFromArrays } from "apache-arrow";
import { HardchargerError, connect } from "@gizmodata/hardcharger";

const conn = await connect({
  url: "hardcharger://localhost?tls=false",
  username: "hardcharger",
  password: "change-me",
});

// A query, with bind parameters: an Arrow Table back.
const table = await conn.query("SELECT 42 AS answer, ?::VARCHAR AS greeting", ["hello"]);
console.log(table.toArray().map((row) => row.toJSON()));

// A big result, read in several partitions at once.
let rows = 0;
for await (const batch of conn.stream("SELECT * FROM range(10000000)")) rows += batch.numRows;
console.log(`streamed ${rows} rows`);

// Bulk ingest from Arrow, then a transaction (it rolls back if the function throws).
await conn.ingest("events", tableFromArrays({ id: Int32Array.from([1, 2, 3]) }), { mode: "replace" });
await conn.transaction(async (tx) => {
  await tx.execute("DELETE FROM events WHERE id = ?", [1]);
});
console.log((await conn.query("SELECT count(*) AS n FROM events")).get(0).toJSON());

// Errors carry the server's code; an AbortSignal cancels the statement on the server.
try {
  await conn.query("SELECT count(*) FROM range(1000000000000)", undefined, { signal: AbortSignal.timeout(1000) });
} catch (err) {
  if (!(err instanceof HardchargerError)) throw err;
  console.log(`${err.code}: ${err.message}`);
}

await conn.close();
[ { answer: 42, greeting: 'hello' } ]
streamed 10000000 rows
{ n: 2n }
statement_timeout: the operation timed out (its AbortSignal fired)

import * as hardcharger from "@gizmodata/hardcharger" reads like the Python driver's from adbc_driver_hardcharger import dbapi as hardcharger: hardcharger.connect({ url, ... }). Results are Apache Arrow Tables and RecordBatches, so apache-arrow (21.2 or later) is a peer dependency: install it beside this package.

📦 Installing

npm install @gizmodata/hardcharger apache-arrow

@gizmodata/chargewire comes with it; apache-arrow (21.2 or later) is a peer dependency, so your application and the client share one copy of Arrow's classes.

🔗 URLs

URLMeaning
hardcharger://hostHTTPS to host:31337 (host:443 for GizmoData Cloud)
hardcharger://host:portHTTPS to another port
hardcharger://host?tls=falsePlain HTTP (development, loopback)
hardcharger://host:port/custom/prefixThe server mounts Chargewire under /custom/prefix
chargewire://…, https://…, http://…The Chargewire client's own spellings, as they are

hardcharger:// means exactly what Chargewire's chargewire:// means, so TLS is on unless the URL says ?tls=false (or tls=0; true and 1 keep it on). These are the URLs the ADBC driver accepts. Refused before anything is sent, each with a client_invalid_argument error that says why:

  • hardcharger+http://… and every other hardcharger+… scheme: there is deliberately one spelling for plain HTTP, ?tls=false, the same in every Hardcharger client;
  • jdbc:hardcharger://…, and a useEncryption parameter (the JDBC driver's property): the message says to drop jdbc: and use ?tls=false;
  • credentials in the URL (pass username and password), any other URL parameter, a URL without a host or with a scheme the client doesn't know.

GizmoData Cloud. A hardcharger:// URL with no port and a GizmoData Cloud host (gizmodata.com, or any name under it such as my-cluster.us-east-1.aws.gizmodata.com, in any case, a trailing dot allowed) goes to port 443, where GizmoData Cloud clusters answer, instead of 31337. Only whole labels match, so evilgizmodata.com and gizmodata.com.example.org keep 31337, and an explicit port always wins (hardcharger://my-cluster.gizmodata.com:31337 is port 31337). isGizmodataCloudHost(host) and gizmodataCloudPort (443) say the same in code.

parseUrl(url) shows the Chargewire base URL a URL stands for (hardcharger://db.example.com → https://db.example.com:31337/chargewire) and throws the errors above; schemesFor(url) is the scheme map connect hands the Chargewire client for that URL (schemes, with port 443 for a GizmoData Cloud host), which does the parsing.

⚙️ Options

connect takes the Chargewire client's options, with their defaults: one credential (username and password, token, tokenProvider, subjectToken for SSO token exchange, or authType: "client_certificate"), tls (ca, cert, key, servername, skipVerify; Node, Deno and Bun), catalog, schema, sessionOptions, retries, and the statement defaults (resultPartitions, 8 in Node and 4 in browsers; resultOrder, async, retainResult, statementTimeoutMs, queryTag, ipcCompression). The Chargewire client's README describes each one. What differs:

OptionHere
urlalso hardcharger:// URLs (above)
authTypealso "mtls", the same as "client_certificate", and "external", the same as "oauth_browser" (as in the ADBC and JDBC drivers)
schemesnot taken: the URL schemes are this package's (use @gizmodata/chargewire for schemes of your own)
loggerwarnings (a session the server lost and the client replaced, say) are printed with [hardcharger]

The current catalog and schema. catalog and schema given to connect, or set later with conn.setOptions({ catalog, schema }), are the session's current catalog and schema. Given together, in one call, they name that catalog's schema, whichever comes first. Setting catalog alone moves the session to that catalog's default schema, as SQL USE does, and a schema set before it is forgotten: a new session that replaces a lost one, and a lazy connection's first session, open in the catalog's default schema too. To be in another catalog's schema, set both together, or the schema after the catalog.

A server that is resuming. A stopped server that is starting again (a GizmoData Cloud cluster with auto-resume) answers server_resuming with a Retry-After. The client waits and sends the same request again, the sign-in included, for up to resumeTimeout seconds (default 600; 0 reports the first answer at once as server_resuming). onResuming is called before each wait with { attempt, retryAfterMs, elapsedMs, resumeTimeoutMs, detail }, so an app can say "the server is resuming" instead of looking frozen; aborting connect's or a call's signal stops the wait at once. An exception onResuming throws is ignored.

import { connect } from "@gizmodata/hardcharger";

const controller = new AbortController(); // a Cancel button calls controller.abort()
const conn = await connect({
  url: "hardcharger://db.example.com",
  username: "joe",
  password,
  resumeTimeout: 300,
  signal: controller.signal,
  onResuming: ({ attempt, elapsedMs }) =>
    console.log(`the server is resuming (attempt ${attempt}, ${Math.round(elapsedMs / 1000)} s)`),
});

🔒 Read-only connections

import { connect } from "@gizmodata/hardcharger";

const conn = await connect({
  url,
  username,
  password,
  sessionOptions: { read_only: true },
});
try {
  console.log((await conn.query("SELECT 42 AS answer")).toArray());
} finally {
  await conn.close();
}

Use your connection details for url, username and password. The client requires options.read_only: true from the server before using the session. You can also call await conn.setOptions({ read_only: true }) on an existing connection. The restriction is one-way; open a separate connection to write. Lazy connections confirm on their first operation, and replacement sessions request and confirm the restriction again. Older servers that reject or ignore the option cause an error, never a writable fallback. Connections that omit it continue to work with older servers. Read-only does not grant additional permissions or sandbox administrator-installed extension code.

🪪 Client certificate sign-in (mutual TLS)

When the server verifies client certificates and lets them sign in, the certificate is the credential: no user name or password.

HARDCHARGER_ADMIN_PASSWORD=change-me hardcharger-server --tls-cert server.pem --tls-key server-key.pem \
  --mtls-ca-cert client-ca.pem --mtls-certificate-sign-in --mtls-admin-identities [email protected]

From examples/mtls.mjs:

import { readFileSync } from "node:fs";

import { connect } from "@gizmodata/hardcharger";

const conn = await connect({
  url: "hardcharger://localhost",
  authType: "client_certificate",
  tls: {
    ca: readFileSync("server-ca.pem", "utf8"), // when the server's CA is private
    cert: readFileSync("client.pem", "utf8"),
    key: readFileSync("client-key.pem", "utf8"),
  },
});
console.log((await conn.query("SELECT HARDCHARGER_USER() AS who")).getChild("who").get(0));
await conn.close();
[email protected]

The identity is the certificate's e-mail SAN unless the server says otherwise (--mtls-identity-source); it must be one of --mtls-admin-identities or, under access control, a user of the store. The token the server issues is bound to the certificate, and every connection the client opens (the partitions of a split result, uploads) presents it. The client refuses a user name, password or token beside it, a missing tls.cert or tls.key, and a plain-HTTP URL before sending anything, and a server that doesn't offer certificate sign-in with not_implemented. The server's refusals keep their codes, each with HTTP 401: unknown_certificate_identity, certificate_required, certificate_revoked, certificate_mismatch and certificate_identity_mismatch. In a browser the certificate is the one the user picks from the browser's store, so there are no tls options; the Chargewire client's README has the details.

🌐 Browser sign-in (SSO)

When hardcharger-server signs people in with an identity provider (--oauth-client-id, --oauth-client-secret, the provider in --token-allowed-issuer), authType: "external" signs in as yourself in a browser. openUrl opens (or shows) the sign-in URL; the server completes the sign-in with the provider and the client collects Hardcharger's own access token.

import { exec } from "node:child_process";
import { connect } from "@gizmodata/hardcharger";

const conn = await connect({
  url: "hardcharger://db.example.com",
  authType: "external",
  openUrl: (url) => void exec(`open ${JSON.stringify(url)}`),
});

The steps (startBrowserSignIn, pollBrowserSignIn, browserSignIn) and the helpers for web pages that come back to themselves (beginBrowserRedirectSignIn, completeBrowserRedirectSignIn) are the Chargewire client's, taking hardcharger:// URLs here; see its README. The server's sign-in lives on its main port; there is no separate sign-in port.

A failed sign-in throws the flow's code (access_denied when the person or the provider refused, identity_provider_error, invalid_credentials for a user the server doesn't allow), with no HTTP status: decide on code. A wrong or used-up flow is flow_not_found, and a sign-in not completed within browserSignInTimeoutMs (timeoutMs for browserSignIn) is client_sign_in_timeout.

🖥️ Browsers, Deno, Bun and Workers

One build serves every runtime: this layer has no platform-specific code, and it imports @gizmodata/chargewire by name, so your bundler or runtime picks that package's own build through its export conditions (node for Node, Deno and Bun; default for browsers and edge runtimes). The browser tests bundle this package with esbuild for the browser, check that the bundle holds the Chargewire client's browser build, and run it in Chromium and WebKit against a server that allows the page's origin (hardcharger-server --cors-origins https://app.example.com), with the same calls as in Node.

🧭 API

ExportWhat it is
connect(options)a Connection (HardchargerConnection): query, stream, execute, prepare, ingest, metadata, transaction, close, ...
HardchargerError (= ChargewireError)every error the client raises: code, status, sqlstate, detail, requestId, ...
HardchargerErrorCode (= ErrorCode)the codes, e.g. HardchargerErrorCode.sqlError is "sql_error"
parseUrl(url), schemes, schemesFor(url), scheme, defaultPort, gizmodataCloudPort, isGizmodataCloudHost(host)the URL translation above; "hardcharger", 31337, 443 and the GizmoData Cloud host test
versionthis package's version
Connection, PreparedStatement, ResultStream, Metadata, Capability, ChargewireError, ErrorCodethe Chargewire client's, under their own names
types: ConnectOptions, CallOptions, StatementOptions, IngestOptions, Parameters, TlsOptions, ColumnInfo, ProblemDocument, ...the Chargewire client's types

The Chargewire client's API table describes every method, and How it behaves the retries, split results, cancel and lost sessions.

⚠️ Errors

Every error is a HardchargerError with a stable code: the server's (sql_error, invalid_credentials, statement_cancelled, statement_timeout, permission_denied, ...) or one of the client's, which begin with client_ (client_invalid_argument before anything is sent, client_transport_error with no HTTP answer, client_http_error for an error answer without a problem document, client_connection_closed, ...), with status, sqlstate, detail, requestId, statementId, reason and cancelReason beside it. Decide on code, never on the message. A statement that fails at run time is execution_error (422); one cancelled or timed out before its submit is answered is statement_cancelled or statement_timeout (409, with statementId and cancelReason). HardchargerError.is(err, "sql_error") checks the class and the code at once. The live tests assert each code this client meets: sql_error (400, with the SQLSTATE), invalid_credentials (401), statement_cancelled, statement_timeout, unknown_certificate_identity (401), not_implemented, execution_error (422), client_transport_error, client_invalid_argument, client_connection_closed, and session_ended with reason idle_in_transaction.

A session the server ended because its transaction sat idle past the server's idle_in_transaction_session_timeout (Hardcharger 2.7.0 and later) is session_ended with reason: "idle_in_transaction": the transaction was rolled back, and the statement that found it ended fails with that error and is never run again, whether the transaction began with setAutocommit(false), transaction() or BEGIN in SQL. The connection carries on: the next statement runs on a new session, without a new sign-in. A session the server lost (session_not_found: a restart, an idle eviction) is replaced too, and the request that found it runs again on the new session only when no transaction can have been open in the old one: autocommit on, and no SQL that can begin a transaction (BEGIN, START TRANSACTION, anything naming autocommit) ran there, and no statement whose first word is USE, SET, RESET or PRAGMA did (the new session has the connection's options, not what SQL set; it opens in the catalog and schema those options left the old one in). Otherwise it fails with session_not_found, and the next call runs on the new session. Other session_ended reasons (killed, credentials_changed, principal_dropped, token_revoked, and token_expired when the token can't be renewed) are not cured by a new session: they are the error, and a new connection is the way on.

The class is the Chargewire client's, under a Hardcharger name (its name stays "ChargewireError"): one class, so errors from anywhere in the client are instanceof both.

🛠️ Building and testing

Node 22.19 or later. For development and CI, @gizmodata/chargewire is built from gizmodata/chargewire-js at the commit pinned in scripts/chargewire-js.commit and packed to .chargewire/, where package-lock.json finds it, so the tests run against that exact client. package.json, and so the published package, names the npm package and its range (^2.4.0); the tarball is a stand-in for development and CI only.

npm run chargewire      # clone chargewire-js, build and pack the pinned commit
npm ci
npm run lint            # eslint (typed rules), prettier, and the lock's shape (scripts/check-lock.mjs)
npm run typecheck       # src, tests and configs
npm test                # unit tests (no server)
npm run build           # dist/: ESM, CJS and types
npm run check:package   # the packed package: this layer only, a few KB, publint, are-the-types-wrong

HARDCHARGER_JS_CHARGEWIRE_REPO=/path/to/chargewire-js npm run chargewire builds from a local checkout. TypeScript stays on 6.0: typescript-eslint and the declaration build need the TypeScript compiler API, which TypeScript 7 doesn't ship.

The live suites start hardcharger-server themselves, on free loopback ports (and one on 31337, to prove a URL without a port reaches it), with a fresh administrator password that contains : and @, an empty home directory (DuckDB's secrets directory included), and only PATH, HOME, TMPDIR and the password in its environment. Without the binary they fail; they never skip, and a run in which no test reached a server fails too. The live suite also checks a Hardcharger released before the protocol was renamed to Chargewire (the ghcr.io/gizmodata/hardcharger:2.2.0 image, already running, plain HTTP) when HARDCHARGER_JS_TEST_OLD_SERVER names it (host:port, with HARDCHARGER_JS_TEST_OLD_SERVER_PASSWORD); CI starts one, and there those tests fail without it.

export HARDCHARGER_JS_TEST_SERVER_BINARY=/path/to/hardcharger-server
npm run test:live       # Node (vitest): sign-in, queries, parameters, split results, ingest,
                        # transactions, cancel, certificate sign-in, error codes
npm run build && npx playwright install chromium webkit && npm run test:browser
npm run build && npm run test:examples   # this README's examples, on port 31337

Negative tests assert the error code, each beside a positive twin. CI runs everything against the image of Hardcharger's main branch (ghcr.io/gizmodata/hardcharger:main), pulled with the workflow's GITHUB_TOKEN; while the image is private the package must grant this repository read access (package settings, "Manage Actions access"), or the live jobs fail. CI clones chargewire-js anonymously over https.

📦 Releasing

Releases follow semantic versioning and CHANGELOG.md: update both and package.json's version, then merge a pull request after its required checks pass. Fetch origin/main, verify its tree matches the tested commit, and tag that exact landed commit vX.Y.Z. Push the release tag without moving it afterward. release.yml runs the full CI on the tagged commit, then makes a GitHub Release with the package tarball and the CHANGELOG section, then publishes to npm (public) with trusted publishing (OIDC, no stored token) when the repository variable NPM_PUBLISH_ENABLED is true. The npm job first checks that @gizmodata/chargewire is on npm in the range package.json names; on npmjs.com, @gizmodata/hardcharger's trusted publisher is this repository's release.yml (environment npm). npm publish from a laptop refuses to run.

📄 License

Apache License 2.0.


GizmoData™
Built by GizmoData™
Hardcharger™ and GizmoData™ are trademarks of GizmoData LLC.

Query progress and statement metadata

onProgress and ResultStream.statement() are available directly through this package:

const rows = conn.stream("SELECT * FROM large_table", undefined, {
  onProgress: (statement) => console.log(statement.state, statement.progress?.fraction),
});
const metadata = await rows.statement();
for await (const batch of rows) {
  // Consume rows as they arrive.
}

These additions preserve the existing APIs and Chargewire protocol version. Progress is optional; servers without estimates report status without a percentage. A statement snapshot may precede completion and does not rerun SQL or retain the result.

版本与发布记录

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

版本发布日期距今
2.5.0latest2026/11/151 天前
2.4.52026/11/142 天前
2.4.42026/11/088 天前
2.4.32026/11/088 天前
2.4.22026/11/079 天前
2.4.12026/11/079 天前

关于 @gizmodata/hardcharger 的常见问题

@gizmodata/hardcharger 是什么?

JavaScript/TypeScript client for Hardcharger™, GizmoData™'s DuckDB 2.0 server: hardcharger:// URLs on the Chargewire client, for Node, browsers, Deno, Bun and edge runtimes.

如何安装 @gizmodata/hardcharger?

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

@gizmodata/hardcharger 支持 TypeScript 吗?

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

@gizmodata/hardcharger 支持 ESM 还是 CommonJS?

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

@gizmodata/hardcharger 需要什么版本的 Node.js?

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

@gizmodata/hardcharger 可以商用吗?

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

@gizmodata/hardcharger 的下载量有多少?

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

@gizmodata/hardcharger 还在维护吗?

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