@gravity-ui/gateway 4.7.1-alpha.0 → 4.7.1

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.
Files changed (94) hide show
  1. package/{dist/esm → build}/components/grpc.d.ts +5 -5
  2. package/{dist/commonjs → build}/components/grpc.js +84 -94
  3. package/{dist/esm → build}/components/mixed.d.ts +4 -4
  4. package/{dist/commonjs → build}/components/mixed.js +12 -11
  5. package/{dist/commonjs → build}/components/rest.d.ts +5 -5
  6. package/{dist/commonjs → build}/components/rest.js +34 -35
  7. package/{dist/esm → build}/constants.d.ts +3 -2
  8. package/{dist/commonjs → build}/constants.js +21 -30
  9. package/{dist/commonjs → build}/index.d.ts +8 -9
  10. package/{dist/commonjs → build}/index.js +46 -35
  11. package/{dist/esm → build}/models/common.d.ts +7 -12
  12. package/{dist/esm → build}/models/context.d.ts +1 -0
  13. package/{dist/esm → build}/utils/axios.d.ts +1 -1
  14. package/{dist/commonjs → build}/utils/axios.js +4 -3
  15. package/{dist/esm → build}/utils/common.d.ts +4 -4
  16. package/{dist/commonjs → build}/utils/common.js +8 -8
  17. package/{dist/commonjs → build}/utils/create-context-api.d.ts +2 -2
  18. package/{dist/commonjs → build}/utils/create-context-api.js +6 -5
  19. package/{dist/commonjs → build}/utils/grpc-reflection.js +35 -15
  20. package/{dist/commonjs → build}/utils/grpc.d.ts +1 -1
  21. package/{dist/commonjs → build}/utils/grpc.js +11 -10
  22. package/build/utils/overrideEndpoints/index.d.ts +2 -0
  23. package/build/utils/overrideEndpoints/index.js +4 -0
  24. package/{dist/esm → build}/utils/overrideEndpoints/overrideEndpoints.d.ts +1 -1
  25. package/{dist/commonjs → build}/utils/overrideEndpoints/overrideEndpoints.js +2 -1
  26. package/{dist/commonjs → build}/utils/parse-error.d.ts +5 -5
  27. package/{dist/commonjs → build}/utils/parse-error.js +19 -19
  28. package/{dist/commonjs → build}/utils/proto-path-resolver.d.ts +1 -1
  29. package/{dist/commonjs → build}/utils/proto-path-resolver.js +15 -24
  30. package/{dist/commonjs → build}/utils/redact-sensitive-headers.d.ts +2 -1
  31. package/{dist/commonjs → build}/utils/redact-sensitive-headers.js +2 -1
  32. package/{dist/commonjs → build}/utils/typed-api.d.ts +1 -1
  33. package/{dist/commonjs → build}/utils/typed-api.js +2 -1
  34. package/{dist/commonjs → build}/utils/validate.d.ts +0 -1
  35. package/{dist/commonjs → build}/utils/validate.js +20 -24
  36. package/package.json +16 -41
  37. package/dist/commonjs/components/grpc.d.ts +0 -24
  38. package/dist/commonjs/components/mixed.d.ts +0 -11
  39. package/dist/commonjs/constants.d.ts +0 -53
  40. package/dist/commonjs/models/common.d.ts +0 -289
  41. package/dist/commonjs/models/context.d.ts +0 -22
  42. package/dist/commonjs/package.json +0 -3
  43. package/dist/commonjs/utils/axios.d.ts +0 -4
  44. package/dist/commonjs/utils/common.d.ts +0 -16
  45. package/dist/commonjs/utils/overrideEndpoints/index.d.ts +0 -2
  46. package/dist/commonjs/utils/overrideEndpoints/index.js +0 -4
  47. package/dist/commonjs/utils/overrideEndpoints/overrideEndpoints.d.ts +0 -17
  48. package/dist/commonjs/utils/package-root.d.ts +0 -1
  49. package/dist/commonjs/utils/package-root.js +0 -44
  50. package/dist/commonjs/utils/source-dir.d.ts +0 -1
  51. package/dist/commonjs/utils/source-dir.js +0 -41
  52. package/dist/esm/components/grpc.js +0 -691
  53. package/dist/esm/components/mixed.js +0 -62
  54. package/dist/esm/components/rest.d.ts +0 -8
  55. package/dist/esm/components/rest.js +0 -357
  56. package/dist/esm/constants.js +0 -82
  57. package/dist/esm/index.d.ts +0 -13
  58. package/dist/esm/index.js +0 -274
  59. package/dist/esm/models/common.js +0 -5
  60. package/dist/esm/models/context.js +0 -1
  61. package/dist/esm/models/error.d.ts +0 -12
  62. package/dist/esm/models/error.js +0 -1
  63. package/dist/esm/package.json +0 -3
  64. package/dist/esm/utils/axios.js +0 -24
  65. package/dist/esm/utils/common.js +0 -48
  66. package/dist/esm/utils/create-context-api.d.ts +0 -4
  67. package/dist/esm/utils/create-context-api.js +0 -38
  68. package/dist/esm/utils/grpc-reflection.d.ts +0 -28
  69. package/dist/esm/utils/grpc-reflection.js +0 -72
  70. package/dist/esm/utils/grpc.d.ts +0 -15
  71. package/dist/esm/utils/grpc.js +0 -72
  72. package/dist/esm/utils/overrideEndpoints/index.d.ts +0 -2
  73. package/dist/esm/utils/overrideEndpoints/index.js +0 -2
  74. package/dist/esm/utils/overrideEndpoints/overrideEndpoints.js +0 -96
  75. package/dist/esm/utils/package-root.d.ts +0 -1
  76. package/dist/esm/utils/package-root.js +0 -8
  77. package/dist/esm/utils/parse-error.d.ts +0 -30
  78. package/dist/esm/utils/parse-error.js +0 -214
  79. package/dist/esm/utils/proto-path-resolver.d.ts +0 -2
  80. package/dist/esm/utils/proto-path-resolver.js +0 -23
  81. package/dist/esm/utils/redact-sensitive-headers.d.ts +0 -3
  82. package/dist/esm/utils/redact-sensitive-headers.js +0 -12
  83. package/dist/esm/utils/source-dir.d.ts +0 -1
  84. package/dist/esm/utils/source-dir.js +0 -4
  85. package/dist/esm/utils/typed-api.d.ts +0 -2
  86. package/dist/esm/utils/typed-api.js +0 -3
  87. package/dist/esm/utils/validate.d.ts +0 -4
  88. package/dist/esm/utils/validate.js +0 -47
  89. /package/bin/{patch.cjs → patch.js} +0 -0
  90. /package/{dist/commonjs → build}/models/common.js +0 -0
  91. /package/{dist/commonjs → build}/models/context.js +0 -0
  92. /package/{dist/commonjs → build}/models/error.d.ts +0 -0
  93. /package/{dist/commonjs → build}/models/error.js +0 -0
  94. /package/{dist/commonjs → build}/utils/grpc-reflection.d.ts +0 -0
package/dist/esm/index.js DELETED
@@ -1,274 +0,0 @@
1
- import _ from 'lodash';
2
- import { createGrpcAction, createRoot, getCredentialsMap } from './components/grpc.js';
3
- import { createMixedAction } from './components/mixed.js';
4
- import { createRestAction } from './components/rest.js';
5
- import { ANY_ACTION_SYMBOL } from './constants.js';
6
- import { getKeys, handleError } from './utils/common.js';
7
- import { overrideEndpoints } from './utils/overrideEndpoints/overrideEndpoints.js';
8
- export * from './utils/typed-api.js';
9
- export * from './utils/grpc-reflection.js';
10
- export { isRetryableGrpcError } from './utils/grpc.js';
11
- export * from './models/common.js';
12
- export * from './models/context.js';
13
- export * from './models/error.js';
14
- function isMixedActionConfig(actionConfig) {
15
- return typeof actionConfig === 'function';
16
- }
17
- function isRestActionConfig(actionConfig) {
18
- return Boolean(actionConfig.method);
19
- }
20
- function createApiAction(schema, config, serviceKey, actionName, api, grpcContext) {
21
- var _a;
22
- const serviceSchema = schema[serviceKey];
23
- if (!serviceSchema) {
24
- throw new config.ErrorConstructor(`Gateway config error. Service "${serviceKey}" have been not found.`, {
25
- code: 'SERVICE_NOT_FOUND',
26
- });
27
- }
28
- const action = serviceSchema.actions[actionName];
29
- if (!action) {
30
- throw new config.ErrorConstructor(`Gateway config error. Action "${serviceKey}.${actionName}" have been not found.`, {
31
- code: 'ACTION_NOT_FOUND',
32
- });
33
- }
34
- const serviceName = serviceSchema.serviceName || '';
35
- const installation = config.installation || '';
36
- const env = config.env || '';
37
- if (isMixedActionConfig(action)) {
38
- const resultServiceName = serviceName || serviceKey;
39
- return createMixedAction(action, api, resultServiceName, actionName, { config, grpcContext }, config.ErrorConstructor);
40
- }
41
- const endpointsConfig = _.get(serviceSchema.endpoints, [installation, env]);
42
- if (isRestActionConfig(action)) {
43
- return createRestAction(endpointsConfig, action, serviceKey, actionName, {
44
- serviceName,
45
- timeout: config.timeout,
46
- sendStats: config.sendStats,
47
- proxyHeaders: config.proxyHeaders,
48
- proxyDebugHeaders: config.proxyDebugHeaders,
49
- axiosConfig: config.axiosConfig,
50
- axiosInterceptors: config.axiosInterceptors,
51
- axiosRetryCondition: config.axiosRetryCondition,
52
- validationSchema: config.validationSchema,
53
- encodePathArgs: config.encodePathArgs,
54
- getAuthHeaders: config.getAuthHeaders,
55
- }, config.ErrorConstructor);
56
- }
57
- const grpcRecreateService = (_a = config.grpcRecreateService) !== null && _a !== void 0 ? _a : true;
58
- return createGrpcAction(grpcContext, endpointsConfig, action, serviceKey, actionName, {
59
- serviceName,
60
- timeout: config.timeout,
61
- sendStats: config.sendStats,
62
- proxyHeaders: config.proxyHeaders,
63
- proxyDebugHeaders: config.proxyDebugHeaders,
64
- grpcRetryCondition: config.grpcRetryCondition,
65
- grpcOptions: config.grpcOptions,
66
- grpcRecreateService,
67
- getAuthHeaders: config.getAuthHeaders,
68
- }, config.ErrorConstructor);
69
- }
70
- function generateGatewayApi(schema, config, grpcContext, baseApi) {
71
- const { installation, env } = config;
72
- if (!installation) {
73
- throw new config.ErrorConstructor('Gateway config error', {
74
- code: 'EMPTY_GATEWAY_INSTALLATION',
75
- });
76
- }
77
- if (!env) {
78
- throw new config.ErrorConstructor('Gateway config error', { code: 'EMPTY_GATEWAY_ENV' });
79
- }
80
- return Object.keys(schema).reduce((api, serviceKey) => {
81
- return _.set(api, serviceKey, Object.keys(schema[serviceKey].actions).reduce((serviceActions, actionName) => (Object.assign(Object.assign({}, serviceActions), { [actionName]: createApiAction(schema, config, serviceKey, actionName, baseApi, grpcContext) })), {}));
82
- }, {});
83
- }
84
- function generateGatewayApiController(schemasByScope, Api, config, controllerActions) {
85
- // eslint-disable-next-line complexity
86
- return async function gateway(req, res) {
87
- var _a, _b, _c;
88
- const { userId } = res.locals || {};
89
- const { service, action, scope = 'root' } = req.params;
90
- const withDebugHeaders = typeof config.withDebugHeaders === 'function'
91
- ? config.withDebugHeaders(req, res)
92
- : Boolean(config.withDebugHeaders);
93
- const onUnknownAction = config === null || config === void 0 ? void 0 : config.onUnknownAction;
94
- const onBeforeAction = config === null || config === void 0 ? void 0 : config.onBeforeAction;
95
- const onRequestSuccess = config === null || config === void 0 ? void 0 : config.onRequestSuccess;
96
- const onRequestFailed = config === null || config === void 0 ? void 0 : config.onRequestFailed;
97
- if (!Api || !Api[scope] || !Api[scope][service]) {
98
- if (onUnknownAction) {
99
- return onUnknownAction(req, res, {
100
- service,
101
- });
102
- }
103
- else {
104
- return res.status(404).send({
105
- status: 404,
106
- code: 'UNKNOWN_SERVICE',
107
- message: 'Unknown service',
108
- });
109
- }
110
- }
111
- if (!Api[scope][service][action]) {
112
- if (onUnknownAction) {
113
- return onUnknownAction(req, res, {
114
- service,
115
- action,
116
- });
117
- }
118
- else {
119
- return res.status(404).send({
120
- status: 404,
121
- code: 'UNKNOWN_SERVICE_ACTION',
122
- message: 'Unknown service action',
123
- });
124
- }
125
- }
126
- // Validation of private endpoints, preventing their invocation through the controller.
127
- if (_.startsWith(action, '_')) {
128
- return res.status(404).send({
129
- status: 404,
130
- code: 'UNKNOWN_SERVICE_ACTION',
131
- message: 'Unknown service action',
132
- });
133
- }
134
- if (controllerActions &&
135
- _.get(controllerActions, [scope]) !== ANY_ACTION_SYMBOL &&
136
- _.get(controllerActions, [scope, service]) !== ANY_ACTION_SYMBOL &&
137
- !_.get(controllerActions, [scope, service, action])) {
138
- return res.status(404).send({
139
- status: 404,
140
- code: 'UNKNOWN_SERVICE_ACTION',
141
- message: 'Unknown service action',
142
- });
143
- }
144
- const args = req.method === 'GET' ? req.query : req.body;
145
- try {
146
- const abortController = new AbortController();
147
- const handleCloseConnection = () => {
148
- abortController.abort();
149
- };
150
- req.connection.once('close', handleCloseConnection);
151
- const apiAction = Api[scope][service][action];
152
- if (onBeforeAction) {
153
- const actionConfig = (_c = (_b = (_a = schemasByScope[scope]) === null || _a === void 0 ? void 0 : _a[service]) === null || _b === void 0 ? void 0 : _b.actions) === null || _c === void 0 ? void 0 : _c[action];
154
- try {
155
- await onBeforeAction(req, res, scope, service, action, actionConfig);
156
- }
157
- catch (error) {
158
- handleError(config.ErrorConstructor, error, req.ctx, 'Before action handler error');
159
- throw { error, debugHeaders: {} };
160
- }
161
- }
162
- const { responseData, responseHeaders, debugHeaders } = await apiAction({
163
- requestId: req.id,
164
- headers: req.headers,
165
- ctx: req.ctx,
166
- args,
167
- authArgs: config.getAuthArgs(req, res),
168
- userId,
169
- abortSignal: abortController.signal,
170
- });
171
- req.connection.removeListener('close', handleCloseConnection);
172
- if (withDebugHeaders) {
173
- res.set(debugHeaders);
174
- }
175
- if (responseHeaders) {
176
- res.set(responseHeaders);
177
- }
178
- if (onRequestSuccess) {
179
- return onRequestSuccess(req, res, responseData);
180
- }
181
- else {
182
- return res.send(responseData);
183
- }
184
- }
185
- catch (respError) {
186
- const { error, debugHeaders } = respError;
187
- let responseError = error;
188
- if (withDebugHeaders) {
189
- res.set(debugHeaders);
190
- }
191
- else {
192
- responseError = _.omit(error, ['debug']);
193
- // Remove DebugInfo
194
- if (responseError.details) {
195
- _.forEach(responseError.details, function (value, key) {
196
- const DEBUG_INFO_TYPE = 'type.googleapis.com/google.rpc.DebugInfo';
197
- if ((value === null || value === void 0 ? void 0 : value['@type']) === DEBUG_INFO_TYPE) {
198
- responseError.details[key] = undefined;
199
- }
200
- });
201
- }
202
- }
203
- if (onRequestFailed) {
204
- return onRequestFailed(req, res, error);
205
- }
206
- else {
207
- return res.status(_.get(error, 'status', 500)).send(responseError);
208
- }
209
- }
210
- };
211
- }
212
- export function getGatewayControllers(schemasByScope, config) {
213
- var _a;
214
- const apiByScope = {};
215
- config.installation = config.installation || process.env.APP_INSTALLATION;
216
- config.env = config.env || process.env.APP_ENV;
217
- if (process.env.GATEWAY_ENDPOINTS_OVERRIDES) {
218
- try {
219
- // eslint-disable-next-line no-param-reassign
220
- schemasByScope = overrideEndpoints(schemasByScope, JSON.parse(process.env.GATEWAY_ENDPOINTS_OVERRIDES), config.installation, config.env);
221
- }
222
- catch (err) {
223
- console.warn('Error when parse GATEWAY_ENDPOINTS_OVERRIDES', err);
224
- }
225
- }
226
- const credentials = getCredentialsMap(config.caCertificatePath);
227
- for (const scope of getKeys(schemasByScope)) {
228
- apiByScope[scope] = generateGatewayApi(schemasByScope[scope], config, { root: createRoot(config.includeProtoRoots), credentials }, apiByScope);
229
- }
230
- const api = Object.assign({}, apiByScope);
231
- const rootScope = apiByScope.root;
232
- if (rootScope) {
233
- for (const rootService of getKeys(rootScope)) {
234
- const curScope = (_a = api[rootService]) !== null && _a !== void 0 ? _a : {};
235
- for (const rootAction of getKeys(rootScope[rootService])) {
236
- const rootServiceFunc = rootScope[rootService][rootAction];
237
- if (curScope[rootAction]) {
238
- for (const curScopeAction of getKeys(curScope[rootAction])) {
239
- rootServiceFunc[curScopeAction] = curScope[rootAction][curScopeAction];
240
- }
241
- }
242
- curScope[rootAction] = rootServiceFunc;
243
- }
244
- api[rootService] = curScope;
245
- }
246
- }
247
- const controllerActions = config.actions
248
- ? config.actions.reduce((acc, item) => {
249
- const [scope, service, action] = item.split('.');
250
- // Ignore option '*' for scopes
251
- if (scope === ANY_ACTION_SYMBOL) {
252
- return acc;
253
- }
254
- if (service === ANY_ACTION_SYMBOL) {
255
- _.set(acc, [scope], ANY_ACTION_SYMBOL);
256
- }
257
- else if (action === ANY_ACTION_SYMBOL) {
258
- if (acc[scope] !== ANY_ACTION_SYMBOL) {
259
- _.set(acc, [scope, service], ANY_ACTION_SYMBOL);
260
- }
261
- }
262
- else {
263
- _.set(acc, [scope, service, action], true);
264
- }
265
- return acc;
266
- }, {})
267
- : undefined;
268
- const controller = generateGatewayApiController(schemasByScope, api, config, controllerActions);
269
- return {
270
- controller,
271
- api,
272
- };
273
- }
274
- export default getGatewayControllers;
@@ -1,5 +0,0 @@
1
- export var GrpcReflection;
2
- (function (GrpcReflection) {
3
- GrpcReflection[GrpcReflection["OnFirstRequest"] = 0] = "OnFirstRequest";
4
- GrpcReflection[GrpcReflection["OnEveryRequest"] = 1] = "OnEveryRequest";
5
- })(GrpcReflection || (GrpcReflection = {}));
@@ -1 +0,0 @@
1
- export {};
@@ -1,12 +0,0 @@
1
- export interface AppErrorArgs {
2
- code?: string | number;
3
- details?: object;
4
- debug?: object;
5
- }
6
- export interface AppErrorWrapArgs extends AppErrorArgs {
7
- message?: string;
8
- }
9
- export interface AppErrorConstructor {
10
- new (message?: string, args?: AppErrorArgs): Error;
11
- wrap: (error: Error, args?: AppErrorWrapArgs) => Error;
12
- }
@@ -1 +0,0 @@
1
- export {};
@@ -1,3 +0,0 @@
1
- {
2
- "type": "module"
3
- }
@@ -1,24 +0,0 @@
1
- import axios from 'axios';
2
- import axiosRetry from 'axios-retry';
3
- import _ from 'lodash';
4
- import { DEFAULT_AXIOS_OPTIONS, DEFAULT_TIMEOUT } from '../constants.js';
5
- export function getAxiosClient(timeout = DEFAULT_TIMEOUT, retries = 0, customRetryCondition, axiosConfig = DEFAULT_AXIOS_OPTIONS, { request: reqInterceptors, response: resInterceptors } = {}) {
6
- const client = axios.create(Object.assign(Object.assign({}, axiosConfig), { timeout }));
7
- reqInterceptors === null || reqInterceptors === void 0 ? void 0 : reqInterceptors.forEach(({ callback, errorCallback }) => client.interceptors.request.use(callback, errorCallback));
8
- resInterceptors === null || resInterceptors === void 0 ? void 0 : resInterceptors.forEach(({ callback, errorCallback }) => client.interceptors.response.use(callback, errorCallback));
9
- axiosRetry(client, {
10
- retries,
11
- retryDelay: axiosRetry.exponentialDelay,
12
- retryCondition: (error) => {
13
- var _a;
14
- if (!error.config) {
15
- return false;
16
- }
17
- return ((_a = customRetryCondition === null || customRetryCondition === void 0 ? void 0 : customRetryCondition(error)) !== null && _a !== void 0 ? _a : (axiosRetry.isNetworkError(error) || axiosRetry.isRetryableError(error)));
18
- },
19
- onRetry: (retryCount, _error, requestConfig) => {
20
- _.set(requestConfig, ['headers', 'x-request-attempt'], retryCount);
21
- },
22
- });
23
- return client;
24
- }
@@ -1,48 +0,0 @@
1
- import _ from 'lodash';
2
- export function isExtendedActionEndpoint(endpoint) {
3
- return (endpoint === null || endpoint === void 0 ? void 0 : endpoint.path) !== undefined;
4
- }
5
- export function isExtendedGrpcActionEndpoint(endpoint) {
6
- return ((endpoint === null || endpoint === void 0 ? void 0 : endpoint.grpcOptions) !== undefined ||
7
- (endpoint === null || endpoint === void 0 ? void 0 : endpoint.insecure) !== undefined ||
8
- (endpoint === null || endpoint === void 0 ? void 0 : endpoint.secureWithoutRootCert) !== undefined);
9
- }
10
- export function isExtendedRestActionEndpoint(endpoint) {
11
- return (endpoint === null || endpoint === void 0 ? void 0 : endpoint.axiosConfig) !== undefined;
12
- }
13
- export function getKeys(obj) {
14
- return Object.keys(obj);
15
- }
16
- /**
17
- * This function should only use to sanitize debugHeaders that are creating in our code
18
- */
19
- export function sanitizeDebugHeaders(debugHeaders) {
20
- return _.omit(debugHeaders, ['x-api-request-body']);
21
- }
22
- export function getHeadersFromMetadata(metadata, prefix = '') {
23
- return Object.entries(metadata).reduce((headers, [key, values]) => {
24
- headers[`${prefix}${key}`] = values.filter((value) => typeof value === 'string').join(' ');
25
- return headers;
26
- }, {});
27
- }
28
- export function handleError(ErrorConstructor, error, ctx, message, extra) {
29
- if (error instanceof Error) {
30
- ctx.logError(message, ErrorConstructor.wrap(error), extra);
31
- }
32
- else if (typeof error === 'string') {
33
- ctx.logError(message, { error }, extra);
34
- }
35
- else {
36
- ctx.logError(message, error, extra);
37
- }
38
- }
39
- export const getProxyHeadersArgs = (serviceName, actionName, grpcConfig) => {
40
- const protopath = grpcConfig && 'protoPath' in grpcConfig ? grpcConfig.protoPath : undefined;
41
- const protokey = grpcConfig === null || grpcConfig === void 0 ? void 0 : grpcConfig.protoKey;
42
- return {
43
- service: serviceName,
44
- action: actionName,
45
- protopath,
46
- protokey,
47
- };
48
- };
@@ -1,4 +0,0 @@
1
- import { ApiActionConfig, ApiByScope, ContextApiWithRoot, GatewayRequest, GatewayResponse, SchemasByScope } from '../models/common.js';
2
- import { GatewayContext } from '../models/context.js';
3
- export type RequestContext<Context extends GatewayContext> = Omit<ApiActionConfig<Context, never>, 'args'>;
4
- export declare function generateContextApi<TFullSchema extends SchemasByScope, Context extends GatewayContext, Req extends GatewayRequest<Context>, Res extends GatewayResponse>(baseApi: ApiByScope<TFullSchema, Context, Req, Res>, requestContext: RequestContext<Context>): ContextApiWithRoot<TFullSchema>;
@@ -1,38 +0,0 @@
1
- import _ from 'lodash';
2
- import { getKeys } from './common.js';
3
- function createContextApiForScope(api, requestContext) {
4
- return _.reduce(api, (acc, service, serviceName) => {
5
- acc[serviceName] = _.reduce(service, (accService, action, actionName) => {
6
- accService[actionName] = (args) => action(Object.assign(Object.assign({}, requestContext), { args })).then((response) => response.responseData ||
7
- response
8
- .stream);
9
- return accService;
10
- }, {});
11
- return acc;
12
- }, {});
13
- }
14
- export function generateContextApi(baseApi, requestContext) {
15
- var _a;
16
- const contextApi = _.reduce(baseApi, (contextApi, scope, scopeName) => {
17
- contextApi[scopeName] = createContextApiForScope(scope, requestContext);
18
- return contextApi;
19
- }, {});
20
- const api = contextApi;
21
- const rootScope = contextApi.root;
22
- if (rootScope) {
23
- for (const rootService of getKeys(rootScope)) {
24
- const curScope = (_a = api[rootService]) !== null && _a !== void 0 ? _a : {};
25
- for (const rootAction of getKeys(rootScope[rootService])) {
26
- const rootServiceFunc = rootScope[rootService][rootAction];
27
- if (curScope[rootAction]) {
28
- for (const curScopeAction of getKeys(curScope[rootAction])) {
29
- rootServiceFunc[curScopeAction] = curScope[rootAction][curScopeAction];
30
- }
31
- }
32
- curScope[rootAction] = rootServiceFunc;
33
- }
34
- api[rootService] = curScope;
35
- }
36
- }
37
- return api;
38
- }
@@ -1,28 +0,0 @@
1
- import type { ChannelCredentials } from '@grpc/grpc-js';
2
- type DescriptorExtensionProto = string[] | {
3
- includeProtoRoots: string[];
4
- filenames: string[];
5
- };
6
- /**
7
- * @param actionEndpoint
8
- * @param protoKey
9
- * @param credentials
10
- * @param grpcOptions
11
- * @param descriptorExtensionProto
12
- * @returns Promise<protobufjs.Root>.
13
- * use toDescriptor for use with protoLoader.
14
- * use toJSON for get a JSON descriptor.
15
- */
16
- export declare function getCachedReflectionRoot(actionEndpoint: string, protoKey: string, credentials: ChannelCredentials, grpcOptions?: object, descriptorExtensionProto?: DescriptorExtensionProto): Promise<any>;
17
- /**
18
- * @param actionEndpoint
19
- * @param protoKey
20
- * @param credentials
21
- * @param grpcOptions
22
- * @param addToCache
23
- * @returns Promise<protobufjs.Root>.
24
- * use toDescriptor for use with protoLoader.
25
- * use toJSON for get a JSON descriptor.
26
- */
27
- export declare function getReflectionRoot(actionEndpoint: string, protoKey: string, credentials: ChannelCredentials, grpcOptions?: object, addToCache?: boolean): Promise<any>;
28
- export {};
@@ -1,72 +0,0 @@
1
- import _ from 'lodash';
2
- import protobufjs from 'protobufjs';
3
- import { patchProtoPathResolver } from './proto-path-resolver.js';
4
- const reflectionClientsMap = {};
5
- async function getCachedClient(actionEndpoint, credentials, grpcOptions, descriptorExtensionProto) {
6
- const cacheKey = [actionEndpoint, JSON.stringify([grpcOptions, descriptorExtensionProto])];
7
- let clientWithCache = _.get(reflectionClientsMap, cacheKey);
8
- if (!clientWithCache) {
9
- const grpcReflection = await import('grpc-reflection-js');
10
- let descriptorRoot;
11
- if (descriptorExtensionProto) {
12
- descriptorRoot = protobufjs.Root.fromJSON(
13
- // @ts-expect-error no typings for default export
14
- (await import('protobufjs/ext/descriptor/index.js')).default);
15
- if (Array.isArray(descriptorExtensionProto)) {
16
- descriptorRoot.loadSync(descriptorExtensionProto);
17
- }
18
- else {
19
- patchProtoPathResolver(descriptorRoot, descriptorExtensionProto.includeProtoRoots);
20
- descriptorRoot.loadSync(descriptorExtensionProto.filenames);
21
- }
22
- }
23
- const client = new grpcReflection.Client(actionEndpoint, credentials, grpcOptions, undefined,
24
- // @ts-ignore this parameter is present only in the patched version
25
- descriptorRoot);
26
- clientWithCache = { client, reflectionRootPromiseMap: {} };
27
- _.set(reflectionClientsMap, cacheKey, clientWithCache);
28
- }
29
- return clientWithCache;
30
- }
31
- /**
32
- * @param actionEndpoint
33
- * @param protoKey
34
- * @param credentials
35
- * @param grpcOptions
36
- * @param descriptorExtensionProto
37
- * @returns Promise<protobufjs.Root>.
38
- * use toDescriptor for use with protoLoader.
39
- * use toJSON for get a JSON descriptor.
40
- */
41
- export async function getCachedReflectionRoot(actionEndpoint, protoKey, credentials, grpcOptions, descriptorExtensionProto) {
42
- const { client, reflectionRootPromiseMap } = await getCachedClient(actionEndpoint, credentials, grpcOptions, descriptorExtensionProto);
43
- const cacheKey = [actionEndpoint, protoKey];
44
- let cachedRootPromise = _.get(reflectionRootPromiseMap, cacheKey);
45
- if (!cachedRootPromise) {
46
- cachedRootPromise = client.fileContainingSymbol(protoKey);
47
- _.set(reflectionRootPromiseMap, cacheKey, cachedRootPromise);
48
- cachedRootPromise.catch(() => {
49
- _.set(reflectionRootPromiseMap, cacheKey, undefined);
50
- });
51
- }
52
- const loadedRoot = await cachedRootPromise;
53
- return loadedRoot;
54
- }
55
- /**
56
- * @param actionEndpoint
57
- * @param protoKey
58
- * @param credentials
59
- * @param grpcOptions
60
- * @param addToCache
61
- * @returns Promise<protobufjs.Root>.
62
- * use toDescriptor for use with protoLoader.
63
- * use toJSON for get a JSON descriptor.
64
- */
65
- export async function getReflectionRoot(actionEndpoint, protoKey, credentials, grpcOptions, addToCache) {
66
- const { client, reflectionRootPromiseMap } = await getCachedClient(actionEndpoint, credentials, grpcOptions);
67
- const loadedRoot = await client.fileContainingSymbol(protoKey);
68
- if (addToCache) {
69
- _.set(reflectionRootPromiseMap, [actionEndpoint, protoKey], Promise.resolve(loadedRoot));
70
- }
71
- return loadedRoot;
72
- }
@@ -1,15 +0,0 @@
1
- import * as grpc from '@grpc/grpc-js';
2
- import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream } from '@grpc/grpc-js';
3
- import protobufjs from 'protobufjs';
4
- export declare function decodeAnyMessageRecursively(root: protobufjs.Root, message?: unknown, decodeAnyMessageProtoLoaderOptions?: protobufjs.IConversionOptions): unknown;
5
- export declare function isRetryableGrpcError(error?: grpc.ServiceError): boolean;
6
- export declare function isRecreateServiceError(error?: grpc.ServiceError): boolean;
7
- export type ListenForAbortArgs = {
8
- signal?: AbortSignal;
9
- config: {
10
- abortOnClientDisconnect?: boolean;
11
- };
12
- call: ClientUnaryCall | ClientReadableStream<unknown> | ClientWritableStream<unknown> | ClientDuplexStream<unknown, unknown>;
13
- reject: (err: Error) => void;
14
- };
15
- export declare function listenForAbort({ signal, config, call, reject }: ListenForAbortArgs): () => void;
@@ -1,72 +0,0 @@
1
- /* eslint-disable camelcase */
2
- import { DEFAULT_PROTO_LOADER_OPTIONS, RECREATE_SERVICE_CODES, RETRYABLE_STATUS_CODES, } from '../constants.js';
3
- import { GrpcError } from './parse-error.js';
4
- function isEncodedMessage(message) {
5
- return Boolean(message.type_url && message.value);
6
- }
7
- export function decodeAnyMessageRecursively(root, message, decodeAnyMessageProtoLoaderOptions) {
8
- if (!message || typeof message !== 'object') {
9
- return message;
10
- }
11
- if (Array.isArray(message)) {
12
- return message.map((innerMessage) => decodeAnyMessageRecursively(root, innerMessage, decodeAnyMessageProtoLoaderOptions));
13
- }
14
- if (typeof message === 'object' && !isEncodedMessage(message)) {
15
- return Object.entries(message).reduce((res, [key, value]) => {
16
- res[key] = decodeAnyMessageRecursively(root, value, decodeAnyMessageProtoLoaderOptions);
17
- return res;
18
- }, {});
19
- }
20
- const lastSlashIndex = message.type_url.lastIndexOf('/');
21
- if (lastSlashIndex < 0) {
22
- return message;
23
- }
24
- const typeName = message.type_url.substring(lastSlashIndex + 1);
25
- try {
26
- const type = root.lookupType(typeName);
27
- const decodedMessage = type.toObject(type.decode(message.value), Object.assign(Object.assign({}, DEFAULT_PROTO_LOADER_OPTIONS), decodeAnyMessageProtoLoaderOptions));
28
- if (typeof decodedMessage === 'object' &&
29
- !Array.isArray(decodedMessage) &&
30
- !decodedMessage['@type']) {
31
- Object.assign(decodedMessage, { '@type': message.type_url });
32
- }
33
- return decodeAnyMessageRecursively(root, decodedMessage, decodeAnyMessageProtoLoaderOptions);
34
- }
35
- catch (error) {
36
- console.error(`Failed to lookup ${typeName}`, error);
37
- return message;
38
- }
39
- }
40
- export function isRetryableGrpcError(error) {
41
- if (!error) {
42
- return false;
43
- }
44
- return RETRYABLE_STATUS_CODES.includes(error.code);
45
- }
46
- export function isRecreateServiceError(error) {
47
- if (!error) {
48
- return false;
49
- }
50
- return RECREATE_SERVICE_CODES.includes(error.code);
51
- }
52
- export function listenForAbort({ signal, config, call, reject }) {
53
- if (!signal || !config.abortOnClientDisconnect) {
54
- return () => null;
55
- }
56
- const handleAbortSignal = () => {
57
- call.cancel();
58
- reject(new GrpcError('Request was cancelled.', {
59
- status: 499,
60
- code: 'REQUEST_WAS_CANCELLED',
61
- message: 'Request was cancelled because the original connection was disconnected.',
62
- }));
63
- };
64
- if (signal.aborted) {
65
- handleAbortSignal();
66
- return () => null;
67
- }
68
- signal.addEventListener('abort', handleAbortSignal);
69
- return () => {
70
- signal.removeEventListener('abort', handleAbortSignal);
71
- };
72
- }
@@ -1,2 +0,0 @@
1
- import { overrideEndpoints } from './overrideEndpoints.js';
2
- export default overrideEndpoints;
@@ -1,2 +0,0 @@
1
- import { overrideEndpoints } from './overrideEndpoints.js';
2
- export default overrideEndpoints;