@mpilk/mp-route 2.0.0 → 3.0.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.
package/dist/index.cjs CHANGED
@@ -1,256 +1,287 @@
1
- 'use strict';
2
-
3
- var path = require('path');
4
- var fs = require('fs');
5
- var pino = require('pino');
6
- var mpShared = require('@vsilk/mp-shared');
7
- var lodashEs = require('lodash-es');
8
- var chokidar = require('chokidar');
9
-
10
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
-
12
- var path__default = /*#__PURE__*/_interopDefault(path);
13
- var fs__default = /*#__PURE__*/_interopDefault(fs);
14
- var pino__default = /*#__PURE__*/_interopDefault(pino);
15
- var chokidar__default = /*#__PURE__*/_interopDefault(chokidar);
16
-
17
- // src/helper.ts
18
- function defineMiniRouter(config) {
19
- return config;
20
- }
21
- function defineMiniTabbar(config) {
22
- return config;
23
- }
24
- var _indexPath = "";
25
- var logger = pino__default.default({
26
- transport: {
27
- target: "pino-pretty",
28
- options: {
29
- colorize: true
30
- // ignore: 'hostname,pid',
31
- }
32
- }
33
- });
34
- var verboseLogger = logger.child({ verbose: true });
35
- function builderWithWatch(options) {
36
- let timer = null;
37
- function run() {
38
- if (timer)
39
- clearTimeout(timer);
40
- timer = setTimeout(() => {
41
- timer = null;
42
- return builder(options);
43
- }, options?.delay || 200);
44
- }
45
- return chokidar__default.default.watch([
46
- `src/**/${options?.routeName || "route"}.{ts,js}`,
47
- `src/${options?.tabbarName || "tabbar"}.{ts,js}`
48
- ]).on("all", (eventName) => {
49
- switch (eventName) {
50
- case "add":
51
- case "change":
52
- case "unlink":
53
- run();
54
- break;
55
- }
56
- });
57
- }
58
- async function builder(options = {}) {
59
- const { input = "./src", routeName = "route", tabbarName = "tabbar", pagesPath = "./src/pages.json", verbose } = options;
60
- logger.info("\u5F00\u59CB\u751F\u6210\u8DEF\u7531\u6587\u4EF6...");
61
- const filePaths = loadDirFiles(input, routeName);
62
- logger.info(`\u6839\u636E ${routeName} \u627E\u5230 ${filePaths.length} \u4E2A\u6587\u4EF6`);
63
- const routeConfigs = [];
64
- for (const filePath of filePaths) {
65
- verbose && verboseLogger.info(`\u5F00\u59CB\u89E3\u6790\u6587\u4EF6 ${filePath}`);
66
- let content = await mpShared.loadFileContent(filePath);
67
- if (!content || typeof content !== "object" || lodashEs.isEmpty(content)) {
68
- verbose && verboseLogger.info(`\u6587\u4EF6 ${filePath} \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7`);
69
- continue;
70
- }
71
- if (!lodashEs.isArray(content))
72
- content = [content];
73
- verbose && verboseLogger.info(`\u6587\u4EF6 ${filePath} \u89E3\u6790\u5B8C\u6210\uFF1A${JSON.stringify(content)}`);
74
- routeConfigs.push(...content);
75
- }
76
- const rs = buildRoute(routeConfigs);
77
- if (_indexPath) {
78
- const idx2 = rs.pages.findIndex((page) => page.path === _indexPath);
79
- if (idx2 !== -1)
80
- rs.pages.unshift(...rs.pages.splice(idx2, 1));
81
- }
82
- logger.info("\u8DEF\u7531\u6587\u4EF6\u89E3\u6790\u5B8C\u6210");
83
- if (!rs.condition.list.length)
84
- rs.condition = void 0;
85
- else if (rs.condition.list.length && rs.condition.current === -1)
86
- rs.condition.current = 0;
87
- const idx = rs.pages.findIndex((page) => page["_index"]);
88
- if (idx !== -1)
89
- rs.pages.unshift(...rs.pages.splice(idx, 1));
90
- let tabbarObj;
91
- const [tabbarPath] = loadDirFiles("./src", tabbarName);
92
- if (tabbarPath && !lodashEs.isEmpty(tabbarPath)) {
93
- logger.info(`\u6839\u636E ${tabbarName} \u627E\u52301\u4E2A\u6587\u4EF6`);
94
- tabbarObj = await mpShared.loadFileContent(tabbarPath);
95
- if (tabbarObj && !lodashEs.isEmpty(tabbarObj))
96
- rs.tabBar = tabbarObj;
97
- }
98
- const {
99
- debug: _debug = false,
100
- pages,
101
- subPackages,
102
- preloadRule,
103
- condition,
104
- tabBar,
105
- ...otherProps
106
- } = await mpShared.loadJson(pagesPath);
107
- const writeContent = {
108
- debug: _debug,
109
- pages: rs.pages || pages,
110
- subPackages: rs.subPackages || subPackages,
111
- preloadRule: rs.preloadRule || preloadRule,
112
- condition: rs.condition || condition,
113
- tabBar: tabbarObj || tabBar,
114
- ...otherProps
115
- };
116
- await mpShared.outputFile(pagesPath, JSON.stringify(writeContent, null, 2));
117
- logger.info("\u8DEF\u7531\u6587\u4EF6\u751F\u6210\u5B8C\u6210\uFF01");
118
- }
119
- function buildRoute(content, ext = {}) {
120
- const result = {
121
- pages: [],
122
- subPackages: [],
123
- preloadRule: {},
124
- condition: {
125
- current: -1,
126
- list: []
127
- }
128
- };
129
- const { parentName = "", parentPath = "", subpackageRoot = "" } = ext;
130
- for (const route of content) {
131
- const { subPackages = false, isSubpackage = subPackages, path: path2, title, name, children } = route;
132
- const style = {
133
- navigationBarTitleText: title || name || parentName,
134
- ...route.style
135
- };
136
- const _path = pathJoin(parentPath, path2);
137
- if (isSubpackage && !subpackageRoot) {
138
- let { preLoadPath, preLoadNetwork } = route;
139
- const { pages, preloadRule, condition } = buildRoute(children ?? [], {
140
- parentName: style.navigationBarTitleText,
141
- subpackageRoot: _path
142
- });
143
- const subPackage = {
144
- root: _path,
145
- pages
146
- };
147
- result.preloadRule = deepMerge(result.preloadRule, preloadRule);
148
- result.condition = deepMerge(result.condition, condition);
149
- if (condition.current > -1)
150
- result.condition.current = result.condition?.list?.indexOf(condition.list[condition.current]);
151
- result.subPackages.push(subPackage);
152
- if (preLoadPath) {
153
- if (!lodashEs.isArray(preLoadPath))
154
- preLoadPath = [preLoadPath];
155
- const preLoadRule = preLoadPath.reduce((acc, cur) => {
156
- acc[pathJoin(cur)] = {
157
- network: preLoadNetwork,
158
- packages: [_path]
159
- };
160
- return acc;
161
- }, {});
162
- result.preloadRule = deepMerge(result.preloadRule, preLoadRule);
163
- }
164
- continue;
165
- }
166
- if (children?.length) {
167
- const { pages, subPackages: subPackages2, preloadRule, condition } = buildRoute(
168
- children,
169
- {
170
- parentName: style.navigationBarTitleText,
171
- parentPath: _path,
172
- subpackageRoot
173
- }
174
- );
175
- result.pages = deepMerge(result.pages, pages);
176
- result.subPackages = deepMerge(result.subPackages, subPackages2);
177
- result.preloadRule = deepMerge(result.preloadRule, preloadRule);
178
- result.condition = deepMerge(result.condition, condition);
179
- if (condition.current > -1)
180
- result.condition.current = result.condition?.list?.indexOf(condition.list[condition.current]);
181
- } else {
182
- const { conditionActive, conditionQuery } = route;
183
- const item = {
184
- path: _path,
185
- style
186
- };
187
- route.isIndex && (_indexPath = _path);
188
- result.pages.push(item);
189
- if (conditionQuery || conditionActive) {
190
- const conditionItem = {
191
- name: style.navigationBarTitleText,
192
- path: _path,
193
- query: conditionQuery
194
- };
195
- result.condition.list.push(conditionItem);
196
- if (conditionActive)
197
- result.condition.current = result.condition.list?.indexOf(conditionItem);
198
- }
199
- }
200
- }
201
- return result;
202
- }
203
- var extension = [".ts", ".js", ".mjs", ".json"];
204
- function loadDirFiles(roots, name, exitByFirst = false) {
205
- if (!Array.isArray(roots))
206
- roots = [roots];
207
- const files = [];
208
- for (let root of roots) {
209
- root = path__default.default.resolve(root);
210
- if (!fs__default.default.existsSync(root))
211
- continue;
212
- const stat = fs__default.default.statSync(root);
213
- const regex = new RegExp(`${name}(${extension.join("|")})$`);
214
- if (stat.isFile() && regex.test(root)) {
215
- files.push(root);
216
- if (exitByFirst)
217
- break;
218
- }
219
- if (stat.isDirectory()) {
220
- const dirents = fs__default.default.readdirSync(root).map((o) => path__default.default.resolve(root, o));
221
- files.push(...loadDirFiles(dirents, name));
222
- }
223
- }
224
- return files;
225
- }
226
- function pathJoin(...paths) {
227
- return paths.join("/").split("/").filter(Boolean).join("/");
228
- }
229
- function deepMerge(target, ...sources) {
230
- if (typeof target !== "object" || target === null)
231
- target = {};
232
- if (!sources.length)
233
- return target;
234
- for (const source of sources) {
235
- if (typeof source !== "object" || source === null)
236
- continue;
237
- if (lodashEs.isArray(target) && lodashEs.isArray(source)) {
238
- const set = /* @__PURE__ */ new Set([...target, ...source]);
239
- return [...set];
240
- } else if (lodashEs.isPlainObject(target) && lodashEs.isPlainObject(source)) {
241
- for (const key in source) {
242
- if (key in target && typeof target[key] === "object" && typeof source[key] === "object") {
243
- target[key] = deepMerge(target[key], source[key]);
244
- } else {
245
- target[key] = source[key] || target[key];
246
- }
247
- }
248
- }
249
- }
250
- return target;
251
- }
252
-
253
- exports.builder = builder;
254
- exports.builderWithWatch = builderWithWatch;
255
- exports.defineMiniRouter = defineMiniRouter;
256
- exports.defineMiniTabbar = defineMiniTabbar;
1
+ 'use strict'
2
+
3
+ var path = require('path')
4
+ var fs = require('fs')
5
+ var pino = require('pino')
6
+ var mpShared = require('@mpilk/mp-shared')
7
+ var lodashEs = require('lodash-es')
8
+ var chokidar = require('chokidar')
9
+
10
+ function _interopDefault(e) {
11
+ return e && e.__esModule ? e : { default: e }
12
+ }
13
+
14
+ var path__default = /*#__PURE__*/ _interopDefault(path)
15
+ var fs__default = /*#__PURE__*/ _interopDefault(fs)
16
+ var pino__default = /*#__PURE__*/ _interopDefault(pino)
17
+ var chokidar__default = /*#__PURE__*/ _interopDefault(chokidar)
18
+
19
+ // src/helper.ts
20
+ function defineMiniRouter(config) {
21
+ return config
22
+ }
23
+ function defineMiniTabbar(config) {
24
+ return config
25
+ }
26
+ var _indexPath = ''
27
+ var logger = pino__default.default({
28
+ transport: {
29
+ target: 'pino-pretty',
30
+ options: {
31
+ colorize: true
32
+ // ignore: 'hostname,pid',
33
+ }
34
+ }
35
+ })
36
+ var verboseLogger = logger.child({ verbose: true })
37
+ function builderWithWatch(options) {
38
+ let timer = null
39
+ function run() {
40
+ if (timer) clearTimeout(timer)
41
+ timer = setTimeout(() => {
42
+ timer = null
43
+ return builder(options)
44
+ }, options?.delay || 200)
45
+ }
46
+ return chokidar__default.default
47
+ .watch([
48
+ `src/**/${options?.routeName || 'route'}.{ts,js}`,
49
+ `src/${options?.tabbarName || 'tabbar'}.{ts,js}`
50
+ ])
51
+ .on('all', (eventName) => {
52
+ switch (eventName) {
53
+ case 'add':
54
+ case 'change':
55
+ case 'unlink':
56
+ run()
57
+ break
58
+ }
59
+ })
60
+ }
61
+ async function builder(options = {}) {
62
+ const {
63
+ input = './src',
64
+ routeName = 'route',
65
+ tabbarName = 'tabbar',
66
+ pagesPath = './src/pages.json',
67
+ verbose
68
+ } = options
69
+ logger.info('\u5F00\u59CB\u751F\u6210\u8DEF\u7531\u6587\u4EF6...')
70
+ const filePaths = loadDirFiles(input, routeName)
71
+ logger.info(
72
+ `\u6839\u636E ${routeName} \u627E\u5230 ${filePaths.length} \u4E2A\u6587\u4EF6`
73
+ )
74
+ const routeConfigs = []
75
+ for (const filePath of filePaths) {
76
+ verbose &&
77
+ verboseLogger.info(`\u5F00\u59CB\u89E3\u6790\u6587\u4EF6 ${filePath}`)
78
+ let content = await mpShared.loadFileContent(filePath)
79
+ if (!content || typeof content !== 'object' || lodashEs.isEmpty(content)) {
80
+ verbose &&
81
+ verboseLogger.info(
82
+ `\u6587\u4EF6 ${filePath} \u4E3A\u7A7A\uFF0C\u8DF3\u8FC7`
83
+ )
84
+ continue
85
+ }
86
+ if (!lodashEs.isArray(content)) content = [content]
87
+ verbose &&
88
+ verboseLogger.info(
89
+ `\u6587\u4EF6 ${filePath} \u89E3\u6790\u5B8C\u6210\uFF1A${JSON.stringify(
90
+ content
91
+ )}`
92
+ )
93
+ routeConfigs.push(...content)
94
+ }
95
+ const rs = buildRoute(routeConfigs)
96
+ if (_indexPath) {
97
+ const idx2 = rs.pages.findIndex((page) => page.path === _indexPath)
98
+ if (idx2 !== -1) rs.pages.unshift(...rs.pages.splice(idx2, 1))
99
+ }
100
+ logger.info('\u8DEF\u7531\u6587\u4EF6\u89E3\u6790\u5B8C\u6210')
101
+ if (!rs.condition.list.length) rs.condition = void 0
102
+ else if (rs.condition.list.length && rs.condition.current === -1)
103
+ rs.condition.current = 0
104
+ const idx = rs.pages.findIndex((page) => page['_index'])
105
+ if (idx !== -1) rs.pages.unshift(...rs.pages.splice(idx, 1))
106
+ let tabbarObj
107
+ const [tabbarPath] = loadDirFiles('./src', tabbarName)
108
+ if (tabbarPath && !lodashEs.isEmpty(tabbarPath)) {
109
+ logger.info(`\u6839\u636E ${tabbarName} \u627E\u52301\u4E2A\u6587\u4EF6`)
110
+ tabbarObj = await mpShared.loadFileContent(tabbarPath)
111
+ if (tabbarObj && !lodashEs.isEmpty(tabbarObj)) rs.tabBar = tabbarObj
112
+ }
113
+ const {
114
+ debug: _debug = false,
115
+ pages,
116
+ subPackages,
117
+ preloadRule,
118
+ condition,
119
+ tabBar,
120
+ ...otherProps
121
+ } = await mpShared.loadJson(pagesPath)
122
+ const writeContent = {
123
+ debug: _debug,
124
+ pages: rs.pages || pages,
125
+ subPackages: rs.subPackages || subPackages,
126
+ preloadRule: rs.preloadRule || preloadRule,
127
+ condition: rs.condition || condition,
128
+ tabBar: tabbarObj || tabBar,
129
+ ...otherProps
130
+ }
131
+ await mpShared.outputFile(pagesPath, JSON.stringify(writeContent, null, 2))
132
+ logger.info('\u8DEF\u7531\u6587\u4EF6\u751F\u6210\u5B8C\u6210\uFF01')
133
+ }
134
+ function buildRoute(content, ext = {}) {
135
+ const result = {
136
+ pages: [],
137
+ subPackages: [],
138
+ preloadRule: {},
139
+ condition: {
140
+ current: -1,
141
+ list: []
142
+ }
143
+ }
144
+ const { parentName = '', parentPath = '', subpackageRoot = '' } = ext
145
+ for (const route of content) {
146
+ const {
147
+ subPackages = false,
148
+ isSubpackage = subPackages,
149
+ path: path2,
150
+ title,
151
+ name,
152
+ children
153
+ } = route
154
+ const style = {
155
+ navigationBarTitleText: title || name || parentName,
156
+ ...route.style
157
+ }
158
+ const _path = pathJoin(parentPath, path2)
159
+ if (isSubpackage && !subpackageRoot) {
160
+ let { preLoadPath, preLoadNetwork } = route
161
+ const { pages, preloadRule, condition } = buildRoute(children ?? [], {
162
+ parentName: style.navigationBarTitleText,
163
+ subpackageRoot: _path
164
+ })
165
+ const subPackage = {
166
+ root: _path,
167
+ pages
168
+ }
169
+ result.preloadRule = deepMerge(result.preloadRule, preloadRule)
170
+ result.condition = deepMerge(result.condition, condition)
171
+ if (condition.current > -1)
172
+ result.condition.current = result.condition?.list?.indexOf(
173
+ condition.list[condition.current]
174
+ )
175
+ result.subPackages.push(subPackage)
176
+ if (preLoadPath) {
177
+ if (!lodashEs.isArray(preLoadPath)) preLoadPath = [preLoadPath]
178
+ const preLoadRule = preLoadPath.reduce((acc, cur) => {
179
+ acc[pathJoin(cur)] = {
180
+ network: preLoadNetwork,
181
+ packages: [_path]
182
+ }
183
+ return acc
184
+ }, {})
185
+ result.preloadRule = deepMerge(result.preloadRule, preLoadRule)
186
+ }
187
+ continue
188
+ }
189
+ if (children?.length) {
190
+ const {
191
+ pages,
192
+ subPackages: subPackages2,
193
+ preloadRule,
194
+ condition
195
+ } = buildRoute(children, {
196
+ parentName: style.navigationBarTitleText,
197
+ parentPath: _path,
198
+ subpackageRoot
199
+ })
200
+ result.pages = deepMerge(result.pages, pages)
201
+ result.subPackages = deepMerge(result.subPackages, subPackages2)
202
+ result.preloadRule = deepMerge(result.preloadRule, preloadRule)
203
+ result.condition = deepMerge(result.condition, condition)
204
+ if (condition.current > -1)
205
+ result.condition.current = result.condition?.list?.indexOf(
206
+ condition.list[condition.current]
207
+ )
208
+ } else {
209
+ const { conditionActive, conditionQuery } = route
210
+ const item = {
211
+ path: _path,
212
+ style
213
+ }
214
+ route.isIndex && (_indexPath = _path)
215
+ result.pages.push(item)
216
+ if (conditionQuery || conditionActive) {
217
+ const conditionItem = {
218
+ name: style.navigationBarTitleText,
219
+ path: _path,
220
+ query: conditionQuery
221
+ }
222
+ result.condition.list.push(conditionItem)
223
+ if (conditionActive)
224
+ result.condition.current =
225
+ result.condition.list?.indexOf(conditionItem)
226
+ }
227
+ }
228
+ }
229
+ return result
230
+ }
231
+ var extension = ['.ts', '.js', '.mjs', '.json']
232
+ function loadDirFiles(roots, name, exitByFirst = false) {
233
+ if (!Array.isArray(roots)) roots = [roots]
234
+ const files = []
235
+ for (let root of roots) {
236
+ root = path__default.default.resolve(root)
237
+ if (!fs__default.default.existsSync(root)) continue
238
+ const stat = fs__default.default.statSync(root)
239
+ const regex = new RegExp(`${name}(${extension.join('|')})$`)
240
+ if (stat.isFile() && regex.test(root)) {
241
+ files.push(root)
242
+ if (exitByFirst) break
243
+ }
244
+ if (stat.isDirectory()) {
245
+ const dirents = fs__default.default
246
+ .readdirSync(root)
247
+ .map((o) => path__default.default.resolve(root, o))
248
+ files.push(...loadDirFiles(dirents, name))
249
+ }
250
+ }
251
+ return files
252
+ }
253
+ function pathJoin(...paths) {
254
+ return paths.join('/').split('/').filter(Boolean).join('/')
255
+ }
256
+ function deepMerge(target, ...sources) {
257
+ if (typeof target !== 'object' || target === null) target = {}
258
+ if (!sources.length) return target
259
+ for (const source of sources) {
260
+ if (typeof source !== 'object' || source === null) continue
261
+ if (lodashEs.isArray(target) && lodashEs.isArray(source)) {
262
+ const set = /* @__PURE__ */ new Set([...target, ...source])
263
+ return [...set]
264
+ } else if (
265
+ lodashEs.isPlainObject(target) &&
266
+ lodashEs.isPlainObject(source)
267
+ ) {
268
+ for (const key in source) {
269
+ if (
270
+ key in target &&
271
+ typeof target[key] === 'object' &&
272
+ typeof source[key] === 'object'
273
+ ) {
274
+ target[key] = deepMerge(target[key], source[key])
275
+ } else {
276
+ target[key] = source[key] || target[key]
277
+ }
278
+ }
279
+ }
280
+ }
281
+ return target
282
+ }
283
+
284
+ exports.builder = builder
285
+ exports.builderWithWatch = builderWithWatch
286
+ exports.defineMiniRouter = defineMiniRouter
287
+ exports.defineMiniTabbar = defineMiniTabbar