@tuya-sat/micro-script 3.0.26 → 3.0.27-beta.10

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,2 @@
1
+ declare const _default: () => Promise<void>;
2
+ export default _default;
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ const fs_extra_1 = __importDefault(require("fs-extra"));
39
+ const path_1 = __importDefault(require("path"));
40
+ const paths_1 = __importDefault(require("../config/paths"));
41
+ const ts = __importStar(require("typescript"));
42
+ const express_1 = require("express");
43
+ const prettier_1 = __importDefault(require("prettier"));
44
+ const isMonorepo = () => {
45
+ return (fs_extra_1.default.existsSync(path_1.default.join(process.cwd(), 'apps')) &&
46
+ fs_extra_1.default.existsSync(path_1.default.join(process.cwd(), 'packages')));
47
+ };
48
+ const isMainApp = () => {
49
+ const { debuggerConfig: { isMainApp }, } = require(paths_1.default.microConfig);
50
+ return isMainApp;
51
+ };
52
+ const createPropertyAssignment = (key, value) => {
53
+ return ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(key), ts.factory.createStringLiteral(value));
54
+ };
55
+ exports.default = () => __awaiter(void 0, void 0, void 0, function* () {
56
+ var _a, _b, _c, _d;
57
+ if (isMainApp()) {
58
+ }
59
+ else if (isMonorepo()) {
60
+ }
61
+ else {
62
+ const microPath = path_1.default.join(process.cwd(), 'node_modules/.micro');
63
+ !fs_extra_1.default.existsSync(microPath) && fs_extra_1.default.mkdirSync(microPath, { recursive: true });
64
+ const sourceCode = fs_extra_1.default
65
+ .readFileSync(path_1.default.join(__dirname, './template.ts'))
66
+ .toString();
67
+ const ast = ts.createSourceFile('apis.ts', sourceCode, ts.ScriptTarget.ES2020, true);
68
+ const apiNode = (_d = (_c = (_b = (_a = ast.statements.find((s) => {
69
+ var _a, _b, _c;
70
+ return s.kind === ts.SyntaxKind.VariableStatement &&
71
+ ((_c = (_b = (_a = s === null || s === void 0 ? void 0 : s.declarationList) === null || _a === void 0 ? void 0 : _a.declarations) === null || _b === void 0 ? void 0 : _b[0].name) === null || _c === void 0 ? void 0 : _c.escapedText) ===
72
+ 'apis';
73
+ })) === null || _a === void 0 ? void 0 : _a.declarationList) === null || _b === void 0 ? void 0 : _b.declarations) === null || _c === void 0 ? void 0 : _c[0].initializer) === null || _d === void 0 ? void 0 : _d.properties;
74
+ const mf = fs_extra_1.default.readJSONSync(path_1.default.join(process.cwd(), 'manifest.json'));
75
+ const apis = mf.apis || [];
76
+ apis.forEach((api) => {
77
+ const paths = api.path.split('/').map((item) => {
78
+ return item
79
+ .replace('.', '')
80
+ .replace('-', '_')
81
+ .replace('{', '')
82
+ .replace('}', '')
83
+ .toUpperCase();
84
+ });
85
+ const apiName = `${api.method.toUpperCase()}${paths.join('_')}`;
86
+ const regex = /{(\w+)}/g;
87
+ const matches = [];
88
+ let match;
89
+ while ((match = regex.exec(api.path))) {
90
+ matches.push(match[1]);
91
+ }
92
+ const createParameterDeclarations = () => {
93
+ console.log('createParameterDeclarations', matches);
94
+ return [
95
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, ts.factory.createObjectBindingPattern([
96
+ ...[
97
+ matches.length > 0
98
+ ? ts.factory.createBindingElement(undefined, undefined, 'params')
99
+ : undefined,
100
+ ].filter(Boolean),
101
+ ts.factory.createBindingElement(undefined, undefined, 'query'),
102
+ ts.factory.createBindingElement(undefined, undefined, 'headers'),
103
+ ts.factory.createBindingElement(undefined, undefined, 'data'),
104
+ ]), undefined, ts.factory.createTypeLiteralNode([
105
+ ...[
106
+ matches.length > 0
107
+ ? ts.factory.createPropertySignature(undefined, 'params', undefined, ts.factory.createTypeLiteralNode(matches.map((match) => {
108
+ return ts.factory.createPropertySignature([], match, undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword));
109
+ })))
110
+ : undefined,
111
+ ].filter(Boolean),
112
+ ts.factory.createPropertySignature(undefined, 'query', ts.factory.createToken(ts.SyntaxKind.QuestionToken), ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
113
+ ts.factory.createPropertySignature(undefined, 'headers', ts.factory.createToken(ts.SyntaxKind.QuestionToken), ts.factory.createTypeLiteralNode([
114
+ ts.factory.createIndexSignature(undefined, undefined, [
115
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, 'key', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), undefined),
116
+ ], ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
117
+ ])),
118
+ ts.factory.createPropertySignature(undefined, 'data', ts.factory.createToken(ts.SyntaxKind.QuestionToken), ts.factory.createTypeLiteralNode([
119
+ ts.factory.createIndexSignature(undefined, undefined, [
120
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, 'key', undefined, ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), undefined),
121
+ ], ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword)),
122
+ ])),
123
+ ])),
124
+ ];
125
+ };
126
+ const reqNodes = () => {
127
+ let reqUrl = '/' +
128
+ `/open-api${api.path}`
129
+ .replace(regex, '')
130
+ .split('/')
131
+ .filter(Boolean)
132
+ .join('/') +
133
+ '/';
134
+ console.log('reqUrl', reqUrl);
135
+ const urlNode = () => {
136
+ if (matches.length > 0 && express_1.query) {
137
+ return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(reqUrl), (() => {
138
+ if (matches.length == 1) {
139
+ return [
140
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[0]), ts.factory.createTemplateMiddle('?')),
141
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('query'), ts.factory.createTemplateMiddle('')),
142
+ ];
143
+ }
144
+ else {
145
+ return [
146
+ ...matches.slice(0, -1).map((match) => {
147
+ return ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + match), ts.factory.createTemplateMiddle('/'));
148
+ }),
149
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[matches.length - 1]), ts.factory.createTemplateMiddle('?')),
150
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('query'), ts.factory.createTemplateTail('')),
151
+ ];
152
+ }
153
+ })());
154
+ }
155
+ if (matches.length > 0) {
156
+ return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(reqUrl + '?'), (() => {
157
+ if (matches.length === 1) {
158
+ return [
159
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[0]), ts.factory.createTemplateMiddle('/')),
160
+ ];
161
+ }
162
+ else {
163
+ return [
164
+ ...matches.slice(0, -1).map((match) => {
165
+ return ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + match), ts.factory.createTemplateMiddle('/'));
166
+ }),
167
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('params.' + matches[matches.length - 1]), ts.factory.createTemplateTail('')),
168
+ ];
169
+ }
170
+ })());
171
+ }
172
+ if (express_1.query) {
173
+ return ts.factory.createTemplateExpression(ts.factory.createTemplateHead(reqUrl + '?'), [
174
+ ts.factory.createTemplateSpan(ts.factory.createIdentifier('query'), ts.factory.createTemplateTail('')),
175
+ ]);
176
+ }
177
+ return ts.factory.createStringLiteral(`/open-api${api.path}`);
178
+ };
179
+ return [
180
+ ts.factory.createObjectLiteralExpression(ts.factory.createNodeArray([
181
+ ts.factory.createPropertyAssignment(ts.factory.createStringLiteral('url'), urlNode()),
182
+ createPropertyAssignment('method', `${api.method}`),
183
+ ts.factory.createPropertyAssignment('headers', ts.factory.createIdentifier('headers')),
184
+ ts.factory.createPropertyAssignment('data', ts.factory.createIdentifier('data')),
185
+ ])),
186
+ ];
187
+ };
188
+ apiNode.push(ts.factory.createPropertyAssignment(apiName, ts.factory.createArrowFunction(undefined, undefined, createParameterDeclarations(), undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock([
189
+ ts.factory.createReturnStatement(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('api'), 'request'), undefined, reqNodes()), 'then'), undefined, [
190
+ ts.factory.createArrowFunction(undefined, undefined, [
191
+ ts.factory.createParameterDeclaration(undefined, undefined, undefined, 'res', undefined, ts.factory.createTypeReferenceNode('any')),
192
+ ], undefined, undefined, ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier('res'), ts.factory.createIdentifier('data'))),
193
+ ])),
194
+ ]))));
195
+ });
196
+ const printer = ts.createPrinter({
197
+ newLine: ts.NewLineKind.LineFeed,
198
+ });
199
+ const output = printer.printNode(ts.EmitHint.Unspecified, ast, ast);
200
+ const apiPath = path_1.default.join(process.cwd(), 'node_modules', '.micro', 'api.ts');
201
+ console.log('apiPath', apiPath);
202
+ fs_extra_1.default.writeFileSync(apiPath, prettier_1.default.format(output), { encoding: 'utf-8' });
203
+ }
204
+ });
@@ -0,0 +1,30 @@
1
+ import axios, { AxiosInstance, AxiosResponse, AxiosRequestConfig } from 'axios';
2
+ import { message } from 'antd';
3
+
4
+ const api = axios.create();
5
+
6
+ api.interceptors.request.use(
7
+ (config: AxiosRequestConfig) => {
8
+ config.headers = {
9
+ ...config.headers,
10
+ 'Content-Type': 'application/json;charset=utf-8',
11
+ };
12
+ return config;
13
+ },
14
+ (error: Error) => Promise.reject(error)
15
+ );
16
+
17
+ api.interceptors.response.use(
18
+ (response: AxiosResponse<any>) => {
19
+ const res = response.data;
20
+ if (!res.success) {
21
+ message.error(res.msg);
22
+ return Promise.reject(res);
23
+ }
24
+ return res;
25
+ },
26
+ (error: Error) => Promise.reject(error)
27
+ );
28
+
29
+ //根据 manifest apis生产微应用可以直接使用的
30
+ export const apis = {};
package/dist/bin/cli.js CHANGED
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env node
2
- "use strict";
3
2
  const PORXY_SIGN = "--proxy";
4
3
  const IS_MAIN = "--main";
5
4
  const params = process.argv.slice(2);
@@ -6,7 +6,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.reactJsConfig = exports.reactTsConfig = void 0;
7
7
  const react_refresh_webpack_plugin_1 = __importDefault(require("@pmmmwh/react-refresh-webpack-plugin"));
8
8
  const tsconfig_paths_webpack_plugin_1 = __importDefault(require("tsconfig-paths-webpack-plugin"));
9
- const fork_ts_checker_webpack_plugin_1 = __importDefault(require("fork-ts-checker-webpack-plugin"));
10
9
  const paths_1 = __importDefault(require("../config/paths"));
11
10
  const reactConfig = ({ isDev, isBuild, currentFramework, isTs, }) => {
12
11
  return {
@@ -56,17 +55,17 @@ const reactConfig = ({ isDev, isBuild, currentFramework, isTs, }) => {
56
55
  },
57
56
  plugins: [
58
57
  isDev && new react_refresh_webpack_plugin_1.default(),
59
- isTs &&
60
- new fork_ts_checker_webpack_plugin_1.default({
61
- //https://github.com/TypeStrong/fork-ts-checker-webpack-plugin#typescript-options
62
- typescript: {
63
- diagnosticOptions: {
64
- semantic: true,
65
- syntactic: true,
66
- },
67
- mode: 'write-references',
68
- },
69
- }),
58
+ // isTs &&
59
+ // new ForkTsCheckerWebpackPlugin({
60
+ // //https://github.com/TypeStrong/fork-ts-checker-webpack-plugin#typescript-options
61
+ // typescript: {
62
+ // diagnosticOptions: {
63
+ // semantic: true,
64
+ // syntactic: true,
65
+ // },
66
+ // mode: 'write-references',
67
+ // },
68
+ // }),
70
69
  ].filter((value) => Boolean(value)),
71
70
  };
72
71
  };
@@ -1,4 +1,27 @@
1
1
  "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
2
25
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
26
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
27
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -15,6 +38,8 @@ Object.defineProperty(exports, "__esModule", { value: true });
15
38
  exports.getFakeUser = void 0;
16
39
  const axios_1 = __importDefault(require("axios"));
17
40
  const chalk_1 = __importDefault(require("chalk"));
41
+ const fs = __importStar(require("fs-extra"));
42
+ const path = __importStar(require("path"));
18
43
  function parse_SDF_CONFIG(html) {
19
44
  var _a;
20
45
  const REGEX = /(?<=window._SDF_CONFIG=).*?(?=;)/;
@@ -36,16 +61,54 @@ function getFakeSaas(config) {
36
61
  console.log(chalk_1.default.red('没有配置target'));
37
62
  process.exit(1);
38
63
  }
39
- const { data } = yield axios_1.default.get(new URL('/login?disable_third_login=true', config.target).href);
40
- const _SDF_CONFIG = parse_SDF_CONFIG(data);
41
- const _SDF = parse_SDF(data);
42
- const __MAIN_APP_PUBLIC_PATH = parse__MAIN_APP_PUBLIC_PATH(data);
43
- const saas = {
44
- _SDF_CONFIG: JSON.parse(_SDF_CONFIG),
45
- _SDF: JSON.parse(_SDF),
46
- __MAIN_APP_PUBLIC_PATH: JSON.parse(__MAIN_APP_PUBLIC_PATH),
47
- };
48
- return saas;
64
+ if (config.isMainApp && fs.existsSync(path.join(process.cwd(), 'apps'))) {
65
+ const saasInfo = fs.readJSONSync(path.join(process.cwd(), 'saas-info.config.json'));
66
+ let saas = {
67
+ _SDF: {
68
+ base: '',
69
+ env: '',
70
+ region: '',
71
+ saas: {
72
+ background_image: 'https://images.tuyacn.com/rms-static/537a3fd0-1b5a-11ec-b7af-2d39f353debc-1632283530317.jpg?tyName=login.jpg',
73
+ charge_status: 'TRIAL',
74
+ entries: { entry_mode: 'normal' },
75
+ favicon: 'https://images.tuyacn.com/rms-static/ae9ba1b0-41d4-11ec-89bb-d7b7de210e4b-1636514225995.png?tyName=favicon.png',
76
+ host_filing: '备案:fast-cn.wgine',
77
+ is_custom: false,
78
+ is_need_jiyan: true,
79
+ is_support_mobile: true,
80
+ message_switch: true,
81
+ label: '',
82
+ legal_notice: 'https://ruomu-abc-001.fast-cn.wgine.com/policies/legal',
83
+ logo: 'https://images.tuyacn.com/rms-static/bc42adb0-6f86-11ec-b5fa-7deb2a111a61-1641538501643.png?tyName=%E9%BB%98%E8%AE%A4logo%2056X56%20.png',
84
+ privacy_policy: "https://ruomu-abc-001.fast-cn.wgine.com/policies/privacy",
85
+ service_terms: "https://ruomu-abc-001.fast-cn.wgine.com/policies/service",
86
+ supported_language: { en: 'English', zh: '简体中文' },
87
+ tenant_register_support: false,
88
+ tenant_type: "SINGLE_TENANT",
89
+ title: "物联网开放平台"
90
+ },
91
+ },
92
+ _SDF_CONFIG: {},
93
+ __MAIN_APP_PUBLIC_PATH: 'https://static1.tuyacn.com/static/sdf-main-app/0.0.0-123/',
94
+ };
95
+ Object.keys(saasInfo).forEach(key => {
96
+ saas._SDF.saas[key] = saasInfo[key] ? saasInfo[key] : saas._SDF.saas[key];
97
+ });
98
+ return saas;
99
+ }
100
+ else {
101
+ const { data } = yield axios_1.default.get(new URL('/login?disable_third_login=true', config.target).href);
102
+ const _SDF_CONFIG = parse_SDF_CONFIG(data);
103
+ const _SDF = parse_SDF(data);
104
+ const __MAIN_APP_PUBLIC_PATH = parse__MAIN_APP_PUBLIC_PATH(data);
105
+ const saas = {
106
+ _SDF_CONFIG: JSON.parse(_SDF_CONFIG),
107
+ _SDF: JSON.parse(_SDF),
108
+ __MAIN_APP_PUBLIC_PATH: JSON.parse(__MAIN_APP_PUBLIC_PATH),
109
+ };
110
+ return saas;
111
+ }
49
112
  });
50
113
  }
51
114
  exports.default = getFakeSaas;
@@ -1,2 +1,2 @@
1
- import { Express } from 'express';
1
+ import { Express } from "express";
2
2
  export default function mockSaasInfo(app: Express, microPort: number): void;
@@ -34,31 +34,73 @@ const path = __importStar(require("path"));
34
34
  const fs_extra_1 = __importDefault(require("fs-extra"));
35
35
  const utils_1 = require("../../utils");
36
36
  function mockSaasInfo(app, microPort) {
37
- let { multiApps, debuggerConfig: { isMainApp }, } = require(paths_1.default.microConfig);
37
+ let { multiApps, microApps, debuggerConfig: { isMainApp }, } = require(paths_1.default.microConfig);
38
38
  const idsMap = new Map();
39
39
  multiApps = (0, utils_1.processMultiApps)(multiApps);
40
- multiApps === null || multiApps === void 0 ? void 0 : multiApps.forEach((app) => {
41
- idsMap.set(app.name, { entry_id: (0, uuid_1.v4)(), oem_micro_app_id: (0, uid_1.uid)(16) });
42
- });
40
+ if (isMainApp && fs_extra_1.default.existsSync(path.join(process.cwd(), "apps"))) {
41
+ const dirs = ((microApps === null || microApps === void 0 ? void 0 : microApps.length) > 0 && microApps) ||
42
+ fs_extra_1.default.readdirSync(path.join(process.cwd(), "apps"));
43
+ dirs === null || dirs === void 0 ? void 0 : dirs.forEach((dir) => {
44
+ idsMap.set(dir, { entry_id: (0, uuid_1.v4)(), oem_micro_app_id: (0, uid_1.uid)(16) });
45
+ });
46
+ app.get("/api/saas-info", (req, res) => {
47
+ const lang = "zh";
48
+ const result = {
49
+ apps: [],
50
+ entry_info: { entries: [], entry_mode: "normal" },
51
+ permissions: {},
52
+ saas_id_info_list: [],
53
+ };
54
+ dirs.forEach((dir) => {
55
+ const entry_id = idsMap.get(dir).entry_id;
56
+ const manifest = fs_extra_1.default.readJSONSync(path.join(process.cwd(), "apps", dir, "manifest.json"), "utf-8");
57
+ const oem_micro_app_id = idsMap.get(dir).oem_micro_app_id;
58
+ const baseUrl = `/apps/${oem_micro_app_id}`;
59
+ result.saas_id_info_list.push({
60
+ oem_micro_app_id: oem_micro_app_id,
61
+ universal_id: "",
62
+ });
63
+ const appConfig = fs_extra_1.default.readJSONSync(path.join(process.cwd(), "node_modules", ".micro", "app.config.json"));
64
+ const micoApp = consturctApp(manifest, oem_micro_app_id, baseUrl, lang, appConfig[dir]);
65
+ const entryInfo = consturctEntry(manifest, oem_micro_app_id, entry_id, baseUrl, lang, `apps/${dir}`);
66
+ const permission = (manifest === null || manifest === void 0 ? void 0 : manifest.privileges.map((item) => {
67
+ return { permission_group: item.code };
68
+ })) || [];
69
+ result.apps.push(micoApp);
70
+ result.entry_info.entries.push(entryInfo);
71
+ result.permissions[oem_micro_app_id] = permission;
72
+ });
73
+ res.send({
74
+ code: null,
75
+ errorMsg: null,
76
+ msg: null,
77
+ result,
78
+ success: true,
79
+ });
80
+ });
81
+ }
43
82
  if (!isMainApp) {
44
- app.get('/api/saas-info', (req, res) => {
45
- const lang = parseCookie(req.headers['cookie'], 'main-i18next');
83
+ multiApps === null || multiApps === void 0 ? void 0 : multiApps.forEach((app) => {
84
+ idsMap.set(app.name, { entry_id: (0, uuid_1.v4)(), oem_micro_app_id: (0, uid_1.uid)(16) });
85
+ });
86
+ app.get("/api/saas-info", (req, res) => {
87
+ const lang = parseCookie(req.headers["cookie"], "main-i18next");
46
88
  if ((0, utils_1.isMonorepo)() || (multiApps && multiApps.length > 0)) {
47
89
  const result = {
48
90
  apps: [],
49
- entry_info: { entries: [], entry_mode: 'normal' },
91
+ entry_info: { entries: [], entry_mode: "normal" },
50
92
  permissions: {},
51
93
  saas_id_info_list: [],
52
94
  };
53
95
  multiApps.forEach((app) => {
54
96
  const entry_id = idsMap.get(app.name).entry_id;
55
97
  const dir = (0, utils_1.isMonorepo)() ? `apps/${app.name}` : `${app.dir}`;
56
- const manifest = fs_extra_1.default.readJSONSync(path.join(process.cwd(), dir, 'manifest.json'), 'utf-8');
98
+ const manifest = fs_extra_1.default.readJSONSync(path.join(process.cwd(), dir, "manifest.json"), "utf-8");
57
99
  const oem_micro_app_id = idsMap.get(app.name).oem_micro_app_id;
58
100
  const baseUrl = `/apps/${oem_micro_app_id}`;
59
101
  result.saas_id_info_list.push({
60
102
  oem_micro_app_id: oem_micro_app_id,
61
- universal_id: '',
103
+ universal_id: "",
62
104
  });
63
105
  const micoApp = consturctApp(manifest, oem_micro_app_id, baseUrl, lang, microPort, app.name);
64
106
  const entryInfo = consturctEntry(manifest, oem_micro_app_id, entry_id, baseUrl, lang, dir);
@@ -81,7 +123,7 @@ function mockSaasInfo(app, microPort) {
81
123
  const oem_micro_app_id = manifest.universalId;
82
124
  const baseUrl = `/apps/${oem_micro_app_id}`;
83
125
  const app = consturctApp(manifest, oem_micro_app_id, baseUrl, lang, microPort);
84
- const entryInfo = consturctEntry(manifest, oem_micro_app_id, entry_id, baseUrl, lang, '');
126
+ const entryInfo = consturctEntry(manifest, oem_micro_app_id, entry_id, baseUrl, lang, "");
85
127
  const permission = consturctPermissions();
86
128
  res.send({
87
129
  code: null,
@@ -89,10 +131,10 @@ function mockSaasInfo(app, microPort) {
89
131
  msg: null,
90
132
  result: {
91
133
  apps: [app],
92
- entry_info: { entries: [entryInfo], entry_mode: 'normal' },
134
+ entry_info: { entries: [entryInfo], entry_mode: "normal" },
93
135
  permissions: { [oem_micro_app_id]: permission },
94
136
  saas_id_info_list: [
95
- { oem_micro_app_id: oem_micro_app_id, universal_id: '' },
137
+ { oem_micro_app_id: oem_micro_app_id, universal_id: "" },
96
138
  ],
97
139
  },
98
140
  success: true,
@@ -110,9 +152,9 @@ function consturctEntry(manifest, oem_micro_app_id, entry_id, baseUrl, lang, dir
110
152
  menu.oem_micro_app_id = oem_micro_app_id;
111
153
  menu.entry_id = entry_id;
112
154
  //@ts-ignore
113
- menu.entry_name_zh = pickText(menu.entry_name, 'zh');
155
+ menu.entry_name_zh = pickText(menu.entry_name, "zh");
114
156
  //@ts-ignore
115
- menu.entry_name_en = pickText(menu.entry_name, 'en');
157
+ menu.entry_name_en = pickText(menu.entry_name, "en");
116
158
  //@ts-ignore
117
159
  menu.entry_name = pickText(menu.entry_name, lang);
118
160
  //@ts-ignore
@@ -121,6 +163,8 @@ function consturctEntry(manifest, oem_micro_app_id, entry_id, baseUrl, lang, dir
121
163
  if (menu.sub_entry_list.length) {
122
164
  stack.push(...menu.sub_entry_list);
123
165
  }
166
+ menu.icon =
167
+ "https://images.tuyacn.com/rms-static/5d202fa0-e909-11eb-815d-e39234ce96ff-1626751199130.png?tyName=space-manage.png";
124
168
  }
125
169
  return fakeMenu;
126
170
  }
@@ -128,13 +172,13 @@ function consturctApp(manifest, oem_micro_app_id, baseUrl, lang, port, code) {
128
172
  const packageInfo = (0, micro_utils_1.getPackage)();
129
173
  return {
130
174
  active_rule: baseUrl,
131
- dependencies: [''],
175
+ dependencies: [""],
132
176
  ext_info: null,
133
177
  micro_app_code: code || `${packageInfo.name}`,
134
178
  micro_app_name: code ? `${code}-dev` : `${packageInfo.name}-dev`,
135
- micro_app_version: '0.0.0-x',
179
+ micro_app_version: "0.0.0-x",
136
180
  oem_micro_app_id,
137
- resource: `http://localhost:${port}/${code || 'index'}.html`,
181
+ resource: `http://localhost:${port}/${code || "index"}.html`,
138
182
  schema: null,
139
183
  universal_id: manifest.universalId,
140
184
  isAuth: true,
@@ -146,15 +190,15 @@ function consturctPermissions() {
146
190
  return mockPermissions.map((code) => ({ permission_group: code }));
147
191
  }
148
192
  function pickText(texts, lang) {
149
- return lang === 'en' ? texts[1] : texts[0];
193
+ return lang === "en" ? texts[1] : texts[0];
150
194
  }
151
195
  function parseCookie(cookie, key) {
152
- const cookies = (cookie || '').split(';');
196
+ const cookies = (cookie || "").split(";");
153
197
  for (let cookieItem of cookies) {
154
- const [cookieKey, value] = cookieItem.split('=');
198
+ const [cookieKey, value] = cookieItem.split("=");
155
199
  if (cookieKey.trim() === key) {
156
200
  return value;
157
201
  }
158
202
  }
159
- return '';
203
+ return "";
160
204
  }
@@ -41,6 +41,8 @@ const fakeSaas_1 = __importStar(require("./fakeSaas"));
41
41
  const paths_1 = __importDefault(require("../../config/paths"));
42
42
  const webpack_common_1 = require("../../config/webpack.common");
43
43
  const undici_1 = require("undici");
44
+ const fs = __importStar(require("fs-extra"));
45
+ const path = __importStar(require("path"));
44
46
  function parse_SDF(html) {
45
47
  var _a;
46
48
  const REGEX = /(?<=window._SDF=).*?}(?=;)/;
@@ -117,6 +119,17 @@ function insertScript($, debuggerConfig) {
117
119
  }
118
120
  : {})), readThemeConfig()));
119
121
  overrideNotification(saas);
122
+ if (fs.existsSync(path.join(process.cwd(), 'saas-info.config.json'))) {
123
+ const saasInfo = fs.readJSONSync(path.join(process.cwd(), 'saas-info.config.json'));
124
+ let $favicon = $('link[rel="icon"]');
125
+ if (!$favicon.length) {
126
+ $('head').prepend('<link rel="icon" />');
127
+ $favicon = $('link[rel="icon"]');
128
+ }
129
+ const favicon = (saasInfo === null || saasInfo === void 0 ? void 0 : saasInfo.favicon) ? saasInfo.favicon : 'https://images.tuyacn.com/rms-static/ae9ba1b0-41d4-11ec-89bb-d7b7de210e4b-1636514225995.png?tyName=favicon.png';
130
+ $favicon
131
+ .attr('href', favicon);
132
+ }
120
133
  // 本地开发态多语言剥离多语言平台,走本地多语言兜底逻辑
121
134
  delete _SDF.saas.saas_locales;
122
135
  $('head').append($('<script>').text(`window._SDF_CONFIG=${JSON.stringify(_SDF_CONFIG)};window._SDF=${JSON.stringify(_SDF)};window.__MAIN_APP_PUBLIC_PATH=${JSON.stringify(__MAIN_APP_PUBLIC_PATH)};
@@ -17,11 +17,17 @@ const chalk_1 = __importDefault(require("chalk"));
17
17
  const ora_1 = __importDefault(require("ora"));
18
18
  const webpack_config_1 = __importDefault(require("../config/webpack.config"));
19
19
  const template_1 = __importDefault(require("../template"));
20
+ const apis_1 = __importDefault(require("../apis"));
21
+ const paths_1 = __importDefault(require("../config/paths"));
22
+ const fs_extra_1 = __importDefault(require("fs-extra"));
23
+ const path_1 = __importDefault(require("path"));
20
24
  const BUILD_FAIL_TIP = '糟糕:打包失败了,下面是具体信息';
21
25
  const spinner = (0, ora_1.default)('building').start();
26
+ let { debuggerConfig: { isMainApp }, } = require(paths_1.default.microConfig);
22
27
  const config = (0, webpack_config_1.default)();
23
28
  (() => __awaiter(void 0, void 0, void 0, function* () {
24
29
  yield (0, template_1.default)();
30
+ yield (0, apis_1.default)();
25
31
  (0, webpack_1.default)(config).run((err, stats) => {
26
32
  if (err) {
27
33
  spinner.fail();
@@ -37,6 +43,19 @@ const config = (0, webpack_config_1.default)();
37
43
  process.exit(1);
38
44
  }
39
45
  spinner.succeed();
46
+ // 修复主应用 manifest.json资源丢失问题
47
+ if (isMainApp) {
48
+ const files = fs_extra_1.default.readdirSync(path_1.default.join(process.cwd(), 'dist/static/img')) || [];
49
+ const manifest = fs_extra_1.default.readJSONSync(path_1.default.join(process.cwd(), 'dist/manifest.json'));
50
+ const result = files.reduce((acc, file) => {
51
+ if (file) {
52
+ const key = file.split('.')[0];
53
+ acc[key] = `static/img/${file}`;
54
+ }
55
+ return acc;
56
+ }, {});
57
+ fs_extra_1.default.writeJSONSync(path_1.default.join(process.cwd(), 'dist/manifest.json'), Object.assign(Object.assign({}, manifest), result));
58
+ }
40
59
  if (stats.hasWarnings()) {
41
60
  console.log(chalk_1.default.yellow('难受:有告警信息,下面是具体信息'));
42
61
  console.log(warnings.map((item) => item.message).join('\n'));
@@ -18,28 +18,48 @@ const mock_1 = __importDefault(require("../module/mock"));
18
18
  const bundleServer_1 = require("../module/bundleServer");
19
19
  const proxy_1 = __importDefault(require("../module/proxy"));
20
20
  const template_1 = __importDefault(require("../template"));
21
+ const apis_1 = __importDefault(require("../apis"));
21
22
  (() => __awaiter(void 0, void 0, void 0, function* () {
22
23
  yield (0, template_1.default)();
24
+ yield (0, apis_1.default)();
23
25
  let defaultPort = 9000;
24
26
  console.log(chalk_1.default.yellow('如果是pc端的微应用调试,请勿使用该命令,考虑使用`start --main`或`start --main --proxy`'));
25
27
  //检测端口占用情况
26
- const port = yield portfinder_1.default.getPortPromise({
27
- port: defaultPort,
28
- stopPort: defaultPort + 100,
29
- });
30
- const compiler = (0, bundleServer_1.createServerCompiler)();
31
- (0, bundleServer_1.runBundleServer)({
32
- port,
33
- compiler,
34
- internalDevConfig: {
35
- open: true,
36
- setupMiddlewares(middleware, { app }) {
37
- (0, mock_1.default)(app);
38
- (0, proxy_1.default)(app);
39
- return middleware;
28
+ console.log('process.env.PROT', process.env.PROT);
29
+ if (process.env.PROT) {
30
+ const compiler = (0, bundleServer_1.createServerCompiler)();
31
+ (0, bundleServer_1.runBundleServer)({
32
+ port: Number(process.env.PROT),
33
+ compiler,
34
+ internalDevConfig: {
35
+ open: false,
36
+ setupMiddlewares(middleware, { app }) {
37
+ (0, mock_1.default)(app);
38
+ (0, proxy_1.default)(app);
39
+ return middleware;
40
+ },
40
41
  },
41
- },
42
- });
42
+ });
43
+ }
44
+ else {
45
+ const port = yield portfinder_1.default.getPortPromise({
46
+ port: defaultPort,
47
+ stopPort: defaultPort + 100,
48
+ });
49
+ const compiler = (0, bundleServer_1.createServerCompiler)();
50
+ (0, bundleServer_1.runBundleServer)({
51
+ port,
52
+ compiler,
53
+ internalDevConfig: {
54
+ open: true,
55
+ setupMiddlewares(middleware, { app }) {
56
+ (0, mock_1.default)(app);
57
+ (0, proxy_1.default)(app);
58
+ return middleware;
59
+ },
60
+ },
61
+ });
62
+ }
43
63
  }))().catch((err) => {
44
64
  console.log(err);
45
65
  });
@@ -18,8 +18,10 @@ const mainServer_1 = __importDefault(require("../module/mainServer"));
18
18
  const bundleServer_1 = require("../module/bundleServer");
19
19
  const kill_port_1 = __importDefault(require("kill-port"));
20
20
  const template_1 = __importDefault(require("../template"));
21
+ const apis_1 = __importDefault(require("../apis"));
21
22
  (() => __awaiter(void 0, void 0, void 0, function* () {
22
23
  yield (0, template_1.default)();
24
+ yield (0, apis_1.default)();
23
25
  let defaultPort = 9000;
24
26
  //检测端口占用情况
25
27
  const bundledServerPort = yield portfinder_1.default.getPortPromise({
@@ -86,8 +86,8 @@ exports.default = () => __awaiter(void 0, void 0, void 0, function* () {
86
86
  let langContent = fs.readFileSync(path.join(__dirname, './micro-app/lang.ts'), {
87
87
  encoding: 'utf8',
88
88
  });
89
- langContent = langContent.replace("import en from './en';", `import en from '../../src/lang/en'`);
90
- langContent = langContent.replace("import zh from './zh';", `import zh from '../../src/lang/zh'`);
89
+ langContent = langContent.replace("import en from './en.json';", `import en from '../../src/lang/en.json'`);
90
+ langContent = langContent.replace("import zh from './zh.json';", `import zh from '../../src/lang/zh.json'`);
91
91
  fs.writeFileSync(microPath + '/lang.ts', langContent);
92
92
  }
93
93
  });
@@ -11,6 +11,7 @@ import './index.css';
11
11
  import './styles/global.less';
12
12
  export * from './interfaces';
13
13
  export * from './antdLang';
14
+ export * from './api';
14
15
  export let microProps: IQiankunProps;
15
16
 
16
17
  function render(props: IQiankunProps) {
@@ -1,8 +1,9 @@
1
1
  import { CaptureContext, Event, Severity } from '@sentry/types';
2
2
 
3
+ type IState = { [k in string]: string | number | null };
3
4
  interface mainHistory {
4
- push: (path, state?) => void;
5
- replace: (path, state?) => void;
5
+ push: (path: string, state?: IState) => void;
6
+ replace: (path: string, state?: IState) => void;
6
7
  go: (n: number) => void;
7
8
  goBack: () => void;
8
9
  goForward: () => void;
@@ -1,8 +1,8 @@
1
1
  import i18n from 'i18next';
2
2
  import { initReactI18next } from 'react-i18next';
3
3
  import LanguageDetector from 'i18next-browser-languagedetector';
4
- import en from './en';
5
- import zh from './zh';
4
+ import en from './en.json';
5
+ import zh from './zh.json';
6
6
 
7
7
  i18n
8
8
  .use(LanguageDetector)
@@ -1,5 +1,5 @@
1
1
  export declare const promiser: () => {
2
2
  waiting: Promise<unknown>;
3
- resolve: undefined;
4
- reject: undefined;
3
+ resolve: any;
4
+ reject: any;
5
5
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tuya-sat/micro-script",
3
- "version": "3.0.26",
3
+ "version": "3.0.27-beta.10",
4
4
  "bin": "./dist/bin/cli.js",
5
5
  "type": "commonjs",
6
6
  "license": "MIT",
@@ -23,9 +23,9 @@
23
23
  "@babel/preset-typescript": "7.16.7",
24
24
  "@babel/traverse": "^7.20.13",
25
25
  "@pmmmwh/react-refresh-webpack-plugin": "0.5.4",
26
- "@tuya-sat/micro-dev-loader": "3.0.26",
27
- "@tuya-sat/micro-dev-proxy": "3.0.26",
28
- "@tuya-sat/micro-utils": "3.0.26",
26
+ "@tuya-sat/micro-dev-loader": "3.0.27-beta.10",
27
+ "@tuya-sat/micro-dev-proxy": "3.0.27-beta.10",
28
+ "@tuya-sat/micro-utils": "3.0.27-beta.10",
29
29
  "@types/kill-port": "^2.0.0",
30
30
  "babel-loader": "8.2.4",
31
31
  "babel-plugin-import": "1.13.3",
@@ -44,6 +44,7 @@
44
44
  "kill-port": "^2.0.1",
45
45
  "less": "4.1.2",
46
46
  "less-loader": "10.2.0",
47
+ "mime": "^3.0.0",
47
48
  "mini-css-extract-plugin": "2.6.0",
48
49
  "open": "8.4.0",
49
50
  "ora": "5.4.1",
@@ -52,6 +53,7 @@
52
53
  "postcss": "8.4.12",
53
54
  "postcss-loader": "6.2.1",
54
55
  "postcss-preset-env": "7.4.3",
56
+ "prettier": "^2.8.8",
55
57
  "react-refresh": "0.11.0",
56
58
  "resolve-url-loader": "5.0.0",
57
59
  "sass": "1.49.9",
@@ -16,3 +16,8 @@ fs.copySync(
16
16
  path.join(process.cwd(), './src/template/main-app'),
17
17
  path.join(process.cwd(), 'dist/template/main-app')
18
18
  );
19
+
20
+ fs.copySync(
21
+ path.join(process.cwd(), './src/apis/template.ts'),
22
+ path.join(process.cwd(), 'dist/apis/template.ts')
23
+ );