bởi Kaisa

A complete gRPC implementation for Node.js featuring a pure JavaScript client/server library, protobuf loader, health checks, reflection, xDS support, and rich example patterns for streaming, TLS, retries, and load balancing.
This block provides the full source of @grpc/grpc-js, a pure-JavaScript implementation of gRPC for Node.js with no native C++ addon. It covers unary, streaming, bidirectional RPC, metadata, credentials, load balancing, retries, interceptors, and a channelz admin service. Typical buyers are backend engineers embedding a gRPC client or server into an existing Node.js/TypeScript service.
index.ts — Public entry point; re-exports every symbol the library exposesserver.ts — Server class: bind ports, register service handlers, start/stopclient.ts — Client base class, CallOptions, UnaryCallback, interceptor typesmake-client.ts — makeClientConstructor, loadPackageDefinition, ServiceDefinitionchannel.ts — Channel, ChannelImplementation: manages a gRPC connectioninternal-channel.ts — Internal channel logic (used by Client)call-credentials.ts — CallCredentials, OAuth2 helperschannel-credentials.ts — ChannelCredentials, TLS and insecure variantsmetadata.ts — Metadata: request/response header containerserver-call.ts — Handler types: ServerUnaryCall, ServerReadableStream, etc.server-credentials.ts — ServerCredentials: TLS and insecure server credsserver-interceptors.ts — ServerInterceptor, listener interfacescall.ts — Client-side call stream types: ClientUnaryCall, ClientReadableStream, etc.call-interface.ts — StatusObject, MessageContext, shared call interfacesresolver.ts — Pluggable name resolver APIresolver-dns.ts / resolver-ip.ts / resolver-uds.ts — Built-in resolversload-balancer.ts — Load-balancer plugin APIload-balancer-round-robin.ts / — Built-in policiesKhởi chạy sandbox cách ly và chạy phía máy chủ — không cần cài đặt cục bộ.
Tetrees AI Review cho phiên bản này
This TypeScript cli / script 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
Quy trình avcp-2026-08-04.1 · SHA-256 a64fdc12f93b2aee…
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.
Đã đánh giá 4 thg 8, 2026
Đưa sản phẩm này thẳng vào AI IDE, trình tạo web hoặc cloud IDE của bạn.
Kết nối Tetrees với AI IDE tương thích để liệt kê sản phẩm bạn sở hữu và nhận ZIP đã xác minh mà không cấp quyền tải lên của người bán.
Chưa có đánh giá.
Sign in to join the discussion
Loading discussion…
load-balancer-pick-first.tsload-balancer-weighted-round-robin.ts / load-balancer-outlier-detection.ts — Advanced LBretrying-call.ts — Retry logic, RetryThrottlerservice-config.ts — Parses gRPC service config JSONchannelz.ts — Channelz admin introspection serviceadmin.ts — registerAdminService helperlogging.ts — Internal trace/log utilitiesconstants.ts — Status, LogVerbosity, Propagate enumsconnectivity-state.ts — ConnectivityState enumcompression-filter.ts / compression-algorithms.ts — Message compressiondeadline.ts — Deadline type and helperstransport.ts — HTTP/2 transport layer, CallEventTrackersubchannel.ts / subchannel-pool.ts / subchannel-address.ts — Subchannel managementtls-helpers.ts — TLS certificate utilitiesuri-parser.ts — GrpcUri parsingstatus-builder.ts — StatusBuilder fluent helperstream-decoder.ts — gRPC message framingfilter.ts / filter-stack.ts — Client interceptor filter pipelineclient-interceptors.ts — Client-side interceptor types and helpershttp_proxy.ts — HTTP CONNECT proxy supportenvironment.ts — Environment variable helperserror.ts — getErrorMessage utilitybackoff-timeout.ts — Exponential backoff timerobject-stream.ts — Typed object stream helpersevents.ts — Shared event helpersorca.ts — ORCA per-request load reportingauth-context.ts — AuthContext per-call auth metadatacertificate-provider.ts — Dynamic certificate provider APIchannel-options.ts — ChannelOptions type definitionsduration.ts — Protobuf Duration helperscontrol-plane-status.ts — xDS control-plane status codescall-number.ts — Monotonic call identifierpriority-queue.ts — Internal priority queueresolving-call.ts / resolving-load-balancer.ts — Resolution-integrated call pathload-balancing-call.ts / load-balancer-child-handler.ts — LB call wrapperssingle-subchannel-channel.ts — Single-subchannel channel wrapperexperimental.ts — Experimental/unstable exportsgenerated/ — Protobuf-generated types for channelz, ORCA, xDSnpm install @js-sdsl/ordered-map
npm install @grpc/proto-loader
No native build steps, no pod install, no NDK configuration required. Runs on any Node.js ≥ 12 platform.
source/ into your project, e.g. at src/grpc-js/.tsconfig.json to include the new source tree and enable needed options:{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true,
"strict": true,
"paths": {
"@grpc/grpc-js": ["./src/grpc-js/index"]
}
},
"include": ["src"]
}
import * as grpc from '@grpc/grpc-js';
| Variable | Effect |
|---|---|
GRPC_VERBOSITY | Log level: DEBUG, INFO, ERROR |
GRPC_TRACE | Comma-separated tracer names to enable |
GRPC_DEFAULT_SSL_ROOTS_FILE_PATH | Path to custom CA bundle |
http_proxy / https_proxy | HTTP CONNECT proxy for outbound connections |
class Server {
constructor(options?: ServerOptions);
addService(service: ServiceDefinition, implementation: UntypedServiceImplementation): void;
bindAsync(port: string, creds: ServerCredentials, cb: (err: Error | null, port: number) => void): void;
start(): void;
forceShutdown(): void;
tryShutdown(cb: (err?: Error) => void): void;
}
Use Server to host gRPC services. Call addService with a generated service definition and your handler object, then bindAsync with a ServerCredentials instance, then start().
function makeClientConstructor(
methods: ServiceDefinition,
serviceName: string,
classOptions?: {}
): typeof Client;
Generates a typed client class from a ServiceDefinition (usually produced by @grpc/proto-loader). The returned constructor accepts (address, credentials, options?). Use this when you have a proto-loaded service object but are not using the loadPackageDefinition convenience wrapper.
class Metadata {
constructor(options?: MetadataOptions);
add(key: string, value: MetadataValue): void;
set(key: string, value: MetadataValue): void;
get(key: string): MetadataValue[];
remove(key: string): void;
clone(): Metadata;
merge(other: Metadata): void;
toJSON(): { [key: string]: MetadataValue[] };
}
Metadata carries gRPC headers for both clients (outgoing call metadata) and servers (initial/trailing metadata). Pass a Metadata instance to any call method or send it from a server handler via call.sendMetadata(meta).
class ChannelCredentials {
static createInsecure(): ChannelCredentials;
static createSsl(
rootCerts?: Buffer | null,
privateKey?: Buffer | null,
certChain?: Buffer | null,
verifyOptions?: VerifyOptions
): ChannelCredentials;
}
Required when creating a client channel. Use createInsecure() for local/dev connections; use createSsl() for production with mutual TLS.
class StatusBuilder {
withCode(statusCode: Status): this;
withDetails(details: string): this;
withMetadata(metadata: Metadata): this;
build(): Partial<StatusObject>;
}
Fluent builder for composing StatusObject values in server handlers or test assertions.
A Node.js client calling a remote Greeter.SayHello unary method using a proto-loader-generated definition.
import * as grpc from '@grpc/grpc-js';
import * as protoLoader from '@grpc/proto-loader';
import path from 'path';
const packageDef = protoLoader.loadSync(
path.join(__dirname, 'protos/helloworld.proto'),
{ keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }
);
const proto = grpc.loadPackageDefinition(packageDef) as any;
const client = new proto.helloworld.Greeter(
'localhost:50051',
grpc.ChannelCredentials.createInsecure()
);
const meta = new grpc.Metadata();
meta.add('x-request-id', 'abc-123');
client.sayHello({ name: 'World' }, meta, (err: grpc.ServiceError | null, response: any) => {
if (err) {
console.error('RPC error:', err.code, err.message);
return;
}
console.log('Response:', response.message);
});
Hosting a Greeter service with a simple unary handler.
import * as grpc from '@grpc/grpc-js';
import * as protoLoader from '@grpc/proto-loader';
import path from 'path';
const packageDef = protoLoader.loadSync(
path.join(__dirname, 'protos/helloworld.proto')
);
const proto = grpc.loadPackageDefinition(packageDef) as any;
function sayHello(
call: grpc.ServerUnaryCall<{ name: string }, { message: string }>,
callback: grpc.sendUnaryData<{ message: string }>
) {
callback(null, { message: `Hello ${call.request.name}` });
}
const server = new grpc.Server();
server.addService(proto.helloworld.Greeter.service, { sayHello });
server.bindAsync(
'0.0.0.0:50051',
grpc.ServerCredentials.createInsecure(),
(err, port) => {
if (err) throw err;
console.log(`Listening on ${port}`);
server.start();
}
);
Production setup with TLS certificates on both sides.
import * as grpc from '@grpc/grpc-js';
import * as fs from 'fs';
// Server
const serverCreds = grpc.ServerCredentials.createSsl(
fs.readFileSync('certs/ca.crt'),
[{ private_key: fs.readFileSync('certs/server.key'), cert_chain: fs.readFileSync('certs/server.crt') }],
true // checkClientCertificate
);
const server = new grpc.Server();
// ... addService ...
server.bindAsync('0.0.0.0:50051', serverCreds, (err, port) => {
if (err) throw err;
server.start();
});
// Client
const clientCreds = grpc.ChannelCredentials.createSsl(
fs.readFileSync('certs/ca.crt'),
fs.readFileSync('certs/client.key'),
fs.readFileSync('certs/client.crt')
);
// const client = new MyServiceClient('hostname:50051', clientCreds);
import * as grpc from '@grpc/grpc-js';
const callCreds = grpc.CallCredentials.createFromMetadataGenerator(
(params, callback) => {
const meta = new grpc.Metadata();
meta.add('authorization', `Bearer my-token`);
callback(null, meta);
}
);
const channelCreds = grpc.ChannelCredentials.createSsl();
const combinedCreds = channelCreds.compose(callCreds);
// const client = new MyServiceClient('api.example.com:443', combinedCreds);
index.ts — Aggregates and re-exports the entire public surface of the library.server.ts — Core Server class: HTTP/2 binding, service registry, graceful shutdown.client.ts — Client base class with call dispatch, options, and interceptor support.make-client.ts — Factory utilities that turn a ServiceDefinition into a Client subclass.channel.ts — Channel interface and ChannelImplementation: connection lifecycle and state.internal-channel.ts — Internal channel plumbing used by Client and load balancers.call-credentials.ts — CallCredentials factory (metadata generators, OAuth2, composition).channel-credentials.ts — ChannelCredentials for insecure and TLS channel security.metadata.ts — Metadata container for gRPC headers; handles binary (-bin) keys automatically.server-call.ts — Typed server-side call objects and handler type aliases.server-credentials.ts — ServerCredentials for insecure and TLS listener security.server-interceptors.ts — Server interceptor interfaces and listener chain types.call.ts — Client-side stream types returned by stub methods.call-interface.ts — Shared interfaces: StatusObject, WriteObject, InterceptingListener.resolver.ts — Resolver plugin registration API and ResolverListener.resolver-dns.ts — DNS SRV/A/AAAA resolver implementation.resolver-ip.ts — Literal IP address resolver.resolver-uds.ts — Unix domain socket resolver.load-balancer.ts — Load-balancer plugin registration and LoadBalancer interface.load-balancer-round-robin.ts — Round-robin policy implementation.load-balancer-pick-first.ts — Pick-first policy implementation.load-balancer-weighted-round-robin.ts — Weight-aware round-robin policy.load-balancer-outlier-detection.ts — Outlier detection wrapping policy.load-balancer-child-handler.ts — Utility for LB policies that wrap another policy.retrying-call.ts — Hedging and retry call wrapper with RetryThrottler.resolving-call.ts — Call layer that waits for name resolution before proceeding.resolving-load-balancer.ts — Combines resolver and LB into a single entity.load-balancing-call.ts — Call layer sitting between retries and the subchannel picker.service-config.ts — Parses and validates gRPC service config (retry, LB, method config).channelz.ts — Full channelz gRPC service implementation for runtime introspection.admin.ts — registerAdminService to add channelz/CSDS to an existing server.subchannel.ts — Subchannel lifecycle: connect, disconnect, HTTP/2 session.subchannel-pool.ts — Shared pool that de-duplicates subchannels by address.subchannel-address.ts — SubchannelAddress type plus TCP/UDS helpers.subchannel-call.ts — Single HTTP/2 stream call executing on a subchannel.subchannel-interface.ts — SubchannelInterface type used across LB layers.transport.ts — HTTP/2 transport abstraction, CallEventTracker.tls-helpers.ts — Reads default root CA certs, builds SecureContext.uri-parser.ts — Parses gRPC target strings into GrpcUri.status-builder.ts — Fluent StatusBuilder for constructing status objects.stream-decoder.ts — Decodes gRPC length-prefixed message frames.filter.ts / filter-stack.ts — Composable client-side interceptor filter chain.client-interceptors.ts — Client interceptor call wrapper and types.logging.ts — trace() and log() with verbosity gating.constants.ts — Status (gRPC status codes), LogVerbosity, Propagate enums.connectivity-state.ts — ConnectivityState enum (IDLE, CONNECTING, READY, …).compression-filter.ts / compression-algorithms.ts — gzip/deflate/identity compression.deadline.ts — Deadline type (Date | number) and formatDateDifference.backoff-timeout.ts — Exponential-backoff timer with jitter.http_proxy.ts — Detects and tunnels through HTTP CONNECT proxies.environment.ts — Reads GRPC_* environment variables.error.ts — getErrorMessage safe extraction from unknown errors.call-number.ts — Monotonically increasing call ID generator.object-stream.ts — Typed duplex/readable/writable stream helpers.events.ts — Internal event name constants.orca.ts — ORCA per-request load reporting via PerRequestMetricRecorder.auth-context.ts — AuthContext exposing per-connection TLS metadata.certificate-provider.ts — Plugin interface for dynamic certificate rotation.channel-options.ts — ChannelOptions keys and types (keepalive, max message sizes, etc.).duration.ts — Protobuf Duration conversions.control-plane-status.ts — xDS control plane NACK status helpers.priority-queue.ts — Min-heap priority queue used by LB subsystem.single-subchannel-channel.ts — A channel that always uses one specific subchannel.experimental.ts — Unstable APIs gated behind an explicit import.generated/ — Auto-generated TypeScript protobuf types for channelz, ORCA, and xDS protos.GRPC_VERBOSITY not set in production — the library defaults to no output; set GRPC_VERBOSITY=ERROR to surface real errors without trace noise.@js-sdsl/ordered-map missing — channelz.ts imports it directly; if your bundler tree-shakes it out, add it as an explicit dependency and verify it appears in node_modules.loadPackageDefinition expects objects produced by @grpc/proto-loader ≥ 0.6; older versions produce incompatible shapes.bindAsync called but start() forgotten — bindAsync only registers the port; the server does not accept connections until start() is explicitly called afterward.-bin must have Buffer values, not strings; passing a string throws at runtime inside Metadata.add.module: commonjs); in an ESM project, use "type": "commonjs" in the source subtree's package.json or configure ts-node with esm: false.I have the source of @grpc/grpc-js at src/grpc-js/ (entry point: src/grpc-js/index.ts)
and a USAGE.md file describing the full API.
Please integrate gRPC into my existing Node.js/TypeScript project by:
1. Reading USAGE.md and src/grpc-js/index.ts to understand the real exports.
2. Installing the required peer dependencies listed in USAGE.md § "Required dependencies".
3. Adding a path alias in tsconfig.json: "@grpc/grpc-js" -> ["./src/grpc-js/index"].
4. Creating src/grpc/server.ts that instantiates grpc.Server, registers my
[SERVICE_NAME] service, binds on port [PORT] with insecure credentials, and starts.
5. Creating src/grpc/client.ts that builds a client stub for [SERVICE_NAME] using
makeClientConstructor or loadPackageDefinition and ChannelCredentials.createInsecure().
6. Adding Metadata headers [HEADERS] to every outgoing call via CallCredentials.createFromMetadataGenerator.
7. Wiring the server into my existing Express app startup (src/app.ts) so both
HTTP and gRPC start together.
Only use symbols present in src/grpc-js/index.ts or explicitly documented in USAGE.md.
Do not invent API surface. Show each file in full.
Licensed under the Apache License 2.0 (see source/LICENSE if present, or the license header at the top of each source file). Upstream package: @grpc/grpc-js, part of the grpc-node monorepo maintained by the gRPC authors.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
Hướng dẫn cài đặt đầy đủ và prompt tích hợp sẽ mở khóa sau khi mua.
Automation, Utilities & Developer Tools
Miễn phí