@modern-js/plugin-bff 2.31.2 → 2.31.3-alpha.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.
@@ -0,0 +1,88 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
5
+ var __export = (target, all) => {
6
+ for (var name in all)
7
+ __defProp(target, name, { get: all[name], enumerable: true });
8
+ };
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") {
11
+ for (let key of __getOwnPropNames(from))
12
+ if (!__hasOwnProp.call(to, key) && key !== except)
13
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
+ }
15
+ return to;
16
+ };
17
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
18
+ var __async = (__this, __arguments, generator) => {
19
+ return new Promise((resolve, reject) => {
20
+ var fulfilled = (value) => {
21
+ try {
22
+ step(generator.next(value));
23
+ } catch (e) {
24
+ reject(e);
25
+ }
26
+ };
27
+ var rejected = (value) => {
28
+ try {
29
+ step(generator.throw(value));
30
+ } catch (e) {
31
+ reject(e);
32
+ }
33
+ };
34
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
35
+ step((generator = generator.apply(__this, __arguments)).next());
36
+ });
37
+ };
38
+ var loader_exports = {};
39
+ __export(loader_exports, {
40
+ default: () => loader_default
41
+ });
42
+ module.exports = __toCommonJS(loader_exports);
43
+ var import_bff_core = require("@modern-js/bff-core");
44
+ var import_utils = require("@modern-js/utils");
45
+ function loader(source) {
46
+ return __async(this, null, function* () {
47
+ this.cacheable();
48
+ const callback = this.async();
49
+ const draftOptions = this.getOptions();
50
+ const { resourcePath } = this;
51
+ const warning = `The file ${resourcePath} is not allowd to be imported in src directory, only API definition files are allowed.`;
52
+ if (!draftOptions.existLambda) {
53
+ import_utils.logger.warn(warning);
54
+ callback(null, `throw new Error('${warning}')`);
55
+ return;
56
+ }
57
+ const options = {
58
+ prefix: Array.isArray(draftOptions.prefix) ? draftOptions.prefix[0] : draftOptions.prefix,
59
+ apiDir: draftOptions.apiDir,
60
+ target: draftOptions.target,
61
+ port: Number(draftOptions.port),
62
+ source,
63
+ resourcePath
64
+ };
65
+ const { lambdaDir } = draftOptions;
66
+ if (!resourcePath.startsWith(lambdaDir)) {
67
+ import_utils.logger.warn(warning);
68
+ callback(null, `throw new Error('${warning}')`);
69
+ return;
70
+ }
71
+ if (draftOptions.fetcher) {
72
+ options.fetcher = draftOptions.fetcher;
73
+ }
74
+ if (draftOptions.requestCreator) {
75
+ options.requestCreator = draftOptions.requestCreator;
76
+ }
77
+ options.requireResolve = require.resolve;
78
+ const result = yield (0, import_bff_core.generateClient)(options);
79
+ if (result.isOk) {
80
+ callback(void 0, result.value);
81
+ } else {
82
+ callback(void 0, `throw new Error('${result.value}')`);
83
+ }
84
+ });
85
+ }
86
+ var loader_default = loader;
87
+ // Annotate the CommonJS export names for ESM import in node:
88
+ 0 && (module.exports = {});
@@ -0,0 +1,113 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __defProps = Object.defineProperties;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
+ var __getProtoOf = Object.getPrototypeOf;
9
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
10
+ var __propIsEnum = Object.prototype.propertyIsEnumerable;
11
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
12
+ var __spreadValues = (a, b) => {
13
+ for (var prop in b || (b = {}))
14
+ if (__hasOwnProp.call(b, prop))
15
+ __defNormalProp(a, prop, b[prop]);
16
+ if (__getOwnPropSymbols)
17
+ for (var prop of __getOwnPropSymbols(b)) {
18
+ if (__propIsEnum.call(b, prop))
19
+ __defNormalProp(a, prop, b[prop]);
20
+ }
21
+ return a;
22
+ };
23
+ var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
24
+ var __export = (target, all) => {
25
+ for (var name in all)
26
+ __defProp(target, name, { get: all[name], enumerable: true });
27
+ };
28
+ var __copyProps = (to, from, except, desc) => {
29
+ if (from && typeof from === "object" || typeof from === "function") {
30
+ for (let key of __getOwnPropNames(from))
31
+ if (!__hasOwnProp.call(to, key) && key !== except)
32
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
33
+ }
34
+ return to;
35
+ };
36
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
37
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
38
+ mod
39
+ ));
40
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
41
+ var server_exports = {};
42
+ __export(server_exports, {
43
+ default: () => server_default
44
+ });
45
+ module.exports = __toCommonJS(server_exports);
46
+ var import_path = __toESM(require("path"));
47
+ var import_bff_core = require("@modern-js/bff-core");
48
+ var import_utils = require("@modern-js/utils");
49
+ var import_constants = require("./constants");
50
+ class Storage {
51
+ constructor() {
52
+ this.middlewares = [];
53
+ }
54
+ reset() {
55
+ this.middlewares = [];
56
+ }
57
+ }
58
+ const createTransformAPI = (storage) => ({
59
+ addMiddleware(fn) {
60
+ storage.middlewares.push(fn);
61
+ }
62
+ });
63
+ var server_default = () => ({
64
+ name: "@modern-js/plugin-bff",
65
+ setup: (api) => {
66
+ const storage = new Storage();
67
+ const transformAPI = createTransformAPI(storage);
68
+ let apiAppPath = "";
69
+ return {
70
+ prepare() {
71
+ const { appDirectory, distDirectory } = api.useAppContext();
72
+ const root = (0, import_utils.isProd)() ? distDirectory : appDirectory;
73
+ const apiPath = import_path.default.resolve(root || process.cwd(), import_utils.API_DIR);
74
+ apiAppPath = import_path.default.resolve(apiPath, import_constants.API_APP_NAME);
75
+ const apiMod = (0, import_utils.requireExistModule)(apiAppPath);
76
+ if (apiMod && typeof apiMod === "function") {
77
+ apiMod(transformAPI);
78
+ }
79
+ },
80
+ reset() {
81
+ storage.reset();
82
+ const newApiModule = (0, import_utils.requireExistModule)(apiAppPath);
83
+ if (newApiModule && typeof newApiModule === "function") {
84
+ newApiModule(transformAPI);
85
+ }
86
+ },
87
+ gather({ addAPIMiddleware }) {
88
+ storage.middlewares.forEach((mid) => {
89
+ addAPIMiddleware(mid);
90
+ });
91
+ },
92
+ prepareApiServer(props, next) {
93
+ const { pwd, prefix } = props;
94
+ const apiDir = import_path.default.resolve(pwd, import_utils.API_DIR);
95
+ const appContext = api.useAppContext();
96
+ const apiRouter = new import_bff_core.ApiRouter({
97
+ apiDir,
98
+ prefix
99
+ });
100
+ const apiMode = apiRouter.getApiMode();
101
+ const apiHandlerInfos = apiRouter.getApiHandlers();
102
+ api.setAppContext(__spreadProps(__spreadValues({}, appContext), {
103
+ apiRouter,
104
+ apiHandlerInfos,
105
+ apiMode
106
+ }));
107
+ return next(props);
108
+ }
109
+ };
110
+ }
111
+ });
112
+ // Annotate the CommonJS export names for ESM import in node:
113
+ 0 && (module.exports = {});
@@ -0,0 +1,309 @@
1
+ function _arrayLikeToArray(arr, len) {
2
+ if (len == null || len > arr.length) len = arr.length;
3
+ for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
4
+ return arr2;
5
+ }
6
+ function _arrayWithoutHoles(arr) {
7
+ if (Array.isArray(arr)) return _arrayLikeToArray(arr);
8
+ }
9
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
10
+ try {
11
+ var info = gen[key](arg);
12
+ var value = info.value;
13
+ } catch (error) {
14
+ reject(error);
15
+ return;
16
+ }
17
+ if (info.done) {
18
+ resolve(value);
19
+ } else {
20
+ Promise.resolve(value).then(_next, _throw);
21
+ }
22
+ }
23
+ function _asyncToGenerator(fn) {
24
+ return function() {
25
+ var self = this, args = arguments;
26
+ return new Promise(function(resolve, reject) {
27
+ var gen = fn.apply(self, args);
28
+ function _next(value) {
29
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
+ }
31
+ function _throw(err) {
32
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
33
+ }
34
+ _next(undefined);
35
+ });
36
+ };
37
+ }
38
+ function _iterableToArray(iter) {
39
+ if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
40
+ }
41
+ function _nonIterableSpread() {
42
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
43
+ }
44
+ function _toConsumableArray(arr) {
45
+ return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();
46
+ }
47
+ function _unsupportedIterableToArray(o, minLen) {
48
+ if (!o) return;
49
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
50
+ var n = Object.prototype.toString.call(o).slice(8, -1);
51
+ if (n === "Object" && o.constructor) n = o.constructor.name;
52
+ if (n === "Map" || n === "Set") return Array.from(n);
53
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
54
+ }
55
+ var __generator = this && this.__generator || function(thisArg, body) {
56
+ var f, y, t, g, _ = {
57
+ label: 0,
58
+ sent: function() {
59
+ if (t[0] & 1) throw t[1];
60
+ return t[1];
61
+ },
62
+ trys: [],
63
+ ops: []
64
+ };
65
+ return g = {
66
+ next: verb(0),
67
+ "throw": verb(1),
68
+ "return": verb(2)
69
+ }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
70
+ return this;
71
+ }), g;
72
+ function verb(n) {
73
+ return function(v) {
74
+ return step([
75
+ n,
76
+ v
77
+ ]);
78
+ };
79
+ }
80
+ function step(op) {
81
+ if (f) throw new TypeError("Generator is already executing.");
82
+ while(_)try {
83
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
84
+ if (y = 0, t) op = [
85
+ op[0] & 2,
86
+ t.value
87
+ ];
88
+ switch(op[0]){
89
+ case 0:
90
+ case 1:
91
+ t = op;
92
+ break;
93
+ case 4:
94
+ _.label++;
95
+ return {
96
+ value: op[1],
97
+ done: false
98
+ };
99
+ case 5:
100
+ _.label++;
101
+ y = op[1];
102
+ op = [
103
+ 0
104
+ ];
105
+ continue;
106
+ case 7:
107
+ op = _.ops.pop();
108
+ _.trys.pop();
109
+ continue;
110
+ default:
111
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
112
+ _ = 0;
113
+ continue;
114
+ }
115
+ if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
116
+ _.label = op[1];
117
+ break;
118
+ }
119
+ if (op[0] === 6 && _.label < t[1]) {
120
+ _.label = t[1];
121
+ t = op;
122
+ break;
123
+ }
124
+ if (t && _.label < t[2]) {
125
+ _.label = t[2];
126
+ _.ops.push(op);
127
+ break;
128
+ }
129
+ if (t[2]) _.ops.pop();
130
+ _.trys.pop();
131
+ continue;
132
+ }
133
+ op = body.call(thisArg, _);
134
+ } catch (e) {
135
+ op = [
136
+ 6,
137
+ e
138
+ ];
139
+ y = 0;
140
+ } finally{
141
+ f = t = 0;
142
+ }
143
+ if (op[0] & 5) throw op[1];
144
+ return {
145
+ value: op[0] ? op[1] : void 0,
146
+ done: true
147
+ };
148
+ }
149
+ };
150
+ import path from "path";
151
+ import { fs, API_DIR, PLUGIN_SCHEMAS, normalizeOutputPath, SHARED_DIR, isProd } from "@modern-js/utils";
152
+ import { compile } from "@modern-js/server-utils";
153
+ import { ApiRouter } from "@modern-js/bff-core";
154
+ import { registerModernRuntimePath } from "./helper";
155
+ var DEFAULT_API_PREFIX = "/api";
156
+ var TS_CONFIG_FILENAME = "tsconfig.json";
157
+ var cli_default = function() {
158
+ return {
159
+ name: "@modern-js/plugin-bff",
160
+ setup: function(api) {
161
+ var unRegisterResolveRuntimePath = null;
162
+ return {
163
+ validateSchema: function validateSchema() {
164
+ return PLUGIN_SCHEMAS["@modern-js/plugin-bff"];
165
+ },
166
+ config: function config() {
167
+ return {
168
+ tools: {
169
+ webpackChain: function(chain, param) {
170
+ var name = param.name, CHAIN_ID = param.CHAIN_ID;
171
+ var ref = api.useAppContext(), appDirectory = ref.appDirectory, port = ref.port;
172
+ var modernConfig = api.useResolvedConfigContext();
173
+ var bff = (modernConfig || {}).bff;
174
+ var prefix = (bff === null || bff === void 0 ? void 0 : bff.prefix) || DEFAULT_API_PREFIX;
175
+ var rootDir = path.resolve(appDirectory, API_DIR);
176
+ chain.resolve.alias.set("@api", rootDir);
177
+ var apiRouter = new ApiRouter({
178
+ apiDir: rootDir,
179
+ prefix: prefix
180
+ });
181
+ var lambdaDir = apiRouter.getLambdaDir();
182
+ var existLambda = apiRouter.isExistLambda();
183
+ var apiRegexp = new RegExp(normalizeOutputPath("".concat(rootDir).concat(path.sep, ".*(.[tj]s)$")));
184
+ chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(apiRegexp);
185
+ chain.module.rule(CHAIN_ID.RULE.JS_BFF_API).test(apiRegexp).use("custom-loader").loader(require.resolve("./loader").replace(/\\/g, "/")).options({
186
+ prefix: prefix,
187
+ apiDir: rootDir,
188
+ lambdaDir: lambdaDir,
189
+ existLambda: existLambda,
190
+ port: port,
191
+ target: name
192
+ });
193
+ }
194
+ },
195
+ source: {
196
+ moduleScopes: [
197
+ "./".concat(API_DIR),
198
+ /create-request/
199
+ ]
200
+ }
201
+ };
202
+ },
203
+ modifyServerRoutes: function modifyServerRoutes(param) {
204
+ var routes = param.routes;
205
+ var modernConfig = api.useResolvedConfigContext();
206
+ var bff = (modernConfig || {}).bff;
207
+ var prefix = (bff === null || bff === void 0 ? void 0 : bff.prefix) || "/api";
208
+ var prefixList = [];
209
+ if (Array.isArray(prefix)) {
210
+ var _prefixList;
211
+ (_prefixList = prefixList).push.apply(_prefixList, _toConsumableArray(prefix));
212
+ } else {
213
+ prefixList.push(prefix);
214
+ }
215
+ var apiServerRoutes = prefixList.map(function(pre) {
216
+ return {
217
+ urlPath: pre,
218
+ isApi: true,
219
+ entryPath: "",
220
+ isSPA: false,
221
+ isSSR: false
222
+ };
223
+ });
224
+ return {
225
+ routes: routes.concat(apiServerRoutes)
226
+ };
227
+ },
228
+ collectServerPlugins: function collectServerPlugins(param) {
229
+ var plugins = param.plugins;
230
+ plugins.push({
231
+ "@modern-js/plugin-bff": "@modern-js/plugin-bff/server"
232
+ });
233
+ return {
234
+ plugins: plugins
235
+ };
236
+ },
237
+ beforeBuild: function beforeBuild() {
238
+ return _asyncToGenerator(function() {
239
+ var internalDirectory;
240
+ return __generator(this, function(_state) {
241
+ if (isProd()) {
242
+ internalDirectory = api.useAppContext().internalDirectory;
243
+ unRegisterResolveRuntimePath = registerModernRuntimePath(internalDirectory);
244
+ }
245
+ return [
246
+ 2
247
+ ];
248
+ });
249
+ })();
250
+ },
251
+ afterBuild: function afterBuild() {
252
+ return _asyncToGenerator(function() {
253
+ var ref, appDirectory, distDirectory, modernConfig, distDir, apiDir, sharedDir, tsconfigPath, sourceDirs, server, _source, alias, define, globalVars, babel;
254
+ return __generator(this, function(_state) {
255
+ switch(_state.label){
256
+ case 0:
257
+ if (unRegisterResolveRuntimePath) {
258
+ unRegisterResolveRuntimePath();
259
+ }
260
+ ref = api.useAppContext(), appDirectory = ref.appDirectory, distDirectory = ref.distDirectory;
261
+ modernConfig = api.useResolvedConfigContext();
262
+ distDir = path.resolve(distDirectory);
263
+ apiDir = path.resolve(appDirectory, API_DIR);
264
+ sharedDir = path.resolve(appDirectory, SHARED_DIR);
265
+ tsconfigPath = path.resolve(appDirectory, TS_CONFIG_FILENAME);
266
+ sourceDirs = [];
267
+ if (fs.existsSync(apiDir)) {
268
+ sourceDirs.push(apiDir);
269
+ }
270
+ if (fs.existsSync(sharedDir)) {
271
+ sourceDirs.push(sharedDir);
272
+ }
273
+ server = modernConfig.server;
274
+ _source = modernConfig.source, alias = _source.alias, define = _source.define, globalVars = _source.globalVars;
275
+ babel = modernConfig.tools.babel;
276
+ if (!(sourceDirs.length > 0)) return [
277
+ 3,
278
+ 2
279
+ ];
280
+ return [
281
+ 4,
282
+ compile(appDirectory, {
283
+ server: server,
284
+ alias: alias,
285
+ define: define,
286
+ globalVars: globalVars,
287
+ babelConfig: babel
288
+ }, {
289
+ sourceDirs: sourceDirs,
290
+ distDir: distDir,
291
+ tsconfigPath: tsconfigPath
292
+ })
293
+ ];
294
+ case 1:
295
+ _state.sent();
296
+ _state.label = 2;
297
+ case 2:
298
+ return [
299
+ 2
300
+ ];
301
+ }
302
+ });
303
+ })();
304
+ }
305
+ };
306
+ }
307
+ };
308
+ };
309
+ export { cli_default as default };
@@ -0,0 +1,11 @@
1
+ var API_APP_NAME = "_app";
2
+ var BUILD_FILES = [
3
+ "**/*.[tj]sx?",
4
+ "!**/*.test.jsx?",
5
+ "!**/*.test.tsx?",
6
+ "!**/*.spec.jsx?",
7
+ "!**/*.spec.tsx?",
8
+ "!__tests__/*.tsx?",
9
+ "!__tests__/*.jsx?"
10
+ ];
11
+ export { API_APP_NAME, BUILD_FILES };
@@ -0,0 +1,23 @@
1
+ function _defineProperty(obj, key, value) {
2
+ if (key in obj) {
3
+ Object.defineProperty(obj, key, {
4
+ value: value,
5
+ enumerable: true,
6
+ configurable: true,
7
+ writable: true
8
+ });
9
+ } else {
10
+ obj[key] = value;
11
+ }
12
+ return obj;
13
+ }
14
+ import * as path from "path";
15
+ import { registerPaths } from "@modern-js/bff-core";
16
+ var serverRuntimeAlias = "@modern-js/runtime/server";
17
+ var serverRuntimePath = ".runtime-exports/server";
18
+ var registerModernRuntimePath = function(internalDirectory) {
19
+ var paths = _defineProperty({}, serverRuntimeAlias, path.join(internalDirectory, serverRuntimePath));
20
+ var unRegister = registerPaths(paths);
21
+ return unRegister;
22
+ };
23
+ export { registerModernRuntimePath };
@@ -0,0 +1 @@
1
+ export * from "./constants";