@xfe-repo/mini-app 2.0.0-beta.1 → 2.0.0-beta.2

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.
package/dist/cli.js CHANGED
@@ -1,744 +1,544 @@
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 _array_without_holes(arr) {
11
- if (Array.isArray(arr)) return _array_like_to_array(arr);
12
- }
13
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
14
- try {
15
- var info = gen[key](arg);
16
- var value = info.value;
17
- } catch (error) {
18
- reject(error);
19
- return;
20
- }
21
- if (info.done) {
22
- resolve(value);
23
- } else {
24
- Promise.resolve(value).then(_next, _throw);
25
- }
26
- }
27
- function _async_to_generator(fn) {
28
- return function() {
29
- var self = this, args = arguments;
30
- return new Promise(function(resolve, reject) {
31
- var gen = fn.apply(self, args);
32
- function _next(value) {
33
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
34
- }
35
- function _throw(err) {
36
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
37
- }
38
- _next(undefined);
39
- });
40
- };
41
- }
42
- function _define_property(obj, key, value) {
43
- if (key in obj) {
44
- Object.defineProperty(obj, key, {
45
- value: value,
46
- enumerable: true,
47
- configurable: true,
48
- writable: true
49
- });
50
- } else {
51
- obj[key] = value;
52
- }
53
- return obj;
54
- }
55
- function _inherits(subClass, superClass) {
56
- if (typeof superClass !== "function" && superClass !== null) {
57
- throw new TypeError("Super expression must either be null or a function");
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+
32
+ // ../../shared/deploy/workspace.ts
33
+ var workspace_exports = {};
34
+ __export(workspace_exports, {
35
+ configWorkspace: () => configWorkspace,
36
+ printDeployment: () => printDeployment
37
+ });
38
+ function configWorkspace({ workspaceRoot, frameworkRoot }) {
39
+ const root = import_node_fs2.default.realpathSync(workspaceRoot);
40
+ const configuration = readJson(import_node_path3.default.join(root, "xfe.json"));
41
+ const applications = configuration.deploy?.applications;
42
+ const targets = configuration.deploy?.targets ?? Object.keys(applications ?? {});
43
+ if (!applications || typeof applications !== "object" || Array.isArray(applications)) {
44
+ throw new Error("\u6839 xfe.json.deploy.applications \u5FC5\u987B\u58F0\u660E\u5E94\u7528\u76EE\u5F55\u548C type");
45
+ }
46
+ if (!Array.isArray(targets) || targets.some((name) => !Object.hasOwn(applications, name))) {
47
+ throw new Error("deploy.targets \u5FC5\u987B\u662F\u5DF2\u58F0\u660E\u5E94\u7528\u540D\u7EC4\u6210\u7684\u6570\u7EC4");
48
+ }
49
+ const yaml = (0, import_node_module2.createRequire)(import_node_path3.default.join(frameworkRoot, "package.json"))("yaml");
50
+ const order = orderTargets({ applications, targets });
51
+ const output = [];
52
+ const steps = [];
53
+ const deploymentNames = /* @__PURE__ */ new Set();
54
+ let pipeline;
55
+ for (const name of order) {
56
+ if (!APPLICATION_NAME.test(name)) throw new Error(`\u5E94\u7528\u540D\u79F0\u65E0\u6548: ${name}`);
57
+ const application = applications[name];
58
+ const directory = resolveApplication(root, application);
59
+ const packageJson = readJson(import_node_path3.default.join(directory, "package.json"));
60
+ const project = readJson(import_node_path3.default.join(directory, "xfe.json"));
61
+ if (!project.deploy) throw new Error(`\u5E94\u7528 ${name} \u7F3A\u5C11 xfe.json.deploy`);
62
+ const deploymentName = project.project;
63
+ if (typeof deploymentName !== "string" || !APPLICATION_NAME.test(deploymentName) || deploymentNames.has(deploymentName)) {
64
+ throw new Error(`\u5E94\u7528 ${name} \u5FC5\u987B\u6709\u552F\u4E00\u7684 xfe.json.project \u5C0F\u5199\u53D1\u5E03\u540D\u79F0`);
58
65
  }
59
- subClass.prototype = Object.create(superClass && superClass.prototype, {
60
- constructor: {
61
- value: subClass,
62
- writable: true,
63
- configurable: true
64
- }
66
+ deploymentNames.add(deploymentName);
67
+ const provider = application.type === "mini" /* Mini */ ? "@xfe-repo/mini-app" : "@xfe-repo/web-app";
68
+ const providerRoot = application.type === "node" /* Node */ ? resolveWebProvider({ root, applications }) : import_node_path3.default.dirname((0, import_node_module2.createRequire)(import_node_path3.default.join(directory, "package.json")).resolve(`${provider}/package.json`));
69
+ const raw = (0, import_node_child_process.execFileSync)(process.execPath, [import_node_path3.default.join(providerRoot, "bin/index.js"), "config", "--json"], {
70
+ cwd: directory,
71
+ encoding: "utf8",
72
+ maxBuffer: COMMAND_OUTPUT_LIMIT
65
73
  });
66
- if (superClass) _set_prototype_of(subClass, superClass);
67
- }
68
- function _iterable_to_array(iter) {
69
- if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter);
70
- }
71
- function _iterable_to_array_limit(arr, i) {
72
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
73
- if (_i == null) return;
74
- var _arr = [];
75
- var _n = true;
76
- var _d = false;
77
- var _s, _e;
78
- try {
79
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
80
- _arr.push(_s.value);
81
- if (i && _arr.length === i) break;
82
- }
83
- } catch (err) {
84
- _d = true;
85
- _e = err;
86
- } finally{
87
- try {
88
- if (!_n && _i["return"] != null) _i["return"]();
89
- } finally{
90
- if (_d) throw _e;
91
- }
74
+ const documents = JSON.parse(raw);
75
+ const appPipeline = documents.find((document) => document.kind === "pipeline");
76
+ if (!appPipeline) throw new Error(`\u5E94\u7528 ${name} \u672A\u751F\u6210\u6D41\u6C34\u7EBF\uFF0C\u8BF7\u914D\u7F6E xfe.json.deploy`);
77
+ if (!pipeline) {
78
+ pipeline = { ...appPipeline, name: "deploy", steps };
79
+ steps.push(appPipeline.steps.find((step) => step.name === "install"));
80
+ steps.push({
81
+ name: "configure",
82
+ image: steps[0].image,
83
+ pull: "if-not-exists",
84
+ commands: ["pnpm deploy:config", "git diff --exit-code -- deploy/.drone.yml"]
85
+ });
92
86
  }
93
- return _arr;
94
- }
95
- function _non_iterable_rest() {
96
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
97
- }
98
- function _non_iterable_spread() {
99
- throw new TypeError("Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
100
- }
101
- function _object_spread(target) {
102
- for(var i = 1; i < arguments.length; i++){
103
- var source = arguments[i] != null ? arguments[i] : {};
104
- var ownKeys = Object.keys(source);
105
- if (typeof Object.getOwnPropertySymbols === "function") {
106
- ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
107
- return Object.getOwnPropertyDescriptor(source, sym).enumerable;
108
- }));
109
- }
110
- ownKeys.forEach(function(key) {
111
- _define_property(target, key, source[key]);
112
- });
87
+ const relative = import_node_path3.default.relative(root, directory).split(import_node_path3.default.sep).join("/");
88
+ const secrets = /* @__PURE__ */ new Map();
89
+ for (const document of documents.filter((document2) => document2.kind === "secret")) {
90
+ const secretName = document.name === "target-k8s-config" ? `${name}-${document.name}` : document.name;
91
+ const secret = { ...document, name: secretName };
92
+ const existing = output.find((item) => item.name === secretName);
93
+ if (existing && JSON.stringify(existing) !== JSON.stringify(secret)) throw new Error(`\u51ED\u636E\u58F0\u660E\u51B2\u7A81: ${secretName}`);
94
+ secrets.set(document.name, secretName);
95
+ if (!existing) output.push(secret);
113
96
  }
114
- return target;
115
- }
116
- function ownKeys(object, enumerableOnly) {
117
- var keys = Object.keys(object);
118
- if (Object.getOwnPropertySymbols) {
119
- var symbols = Object.getOwnPropertySymbols(object);
120
- if (enumerableOnly) {
121
- symbols = symbols.filter(function(sym) {
122
- return Object.getOwnPropertyDescriptor(object, sym).enumerable;
123
- });
97
+ for (const step of appPipeline.steps) {
98
+ if (["install", "configure"].includes(step.name)) continue;
99
+ const next = { ...step, name: `${name}-${step.name}` };
100
+ if (next.depends_on) next.depends_on = next.depends_on.map((dependency) => `${name}-${dependency}`);
101
+ if (next.environment) {
102
+ next.environment = Object.fromEntries(
103
+ Object.entries(next.environment).map(([key, value]) => [
104
+ key,
105
+ value?.from_secret && secrets.has(value.from_secret) ? { from_secret: secrets.get(value.from_secret) } : value
106
+ ])
107
+ );
108
+ }
109
+ if (step.commands) {
110
+ let commands2 = step.commands.filter(
111
+ (command2) => !["pnpm exec xfe-web config", "git diff --exit-code -- deploy/.drone.yml", "cp -a node_modules deploy/modules"].includes(
112
+ command2
113
+ )
114
+ );
115
+ if (application.type === "node" /* Node */ && step.name === "build") commands2 = ["pnpm run build:ci"];
116
+ if (step.name === "build" && application.type !== "mini" /* Mini */) {
117
+ commands2.push(
118
+ ...packageCommands({
119
+ name,
120
+ relative,
121
+ packageName: packageJson.name,
122
+ isWeb: application.type === "web" /* Web */
123
+ })
124
+ );
124
125
  }
125
- keys.push.apply(keys, symbols);
126
+ next.commands = [
127
+ `cd ${quote(relative)}`,
128
+ ...commands2.map(
129
+ (command2) => command2.replaceAll("$DRONE_REPO_NAME", deploymentName).replaceAll("${DRONE_REPO}", deploymentName).replaceAll("$DRONE_REPO", deploymentName).replaceAll("$CI_COMMIT_SHA", "$DRONE_COMMIT_SHA")
130
+ )
131
+ ];
132
+ }
133
+ if (step.name === "image-build") {
134
+ const context = application.type === "mini" /* Mini */ ? relative : `deploy/artifacts/${name}`;
135
+ next.settings = {
136
+ ...step.settings,
137
+ repo_name: deploymentName,
138
+ tags: step.settings.tags.map((tag) => tag.replaceAll("${CI_COMMIT_SHA}", "${DRONE_COMMIT_SHA}")),
139
+ context,
140
+ dockerfile: application.type === "mini" /* Mini */ ? "deploy/Dockerfile" : "Dockerfile"
141
+ };
142
+ }
143
+ steps.push(next);
126
144
  }
127
- return keys;
128
- }
129
- function _object_spread_props(target, source) {
130
- source = source != null ? source : {};
131
- if (Object.getOwnPropertyDescriptors) {
132
- Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
133
- } else {
134
- ownKeys(Object(source)).forEach(function(key) {
135
- Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
136
- });
145
+ if (application.type === "node" /* Node */) {
146
+ import_node_fs2.default.copyFileSync(import_node_path3.default.join(directory, "migration-job.yaml"), import_node_path3.default.join(directory, "deploy/helm/templates/migration-job.yaml"));
137
147
  }
138
- return target;
148
+ }
149
+ if (!pipeline) throw new Error("deploy.targets \u81F3\u5C11\u9700\u8981\u9009\u62E9\u4E00\u4E2A\u5E94\u7528");
150
+ steps[0].commands = ["pnpm config set registry https://registry.npmmirror.com", "pnpm install --frozen-lockfile"];
151
+ const deployDirectory = import_node_path3.default.join(root, "deploy");
152
+ if (import_node_fs2.default.lstatSync(deployDirectory, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error("\u6839 deploy \u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5");
153
+ import_node_fs2.default.mkdirSync(deployDirectory, { recursive: true });
154
+ import_node_fs2.default.writeFileSync(
155
+ import_node_path3.default.join(deployDirectory, ".drone.yml"),
156
+ [pipeline, ...output].map((document) => yaml.stringify(document, { defaultStringType: "QUOTE_SINGLE", defaultKeyType: "PLAIN", lineWidth: 0 })).join("---\n")
157
+ );
139
158
  }
140
- function _object_without_properties(source, excluded) {
141
- if (source == null) return {};
142
- var target = {}, sourceKeys, key, i;
143
- if (typeof Reflect !== "undefined" && Reflect.ownKeys) {
144
- sourceKeys = Reflect.ownKeys(Object(source));
145
- for(i = 0; i < sourceKeys.length; i++){
146
- key = sourceKeys[i];
147
- if (excluded.indexOf(key) >= 0) continue;
148
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
149
- target[key] = source[key];
150
- }
151
- return target;
152
- }
153
- target = _object_without_properties_loose(source, excluded);
154
- if (Object.getOwnPropertySymbols) {
155
- sourceKeys = Object.getOwnPropertySymbols(source);
156
- for(i = 0; i < sourceKeys.length; i++){
157
- key = sourceKeys[i];
158
- if (excluded.indexOf(key) >= 0) continue;
159
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
160
- target[key] = source[key];
161
- }
162
- }
163
- return target;
159
+ function printDeployment(frameworkRoot) {
160
+ const yaml = (0, import_node_module2.createRequire)(import_node_path3.default.join(frameworkRoot, "package.json"))("yaml");
161
+ const source = import_node_fs2.default.readFileSync(import_node_path3.default.join(process.cwd(), "deploy/.drone.yml"), "utf8");
162
+ process.stdout.write(
163
+ JSON.stringify(
164
+ yaml.parseAllDocuments(source).map((document) => document.toJS()).filter(Boolean)
165
+ )
166
+ );
164
167
  }
165
- function _object_without_properties_loose(source, excluded) {
166
- if (source == null) return {};
167
- var target = {}, sourceKeys = Object.getOwnPropertyNames(source), key, i;
168
- for(i = 0; i < sourceKeys.length; i++){
169
- key = sourceKeys[i];
170
- if (excluded.indexOf(key) >= 0) continue;
171
- if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;
172
- target[key] = source[key];
168
+ function orderTargets({ applications, targets }) {
169
+ const ordered = [];
170
+ const visiting = /* @__PURE__ */ new Set();
171
+ const selected = new Set(targets);
172
+ const visit = (name) => {
173
+ if (ordered.includes(name)) return;
174
+ if (visiting.has(name)) throw new Error(`\u5E94\u7528\u53D1\u5E03\u987A\u5E8F\u5305\u542B\u5FAA\u73AF: ${name}`);
175
+ const dependencies = applications[name].dependsOn ?? [];
176
+ if (!Array.isArray(dependencies) || dependencies.some((dependency) => !Object.hasOwn(applications, dependency))) {
177
+ throw new Error(`\u5E94\u7528 ${name} \u7684 dependsOn \u5305\u542B\u672A\u77E5\u5E94\u7528`);
173
178
  }
174
- return target;
179
+ visiting.add(name);
180
+ dependencies.filter((dependency) => selected.has(dependency)).forEach(visit);
181
+ visiting.delete(name);
182
+ ordered.push(name);
183
+ };
184
+ targets.forEach(visit);
185
+ return ordered;
175
186
  }
176
- function _set_prototype_of(o, p) {
177
- _set_prototype_of = Object.setPrototypeOf || function setPrototypeOf(o, p) {
178
- o.__proto__ = p;
179
- return o;
180
- };
181
- return _set_prototype_of(o, p);
187
+ function resolveApplication(root, application) {
188
+ if (!application || typeof application.directory !== "string" || !Object.values(ApplicationType).includes(application.type)) {
189
+ throw new Error("\u5E94\u7528\u5FC5\u987B\u58F0\u660E directory\uFF0C\u4EE5\u53CA node\u3001web\u3001mini \u4E2D\u7684 type");
190
+ }
191
+ const directory = import_node_fs2.default.realpathSync(import_node_path3.default.resolve(root, application.directory));
192
+ const relative = import_node_path3.default.relative(root, directory);
193
+ if (!relative || relative.split(import_node_path3.default.sep)[0] === ".." || import_node_path3.default.isAbsolute(relative)) throw new Error("\u5E94\u7528\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E\u4ED3\u5E93\u5185");
194
+ return directory;
182
195
  }
183
- function _sliced_to_array(arr, i) {
184
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
196
+ function resolveWebProvider({ root, applications }) {
197
+ const application = Object.values(applications).find((application2) => application2.type === "web" /* Web */);
198
+ if (!application) throw new Error("Node \u90E8\u7F72\u9700\u8981\u4ED3\u5E93\u5185\u7684 Web \u6784\u5EFA\u5DE5\u5177\u63D0\u4F9B\u901A\u7528 Helm \u6A21\u677F");
199
+ const directory = resolveApplication(root, application);
200
+ return import_node_path3.default.dirname((0, import_node_module2.createRequire)(import_node_path3.default.join(directory, "package.json")).resolve("@xfe-repo/web-app/package.json"));
185
201
  }
186
- function _to_consumable_array(arr) {
187
- return _array_without_holes(arr) || _iterable_to_array(arr) || _unsupported_iterable_to_array(arr) || _non_iterable_spread();
202
+ function packageCommands({
203
+ name,
204
+ relative,
205
+ packageName,
206
+ isWeb
207
+ }) {
208
+ if (typeof packageName !== "string" || !packageName) throw new Error(`\u5E94\u7528 ${name} \u7F3A\u5C11 package.json.name`);
209
+ const root = import_node_path3.default.posix.relative(relative, ".") || ".";
210
+ const commands2 = [
211
+ `packageDirectory="$PWD/${root}/deploy/artifacts/${name}"`,
212
+ `pnpm --dir ${quote(root)} --filter ${quote(packageName)} deploy --legacy --prod "$packageDirectory"`
213
+ ];
214
+ const selfReference = packageName.startsWith("@") ? "../../../.." : "../../..";
215
+ commands2.push(
216
+ `selfLink="$packageDirectory/node_modules/.pnpm/node_modules/${packageName}"`,
217
+ `if [ -L "$selfLink" ]; then ln -sfn ${quote(selfReference)} "$selfLink"; fi`
218
+ );
219
+ if (isWeb) {
220
+ commands2.push(
221
+ 'mkdir -p "$packageDirectory/deploy"',
222
+ 'mv "$packageDirectory/node_modules" "$packageDirectory/deploy/modules"',
223
+ `selfLink="$packageDirectory/deploy/modules/.pnpm/node_modules/${packageName}"`,
224
+ `if [ -L "$selfLink" ]; then ln -sfn ${quote(`../${selfReference}`)} "$selfLink"; fi`,
225
+ 'cp -a deploy/static "$packageDirectory/deploy/static"',
226
+ 'cp deploy/Dockerfile "$packageDirectory/Dockerfile"'
227
+ );
228
+ return commands2;
229
+ }
230
+ commands2.push('cp Dockerfile "$packageDirectory/Dockerfile"');
231
+ return commands2;
188
232
  }
189
- function _type_of(obj) {
190
- "@swc/helpers - typeof";
191
- return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj;
233
+ function readJson(file) {
234
+ return JSON.parse(import_node_fs2.default.readFileSync(file, "utf8"));
192
235
  }
193
- function _unsupported_iterable_to_array(o, minLen) {
194
- if (!o) return;
195
- if (typeof o === "string") return _array_like_to_array(o, minLen);
196
- var n = Object.prototype.toString.call(o).slice(8, -1);
197
- if (n === "Object" && o.constructor) n = o.constructor.name;
198
- if (n === "Map" || n === "Set") return Array.from(n);
199
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
236
+ function quote(value) {
237
+ return `'${value.replaceAll("'", "'\\''")}'`;
200
238
  }
201
- function _wrap_reg_exp(re, groups) {
202
- _wrap_reg_exp = function(re, groups) {
203
- return new WrappedRegExp(re, undefined, groups);
204
- };
205
- var _super = RegExp.prototype;
206
- var _groups = new WeakMap();
207
- function WrappedRegExp(re, flags, groups) {
208
- var _re = new RegExp(re, flags);
209
- _groups.set(_re, groups || _groups.get(re));
210
- return _set_prototype_of(_re, WrappedRegExp.prototype);
211
- }
212
- _inherits(WrappedRegExp, RegExp);
213
- WrappedRegExp.prototype.exec = function(str) {
214
- var result = _super.exec.call(this, str);
215
- if (result) {
216
- result.groups = buildGroups(result, this);
217
- var indices = result.indices;
218
- if (indices) indices.groups = buildGroups(indices, this);
219
- }
220
- return result;
221
- };
222
- WrappedRegExp.prototype[Symbol.replace] = function(str, substitution) {
223
- if (typeof substitution === "string") {
224
- var groups = _groups.get(this);
225
- return _super[Symbol.replace].call(this, str, substitution.replace(/\$<([^>]+)>/g, function(_, name) {
226
- var group = groups ? groups[name] : undefined;
227
- if (group === undefined) return "";
228
- return "$" + (Array.isArray(group) ? group.join("$") : group);
229
- }));
230
- }
231
- if (typeof substitution === "function") {
232
- var _this = this;
233
- return _super[Symbol.replace].call(this, str, function() {
234
- var args = arguments;
235
- if (typeof args[args.length - 1] !== "object") {
236
- args = [].slice.call(args);
237
- args.push(buildGroups(args, _this));
238
- }
239
- return substitution.apply(this, args);
240
- });
241
- }
242
- return _super[Symbol.replace].call(this, str, substitution);
243
- };
244
- function buildGroups(result, re) {
245
- var g = _groups.get(re);
246
- return Object.keys(g).reduce(function(groups, name) {
247
- var i = g[name];
248
- if (typeof i === "number") groups[name] = result[i];
249
- else {
250
- var k = 0;
251
- while(result[i[k]] === undefined && k + 1 < i.length)k++;
252
- groups[name] = result[i[k]];
253
- }
254
- return groups;
255
- }, Object.create(null));
256
- }
257
- return _wrap_reg_exp.apply(this, arguments);
258
- }
259
- function _ts_generator(thisArg, body) {
260
- var f, y, t, _ = {
261
- label: 0,
262
- sent: function() {
263
- if (t[0] & 1) throw t[1];
264
- return t[1];
265
- },
266
- trys: [],
267
- ops: []
268
- }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
269
- return d(g, "next", {
270
- value: verb(0)
271
- }), d(g, "throw", {
272
- value: verb(1)
273
- }), d(g, "return", {
274
- value: verb(2)
275
- }), typeof Symbol === "function" && d(g, Symbol.iterator, {
276
- value: function() {
277
- return this;
278
- }
279
- }), g;
280
- function verb(n) {
281
- return function(v) {
282
- return step([
283
- n,
284
- v
285
- ]);
286
- };
287
- }
288
- function step(op) {
289
- if (f) throw new TypeError("Generator is already executing.");
290
- while(g && (g = 0, op[0] && (_ = 0)), _)try {
291
- 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;
292
- if (y = 0, t) op = [
293
- op[0] & 2,
294
- t.value
295
- ];
296
- switch(op[0]){
297
- case 0:
298
- case 1:
299
- t = op;
300
- break;
301
- case 4:
302
- _.label++;
303
- return {
304
- value: op[1],
305
- done: false
306
- };
307
- case 5:
308
- _.label++;
309
- y = op[1];
310
- op = [
311
- 0
312
- ];
313
- continue;
314
- case 7:
315
- op = _.ops.pop();
316
- _.trys.pop();
317
- continue;
318
- default:
319
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
320
- _ = 0;
321
- continue;
322
- }
323
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
324
- _.label = op[1];
325
- break;
326
- }
327
- if (op[0] === 6 && _.label < t[1]) {
328
- _.label = t[1];
329
- t = op;
330
- break;
331
- }
332
- if (t && _.label < t[2]) {
333
- _.label = t[2];
334
- _.ops.push(op);
335
- break;
336
- }
337
- if (t[2]) _.ops.pop();
338
- _.trys.pop();
339
- continue;
340
- }
341
- op = body.call(thisArg, _);
342
- } catch (e) {
343
- op = [
344
- 6,
345
- e
346
- ];
347
- y = 0;
348
- } finally{
349
- f = t = 0;
350
- }
351
- if (op[0] & 5) throw op[1];
352
- return {
353
- value: op[0] ? op[1] : void 0,
354
- done: true
355
- };
356
- }
357
- }
358
- var __create = Object.create;
359
- var __defProp = Object.defineProperty;
360
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
361
- var __getOwnPropNames = Object.getOwnPropertyNames;
362
- var __getProtoOf = Object.getPrototypeOf;
363
- var __hasOwnProp = Object.prototype.hasOwnProperty;
364
- var __copyProps = function __copyProps(to, from, except, desc) {
365
- if (from && (typeof from === "undefined" ? "undefined" : _type_of(from)) === "object" || typeof from === "function") {
366
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
367
- try {
368
- var _loop = function() {
369
- var key = _step.value;
370
- if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
371
- get: function get() {
372
- return from[key];
373
- },
374
- enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
375
- });
376
- };
377
- for(var _iterator = __getOwnPropNames(from)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true)_loop();
378
- } catch (err) {
379
- _didIteratorError = true;
380
- _iteratorError = err;
381
- } finally{
382
- try {
383
- if (!_iteratorNormalCompletion && _iterator.return != null) {
384
- _iterator.return();
385
- }
386
- } finally{
387
- if (_didIteratorError) {
388
- throw _iteratorError;
389
- }
390
- }
391
- }
392
- }
393
- return to;
394
- };
395
- var __toESM = function __toESM(mod, isNodeMode, target) {
396
- return target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(// If the importer is in node compatibility mode or this is not an ESM
397
- // file that has been converted to a CommonJS file using a Babel-
398
- // compatible transform (i.e. "__esModule" has not been set), then set
399
- // "default" to the CommonJS "module.exports" for node compatibility.
400
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
401
- value: mod,
402
- enumerable: true
403
- }) : target, mod);
404
- };
239
+ var import_node_fs2, import_node_path3, import_node_child_process, import_node_module2, ApplicationType, COMMAND_OUTPUT_LIMIT, APPLICATION_NAME;
240
+ var init_workspace = __esm({
241
+ "../../shared/deploy/workspace.ts"() {
242
+ "use strict";
243
+ import_node_fs2 = __toESM(require("fs"));
244
+ import_node_path3 = __toESM(require("path"));
245
+ import_node_child_process = require("child_process");
246
+ import_node_module2 = require("module");
247
+ ApplicationType = /* @__PURE__ */ ((ApplicationType2) => {
248
+ ApplicationType2["Node"] = "node";
249
+ ApplicationType2["Web"] = "web";
250
+ ApplicationType2["Mini"] = "mini";
251
+ return ApplicationType2;
252
+ })(ApplicationType || {});
253
+ COMMAND_OUTPUT_LIMIT = 8 * 1024 * 1024;
254
+ APPLICATION_NAME = /^[a-z][a-z0-9-]*$/;
255
+ }
256
+ });
257
+
405
258
  // src/cli.ts
406
259
  var import_minimist = __toESM(require("minimist"));
407
- var import_path3 = __toESM(require("path"));
408
- var import_node_child_process = require("child_process");
260
+ var import_path2 = __toESM(require("path"));
261
+ var import_node_child_process2 = require("child_process");
262
+
409
263
  // src/config.ts
410
- var import_path = __toESM(require("path"));
411
264
  var import_fs = __toESM(require("fs"));
412
- var import_yaml = __toESM(require("yaml"));
413
- var loadXfeConfig = function loadXfeConfig() {
414
- var xfeConfigPath = "./xfe.json";
415
- if (!import_fs.default.existsSync(xfeConfigPath)) {
416
- 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");
265
+
266
+ // src/config/deploy.ts
267
+ var import_node_path2 = __toESM(require("path"));
268
+ var import_node_url = require("url");
269
+
270
+ // ../../shared/deploy/config.ts
271
+ var import_node_fs = __toESM(require("fs"));
272
+ var import_node_path = __toESM(require("path"));
273
+ var import_node_module = require("module");
274
+ var DeployEnvironment = /* @__PURE__ */ ((DeployEnvironment2) => {
275
+ DeployEnvironment2["Test"] = "test";
276
+ DeployEnvironment2["Stage"] = "stage";
277
+ DeployEnvironment2["Prod"] = "prod";
278
+ DeployEnvironment2["Stable"] = "stable";
279
+ return DeployEnvironment2;
280
+ })(DeployEnvironment || {});
281
+ var generateDeploy = ({
282
+ deploy,
283
+ frameworkRoot,
284
+ isMini = false
285
+ }) => {
286
+ const yaml = (0, import_node_module.createRequire)(import_node_path.default.join(frameworkRoot, "package.json"))("yaml");
287
+ const supportedFields = ["values", "environments", "pushHelmChart", ...isMini ? ["platforms"] : []];
288
+ if (deploy === void 0) return;
289
+ if (!deploy || typeof deploy !== "object" || Array.isArray(deploy) || Object.keys(deploy).some(
290
+ /** 运行参数只能来自 values,流水线开关保留独立入口。 */
291
+ (key) => !supportedFields.includes(key)
292
+ )) {
293
+ throw new Error(`xfe.json.deploy \u4EC5\u652F\u6301 ${supportedFields.join("\u3001")}\uFF1B\u8FD0\u884C\u53C2\u6570\u8BF7\u653E\u5165 values`);
294
+ }
295
+ const environments = deploy.environments === void 0 ? Object.values(DeployEnvironment) : deploy.environments;
296
+ if (!Array.isArray(environments) || environments.some(
297
+ /** 只接受已知的环境名称,非法值不能误开启发布。 */
298
+ (environment) => !Object.values(DeployEnvironment).includes(environment)
299
+ ))
300
+ throw new Error("deploy.environments \u5FC5\u987B\u662F test\u3001stage\u3001prod\u3001stable \u7EC4\u6210\u7684\u6570\u7EC4\uFF1B\u7A7A\u6570\u7EC4\u5173\u95ED\u5168\u90E8\u90E8\u7F72");
301
+ if (deploy.pushHelmChart !== void 0 && typeof deploy.pushHelmChart !== "boolean") throw new Error("deploy.pushHelmChart \u5FC5\u987B\u662F\u5E03\u5C14\u503C");
302
+ const platforms = deploy.platforms === void 0 ? ["weapp", "h5"] : deploy.platforms;
303
+ if (!Array.isArray(platforms) || platforms.some((platform) => !["weapp", "h5"].includes(platform))) {
304
+ throw new Error("deploy.platforms \u5FC5\u987B\u662F weapp\u3001h5 \u7EC4\u6210\u7684\u6570\u7EC4\uFF1B\u7A7A\u6570\u7EC4\u5173\u95ED\u5168\u90E8\u53D1\u5E03");
305
+ }
306
+ const h5Environments = platforms.includes("h5") ? environments : [];
307
+ const miniEnvironments = platforms.includes("weapp") ? environments : [];
308
+ const pushHelmChart = deploy.pushHelmChart !== false && h5Environments.includes("prod" /* Prod */);
309
+ const source = import_node_path.default.join(frameworkRoot, "deploy");
310
+ const target = import_node_path.default.join(process.cwd(), "deploy");
311
+ let overrides = deploy.values === void 0 ? {} : deploy.values;
312
+ if (typeof overrides === "string") {
313
+ const valuesPath = import_node_fs.default.realpathSync(import_node_path.default.resolve(overrides));
314
+ if (valuesPath.startsWith(target + import_node_path.default.sep) && valuesPath !== import_node_path.default.join(target, "values.yaml")) {
315
+ throw new Error("\u9879\u76EE values \u6587\u4EF6\u4E0D\u80FD\u653E\u5728\u751F\u6210\u5B50\u76EE\u5F55\u4E2D\uFF0C\u8BF7\u4F7F\u7528 deploy/values.yaml \u6216\u9879\u76EE\u6839\u76EE\u5F55\u7684 values.yaml");
417
316
  }
418
- var xfeConfigContent = import_fs.default.readFileSync(xfeConfigPath, "utf8");
419
- return JSON.parse(xfeConfigContent);
317
+ overrides = yaml.parse(import_node_fs.default.readFileSync(valuesPath, "utf8"));
318
+ }
319
+ if (!overrides || typeof overrides !== "object" || Array.isArray(overrides)) {
320
+ throw new Error("deploy.values \u5FC5\u987B\u662F\u5BF9\u8C61\u6216\u6307\u5411 YAML \u5BF9\u8C61\u6587\u4EF6\u7684\u8DEF\u5F84");
321
+ }
322
+ if (Object.hasOwn(overrides, "environments") || Object.hasOwn(overrides, "pushHelmChart"))
323
+ throw new Error("values \u4E0D\u518D\u652F\u6301 environments \u6216 pushHelmChart\uFF1B\u8BF7\u8FC1\u5165 xfe.json.deploy\uFF0C\u73AF\u5883\u5F00\u5173\u4F7F\u7528\u6570\u7EC4");
324
+ const defaults = yaml.parse(import_node_fs.default.readFileSync(import_node_path.default.join(source, "helm/values.yaml"), "utf8"));
325
+ const values = mergeDeployValues(defaults, overrides);
326
+ if (typeof values.host !== "string" || /[\\/?#@:\s]/.test(values.host)) {
327
+ throw new Error("values.host \u5FC5\u987B\u662F\u4E0D\u542B\u534F\u8BAE\u3001\u7AEF\u53E3\u548C\u8DEF\u5F84\u7684\u4E3B\u673A\u540D\uFF0C\u4F8B\u5982 specdoc.example.com");
328
+ }
329
+ if (!["saas", "infra"].includes(values.targetK8s)) throw new Error("deploy.values.targetK8s \u53EA\u80FD\u4E3A saas \u6216 infra");
330
+ if (target === source) throw new Error("\u90E8\u7F72\u8F93\u51FA\u4E0D\u80FD\u8986\u76D6\u6846\u67B6\u6A21\u677F\u76EE\u5F55");
331
+ if (import_node_fs.default.lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) throw new Error("deploy \u4E0D\u80FD\u4E3A\u7B26\u53F7\u94FE\u63A5\uFF0C\u4EE5\u514D\u8986\u76D6\u5916\u90E8\u76EE\u5F55");
332
+ const disabledEvents = "[custom, tag]";
333
+ const drone = import_node_fs.default.readFileSync(import_node_path.default.join(source, ".drone.yml"), "utf8").replaceAll("<<TARGET_K8S>>", values.targetK8s).replaceAll("<<EXCLUDE_EVENTS_deploy>>", h5Environments.length ? "[]" : disabledEvents).replaceAll("<<EXCLUDE_EVENTS_h5>>", h5Environments.length ? "[]" : disabledEvents).replaceAll(
334
+ "<<EXCLUDE_EVENTS_weapp>>",
335
+ miniEnvironments.some((environment) => environment !== "stable" /* Stable */) ? "[]" : disabledEvents
336
+ ).replace(
337
+ /<<EXCLUDE_EVENTS_weapp_(test|stage|prod)>>/g,
338
+ (_placeholder, environment) => miniEnvironments.includes(environment) ? "[]" : disabledEvents
339
+ ).replaceAll("<<EXCLUDE_EVENTS_push_helm_chart>>", pushHelmChart ? "[]" : disabledEvents).replace(
340
+ /<<EXCLUDE_EVENTS_(test|stage|prod|stable)>>/g,
341
+ /** 开启时不排除事件,关闭时由 Drone 原生 when 跳过该步骤。 */
342
+ (_placeholder, environment) => h5Environments.includes(environment) ? "[]" : disabledEvents
343
+ );
344
+ import_node_fs.default.cpSync(source, target, { recursive: true });
345
+ import_node_fs.default.writeFileSync(
346
+ import_node_path.default.join(target, "helm/values.yaml"),
347
+ yaml.stringify(values, {
348
+ defaultStringType: "QUOTE_SINGLE",
349
+ defaultKeyType: "PLAIN"
350
+ })
351
+ );
352
+ import_node_fs.default.writeFileSync(import_node_path.default.join(target, ".drone.yml"), drone);
420
353
  };
421
- var configDeploy = function configDeploy() {
422
- var xfeConfig = loadXfeConfig();
423
- if (!(xfeConfig === null || xfeConfig === void 0 ? void 0 : xfeConfig.deploy)) return;
424
- var droneConfigFilePath = import_path.default.resolve(__dirname, "../deploy/.drone.yml");
425
- import_fs.default.cpSync(droneConfigFilePath, xfeConfig.deploy.droneConfigPath || "./.drone.yml");
426
- var valuesYamlFilePath = import_path.default.resolve(__dirname, "../deploy/helm/values.yaml");
427
- var valuesYamlFile = import_fs.default.readFileSync(valuesYamlFilePath, "utf8");
428
- var valuesYaml = import_yaml.default.parse(valuesYamlFile);
429
- if (!valuesYaml.virtualService) valuesYaml.virtualService = {};
430
- if (!valuesYaml.virtualService.hosts) valuesYaml.virtualService.hosts = {
431
- test: [],
432
- stage: [],
433
- prod: []
434
- };
435
- 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 ? [
436
- "common-gateway-eshetang"
437
- ] : _xfeConfig_deploy_gateways;
438
- 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;
439
- valuesYaml.virtualService.enabled = virtualServiceEnabled;
440
- valuesYaml.virtualService.gateways = gateways;
441
- valuesYaml.virtualService.hosts.prod = hostsProd;
442
- valuesYaml.virtualService.hosts.stage = hostsStage;
443
- valuesYaml.virtualService.hosts.test = hostsTest;
444
- valuesYaml.targetK8s = targetK8s;
445
- valuesYaml.namespace = targetNamespace;
446
- var valuesYamlStr = import_yaml.default.stringify(valuesYaml, {
447
- defaultStringType: "QUOTE_SINGLE",
448
- defaultKeyType: "PLAIN"
449
- });
450
- import_fs.default.writeFileSync(valuesYamlFilePath, valuesYamlStr, "utf8");
354
+ function mergeDeployValues(base, overrides) {
355
+ return Object.fromEntries(
356
+ Object.entries({ ...base, ...overrides }).map(
357
+ /** 仅合并普通对象,列表保持声明的顺序。 */
358
+ ([key, value]) => {
359
+ const previous = base[key];
360
+ const previousObject = previous && typeof previous === "object" && !Array.isArray(previous);
361
+ if (value === true && previousObject) {
362
+ return [key, Object.hasOwn(previous, "enabled") ? { ...previous, enabled: true } : previous];
363
+ }
364
+ const mergeable = value && previousObject && typeof value === "object" && !Array.isArray(value);
365
+ return [key, mergeable ? mergeDeployValues(previous, value) : value];
366
+ }
367
+ )
368
+ );
369
+ }
370
+
371
+ // src/config/deploy.ts
372
+ var import_meta = {};
373
+ var generateDeploy2 = (deploy) => {
374
+ const directory = typeof __dirname === "string" ? __dirname : import_node_path2.default.dirname((0, import_node_url.fileURLToPath)(import_meta.url));
375
+ generateDeploy({ deploy, frameworkRoot: import_node_path2.default.resolve(directory, ".."), isMini: true });
376
+ };
377
+
378
+ // src/config.ts
379
+ var loadXfeConfig = () => {
380
+ const xfeConfigPath = "./xfe.json";
381
+ if (!import_fs.default.existsSync(xfeConfigPath)) {
382
+ 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");
383
+ }
384
+ const xfeConfigContent = import_fs.default.readFileSync(xfeConfigPath, "utf8");
385
+ return JSON.parse(xfeConfigContent);
451
386
  };
452
- var getJwtEnv = function getJwtEnv() {
453
- return _async_to_generator(function() {
454
- var xfeConfig, _xfeConfig_jwt, _xfeConfig_jwt_aud, aud, jwkRes, JwkResponseJson, err, _, _1, _2, _ref, keyId, privateKeyPkcs8;
455
- return _ts_generator(this, function(_state) {
456
- switch(_state.label){
457
- case 0:
458
- xfeConfig = loadXfeConfig();
459
- if (!(xfeConfig === null || xfeConfig === void 0 ? void 0 : xfeConfig.jwt)) return [
460
- 2,
461
- {}
462
- ];
463
- _xfeConfig_jwt = xfeConfig.jwt, _xfeConfig_jwt_aud = _xfeConfig_jwt.aud, aud = _xfeConfig_jwt_aud === void 0 ? "" : _xfeConfig_jwt_aud;
464
- 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");
465
- return [
466
- 4,
467
- fetch("https://app.eshetang.com/jwk?appId=".concat(aud))
468
- ];
469
- case 1:
470
- jwkRes = _state.sent();
471
- if (!jwkRes.ok) {
472
- throw new Error("远程获取密钥失败: ".concat(jwkRes.status, " ").concat(jwkRes.statusText));
473
- }
474
- _state.label = 2;
475
- case 2:
476
- _state.trys.push([
477
- 2,
478
- 4,
479
- ,
480
- 6
481
- ]);
482
- return [
483
- 4,
484
- jwkRes.json()
485
- ];
486
- case 3:
487
- JwkResponseJson = _state.sent();
488
- return [
489
- 3,
490
- 6
491
- ];
492
- case 4:
493
- err = _state.sent();
494
- _ = Error.bind;
495
- _2 = (_1 = "远程获取密钥失败,响应解析错误: ".concat(err.message, ", response text: ")).concat;
496
- return [
497
- 4,
498
- jwkRes.text()
499
- ];
500
- case 5:
501
- throw new (_.apply(Error, [
502
- void 0,
503
- _2.apply(_1, [
504
- _state.sent()
505
- ])
506
- ]));
507
- case 6:
508
- _ref = (JwkResponseJson === null || JwkResponseJson === void 0 ? void 0 : JwkResponseJson.data) || {}, keyId = _ref.keyId, privateKeyPkcs8 = _ref.privateKeyPkcs8;
509
- if (!keyId || !privateKeyPkcs8) throw new Error("未获取到项目签名密钥, 请检查aud是否正确: ".concat(aud));
510
- return [
511
- 2,
512
- {
513
- XFE_JWT_AUD: aud,
514
- XFE_JWT_KEY_ID: keyId,
515
- XFE_JWT_PRIVATE_KEY: privateKeyPkcs8
516
- }
517
- ];
518
- }
519
- });
520
- })();
387
+ var configDeploy = () => generateDeploy2(loadXfeConfig().deploy);
388
+ var getJwtEnv = async () => {
389
+ const xfeConfig = loadXfeConfig();
390
+ if (!xfeConfig?.jwt) return {};
391
+ const { aud = "" } = xfeConfig.jwt;
392
+ 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");
393
+ const jwkRes = await fetch(`https://app.eshetang.com/jwk?appId=${aud}`);
394
+ if (!jwkRes.ok) {
395
+ throw new Error(`\u8FDC\u7A0B\u83B7\u53D6\u5BC6\u94A5\u5931\u8D25: ${jwkRes.status} ${jwkRes.statusText}`);
396
+ }
397
+ let JwkResponseJson;
398
+ try {
399
+ JwkResponseJson = await jwkRes.json();
400
+ } catch (err) {
401
+ 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()}`);
402
+ }
403
+ const { keyId, privateKeyPkcs8 } = JwkResponseJson?.data || {};
404
+ if (!keyId || !privateKeyPkcs8) throw new Error(`\u672A\u83B7\u53D6\u5230\u9879\u76EE\u7B7E\u540D\u5BC6\u94A5, \u8BF7\u68C0\u67E5aud\u662F\u5426\u6B63\u786E: ${aud}`);
405
+ return {
406
+ XFE_JWT_AUD: aud,
407
+ XFE_JWT_KEY_ID: keyId,
408
+ XFE_JWT_PRIVATE_KEY: privateKeyPkcs8
409
+ };
521
410
  };
411
+
522
412
  // src/upload.ts
523
413
  var import_miniprogram_ci2 = require("miniprogram-ci");
414
+
524
415
  // src/preview.ts
525
416
  var import_fs2 = __toESM(require("fs"));
526
- var import_path2 = __toESM(require("path"));
417
+ var import_path = __toESM(require("path"));
527
418
  var import_miniprogram_ci = require("miniprogram-ci");
528
- var getProject = function getProject() {
529
- var rwaPrivateKey = "", rawProjectConfig = "";
530
- var projectRoot = process.cwd();
531
- try {
532
- rwaPrivateKey = import_fs2.default.readFileSync(import_path2.default.join(projectRoot, "private.key")).toString();
533
- } catch (unused) {
534
- console.error("Error: \u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA private.key \u6587\u4EF6\uFF0C\u5185\u5BB9\u4E3A\u5C0F\u7A0B\u5E8F\u7684\u79C1\u94A5");
535
- process.exit(1);
536
- }
537
- try {
538
- rawProjectConfig = import_fs2.default.readFileSync(import_path2.default.join(projectRoot, "project.config.json")).toString();
539
- } catch (unused) {
540
- console.error("Error: \u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA project.config.json \u6587\u4EF6\uFF0C\u5185\u5BB9\u4E3A\u5C0F\u7A0B\u5E8F\u7684\u914D\u7F6E");
541
- process.exit(1);
542
- }
543
- var projectConfig = JSON.parse(rawProjectConfig);
544
- return new import_miniprogram_ci.Project({
545
- appid: projectConfig.appid,
546
- projectPath: projectConfig.miniprogramRoot,
547
- privateKey: rwaPrivateKey,
548
- type: "miniProgram",
549
- ignores: [
550
- "node_modules/**/*"
551
- ]
552
- });
419
+ var getProject = () => {
420
+ let rwaPrivateKey = "", rawProjectConfig = "";
421
+ const projectRoot = process.cwd();
422
+ try {
423
+ rwaPrivateKey = import_fs2.default.readFileSync(import_path.default.join(projectRoot, "private.key")).toString();
424
+ } catch {
425
+ console.error("Error: \u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA private.key \u6587\u4EF6\uFF0C\u5185\u5BB9\u4E3A\u5C0F\u7A0B\u5E8F\u7684\u79C1\u94A5");
426
+ process.exit(1);
427
+ }
428
+ try {
429
+ rawProjectConfig = import_fs2.default.readFileSync(import_path.default.join(projectRoot, "project.config.json")).toString();
430
+ } catch {
431
+ console.error("Error: \u8BF7\u5728\u9879\u76EE\u6839\u76EE\u5F55\u4E0B\u521B\u5EFA project.config.json \u6587\u4EF6\uFF0C\u5185\u5BB9\u4E3A\u5C0F\u7A0B\u5E8F\u7684\u914D\u7F6E");
432
+ process.exit(1);
433
+ }
434
+ const projectConfig = JSON.parse(rawProjectConfig);
435
+ return new import_miniprogram_ci.Project({
436
+ appid: projectConfig.appid,
437
+ projectPath: projectConfig.miniprogramRoot,
438
+ privateKey: rwaPrivateKey,
439
+ type: "miniProgram",
440
+ ignores: ["node_modules/**/*"]
441
+ });
553
442
  };
554
- function previewMini(version) {
555
- var pageUrl = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "", desc = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "", scene = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 1011, progress = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : false;
556
- return _async_to_generator(function() {
557
- var _pageUrl_split, pagePath, searchQuery, project, robot;
558
- return _ts_generator(this, function(_state) {
559
- switch(_state.label){
560
- case 0:
561
- _pageUrl_split = _sliced_to_array(pageUrl.split("?"), 2), pagePath = _pageUrl_split[0], searchQuery = _pageUrl_split[1];
562
- project = getProject();
563
- robot = choiceRobot();
564
- return [
565
- 4,
566
- (0, import_miniprogram_ci.preview)({
567
- project: project,
568
- version: version,
569
- qrcodeFormat: "terminal",
570
- qrcodeOutputDest: "deploy/preview.qrcode.jpg",
571
- pagePath: pagePath,
572
- searchQuery: searchQuery,
573
- desc: desc,
574
- robot: robot,
575
- scene: scene
576
- })
577
- ];
578
- case 1:
579
- _state.sent();
580
- return [
581
- 2
582
- ];
583
- }
584
- });
585
- })();
443
+ async function previewMini(version, pageUrl = "", desc = "", scene = 1011, progress = false) {
444
+ const [pagePath, searchQuery] = pageUrl.split("?");
445
+ const project = getProject();
446
+ const robot = choiceRobot();
447
+ await (0, import_miniprogram_ci.preview)({
448
+ project,
449
+ version,
450
+ qrcodeFormat: "terminal",
451
+ qrcodeOutputDest: "deploy/preview.qrcode.jpg",
452
+ pagePath,
453
+ searchQuery,
454
+ desc,
455
+ robot,
456
+ scene
457
+ });
586
458
  }
587
- var choiceRobot = function choiceRobot() {
588
- var _process_env = process.env, _process_env_API_ENV = _process_env.API_ENV, API_ENV = _process_env_API_ENV === void 0 ? "" : _process_env_API_ENV;
589
- var groups = (API_ENV.match(_wrap_reg_exp(/^(prod|beta|stage|test)(.*)/, {
590
- env: 1,
591
- sn: 2
592
- })) || {}).groups;
593
- var env2 = (groups === null || groups === void 0 ? void 0 : groups.env) || "other";
594
- var sn = Number(groups === null || groups === void 0 ? void 0 : groups.sn) || 0;
595
- var robot;
596
- switch(env2){
597
- case "prod":
598
- case "beta":
599
- robot = 1;
600
- break;
601
- case "stage":
602
- robot = 2;
603
- break;
604
- case "test":
605
- robot = sn % 29 >= 3 ? sn % 29 : 3;
606
- break;
607
- case "other":
608
- robot = 30;
609
- break;
610
- }
611
- console.log("将使用CI".concat(robot, "机器人"));
612
- return robot;
459
+ var choiceRobot = () => {
460
+ const { API_ENV = "" } = process.env;
461
+ const { groups } = API_ENV.match(/^(?<env>prod|beta|stage|test)(?<sn>.*)/) || {};
462
+ const env2 = groups?.env || "other";
463
+ const sn = Number(groups?.sn) || 0;
464
+ let robot;
465
+ switch (env2) {
466
+ case "prod":
467
+ case "beta":
468
+ robot = 1;
469
+ break;
470
+ case "stage":
471
+ robot = 2;
472
+ break;
473
+ case "test":
474
+ robot = sn % 29 >= 3 ? sn % 29 : 3;
475
+ break;
476
+ case "other":
477
+ robot = 30;
478
+ break;
479
+ }
480
+ console.log(`\u5C06\u4F7F\u7528CI${robot}\u673A\u5668\u4EBA`);
481
+ return robot;
613
482
  };
483
+
614
484
  // src/upload.ts
615
- function uploadMini(version) {
616
- var desc = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "", progress = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : false;
617
- return _async_to_generator(function() {
618
- var project, robot, onProgressUpdate;
619
- return _ts_generator(this, function(_state) {
620
- switch(_state.label){
621
- case 0:
622
- if (!version) throw new Error("\u8BF7\u4F20\u9012\u7248\u672C\u53F7\uFF01 -v \u6216\u8005 --version");
623
- project = getProject();
624
- robot = choiceRobot();
625
- onProgressUpdate = progress ? console.log : function() {
626
- return null;
627
- };
628
- return [
629
- 4,
630
- (0, import_miniprogram_ci2.upload)({
631
- project: project,
632
- version: version,
633
- robot: robot,
634
- desc: desc,
635
- onProgressUpdate: onProgressUpdate,
636
- setting: {
637
- es6: true
638
- }
639
- })
640
- ];
641
- case 1:
642
- _state.sent();
643
- return [
644
- 2
645
- ];
646
- }
647
- });
648
- })();
485
+ async function uploadMini(version, desc = "", progress = false) {
486
+ if (!version) throw new Error("\u8BF7\u4F20\u9012\u7248\u672C\u53F7\uFF01 -v \u6216\u8005 --version");
487
+ const project = getProject();
488
+ const robot = choiceRobot();
489
+ const onProgressUpdate = progress ? console.log : () => null;
490
+ await (0, import_miniprogram_ci2.upload)({
491
+ project,
492
+ version,
493
+ robot,
494
+ desc,
495
+ onProgressUpdate,
496
+ setting: { es6: true }
497
+ });
649
498
  }
499
+
650
500
  // src/cli.ts
651
501
  var argv = (0, import_minimist.default)(process.argv.slice(2));
652
- var commands = argv._, args = _object_without_properties(argv, [
653
- "_"
654
- ]);
655
- var _commands = _sliced_to_array(commands, 1), command = _commands[0];
656
- var appPackageRoot = import_path3.default.resolve(__dirname, "../");
502
+ var { _: commands, ...args } = argv;
503
+ var [command] = commands;
504
+ var appPackageRoot = import_path2.default.resolve(__dirname, "../");
657
505
  var appProjectRoot = process.cwd();
658
- var env = _object_spread_props(_object_spread({}, process.env), {
659
- APP_PROJECT_ROOT: appProjectRoot
660
- });
506
+ var env = { ...process.env, APP_PROJECT_ROOT: appProjectRoot };
661
507
  var taroBin = require.resolve("@tarojs/cli/bin/taro");
662
- var taroArgs = Object.entries(args).map(function(param) {
663
- var _param = _sliced_to_array(param, 2), key = _param[0], value = _param[1];
664
- return "--".concat(key, "=").concat(value);
665
- });
666
- function main() {
667
- return _async_to_generator(function() {
668
- var jwtEnv, jwtEnv1, v, version, d, desc, P, progress, v1, version1, p, previewPath, d1, desc1, s, scene, P1, progress1;
669
- return _ts_generator(this, function(_state) {
670
- switch(_state.label){
671
- case 0:
672
- if (!(command === "dev")) return [
673
- 3,
674
- 2
675
- ];
676
- return [
677
- 4,
678
- getJwtEnv()
679
- ];
680
- case 1:
681
- jwtEnv = _state.sent();
682
- (0, import_node_child_process.execFileSync)(process.execPath, [
683
- taroBin,
684
- "build",
685
- "--watch"
686
- ].concat(_to_consumable_array(taroArgs)), {
687
- stdio: "inherit",
688
- cwd: appPackageRoot,
689
- env: _object_spread({}, env, jwtEnv)
690
- });
691
- return [
692
- 3,
693
- 5
694
- ];
695
- case 2:
696
- if (!(command === "build")) return [
697
- 3,
698
- 4
699
- ];
700
- return [
701
- 4,
702
- getJwtEnv()
703
- ];
704
- case 3:
705
- jwtEnv1 = _state.sent();
706
- (0, import_node_child_process.execFileSync)(process.execPath, [
707
- taroBin,
708
- "build"
709
- ].concat(_to_consumable_array(taroArgs)), {
710
- stdio: "inherit",
711
- cwd: appPackageRoot,
712
- env: _object_spread({}, env, jwtEnv1)
713
- });
714
- return [
715
- 3,
716
- 5
717
- ];
718
- case 4:
719
- if (command === "config") {
720
- configDeploy();
721
- } else if (command === "upload") {
722
- v = argv.v, version = argv.version, d = argv.d, desc = argv.desc, P = argv.P, progress = argv.progress;
723
- void uploadMini(v || version, d || desc, P || progress).catch(console.error).finally(function() {
724
- return process.exit(0);
725
- });
726
- } else if (command === "preview") {
727
- v1 = argv.v, version1 = argv.version, p = argv.p, previewPath = argv.path, d1 = argv.d, desc1 = argv.desc, s = argv.s, scene = argv.scene, P1 = argv.P, progress1 = argv.progress;
728
- void previewMini(v1 || version1, p || previewPath, d1 || desc1, s || scene, P1 || progress1).finally(function() {
729
- return process.exit(0);
730
- });
731
- }
732
- _state.label = 5;
733
- case 5:
734
- return [
735
- 2
736
- ];
737
- }
738
- });
739
- })();
508
+ var taroArgs = Object.entries(args).map(([key, value]) => `--${key}=${value}`);
509
+ async function main() {
510
+ if (command === "dev") {
511
+ const jwtEnv = await getJwtEnv();
512
+ (0, import_node_child_process2.execFileSync)(process.execPath, [taroBin, "build", "--watch", ...taroArgs], {
513
+ stdio: "inherit",
514
+ cwd: appPackageRoot,
515
+ env: { ...env, ...jwtEnv }
516
+ });
517
+ } else if (command === "build") {
518
+ const jwtEnv = await getJwtEnv();
519
+ (0, import_node_child_process2.execFileSync)(process.execPath, [taroBin, "build", ...taroArgs], {
520
+ stdio: "inherit",
521
+ cwd: appPackageRoot,
522
+ env: { ...env, ...jwtEnv }
523
+ });
524
+ } else if (command === "config") {
525
+ const { configWorkspace: configWorkspace2, printDeployment: printDeployment2 } = await Promise.resolve().then(() => (init_workspace(), workspace_exports));
526
+ if (argv.workspace)
527
+ return configWorkspace2({
528
+ workspaceRoot: import_path2.default.resolve(argv.workspace),
529
+ frameworkRoot: appPackageRoot
530
+ });
531
+ configDeploy();
532
+ if (argv.json) printDeployment2(appPackageRoot);
533
+ } else if (command === "upload") {
534
+ const { v, version, d, desc, P, progress } = argv;
535
+ await uploadMini(v || version, d || desc, P || progress);
536
+ } else if (command === "preview") {
537
+ const { v, version, p, path: previewPath, d, desc, s, scene, P, progress } = argv;
538
+ await previewMini(v || version, p || previewPath, d || desc, s || scene, P || progress);
539
+ }
740
540
  }
741
- main().catch(function(err) {
742
- console.error("XFE Mini CLI \u6267\u884C\u51FA\u9519:", err);
743
- process.exit(1);
541
+ main().catch((err) => {
542
+ console.error("XFE Mini CLI \u6267\u884C\u51FA\u9519:", err);
543
+ process.exit(1);
744
544
  });