@bleedingdev/modern-js-plugin-bff 3.2.0-ultramodern.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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -0
  3. package/cli.js +1 -0
  4. package/dist/cjs/cli.js +294 -0
  5. package/dist/cjs/constants.js +48 -0
  6. package/dist/cjs/index.js +58 -0
  7. package/dist/cjs/loader.js +106 -0
  8. package/dist/cjs/runtime/create-request/index.js +48 -0
  9. package/dist/cjs/runtime/data-platform/index.js +693 -0
  10. package/dist/cjs/runtime/effect/adapter.js +311 -0
  11. package/dist/cjs/runtime/effect/context.js +48 -0
  12. package/dist/cjs/runtime/effect/index.js +608 -0
  13. package/dist/cjs/runtime/effect-client/index.js +178 -0
  14. package/dist/cjs/runtime/hono/adapter.js +168 -0
  15. package/dist/cjs/runtime/hono/index.js +65 -0
  16. package/dist/cjs/runtime/hono/operators.js +68 -0
  17. package/dist/cjs/server.js +179 -0
  18. package/dist/cjs/utils/clientGenerator.js +342 -0
  19. package/dist/cjs/utils/createHonoRoutes.js +138 -0
  20. package/dist/cjs/utils/crossProjectApiPlugin.js +118 -0
  21. package/dist/cjs/utils/effectClientGenerator.js +673 -0
  22. package/dist/cjs/utils/pluginGenerator.js +73 -0
  23. package/dist/cjs/utils/runtimeGenerator.js +133 -0
  24. package/dist/esm/cli.mjs +245 -0
  25. package/dist/esm/constants.mjs +11 -0
  26. package/dist/esm/index.mjs +1 -0
  27. package/dist/esm/loader.mjs +62 -0
  28. package/dist/esm/runtime/create-request/index.mjs +1 -0
  29. package/dist/esm/runtime/data-platform/index.mjs +599 -0
  30. package/dist/esm/runtime/effect/adapter.mjs +267 -0
  31. package/dist/esm/runtime/effect/context.mjs +11 -0
  32. package/dist/esm/runtime/effect/index.mjs +438 -0
  33. package/dist/esm/runtime/effect-client/index.mjs +90 -0
  34. package/dist/esm/runtime/hono/adapter.mjs +124 -0
  35. package/dist/esm/runtime/hono/index.mjs +2 -0
  36. package/dist/esm/runtime/hono/operators.mjs +31 -0
  37. package/dist/esm/server.mjs +135 -0
  38. package/dist/esm/utils/clientGenerator.mjs +293 -0
  39. package/dist/esm/utils/createHonoRoutes.mjs +92 -0
  40. package/dist/esm/utils/crossProjectApiPlugin.mjs +54 -0
  41. package/dist/esm/utils/effectClientGenerator.mjs +623 -0
  42. package/dist/esm/utils/pluginGenerator.mjs +29 -0
  43. package/dist/esm/utils/runtimeGenerator.mjs +89 -0
  44. package/dist/esm-node/cli.mjs +249 -0
  45. package/dist/esm-node/constants.mjs +12 -0
  46. package/dist/esm-node/index.mjs +2 -0
  47. package/dist/esm-node/loader.mjs +64 -0
  48. package/dist/esm-node/runtime/create-request/index.mjs +2 -0
  49. package/dist/esm-node/runtime/data-platform/index.mjs +600 -0
  50. package/dist/esm-node/runtime/effect/adapter.mjs +269 -0
  51. package/dist/esm-node/runtime/effect/context.mjs +12 -0
  52. package/dist/esm-node/runtime/effect/index.mjs +439 -0
  53. package/dist/esm-node/runtime/effect-client/index.mjs +91 -0
  54. package/dist/esm-node/runtime/hono/adapter.mjs +125 -0
  55. package/dist/esm-node/runtime/hono/index.mjs +3 -0
  56. package/dist/esm-node/runtime/hono/operators.mjs +32 -0
  57. package/dist/esm-node/server.mjs +136 -0
  58. package/dist/esm-node/utils/clientGenerator.mjs +294 -0
  59. package/dist/esm-node/utils/createHonoRoutes.mjs +93 -0
  60. package/dist/esm-node/utils/crossProjectApiPlugin.mjs +55 -0
  61. package/dist/esm-node/utils/effectClientGenerator.mjs +625 -0
  62. package/dist/esm-node/utils/pluginGenerator.mjs +33 -0
  63. package/dist/esm-node/utils/runtimeGenerator.mjs +91 -0
  64. package/dist/types/cli.d.ts +3 -0
  65. package/dist/types/constants.d.ts +2 -0
  66. package/dist/types/index.d.ts +1 -0
  67. package/dist/types/loader.d.ts +27 -0
  68. package/dist/types/runtime/create-request/index.d.ts +2 -0
  69. package/dist/types/runtime/data-platform/index.d.ts +187 -0
  70. package/dist/types/runtime/effect/adapter.d.ts +22 -0
  71. package/dist/types/runtime/effect/context.d.ts +8 -0
  72. package/dist/types/runtime/effect/index.d.ts +171 -0
  73. package/dist/types/runtime/effect-client/index.d.ts +47 -0
  74. package/dist/types/runtime/hono/adapter.d.ts +19 -0
  75. package/dist/types/runtime/hono/index.d.ts +2 -0
  76. package/dist/types/runtime/hono/operators.d.ts +10 -0
  77. package/dist/types/server.d.ts +3 -0
  78. package/dist/types/utils/clientGenerator.d.ts +37 -0
  79. package/dist/types/utils/createHonoRoutes.d.ts +10 -0
  80. package/dist/types/utils/crossProjectApiPlugin.d.ts +9 -0
  81. package/dist/types/utils/effectClientGenerator.d.ts +27 -0
  82. package/dist/types/utils/pluginGenerator.d.ts +9 -0
  83. package/dist/types/utils/runtimeGenerator.d.ts +7 -0
  84. package/docs/data-platform-architecture.md +61 -0
  85. package/package.json +172 -0
  86. package/rslib.config.mts +4 -0
  87. package/rstest.config.mts +10 -0
  88. package/server.js +1 -0
@@ -0,0 +1,673 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, definition)=>{
14
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
15
+ enumerable: true,
16
+ get: definition[key]
17
+ });
18
+ };
19
+ })();
20
+ (()=>{
21
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
22
+ })();
23
+ (()=>{
24
+ __webpack_require__.r = (exports1)=>{
25
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
26
+ value: 'Module'
27
+ });
28
+ Object.defineProperty(exports1, '__esModule', {
29
+ value: true
30
+ });
31
+ };
32
+ })();
33
+ var __webpack_exports__ = {};
34
+ __webpack_require__.r(__webpack_exports__);
35
+ __webpack_require__.d(__webpack_exports__, {
36
+ generateEffectClientCode: ()=>generateEffectClientCode,
37
+ renderEffectClientDeclaration: ()=>renderEffectClientDeclaration,
38
+ resolveEffectEntryFile: ()=>resolveEffectEntryFile
39
+ });
40
+ const bff_core_namespaceObject = require("@modern-js/bff-core");
41
+ const utils_namespaceObject = require("@modern-js/utils");
42
+ const external_path_namespaceObject = require("path");
43
+ var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
44
+ const JS_OR_TS_EXTS = [
45
+ '.js',
46
+ '.jsx',
47
+ '.ts',
48
+ '.tsx',
49
+ '.mjs',
50
+ '.mts',
51
+ '.cjs',
52
+ '.cts'
53
+ ];
54
+ const DEFAULT_REQUEST_CREATOR = '@modern-js/plugin-bff/client';
55
+ const DEFAULT_DATA_PLATFORM_IMPORT = '@modern-js/plugin-bff/data-platform';
56
+ let httpApiRuntimePromise;
57
+ function isRecord(value) {
58
+ return 'object' == typeof value && null !== value;
59
+ }
60
+ function ensureLeadingSlash(pathname) {
61
+ return pathname.startsWith('/') ? pathname : `/${pathname}`;
62
+ }
63
+ function normalizePrefix(prefix) {
64
+ if ('/' === prefix) return '';
65
+ return ensureLeadingSlash(prefix || '/api');
66
+ }
67
+ function isAbsoluteUrl(value) {
68
+ try {
69
+ new URL(value);
70
+ return true;
71
+ } catch {
72
+ return false;
73
+ }
74
+ }
75
+ function resolveBatchEndpoint(prefix, endpoint) {
76
+ const value = endpoint || '/_data/batch';
77
+ if (isAbsoluteUrl(value)) return value;
78
+ const normalizedPrefix = normalizePrefix(prefix);
79
+ const normalizedEndpoint = ensureLeadingSlash(value);
80
+ if (!normalizedPrefix) return normalizedEndpoint;
81
+ if (normalizedEndpoint === normalizedPrefix || normalizedEndpoint.startsWith(`${normalizedPrefix}/`)) return normalizedEndpoint;
82
+ return `${normalizedPrefix}${'/' === normalizedEndpoint ? '' : normalizedEndpoint}`;
83
+ }
84
+ function getRoutePath(prefix, endpointPath) {
85
+ const normalizedPrefix = normalizePrefix(prefix);
86
+ const normalizedEndpointPath = ensureLeadingSlash(endpointPath);
87
+ const finalEndpointPath = '/' === normalizedEndpointPath ? '' : endpointPath;
88
+ if (!normalizedPrefix && !finalEndpointPath) return '/';
89
+ return `${normalizedPrefix}${finalEndpointPath || ''}`;
90
+ }
91
+ function toSafeIdentifier(name) {
92
+ const sanitized = name.replace(/[^a-zA-Z0-9_$]/g, '_');
93
+ if (!sanitized) return '_';
94
+ if (/^[0-9]/.test(sanitized)) return `_${sanitized}`;
95
+ return sanitized;
96
+ }
97
+ function getPackageName(appDir) {
98
+ try {
99
+ const packageJsonPath = external_path_default().resolve(appDir, './package.json');
100
+ const packageJson = utils_namespaceObject.fs.readJSONSync(packageJsonPath);
101
+ return packageJson.name;
102
+ } catch {
103
+ return;
104
+ }
105
+ }
106
+ async function getHttpApiRuntime() {
107
+ if (!httpApiRuntimePromise) httpApiRuntimePromise = (async ()=>{
108
+ let mod;
109
+ try {
110
+ mod = await (0, utils_namespaceObject.compatibleRequire)('effect/unstable/httpapi', false);
111
+ } catch (error) {
112
+ const message = error instanceof Error ? error.message : String(error);
113
+ if (!message.includes("Cannot find module 'effect/unstable/httpapi'")) throw error;
114
+ const effectPackageJson = require.resolve('effect/package.json');
115
+ const effectHttpApiRuntimePath = external_path_default().join(external_path_default().dirname(effectPackageJson), 'dist', 'unstable', 'httpapi', 'index.js');
116
+ mod = await (0, utils_namespaceObject.compatibleRequire)(effectHttpApiRuntimePath, false);
117
+ }
118
+ if (isRecord(mod) && isRecord(mod.HttpApi)) {
119
+ const maybeHttpApi = mod.HttpApi;
120
+ if ('function' == typeof maybeHttpApi.isHttpApi && 'function' == typeof maybeHttpApi.reflect) return maybeHttpApi;
121
+ }
122
+ throw new Error('[BFF][Effect] Unable to resolve HttpApi runtime from effect/unstable/httpapi.');
123
+ })();
124
+ return httpApiRuntimePromise;
125
+ }
126
+ function resolveApiId(api) {
127
+ const fallback = 'EffectHttpApi';
128
+ const maybeApi = api;
129
+ if ('identifier' in maybeApi && 'string' == typeof maybeApi.identifier && maybeApi.identifier) return maybeApi.identifier;
130
+ return fallback;
131
+ }
132
+ function collectEffectEndpoints(httpApiRuntime, api, prefix) {
133
+ const endpoints = [];
134
+ const apiId = resolveApiId(api);
135
+ httpApiRuntime.reflect(api, {
136
+ onGroup: ()=>{},
137
+ onEndpoint: ({ group, endpoint })=>{
138
+ endpoints.push({
139
+ apiId,
140
+ groupName: String(group.identifier),
141
+ endpointName: String(endpoint.name),
142
+ method: String(endpoint.method).toUpperCase(),
143
+ routePath: getRoutePath(prefix, String(endpoint.path))
144
+ });
145
+ }
146
+ });
147
+ return endpoints.sort((a, b)=>{
148
+ if (a.groupName === b.groupName) return a.endpointName.localeCompare(b.endpointName);
149
+ return a.groupName.localeCompare(b.groupName);
150
+ });
151
+ }
152
+ async function loadEffectApi(resourcePath) {
153
+ const httpApiRuntime = await getHttpApiRuntime();
154
+ const mod = await (0, utils_namespaceObject.compatibleRequire)(resourcePath, false);
155
+ if (isRecord(mod) && httpApiRuntime.isHttpApi(mod.api)) return mod.api;
156
+ if (isRecord(mod) && isRecord(mod.default) && httpApiRuntime.isHttpApi(mod.default.api)) return mod.default.api;
157
+ if (isRecord(mod) && 'function' == typeof mod.default && 0 === mod.default.length) {
158
+ const output = await mod.default();
159
+ if (isRecord(output) && httpApiRuntime.isHttpApi(output.api)) return output.api;
160
+ }
161
+ return null;
162
+ }
163
+ function renderEffectClientCode(endpoints, options) {
164
+ const senderDeclarations = [];
165
+ const operationDeclarations = [];
166
+ const callerDeclarations = [];
167
+ const groupedCallers = {};
168
+ const groupedOperations = {};
169
+ const requestCreator = options.requestCreator || DEFAULT_REQUEST_CREATOR;
170
+ const dataPlatformImport = DEFAULT_DATA_PLATFORM_IMPORT;
171
+ const httpMethodDecider = options.httpMethodDecider || 'functionName';
172
+ const portCode = 'server' === options.target ? `process.env.PORT || ${String(options.port)}` : String(options.port);
173
+ const packageName = getPackageName(options.appDir);
174
+ const dataPlatformAppNamespace = packageName || 'unknown-app';
175
+ const requestId = 'bundle' === options.target ? packageName || process.env.npm_package_name : void 0;
176
+ const normalizedRequestId = requestId || 'default';
177
+ const operationVersion = 'number' == typeof bff_core_namespaceObject.DEFAULT_OPERATION_VERSION ? bff_core_namespaceObject.DEFAULT_OPERATION_VERSION : 1;
178
+ const schemaHash = (0, bff_core_namespaceObject.createOperationSchemaHash)((0, bff_core_namespaceObject.createOperationEntries)(endpoints.map((endpoint)=>({
179
+ name: endpoint.endpointName,
180
+ httpMethod: endpoint.method,
181
+ routePath: endpoint.routePath
182
+ }))), normalizedRequestId);
183
+ const batchConfig = options.dataPlatformBatch;
184
+ const batchEndpoint = resolveBatchEndpoint(options.prefix, batchConfig?.endpoint);
185
+ const batchConfigCode = JSON.stringify({
186
+ enabled: batchConfig?.enabled ?? true,
187
+ endpoint: batchEndpoint,
188
+ flushIntervalMs: batchConfig?.flushIntervalMs ?? 8,
189
+ maxBatchSize: batchConfig?.maxBatchSize ?? 16,
190
+ maxBatchBytes: batchConfig?.maxBatchBytes ?? 65536,
191
+ requestTimeoutMs: batchConfig?.requestTimeoutMs ?? 10000,
192
+ allowedMethods: batchConfig?.allowedMethods && batchConfig.allowedMethods.length > 0 ? batchConfig.allowedMethods : [
193
+ 'GET'
194
+ ]
195
+ });
196
+ endpoints.forEach((endpoint, index)=>{
197
+ const senderVar = `__sender_${toSafeIdentifier(endpoint.groupName)}_${toSafeIdentifier(endpoint.endpointName)}_${index}`;
198
+ const callVar = `__call_${toSafeIdentifier(endpoint.groupName)}_${toSafeIdentifier(endpoint.endpointName)}_${index}`;
199
+ const operationVar = `__operation_${toSafeIdentifier(endpoint.groupName)}_${toSafeIdentifier(endpoint.endpointName)}_${index}`;
200
+ const operationId = `${endpoint.method}:${endpoint.routePath}`;
201
+ const operationContextCode = JSON.stringify({
202
+ operationId,
203
+ routePath: endpoint.routePath,
204
+ method: endpoint.method,
205
+ schemaHash,
206
+ operationVersion
207
+ });
208
+ const createRequestOptions = `{
209
+ path: ${JSON.stringify(endpoint.routePath)},
210
+ method: ${JSON.stringify(endpoint.method)},
211
+ port: ${portCode},
212
+ operationContext: ${operationContextCode},
213
+ httpMethodDecider: ${JSON.stringify(httpMethodDecider)}${requestId ? `, requestId: ${JSON.stringify(requestId)}` : ''}
214
+ }`.replace(/\n\s*/g, '');
215
+ senderDeclarations.push(`const ${senderVar} = createRequest(${createRequestOptions});`);
216
+ operationDeclarations.push(`const ${operationVar} = ${JSON.stringify({
217
+ appNamespace: dataPlatformAppNamespace,
218
+ apiId: endpoint.apiId,
219
+ group: endpoint.groupName,
220
+ endpoint: endpoint.endpointName,
221
+ operationId,
222
+ routePath: endpoint.routePath,
223
+ method: endpoint.method,
224
+ operationVersion,
225
+ schemaHash,
226
+ version: operationVersion
227
+ })};`);
228
+ callerDeclarations.push(`const ${callVar} = (request = {}) => ${senderVar}(__prepareEffectRequest(${JSON.stringify(endpoint.method)}, ${JSON.stringify(endpoint.routePath)}, ${operationVar}, request));`);
229
+ groupedCallers[endpoint.groupName] ??= [];
230
+ groupedCallers[endpoint.groupName].push({
231
+ endpointName: endpoint.endpointName,
232
+ callVar
233
+ });
234
+ groupedOperations[endpoint.groupName] ??= [];
235
+ groupedOperations[endpoint.groupName].push({
236
+ endpointName: endpoint.endpointName,
237
+ operationVar
238
+ });
239
+ });
240
+ const groupObjectEntries = Object.entries(groupedCallers).map(([groupName, groupCallers])=>{
241
+ const endpointEntries = groupCallers.map((caller)=>`${JSON.stringify(caller.endpointName)}: ${caller.callVar}`).join(', ');
242
+ return `${JSON.stringify(groupName)}: { ${endpointEntries} }`;
243
+ });
244
+ const clientObject = groupObjectEntries.length ? `{
245
+ ${groupObjectEntries.join(',\n ')}
246
+ }` : '{}';
247
+ const operationManifestEntries = Object.entries(groupedOperations).map(([groupName, groupOperations])=>{
248
+ const endpointEntries = groupOperations.map((operation)=>`${JSON.stringify(operation.endpointName)}: ${operation.operationVar}`).join(', ');
249
+ return `${JSON.stringify(groupName)}: { ${endpointEntries} }`;
250
+ });
251
+ const operationManifestObject = operationManifestEntries.length ? `{
252
+ ${operationManifestEntries.join(',\n ')}
253
+ }` : '{}';
254
+ return `import * as __requestRuntime from ${JSON.stringify(requestCreator)};
255
+ import {
256
+ createDataBatchTransport,
257
+ DEFAULT_DATA_BATCH_HEADER,
258
+ DEFAULT_DATA_ENVELOPE_HEADER,
259
+ createRequestEnvelope,
260
+ encodeRequestEnvelopeHeader,
261
+ } from ${JSON.stringify(dataPlatformImport)};
262
+
263
+ const createRequest = __requestRuntime.createRequest;
264
+ const __configureRequest =
265
+ typeof __requestRuntime.configure === 'function'
266
+ ? __requestRuntime.configure
267
+ : undefined;
268
+ const __createRequestContextHeaders =
269
+ typeof __requestRuntime.createRequestContextHeaders === 'function'
270
+ ? __requestRuntime.createRequestContextHeaders
271
+ : undefined;
272
+
273
+ const __METHODS_WITHOUT_BODY = new Set(['GET', 'DELETE', 'HEAD', 'OPTIONS']);
274
+ const __DATA_REQUEST_MODES = new Set(['cache-first', 'stale-while-revalidate', 'network-only']);
275
+ const __DATA_MUTATION_MODES = new Set(['optimistic', 'pessimistic', 'fire-and-forget']);
276
+ const __DEFAULT_APP_NAMESPACE = ${JSON.stringify(dataPlatformAppNamespace)};
277
+ const __DEFAULT_ORIGIN = 'http://localhost:${String(options.port)}';
278
+ const __DEFAULT_BATCH_CONFIG = ${batchConfigCode};
279
+ const __REQUEST_ID = ${requestId ? JSON.stringify(requestId) : 'undefined'};
280
+ const __RUNTIME_FETCH =
281
+ typeof fetch === 'function' ? fetch.bind(globalThis) : undefined;
282
+
283
+ if (__REQUEST_ID && __configureRequest) {
284
+ const __configurePayload = {
285
+ requestId: __REQUEST_ID,
286
+ requireEnvelope: true,
287
+ identityBinding: {
288
+ enabled: true,
289
+ strict: true,
290
+ },
291
+ operationContract: {
292
+ enabled: true,
293
+ strict: true,
294
+ requireSchemaHash: true,
295
+ requireOperationVersion: true,
296
+ },
297
+ setDomain: () => {
298
+ if (
299
+ typeof window !== 'undefined' &&
300
+ window.location &&
301
+ typeof window.location.origin === 'string' &&
302
+ window.location.origin
303
+ ) {
304
+ return window.location.origin;
305
+ }
306
+
307
+ if (
308
+ typeof globalThis !== 'undefined' &&
309
+ globalThis.location &&
310
+ typeof globalThis.location.origin === 'string' &&
311
+ globalThis.location.origin
312
+ ) {
313
+ return globalThis.location.origin;
314
+ }
315
+
316
+ return __DEFAULT_ORIGIN;
317
+ },
318
+ };
319
+
320
+ if (__DEFAULT_BATCH_CONFIG.enabled !== false && __RUNTIME_FETCH) {
321
+ __configurePayload.request = createDataBatchTransport({
322
+ fetch: __RUNTIME_FETCH,
323
+ endpoint: __DEFAULT_BATCH_CONFIG.endpoint,
324
+ flushIntervalMs: __DEFAULT_BATCH_CONFIG.flushIntervalMs,
325
+ maxBatchSize: __DEFAULT_BATCH_CONFIG.maxBatchSize,
326
+ maxBatchBytes: __DEFAULT_BATCH_CONFIG.maxBatchBytes,
327
+ requestTimeoutMs: __DEFAULT_BATCH_CONFIG.requestTimeoutMs,
328
+ allowedMethods: __DEFAULT_BATCH_CONFIG.allowedMethods,
329
+ });
330
+ }
331
+
332
+ __configureRequest(__configurePayload);
333
+ }
334
+
335
+ const __isRecord = value => typeof value === 'object' && value !== null;
336
+ const __stringOrUndefined = value =>
337
+ typeof value === 'string' && value.length > 0 ? value : undefined;
338
+ const __isDataRequestMode = value =>
339
+ typeof value === 'string' && __DATA_REQUEST_MODES.has(value);
340
+ const __isDataMutationMode = value =>
341
+ typeof value === 'string' && __DATA_MUTATION_MODES.has(value);
342
+ const __normalizeOrigin = value => {
343
+ if (typeof value !== 'string' || value.length === 0) {
344
+ return undefined;
345
+ }
346
+ try {
347
+ return new URL(value).origin;
348
+ } catch {
349
+ return undefined;
350
+ }
351
+ };
352
+
353
+ const __normalizeRequest = (method, request = {}) => {
354
+ if (!__isRecord(request)) {
355
+ return {};
356
+ }
357
+
358
+ const payload = { ...request };
359
+
360
+ if (__isRecord(request.path) && !__isRecord(payload.params)) {
361
+ payload.params = request.path;
362
+ }
363
+
364
+ if (__isRecord(request.urlParams) && !__isRecord(payload.query)) {
365
+ payload.query = request.urlParams;
366
+ }
367
+
368
+ if (__isRecord(request.headers) && !__isRecord(payload.headers)) {
369
+ payload.headers = request.headers;
370
+ }
371
+
372
+ if ('payload' in request && request.payload !== undefined) {
373
+ if (request.payload instanceof FormData && !('formData' in payload)) {
374
+ payload.formData = request.payload;
375
+ } else if (__METHODS_WITHOUT_BODY.has(method)) {
376
+ if (__isRecord(request.payload)) {
377
+ payload.query = __isRecord(payload.query)
378
+ ? { ...payload.query, ...request.payload }
379
+ : request.payload;
380
+ } else if (!('body' in payload)) {
381
+ payload.body = request.payload;
382
+ }
383
+ } else if (__isRecord(request.payload) && !('data' in payload)) {
384
+ payload.data = request.payload;
385
+ } else if (!('body' in payload)) {
386
+ payload.body = request.payload;
387
+ }
388
+ }
389
+
390
+ return payload;
391
+ };
392
+
393
+ const __resolveOrigin = () => {
394
+ if (
395
+ typeof window !== 'undefined' &&
396
+ window.location &&
397
+ typeof window.location.origin === 'string' &&
398
+ window.location.origin
399
+ ) {
400
+ return window.location.origin;
401
+ }
402
+
403
+ if (
404
+ typeof globalThis !== 'undefined' &&
405
+ globalThis.location &&
406
+ typeof globalThis.location.origin === 'string' &&
407
+ globalThis.location.origin
408
+ ) {
409
+ return globalThis.location.origin;
410
+ }
411
+
412
+ return __DEFAULT_ORIGIN;
413
+ };
414
+
415
+ const __resolveTargetOrigin = dataPlatform => {
416
+ const explicitTargetOrigin =
417
+ __stringOrUndefined(dataPlatform.targetOrigin) ||
418
+ __stringOrUndefined(dataPlatform.endpointOrigin);
419
+ if (explicitTargetOrigin) {
420
+ return explicitTargetOrigin;
421
+ }
422
+ return __DEFAULT_ORIGIN;
423
+ };
424
+
425
+ const __shouldAttachEnvelopeHeader = dataPlatform => {
426
+ if (dataPlatform.allowCrossOriginEnvelope === true) {
427
+ return true;
428
+ }
429
+ const currentOrigin = __normalizeOrigin(__resolveOrigin());
430
+ const targetOrigin = __normalizeOrigin(__resolveTargetOrigin(dataPlatform));
431
+ if (!currentOrigin || !targetOrigin) {
432
+ return true;
433
+ }
434
+ return currentOrigin === targetOrigin;
435
+ };
436
+
437
+ const __toEnvelopeInput = normalizedRequest => {
438
+ if (!__isRecord(normalizedRequest)) {
439
+ return {};
440
+ }
441
+
442
+ const payload = {};
443
+ if (__isRecord(normalizedRequest.params)) {
444
+ payload.path = normalizedRequest.params;
445
+ }
446
+ if (__isRecord(normalizedRequest.query)) {
447
+ payload.query = normalizedRequest.query;
448
+ }
449
+ if ('data' in normalizedRequest && normalizedRequest.data !== undefined) {
450
+ payload.data = normalizedRequest.data;
451
+ }
452
+ if ('body' in normalizedRequest && normalizedRequest.body !== undefined) {
453
+ payload.body = normalizedRequest.body;
454
+ }
455
+ if (
456
+ typeof FormData !== 'undefined' &&
457
+ normalizedRequest.formData instanceof FormData
458
+ ) {
459
+ payload.formData = Array.from(normalizedRequest.formData.entries()).map(
460
+ ([key, value]) => [key, String(value)],
461
+ );
462
+ }
463
+ if (
464
+ typeof URLSearchParams !== 'undefined' &&
465
+ normalizedRequest.formUrlencoded instanceof URLSearchParams
466
+ ) {
467
+ payload.formUrlencoded = normalizedRequest.formUrlencoded.toString();
468
+ }
469
+ return payload;
470
+ };
471
+
472
+ const createEffectRequestContext = requestContext => {
473
+ if (!__isRecord(requestContext)) {
474
+ return {};
475
+ }
476
+
477
+ const headers = __createRequestContextHeaders
478
+ ? __createRequestContextHeaders(requestContext)
479
+ : {};
480
+
481
+ return {
482
+ ...requestContext,
483
+ headers,
484
+ };
485
+ };
486
+
487
+ const __applyRequestContext = (normalizedRequest, request = {}) => {
488
+ if (!__isRecord(request) || !__isRecord(request.requestContext)) {
489
+ return normalizedRequest;
490
+ }
491
+
492
+ const requestContext = createEffectRequestContext(request.requestContext);
493
+ const requestHeaders = __isRecord(requestContext.headers)
494
+ ? requestContext.headers
495
+ : {};
496
+
497
+ if (Object.keys(requestHeaders).length === 0) {
498
+ return normalizedRequest;
499
+ }
500
+
501
+ return {
502
+ ...normalizedRequest,
503
+ headers: {
504
+ ...requestHeaders,
505
+ ...(__isRecord(normalizedRequest.headers) ? normalizedRequest.headers : {}),
506
+ },
507
+ };
508
+ };
509
+
510
+ const __prepareEffectRequest = (method, routePath, operation, request = {}) => {
511
+ const normalizedRequest = __applyRequestContext(
512
+ __normalizeRequest(method, request),
513
+ request,
514
+ );
515
+ const dataPlatform = __isRecord(request) && __isRecord(request.dataPlatform)
516
+ ? request.dataPlatform
517
+ : {};
518
+ const strictEnvelope =
519
+ dataPlatform.requireEnvelope === true || dataPlatform.strict === true;
520
+
521
+ if (!strictEnvelope && !__shouldAttachEnvelopeHeader(dataPlatform)) {
522
+ return normalizedRequest;
523
+ }
524
+
525
+ try {
526
+ const namespace =
527
+ __stringOrUndefined(dataPlatform.appNamespace) || __DEFAULT_APP_NAMESPACE;
528
+ const origin = __stringOrUndefined(dataPlatform.origin) || __resolveOrigin();
529
+ const envelope = createRequestEnvelope({
530
+ operation: {
531
+ ...operation,
532
+ appNamespace: namespace,
533
+ },
534
+ scope: {
535
+ appNamespace: namespace,
536
+ origin,
537
+ tenantId: __stringOrUndefined(dataPlatform.tenantId),
538
+ userId: __stringOrUndefined(dataPlatform.userId),
539
+ sessionId: __stringOrUndefined(dataPlatform.sessionId),
540
+ },
541
+ requestInput: {
542
+ method,
543
+ routePath,
544
+ payload: __toEnvelopeInput(normalizedRequest),
545
+ },
546
+ requestMode: __isDataRequestMode(dataPlatform.requestMode)
547
+ ? dataPlatform.requestMode
548
+ : undefined,
549
+ mutationMode: __isDataMutationMode(dataPlatform.mutationMode)
550
+ ? dataPlatform.mutationMode
551
+ : undefined,
552
+ selectionPlan: __isRecord(dataPlatform.selectionPlan)
553
+ ? dataPlatform.selectionPlan
554
+ : undefined,
555
+ traceContext: __isRecord(dataPlatform.traceContext)
556
+ ? dataPlatform.traceContext
557
+ : undefined,
558
+ requireTraceContext: dataPlatform.requireTraceContext === true,
559
+ });
560
+
561
+ const headerName =
562
+ __stringOrUndefined(dataPlatform.envelopeHeader) ||
563
+ DEFAULT_DATA_ENVELOPE_HEADER;
564
+ const headers = __isRecord(normalizedRequest.headers)
565
+ ? { ...normalizedRequest.headers }
566
+ : {};
567
+
568
+ if (dataPlatform.batch === false) {
569
+ headers[DEFAULT_DATA_BATCH_HEADER] = 'off';
570
+ }
571
+
572
+ headers[headerName] = encodeRequestEnvelopeHeader(envelope);
573
+
574
+ return {
575
+ ...normalizedRequest,
576
+ headers,
577
+ };
578
+ } catch (error) {
579
+ if (strictEnvelope) {
580
+ throw error;
581
+ }
582
+ return normalizedRequest;
583
+ }
584
+ };
585
+
586
+ ${senderDeclarations.join('\n')}
587
+ ${operationDeclarations.join('\n')}
588
+ ${callerDeclarations.join('\n')}
589
+
590
+ const client = ${clientObject};
591
+ const operationManifest = ${operationManifestObject};
592
+ const effectBffModule = {
593
+ client,
594
+ operationManifest,
595
+ createEffectRequestContext,
596
+ };
597
+
598
+ export { client, createEffectRequestContext, operationManifest };
599
+ export default effectBffModule;
600
+ `;
601
+ }
602
+ function renderEffectClientDeclaration() {
603
+ return `export type EffectClientOperation = (
604
+ request?: unknown,
605
+ ) => Promise<unknown>;
606
+ export type EffectClientGroup = Record<string, EffectClientOperation>;
607
+ export type EffectClient = Record<string, EffectClientGroup>;
608
+ export type EffectOperationDescriptor = {
609
+ appNamespace: string;
610
+ apiId: string;
611
+ group: string;
612
+ endpoint: string;
613
+ operationId: string;
614
+ routePath: string;
615
+ method: string;
616
+ operationVersion: number;
617
+ schemaHash: string;
618
+ version: number;
619
+ };
620
+ export type EffectOperationManifest = Record<
621
+ string,
622
+ Record<string, EffectOperationDescriptor>
623
+ >;
624
+ export type EffectRequestContext = {
625
+ headers?: Record<string, string>;
626
+ locale?: string;
627
+ traceparent?: string;
628
+ traceId?: string;
629
+ spanId?: string;
630
+ };
631
+
632
+ export declare const client: EffectClient;
633
+ export declare const createEffectRequestContext: (
634
+ requestContext: Record<string, unknown>,
635
+ ) => EffectRequestContext;
636
+ export declare const operationManifest: EffectOperationManifest;
637
+ declare const effectBffModule: {
638
+ client: EffectClient;
639
+ createEffectRequestContext: typeof createEffectRequestContext;
640
+ operationManifest: EffectOperationManifest;
641
+ };
642
+
643
+ export default effectBffModule;
644
+ `;
645
+ }
646
+ async function generateEffectClientCode(options) {
647
+ const api = await loadEffectApi(options.resourcePath);
648
+ if (!api) {
649
+ utils_namespaceObject.logger.warn(`[BFF][Effect] Failed to generate client for ${options.resourcePath}: unable to resolve exported HttpApi.`);
650
+ return null;
651
+ }
652
+ const httpApiRuntime = await getHttpApiRuntime();
653
+ const endpoints = collectEffectEndpoints(httpApiRuntime, api, options.prefix);
654
+ return renderEffectClientCode(endpoints, options);
655
+ }
656
+ function resolveEffectEntryFile(options) {
657
+ const { appDir, apiDir, effectEntry } = options;
658
+ const defaultEntry = external_path_default().resolve(apiDir, 'effect', 'index');
659
+ const entryWithoutExt = effectEntry ? external_path_default().isAbsolute(effectEntry) ? effectEntry : external_path_default().resolve(appDir, effectEntry) : defaultEntry;
660
+ if (external_path_default().extname(entryWithoutExt)) return utils_namespaceObject.fs.existsSync(entryWithoutExt) ? entryWithoutExt : void 0;
661
+ return (0, utils_namespaceObject.findExists)(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutExt}${ext}`));
662
+ }
663
+ exports.generateEffectClientCode = __webpack_exports__.generateEffectClientCode;
664
+ exports.renderEffectClientDeclaration = __webpack_exports__.renderEffectClientDeclaration;
665
+ exports.resolveEffectEntryFile = __webpack_exports__.resolveEffectEntryFile;
666
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
667
+ "generateEffectClientCode",
668
+ "renderEffectClientDeclaration",
669
+ "resolveEffectEntryFile"
670
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
671
+ Object.defineProperty(exports, '__esModule', {
672
+ value: true
673
+ });