@modern-js/server 2.0.0-beta.0 → 2.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/dist/js/modern/dev-tools/dev-middleware/dev-server-plugin.js +4 -9
  3. package/dist/js/modern/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +2 -5
  4. package/dist/js/modern/dev-tools/dev-middleware/hmr-client/index.js +43 -50
  5. package/dist/js/modern/dev-tools/dev-middleware/index.js +14 -32
  6. package/dist/js/modern/dev-tools/dev-middleware/socket-server.js +18 -43
  7. package/dist/js/modern/dev-tools/https/index.js +0 -2
  8. package/dist/js/modern/dev-tools/mock/getMockData.js +4 -23
  9. package/dist/js/modern/dev-tools/mock/index.js +0 -8
  10. package/dist/js/modern/dev-tools/register/index.js +2 -18
  11. package/dist/js/modern/dev-tools/watcher/dependency-tree.js +5 -15
  12. package/dist/js/modern/dev-tools/watcher/index.js +0 -18
  13. package/dist/js/modern/dev-tools/watcher/stats-cache.js +0 -16
  14. package/dist/js/modern/index.js +0 -1
  15. package/dist/js/modern/server/dev-server.js +36 -56
  16. package/dist/js/modern/server/index.js +0 -4
  17. package/dist/js/node/constants.js +0 -3
  18. package/dist/js/node/dev-tools/dev-middleware/dev-server-plugin.js +4 -11
  19. package/dist/js/node/dev-tools/dev-middleware/hmr-client/createSocketUrl.js +2 -8
  20. package/dist/js/node/dev-tools/dev-middleware/hmr-client/index.js +41 -53
  21. package/dist/js/node/dev-tools/dev-middleware/index.js +14 -38
  22. package/dist/js/node/dev-tools/dev-middleware/socket-server.js +18 -48
  23. package/dist/js/node/dev-tools/https/index.js +0 -7
  24. package/dist/js/node/dev-tools/mock/getMockData.js +4 -29
  25. package/dist/js/node/dev-tools/mock/index.js +0 -17
  26. package/dist/js/node/dev-tools/register/index.js +2 -27
  27. package/dist/js/node/dev-tools/watcher/dependency-tree.js +5 -19
  28. package/dist/js/node/dev-tools/watcher/index.js +0 -32
  29. package/dist/js/node/dev-tools/watcher/stats-cache.js +0 -23
  30. package/dist/js/node/index.js +0 -4
  31. package/dist/js/node/server/dev-server.js +36 -75
  32. package/dist/js/node/server/index.js +0 -7
  33. package/dist/types/dev-tools/mock/getMockData.d.ts +0 -2
  34. package/dist/types/dev-tools/watcher/dependency-tree.d.ts +0 -2
  35. package/dist/types/index.d.ts +0 -2
  36. package/package.json +11 -11
@@ -1,11 +1,9 @@
1
1
  import * as devcert from 'devcert';
2
2
  export const genHttpsOptions = async userOptions => {
3
3
  const httpsOptions = typeof userOptions === 'boolean' ? {} : userOptions;
4
-
5
4
  if (!httpsOptions.key || !httpsOptions.cert) {
6
5
  const selfsign = await devcert.certificateFor(['localhost']);
7
6
  return selfsign;
8
7
  }
9
-
10
8
  return httpsOptions;
11
9
  };
@@ -1,16 +1,12 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import { compatRequire } from '@modern-js/utils';
8
5
  import { match } from 'path-to-regexp';
9
6
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
10
- const VALID_METHODS = ['get', 'post', 'put', 'delete', 'patch']; // eslint-disable-next-line @typescript-eslint/no-unused-vars
11
-
7
+ const VALID_METHODS = ['get', 'post', 'put', 'delete', 'patch'];
8
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
12
9
  const BODY_PARSED_METHODS = ['post', 'put', 'delete', 'patch'];
13
-
14
10
  const createFunctionDataHandler = (method, handler) => async (context, next) => {
15
11
  const {
16
12
  req,
@@ -18,7 +14,6 @@ const createFunctionDataHandler = (method, handler) => async (context, next) =>
18
14
  } = context;
19
15
  return handler(req, res, next);
20
16
  };
21
-
22
17
  const createStaticDataHandler = (method, handler) => context => {
23
18
  const {
24
19
  res
@@ -26,19 +21,14 @@ const createStaticDataHandler = (method, handler) => context => {
26
21
  res.setHeader('Content-Type', 'application/json');
27
22
  res.end(JSON.stringify(handler));
28
23
  };
29
-
30
24
  const allowTypes = ['object', 'function'];
31
-
32
25
  const normalizeConfig = mockConfig => Object.keys(mockConfig).reduce((acc, key) => {
33
26
  const handler = mockConfig[key];
34
27
  const type = typeof handler;
35
-
36
28
  if (!allowTypes.includes(type)) {
37
29
  throw new Error(`mock value of ${key} should be object or function, but got ${type}`);
38
30
  }
39
-
40
31
  const meta = parseKey(key);
41
-
42
32
  if (type === 'object') {
43
33
  acc.push(_objectSpread(_objectSpread({}, meta), {}, {
44
34
  handler: createStaticDataHandler(meta.method, handler)
@@ -48,38 +38,31 @@ const normalizeConfig = mockConfig => Object.keys(mockConfig).reduce((acc, key)
48
38
  handler: createFunctionDataHandler(meta.method, handler)
49
39
  }));
50
40
  }
51
-
52
41
  return acc;
53
42
  }, []);
54
-
55
43
  const _blank = ' ';
56
-
57
44
  const parseKey = key => {
58
45
  // 'Method /pathname' | '/pathname'
59
46
  const splitted = key.split(_blank).filter(Boolean);
60
-
61
47
  if (splitted.length > 1) {
62
48
  const [method, pathname] = splitted;
63
49
  return {
64
50
  method: method.toLowerCase(),
65
51
  path: pathname
66
52
  };
67
- } // default return get method
68
-
53
+ }
69
54
 
55
+ // default return get method
70
56
  return {
71
57
  method: 'get',
72
58
  path: key
73
59
  };
74
60
  };
75
-
76
61
  export default (filepath => {
77
62
  const mockModule = compatRequire(filepath);
78
-
79
63
  if (!mockModule) {
80
64
  throw new Error(`Mock file ${filepath} parsed failed!`);
81
65
  }
82
-
83
66
  const data = normalizeConfig(mockModule);
84
67
  return data;
85
68
  });
@@ -93,14 +76,12 @@ export const getMatched = (context, mockApiList) => {
93
76
  method,
94
77
  path: pathname
95
78
  } = mockApi;
96
-
97
79
  if (method.toLowerCase() === targetMethod.toLowerCase()) {
98
80
  return match(pathname, {
99
81
  encode: encodeURI,
100
82
  decode: decodeURIComponent
101
83
  })(targetPathname);
102
84
  }
103
-
104
85
  return false;
105
86
  });
106
87
  return matched;
@@ -7,36 +7,28 @@ export const createMockHandler = ({
7
7
  }) => {
8
8
  const exts = ['.ts', '.js'];
9
9
  let filepath = '';
10
-
11
10
  for (const ext of exts) {
12
11
  const maybeMatch = path.join(pwd, `${AGGRED_DIR.mock}/index${ext}`);
13
-
14
12
  if (fs.existsSync(maybeMatch)) {
15
13
  filepath = maybeMatch;
16
14
  break;
17
15
  }
18
16
  }
19
-
20
17
  if (!filepath) {
21
18
  return null;
22
19
  }
23
-
24
20
  const apiList = getMockData(filepath);
25
-
26
21
  if (!apiList || apiList.length === 0) {
27
22
  return null;
28
23
  }
29
-
30
24
  return async (context, next) => {
31
25
  const {
32
26
  res
33
27
  } = context;
34
28
  const matched = getMatched(context, apiList);
35
-
36
29
  if (!matched) {
37
30
  return next();
38
31
  }
39
-
40
32
  res.setHeader('Access-Control-Allow-Origin', '*');
41
33
  return matched.handler(context, next);
42
34
  };
@@ -1,27 +1,21 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import path from 'path';
8
5
  import { resolveBabelConfig } from '@modern-js/server-utils';
9
6
  import { fs, getAliasConfig, createDebugger } from '@modern-js/utils';
10
7
  const debug = createDebugger('server');
11
-
12
8
  const checkDep = (depName, paths) => {
13
9
  let packagePath = '';
14
-
15
10
  try {
16
11
  packagePath = require.resolve(depName, {
17
12
  paths
18
13
  });
19
14
  } catch (error) {}
20
-
21
15
  return Boolean(packagePath);
22
16
  };
23
-
24
- export const enableRegister = (projectRoot, config // eslint-disable-next-line consistent-return
17
+ export const enableRegister = (projectRoot, config
18
+ // eslint-disable-next-line consistent-return
25
19
  ) => {
26
20
  const registerDirs = ['./api', './server', './config/mock', './shared'];
27
21
  const TS_CONFIG_FILENAME = `tsconfig.json`;
@@ -29,17 +23,12 @@ export const enableRegister = (projectRoot, config // eslint-disable-next-line c
29
23
  const isTsProject = fs.existsSync(tsconfigPath);
30
24
  const existTsNode = checkDep('ts-node', [projectRoot]);
31
25
  const existTsConfigPaths = checkDep('tsconfig-paths', [projectRoot]);
32
-
33
26
  if (isTsProject && existTsNode && existTsConfigPaths) {
34
27
  var _config$output;
35
-
36
28
  debug('use ts-node');
37
29
  const distPath = (config === null || config === void 0 ? void 0 : (_config$output = config.output) === null || _config$output === void 0 ? void 0 : _config$output.path) || 'dist';
38
-
39
30
  const tsNode = require('ts-node');
40
-
41
31
  const tsConfigPaths = require('tsconfig-paths');
42
-
43
32
  const {
44
33
  alias
45
34
  } = config.source;
@@ -53,15 +42,12 @@ export const enableRegister = (projectRoot, config // eslint-disable-next-line c
53
42
  } = aliasConfig;
54
43
  const tsPaths = Object.keys(paths).reduce((o, key) => {
55
44
  let tsPath = paths[key];
56
-
57
45
  if (typeof tsPath === 'string' && path.isAbsolute(tsPath)) {
58
46
  tsPath = path.relative(absoluteBaseUrl, tsPath);
59
47
  }
60
-
61
48
  if (typeof tsPath === 'string') {
62
49
  tsPath = [tsPath];
63
50
  }
64
-
65
51
  return _objectSpread(_objectSpread({}, o), {}, {
66
52
  [`${key}`]: tsPath
67
53
  });
@@ -79,7 +65,6 @@ export const enableRegister = (projectRoot, config // eslint-disable-next-line c
79
65
  });
80
66
  } else {
81
67
  var _config$tools, _config$server;
82
-
83
68
  debug('use @babel/register');
84
69
  const babelConfig = resolveBabelConfig(projectRoot, _objectSpread(_objectSpread({}, config.source), {}, {
85
70
  babelConfig: (_config$tools = config.tools) === null || _config$tools === void 0 ? void 0 : _config$tools.babel,
@@ -98,7 +83,6 @@ export const enableRegister = (projectRoot, config // eslint-disable-next-line c
98
83
  if (filePath.includes(`node_modules${path.sep}.modern-js`)) {
99
84
  return true;
100
85
  }
101
-
102
86
  return registerDirs.some(registerDir => filePath.startsWith(path.join(projectRoot, registerDir)));
103
87
  }],
104
88
  extensions: ['.js', '.ts'],
@@ -1,8 +1,6 @@
1
1
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2
-
3
2
  import minimatch from 'minimatch';
4
3
  export const defaultIgnores = ['**/bower_components/**', '**/coverage/**', '**/node_modules/**', '**/.*/**', '**/*.d.ts', '**/*.log'];
5
-
6
4
  /**
7
5
  * `require.cache` already is a dependency tree, however require cache's
8
6
  * `module.parent` is the module that first required. so we have to implement
@@ -11,26 +9,23 @@ export const defaultIgnores = ['**/bower_components/**', '**/coverage/**', '**/n
11
9
  export class DependencyTree {
12
10
  constructor() {
13
11
  _defineProperty(this, "tree", void 0);
14
-
15
12
  _defineProperty(this, "ignore", void 0);
16
-
17
13
  this.tree = new Map();
18
14
  this.ignore = [...defaultIgnores];
19
15
  }
20
-
21
16
  getNode(path) {
22
17
  return this.tree.get(path);
23
18
  }
19
+
24
20
  /**
25
21
  * update dependency tree
26
22
  *
27
23
  * @param cache
28
24
  */
29
-
30
-
31
25
  update(cache) {
32
- this.tree.clear(); // insert all module that not ignored
26
+ this.tree.clear();
33
27
 
28
+ // insert all module that not ignored
34
29
  Object.keys(cache).forEach(path => {
35
30
  if (!this.shouldIgnore(path)) {
36
31
  const module = cache[path];
@@ -40,8 +35,9 @@ export class DependencyTree {
40
35
  children: new Set()
41
36
  });
42
37
  }
43
- }); // update treeNode parent and children
38
+ });
44
39
 
40
+ // update treeNode parent and children
45
41
  for (const treeNode of this.tree.values()) {
46
42
  const {
47
43
  parent
@@ -49,19 +45,15 @@ export class DependencyTree {
49
45
  const {
50
46
  children
51
47
  } = treeNode.module;
52
-
53
48
  if (parent && !this.shouldIgnore(parent.filename)) {
54
49
  const parentTreeNode = this.tree.get(parent.filename);
55
-
56
50
  if (parentTreeNode) {
57
51
  treeNode.parent.add(parentTreeNode);
58
52
  }
59
53
  }
60
-
61
54
  children.forEach(child => {
62
55
  if (!this.shouldIgnore(child.filename)) {
63
56
  const childTreeNode = this.tree.get(child.filename);
64
-
65
57
  if (childTreeNode) {
66
58
  treeNode.children.add(childTreeNode);
67
59
  childTreeNode.parent.add(treeNode);
@@ -70,9 +62,7 @@ export class DependencyTree {
70
62
  });
71
63
  }
72
64
  }
73
-
74
65
  shouldIgnore(path) {
75
66
  return !path || Boolean(this.ignore.find(rule => minimatch.match([path], rule).length > 0));
76
67
  }
77
-
78
68
  }
@@ -1,9 +1,6 @@
1
1
  function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
-
3
2
  function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
-
5
3
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
6
-
7
4
  import path from 'path';
8
5
  import { fs, chokidar } from '@modern-js/utils';
9
6
  import { DependencyTree } from "./dependency-tree";
@@ -25,29 +22,23 @@ export const getWatchedFiles = watcher => {
25
22
  };
26
23
  export const mergeWatchOptions = options => {
27
24
  const watchOptions = _objectSpread({}, options);
28
-
29
25
  if (watchOptions) {
30
26
  const {
31
27
  ignored
32
28
  } = watchOptions;
33
29
  const finalIgnored = ignored ? [defaultWatchOptions.ignored, ...(Array.isArray(ignored) ? ignored : [ignored])] : ignored;
34
-
35
30
  if (finalIgnored) {
36
31
  watchOptions.ignored = finalIgnored;
37
32
  }
38
33
  }
39
-
40
34
  const finalWatchOptions = _objectSpread(_objectSpread({}, defaultWatchOptions), watchOptions);
41
-
42
35
  return finalWatchOptions;
43
36
  };
44
37
  export default class Watcher {
45
38
  constructor() {
46
39
  _defineProperty(this, "dependencyTree", null);
47
-
48
40
  _defineProperty(this, "watcher", void 0);
49
41
  }
50
-
51
42
  listen(files, options, callback) {
52
43
  const watched = files.filter(Boolean);
53
44
  const filenames = watched.map(filename => filename.replace(/\\/g, '/'));
@@ -74,33 +65,24 @@ export default class Watcher {
74
65
  });
75
66
  this.watcher = watcher;
76
67
  }
77
-
78
68
  createDepTree() {
79
69
  this.dependencyTree = new DependencyTree();
80
70
  }
81
-
82
71
  updateDepTree() {
83
72
  var _this$dependencyTree;
84
-
85
73
  (_this$dependencyTree = this.dependencyTree) === null || _this$dependencyTree === void 0 ? void 0 : _this$dependencyTree.update(require.cache);
86
74
  }
87
-
88
75
  cleanDepCache(filepath) {
89
76
  var _this$dependencyTree2;
90
-
91
77
  const node = (_this$dependencyTree2 = this.dependencyTree) === null || _this$dependencyTree2 === void 0 ? void 0 : _this$dependencyTree2.getNode(filepath);
92
-
93
78
  if (node && require.cache[filepath]) {
94
79
  delete require.cache[filepath];
95
-
96
80
  for (const parentNode of node.parent.values()) {
97
81
  this.cleanDepCache(parentNode.module.filename);
98
82
  }
99
83
  }
100
84
  }
101
-
102
85
  close() {
103
86
  return this.watcher.close();
104
87
  }
105
-
106
88
  }
@@ -1,24 +1,19 @@
1
1
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
2
-
3
2
  import fs from 'fs';
4
3
  import crypto from 'crypto';
5
4
  export class StatsCache {
6
5
  constructor() {
7
6
  _defineProperty(this, "cachedHash", {});
8
-
9
7
  _defineProperty(this, "cachedSize", {});
10
8
  }
11
-
12
9
  add(files) {
13
10
  const {
14
11
  cachedHash,
15
12
  cachedSize
16
13
  } = this;
17
-
18
14
  for (const filename of files) {
19
15
  if (fs.existsSync(filename)) {
20
16
  const stats = fs.statSync(filename);
21
-
22
17
  if (stats.isFile() && !cachedHash[filename]) {
23
18
  cachedHash[filename] = this.hash(stats, filename);
24
19
  cachedSize[filename] = stats.size;
@@ -26,30 +21,25 @@ export class StatsCache {
26
21
  }
27
22
  }
28
23
  }
29
-
30
24
  refresh(filename) {
31
25
  const {
32
26
  cachedHash,
33
27
  cachedSize
34
28
  } = this;
35
-
36
29
  if (fs.existsSync(filename)) {
37
30
  const stats = fs.statSync(filename);
38
-
39
31
  if (stats.isFile()) {
40
32
  cachedHash[filename] = this.hash(stats, filename);
41
33
  cachedSize[filename] = stats.size;
42
34
  }
43
35
  }
44
36
  }
45
-
46
37
  del(filename) {
47
38
  if (this.cachedHash[filename]) {
48
39
  delete this.cachedHash[filename];
49
40
  delete this.cachedSize[filename];
50
41
  }
51
42
  }
52
-
53
43
  isDiff(filename) {
54
44
  const {
55
45
  cachedHash,
@@ -58,24 +48,18 @@ export class StatsCache {
58
48
  const stats = fs.statSync(filename);
59
49
  const hash = cachedHash[filename];
60
50
  const size = cachedSize[filename];
61
-
62
51
  if (stats.size !== size) {
63
52
  return true;
64
53
  }
65
-
66
54
  if (this.hash(stats, filename) !== hash) {
67
55
  return true;
68
56
  }
69
-
70
57
  return false;
71
58
  }
72
-
73
59
  has(filename) {
74
60
  return Boolean(this.cachedHash[filename]);
75
61
  }
76
-
77
62
  hash(stats, filename) {
78
63
  return crypto.createHash('md5').update(fs.readFileSync(filename)).digest('hex');
79
64
  }
80
-
81
65
  }
@@ -4,7 +4,6 @@ export default (options => {
4
4
  if (options == null) {
5
5
  throw new Error('can not start mserver without options');
6
6
  }
7
-
8
7
  const server = new Server(options);
9
8
  return server.init();
10
9
  });