由 jin 出售

Official Node.js/TypeScript client library for Gel (formerly EdgeDB), featuring a type-safe query builder, code generators, auth integrations for Next.js, Remix, Express, and SvelteKit, plus AI/RAG support.
This block is the core source of the official Gel (formerly EdgeDB) JavaScript/TypeScript client library. It provides connection management, query execution, codec serialization/deserialization, error handling, and schema reflection for communicating with a Gel database server. The typical buyer is a backend TypeScript developer embedding Gel database access directly into a Node.js service or framework without depending on the published npm package.
baseClient.ts - ClientConnectionHolder and BaseClientPool: pooled connection management and query dispatchbaseConn.ts - BaseRawConnection: low-level binary protocol implementation, capability flags, protocol version constantsbrowserClient.ts - Browser-specific client subclass wiring fetch-based transportbrowserCrypto.ts - Web Crypto API adapter for SCRAM authentication in browserscodecTypeRegistry.ts - Top-level codec type registry initializationconUtils.ts - Connection string parsing, DSN resolution, TLS security config, Address typeconUtils.server.ts - Node.js-only connection resolution (file-based credentials, project discovery)credentials.ts - Reading and validating .gel/credentials filescryptoUtils.ts - Shared crypto helpers (HMAC, SHA-256)fetchConn.ts - HTTP/fetch-based connection transport for edge runtimeshttpScram.ts - SCRAM-SHA-256 authentication over HTTPifaces.ts - Core interfaces: Executor, QueryArgs, Cardinality, OutputFormat, Language, ProtocolVersionindex.browser.ts - Browser entry point re-exportsindex.node.ts - Node.js entry point re-exportsindex.shared.ts - Shared entry point re-exportsnodeClient.ts - Node.js TCP/TLS client subclassnodeCrypto.ts - Node.js crypto module adapteroptions.ts - Options, IsolationLevel, retry/transaction/warning configuration typesplatform.ts - Runtime platform detection utilities启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 330ccfa80373f94d…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
rawConn.ts - Raw connection wrapper used by the poolretry.ts - retryingConnect and ConnectWithTimeout retry logicscram.ts - SCRAM-SHA-256 authentication implementationsystemUtils.ts - OS/environment utility helperstransaction.ts - Transaction and TransactionImpl classestypeutil.ts - TypeScript utility typesutils.ts - Miscellaneous helpers (versionGreaterThan, sleep, etc.)codecs/ - Binary codec implementations for every Gel scalar and composite typedatatypes/ - JavaScript representations of Gel types (DateTime, Range, Memory, pgvector, PostGIS)errors/ - Full error class hierarchy, error tags, and server-error resolutionprimitives/ - Low-level building blocks: ReadBuffer/WriteBuffer, LRU cache, event, queues, CRCreflection/ - Schema introspection queries, query analysis, reserved keywords, enums# No external runtime dependencies are declared in package.json.
# The source is self-contained. Node.js built-ins (net, tls, crypto, fs)
# are used via the nodeCrypto.ts / conUtils.server.ts platform split.
npm install typescript
If targeting Node.js with TLS connections, ensure Node.js 18+ is installed (native tls module required). No native addons, no pod install, no Android linking.
Copy the source/ directory into your project, for example at src/gel/.
Configure tsconfig.json:
{
"compilerOptions": {
"target": "ES2020",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"strict": true,
"esModuleInterop": true,
"paths": {
"gel": ["./src/gel/index.node.ts"],
"gel/*": ["./src/gel/*"]
}
}
}
# DSN form
export GEL_DSN="gel://user:password@localhost:5656/mydb"
# Or individual variables
export GEL_HOST=localhost
export GEL_PORT=5656
export GEL_USER=myuser
export GEL_PASSWORD=secret
export GEL_DATABASE=mydb
export GEL_TLS_SECURITY=strict # insecure | no_host_verification | strict | default
./src/gel/index.node.ts (or via the path alias gel).Capabilities (enum, baseConn.ts)export enum Capabilities {
NONE = 0,
// further members defined in baseConn.ts
}
Used to declare which server capabilities a query requires (e.g. DDL, persistent, transaction). Pass when constructing low-level query options to control what the server is permitted to execute.
TlsSecurity / validTlsSecurityValues (conUtils.ts)export type TlsSecurity = "insecure" | "no_host_verification" | "strict" | "default";
export const validTlsSecurityValues: readonly TlsSecurity[];
export function isValidTlsSecurityValue(candidate: unknown): candidate is TlsSecurity;
Use isValidTlsSecurityValue to validate user-supplied TLS configuration before passing it into connection resolution. Prefer "strict" in production; use "insecure" only in local dev with self-signed certificates.
Options / IsolationLevel (options.ts)export class Options { /* retry, transaction, warning config */ }
export enum IsolationLevel { /* Serializable, ... */ }
Options is the immutable configuration object threaded through every query and transaction. Create a customized instance to set retry rules, isolation level, or a warning handler, then pass it to the client via withRetryOptions / withTransactionOptions.
Transaction (transaction.ts)export class Transaction { /* implements Executor */ }
Represents an active database transaction. Obtained inside the callback passed to client.transaction(). Provides the same query methods as the top-level client but scoped to the transaction.
GelError (errors/base.ts) and the full error hierarchy (errors/index.ts)export class GelError extends Error { get code(): number; }
export class QueryError extends GelError { }
export class ConstraintViolationError extends QueryError { }
// ... many more
Catch GelError at the top level or narrow to specific subclasses for domain-level error handling.
Import the Node.js client, create a pool, run a query, and close cleanly.
import { createClient } from "./src/gel/index.node";
async function main() {
const client = createClient(); // reads GEL_DSN or GEL_HOST/PORT/etc.
const result = await client.query<{ id: string; name: string }>(
"SELECT Person { id, name } FILTER .name = <str>$name",
{ name: "Alice" }
);
console.log(result); // Array<{ id: string; name: string }>
await client.close();
}
main().catch(console.error);
Use client.transaction() for operations that must be atomic. The library automatically retries on serialization conflicts according to the configured RetryOptions.
import { createClient } from "./src/gel/index.node";
import { IsolationLevel } from "./src/gel/options";
const client = createClient().withTransactionOptions({
isolation: IsolationLevel.Serializable,
readonly: false,
deferrable: false,
});
await client.transaction(async (tx) => {
const [account] = await tx.query<{ balance: number }>(
"SELECT Account { balance } FILTER .id = <uuid>$id",
{ id: "00000000-0000-0000-0000-000000000001" }
);
if (account.balance < 100) throw new Error("Insufficient funds");
await tx.execute(
"UPDATE Account FILTER .id = <uuid>$id SET { balance := .balance - 100 }",
{ id: "00000000-0000-0000-0000-000000000001" }
);
});
Narrow caught errors to specific Gel error classes to handle constraint violations distinctly from connection failures.
import { createClient } from "./src/gel/index.node";
import { ConstraintViolationError, GelError } from "./src/gel/errors";
const client = createClient();
async function createUser(email: string) {
try {
await client.querySingle(
"INSERT User { email := <str>$email }",
{ email }
);
} catch (err) {
if (err instanceof ConstraintViolationError) {
console.error("Email already registered:", email);
return null;
}
if (err instanceof GelError) {
console.error("Database error code", err.code.toString(16), err.message);
}
throw err;
}
}
import { isValidTlsSecurityValue } from "./src/gel/conUtils";
const tlsSecurity = process.env.GEL_TLS_SECURITY;
if (tlsSecurity !== undefined && !isValidTlsSecurityValue(tlsSecurity)) {
throw new Error(
`Invalid GEL_TLS_SECURITY value: "${tlsSecurity}". ` +
`Must be one of: insecure, no_host_verification, strict, default`
);
}
baseClient.ts - Implements ClientConnectionHolder and BaseClientPool; manages connection lifecycle, pooling, and routes queries to raw connections.baseConn.ts - Binary protocol state machine; encodes/decodes messages, handles authentication handshake, exports Capabilities enum and protocol version constants.browserClient.ts - Thin subclass wiring the fetch-based transport for use in browser/edge environments.browserCrypto.ts - Adapts the Web Crypto API to the interface expected by SCRAM authentication.codecTypeRegistry.ts - Initializes and exports the global codec registry with all built-in type codecs registered.conUtils.ts - Parses DSNs, validates TLS settings, merges environment variables, exports Address, TlsSecurity, and config resolution logic.conUtils.server.ts - Node.js-only: discovers project credentials files and resolves connection from the filesystem.credentials.ts - Reads and validates .gel/credentials/*.json credential files.cryptoUtils.ts - Low-level HMAC/SHA-256 helpers shared by SCRAM implementations.fetchConn.ts - HTTP transport connection, used by the browser/edge client.httpScram.ts - SCRAM-SHA-256 authentication flow over HTTP for the fetch-based transport.ifaces.ts - Canonical interface and enum definitions (Executor, Cardinality, OutputFormat, Language, QueryArgs).index.browser.ts / index.node.ts / index.shared.ts - Platform-specific and shared entry points; control what is re-exported to consumers.nodeClient.ts - Node.js TCP/TLS client; constructs native socket connections.nodeCrypto.ts - Wraps Node.js crypto module for SCRAM.options.ts - Options (immutable config), IsolationLevel, retry/transaction/warning handler types.platform.ts - Detects runtime environment (Node.js vs. browser vs. edge).rawConn.ts - Wraps baseConn for pool use; manages checked-out connection state.retry.ts - retryingConnect helper and ConnectWithTimeout for connection establishment with backoff.scram.ts - Full SCRAM-SHA-256 authentication implementation.systemUtils.ts - Environment variable reading, home directory lookup.transaction.ts - Transaction (public API) and TransactionImpl (internal); wraps a connection holder in transaction semantics.typeutil.ts - TypeScript conditional/utility types used internally and by codegen.utils.ts - versionGreaterThan, versionGreaterThanOrEqual, sleep, and other small helpers.codecs/ - One file per Gel scalar/composite type (array, bool, bytes, datetime, enum, JSON, range, tuple, UUID, pgvector, PostGIS, etc.); each exports a codec class implementing ICodec.datatypes/ - JavaScript class representations of Gel types returned from the database (e.g. LocalDate, Duration, Range, Memory, Vector).errors/ - Auto-generated error class hierarchy rooted at GelError; errors/resolve.ts maps server error codes to classes.primitives/ - ReadBuffer/WriteBuffer for binary framing, LRU cache, async event, LIFO/FIFO queues, CRC-HQX.reflection/ - Schema introspection query runners, analyzeQuery, reserved keyword lists, and enums used by codegen.GEL_DSN or host env vars at runtime: createClient() will throw InterfaceError immediately; set at least GEL_DSN or GEL_HOST + GEL_PORT + GEL_USER + GEL_PASSWORD + GEL_DATABASE.export * and named exports throughout; if bundling with CommonJS, set "module": "CommonJS" in tsconfig or use a bundler transform - do not mix require() and import for the same module.index.node.ts in a browser bundle or vice versa; use index.browser.ts for fetch-based environments, index.node.ts for Node.js.GEL_TLS_SECURITY=insecure or no_host_verification; leaving it as strict (default) will reject self-signed development server certs.moduleResolution: Must be "NodeNext" or "Bundler" - older "node" resolution will fail to resolve .ts extension imports used internally.PROTO_VER = [3, 0], PROTO_VER_MIN = [0, 9]; connecting to a Gel server older than 0.9 will throw UnsupportedProtocolVersionError.I have the Gel JS client library core source at `src/gel/` in my project.
The integration guide is at `USAGE.md`.
The upstream package is `edgedb-js` (published as `gel` on npm).
Please help me integrate this source into my Node.js/TypeScript project step by step:
1. Read `USAGE.md` fully before writing any code.
2. Set up the tsconfig `paths` alias so `gel` resolves to `src/gel/index.node.ts`.
3. Create a `src/db.ts` module that initializes a single shared client instance,
reads connection config from environment variables, and exports the client.
4. Add query helper functions for the following operations: [DESCRIBE YOUR USE CASES].
5. Add a `src/db.transaction.ts` module demonstrating a multi-step transaction
with automatic retry using `client.transaction()`.
6. Handle `GelError` and its subclasses (especially `ConstraintViolationError`)
at the service layer with appropriate HTTP status codes.
7. Do not install the npm `gel` package - use only the source in `src/gel/`.
8. Show me the complete file contents for every file you create or modify.
The source is licensed under the Apache License 2.0. See the LICENSE file in the upstream repository or source/ if present.
Upstream repository: geldata/gel-js
Upstream npm package: gel
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费