@bleedingdev/modern-js-bff-core 3.9.0-ultramodern.3 → 3.9.0-ultramodern.5

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 (49) hide show
  1. package/dist/cjs/client/generateClient.js +67 -138
  2. package/dist/cjs/index.js +25 -101
  3. package/dist/esm/client/generateClient.mjs +65 -139
  4. package/dist/esm/index.mjs +0 -4
  5. package/dist/esm-node/client/generateClient.mjs +65 -139
  6. package/dist/esm-node/index.mjs +0 -4
  7. package/dist/types/client/generateClient.d.ts +24 -1
  8. package/dist/types/index.d.ts +0 -4
  9. package/package.json +5 -12
  10. package/dist/cjs/adapter-kit/index.js +0 -144
  11. package/dist/cjs/adapter-kit/parity-scenarios/cross-project-denial.js +0 -55
  12. package/dist/cjs/adapter-kit/parity-scenarios/envelope.js +0 -128
  13. package/dist/cjs/adapter-kit/parity-scenarios/operation-context.js +0 -152
  14. package/dist/cjs/adapter-kit/parity-scenarios/schema.js +0 -109
  15. package/dist/cjs/adapter-kit/parity-scenarios/shared.js +0 -71
  16. package/dist/cjs/adapter-kit/parity.js +0 -204
  17. package/dist/cjs/security/crossProjectPolicy.js +0 -309
  18. package/dist/cjs/security/operationContracts.js +0 -183
  19. package/dist/cjs/security/resolveCrossProjectPolicy.js +0 -65
  20. package/dist/esm/adapter-kit/index.mjs +0 -79
  21. package/dist/esm/adapter-kit/parity-scenarios/cross-project-denial.mjs +0 -17
  22. package/dist/esm/adapter-kit/parity-scenarios/envelope.mjs +0 -90
  23. package/dist/esm/adapter-kit/parity-scenarios/operation-context.mjs +0 -111
  24. package/dist/esm/adapter-kit/parity-scenarios/schema.mjs +0 -71
  25. package/dist/esm/adapter-kit/parity-scenarios/shared.mjs +0 -21
  26. package/dist/esm/adapter-kit/parity.mjs +0 -148
  27. package/dist/esm/security/crossProjectPolicy.mjs +0 -259
  28. package/dist/esm/security/operationContracts.mjs +0 -127
  29. package/dist/esm/security/resolveCrossProjectPolicy.mjs +0 -27
  30. package/dist/esm-node/adapter-kit/index.mjs +0 -80
  31. package/dist/esm-node/adapter-kit/parity-scenarios/cross-project-denial.mjs +0 -18
  32. package/dist/esm-node/adapter-kit/parity-scenarios/envelope.mjs +0 -91
  33. package/dist/esm-node/adapter-kit/parity-scenarios/operation-context.mjs +0 -112
  34. package/dist/esm-node/adapter-kit/parity-scenarios/schema.mjs +0 -72
  35. package/dist/esm-node/adapter-kit/parity-scenarios/shared.mjs +0 -22
  36. package/dist/esm-node/adapter-kit/parity.mjs +0 -149
  37. package/dist/esm-node/security/crossProjectPolicy.mjs +0 -260
  38. package/dist/esm-node/security/operationContracts.mjs +0 -130
  39. package/dist/esm-node/security/resolveCrossProjectPolicy.mjs +0 -28
  40. package/dist/types/adapter-kit/index.d.ts +0 -90
  41. package/dist/types/adapter-kit/parity-scenarios/cross-project-denial.d.ts +0 -2
  42. package/dist/types/adapter-kit/parity-scenarios/envelope.d.ts +0 -2
  43. package/dist/types/adapter-kit/parity-scenarios/operation-context.d.ts +0 -3
  44. package/dist/types/adapter-kit/parity-scenarios/schema.d.ts +0 -2
  45. package/dist/types/adapter-kit/parity-scenarios/shared.d.ts +0 -32
  46. package/dist/types/adapter-kit/parity.d.ts +0 -43
  47. package/dist/types/security/crossProjectPolicy.d.ts +0 -110
  48. package/dist/types/security/operationContracts.d.ts +0 -84
  49. package/dist/types/security/resolveCrossProjectPolicy.d.ts +0 -39
@@ -28,28 +28,25 @@ var __webpack_require__ = {};
28
28
  var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
30
  __webpack_require__.d(__webpack_exports__, {
31
+ ClientCodegenError: ()=>ClientCodegenError,
31
32
  INNER_CLIENT_REQUEST_CREATOR: ()=>INNER_CLIENT_REQUEST_CREATOR,
32
33
  generateClient: ()=>generateClient
33
34
  });
35
+ const external_node_url_namespaceObject = require("node:url");
34
36
  const external_path_namespaceObject = require("path");
35
37
  const index_js_namespaceObject = require("../router/index.js");
36
- const operationContracts_js_namespaceObject = require("../security/operationContracts.js");
37
38
  const external_result_js_namespaceObject = require("./result.js");
38
- const getPackageInfo = (appDir)=>{
39
- try {
40
- const packageJsonPath = external_path_namespaceObject.resolve(appDir, './package.json');
41
- const packageJson = require(packageJsonPath);
42
- return {
43
- name: packageJson.name,
44
- version: packageJson.version
45
- };
46
- } catch (error) {
47
- return {};
39
+ class ClientCodegenError extends Error {
40
+ constructor(plugin, cause){
41
+ super(`BFF client code-generation plugin failed: ${plugin}`, {
42
+ cause
43
+ });
44
+ this.name = 'ClientCodegenError';
48
45
  }
49
- };
46
+ }
50
47
  const INNER_CLIENT_REQUEST_CREATOR = '@modern-js/plugin-bff/client';
51
- const generateClient = async ({ appDir, resourcePath, apiDir, lambdaDir, prefix, port, target, requestCreator, fetcher, requireResolve = require.resolve, httpMethodDecider, domain, requestId })=>{
52
- requestCreator = requestCreator || INNER_CLIENT_REQUEST_CREATOR;
48
+ const generateClient = async (options)=>{
49
+ const { appDir, resourcePath, apiDir, lambdaDir, prefix, port, target, fetcher, requireResolve = require.resolve, httpMethodDecider, domain, requestId, clientCodegenPlugin } = options;
53
50
  const apiRouter = new index_js_namespaceObject.ApiRouter({
54
51
  appDir,
55
52
  apiDir,
@@ -59,136 +56,68 @@ const generateClient = async ({ appDir, resourcePath, apiDir, lambdaDir, prefix,
59
56
  });
60
57
  const handlerInfos = await apiRouter.getSingleModuleHandlers(resourcePath);
61
58
  if (!handlerInfos) return (0, external_result_js_namespaceObject.Err)(`generate client error: Cannot require module ${resourcePath}`);
62
- const normalizedRequestId = requestId || 'default';
63
- const operationVersion = (0, operationContracts_js_namespaceObject.deriveOperationVersion)(getPackageInfo(appDir).version);
64
- const operationContracts = (0, operationContracts_js_namespaceObject.buildOperationContractMap)({
65
- handlers: handlerInfos,
66
- requestId: normalizedRequestId,
67
- operationVersion
68
- });
69
- const operationEntries = handlerInfos.map((handlerInfo)=>{
70
- const upperHttpMethod = handlerInfo.httpMethod.toUpperCase();
71
- const contract = operationContracts[`${upperHttpMethod}:${handlerInfo.routePath}`];
72
- return {
73
- name: handlerInfo.name,
74
- httpMethod: upperHttpMethod,
75
- routePath: handlerInfo.routePath,
76
- schemaHash: contract?.schemaHash ?? ''
77
- };
78
- }).sort((a, b)=>{
79
- const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
80
- const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
81
- return keyA.localeCompare(keyB);
82
- });
83
- const schemaHash = (0, operationContracts_js_namespaceObject.createOperationSchemaHash)(operationEntries, normalizedRequestId);
84
- let hasUploadHandler = false;
85
- let handlersCode = '';
86
- for (const handlerInfo of handlerInfos){
87
- const { name, httpMethod, routePath, action } = handlerInfo;
88
- let exportStatement = `var ${name} =`;
89
- if ('default' === name.toLowerCase()) exportStatement = 'default';
90
- const upperHttpMethod = httpMethod.toUpperCase();
91
- const operationSchemaHash = operationContracts[`${upperHttpMethod}:${routePath}`]?.schemaHash ?? '';
92
- const operationContext = {
93
- operationId: name,
94
- routePath,
95
- method: upperHttpMethod,
96
- schemaHash: operationSchemaHash,
97
- operationVersion
98
- };
99
- if ('upload' === action) {
100
- hasUploadHandler = true;
101
- const uploadOptions = {
102
- path: routePath,
103
- ...domain ? {
104
- domain
105
- } : {},
106
- ...requestId ? {
107
- requestId
108
- } : {},
109
- ...requestId ? {
110
- operationContext
111
- } : {}
59
+ const draft = {
60
+ requestCreator: options.requestCreator || INNER_CLIENT_REQUEST_CREATOR,
61
+ imports: fetcher ? [
62
+ `import { fetch } from ${JSON.stringify(fetcher)};`
63
+ ] : [],
64
+ statements: [],
65
+ handlers: handlerInfos.map((handlerInfo)=>{
66
+ const optionProperties = [
67
+ `path: ${JSON.stringify(handlerInfo.routePath)}`
68
+ ];
69
+ if ('upload' !== handlerInfo.action) {
70
+ const portExpression = 'server' === target ? `process.env.PORT || ${String(port)}` : String(port);
71
+ optionProperties.push(`method: ${JSON.stringify(handlerInfo.httpMethod.toUpperCase())}`, `port: ${portExpression}`, `httpMethodDecider: ${JSON.stringify(httpMethodDecider || 'functionName')}`);
72
+ }
73
+ if (domain) optionProperties.push(`domain: ${JSON.stringify(domain)}`);
74
+ if (fetcher && 'upload' !== handlerInfo.action) optionProperties.push('fetch');
75
+ if (requestId) optionProperties.push(`requestId: ${JSON.stringify(requestId)}`);
76
+ return {
77
+ handlerInfo,
78
+ optionProperties
112
79
  };
113
- handlersCode += `export ${exportStatement} createUploader(${JSON.stringify(uploadOptions)});
114
- `;
115
- continue;
116
- }
117
- const portExpression = 'server' === target ? `process.env.PORT || ${String(port)}` : String(port);
118
- const requestOptionProperties = [
119
- `path: ${JSON.stringify(routePath)}`,
120
- `method: ${JSON.stringify(upperHttpMethod)}`,
121
- `port: ${portExpression}`,
122
- `httpMethodDecider: ${JSON.stringify(httpMethodDecider ? httpMethodDecider : 'functionName')}`
123
- ];
124
- if (domain) requestOptionProperties.push(`domain: ${JSON.stringify(domain)}`);
125
- if (fetcher) requestOptionProperties.push('fetch');
126
- if (requestId) requestOptionProperties.push(`requestId: ${JSON.stringify(requestId)}`);
127
- requestOptionProperties.push(`operationContext: ${JSON.stringify(operationContext)}`);
128
- handlersCode += `export ${exportStatement} createRequest({ ${requestOptionProperties.join(', ')} });
129
- `;
80
+ })
81
+ };
82
+ if (clientCodegenPlugin) try {
83
+ const specifier = clientCodegenPlugin.startsWith('.') ? external_path_namespaceObject.resolve(appDir, clientCodegenPlugin) : clientCodegenPlugin;
84
+ const resolved = requireResolve(specifier, {
85
+ paths: [
86
+ appDir
87
+ ]
88
+ });
89
+ const extension = await import((0, external_node_url_namespaceObject.pathToFileURL)(resolved).href);
90
+ const modifyClient = extension.modifyClient ?? extension.default?.modifyClient;
91
+ if ('function' != typeof modifyClient) throw new TypeError('The module must export a modifyClient function.');
92
+ await modifyClient(draft, {
93
+ options,
94
+ handlerInfos
95
+ });
96
+ } catch (cause) {
97
+ throw new ClientCodegenError(clientCodegenPlugin, cause);
130
98
  }
131
- const serializedRequestCreator = JSON.stringify(requestCreator);
132
- const serializedFetcher = fetcher ? JSON.stringify(fetcher) : void 0;
133
- const namedRequestImports = `createRequest${hasUploadHandler ? ', createUploader' : ''}`;
134
- const importCode = requestId ? `import * as requestRuntime from ${serializedRequestCreator};
135
- const { ${namedRequestImports} } = requestRuntime;
136
- ${serializedFetcher ? `import { fetch } from ${serializedFetcher};\n` : ''}` : `import { ${namedRequestImports} } from ${serializedRequestCreator};
137
- ${serializedFetcher ? `import { fetch } from ${serializedFetcher};\n` : ''}`;
138
- const bootstrapCode = requestId ? `export const initProducerClient = (options = {}) => {
139
- const configure = requestRuntime.configure;
140
- if (typeof configure !== 'function') {
141
- console.warn('[modernjs] Compatibility request creator path does not expose configure(); use default @modern-js/create-request or migrate the compatibility path.');
142
- return undefined;
143
- }
144
- const defaultSecureOptions = {
145
- requestId: ${JSON.stringify(requestId)},
146
- requireEnvelope: true,
147
- identityBinding: {
148
- enabled: true,
149
- strict: true,
150
- },
151
- operationContract: {
152
- enabled: true,
153
- strict: true,
154
- requireSchemaHash: true,
155
- requireOperationVersion: true,
156
- },
157
- };
158
- return configure({
159
- ...defaultSecureOptions,
160
- ...options,
161
- identityBinding: {
162
- ...defaultSecureOptions.identityBinding,
163
- ...(options && options.identityBinding ? options.identityBinding : {}),
164
- },
165
- operationContract: {
166
- ...defaultSecureOptions.operationContract,
167
- ...(options && options.operationContract ? options.operationContract : {}),
168
- },
169
- });
170
- };
171
- ` : '';
172
- const manifestCode = `export const operationVersion = ${String(operationVersion)};
173
- export const operationSchemaHash = '${schemaHash}';
174
- export const operationManifest = ${JSON.stringify({
175
- operationVersion,
176
- schemaHash,
177
- operations: operationEntries
178
- }, null, 2)};
179
- `;
180
- const generatedParts = [
181
- importCode.trimEnd(),
182
- bootstrapCode.trimEnd(),
183
- manifestCode.trimEnd(),
184
- handlersCode.trimEnd()
185
- ].filter(Boolean);
186
- return (0, external_result_js_namespaceObject.Ok)(`${generatedParts.join('\n\n')}
187
- `);
99
+ const hasUploadHandler = handlerInfos.some((info)=>'upload' === info.action);
100
+ const requestImports = `createRequest${hasUploadHandler ? ', createUploader' : ''}`;
101
+ const importCode = [
102
+ `import { ${requestImports} } from ${JSON.stringify(draft.requestCreator)};`,
103
+ ...draft.imports
104
+ ].join('\n');
105
+ const handlersCode = draft.handlers.map(({ handlerInfo, optionProperties })=>{
106
+ const exportStatement = 'default' === handlerInfo.name.toLowerCase() ? 'default' : `var ${handlerInfo.name} =`;
107
+ const creator = 'upload' === handlerInfo.action ? 'createUploader' : 'createRequest';
108
+ return `export ${exportStatement} ${creator}({ ${optionProperties.join(', ')} });`;
109
+ }).join('\n');
110
+ return (0, external_result_js_namespaceObject.Ok)(`${[
111
+ importCode,
112
+ ...draft.statements,
113
+ handlersCode
114
+ ].filter(Boolean).join('\n\n')}\n`);
188
115
  };
116
+ exports.ClientCodegenError = __webpack_exports__.ClientCodegenError;
189
117
  exports.INNER_CLIENT_REQUEST_CREATOR = __webpack_exports__.INNER_CLIENT_REQUEST_CREATOR;
190
118
  exports.generateClient = __webpack_exports__.generateClient;
191
119
  for(var __rspack_i in __webpack_exports__)if (-1 === [
120
+ "ClientCodegenError",
192
121
  "INNER_CLIENT_REQUEST_CREATOR",
193
122
  "generateClient"
194
123
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
package/dist/cjs/index.js CHANGED
@@ -1,8 +1,5 @@
1
1
  "use strict";
2
2
  var __webpack_modules__ = {
3
- "./adapter-kit" (module) {
4
- module.exports = require("./adapter-kit/index.js");
5
- },
6
3
  "./api" (module) {
7
4
  module.exports = require("./api.js");
8
5
  },
@@ -18,15 +15,6 @@ var __webpack_modules__ = {
18
15
  "./router" (module) {
19
16
  module.exports = require("./router/index.js");
20
17
  },
21
- "./security/crossProjectPolicy" (module) {
22
- module.exports = require("./security/crossProjectPolicy.js");
23
- },
24
- "./security/operationContracts" (module) {
25
- module.exports = require("./security/operationContracts.js");
26
- },
27
- "./security/resolveCrossProjectPolicy" (module) {
28
- module.exports = require("./security/resolveCrossProjectPolicy.js");
29
- },
30
18
  "./types" (module) {
31
19
  module.exports = require("./types.js");
32
20
  },
@@ -81,75 +69,10 @@ function __webpack_require__(moduleId) {
81
69
  var __webpack_exports__ = {};
82
70
  (()=>{
83
71
  __webpack_require__.r(__webpack_exports__);
84
- var _adapter_kit__rspack_import_0 = __webpack_require__("./adapter-kit");
85
- var __rspack_reexport = {};
86
- for(const __rspack_import_key in _adapter_kit__rspack_import_0)if ([
87
- "HttpError",
88
- "registerPaths",
89
- "createStorage",
90
- "isWithMetaHandler",
91
- "default",
92
- "HANDLER_WITH_META",
93
- "ValidationError",
94
- "getRelativeRuntimePath",
95
- "INPUT_PARAMS_DECIDER",
96
- "isInputParamsDeciderHandler",
97
- "Api"
98
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_adapter_kit__rspack_import_0[__rspack_import_key];
99
- __webpack_require__.d(__webpack_exports__, __rspack_reexport);
100
- var _api__rspack_import_1 = __webpack_require__("./api");
101
- var _client__rspack_import_2 = __webpack_require__("./client");
102
- var __rspack_reexport = {};
103
- for(const __rspack_import_key in _client__rspack_import_2)if ([
104
- "HttpError",
105
- "registerPaths",
106
- "createStorage",
107
- "isWithMetaHandler",
108
- "default",
109
- "HANDLER_WITH_META",
110
- "ValidationError",
111
- "getRelativeRuntimePath",
112
- "INPUT_PARAMS_DECIDER",
113
- "isInputParamsDeciderHandler",
114
- "Api"
115
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_client__rspack_import_2[__rspack_import_key];
116
- __webpack_require__.d(__webpack_exports__, __rspack_reexport);
117
- var _errors_http__rspack_import_3 = __webpack_require__("./errors/http");
118
- var _operators_http__rspack_import_4 = __webpack_require__("./operators/http");
119
- var __rspack_reexport = {};
120
- for(const __rspack_import_key in _operators_http__rspack_import_4)if ([
121
- "HttpError",
122
- "registerPaths",
123
- "createStorage",
124
- "isWithMetaHandler",
125
- "default",
126
- "HANDLER_WITH_META",
127
- "ValidationError",
128
- "getRelativeRuntimePath",
129
- "INPUT_PARAMS_DECIDER",
130
- "isInputParamsDeciderHandler",
131
- "Api"
132
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_operators_http__rspack_import_4[__rspack_import_key];
133
- __webpack_require__.d(__webpack_exports__, __rspack_reexport);
134
- var _router__rspack_import_5 = __webpack_require__("./router");
135
- var __rspack_reexport = {};
136
- for(const __rspack_import_key in _router__rspack_import_5)if ([
137
- "HttpError",
138
- "registerPaths",
139
- "createStorage",
140
- "isWithMetaHandler",
141
- "default",
142
- "HANDLER_WITH_META",
143
- "ValidationError",
144
- "getRelativeRuntimePath",
145
- "INPUT_PARAMS_DECIDER",
146
- "isInputParamsDeciderHandler",
147
- "Api"
148
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_router__rspack_import_5[__rspack_import_key];
149
- __webpack_require__.d(__webpack_exports__, __rspack_reexport);
150
- var _security_crossProjectPolicy__rspack_import_6 = __webpack_require__("./security/crossProjectPolicy");
72
+ var _api__rspack_import_0 = __webpack_require__("./api");
73
+ var _client__rspack_import_1 = __webpack_require__("./client");
151
74
  var __rspack_reexport = {};
152
- for(const __rspack_import_key in _security_crossProjectPolicy__rspack_import_6)if ([
75
+ for(const __rspack_import_key in _client__rspack_import_1)if ([
153
76
  "HttpError",
154
77
  "registerPaths",
155
78
  "createStorage",
@@ -161,11 +84,12 @@ var __webpack_exports__ = {};
161
84
  "INPUT_PARAMS_DECIDER",
162
85
  "isInputParamsDeciderHandler",
163
86
  "Api"
164
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_security_crossProjectPolicy__rspack_import_6[__rspack_import_key];
87
+ ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_client__rspack_import_1[__rspack_import_key];
165
88
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
166
- var _security_operationContracts__rspack_import_7 = __webpack_require__("./security/operationContracts");
89
+ var _errors_http__rspack_import_2 = __webpack_require__("./errors/http");
90
+ var _operators_http__rspack_import_3 = __webpack_require__("./operators/http");
167
91
  var __rspack_reexport = {};
168
- for(const __rspack_import_key in _security_operationContracts__rspack_import_7)if ([
92
+ for(const __rspack_import_key in _operators_http__rspack_import_3)if ([
169
93
  "HttpError",
170
94
  "registerPaths",
171
95
  "createStorage",
@@ -177,11 +101,11 @@ var __webpack_exports__ = {};
177
101
  "INPUT_PARAMS_DECIDER",
178
102
  "isInputParamsDeciderHandler",
179
103
  "Api"
180
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_security_operationContracts__rspack_import_7[__rspack_import_key];
104
+ ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_operators_http__rspack_import_3[__rspack_import_key];
181
105
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
182
- var _security_resolveCrossProjectPolicy__rspack_import_8 = __webpack_require__("./security/resolveCrossProjectPolicy");
106
+ var _router__rspack_import_4 = __webpack_require__("./router");
183
107
  var __rspack_reexport = {};
184
- for(const __rspack_import_key in _security_resolveCrossProjectPolicy__rspack_import_8)if ([
108
+ for(const __rspack_import_key in _router__rspack_import_4)if ([
185
109
  "HttpError",
186
110
  "registerPaths",
187
111
  "createStorage",
@@ -193,11 +117,11 @@ var __webpack_exports__ = {};
193
117
  "INPUT_PARAMS_DECIDER",
194
118
  "isInputParamsDeciderHandler",
195
119
  "Api"
196
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_security_resolveCrossProjectPolicy__rspack_import_8[__rspack_import_key];
120
+ ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_router__rspack_import_4[__rspack_import_key];
197
121
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
198
- var _types__rspack_import_9 = __webpack_require__("./types");
122
+ var _types__rspack_import_5 = __webpack_require__("./types");
199
123
  var __rspack_reexport = {};
200
- for(const __rspack_import_key in _types__rspack_import_9)if ([
124
+ for(const __rspack_import_key in _types__rspack_import_5)if ([
201
125
  "HttpError",
202
126
  "registerPaths",
203
127
  "createStorage",
@@ -209,20 +133,20 @@ var __webpack_exports__ = {};
209
133
  "INPUT_PARAMS_DECIDER",
210
134
  "isInputParamsDeciderHandler",
211
135
  "Api"
212
- ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_types__rspack_import_9[__rspack_import_key];
136
+ ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_types__rspack_import_5[__rspack_import_key];
213
137
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
214
- var _utils__rspack_import_10 = __webpack_require__("./utils?637c");
138
+ var _utils__rspack_import_6 = __webpack_require__("./utils?637c");
215
139
  __webpack_require__.d(__webpack_exports__, {
216
- Api: ()=>_api__rspack_import_1.Api,
217
- HANDLER_WITH_META: ()=>_utils__rspack_import_10.HANDLER_WITH_META,
218
- HttpError: ()=>_errors_http__rspack_import_3.HttpError,
219
- INPUT_PARAMS_DECIDER: ()=>_utils__rspack_import_10.INPUT_PARAMS_DECIDER,
220
- ValidationError: ()=>_errors_http__rspack_import_3.ValidationError,
221
- createStorage: ()=>_utils__rspack_import_10.createStorage,
222
- getRelativeRuntimePath: ()=>_utils__rspack_import_10.getRelativeRuntimePath,
223
- isInputParamsDeciderHandler: ()=>_utils__rspack_import_10.isInputParamsDeciderHandler,
224
- isWithMetaHandler: ()=>_utils__rspack_import_10.isWithMetaHandler,
225
- registerPaths: ()=>_utils__rspack_import_10.registerPaths
140
+ Api: ()=>_api__rspack_import_0.Api,
141
+ HANDLER_WITH_META: ()=>_utils__rspack_import_6.HANDLER_WITH_META,
142
+ HttpError: ()=>_errors_http__rspack_import_2.HttpError,
143
+ INPUT_PARAMS_DECIDER: ()=>_utils__rspack_import_6.INPUT_PARAMS_DECIDER,
144
+ ValidationError: ()=>_errors_http__rspack_import_2.ValidationError,
145
+ createStorage: ()=>_utils__rspack_import_6.createStorage,
146
+ getRelativeRuntimePath: ()=>_utils__rspack_import_6.getRelativeRuntimePath,
147
+ isInputParamsDeciderHandler: ()=>_utils__rspack_import_6.isInputParamsDeciderHandler,
148
+ isWithMetaHandler: ()=>_utils__rspack_import_6.isWithMetaHandler,
149
+ registerPaths: ()=>_utils__rspack_import_6.registerPaths
226
150
  });
227
151
  })();
228
152
  exports.Api = __webpack_exports__.Api;
@@ -1,22 +1,18 @@
1
+ import { pathToFileURL } from "node:url";
1
2
  import { ApiRouter } from "../router/index.mjs";
2
- import { buildOperationContractMap, createOperationSchemaHash, deriveOperationVersion } from "../security/operationContracts.mjs";
3
3
  import { Err, Ok } from "./result.mjs";
4
4
  import * as __rspack_external_path from "path";
5
- const getPackageInfo = (appDir)=>{
6
- try {
7
- const packageJsonPath = __rspack_external_path.resolve(appDir, './package.json');
8
- const packageJson = require(packageJsonPath);
9
- return {
10
- name: packageJson.name,
11
- version: packageJson.version
12
- };
13
- } catch (error) {
14
- return {};
5
+ class ClientCodegenError extends Error {
6
+ constructor(plugin, cause){
7
+ super(`BFF client code-generation plugin failed: ${plugin}`, {
8
+ cause
9
+ });
10
+ this.name = 'ClientCodegenError';
15
11
  }
16
- };
12
+ }
17
13
  const INNER_CLIENT_REQUEST_CREATOR = '@modern-js/plugin-bff/client';
18
- const generateClient = async ({ appDir, resourcePath, apiDir, lambdaDir, prefix, port, target, requestCreator, fetcher, requireResolve = require.resolve, httpMethodDecider, domain, requestId })=>{
19
- requestCreator = requestCreator || INNER_CLIENT_REQUEST_CREATOR;
14
+ const generateClient = async (options)=>{
15
+ const { appDir, resourcePath, apiDir, lambdaDir, prefix, port, target, fetcher, requireResolve = require.resolve, httpMethodDecider, domain, requestId, clientCodegenPlugin } = options;
20
16
  const apiRouter = new ApiRouter({
21
17
  appDir,
22
18
  apiDir,
@@ -26,131 +22,61 @@ const generateClient = async ({ appDir, resourcePath, apiDir, lambdaDir, prefix,
26
22
  });
27
23
  const handlerInfos = await apiRouter.getSingleModuleHandlers(resourcePath);
28
24
  if (!handlerInfos) return Err(`generate client error: Cannot require module ${resourcePath}`);
29
- const normalizedRequestId = requestId || 'default';
30
- const operationVersion = deriveOperationVersion(getPackageInfo(appDir).version);
31
- const operationContracts = buildOperationContractMap({
32
- handlers: handlerInfos,
33
- requestId: normalizedRequestId,
34
- operationVersion
35
- });
36
- const operationEntries = handlerInfos.map((handlerInfo)=>{
37
- const upperHttpMethod = handlerInfo.httpMethod.toUpperCase();
38
- const contract = operationContracts[`${upperHttpMethod}:${handlerInfo.routePath}`];
39
- return {
40
- name: handlerInfo.name,
41
- httpMethod: upperHttpMethod,
42
- routePath: handlerInfo.routePath,
43
- schemaHash: contract?.schemaHash ?? ''
44
- };
45
- }).sort((a, b)=>{
46
- const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
47
- const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
48
- return keyA.localeCompare(keyB);
49
- });
50
- const schemaHash = createOperationSchemaHash(operationEntries, normalizedRequestId);
51
- let hasUploadHandler = false;
52
- let handlersCode = '';
53
- for (const handlerInfo of handlerInfos){
54
- const { name, httpMethod, routePath, action } = handlerInfo;
55
- let exportStatement = `var ${name} =`;
56
- if ('default' === name.toLowerCase()) exportStatement = 'default';
57
- const upperHttpMethod = httpMethod.toUpperCase();
58
- const operationSchemaHash = operationContracts[`${upperHttpMethod}:${routePath}`]?.schemaHash ?? '';
59
- const operationContext = {
60
- operationId: name,
61
- routePath,
62
- method: upperHttpMethod,
63
- schemaHash: operationSchemaHash,
64
- operationVersion
65
- };
66
- if ('upload' === action) {
67
- hasUploadHandler = true;
68
- const uploadOptions = {
69
- path: routePath,
70
- ...domain ? {
71
- domain
72
- } : {},
73
- ...requestId ? {
74
- requestId
75
- } : {},
76
- ...requestId ? {
77
- operationContext
78
- } : {}
25
+ const draft = {
26
+ requestCreator: options.requestCreator || INNER_CLIENT_REQUEST_CREATOR,
27
+ imports: fetcher ? [
28
+ `import { fetch } from ${JSON.stringify(fetcher)};`
29
+ ] : [],
30
+ statements: [],
31
+ handlers: handlerInfos.map((handlerInfo)=>{
32
+ const optionProperties = [
33
+ `path: ${JSON.stringify(handlerInfo.routePath)}`
34
+ ];
35
+ if ('upload' !== handlerInfo.action) {
36
+ const portExpression = 'server' === target ? `process.env.PORT || ${String(port)}` : String(port);
37
+ optionProperties.push(`method: ${JSON.stringify(handlerInfo.httpMethod.toUpperCase())}`, `port: ${portExpression}`, `httpMethodDecider: ${JSON.stringify(httpMethodDecider || 'functionName')}`);
38
+ }
39
+ if (domain) optionProperties.push(`domain: ${JSON.stringify(domain)}`);
40
+ if (fetcher && 'upload' !== handlerInfo.action) optionProperties.push('fetch');
41
+ if (requestId) optionProperties.push(`requestId: ${JSON.stringify(requestId)}`);
42
+ return {
43
+ handlerInfo,
44
+ optionProperties
79
45
  };
80
- handlersCode += `export ${exportStatement} createUploader(${JSON.stringify(uploadOptions)});
81
- `;
82
- continue;
83
- }
84
- const portExpression = 'server' === target ? `process.env.PORT || ${String(port)}` : String(port);
85
- const requestOptionProperties = [
86
- `path: ${JSON.stringify(routePath)}`,
87
- `method: ${JSON.stringify(upperHttpMethod)}`,
88
- `port: ${portExpression}`,
89
- `httpMethodDecider: ${JSON.stringify(httpMethodDecider ? httpMethodDecider : 'functionName')}`
90
- ];
91
- if (domain) requestOptionProperties.push(`domain: ${JSON.stringify(domain)}`);
92
- if (fetcher) requestOptionProperties.push('fetch');
93
- if (requestId) requestOptionProperties.push(`requestId: ${JSON.stringify(requestId)}`);
94
- requestOptionProperties.push(`operationContext: ${JSON.stringify(operationContext)}`);
95
- handlersCode += `export ${exportStatement} createRequest({ ${requestOptionProperties.join(', ')} });
96
- `;
46
+ })
47
+ };
48
+ if (clientCodegenPlugin) try {
49
+ const specifier = clientCodegenPlugin.startsWith('.') ? __rspack_external_path.resolve(appDir, clientCodegenPlugin) : clientCodegenPlugin;
50
+ const resolved = requireResolve(specifier, {
51
+ paths: [
52
+ appDir
53
+ ]
54
+ });
55
+ const extension = await import(pathToFileURL(resolved).href);
56
+ const modifyClient = extension.modifyClient ?? extension.default?.modifyClient;
57
+ if ('function' != typeof modifyClient) throw new TypeError('The module must export a modifyClient function.');
58
+ await modifyClient(draft, {
59
+ options,
60
+ handlerInfos
61
+ });
62
+ } catch (cause) {
63
+ throw new ClientCodegenError(clientCodegenPlugin, cause);
97
64
  }
98
- const serializedRequestCreator = JSON.stringify(requestCreator);
99
- const serializedFetcher = fetcher ? JSON.stringify(fetcher) : void 0;
100
- const namedRequestImports = `createRequest${hasUploadHandler ? ', createUploader' : ''}`;
101
- const importCode = requestId ? `import * as requestRuntime from ${serializedRequestCreator};
102
- const { ${namedRequestImports} } = requestRuntime;
103
- ${serializedFetcher ? `import { fetch } from ${serializedFetcher};\n` : ''}` : `import { ${namedRequestImports} } from ${serializedRequestCreator};
104
- ${serializedFetcher ? `import { fetch } from ${serializedFetcher};\n` : ''}`;
105
- const bootstrapCode = requestId ? `export const initProducerClient = (options = {}) => {
106
- const configure = requestRuntime.configure;
107
- if (typeof configure !== 'function') {
108
- console.warn('[modernjs] Compatibility request creator path does not expose configure(); use default @modern-js/create-request or migrate the compatibility path.');
109
- return undefined;
110
- }
111
- const defaultSecureOptions = {
112
- requestId: ${JSON.stringify(requestId)},
113
- requireEnvelope: true,
114
- identityBinding: {
115
- enabled: true,
116
- strict: true,
117
- },
118
- operationContract: {
119
- enabled: true,
120
- strict: true,
121
- requireSchemaHash: true,
122
- requireOperationVersion: true,
123
- },
124
- };
125
- return configure({
126
- ...defaultSecureOptions,
127
- ...options,
128
- identityBinding: {
129
- ...defaultSecureOptions.identityBinding,
130
- ...(options && options.identityBinding ? options.identityBinding : {}),
131
- },
132
- operationContract: {
133
- ...defaultSecureOptions.operationContract,
134
- ...(options && options.operationContract ? options.operationContract : {}),
135
- },
136
- });
137
- };
138
- ` : '';
139
- const manifestCode = `export const operationVersion = ${String(operationVersion)};
140
- export const operationSchemaHash = '${schemaHash}';
141
- export const operationManifest = ${JSON.stringify({
142
- operationVersion,
143
- schemaHash,
144
- operations: operationEntries
145
- }, null, 2)};
146
- `;
147
- const generatedParts = [
148
- importCode.trimEnd(),
149
- bootstrapCode.trimEnd(),
150
- manifestCode.trimEnd(),
151
- handlersCode.trimEnd()
152
- ].filter(Boolean);
153
- return Ok(`${generatedParts.join('\n\n')}
154
- `);
65
+ const hasUploadHandler = handlerInfos.some((info)=>'upload' === info.action);
66
+ const requestImports = `createRequest${hasUploadHandler ? ', createUploader' : ''}`;
67
+ const importCode = [
68
+ `import { ${requestImports} } from ${JSON.stringify(draft.requestCreator)};`,
69
+ ...draft.imports
70
+ ].join('\n');
71
+ const handlersCode = draft.handlers.map(({ handlerInfo, optionProperties })=>{
72
+ const exportStatement = 'default' === handlerInfo.name.toLowerCase() ? 'default' : `var ${handlerInfo.name} =`;
73
+ const creator = 'upload' === handlerInfo.action ? 'createUploader' : 'createRequest';
74
+ return `export ${exportStatement} ${creator}({ ${optionProperties.join(', ')} });`;
75
+ }).join('\n');
76
+ return Ok(`${[
77
+ importCode,
78
+ ...draft.statements,
79
+ handlersCode
80
+ ].filter(Boolean).join('\n\n')}\n`);
155
81
  };
156
- export { INNER_CLIENT_REQUEST_CREATOR, generateClient };
82
+ export { ClientCodegenError, INNER_CLIENT_REQUEST_CREATOR, generateClient };
@@ -1,10 +1,6 @@
1
- export * from "./adapter-kit/index.mjs";
2
1
  export * from "./client/index.mjs";
3
2
  export * from "./operators/http.mjs";
4
3
  export * from "./router/index.mjs";
5
- export * from "./security/crossProjectPolicy.mjs";
6
- export * from "./security/operationContracts.mjs";
7
- export * from "./security/resolveCrossProjectPolicy.mjs";
8
4
  export * from "./types.mjs";
9
5
  export { Api } from "./api.mjs";
10
6
  export { HttpError, ValidationError } from "./errors/http.mjs";