@umijs/plugins 4.0.0-rc.9 → 4.0.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/request.js CHANGED
@@ -7,7 +7,12 @@ exports.default = (api) => {
7
7
  key: 'request',
8
8
  config: {
9
9
  schema: (joi) => {
10
- return joi.object();
10
+ return joi.object({
11
+ dataField: joi
12
+ .string()
13
+ .pattern(/^[a-zA-Z]*$/)
14
+ .allow(''),
15
+ });
11
16
  },
12
17
  },
13
18
  enableBy: api.EnableBy.config,
@@ -20,7 +25,6 @@ import axios, {
20
25
  type AxiosResponse,
21
26
  } from '{{{axiosPath}}}';
22
27
  import useUmiRequest, { UseRequestProvider } from '{{{umiRequestPath}}}';
23
- import { message, notification } from '{{{antdPkg}}}';
24
28
  import { ApplyPluginsType } from 'umi';
25
29
  import { getPluginManager } from '../core/plugin';
26
30
 
@@ -81,7 +85,7 @@ function useRequest<Item = any, U extends Item = any>(
81
85
  ): PaginatedResult<Item>;
82
86
  function useRequest(service: any, options: any = {}) {
83
87
  return useUmiRequest(service, {
84
- formatResult: result => result?.data,
88
+ formatResult: {{{formatResult}}},
85
89
  requestMethod: (requestOptions: any) => {
86
90
  if (typeof requestOptions === 'string') {
87
91
  return request(requestOptions);
@@ -96,114 +100,49 @@ function useRequest(service: any, options: any = {}) {
96
100
  });
97
101
  }
98
102
 
99
- export interface RequestConfig extends AxiosRequestConfig {
100
- errorConfig?: {
101
- errorPage?: string;
102
- adaptor?: IAdaptor; // adaptor 用以用户将不满足接口的后端数据修改成 errorInfo
103
- errorHandler?: IErrorHandler;
104
- defaultNoneResponseErrorMessage?: string;
105
- defaultRequestErrorMessage?: string;
106
- };
107
- formatResultAdaptor?: IFormatResultAdaptor;
108
- }
109
-
110
- export enum ErrorShowType {
111
- SILENT = 0,
112
- WARN_MESSAGE = 1,
113
- ERROR_MESSAGE = 2,
114
- NOTIFICATION = 3,
115
- REDIRECT = 9,
116
- }
117
-
118
- export interface IErrorInfo {
119
- success: boolean;
120
- data?: any;
121
- errorCode?: string;
122
- errorMessage?: string;
123
- showType?: ErrorShowType;
124
- traceId?: string;
125
- host?: string;
103
+ // request 方法 opts 参数的接口
104
+ interface IRequestOptions extends AxiosRequestConfig {
105
+ skipErrorHandler?: boolean;
106
+ requestInterceptors?: IRequestInterceptorTuple[];
107
+ responseInterceptors?: IResponseInterceptorTuple[];
126
108
  [key: string]: any;
127
109
  }
128
- // resData 其实就是 response.data, response 则是 axios 的响应对象
129
- interface IAdaptor {
130
- (resData: any, response: AxiosResponse): IErrorInfo;
110
+
111
+ interface IRequestOptionsWithResponse extends IRequestOptions {
112
+ getResponse: true;
131
113
  }
132
114
 
133
- export interface RequestError extends Error {
134
- data?: any;
135
- info?: IErrorInfo;
115
+ interface IRequestOptionsWithoutResponse extends IRequestOptions{
116
+ getResponse: false;
136
117
  }
137
118
 
138
- interface IRequest {
139
- (
140
- url: string,
141
- opts: AxiosRequestConfig & { skipErrorHandler?: boolean },
142
- ): Promise<AxiosResponse<any, any>>;
119
+ interface IRequest{
120
+ <T = any>(url: string, opts: IRequestOptionsWithResponse): Promise<AxiosResponse<T>>;
121
+ <T = any>(url: string, opts: IRequestOptionsWithoutResponse): Promise<T>;
122
+ <T = any>(url: string, opts: IRequestOptions): Promise<T>; // getResponse 默认是 false, 因此不提供该参数时,只返回 data
123
+ <T = any>(url: string): Promise<T>; // 不提供 opts 时,默认使用 'GET' method,并且默认返回 data
143
124
  }
144
125
 
145
126
  interface IErrorHandler {
146
- (error: RequestError, opts: AxiosRequestConfig & { skipErrorHandler?: boolean }, config: RequestConfig): void;
127
+ (error: RequestError, opts: IRequestOptions): void;
147
128
  }
129
+ type IRequestInterceptorAxios = (config: RequestOptions) => RequestOptions;
130
+ type IRequestInterceptorUmiRequest = (url: string, config : RequestOptions) => { url: string, options: RequestOptions };
131
+ type IRequestInterceptor = IRequestInterceptorAxios;
132
+ type IErrorInterceptor = (error: Error) => Promise<Error>;
133
+ type IResponseInterceptor = <T = any>(response : AxiosResponse<T>) => AxiosResponse<T> ;
134
+ type IRequestInterceptorTuple = [IRequestInterceptor , IErrorInterceptor] | [ IRequestInterceptor ] | IRequestInterceptor
135
+ type IResponseInterceptorTuple = [IResponseInterceptor, IErrorInterceptor] | [IResponseInterceptor] | IResponseInterceptor
148
136
 
149
- interface IFormatResultAdaptor {
150
- (res: AxiosResponse): any;
137
+ export interface RequestConfig extends AxiosRequestConfig {
138
+ errorConfig?: {
139
+ errorHandler?: IErrorHandler;
140
+ errorThrower?: <T = any>( res: T ) => void
141
+ };
142
+ requestInterceptors?: IRequestInterceptorTuple[];
143
+ responseInterceptors?: IResponseInterceptorTuple[];
151
144
  }
152
145
 
153
- const defaultErrorHandler: IErrorHandler = (error, opts, config) => {
154
- if (opts?.skipErrorHandler) throw error;
155
- const { errorConfig } = config;
156
- if (error.response) {
157
- // 请求成功发出且服务器也响应了状态码,但状态代码超出了 2xx 的范围 或者 成功响应,success字段为false 由我们抛出的错误
158
- let errorInfo: IErrorInfo | undefined;
159
- // 不是我们的错误
160
- if(error.name === 'ResponseError'){
161
- const adaptor: IAdaptor =
162
- errorConfig?.adaptor || ((errorData) => errorData);
163
- errorInfo = adaptor(error.response.data, error.response);
164
- error.info = errorInfo;
165
- error.data = error.response.data;
166
- }
167
- errorInfo = error.info;
168
- if (errorInfo) {
169
- const { errorMessage, errorCode } = errorInfo;
170
- switch (errorInfo.showType) {
171
- case ErrorShowType.SILENT:
172
- // do nothong
173
- break;
174
- case ErrorShowType.WARN_MESSAGE:
175
- message.warn(errorMessage);
176
- break;
177
- case ErrorShowType.ERROR_MESSAGE:
178
- message.error(errorMessage);
179
- break;
180
- case ErrorShowType.NOTIFICATION:
181
- notification.open({ description: errorMessage, message: errorCode });
182
- break;
183
- case ErrorShowType.REDIRECT:
184
- // TODO: redirect
185
- break;
186
- default:
187
- message.error(errorMessage);
188
- }
189
- }
190
- } else if (error.request) {
191
- // 请求已经成功发起,但没有收到响应
192
- // \`error.request\` 在浏览器中是 XMLHttpRequest 的实例,
193
- // 而在node.js中是 http.ClientRequest 的实例
194
- message.error(
195
- errorConfig?.defaultNoneResponseErrorMessage ||
196
- 'None response! Please retry.',
197
- );
198
- } else {
199
- // 发送请求时出了点问题
200
- message.error(
201
- errorConfig?.defaultRequestErrorMessage || 'Request error, please retry.',
202
- );
203
- }
204
- throw error;
205
- };
206
-
207
146
  let requestInstance: AxiosInstance;
208
147
  let config: RequestConfig;
209
148
  const getConfig = (): RequestConfig => {
@@ -215,51 +154,112 @@ const getConfig = (): RequestConfig => {
215
154
  });
216
155
  return config;
217
156
  };
157
+
218
158
  const getRequestInstance = (): AxiosInstance => {
219
159
  if (requestInstance) return requestInstance;
220
160
  const config = getConfig();
221
161
  requestInstance = axios.create(config);
222
162
 
163
+ config?.requestInterceptors?.forEach((interceptor) => {
164
+ if(interceptor instanceof Array){
165
+ requestInstance.interceptors.request.use((config) => {
166
+ const { url } = config;
167
+ if(interceptor[0].length === 2){
168
+ const { url: newUrl, options } = interceptor[0](url, config);
169
+ return { ...options, url: newUrl };
170
+ }
171
+ return interceptor[0](config);
172
+ }, interceptor[1]);
173
+ } else {
174
+ requestInstance.interceptors.request.use((config) => {
175
+ const { url } = config;
176
+ if(interceptor.length === 2){
177
+ const { url: newUrl, options } = interceptor(url, config);
178
+ return { ...options, url: newUrl };
179
+ }
180
+ return interceptor(config);
181
+ })
182
+ }
183
+ });
184
+
185
+ config?.responseInterceptors?.forEach((interceptor) => {
186
+ interceptor instanceof Array ?
187
+ requestInstance.interceptors.response.use(interceptor[0], interceptor[1]):
188
+ requestInstance.interceptors.response.use(interceptor);
189
+ });
190
+
223
191
  // 当响应的数据 success 是 false 的时候,抛出 error 以供 errorHandler 处理。
224
- requestInstance.interceptors.response.use((response)=>{
225
- const {data} = response;
226
- const adaptor = config?.errorConfig?.adaptor || ((resData) => resData);
227
- const errorInfo = adaptor(data,response);
228
- if(errorInfo.success === false){
229
- const error: RequestError = new Error(errorInfo.errorMessage);
230
- error.name = 'BizError';
231
- error.data = data;
232
- error.info = errorInfo;
233
- error.response = response;
234
- throw error;
192
+ requestInstance.interceptors.response.use((response) => {
193
+ const { data } = response;
194
+ if(data?.success === false && config?.errorConfig?.errorThrower){
195
+ config.errorConfig.errorThrower(data);
235
196
  }
236
197
  return response;
237
198
  })
238
199
  return requestInstance;
239
200
  };
240
201
 
241
- const request: IRequest = (url, opts) => {
202
+ const request: IRequest = (url: string, opts: any = { method: 'GET' }) => {
242
203
  const requestInstance = getRequestInstance();
243
204
  const config = getConfig();
244
- return new Promise((resolve, reject) => {
205
+ const { getResponse = false, requestInterceptors, responseInterceptors } = opts;
206
+ const requestInterceptorsToEject = requestInterceptors?.map((interceptor) => {
207
+ if(interceptor instanceof Array){
208
+ return requestInstance.interceptors.request.use((config) => {
209
+ const { url } = config;
210
+ if(interceptor[0].length === 2){
211
+ const { url: newUrl, options } = interceptor[0](url, config);
212
+ return { ...options, url: newUrl };
213
+ }
214
+ return interceptor[0](config);
215
+ }, interceptor[1]);
216
+ } else {
217
+ return requestInstance.interceptors.request.use((config) => {
218
+ const { url } = config;
219
+ if(interceptor.length === 2){
220
+ const { url: newUrl, options } = interceptor(url, config);
221
+ return { ...options, url: newUrl };
222
+ }
223
+ return interceptor(config);
224
+ })
225
+ }
226
+ });
227
+ const responseInterceptorsToEject = responseInterceptors?.map((interceptor) => {
228
+ return interceptor instanceof Array ?
229
+ requestInstance.interceptors.response.use(interceptor[0], interceptor[1]):
230
+ requestInstance.interceptors.response.use(interceptor);
231
+ });
232
+ return new Promise((resolve, reject)=>{
245
233
  requestInstance
246
- .request({ ...opts, url })
247
- .then((res) => {
248
- const formatResultAdaptor =
249
- config?.formatResultAdaptor || ((res) => res.data);
250
- resolve(formatResultAdaptor(res));
234
+ .request({...opts, url})
235
+ .then((res)=>{
236
+ requestInterceptorsToEject?.forEach((interceptor) => {
237
+ requestInstance.interceptors.request.eject(interceptor);
238
+ });
239
+ responseInterceptorsToEject?.forEach((interceptor) => {
240
+ requestInstance.interceptors.response.eject(interceptor);
241
+ });
242
+ resolve(getResponse ? res : res.data);
251
243
  })
252
- .catch((error) => {
244
+ .catch((error)=>{
245
+ requestInterceptorsToEject?.forEach((interceptor) => {
246
+ requestInstance.interceptors.request.eject(interceptor);
247
+ });
248
+ responseInterceptorsToEject?.forEach((interceptor) => {
249
+ requestInstance.interceptors.response.eject(interceptor);
250
+ });
253
251
  try {
254
252
  const handler =
255
- config.errorConfig?.errorHandler || defaultErrorHandler;
256
- handler(error, opts, config);
253
+ config?.errorConfig?.errorHandler;
254
+ if(handler)
255
+ handler(error, opts, config);
257
256
  } catch (e) {
258
257
  reject(e);
259
258
  }
260
- });
261
- });
262
- };
259
+ reject(error);
260
+ })
261
+ })
262
+ }
263
263
 
264
264
  export {
265
265
  useRequest,
@@ -272,6 +272,9 @@ export type {
272
272
  AxiosInstance,
273
273
  AxiosRequestConfig,
274
274
  AxiosResponse,
275
+ IResponseInterceptor as ResponseInterceptor,
276
+ IRequestOptions as RequestOptions,
277
+ IRequest as Request,
275
278
  };
276
279
 
277
280
  `;
@@ -279,18 +282,29 @@ export type {
279
282
  var _a;
280
283
  const umiRequestPath = (0, plugin_utils_1.winPath)((0, path_1.dirname)(require.resolve('@ahooksjs/use-request/package.json')));
281
284
  const axiosPath = (0, plugin_utils_1.winPath)((0, path_1.dirname)(require.resolve('axios/package.json')));
282
- const antdPkg = (0, plugin_utils_1.winPath)(
283
- // use path from antd plugin first
284
- ((_a = api.appData.antd) === null || _a === void 0 ? void 0 : _a.pkgPath) ||
285
- (0, path_1.dirname)(require.resolve('antd/package.json')));
285
+ let dataField = (_a = api.config.request) === null || _a === void 0 ? void 0 : _a.dataField;
286
+ if (dataField === undefined)
287
+ dataField = 'data';
288
+ const formatResult = dataField === '' ? `result => result` : `result => result?.${dataField}`;
286
289
  api.writeTmpFile({
287
290
  path: 'request.ts',
288
291
  content: plugin_utils_1.Mustache.render(requestTpl, {
289
292
  umiRequestPath,
290
293
  axiosPath,
291
- antdPkg,
294
+ formatResult,
292
295
  }),
293
296
  });
297
+ api.writeTmpFile({
298
+ path: 'types.d.ts',
299
+ content: `
300
+ export type {
301
+ RequestConfig,
302
+ AxiosInstance,
303
+ AxiosRequestConfig,
304
+ AxiosResponse,
305
+ ResponseInterceptor } from './request';
306
+ `,
307
+ });
294
308
  api.writeTmpFile({
295
309
  path: 'index.ts',
296
310
  content: `
@@ -18,18 +18,30 @@ exports.default = (api) => {
18
18
  const inputPath = (0, path_1.join)(api.cwd, 'tailwind.css');
19
19
  const generatedPath = (0, path_1.join)(api.paths.absTmpPath, outputPath);
20
20
  const binPath = (0, path_1.join)(api.cwd, 'node_modules/.bin/tailwind');
21
- /** 透过子进程建立 tailwindcss 服务,将生成的 css 写入 generatedPath */
22
- tailwind = (0, plugin_utils_1.crossSpawn)(`${binPath}`, [
23
- '-i',
24
- inputPath,
25
- '-o',
26
- generatedPath,
27
- api.env === 'development' ? '--watch' : '',
28
- ], {
29
- stdio: 'inherit',
30
- });
31
- tailwind.on('error', (m) => {
32
- api.logger.error('tailwindcss service encounter an error: ' + m);
21
+ return new Promise((resolve) => {
22
+ /** 透过子进程建立 tailwindcss 服务,将生成的 css 写入 generatedPath */
23
+ tailwind = (0, plugin_utils_1.crossSpawn)(`${binPath}`, [
24
+ '-i',
25
+ inputPath,
26
+ '-o',
27
+ generatedPath,
28
+ api.env === 'development' ? '--watch' : '',
29
+ ], {
30
+ stdio: 'inherit',
31
+ });
32
+ tailwind.on('error', (m) => {
33
+ api.logger.error('tailwindcss service encounter an error: ' + m);
34
+ });
35
+ if (api.env === 'production') {
36
+ tailwind.on('exit', () => {
37
+ api.logger.info('tailwindcss service exited');
38
+ resolve();
39
+ });
40
+ }
41
+ else {
42
+ api.logger.info('tailwindcss service started');
43
+ resolve();
44
+ }
33
45
  });
34
46
  });
35
47
  /** 将生成的 css 文件加入到 import 中 */
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.isNeedPolyfill = exports.exactLocalePaths = exports.getLocaleList = exports.getAntdLocale = exports.getMomentLocale = void 0;
13
4
  const fs_1 = require("fs");
@@ -55,7 +46,7 @@ const modulesHasLocale = (localePath) => {
55
46
  return false;
56
47
  }
57
48
  };
58
- const getLocaleList = (opts) => __awaiter(void 0, void 0, void 0, function* () {
49
+ const getLocaleList = async (opts) => {
59
50
  const { localeFolder, separator = '-', absSrcPath = '', absPagesPath = '', addAntdLocales, resolveKey = 'moment', } = opts;
60
51
  const localeFileMath = new RegExp(`^([a-z]{2})${separator}?([A-Z]{2})?\.(js|json|ts)$`);
61
52
  const localeFiles = plugin_utils_1.glob
@@ -80,11 +71,11 @@ const getLocaleList = (opts) => __awaiter(void 0, void 0, void 0, function* () {
80
71
  };
81
72
  });
82
73
  const groups = plugin_utils_1.lodash.groupBy(localeFiles, 'name');
83
- const promises = Object.keys(groups).map((name) => __awaiter(void 0, void 0, void 0, function* () {
74
+ const promises = Object.keys(groups).map(async (name) => {
84
75
  const [lang, country = ''] = name.split(separator);
85
76
  const { momentLocale } = (0, exports.getMomentLocale)(lang, country, resolveKey);
86
77
  const antdLocale = plugin_utils_1.lodash
87
- .uniq(yield addAntdLocales({ lang, country }))
78
+ .uniq(await addAntdLocales({ lang, country }))
88
79
  .filter((localePath) => modulesHasLocale(localePath));
89
80
  return {
90
81
  lang,
@@ -97,9 +88,9 @@ const getLocaleList = (opts) => __awaiter(void 0, void 0, void 0, function* () {
97
88
  paths: groups[name].map((item) => (0, plugin_utils_1.winPath)(item.path)),
98
89
  momentLocale,
99
90
  };
100
- }));
91
+ });
101
92
  return Promise.all(promises);
102
- });
93
+ };
103
94
  exports.getLocaleList = getLocaleList;
104
95
  const exactLocalePaths = (data) => {
105
96
  return plugin_utils_1.lodash.flatten(data.map((item) => item.paths));
@@ -7,12 +7,15 @@ interface IOpts {
7
7
  content: string;
8
8
  }) => Boolean;
9
9
  }
10
+ export declare function getNamespace(absFilePath: string, absSrcPath: string): string;
10
11
  export declare class Model {
11
12
  file: string;
12
13
  namespace: string;
13
14
  id: string;
14
15
  exportName: string;
15
- constructor(file: string, id: number);
16
+ deps: string[];
17
+ constructor(file: string, absSrcPath: string, sort: {} | undefined, id: number);
18
+ findDeps(sort: object): string[];
16
19
  }
17
20
  export declare class ModelUtils {
18
21
  api: IApi;
@@ -20,8 +23,10 @@ export declare class ModelUtils {
20
23
  count: number;
21
24
  constructor(api: IApi | null, opts: IOpts);
22
25
  getAllModels(opts: {
26
+ sort?: object;
23
27
  extraModels: string[];
24
28
  }): Model[];
29
+ getSortedNamespaces(models: Model[]): string[];
25
30
  getModels(opts: {
26
31
  base: string;
27
32
  pattern?: string;
@@ -26,16 +26,33 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
26
26
  return (mod && mod.__esModule) ? mod : { "default": mod };
27
27
  };
28
28
  Object.defineProperty(exports, "__esModule", { value: true });
29
- exports.ModelUtils = exports.Model = void 0;
29
+ exports.ModelUtils = exports.Model = exports.getNamespace = void 0;
30
30
  const parser = __importStar(require("@umijs/bundler-utils/compiled/babel/parser"));
31
31
  const traverse_1 = __importDefault(require("@umijs/bundler-utils/compiled/babel/traverse"));
32
+ const t = __importStar(require("@umijs/bundler-utils/compiled/babel/types"));
32
33
  const esbuild_1 = require("@umijs/bundler-utils/compiled/esbuild");
33
34
  const fs_1 = require("fs");
34
35
  const path_1 = require("path");
35
36
  const plugin_utils_1 = require("umi/plugin-utils");
36
37
  const astUtils_1 = require("./astUtils");
38
+ function getNamespace(absFilePath, absSrcPath) {
39
+ const relPath = (0, plugin_utils_1.winPath)((0, path_1.relative)((0, plugin_utils_1.winPath)(absSrcPath), (0, plugin_utils_1.winPath)(absFilePath)));
40
+ const parts = relPath.split('/');
41
+ const dirs = parts.slice(0, -1);
42
+ const file = parts[parts.length - 1];
43
+ // src/pages/foo/models/bar > foo/bar
44
+ const validDirs = dirs.filter((dir) => !['src', 'pages', 'models'].includes(dir));
45
+ let normalizedFile = file;
46
+ normalizedFile = (0, path_1.basename)(file, (0, path_1.extname)(file));
47
+ // foo.model > foo
48
+ if (normalizedFile.endsWith('.model')) {
49
+ normalizedFile = normalizedFile.split('.').slice(0, -1).join('.');
50
+ }
51
+ return [...validDirs, normalizedFile].join('.');
52
+ }
53
+ exports.getNamespace = getNamespace;
37
54
  class Model {
38
- constructor(file, id) {
55
+ constructor(file, absSrcPath, sort, id) {
39
56
  let namespace;
40
57
  let exportName;
41
58
  const [_file, meta] = file.split('#');
@@ -46,8 +63,38 @@ class Model {
46
63
  }
47
64
  this.file = _file;
48
65
  this.id = `model_${id}`;
49
- this.namespace = namespace || (0, path_1.basename)(file, (0, path_1.extname)(file));
66
+ this.namespace = namespace || getNamespace(_file, absSrcPath);
50
67
  this.exportName = exportName || 'default';
68
+ this.deps = sort ? this.findDeps(sort) : [];
69
+ }
70
+ findDeps(sort) {
71
+ const content = (0, fs_1.readFileSync)(this.file, 'utf-8');
72
+ // transform with esbuild first
73
+ // to reduce unexpected ast problem
74
+ const loader = (0, path_1.extname)(this.file).slice(1);
75
+ const result = (0, esbuild_1.transformSync)(content, {
76
+ loader,
77
+ sourcemap: false,
78
+ minify: false,
79
+ });
80
+ // transform with babel
81
+ const deps = new Set();
82
+ const ast = parser.parse(result.code, {
83
+ sourceType: 'module',
84
+ sourceFilename: this.file,
85
+ plugins: [],
86
+ });
87
+ // TODO: use sort
88
+ sort;
89
+ (0, traverse_1.default)(ast, {
90
+ CallExpression: (path) => {
91
+ if (t.isIdentifier(path.node.callee, { name: 'useModel' }) &&
92
+ t.isStringLiteral(path.node.arguments[0])) {
93
+ deps.add(path.node.arguments[0].value);
94
+ }
95
+ },
96
+ });
97
+ return [...deps];
51
98
  }
52
99
  }
53
100
  exports.Model = Model;
@@ -61,7 +108,7 @@ class ModelUtils {
61
108
  getAllModels(opts) {
62
109
  // reset count
63
110
  this.count = 1;
64
- return [
111
+ const models = [
65
112
  ...this.getModels({
66
113
  base: (0, path_1.join)(this.api.paths.absSrcPath, 'models'),
67
114
  pattern: '**/*.{ts,tsx,js,jsx}',
@@ -76,8 +123,59 @@ class ModelUtils {
76
123
  }),
77
124
  ...opts.extraModels,
78
125
  ].map((file) => {
79
- return new Model(file, this.count++);
126
+ return new Model(file, this.api.paths.absSrcPath, opts.sort, this.count++);
127
+ });
128
+ // check duplicate
129
+ const namespaces = models.map((model) => model.namespace);
130
+ if (new Set(namespaces).size !== namespaces.length) {
131
+ throw new Error(`Duplicate namespace in models: ${namespaces.join(', ')}`);
132
+ }
133
+ // sort models by deps
134
+ if (opts.sort) {
135
+ const namespaces = this.getSortedNamespaces(models);
136
+ models.sort((a, b) => namespaces.indexOf(a.namespace) - namespaces.indexOf(b.namespace));
137
+ }
138
+ return models;
139
+ }
140
+ getSortedNamespaces(models) {
141
+ let final = [];
142
+ models.forEach((model, index) => {
143
+ const { deps, namespace } = model;
144
+ if (deps && deps.length) {
145
+ const itemGroup = [...deps, namespace];
146
+ const cannotUse = [namespace];
147
+ for (let i = 0; i <= index; i += 1) {
148
+ if (models[i].deps.filter((v) => cannotUse.includes(v)).length) {
149
+ if (!cannotUse.includes(models[i].namespace)) {
150
+ cannotUse.push(models[i].namespace);
151
+ i = -1;
152
+ }
153
+ }
154
+ }
155
+ const errorList = deps.filter((v) => cannotUse.includes(v));
156
+ if (errorList.length) {
157
+ throw Error(`Circular dependencies: ${namespace} can't use ${errorList.join(', ')}`);
158
+ }
159
+ const intersection = final.filter((v) => itemGroup.includes(v));
160
+ if (intersection.length) {
161
+ // first intersection
162
+ const finalIndex = final.indexOf(intersection[0]);
163
+ // replace with groupItem
164
+ final = final
165
+ .slice(0, finalIndex)
166
+ .concat(itemGroup)
167
+ .concat(final.slice(finalIndex + 1));
168
+ }
169
+ else {
170
+ final.push(...itemGroup);
171
+ }
172
+ }
173
+ if (!final.includes(namespace)) {
174
+ // first occurrence append to the end
175
+ final.push(namespace);
176
+ }
80
177
  });
178
+ return [...new Set(final)];
81
179
  }
82
180
  getModels(opts) {
83
181
  return plugin_utils_1.glob
@@ -130,11 +228,15 @@ class ModelUtils {
130
228
  const imports = [];
131
229
  const modelProps = [];
132
230
  models.forEach((model) => {
231
+ const fileWithoutExt = (0, plugin_utils_1.winPath)((0, path_1.format)({
232
+ dir: (0, path_1.dirname)(model.file),
233
+ base: (0, path_1.basename)(model.file, (0, path_1.extname)(model.file)),
234
+ }));
133
235
  if (model.exportName !== 'default') {
134
- imports.push(`import { ${model.exportName} as ${model.id} } from '${model.file}';`);
236
+ imports.push(`import { ${model.exportName} as ${model.id} } from '${fileWithoutExt}';`);
135
237
  }
136
238
  else {
137
- imports.push(`import ${model.id} from '${model.file}';`);
239
+ imports.push(`import ${model.id} from '${fileWithoutExt}';`);
138
240
  }
139
241
  modelProps.push(`${model.id}: { namespace: '${model.namespace}', model: ${model.id} },`);
140
242
  });
@@ -143,7 +245,7 @@ ${imports.join('\n')}
143
245
 
144
246
  export const models = {
145
247
  ${modelProps.join('\n')}
146
- }`;
248
+ } as const`;
147
249
  }
148
250
  }
149
251
  exports.ModelUtils = ModelUtils;