grpc-descriptor-reflection 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 MasonryStack
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # grpc-descriptor-reflection
2
+
3
+ A gRPC server reflection service for [`@grpc/grpc-js`](https://www.npmjs.com/package/@grpc/grpc-js) that serves **raw `FileDescriptorProto` bytes** from a pre-built descriptor set, preserving all extensions and custom options byte-for-byte.
4
+
5
+ ## Why?
6
+
7
+ Existing reflection libraries for Node.js gRPC lose extension fields during serialization:
8
+
9
+ - **`@grpc/reflection`** decodes descriptors through protobufjs and re-encodes them. protobufjs silently drops all extension fields (`google.api.http`, `openapiv2_operation`, custom options, etc.) because they are not declared fields on the standard option message types.
10
+
11
+ - **`grpc-server-reflection`** uses `google-protobuf` which performs a similar decode/re-encode round-trip, with no guarantee of byte-for-byte fidelity.
12
+
13
+ This means any downstream consumer relying on reflection (API gateways, documentation generators, gRPC-to-HTTP transcoders) will see methods without HTTP bindings, missing OpenAPI annotations, or stripped custom options.
14
+
15
+ **`grpc-descriptor-reflection`** solves this by:
16
+
17
+ 1. Parsing the `FileDescriptorSet` wire format directly to extract each `FileDescriptorProto` as a raw byte slice
18
+ 2. Using `@bufbuild/protobuf` only for indexing (building symbol and dependency lookups)
19
+ 3. Serving the original raw bytes to reflection clients without any re-encoding
20
+
21
+ The result is **byte-for-byte identical** output to what `buf build` or `protoc` produced.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ npm install grpc-descriptor-reflection
27
+ ```
28
+
29
+ Peer dependencies (you likely already have these):
30
+
31
+ ```bash
32
+ npm install @grpc/grpc-js @grpc/proto-loader
33
+ ```
34
+
35
+ ## Generating a Descriptor Set
36
+
37
+ You need a binary `FileDescriptorSet` file. Generate one with either `buf` or `protoc`:
38
+
39
+ ### With buf (recommended)
40
+
41
+ ```bash
42
+ buf build -o descriptor.bin --as-file-descriptor-set
43
+ ```
44
+
45
+ ### With protoc
46
+
47
+ ```bash
48
+ protoc \
49
+ --descriptor_set_out=descriptor.bin \
50
+ --include_imports \
51
+ -I ./proto \
52
+ ./proto/**/*.proto
53
+ ```
54
+
55
+ > **Important:** Use `--include_imports` (protoc) or the default behavior of `buf build` to include all transitive dependencies. The reflection service needs the full dependency graph to serve complete responses.
56
+
57
+ ## Usage
58
+
59
+ ### With vanilla `@grpc/grpc-js`
60
+
61
+ ```ts
62
+ import * as grpc from "@grpc/grpc-js";
63
+ import { DescriptorReflectionService } from "grpc-descriptor-reflection";
64
+
65
+ const server = new grpc.Server();
66
+
67
+ // Add your application services...
68
+ // server.addService(MyService, myImplementation);
69
+
70
+ // Add reflection (registers both v1 and v1alpha endpoints)
71
+ const reflection = new DescriptorReflectionService("path/to/descriptor.bin");
72
+ reflection.addToServer(server);
73
+
74
+ server.bindAsync("0.0.0.0:50051", grpc.ServerCredentials.createInsecure(), () => {
75
+ console.log("Server listening on port 50051");
76
+ });
77
+ ```
78
+
79
+ ### With NestJS gRPC microservice
80
+
81
+ ```ts
82
+ import { DescriptorReflectionService } from "grpc-descriptor-reflection";
83
+
84
+ const reflection = new DescriptorReflectionService(
85
+ join(__dirname, "..", "descriptor.bin"),
86
+ );
87
+
88
+ @Module({
89
+ imports: [
90
+ ClientsModule.register([
91
+ {
92
+ name: "ORDERS_PACKAGE",
93
+ transport: Transport.GRPC,
94
+ options: {
95
+ package: "orders.v1",
96
+ protoPath: join(__dirname, "../proto/orders/v1/orders.proto"),
97
+ url: "0.0.0.0:50051",
98
+ onLoadPackageDefinition: (_pkg, server) => {
99
+ reflection.addToServer(server);
100
+ },
101
+ },
102
+ },
103
+ ]),
104
+ ],
105
+ })
106
+ export class AppModule {}
107
+ ```
108
+
109
+ ### Filtering advertised services
110
+
111
+ By default, all services found in the descriptor set are advertised via `ListServices`. You can restrict which services are listed:
112
+
113
+ ```ts
114
+ const reflection = new DescriptorReflectionService("descriptor.bin", {
115
+ services: ["mypackage.MyService", "mypackage.AdminService"],
116
+ });
117
+ ```
118
+
119
+ > Note: The filter only affects `ListServices` responses. All symbols remain resolvable via `FileContainingSymbol` regardless of the filter.
120
+
121
+ ## API
122
+
123
+ ### `new DescriptorReflectionService(descriptorSetPath, options?)`
124
+
125
+ Creates a new reflection service instance.
126
+
127
+ **Parameters:**
128
+
129
+ - `descriptorSetPath` (`string`) - Path to a binary-encoded `FileDescriptorSet` file.
130
+ - `options` (`DescriptorReflectionServiceOptions`) - Optional configuration.
131
+ - `services` (`string[]`) - Restrict which services are advertised via `ListServices`. If omitted, all services in the descriptor set are advertised.
132
+
133
+ ### `reflection.addToServer(server)`
134
+
135
+ Registers both `grpc.reflection.v1.ServerReflection` and `grpc.reflection.v1alpha.ServerReflection` services on the given server.
136
+
137
+ **Parameters:**
138
+
139
+ - `server` - A `grpc.Server` instance or any object with an `addService(service, implementation)` method.
140
+
141
+ ## Supported Reflection Operations
142
+
143
+ | Operation | Description |
144
+ |---|---|
145
+ | `ListServices` | Lists all (or filtered) services |
146
+ | `FileContainingSymbol` | Returns file descriptors for a fully-qualified symbol |
147
+ | `FileByFilename` | Returns a file descriptor by its proto filename |
148
+ | `FileContainingExtension` | Returns the file containing an extension field |
149
+ | `AllExtensionNumbersOfType` | Returns all extension field numbers for a type |
150
+
151
+ All responses include transitive dependencies.
152
+
153
+ ## Comparison with `@grpc/reflection`
154
+
155
+ | Feature | `@grpc/reflection` | `grpc-descriptor-reflection` |
156
+ |---|---|---|
157
+ | Preserves `google.api.http` | No | Yes |
158
+ | Preserves `openapiv2_operation` | No | Yes |
159
+ | Preserves custom options | No | Yes |
160
+ | Byte-for-byte fidelity | No | Yes |
161
+ | Input | Proto file paths | Pre-built descriptor set |
162
+ | Encoding library | protobufjs (lossy) | Raw wire format (lossless) |
163
+
164
+ ## How It Works
165
+
166
+ 1. The constructor reads the binary `FileDescriptorSet` and parses the protobuf wire format directly to extract each `FileDescriptorProto` as a raw `Uint8Array` slice.
167
+ 2. It then decodes the set with `@bufbuild/protobuf` (which does preserve extensions) solely to build indexes: symbol-to-file mappings, dependency graphs, and extension registries.
168
+ 3. When a reflection client requests a file, the service serves the **original raw bytes** extracted in step 1, along with all transitive dependencies.
169
+
170
+ Since the raw bytes are never decoded and re-encoded, every extension field, custom option, and annotation is preserved exactly as the proto compiler produced it.
171
+
172
+ ## License
173
+
174
+ MIT
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Options for creating a {@link DescriptorReflectionService}.
3
+ */
4
+ export interface DescriptorReflectionServiceOptions {
5
+ /**
6
+ * Restrict which services are advertised via `ListServices`.
7
+ * If omitted, all services found in the descriptor set are advertised.
8
+ */
9
+ services?: string[];
10
+ }
11
+ /**
12
+ * A gRPC server reflection service that serves raw `FileDescriptorProto` bytes
13
+ * from a pre-built descriptor set (e.g. produced by `buf build -o descriptor.bin`).
14
+ *
15
+ * Unlike `@grpc/reflection`, which decodes and re-encodes descriptors through
16
+ * protobufjs (silently stripping all extensions like `google.api.http`,
17
+ * `openapiv2_operation`, etc.), this implementation preserves the original binary
18
+ * encoding byte-for-byte. All custom options and extensions are retained.
19
+ *
20
+ * Registers both `grpc.reflection.v1` and `grpc.reflection.v1alpha` endpoints.
21
+ *
22
+ * @example
23
+ * ```ts
24
+ * import { DescriptorReflectionService } from "grpc-descriptor-reflection";
25
+ *
26
+ * const reflection = new DescriptorReflectionService("path/to/descriptor.bin");
27
+ *
28
+ * // With NestJS gRPC microservice:
29
+ * onLoadPackageDefinition: (_pkg, server) => {
30
+ * reflection.addToServer(server);
31
+ * }
32
+ *
33
+ * // With vanilla @grpc/grpc-js:
34
+ * reflection.addToServer(server);
35
+ * ```
36
+ */
37
+ export declare class DescriptorReflectionService {
38
+ /** Files indexed by filename. */
39
+ private files;
40
+ /** Fully-qualified symbol name -> filename. */
41
+ private symbols;
42
+ /** Service FQN -> filename. */
43
+ private services;
44
+ /** File dependency graph: filename -> list of dependency filenames. */
45
+ private dependencies;
46
+ /** Extension index: extendee type -> Map<field number, filename>. */
47
+ private extensions;
48
+ /** Optional filter for advertised services. */
49
+ private serviceFilter?;
50
+ /**
51
+ * @param descriptorSetPath - Path to a binary-encoded `FileDescriptorSet`
52
+ * file (e.g. produced by `buf build -o descriptor.bin --as-file-descriptor-set`
53
+ * or `protoc --descriptor_set_out`).
54
+ * @param options - Optional configuration.
55
+ */
56
+ constructor(descriptorSetPath: string, options?: DescriptorReflectionServiceOptions);
57
+ private indexMessage;
58
+ /** Collect raw bytes for a file and all its transitive dependencies. */
59
+ private collectFileWithDeps;
60
+ private handleRequest;
61
+ /**
62
+ * Register both `grpc.reflection.v1` and `grpc.reflection.v1alpha` reflection
63
+ * services on the given gRPC server.
64
+ *
65
+ * @param server - A `grpc.Server` instance or any object with an `addService` method
66
+ * (e.g. the server object from NestJS `onLoadPackageDefinition`).
67
+ */
68
+ addToServer(server: {
69
+ addService: (service: any, implementation: any) => any;
70
+ }): void;
71
+ }
72
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AA2BA;;GAEG;AACH,MAAM,WAAW,kCAAkC;IACjD;;;OAGG;IACH,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;CACrB;AAiBD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,2BAA2B;IACtC,iCAAiC;IACjC,OAAO,CAAC,KAAK,CAAgC;IAC7C,+CAA+C;IAC/C,OAAO,CAAC,OAAO,CAA6B;IAC5C,+BAA+B;IAC/B,OAAO,CAAC,QAAQ,CAA6B;IAC7C,uEAAuE;IACvE,OAAO,CAAC,YAAY,CAA+B;IACnD,qEAAqE;IACrE,OAAO,CAAC,UAAU,CAA0C;IAC5D,+CAA+C;IAC/C,OAAO,CAAC,aAAa,CAAC,CAAc;IAEpC;;;;;OAKG;gBAED,iBAAiB,EAAE,MAAM,EACzB,OAAO,CAAC,EAAE,kCAAkC;IA6E9C,OAAO,CAAC,YAAY;IAmDpB,wEAAwE;IACxE,OAAO,CAAC,mBAAmB;IAmB3B,OAAO,CAAC,aAAa;IAwFrB;;;;;;OAMG;IACH,WAAW,CAAC,MAAM,EAAE;QAClB,UAAU,EAAE,CAAC,OAAO,EAAE,GAAG,EAAE,cAAc,EAAE,GAAG,KAAK,GAAG,CAAC;KACxD,GAAG,IAAI;CA4CT"}
package/dist/index.js ADDED
@@ -0,0 +1,404 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.DescriptorReflectionService = void 0;
37
+ const node_fs_1 = require("node:fs");
38
+ const node_path_1 = require("node:path");
39
+ const grpc = __importStar(require("@grpc/grpc-js"));
40
+ const protoLoader = __importStar(require("@grpc/proto-loader"));
41
+ const protobuf_1 = require("@bufbuild/protobuf");
42
+ const wkt_1 = require("@bufbuild/protobuf/wkt");
43
+ /**
44
+ * Resolve the package root directory, supporting both CJS and ESM.
45
+ * In CJS (compiled output), __dirname points to dist/, so we go up one level.
46
+ * In ESM (e.g. running source directly with --experimental-strip-types),
47
+ * __dirname is not available so we use import.meta.
48
+ */
49
+ function resolvePackageDir() {
50
+ if (typeof __dirname !== "undefined") {
51
+ // CJS: __dirname is dist/ → package root is ..
52
+ return (0, node_path_1.join)(__dirname, "..");
53
+ }
54
+ // ESM: import.meta.filename points to src/index.ts → package root is ..
55
+ // @ts-ignore -- import.meta.filename available in Node 21+
56
+ return (0, node_path_1.join)((0, node_path_1.dirname)(import.meta.filename), "..");
57
+ }
58
+ const PROTO_LOADER_OPTS = {
59
+ longs: String,
60
+ enums: String,
61
+ bytes: Array,
62
+ defaults: true,
63
+ oneofs: true,
64
+ };
65
+ /**
66
+ * A gRPC server reflection service that serves raw `FileDescriptorProto` bytes
67
+ * from a pre-built descriptor set (e.g. produced by `buf build -o descriptor.bin`).
68
+ *
69
+ * Unlike `@grpc/reflection`, which decodes and re-encodes descriptors through
70
+ * protobufjs (silently stripping all extensions like `google.api.http`,
71
+ * `openapiv2_operation`, etc.), this implementation preserves the original binary
72
+ * encoding byte-for-byte. All custom options and extensions are retained.
73
+ *
74
+ * Registers both `grpc.reflection.v1` and `grpc.reflection.v1alpha` endpoints.
75
+ *
76
+ * @example
77
+ * ```ts
78
+ * import { DescriptorReflectionService } from "grpc-descriptor-reflection";
79
+ *
80
+ * const reflection = new DescriptorReflectionService("path/to/descriptor.bin");
81
+ *
82
+ * // With NestJS gRPC microservice:
83
+ * onLoadPackageDefinition: (_pkg, server) => {
84
+ * reflection.addToServer(server);
85
+ * }
86
+ *
87
+ * // With vanilla @grpc/grpc-js:
88
+ * reflection.addToServer(server);
89
+ * ```
90
+ */
91
+ class DescriptorReflectionService {
92
+ /**
93
+ * @param descriptorSetPath - Path to a binary-encoded `FileDescriptorSet`
94
+ * file (e.g. produced by `buf build -o descriptor.bin --as-file-descriptor-set`
95
+ * or `protoc --descriptor_set_out`).
96
+ * @param options - Optional configuration.
97
+ */
98
+ constructor(descriptorSetPath, options) {
99
+ /** Files indexed by filename. */
100
+ this.files = new Map();
101
+ /** Fully-qualified symbol name -> filename. */
102
+ this.symbols = new Map();
103
+ /** Service FQN -> filename. */
104
+ this.services = new Map();
105
+ /** File dependency graph: filename -> list of dependency filenames. */
106
+ this.dependencies = new Map();
107
+ /** Extension index: extendee type -> Map<field number, filename>. */
108
+ this.extensions = new Map();
109
+ if (options?.services) {
110
+ this.serviceFilter = new Set(options.services);
111
+ }
112
+ const bin = (0, node_fs_1.readFileSync)(descriptorSetPath);
113
+ const descriptorSet = (0, protobuf_1.fromBinary)(wkt_1.FileDescriptorSetSchema, bin);
114
+ // Extract raw bytes for each FileDescriptorProto by parsing the wire
115
+ // format of the FileDescriptorSet directly. This preserves the exact bytes
116
+ // produced by buf/protoc without any decode/re-encode cycle.
117
+ const rawEntries = extractRawFileDescriptorProtos(bin);
118
+ for (let i = 0; i < descriptorSet.file.length; i++) {
119
+ const fd = descriptorSet.file[i];
120
+ const name = fd.name;
121
+ if (!name)
122
+ continue;
123
+ // Use raw bytes extracted from the original binary if available,
124
+ // otherwise fall back to re-encoding via @bufbuild/protobuf (which
125
+ // does preserve extensions, unlike protobufjs).
126
+ const rawBytes = rawEntries[i] ?? (0, protobuf_1.toBinary)(wkt_1.FileDescriptorProtoSchema, fd);
127
+ this.files.set(name, { descriptor: fd, rawBytes });
128
+ this.dependencies.set(name, [...fd.dependency]);
129
+ const pkg = fd.package;
130
+ const prefix = pkg ? `${pkg}.` : "";
131
+ for (const msg of fd.messageType) {
132
+ this.indexMessage(prefix, msg, name);
133
+ }
134
+ for (const en of fd.enumType) {
135
+ if (en.name) {
136
+ this.symbols.set(`${prefix}${en.name}`, name);
137
+ for (const val of en.value) {
138
+ if (val.name) {
139
+ this.symbols.set(`${prefix}${en.name}.${val.name}`, name);
140
+ }
141
+ }
142
+ }
143
+ }
144
+ for (const svc of fd.service) {
145
+ if (svc.name) {
146
+ const svcFqn = `${prefix}${svc.name}`;
147
+ this.symbols.set(svcFqn, name);
148
+ this.services.set(svcFqn, name);
149
+ for (const method of svc.method) {
150
+ if (method.name) {
151
+ this.symbols.set(`${svcFqn}.${method.name}`, name);
152
+ }
153
+ }
154
+ }
155
+ }
156
+ for (const ext of fd.extension) {
157
+ if (ext.extendee && ext.number) {
158
+ const extendee = ext.extendee.startsWith(".")
159
+ ? ext.extendee.slice(1)
160
+ : ext.extendee;
161
+ let extMap = this.extensions.get(extendee);
162
+ if (!extMap) {
163
+ extMap = new Map();
164
+ this.extensions.set(extendee, extMap);
165
+ }
166
+ extMap.set(ext.number, name);
167
+ if (ext.name) {
168
+ this.symbols.set(`${prefix}${ext.name}`, name);
169
+ }
170
+ }
171
+ }
172
+ }
173
+ }
174
+ indexMessage(prefix, msg, filename) {
175
+ if (!msg.name)
176
+ return;
177
+ const fqn = `${prefix}${msg.name}`;
178
+ this.symbols.set(fqn, filename);
179
+ for (const field of msg.field) {
180
+ if (field.name) {
181
+ this.symbols.set(`${fqn}.${field.name}`, filename);
182
+ }
183
+ }
184
+ for (const oneof of msg.oneofDecl) {
185
+ if (oneof.name) {
186
+ this.symbols.set(`${fqn}.${oneof.name}`, filename);
187
+ }
188
+ }
189
+ for (const nested of msg.nestedType) {
190
+ this.indexMessage(`${fqn}.`, nested, filename);
191
+ }
192
+ for (const en of msg.enumType) {
193
+ if (en.name) {
194
+ this.symbols.set(`${fqn}.${en.name}`, filename);
195
+ for (const val of en.value) {
196
+ if (val.name) {
197
+ this.symbols.set(`${fqn}.${en.name}.${val.name}`, filename);
198
+ }
199
+ }
200
+ }
201
+ }
202
+ for (const ext of msg.extension) {
203
+ if (ext.extendee && ext.number) {
204
+ const extendee = ext.extendee.startsWith(".")
205
+ ? ext.extendee.slice(1)
206
+ : ext.extendee;
207
+ let extMap = this.extensions.get(extendee);
208
+ if (!extMap) {
209
+ extMap = new Map();
210
+ this.extensions.set(extendee, extMap);
211
+ }
212
+ extMap.set(ext.number, filename);
213
+ }
214
+ }
215
+ }
216
+ /** Collect raw bytes for a file and all its transitive dependencies. */
217
+ collectFileWithDeps(filename) {
218
+ const visited = new Set();
219
+ const result = [];
220
+ const visit = (name) => {
221
+ if (visited.has(name))
222
+ return;
223
+ visited.add(name);
224
+ const entry = this.files.get(name);
225
+ if (!entry)
226
+ return;
227
+ result.push(entry.rawBytes);
228
+ for (const dep of this.dependencies.get(name) ?? []) {
229
+ visit(dep);
230
+ }
231
+ };
232
+ visit(filename);
233
+ return result;
234
+ }
235
+ handleRequest(message) {
236
+ const response = {
237
+ validHost: message.host,
238
+ originalRequest: message,
239
+ };
240
+ try {
241
+ switch (message.messageRequest) {
242
+ case "fileByFilename": {
243
+ const filename = message.fileByFilename || "";
244
+ if (!this.files.has(filename)) {
245
+ throw {
246
+ code: 5 /* NOT_FOUND */,
247
+ msg: `File not found: ${filename}`,
248
+ };
249
+ }
250
+ response.fileDescriptorResponse = {
251
+ fileDescriptorProto: this.collectFileWithDeps(filename),
252
+ };
253
+ break;
254
+ }
255
+ case "fileContainingSymbol": {
256
+ const symbol = message.fileContainingSymbol || "";
257
+ const filename = this.symbols.get(symbol);
258
+ if (!filename) {
259
+ throw {
260
+ code: 5 /* NOT_FOUND */,
261
+ msg: `Symbol not found: ${symbol}`,
262
+ };
263
+ }
264
+ response.fileDescriptorResponse = {
265
+ fileDescriptorProto: this.collectFileWithDeps(filename),
266
+ };
267
+ break;
268
+ }
269
+ case "fileContainingExtension": {
270
+ const containingType = message.fileContainingExtension?.containingType || "";
271
+ const extensionNumber = message.fileContainingExtension?.extensionNumber ?? -1;
272
+ const extMap = this.extensions.get(containingType);
273
+ const filename = extMap?.get(extensionNumber);
274
+ if (!filename) {
275
+ throw {
276
+ code: 5 /* NOT_FOUND */,
277
+ msg: `Extension not found: ${containingType}(${extensionNumber})`,
278
+ };
279
+ }
280
+ response.fileDescriptorResponse = {
281
+ fileDescriptorProto: this.collectFileWithDeps(filename),
282
+ };
283
+ break;
284
+ }
285
+ case "allExtensionNumbersOfType": {
286
+ const typeName = message.allExtensionNumbersOfType || "";
287
+ const extMap = this.extensions.get(typeName);
288
+ response.allExtensionNumbersResponse = {
289
+ baseTypeName: typeName,
290
+ extensionNumber: extMap ? [...extMap.keys()] : [],
291
+ };
292
+ break;
293
+ }
294
+ case "listServices": {
295
+ const serviceNames = this.serviceFilter
296
+ ? [...this.serviceFilter]
297
+ : [...this.services.keys()];
298
+ response.listServicesResponse = {
299
+ service: serviceNames.map((name) => ({ name })),
300
+ };
301
+ break;
302
+ }
303
+ default: {
304
+ throw {
305
+ code: 12 /* UNIMPLEMENTED */,
306
+ msg: `Unimplemented: ${message.messageRequest}`,
307
+ };
308
+ }
309
+ }
310
+ }
311
+ catch (e) {
312
+ response.errorResponse = {
313
+ errorCode: e.code ?? 2 /* UNKNOWN */,
314
+ errorMessage: e.msg ?? "Unknown error",
315
+ };
316
+ }
317
+ return response;
318
+ }
319
+ /**
320
+ * Register both `grpc.reflection.v1` and `grpc.reflection.v1alpha` reflection
321
+ * services on the given gRPC server.
322
+ *
323
+ * @param server - A `grpc.Server` instance or any object with an `addService` method
324
+ * (e.g. the server object from NestJS `onLoadPackageDefinition`).
325
+ */
326
+ addToServer(server) {
327
+ const handler = {
328
+ ServerReflectionInfo: (stream) => {
329
+ stream.on("end", () => stream.end());
330
+ stream.on("data", (message) => {
331
+ try {
332
+ stream.write(this.handleRequest(message));
333
+ }
334
+ catch (e) {
335
+ console.error("[grpc-descriptor-reflection] Error:", e);
336
+ stream.end();
337
+ }
338
+ });
339
+ },
340
+ };
341
+ // Resolve the proto directory relative to this source file.
342
+ // In CJS (compiled), __dirname is available. In ESM (strip-types),
343
+ // we fall back to resolving from the package root via require.resolve.
344
+ const protoDir = (0, node_path_1.join)(resolvePackageDir(), "proto");
345
+ // Register v1
346
+ const v1ProtoPath = (0, node_path_1.join)(protoDir, "grpc/reflection/v1/reflection.proto");
347
+ const v1PkgDef = protoLoader.loadSync(v1ProtoPath, PROTO_LOADER_OPTS);
348
+ const v1Pkg = grpc.loadPackageDefinition(v1PkgDef);
349
+ server.addService(v1Pkg.grpc.reflection.v1.ServerReflection.service, handler);
350
+ // Register v1alpha
351
+ const v1AlphaProtoPath = (0, node_path_1.join)(protoDir, "grpc/reflection/v1alpha/reflection.proto");
352
+ const v1AlphaPkgDef = protoLoader.loadSync(v1AlphaProtoPath, PROTO_LOADER_OPTS);
353
+ const v1AlphaPkg = grpc.loadPackageDefinition(v1AlphaPkgDef);
354
+ server.addService(v1AlphaPkg.grpc.reflection.v1alpha.ServerReflection.service, handler);
355
+ }
356
+ }
357
+ exports.DescriptorReflectionService = DescriptorReflectionService;
358
+ /**
359
+ * Extracts raw `FileDescriptorProto` byte arrays from a serialized
360
+ * `FileDescriptorSet` by parsing the protobuf wire format directly.
361
+ *
362
+ * This preserves the exact bytes produced by `buf build` or `protoc` without
363
+ * any decode/re-encode cycle, guaranteeing all extensions and custom options
364
+ * are retained byte-for-byte.
365
+ */
366
+ function extractRawFileDescriptorProtos(bin) {
367
+ const result = [];
368
+ let offset = 0;
369
+ while (offset < bin.length) {
370
+ // Read tag varint
371
+ let tag = 0;
372
+ let shift = 0;
373
+ while (offset < bin.length) {
374
+ const byte = bin[offset++];
375
+ tag |= (byte & 0x7f) << shift;
376
+ if ((byte & 0x80) === 0)
377
+ break;
378
+ shift += 7;
379
+ }
380
+ const fieldNumber = tag >>> 3;
381
+ const wireType = tag & 0x7;
382
+ if (wireType !== 2) {
383
+ throw new Error(`Unexpected wire type ${wireType} for field ${fieldNumber} in FileDescriptorSet`);
384
+ }
385
+ // Read varint length
386
+ let length = 0;
387
+ shift = 0;
388
+ while (offset < bin.length) {
389
+ const byte = bin[offset++];
390
+ length |= (byte & 0x7f) << shift;
391
+ if ((byte & 0x80) === 0)
392
+ break;
393
+ shift += 7;
394
+ }
395
+ if (fieldNumber === 1) {
396
+ // Field 1 = repeated FileDescriptorProto
397
+ result.push(new Uint8Array(bin.buffer, bin.byteOffset + offset, length));
398
+ }
399
+ // Skip any other fields
400
+ offset += length;
401
+ }
402
+ return result;
403
+ }
404
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAuC;AACvC,yCAA0C;AAC1C,oDAAsC;AACtC,gEAAkD;AAClD,iDAA0D;AAC1D,gDAIgC;AAEhC;;;;;GAKG;AACH,SAAS,iBAAiB;IACxB,IAAI,OAAO,SAAS,KAAK,WAAW,E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AC,KAAK,CAAC;gBAAE,MAAM;YAC/B,KAAK,IAAI,CAAC,CAAC;QACb,CAAC;QAED,IAAI,WAAW,KAAK,CAAC,EAAE,CAAC;YACtB,yCAAyC;YACzC,MAAM,CAAC,IAAI,CAAC,IAAI,UAAU,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,UAAU,GAAG,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;QAC3E,CAAC;QACD,wBAAwB;QACxB,MAAM,IAAI,MAAM,CAAC;IACnB,CAAC;IAED,OAAO,MAAM,CAAC;AAChB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "grpc-descriptor-reflection",
3
+ "version": "1.0.0",
4
+ "description": "gRPC reflection service for @grpc/grpc-js that serves raw FileDescriptorProto bytes from a pre-built descriptor set, preserving all extensions and custom options (google.api.http, openapiv2, etc.)",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "files": [
8
+ "dist",
9
+ "proto"
10
+ ],
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "test": "node --experimental-strip-types --no-warnings --test test/reflection.test.ts",
14
+ "prepublishOnly": "npm run build"
15
+ },
16
+ "keywords": [
17
+ "grpc",
18
+ "reflection",
19
+ "protobuf",
20
+ "descriptor",
21
+ "grpc-js",
22
+ "google.api.http",
23
+ "extensions",
24
+ "openapi",
25
+ "buf"
26
+ ],
27
+ "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/MasonryStack/grpc-descriptor-reflection.git"
31
+ },
32
+ "dependencies": {
33
+ "@bufbuild/protobuf": "^2.0.0"
34
+ },
35
+ "peerDependencies": {
36
+ "@grpc/grpc-js": "^1.0.0",
37
+ "@grpc/proto-loader": "^0.7.0 || ^0.8.0"
38
+ },
39
+ "devDependencies": {
40
+ "@grpc/grpc-js": "^1.14.3",
41
+ "@grpc/proto-loader": "^0.8.0",
42
+ "@types/node": "^22.0.0",
43
+ "typescript": "^5.0.0"
44
+ }
45
+ }
@@ -0,0 +1,146 @@
1
+ // Copyright 2016 The gRPC Authors
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ // Service exported by server reflection. A more complete description of how
16
+ // server reflection works can be found at
17
+ // https://github.com/grpc/grpc/blob/master/doc/server-reflection.md
18
+ //
19
+ // The canonical version of this proto can be found at
20
+ // https://github.com/grpc/grpc-proto/blob/master/grpc/reflection/v1/reflection.proto
21
+
22
+ syntax = "proto3";
23
+
24
+ package grpc.reflection.v1;
25
+
26
+ option go_package = "google.golang.org/grpc/reflection/grpc_reflection_v1";
27
+ option java_multiple_files = true;
28
+ option java_package = "io.grpc.reflection.v1";
29
+ option java_outer_classname = "ServerReflectionProto";
30
+
31
+ service ServerReflection {
32
+ // The reflection service is structured as a bidirectional stream, ensuring
33
+ // all related requests go to a single server.
34
+ rpc ServerReflectionInfo(stream ServerReflectionRequest)
35
+ returns (stream ServerReflectionResponse);
36
+ }
37
+
38
+ // The message sent by the client when calling ServerReflectionInfo method.
39
+ message ServerReflectionRequest {
40
+ string host = 1;
41
+ // To use reflection service, the client should set one of the following
42
+ // fields in message_request. The server distinguishes requests by their
43
+ // defined field and then handles them using corresponding methods.
44
+ oneof message_request {
45
+ // Find a proto file by the file name.
46
+ string file_by_filename = 3;
47
+
48
+ // Find the proto file that declares the given fully-qualified symbol name.
49
+ // This field should be a fully-qualified symbol name
50
+ // (e.g. <package>.<service>[.<method>] or <package>.<type>).
51
+ string file_containing_symbol = 4;
52
+
53
+ // Find the proto file which defines an extension extending the given
54
+ // message type with the given field number.
55
+ ExtensionRequest file_containing_extension = 5;
56
+
57
+ // Finds the tag numbers used by all known extensions of the given message
58
+ // type, and appends them to ExtensionNumberResponse in an undefined order.
59
+ // Its corresponding method is best-effort: it's not guaranteed that the
60
+ // reflection service will implement this method, and it's not guaranteed
61
+ // that this method will provide all extensions. Returns
62
+ // StatusCode::UNIMPLEMENTED if it's not implemented.
63
+ // This field should be a fully-qualified type name. The format is
64
+ // <package>.<type>
65
+ string all_extension_numbers_of_type = 6;
66
+
67
+ // List the full names of registered services. The content will not be
68
+ // checked.
69
+ string list_services = 7;
70
+ }
71
+ }
72
+
73
+ // The type name and extension number sent by the client when requesting
74
+ // file_containing_extension.
75
+ message ExtensionRequest {
76
+ // Fully-qualified type name. The format should be <package>.<type>
77
+ string containing_type = 1;
78
+ int32 extension_number = 2;
79
+ }
80
+
81
+ // The message sent by the server to answer ServerReflectionInfo method.
82
+ message ServerReflectionResponse {
83
+ string valid_host = 1;
84
+ ServerReflectionRequest original_request = 2;
85
+ // The server sets one of the following fields according to the message_request
86
+ // in the request.
87
+ oneof message_response {
88
+ // This message is used to answer file_by_filename, file_containing_symbol,
89
+ // file_containing_extension requests with transitive dependencies.
90
+ // As the repeated label is not allowed in oneof fields, we use a
91
+ // FileDescriptorResponse message to encapsulate the repeated fields.
92
+ // The reflection service is allowed to avoid sending FileDescriptorProtos
93
+ // that were previously sent in response to earlier requests in the stream.
94
+ FileDescriptorResponse file_descriptor_response = 4;
95
+
96
+ // This message is used to answer all_extension_numbers_of_type requests.
97
+ ExtensionNumberResponse all_extension_numbers_response = 5;
98
+
99
+ // This message is used to answer list_services requests.
100
+ ListServiceResponse list_services_response = 6;
101
+
102
+ // This message is used when an error occurs.
103
+ ErrorResponse error_response = 7;
104
+ }
105
+ }
106
+
107
+ // Serialized FileDescriptorProto messages sent by the server answering
108
+ // a file_by_filename, file_containing_symbol, or file_containing_extension
109
+ // request.
110
+ message FileDescriptorResponse {
111
+ // Serialized FileDescriptorProto messages. We avoid taking a dependency on
112
+ // descriptor.proto, which uses proto2 only features, by making them opaque
113
+ // bytes instead.
114
+ repeated bytes file_descriptor_proto = 1;
115
+ }
116
+
117
+ // A list of extension numbers sent by the server answering
118
+ // all_extension_numbers_of_type request.
119
+ message ExtensionNumberResponse {
120
+ // Full name of the base type, including the package name. The format
121
+ // is <package>.<type>
122
+ string base_type_name = 1;
123
+ repeated int32 extension_number = 2;
124
+ }
125
+
126
+ // A list of ServiceResponse sent by the server answering list_services request.
127
+ message ListServiceResponse {
128
+ // The information of each service may be expanded in the future, so we use
129
+ // ServiceResponse message to encapsulate it.
130
+ repeated ServiceResponse service = 1;
131
+ }
132
+
133
+ // The information of a single service used by ListServiceResponse to answer
134
+ // list_services request.
135
+ message ServiceResponse {
136
+ // Full name of a registered service, including its package name. The format
137
+ // is <package>.<service>
138
+ string name = 1;
139
+ }
140
+
141
+ // The error code and error message sent by the server when an error occurs.
142
+ message ErrorResponse {
143
+ // This field uses the error codes defined in grpc::StatusCode.
144
+ int32 error_code = 1;
145
+ string error_message = 2;
146
+ }
@@ -0,0 +1,136 @@
1
+ // Copyright 2016 gRPC authors.
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+
15
+ // Service exported by server reflection
16
+
17
+ syntax = "proto3";
18
+
19
+ package grpc.reflection.v1alpha;
20
+
21
+ service ServerReflection {
22
+ // The reflection service is structured as a bidirectional stream, ensuring
23
+ // all related requests go to a single server.
24
+ rpc ServerReflectionInfo(stream ServerReflectionRequest)
25
+ returns (stream ServerReflectionResponse);
26
+ }
27
+
28
+ // The message sent by the client when calling ServerReflectionInfo method.
29
+ message ServerReflectionRequest {
30
+ string host = 1;
31
+ // To use reflection service, the client should set one of the following
32
+ // fields in message_request. The server distinguishes requests by their
33
+ // defined field and then handles them using corresponding methods.
34
+ oneof message_request {
35
+ // Find a proto file by the file name.
36
+ string file_by_filename = 3;
37
+
38
+ // Find the proto file that declares the given fully-qualified symbol name.
39
+ // This field should be a fully-qualified symbol name
40
+ // (e.g. <package>.<service>[.<method>] or <package>.<type>).
41
+ string file_containing_symbol = 4;
42
+
43
+ // Find the proto file which defines an extension extending the given
44
+ // message type with the given field number.
45
+ ExtensionRequest file_containing_extension = 5;
46
+
47
+ // Finds the tag numbers used by all known extensions of the given message
48
+ // type, and appends them to ExtensionNumberResponse in an undefined order.
49
+ // Its corresponding method is best-effort: it's not guaranteed that the
50
+ // reflection service will implement this method, and it's not guaranteed
51
+ // that this method will provide all extensions. Returns
52
+ // StatusCode::UNIMPLEMENTED if it's not implemented.
53
+ // This field should be a fully-qualified type name. The format is
54
+ // <package>.<type>
55
+ string all_extension_numbers_of_type = 6;
56
+
57
+ // List the full names of registered services. The content will not be
58
+ // checked.
59
+ string list_services = 7;
60
+ }
61
+ }
62
+
63
+ // The type name and extension number sent by the client when requesting
64
+ // file_containing_extension.
65
+ message ExtensionRequest {
66
+ // Fully-qualified type name. The format should be <package>.<type>
67
+ string containing_type = 1;
68
+ int32 extension_number = 2;
69
+ }
70
+
71
+ // The message sent by the server to answer ServerReflectionInfo method.
72
+ message ServerReflectionResponse {
73
+ string valid_host = 1;
74
+ ServerReflectionRequest original_request = 2;
75
+ // The server set one of the following fields accroding to the message_request
76
+ // in the request.
77
+ oneof message_response {
78
+ // This message is used to answer file_by_filename, file_containing_symbol,
79
+ // file_containing_extension requests with transitive dependencies. As
80
+ // the repeated label is not allowed in oneof fields, we use a
81
+ // FileDescriptorResponse message to encapsulate the repeated fields.
82
+ // The reflection service is allowed to avoid sending FileDescriptorProtos
83
+ // that were previously sent in response to earlier requests in the stream.
84
+ FileDescriptorResponse file_descriptor_response = 4;
85
+
86
+ // This message is used to answer all_extension_numbers_of_type requst.
87
+ ExtensionNumberResponse all_extension_numbers_response = 5;
88
+
89
+ // This message is used to answer list_services request.
90
+ ListServiceResponse list_services_response = 6;
91
+
92
+ // This message is used when an error occurs.
93
+ ErrorResponse error_response = 7;
94
+ }
95
+ }
96
+
97
+ // Serialized FileDescriptorProto messages sent by the server answering
98
+ // a file_by_filename, file_containing_symbol, or file_containing_extension
99
+ // request.
100
+ message FileDescriptorResponse {
101
+ // Serialized FileDescriptorProto messages. We avoid taking a dependency on
102
+ // descriptor.proto, which uses proto2 only features, by making them opaque
103
+ // bytes instead.
104
+ repeated bytes file_descriptor_proto = 1;
105
+ }
106
+
107
+ // A list of extension numbers sent by the server answering
108
+ // all_extension_numbers_of_type request.
109
+ message ExtensionNumberResponse {
110
+ // Full name of the base type, including the package name. The format
111
+ // is <package>.<type>
112
+ string base_type_name = 1;
113
+ repeated int32 extension_number = 2;
114
+ }
115
+
116
+ // A list of ServiceResponse sent by the server answering list_services request.
117
+ message ListServiceResponse {
118
+ // The information of each service may be expanded in the future, so we use
119
+ // ServiceResponse message to encapsulate it.
120
+ repeated ServiceResponse service = 1;
121
+ }
122
+
123
+ // The information of a single service used by ListServiceResponse to answer
124
+ // list_services request.
125
+ message ServiceResponse {
126
+ // Full name of a registered service, including its package name. The format
127
+ // is <package>.<service>
128
+ string name = 1;
129
+ }
130
+
131
+ // The error code and error message sent by the server when an error occurs.
132
+ message ErrorResponse {
133
+ // This field uses the error codes defined in grpc::StatusCode.
134
+ int32 error_code = 1;
135
+ string error_message = 2;
136
+ }