-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathindex.js
190 lines (161 loc) · 5.45 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
const plugin = require("./compiler/plugin");
const fs = require("fs");
const path = require("path");
const ts = require("typescript");
const type = require("./type");
const descriptor = require("./descriptor");
const rpc = require("./rpc");
function createImport(identifier, moduleSpecifier) {
return ts.factory.createImportDeclaration(
undefined,
undefined,
ts.factory.createImportClause(undefined, ts.factory.createNamespaceImport(identifier)),
ts.factory.createStringLiteral(moduleSpecifier)
);
}
function replaceExtension(filename, extension = ".ts") {
return filename.replace(/\.[^/.]+$/, extension)
}
/**
* @typedef {{ unary_rpc_promise: boolean, grpc_package: string }} ConfigParameters
*/
/**
* @param {string | undefined | null} parameters
* @return{ConfigParameters}
*/
function parseParameters(parameters) {
/** @type{ConfigParameters} */
const defaultValues = {
unary_rpc_promise: false,
grpc_package: "@grpc/grpc-js",
};
/** @type{{ [K keyof ConfigParameters]: (value: string) => ConfigParameters[K] }} */
const parsers = {
unary_rpc_promise: (value) => value === "true",
grpc_package: (value) => value,
};
/** @type{Partial<ConfigParameters>} */
const inputParams = {};
// comma separated
(parameters || "").split(',').forEach(param => {
const [key, value = "true"] = param.split('=', 2)
if (key in parsers) {
inputParams[key] = parsers[key](value);
}
})
// Legacy Environment variables
const legacy = {
...(process.env.EXPERIMENTAL_FEATURES ? { unary_rpc_promise: true } : {}),
...(process.env.GRPC_PACKAGE_NAME ? { grpc_package: process.env.GRPC_PACKAGE_NAME } : {}),
}
return { ...defaultValues, ...legacy, ...inputParams }
}
const request = plugin.CodeGeneratorRequest.deserialize(new Uint8Array(fs.readFileSync(0)));
const response = new plugin.CodeGeneratorResponse({
supported_features: plugin.CodeGeneratorResponse.Feature.FEATURE_PROTO3_OPTIONAL
});
const configParams = parseParameters(request.parameter)
for (const descriptor of request.proto_file) {
type.preprocess(descriptor, descriptor.name, `.${descriptor.package || ""}`);
}
for (const fileDescriptor of request.proto_file) {
const name = replaceExtension(fileDescriptor.name);
const pbIdentifier = ts.factory.createUniqueName("pb");
const grpcIdentifier = ts.factory.createUniqueName("grpc");
// Will keep track of import statements
const importStatements = [];
// Create all named imports from dependencies
for (const dependency of fileDescriptor.dependency) {
const identifier = ts.factory.createUniqueName("dependency");
const moduleSpecifier = replaceExtension(dependency, "");
type.setIdentifierForDependency(dependency, identifier);
const importedFrom = `./${path.relative(path.dirname(fileDescriptor.name), moduleSpecifier)}`;
importStatements.push(createImport(identifier, importedFrom));
}
// Create all messages recursively
let statements = [];
// Process enums
for (const enumDescriptor of fileDescriptor.enum_type) {
statements.push(descriptor.createEnum(enumDescriptor));
}
// Process root messages
for (const messageDescriptor of fileDescriptor.message_type) {
statements = statements.concat(
descriptor.processDescriptorRecursively(fileDescriptor, messageDescriptor, pbIdentifier)
)
}
if (statements.length) {
importStatements.push(createImport(pbIdentifier, "google-protobuf"));
}
if (fileDescriptor.service.length) {
// Import grpc only if there is service statements
importStatements.push(
createImport(
grpcIdentifier,
configParams.grpc_package,
)
);
statements.push(
...rpc.createGrpcInterfaceType(fileDescriptor, grpcIdentifier, configParams)
);
// Create all services and clients
for (const serviceDescriptor of fileDescriptor.service) {
statements.push(
rpc.createUnimplementedServer(
fileDescriptor,
serviceDescriptor,
grpcIdentifier
)
);
statements.push(
rpc.createServiceClient(
fileDescriptor,
serviceDescriptor,
grpcIdentifier,
configParams,
)
);
}
}
const {major, minor, patch} = request.compiler_version || {major: 0, minor: 0, patch: 0};
const doNotEditComment = ts.factory.createJSDocComment(
`Generated by the protoc-gen-ts. DO NOT EDIT!\n` +
`compiler version: ${major}.${minor}.${patch}\n` +
`source: ${fileDescriptor.name}\n` +
`git: https://github.com/thesayyn/protoc-gen-ts\n`
);
// Wrap statements within the namespace
if (fileDescriptor.package) {
statements = [
doNotEditComment,
...importStatements,
descriptor.createNamespace(fileDescriptor.package, statements),
]
} else {
statements = [
doNotEditComment,
...importStatements,
...statements
];
}
const sourcefile = ts.factory.createSourceFile(
statements,
ts.factory.createToken(ts.SyntaxKind.EndOfFileToken),
ts.NodeFlags.None
);
sourcefile.identifiers = new Set();
const content = ts
.createPrinter({
newLine: ts.NewLineKind.LineFeed,
omitTrailingSemicolon: true,
})
.printFile(sourcefile);
response.file.push(new plugin.CodeGeneratorResponse.File({
name,
content
}));
// after each iteration we need to clear the dependency map to prevent accidental
// misuse of identifiers
type.resetDependencyMap();
}
process.stdout.write(response.serialize());