@xfe-repo/web-app 1.6.2 → 2.0.0-beta.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 (48) hide show
  1. package/README.md +64 -1
  2. package/client.d.ts +1 -0
  3. package/deploy/.drone.yml +12 -5
  4. package/deploy/Dockerfile +14 -6
  5. package/deploy/helm/templates/deployment.yaml +5 -18
  6. package/deploy/helm/templates/svc.yaml +1 -1
  7. package/dist/cli.js +275 -413
  8. package/dist/cli.mjs +273 -267
  9. package/dist/config.d.mts +20 -6
  10. package/dist/config.d.ts +20 -6
  11. package/dist/config.js +83 -297
  12. package/dist/config.mjs +69 -2
  13. package/dist/framework.d.mts +10 -0
  14. package/dist/framework.d.ts +10 -0
  15. package/dist/framework.js +174 -0
  16. package/dist/framework.mjs +137 -0
  17. package/dist/react-router-config.d.mts +11 -0
  18. package/dist/react-router-config.d.ts +11 -0
  19. package/dist/react-router-config.js +66 -0
  20. package/dist/react-router-config.mjs +35 -0
  21. package/dist/root.d.mts +17 -0
  22. package/dist/root.d.ts +17 -0
  23. package/dist/root.js +61 -0
  24. package/dist/root.mjs +34 -0
  25. package/dist/serve.d.mts +10 -0
  26. package/dist/serve.d.ts +10 -0
  27. package/dist/serve.js +71 -0
  28. package/dist/serve.mjs +36 -0
  29. package/dist/vite.d.mts +9 -0
  30. package/dist/vite.d.ts +9 -0
  31. package/dist/vite.js +135 -0
  32. package/dist/vite.mjs +100 -0
  33. package/package.json +22 -71
  34. package/tsconfig.json +4 -1
  35. package/config/env.js +0 -104
  36. package/config/getHttpsConfig.js +0 -66
  37. package/config/jest/babelTransform.js +0 -29
  38. package/config/jest/cssTransform.js +0 -14
  39. package/config/jest/fileTransform.js +0 -40
  40. package/config/modules.js +0 -133
  41. package/config/paths.js +0 -65
  42. package/config/webpack/persistentCache/createEnvironmentHash.js +0 -9
  43. package/config/webpack/webpack.config.js +0 -724
  44. package/config/webpack/webpackDevServer.config.js +0 -122
  45. package/deploy/nginx.conf +0 -62
  46. package/dist/chunk-75BJNL7E.mjs +0 -239
  47. package/scripts/build.js +0 -217
  48. package/scripts/dev.js +0 -162
package/dist/cli.js CHANGED
@@ -1,433 +1,295 @@
1
1
  "use strict";
2
- function _array_like_to_array(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _array_with_holes(arr) {
8
- if (Array.isArray(arr)) return arr;
9
- }
10
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
- try {
12
- var info = gen[key](arg);
13
- var value = info.value;
14
- } catch (error) {
15
- reject(error);
16
- return;
17
- }
18
- if (info.done) {
19
- resolve(value);
20
- } else {
21
- Promise.resolve(value).then(_next, _throw);
22
- }
23
- }
24
- function _async_to_generator(fn) {
25
- return function() {
26
- var self = this, args = arguments;
27
- return new Promise(function(resolve, reject) {
28
- var gen = fn.apply(self, args);
29
- function _next(value) {
30
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
31
- }
32
- function _throw(err) {
33
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
34
- }
35
- _next(undefined);
36
- });
37
- };
38
- }
39
- function _define_property(obj, key, value) {
40
- if (key in obj) {
41
- Object.defineProperty(obj, key, {
42
- value: value,
43
- enumerable: true,
44
- configurable: true,
45
- writable: true
46
- });
47
- } else {
48
- obj[key] = value;
49
- }
50
- return obj;
51
- }
52
- function _iterable_to_array_limit(arr, i) {
53
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
54
- if (_i == null) return;
55
- var _arr = [];
56
- var _n = true;
57
- var _d = false;
58
- var _s, _e;
59
- try {
60
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
61
- _arr.push(_s.value);
62
- if (i && _arr.length === i) break;
63
- }
64
- } catch (err) {
65
- _d = true;
66
- _e = err;
67
- } finally{
68
- try {
69
- if (!_n && _i["return"] != null) _i["return"]();
70
- } finally{
71
- if (_d) throw _e;
72
- }
73
- }
74
- return _arr;
75
- }
76
- function _non_iterable_rest() {
77
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
78
- }
79
- function _object_spread(target) {
80
- for(var i = 1; i < arguments.length; i++){
81
- var source = arguments[i] != null ? arguments[i] : {};
82
- var ownKeys = Object.keys(source);
83
- if (typeof Object.getOwnPropertySymbols === "function") {
84
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
85
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
86
- }));
87
- }
88
- ownKeys.forEach(function(key) {
89
- _define_property(target, key, source[key]);
90
- });
91
- }
92
- return target;
93
- }
94
- function _sliced_to_array(arr, i) {
95
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
96
- }
97
- function _type_of(obj) {
98
- "@swc/helpers - typeof";
99
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
100
- }
101
- function _unsupported_iterable_to_array(o, minLen) {
102
- if (!o) return;
103
- if (typeof o === "string") return _array_like_to_array(o, minLen);
104
- var n = Object.prototype.toString.call(o).slice(8, -1);
105
- if (n === "Object" && o.constructor) n = o.constructor.name;
106
- if (n === "Map" || n === "Set") return Array.from(n);
107
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
108
- }
109
- function _ts_generator(thisArg, body) {
110
- var f, y, t, _ = {
111
- label: 0,
112
- sent: function() {
113
- if (t[0] & 1) throw t[1];
114
- return t[1];
115
- },
116
- trys: [],
117
- ops: []
118
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
119
- return d(g, "next", {
120
- value: verb(0)
121
- }), d(g, "throw", {
122
- value: verb(1)
123
- }), d(g, "return", {
124
- value: verb(2)
125
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
126
- value: function() {
127
- return this;
128
- }
129
- }), g;
130
- function verb(n) {
131
- return function(v) {
132
- return step([
133
- n,
134
- v
135
- ]);
136
- };
137
- }
138
- function step(op) {
139
- if (f) throw new TypeError("Generator is already executing.");
140
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
141
- 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;
142
- if (y = 0, t) op = [
143
- op[0] & 2,
144
- t.value
145
- ];
146
- switch(op[0]){
147
- case 0:
148
- case 1:
149
- t = op;
150
- break;
151
- case 4:
152
- _.label++;
153
- return {
154
- value: op[1],
155
- done: false
156
- };
157
- case 5:
158
- _.label++;
159
- y = op[1];
160
- op = [
161
- 0
162
- ];
163
- continue;
164
- case 7:
165
- op = _.ops.pop();
166
- _.trys.pop();
167
- continue;
168
- default:
169
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
170
- _ = 0;
171
- continue;
172
- }
173
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
174
- _.label = op[1];
175
- break;
176
- }
177
- if (op[0] === 6 && _.label < t[1]) {
178
- _.label = t[1];
179
- t = op;
180
- break;
181
- }
182
- if (t && _.label < t[2]) {
183
- _.label = t[2];
184
- _.ops.push(op);
185
- break;
186
- }
187
- if (t[2]) _.ops.pop();
188
- _.trys.pop();
189
- continue;
190
- }
191
- op = body.call(thisArg, _);
192
- } catch (e) {
193
- op = [
194
- 6,
195
- e
196
- ];
197
- y = 0;
198
- } finally{
199
- f = t = 0;
200
- }
201
- if (op[0] & 5) throw op[1];
202
- return {
203
- value: op[0] ? op[1] : void 0,
204
- done: true
205
- };
206
- }
207
- }
208
2
  var __create = Object.create;
209
3
  var __defProp = Object.defineProperty;
210
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
211
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
212
6
  var __getProtoOf = Object.getPrototypeOf;
213
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
214
- var __copyProps = function __copyProps(to, from, except, desc) {
215
- if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") {
216
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
217
- try {
218
- var _loop = function() {
219
- var key = _step.value;
220
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
221
- get: function get() {
222
- return from[key];
223
- },
224
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
225
- });
226
- };
227
- for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
228
- } catch (err) {
229
- _didIteratorError = true;
230
- _iteratorError = err;
231
- } finally{
232
- try {
233
- if (!_iteratorNormalCompletion && _iterator.return != null) {
234
- _iterator.return();
235
- }
236
- } finally{
237
- if (_didIteratorError) {
238
- throw _iteratorError;
239
- }
240
- }
241
- }
242
- }
243
- return to;
244
- };
245
- var __toESM = function __toESM(mod, isNodeMode, target) {
246
- return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
247
- // file that has been converted to a CommonJS file using a Babel-
248
- // compatible transform (i.e. "__esModule" has not been set), then set
249
- // "default" to the CommonJS "module.exports" for node compatibility.
250
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
251
- value: mod,
252
- enumerable: true
253
- }) : target, mod);
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") {
10
+ for (let key of __getOwnPropNames(from))
11
+ if (!__hasOwnProp.call(to, key) && key !== except)
12
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
13
+ }
14
+ return to;
254
15
  };
16
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
17
+ // If the importer is in node compatibility mode or this is not an ESM
18
+ // file that has been converted to a CommonJS file using a Babel-
19
+ // compatible transform (i.e. "__esModule" has not been set), then set
20
+ // "default" to the CommonJS "module.exports" for node compatibility.
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+
255
25
  // src/cli.ts
256
- var import_minimist = __toESM(require("minimist"));
257
- var import_child_process = require("child_process");
26
+ var import_node_child_process = require("child_process");
27
+ var import_node_fs3 = require("fs");
258
28
  var import_path2 = __toESM(require("path"));
29
+
259
30
  // src/config.ts
260
31
  var import_path = __toESM(require("path"));
261
32
  var import_fs = __toESM(require("fs"));
262
33
  var import_yaml = __toESM(require("yaml"));
263
- var loadXfeConfig = function loadXfeConfig() {
264
- var xfeConfigPath = "./xfe.json";
265
- if (!import_fs.default.existsSync(xfeConfigPath)) {
266
- throw new Error("xfe.json \u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA\u8BE5\u6587\u4EF6\u3002");
267
- }
268
- var xfeConfigContent = import_fs.default.readFileSync(xfeConfigPath, "utf8");
269
- return JSON.parse(xfeConfigContent);
34
+ var loadXfeConfig = (root = process.cwd()) => {
35
+ const xfeConfigPath = import_path.default.join(root, "xfe.json");
36
+ if (!import_fs.default.existsSync(xfeConfigPath)) {
37
+ throw new Error("xfe.json \u914D\u7F6E\u6587\u4EF6\u4E0D\u5B58\u5728\uFF0C\u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA\u8BE5\u6587\u4EF6\u3002");
38
+ }
39
+ const xfeConfigContent = import_fs.default.readFileSync(xfeConfigPath, "utf8");
40
+ const config = JSON.parse(xfeConfigContent);
41
+ const renderMode = config.webapp?.renderMode;
42
+ if (renderMode !== void 0 && renderMode !== "client" && renderMode !== "server") {
43
+ throw new Error("xfe.json.webapp.renderMode \u53EA\u80FD\u4E3A client \u6216 server");
44
+ }
45
+ return config;
270
46
  };
271
- var configDeploy = function configDeploy() {
272
- var xfeConfig = loadXfeConfig();
273
- if (!(xfeConfig === null || xfeConfig === void 0 ? void 0 : xfeConfig.deploy)) return;
274
- var droneConfigFilePath = import_path.default.resolve(__dirname, "../deploy/.drone.yml");
275
- import_fs.default.cpSync(droneConfigFilePath, xfeConfig.deploy.droneConfigPath || "./.drone.yml");
276
- var valuesYamlFilePath = import_path.default.resolve(__dirname, "../deploy/helm/values.yaml");
277
- var valuesYamlFile = import_fs.default.readFileSync(valuesYamlFilePath, "utf8");
278
- var valuesYaml = import_yaml.default.parse(valuesYamlFile);
279
- if (!valuesYaml.virtualService) valuesYaml.virtualService = {};
280
- if (!valuesYaml.virtualService.hosts) valuesYaml.virtualService.hosts = {
281
- test: [],
282
- stage: [],
283
- prod: []
284
- };
285
- var _xfeConfig_deploy = xfeConfig.deploy, _xfeConfig_deploy_virtualServiceEnabled = _xfeConfig_deploy.virtualServiceEnabled, virtualServiceEnabled = _xfeConfig_deploy_virtualServiceEnabled === void 0 ? true : _xfeConfig_deploy_virtualServiceEnabled, _xfeConfig_deploy_hostsProd = _xfeConfig_deploy.hostsProd, hostsProd = _xfeConfig_deploy_hostsProd === void 0 ? [] : _xfeConfig_deploy_hostsProd, _xfeConfig_deploy_hostsStage = _xfeConfig_deploy.hostsStage, hostsStage = _xfeConfig_deploy_hostsStage === void 0 ? [] : _xfeConfig_deploy_hostsStage, _xfeConfig_deploy_hostsTest = _xfeConfig_deploy.hostsTest, hostsTest = _xfeConfig_deploy_hostsTest === void 0 ? [] : _xfeConfig_deploy_hostsTest, _xfeConfig_deploy_gateways = _xfeConfig_deploy.gateways, gateways = _xfeConfig_deploy_gateways === void 0 ? [
286
- "common-gateway-eshetang"
287
- ] : _xfeConfig_deploy_gateways;
288
- var _xfeConfig_deploy1 = xfeConfig.deploy, _xfeConfig_deploy_targetK8s = _xfeConfig_deploy1.targetK8s, targetK8s = _xfeConfig_deploy_targetK8s === void 0 ? "saas" : _xfeConfig_deploy_targetK8s, _xfeConfig_deploy_targetNamespace = _xfeConfig_deploy1.targetNamespace, targetNamespace = _xfeConfig_deploy_targetNamespace === void 0 ? "" : _xfeConfig_deploy_targetNamespace;
289
- valuesYaml.virtualService.enabled = virtualServiceEnabled;
290
- valuesYaml.virtualService.gateways = gateways;
291
- valuesYaml.virtualService.hosts.prod = hostsProd;
292
- valuesYaml.virtualService.hosts.stage = hostsStage;
293
- valuesYaml.virtualService.hosts.test = hostsTest;
294
- valuesYaml.targetK8s = targetK8s;
295
- valuesYaml.namespace = targetNamespace;
296
- var valuesYamlStr = import_yaml.default.stringify(valuesYaml, {
297
- defaultStringType: "QUOTE_SINGLE",
298
- defaultKeyType: "PLAIN"
299
- });
300
- import_fs.default.writeFileSync(valuesYamlFilePath, valuesYamlStr, "utf8");
47
+ var configDeploy = () => {
48
+ const xfeConfig = loadXfeConfig();
49
+ if (!xfeConfig?.deploy) return;
50
+ const droneConfigFilePath = import_path.default.resolve(__dirname, "../deploy/.drone.yml");
51
+ import_fs.default.cpSync(droneConfigFilePath, xfeConfig.deploy.droneConfigPath || "./.drone.yml");
52
+ const valuesYamlFilePath = import_path.default.resolve(__dirname, "../deploy/helm/values.yaml");
53
+ const valuesYamlFile = import_fs.default.readFileSync(valuesYamlFilePath, "utf8");
54
+ const valuesYaml = import_yaml.default.parse(valuesYamlFile);
55
+ if (!valuesYaml.virtualService) valuesYaml.virtualService = {};
56
+ if (!valuesYaml.virtualService.hosts) valuesYaml.virtualService.hosts = { test: [], stage: [], prod: [] };
57
+ const {
58
+ virtualServiceEnabled = true,
59
+ hostsProd = [],
60
+ hostsStage = [],
61
+ hostsTest = [],
62
+ gateways = ["common-gateway-eshetang"]
63
+ } = xfeConfig.deploy;
64
+ const { targetK8s = "saas", targetNamespace = "" } = xfeConfig.deploy;
65
+ valuesYaml.virtualService.enabled = virtualServiceEnabled;
66
+ valuesYaml.virtualService.gateways = gateways;
67
+ valuesYaml.virtualService.hosts.prod = hostsProd;
68
+ valuesYaml.virtualService.hosts.stage = hostsStage;
69
+ valuesYaml.virtualService.hosts.test = hostsTest;
70
+ valuesYaml.targetK8s = targetK8s;
71
+ valuesYaml.namespace = targetNamespace;
72
+ const valuesYamlStr = import_yaml.default.stringify(valuesYaml, { defaultStringType: "QUOTE_SINGLE", defaultKeyType: "PLAIN" });
73
+ import_fs.default.writeFileSync(valuesYamlFilePath, valuesYamlStr, "utf8");
74
+ };
75
+ var getJwtEnv = async () => {
76
+ const xfeConfig = loadXfeConfig();
77
+ if (!xfeConfig?.jwt) return {};
78
+ const { aud = "" } = xfeConfig.jwt;
79
+ if (!aud) throw new Error("xfe.json \u4E2D\u7684 jwt \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u786E\u4FDD\u5305\u542B aud \u5B57\u6BB5\u3002");
80
+ const jwkRes = await fetch(`https://app.eshetang.com/jwk?appId=${aud}`);
81
+ if (!jwkRes.ok) {
82
+ throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25: ${jwkRes.status} ${jwkRes.statusText}`);
83
+ }
84
+ let JwkResponseJson;
85
+ try {
86
+ JwkResponseJson = await jwkRes.json();
87
+ } catch (err) {
88
+ throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25\uFF0C\u54CD\u5E94\u89E3\u6790\u9519\u8BEF: ${err.message}, response text: ${await jwkRes.text()}`);
89
+ }
90
+ const { keyId, privateKeyPkcs8 } = JwkResponseJson?.data || {};
91
+ if (!keyId || !privateKeyPkcs8) throw new Error(`\u672A\u83B7\u53D6\u5230\u9879\u76EE\u7B7E\u540D\u5BC6\u94A5, \u8BF7\u68C0\u67E5aud\u662F\u5426\u6B63\u786E: ${aud}`);
92
+ return { XFE_JWT_AUD: aud, XFE_JWT_KEY_ID: keyId, XFE_JWT_PRIVATE_KEY: privateKeyPkcs8 };
301
93
  };
302
- var getJwtEnv = function getJwtEnv() {
303
- return _async_to_generator(function() {
304
- var xfeConfig, _xfeConfig_jwt, _xfeConfig_jwt_aud, aud, jwkRes, JwkResponseJson, err, _, _1, _2, _ref, keyId, privateKeyPkcs8;
305
- return _ts_generator(this, function(_state) {
306
- switch(_state.label){
307
- case 0:
308
- xfeConfig = loadXfeConfig();
309
- if (!(xfeConfig === null || xfeConfig === void 0 ? void 0 : xfeConfig.jwt)) throw new Error("xfe.json \u4E2D\u672A\u914D\u7F6E jwt \u4FE1\u606F\uFF0C\u8BF7\u68C0\u67E5\u914D\u7F6E\u6587\u4EF6\u3002");
310
- _xfeConfig_jwt = xfeConfig.jwt, _xfeConfig_jwt_aud = _xfeConfig_jwt.aud, aud = _xfeConfig_jwt_aud === void 0 ? "" : _xfeConfig_jwt_aud;
311
- if (!aud) throw new Error("xfe.json \u4E2D\u7684 jwt \u914D\u7F6E\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u786E\u4FDD\u5305\u542B aud \u5B57\u6BB5\u3002");
312
- return [
313
- 4,
314
- fetch("https://app.eshetang.com/jwk?appId=".concat(aud))
315
- ];
316
- case 1:
317
- jwkRes = _state.sent();
318
- if (!jwkRes.ok) {
319
- throw new Error("远程获取密钥失败: ".concat(jwkRes.status, " ").concat(jwkRes.statusText));
320
- }
321
- _state.label = 2;
322
- case 2:
323
- _state.trys.push([
324
- 2,
325
- 4,
326
- ,
327
- 6
328
- ]);
329
- return [
330
- 4,
331
- jwkRes.json()
332
- ];
333
- case 3:
334
- JwkResponseJson = _state.sent();
335
- return [
336
- 3,
337
- 6
338
- ];
339
- case 4:
340
- err = _state.sent();
341
- _ = Error.bind;
342
- _2 = (_1 = "远程获取密钥失败,响应解析错误: ".concat(err.message, ", response text: ")).concat;
343
- return [
344
- 4,
345
- jwkRes.text()
346
- ];
347
- case 5:
348
- throw new (_.apply(Error, [
349
- void 0,
350
- _2.apply(_1, [
351
- _state.sent()
352
- ])
353
- ]));
354
- case 6:
355
- _ref = (JwkResponseJson === null || JwkResponseJson === void 0 ? void 0 : JwkResponseJson.data) || {}, keyId = _ref.keyId, privateKeyPkcs8 = _ref.privateKeyPkcs8;
356
- if (!keyId || !privateKeyPkcs8) throw new Error("未获取到项目签名密钥, 请检查aud是否正确: ".concat(aud));
357
- return [
358
- 2,
359
- {
360
- XFE_JWT_AUD: aud,
361
- XFE_JWT_KEY_ID: keyId,
362
- XFE_JWT_PRIVATE_KEY: privateKeyPkcs8
363
- }
364
- ];
365
- }
366
- });
367
- })();
94
+
95
+ // src/framework.ts
96
+ var import_node_fs = __toESM(require("fs"));
97
+ var import_node_module = require("module");
98
+ var import_node_path = __toESM(require("path"));
99
+ var import_node_url = require("url");
100
+ var import_meta = {};
101
+ var frameworkDirectory = typeof __dirname === "string" ? __dirname : import_node_path.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
102
+ var requireFromFramework = (0, import_node_module.createRequire)(import_node_path.default.join(frameworkDirectory, "framework.js"));
103
+ var extensions = [".tsx", ".ts", ".jsx", ".js"];
104
+ var findSource = (directory, name) => extensions.map((extension) => import_node_path.default.join(directory, `${name}${extension}`)).find(import_node_fs.default.existsSync);
105
+ var findValueExports = (file) => [...import_node_fs.default.readFileSync(file, "utf8").matchAll(/^\s*export\s+(?:async\s+)?(?:const|let|var|function|class)\s+([A-Za-z_$][\w$]*)/gm)].map(
106
+ ([, name]) => name
107
+ );
108
+ var importPath = (from, target) => {
109
+ const relative = import_node_path.default.relative(from, target).replace(import_node_path.default.extname(target), "").replaceAll(import_node_path.default.sep, "/");
110
+ return relative.startsWith(".") ? relative : `./${relative}`;
368
111
  };
112
+ var writeGenerated = (file, content) => {
113
+ if (import_node_fs.default.existsSync(file) && import_node_fs.default.readFileSync(file, "utf8") === content) return;
114
+ import_node_fs.default.writeFileSync(file, content);
115
+ };
116
+ var defaultRootSource = (projectRoot, appDirectory) => {
117
+ const { webapp = {} } = loadXfeConfig(projectRoot);
118
+ const layoutSource = findSource(import_node_path.default.join(projectRoot, "src"), "layout");
119
+ const layoutExports = layoutSource ? findValueExports(layoutSource) : [];
120
+ const hasErrorView = layoutExports.includes("ErrorView");
121
+ const layoutImport = layoutSource ? `import AppLayout${hasErrorView ? ", { ErrorView }" : ""} from ${JSON.stringify(importPath(appDirectory, layoutSource))}
122
+ ` : "";
123
+ return `import { createElement, type ReactNode } from 'react'
124
+ import { Outlet } from 'react-router'
125
+ import { Document, PageError, PageLoading } from '@xfe-repo/web-app/dist/root.mjs'
126
+ ${layoutImport}
127
+ export const meta = () => [{ title: ${JSON.stringify(webapp.title || "XFE App")} }]
128
+ export const Layout = ({ children }: { children: ReactNode }) => createElement(Document, { children, lang: ${JSON.stringify(webapp.lang || "zh-CN")}, themeColor: ${JSON.stringify(webapp.themeColor)} })
129
+ export default function Root() { return ${layoutSource ? "createElement(AppLayout, { children: createElement(Outlet) })" : "createElement(Outlet)"} }
130
+ export function ErrorBoundary() { return createElement(PageError, { ${hasErrorView ? "view: ErrorView" : ""} }) }
131
+ export function HydrateFallback() { return createElement(PageLoading) }
132
+ `;
133
+ };
134
+ var getFrameworkRoot = (projectRoot) => import_node_path.default.join(projectRoot, "node_modules/.cache/xfe-web/react-router");
135
+ var prepareFramework = (projectRoot = process.cwd()) => {
136
+ const sourceDirectory = import_node_path.default.join(projectRoot, "src");
137
+ const rootSource = findSource(sourceDirectory, "root");
138
+ const appServerSource = findSource(sourceDirectory, "app.server");
139
+ const pagesSource = import_node_path.default.join(sourceDirectory, "pages");
140
+ if (!import_node_fs.default.existsSync(pagesSource)) throw new Error("\u672A\u627E\u5230 src/pages");
141
+ const rootDirectory = getFrameworkRoot(projectRoot);
142
+ const appDirectory = import_node_path.default.join(rootDirectory, "app");
143
+ import_node_fs.default.mkdirSync(appDirectory, { recursive: true });
144
+ const routerDirectory = import_node_path.default.dirname(requireFromFramework.resolve("react-router/package.json"));
145
+ const routerLink = import_node_path.default.join(rootDirectory, "node_modules/react-router");
146
+ import_node_fs.default.mkdirSync(import_node_path.default.dirname(routerLink), { recursive: true });
147
+ if (!import_node_fs.default.lstatSync(routerLink, { throwIfNoEntry: false })?.isSymbolicLink() || import_node_fs.default.readlinkSync(routerLink) !== routerDirectory) {
148
+ import_node_fs.default.rmSync(routerLink, { force: true });
149
+ import_node_fs.default.symlinkSync(routerDirectory, routerLink, "junction");
150
+ }
151
+ const rootTarget = import_node_path.default.join(appDirectory, "root.tsx");
152
+ const rootImport = rootSource ? importPath(appDirectory, rootSource) : "";
153
+ const rootExports = rootSource ? findValueExports(rootSource).filter((name) => name !== "middleware" || !appServerSource) : [];
154
+ const namedExports = rootExports.length ? `export { ${rootExports.join(", ")} } from ${JSON.stringify(rootImport)}
155
+ ` : "";
156
+ const errorBoundaryExport = rootExports.includes("ErrorBoundary") ? "" : "export { DefaultErrorBoundary as ErrorBoundary } from '@xfe-repo/web-router/errors'\n";
157
+ const middlewareExport = appServerSource ? `export { middleware } from ${JSON.stringify(importPath(appDirectory, appServerSource))}
158
+ ` : "";
159
+ writeGenerated(
160
+ rootTarget,
161
+ rootSource ? `export * from ${JSON.stringify(rootImport)}
162
+ export { default } from ${JSON.stringify(rootImport)}
163
+ ${namedExports}${errorBoundaryExport}${middlewareExport}` : `${defaultRootSource(projectRoot, appDirectory)}${middlewareExport}`
164
+ );
165
+ const pagesLink = import_node_path.default.join(appDirectory, "pages");
166
+ if (!import_node_fs.default.existsSync(pagesLink)) import_node_fs.default.symlinkSync(import_node_path.default.relative(appDirectory, pagesSource), pagesLink, "dir");
167
+ writeGenerated(
168
+ import_node_path.default.join(rootDirectory, "react-router.config.js"),
169
+ "export { default } from '@xfe-repo/web-app/dist/react-router-config.mjs'\n"
170
+ );
171
+ writeGenerated(
172
+ import_node_path.default.join(appDirectory, "routes.js"),
173
+ `import { collectPageRoutes } from '@xfe-repo/web-router/routes'
174
+ export default collectPageRoutes(${JSON.stringify(appDirectory)})
175
+ `
176
+ );
177
+ const defaultsDirectory = import_node_path.default.join(import_node_path.default.dirname(requireFromFramework.resolve("@react-router/dev/package.json")), "dist/config/defaults");
178
+ writeGenerated(
179
+ import_node_path.default.join(appDirectory, "entry.server.tsx"),
180
+ `export { default, streamTimeout } from ${JSON.stringify(importPath(appDirectory, import_node_path.default.join(defaultsDirectory, "entry.server.web.tsx")))}
181
+ `
182
+ );
183
+ const typeScriptConfig = import_node_path.default.join(rootDirectory, "tsconfig.json");
184
+ writeGenerated(
185
+ typeScriptConfig,
186
+ JSON.stringify(
187
+ {
188
+ extends: import_node_path.default.join(projectRoot, "tsconfig.json"),
189
+ compilerOptions: { rootDirs: [projectRoot, rootDirectory, import_node_path.default.join(rootDirectory, ".react-router/types")] },
190
+ include: [
191
+ import_node_path.default.join(sourceDirectory, "**/*"),
192
+ import_node_path.default.join(projectRoot, "types/**/*"),
193
+ import_node_path.default.join(appDirectory, "*.tsx"),
194
+ import_node_path.default.join(rootDirectory, ".react-router/types/**/*")
195
+ ],
196
+ exclude: []
197
+ },
198
+ null,
199
+ 2
200
+ )
201
+ );
202
+ return {
203
+ appDirectory,
204
+ rootDirectory,
205
+ viteConfig: import_node_path.default.resolve(frameworkDirectory, "vite.mjs"),
206
+ typeScriptConfig
207
+ };
208
+ };
209
+
210
+ // src/serve.ts
211
+ var import_node_fs2 = require("fs");
212
+ var import_node_path2 = __toESM(require("path"));
213
+ var import_express = __toESM(require("express"));
214
+ var serveClient = ({
215
+ directory,
216
+ host,
217
+ port,
218
+ basename = "/"
219
+ }) => {
220
+ const indexFile = import_node_path2.default.join(directory, "index.html");
221
+ if (!(0, import_node_fs2.existsSync)(indexFile)) throw new Error(`\u672A\u627E\u5230 SPA \u5165\u53E3 ${indexFile}\uFF0C\u8BF7\u5148\u6267\u884C xfe-web build`);
222
+ const app = (0, import_express.default)().disable("x-powered-by");
223
+ const router = import_express.default.Router();
224
+ app.use((_request, response, next) => {
225
+ response.setHeader("Access-Control-Allow-Origin", "*");
226
+ next();
227
+ });
228
+ app.use(
229
+ "/assets",
230
+ import_express.default.static(import_node_path2.default.join(directory, "assets"), { immutable: true, maxAge: "1y" }),
231
+ (_request, response) => response.status(404).end()
232
+ );
233
+ app.use(import_express.default.static(directory));
234
+ router.get("/{*path}", (_request, response) => response.sendFile(indexFile));
235
+ app.use(basename, router);
236
+ const server = app.listen(port, host);
237
+ server.once("listening", () => {
238
+ const address = server.address();
239
+ console.log(`[xfe-web] SPA http://${host}:${typeof address === "object" && address ? address.port : port}${basename}`);
240
+ });
241
+ return server;
242
+ };
243
+
369
244
  // src/cli.ts
370
- var argv = (0, import_minimist.default)(process.argv.slice(2));
371
- var commands = argv._;
372
- var _commands = _sliced_to_array(commands, 1), command = _commands[0];
373
- var appPackageRoot = import_path2.default.resolve(__dirname, "../");
374
- function main() {
375
- return _async_to_generator(function() {
376
- var jwtEnv, jwtEnv1;
377
- return _ts_generator(this, function(_state) {
378
- switch(_state.label){
379
- case 0:
380
- if (!(command === "dev")) return [
381
- 3,
382
- 2
383
- ];
384
- return [
385
- 4,
386
- getJwtEnv()
387
- ];
388
- case 1:
389
- jwtEnv = _state.sent();
390
- (0, import_child_process.execSync)("node ".concat(import_path2.default.join(appPackageRoot, "scripts/dev.js")), {
391
- stdio: "inherit",
392
- env: _object_spread({}, process.env, jwtEnv)
393
- });
394
- return [
395
- 3,
396
- 5
397
- ];
398
- case 2:
399
- if (!(command === "build")) return [
400
- 3,
401
- 4
402
- ];
403
- return [
404
- 4,
405
- getJwtEnv()
406
- ];
407
- case 3:
408
- jwtEnv1 = _state.sent();
409
- (0, import_child_process.execSync)("node ".concat(import_path2.default.join(appPackageRoot, "scripts/build.js")), {
410
- stdio: "inherit",
411
- env: _object_spread({}, process.env, jwtEnv1)
412
- });
413
- return [
414
- 3,
415
- 5
416
- ];
417
- case 4:
418
- if (command === "config") {
419
- configDeploy();
420
- }
421
- _state.label = 5;
422
- case 5:
423
- return [
424
- 2
425
- ];
426
- }
427
- });
428
- })();
245
+ var [command, ...args] = process.argv.slice(2);
246
+ var resolveBin = (packageName) => import_path2.default.join(import_path2.default.dirname(require.resolve(`${packageName}/package.json`)), packageName === "typescript" ? "lib/tsc.js" : "bin.cjs");
247
+ var run = (packageName, commandArgs, options = {}) => {
248
+ const result = (0, import_node_child_process.spawnSync)(process.execPath, [resolveBin(packageName), ...commandArgs], {
249
+ stdio: "inherit",
250
+ env: options.env,
251
+ cwd: options.cwd
252
+ });
253
+ if (result.error) throw result.error;
254
+ if (result.status !== 0) process.exit(result.status ?? 1);
255
+ };
256
+ async function main() {
257
+ const projectRoot = process.cwd();
258
+ if (command === "config") return configDeploy();
259
+ if (command === "start") {
260
+ const { webapp = {} } = loadXfeConfig(projectRoot);
261
+ if (webapp.renderMode === "client") {
262
+ serveClient({
263
+ directory: import_path2.default.join(projectRoot, "build/client"),
264
+ host: process.env.HOST || webapp.host || "0.0.0.0",
265
+ port: Number(process.env.PORT ?? webapp.port ?? 3e3),
266
+ basename: webapp.basename
267
+ });
268
+ return;
269
+ }
270
+ const rootDirectory = getFrameworkRoot(projectRoot);
271
+ (0, import_node_fs3.mkdirSync)(rootDirectory, { recursive: true });
272
+ return run("@react-router/serve", [import_path2.default.join(projectRoot, "build/server/index.js"), ...args], {
273
+ cwd: rootDirectory,
274
+ env: { ...process.env, ...await getJwtEnv() }
275
+ });
276
+ }
277
+ if (!command || !["dev", "build", "typegen", "typecheck"].includes(command)) {
278
+ throw new Error(`\u4E0D\u652F\u6301\u7684\u547D\u4EE4: ${command || "undefined"}\uFF0C\u53EF\u7528\u547D\u4EE4: dev\u3001build\u3001typegen\u3001typecheck\u3001start\u3001config`);
279
+ }
280
+ const framework = prepareFramework(projectRoot);
281
+ const env = { ...process.env, XFE_WEB_ROOT: projectRoot };
282
+ const options = { cwd: framework.rootDirectory, env };
283
+ if (command === "typegen" || command === "typecheck") {
284
+ run("@react-router/dev", ["typegen", ...command === "typegen" ? args : []], options);
285
+ if (command === "typecheck") run("typescript", ["--noEmit", "--project", framework.typeScriptConfig, ...args]);
286
+ return;
287
+ }
288
+ Object.assign(env, await getJwtEnv());
289
+ if (command === "build") delete env.XFE_JWT_PRIVATE_KEY;
290
+ run("@react-router/dev", [command, framework.rootDirectory, "--config", framework.viteConfig, ...args], options);
429
291
  }
430
- main().catch(function(err) {
431
- console.error("XFE Web CLI \u6267\u884C\u51FA\u9519:", err);
432
- process.exit(1);
292
+ main().catch((err) => {
293
+ console.error("XFE Web CLI \u6267\u884C\u51FA\u9519:", err);
294
+ process.exit(1);
433
295
  });