@modern-js/server 1.4.8 → 1.4.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.
package/.eslintrc.js ADDED
@@ -0,0 +1,8 @@
1
+ module.exports = {
2
+ root: true,
3
+ extends: ['@modern-js'],
4
+ parserOptions: {
5
+ tsconfigRootDir: __dirname,
6
+ project: ['./tsconfig.json'],
7
+ },
8
+ };
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # @modern-js/server
2
2
 
3
+ ## 1.4.10
4
+
5
+ ### Patch Changes
6
+
7
+ - 6cffe99d: chore:
8
+ remove react eslint rules for `modern-js` rule set.
9
+ add .eslintrc for each package to speed up linting
10
+ - 04ae5262: chore: bump @modern-js/utils to v1.4.1 in dependencies
11
+ - 60f7d8bf: feat: add tests dir to npmignore
12
+ - 28ac120a: fix: remove unused webpack/hot/dev-server entry
13
+ - Updated dependencies [b8599d09]
14
+ - Updated dependencies [6cffe99d]
15
+ - Updated dependencies [04ae5262]
16
+ - Updated dependencies [60f7d8bf]
17
+ - Updated dependencies [3bf4f8b0]
18
+ - @modern-js/utils@1.5.0
19
+ - @modern-js/bff-utils@1.2.3
20
+ - @modern-js/hmr-client@1.2.5
21
+ - @modern-js/prod-server@1.1.1
22
+ - @modern-js/server-utils@1.2.3
23
+
24
+ ## 1.4.9
25
+
26
+ ### Patch Changes
27
+
28
+ - bebb39b6: chore: improve devDependencies and peerDependencies
29
+ - Updated dependencies [bebb39b6]
30
+ - Updated dependencies [afc836f4]
31
+ - Updated dependencies [132f7b53]
32
+ - @modern-js/prod-server@1.0.6
33
+ - @modern-js/server-utils@1.2.2
34
+ - @modern-js/hmr-client@1.2.3
35
+ - @modern-js/utils@1.3.7
36
+
3
37
  ## 1.4.8
4
38
 
5
39
  ### Patch Changes
@@ -26,10 +26,7 @@ export default class DevServerPlugin {
26
26
  const path = `&path=${client.path}`;
27
27
  const port = `&port=${client.port}`;
28
28
  const clientEntry = `${require.resolve('@modern-js/hmr-client')}?${host}${path}${port}`;
29
-
30
- const hotEntry = require.resolve('webpack/hot/dev-server');
31
-
32
- const additionalEntries = [clientEntry, hotEntry]; // use a hook to add entries if available
29
+ const additionalEntries = [clientEntry]; // use a hook to add entries if available
33
30
 
34
31
  for (const additionalEntry of additionalEntries) {
35
32
  new EntryPlugin(compiler.context, additionalEntry, {
@@ -41,7 +38,7 @@ export default class DevServerPlugin {
41
38
  const compilerOptions = compiler.options;
42
39
  compilerOptions.plugins = compilerOptions.plugins || [];
43
40
 
44
- if (hotEntry && !compilerOptions.plugins.find(p => p.constructor === Webpack.HotModuleReplacementPlugin)) {
41
+ if (!compilerOptions.plugins.find(p => p.constructor === Webpack.HotModuleReplacementPlugin)) {
45
42
  // apply the HMR plugin, if it didn't exist before.
46
43
  const plugin = new Webpack.HotModuleReplacementPlugin();
47
44
  plugin.apply(compiler);
@@ -1,6 +1,5 @@
1
1
  import path from 'path';
2
- import { fs } from '@modern-js/utils';
3
- import chokidar from 'chokidar';
2
+ import { fs, chokidar } from '@modern-js/utils';
4
3
  import { DependencyTree } from "./dependency-tree";
5
4
  import { StatsCache } from "./stats-cache";
6
5
  export const getWatchedFiles = watcher => {
@@ -38,10 +38,7 @@ class DevServerPlugin {
38
38
  const path = `&path=${client.path}`;
39
39
  const port = `&port=${client.port}`;
40
40
  const clientEntry = `${require.resolve('@modern-js/hmr-client')}?${host}${path}${port}`;
41
-
42
- const hotEntry = require.resolve('webpack/hot/dev-server');
43
-
44
- const additionalEntries = [clientEntry, hotEntry]; // use a hook to add entries if available
41
+ const additionalEntries = [clientEntry]; // use a hook to add entries if available
45
42
 
46
43
  for (const additionalEntry of additionalEntries) {
47
44
  new EntryPlugin(compiler.context, additionalEntry, {
@@ -53,7 +50,7 @@ class DevServerPlugin {
53
50
  const compilerOptions = compiler.options;
54
51
  compilerOptions.plugins = compilerOptions.plugins || [];
55
52
 
56
- if (hotEntry && !compilerOptions.plugins.find(p => p.constructor === _webpack.default.HotModuleReplacementPlugin)) {
53
+ if (!compilerOptions.plugins.find(p => p.constructor === _webpack.default.HotModuleReplacementPlugin)) {
57
54
  // apply the HMR plugin, if it didn't exist before.
58
55
  const plugin = new _webpack.default.HotModuleReplacementPlugin();
59
56
  plugin.apply(compiler);
@@ -9,8 +9,6 @@ var _path = _interopRequireDefault(require("path"));
9
9
 
10
10
  var _utils = require("@modern-js/utils");
11
11
 
12
- var _chokidar = _interopRequireDefault(require("chokidar"));
13
-
14
12
  var _dependencyTree = require("./dependency-tree");
15
13
 
16
14
  var _statsCache = require("./stats-cache");
@@ -41,7 +39,7 @@ class Watcher {
41
39
  const filenames = watched.map(filename => filename.replace(/\\/g, '/'));
42
40
  const cache = new _statsCache.StatsCache();
43
41
 
44
- const watcher = _chokidar.default.watch(filenames, options);
42
+ const watcher = _utils.chokidar.watch(filenames, options);
45
43
 
46
44
  watcher.on('ready', () => {
47
45
  cache.add(getWatchedFiles(watcher));
@@ -1,5 +1,5 @@
1
- import chokidar, { FSWatcher, WatchOptions } from 'chokidar';
2
- export declare const getWatchedFiles: (watcher: chokidar.FSWatcher) => string[];
1
+ import { FSWatcher, WatchOptions } from '@modern-js/utils';
2
+ export declare const getWatchedFiles: (watcher: FSWatcher) => string[];
3
3
  export default class Watcher {
4
4
  private dependencyTree;
5
5
  private watcher;
package/jest.config.js CHANGED
@@ -2,7 +2,6 @@ const sharedConfig = require('@scripts/jest-config');
2
2
 
3
3
  /** @type {import('@jest/types').Config.InitialOptions} */
4
4
  module.exports = {
5
- // eslint-disable-next-line node/no-unsupported-features/es-syntax
6
5
  ...sharedConfig,
7
6
  testEnvironment: 'node',
8
7
  rootDir: __dirname,
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.4.8",
14
+ "version": "1.4.10",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
@@ -28,13 +28,13 @@
28
28
  }
29
29
  },
30
30
  "dependencies": {
31
- "@modern-js/prod-server": "^1.0.5",
31
+ "@babel/core": "7.16.7",
32
32
  "@babel/register": "^7.15.3",
33
- "@modern-js/bff-utils": "^1.2.2",
34
- "@modern-js/hmr-client": "^1.2.2",
35
- "@modern-js/server-utils": "^1.2.1",
36
- "@modern-js/utils": "^1.3.6",
37
- "chokidar": "^3.5.2",
33
+ "@modern-js/bff-utils": "^1.2.3",
34
+ "@modern-js/hmr-client": "^1.2.5",
35
+ "@modern-js/prod-server": "^1.1.1",
36
+ "@modern-js/server-utils": "^1.2.3",
37
+ "@modern-js/utils": "^1.5.0",
38
38
  "devcert": "^1.1.3",
39
39
  "launch-editor": "^2.2.1",
40
40
  "minimatch": "^3.0.4",
@@ -44,10 +44,11 @@
44
44
  "ws": "^8.2.0"
45
45
  },
46
46
  "devDependencies": {
47
- "@modern-js/server-core": "^1.2.4",
48
- "@modern-js/core": "^1.6.0",
47
+ "@modern-js/core": "1.8.0",
48
+ "@modern-js/server-core": "1.3.1",
49
+ "@modern-js/types": "^1.5.0",
49
50
  "@scripts/build": "0.0.0",
50
- "@modern-js/types": "^1.3.5",
51
+ "@scripts/jest-config": "0.0.0",
51
52
  "@types/jest": "^26",
52
53
  "@types/minimatch": "^3.0.5",
53
54
  "@types/node": "^14",
@@ -55,8 +56,7 @@
55
56
  "@types/ws": "^7.4.7",
56
57
  "jest": "^27",
57
58
  "typescript": "^4",
58
- "webpack": "^5.54.0",
59
- "@scripts/jest-config": "0.0.0",
59
+ "webpack": "^5.71.0",
60
60
  "websocket": "^1"
61
61
  },
62
62
  "peerDependencies": {
@@ -1,6 +0,0 @@
1
- module.exports = {
2
- extends: ['@modern-js'],
3
- parserOptions: {
4
- project: require.resolve('./tsconfig.json'),
5
- },
6
- };
package/tests/dev.test.ts DELETED
@@ -1,130 +0,0 @@
1
- import http from 'http';
2
- import { webpack, HotModuleReplacementPlugin } from 'webpack';
3
- import SocketServer from '../src/dev-tools/socket-server';
4
- import DevServerPlugin from '../src/dev-tools/dev-server-plugin';
5
-
6
- function getRandomPort() {
7
- return Math.floor(Math.random() * (8000 - 1024)) + 1024;
8
- }
9
-
10
- describe('test dev tools', () => {
11
- test('should socket server work correctly', () => {
12
- const port = getRandomPort();
13
- const socketServer: any = new SocketServer({
14
- client: {
15
- port: port.toString(),
16
- overlay: false,
17
- logging: 'error',
18
- path: '/',
19
- host: '127.0.0.1',
20
- },
21
- dev: {
22
- writeToDisk: false,
23
- },
24
- watch: true,
25
- hot: true,
26
- liveReload: true,
27
- });
28
- const app = http.createServer((req, res) => {
29
- res.end();
30
- });
31
-
32
- socketServer.prepare(app);
33
- expect(socketServer.app).toBe(app);
34
- expect(socketServer.stats).toBeUndefined();
35
-
36
- const mockStats = {
37
- toJson: () => ({}),
38
- };
39
- socketServer.updateStats(mockStats);
40
- expect(socketServer.stats).toBe(mockStats);
41
-
42
- const socket = {
43
- state: 1,
44
- readyState: 1,
45
- data: '',
46
- close() {
47
- socket.state = 0;
48
- },
49
- send(data: string) {
50
- socket.data = data;
51
- },
52
- on() {
53
- // empty
54
- },
55
- };
56
-
57
- socketServer.onConnect(socket);
58
-
59
- socketServer.sockets = [socket];
60
- socketServer.sockWrite('test');
61
- expect(socket.data).toBe(JSON.stringify({ type: 'test' }));
62
-
63
- socketServer.singleWrite(socket, 'single');
64
- expect(socket.data).toBe(JSON.stringify({ type: 'single' }));
65
-
66
- socketServer.close();
67
- expect(socket.state).toBe(0);
68
- app.close();
69
- });
70
-
71
- test('should dev server plugin work correctly with hot plugin', () => {
72
- const compiler = webpack({
73
- plugins: [new HotModuleReplacementPlugin()],
74
- });
75
- new DevServerPlugin({
76
- client: {
77
- port: '8080',
78
- overlay: false,
79
- logging: 'error',
80
- path: '/',
81
- host: '127.0.0.1',
82
- },
83
- dev: {
84
- writeToDisk: false,
85
- },
86
- watch: true,
87
- hot: true,
88
- liveReload: true,
89
- }).apply(compiler);
90
-
91
- // expect(compiler.options.entry)
92
- const entryPluginHook = compiler.hooks.compilation.taps.filter(
93
- tap => tap.name === 'EntryPlugin',
94
- );
95
- const hotPluginHook = compiler.hooks.compilation.taps.filter(
96
- tap => tap.name === 'HotModuleReplacementPlugin',
97
- );
98
- expect(entryPluginHook.length).toBe(3);
99
- expect(hotPluginHook.length).toBe(1);
100
- });
101
-
102
- test('should dev server plugin work correctly', () => {
103
- const compiler = webpack({});
104
- new DevServerPlugin({
105
- client: {
106
- port: '8080',
107
- overlay: false,
108
- logging: 'error',
109
- path: '/',
110
- host: '127.0.0.1',
111
- },
112
- dev: {
113
- writeToDisk: false,
114
- },
115
- watch: true,
116
- hot: true,
117
- liveReload: true,
118
- }).apply(compiler);
119
-
120
- // expect(compiler.options.entry)
121
- const entryPluginHook = compiler.hooks.compilation.taps.filter(
122
- tap => tap.name === 'EntryPlugin',
123
- );
124
- const hotPluginHook = compiler.hooks.compilation.taps.filter(
125
- tap => tap.name === 'HotModuleReplacementPlugin',
126
- );
127
- expect(entryPluginHook.length).toBe(3);
128
- expect(hotPluginHook.length).toBe(1);
129
- });
130
- });
@@ -1,11 +0,0 @@
1
- export default {
2
- 'GET /api/getInfo': { data: [1, 2, 3, 4] },
3
-
4
- '/api/getExample': { id: 1 },
5
-
6
- 'GET /api/addInfo': (req: any, res: any) => {
7
- setTimeout(() => {
8
- res.end('delay 2000ms');
9
- }, 2000);
10
- },
11
- };
@@ -1 +0,0 @@
1
- export default null;
@@ -1,3 +0,0 @@
1
- export default {
2
- 'GET /api/getInfo': 'foo',
3
- };
@@ -1 +0,0 @@
1
- export default {};
@@ -1,11 +0,0 @@
1
- export default {
2
- 'GET /api/getInfo': { data: [1, 2, 3, 4] },
3
-
4
- '/api/getExample': { id: 1 },
5
-
6
- 'GET /api/addInfo': (req: any, res: any) => {
7
- setTimeout(() => {
8
- res.end('delay 2000ms');
9
- }, 2000);
10
- },
11
- };
@@ -1,5 +0,0 @@
1
- module.exports = {
2
- server: {
3
- ssr: true,
4
- },
5
- };
@@ -1,21 +0,0 @@
1
- {
2
- "name": "deploy",
3
- "version": "0.1.0",
4
- "scripts": {
5
- "reset": "del-cli node_modules",
6
- "dev": "modern dev",
7
- "build": "modern build",
8
- "start": "modern start",
9
- "new": "modern new",
10
- "lint": "modern lint",
11
- "deploy": "modern deploy"
12
- },
13
- "dependencies": {},
14
- "devDependencies": {},
15
- "modernConfig": {
16
- "runtime": {
17
- "router": true,
18
- "state": true
19
- }
20
- }
21
- }
@@ -1,119 +0,0 @@
1
- html,
2
- body {
3
- padding: 0;
4
- margin: 0;
5
- font-family: nunito_for_arco, Helvetica Neue, Helvetica, PingFang SC,
6
- Hiragino Sans GB, Microsoft YaHei, 微软雅黑, Arial, sans-serif;
7
- }
8
-
9
- * {
10
- -webkit-font-smoothing: antialiased;
11
- -moz-osx-font-smoothing: grayscale;
12
- box-sizing: border-box;
13
- }
14
-
15
- .container {
16
- min-height: 100vh;
17
- max-width: 100%;
18
- display: flex;
19
- flex-direction: column;
20
- justify-content: center;
21
- align-items: center;
22
- }
23
-
24
- main {
25
- padding: 5rem 0;
26
- flex: 1;
27
- display: flex;
28
- flex-direction: column;
29
- justify-content: center;
30
- align-items: center;
31
- }
32
-
33
- .footer {
34
- width: 100%;
35
- height: 80px;
36
- border-top: 1px solid #eaeaea;
37
- display: flex;
38
- justify-content: center;
39
- align-items: center;
40
- background-color: #470000;
41
- }
42
-
43
- .footer a {
44
- display: flex;
45
- justify-content: center;
46
- align-items: center;
47
- flex-grow: 1;
48
- color: #f4f4f4;
49
- text-decoration: none;
50
- font-size: 1.1rem;
51
- }
52
-
53
- .logo {
54
- margin-bottom: 2rem;
55
- }
56
-
57
- .logo svg {
58
- width: 450px;
59
- height: 132px;
60
- }
61
-
62
- .description {
63
- text-align: center;
64
- line-height: 1.5;
65
- font-size: 1.5rem;
66
- }
67
-
68
- .code {
69
- background: #fafafa;
70
- border-radius: 5px;
71
- padding: 0.75rem;
72
- font-size: 1.1rem;
73
- font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
74
- Bitstream Vera Sans Mono, Courier New, monospace;
75
- }
76
-
77
- @media (max-width: 600px) {
78
- .grid {
79
- width: 100%;
80
- flex-direction: column;
81
- }
82
- }
83
-
84
- .grid {
85
- display: flex;
86
- align-items: center;
87
- justify-content: center;
88
- flex-wrap: wrap;
89
- width: 800px;
90
- margin-top: 3rem;
91
- }
92
-
93
- .card {
94
- margin: 1rem;
95
- padding: 1.5rem;
96
- display: flex;
97
- align-items: center;
98
- justify-content: center;
99
- height: 100px;
100
- color: inherit;
101
- text-decoration: none;
102
- border: 1px solid #470000;
103
- color: #470000;
104
- transition: color 0.15s ease, border-color 0.15s ease;
105
- width: 45%;
106
- }
107
-
108
- .card:hover,
109
- .card:focus,
110
- .card:active {
111
- transform: scale(1.05);
112
- transition: 0.1s ease-in-out;
113
- }
114
-
115
- .card h2 {
116
- font-size: 1.5rem;
117
- margin: 0;
118
- padding: 0;
119
- }
@@ -1,43 +0,0 @@
1
- import './App.css';
2
-
3
- const App = () => (
4
- <div className="container">
5
- <main>
6
- <div className="logo">
7
- <img
8
- src="https://lf3-static.bytednsdoc.com/obj/eden-cn/ylaelkeh7nuhfnuhf/modernjs-cover.png"
9
- width="300"
10
- alt="Modern.js Logo"
11
- />
12
- </div>
13
- <p className="description">
14
- Get started by editing <code className="code">src/home/App.tsx</code>
15
- </p>
16
- <div className="grid">
17
- <a href="https://modernjs.dev/docs/start" className="card">
18
- <h2>Quick Start Tencent</h2>
19
- </a>
20
- <a href="https://modernjs.dev/docs/guides" className="card">
21
- <h2>Handbook</h2>
22
- </a>
23
- <a href="https://modernjs.dev/docs/apis" className="card">
24
- <h2>API Reference </h2>
25
- </a>
26
- <a
27
- href="https://modernjs.dev/coming-soon"
28
- target="_blank"
29
- rel="noopener noreferrer"
30
- className="card">
31
- <h2>Community </h2>
32
- </a>
33
- </div>
34
- </main>
35
- <footer className="footer">
36
- <a href="https://modernjs.dev" target="_blank" rel="noopener noreferrer">
37
- Powered by Modern.js
38
- </a>
39
- </footer>
40
- </div>
41
- );
42
-
43
- export default App;
@@ -1,12 +0,0 @@
1
- {
2
- "extends": "@modern-js/tsconfig/base",
3
- "compilerOptions": {
4
- "declaration": false,
5
- "jsx": "preserve",
6
- "baseUrl": "./",
7
- "paths": {
8
- "@shared/*": ["./shared/*"]
9
- }
10
- },
11
- "include": ["src", "shared", "config"]
12
- }
@@ -1,3 +0,0 @@
1
- export default {
2
- name: 'a',
3
- };
@@ -1,5 +0,0 @@
1
- import a from './a';
2
-
3
- export default {
4
- a,
5
- };
@@ -1 +0,0 @@
1
- 1
package/tests/helper.ts DELETED
@@ -1,3 +0,0 @@
1
- export const noop = () => {
2
- // empty
3
- };
@@ -1,17 +0,0 @@
1
- import { genHttpsOptions } from '../src/dev-tools/https';
2
-
3
- describe('test dev tools', () => {
4
- test('should get http cert correctly', async () => {
5
- // Todo Interaction in CI
6
- // const options = await genHttpsOptions(true);
7
- // expect(options.key).toBeDefined();
8
- // expect(options.cert).toBeDefined();
9
-
10
- const useOpt = await genHttpsOptions({
11
- key: 'foo',
12
- cert: 'baz',
13
- });
14
- expect(useOpt.key).toBe('foo');
15
- expect(useOpt.cert).toBe('baz');
16
- });
17
- });
@@ -1,58 +0,0 @@
1
- import { LAUNCH_EDITOR_ENDPOINT } from '@modern-js/utils';
2
- import { createLaunchEditorHandler } from '../src/dev-tools/launch-editor';
3
- import { noop } from './helper';
4
-
5
- describe('should createLaunchEditorHandler work correctly', () => {
6
- const middleware = createLaunchEditorHandler();
7
-
8
- it('should return 200 if filename exist', () => {
9
- let response: any;
10
- const context: any = {
11
- url: LAUNCH_EDITOR_ENDPOINT,
12
- query: {
13
- filename: 'test.ts',
14
- },
15
- res: {
16
- end: (data: any) => {
17
- response = data;
18
- },
19
- },
20
- };
21
- middleware(context, noop);
22
- expect(context.status).toBe(200);
23
- expect(response).toBeUndefined();
24
- });
25
-
26
- it('should return 500 if filename not exist', () => {
27
- let response: any;
28
- const context: any = {
29
- url: LAUNCH_EDITOR_ENDPOINT,
30
- query: {
31
- filename: '',
32
- },
33
- res: {
34
- end: (data: any) => {
35
- response = data;
36
- },
37
- },
38
- };
39
- middleware(context, noop);
40
- expect(context.status).toBe(500);
41
- expect(typeof response === 'string').toBeTruthy();
42
- });
43
-
44
- it('should invoke next if not launch editor url', () => {
45
- let response: any;
46
- const context: any = {
47
- url: '',
48
- res: {
49
- end: (data: any) => {
50
- response = data;
51
- },
52
- },
53
- };
54
- middleware(context, noop);
55
- expect(context.status).toBeUndefined();
56
- expect(response).toBeUndefined();
57
- });
58
- });
@@ -1,150 +0,0 @@
1
- import path from 'path';
2
- import { createMockHandler } from '../src/dev-tools/mock';
3
- import getMockData, { getMatched } from '../src/dev-tools/mock/getMockData';
4
- import { noop } from './helper';
5
-
6
- describe('test dev tools', () => {
7
- describe('should mock middleware work correctly', () => {
8
- const pwd = path.join(__dirname, './fixtures/mock');
9
-
10
- it('should return null if no config mock dir', () => {
11
- expect(createMockHandler({ pwd: path.join(pwd, 'empty') })).toBeNull();
12
- });
13
-
14
- it('should return null if no api dir', () => {
15
- expect(createMockHandler({ pwd: path.join(pwd, 'zero') })).toBeNull();
16
- });
17
-
18
- it('should return middleware if mock api exist', async () => {
19
- const middleware = createMockHandler({ pwd: path.join(pwd, 'exist') });
20
-
21
- expect(middleware).not.toBeNull();
22
-
23
- let response: any;
24
- const context: any = {
25
- path: '/api/getInfo',
26
- method: 'get',
27
- res: {
28
- setHeader: noop,
29
- end: (data: any) => {
30
- response = JSON.parse(data);
31
- },
32
- },
33
- };
34
- await middleware?.(context, noop);
35
- expect(response).toEqual({
36
- data: [1, 2, 3, 4],
37
- });
38
- });
39
-
40
- it('should not return middleware if mock api exist', async () => {
41
- const middleware = createMockHandler({ pwd: path.join(pwd, 'exist') });
42
-
43
- expect(middleware).not.toBeNull();
44
-
45
- let response: any;
46
- const context: any = {
47
- path: '/api/getInfp',
48
- method: 'get',
49
- res: {
50
- setHeader: noop,
51
- end: (data: any) => {
52
- response = JSON.parse(data);
53
- },
54
- },
55
- };
56
- await middleware?.(context, noop);
57
- expect(response).toBeUndefined();
58
- });
59
-
60
- it('should get api list correctly', resolve => {
61
- const apiList = getMockData(path.join(pwd, 'exist/config/mock/index.ts'));
62
- expect(apiList.length).toBe(3);
63
-
64
- const pathList = apiList.map(api => api.path);
65
- expect(pathList).toEqual([
66
- '/api/getInfo',
67
- '/api/getExample',
68
- '/api/addInfo',
69
- ]);
70
-
71
- let response: any;
72
- const context: any = {
73
- res: {
74
- setHeader: noop,
75
- end: (data: any) => {
76
- try {
77
- response = JSON.parse(data);
78
- } catch (e) {
79
- response = data;
80
- }
81
- },
82
- },
83
- };
84
-
85
- apiList[0].handler(context, noop as any);
86
- expect(response).toEqual({
87
- data: [1, 2, 3, 4],
88
- });
89
- apiList[1].handler(context, noop as any);
90
- expect(response).toEqual({ id: 1 });
91
-
92
- apiList[2].handler(context, noop as any);
93
- setTimeout(() => {
94
- expect(response).toBe('delay 2000ms');
95
- resolve();
96
- }, 3000);
97
- });
98
-
99
- it('should match api correctly', () => {
100
- const apiList = [
101
- {
102
- method: 'get',
103
- path: '/api/getInfo',
104
- handler: noop,
105
- },
106
- {
107
- method: 'get',
108
- path: '/api/getExample',
109
- handler: noop,
110
- },
111
- {
112
- method: 'get',
113
- path: '/api/addInfo',
114
- handler: noop,
115
- },
116
- ];
117
- const matched = getMatched(
118
- { path: '/api/getInfo', method: 'get' } as any,
119
- apiList,
120
- );
121
- expect(matched).toBe(apiList[0]);
122
-
123
- const missMethod = getMatched(
124
- { path: '/api/getModern', method: 'post' } as any,
125
- apiList,
126
- );
127
- expect(missMethod).toBeUndefined();
128
- });
129
-
130
- it('should throw error if get mock file fail', resolve => {
131
- try {
132
- createMockHandler({ pwd: path.join(pwd, 'module-error') });
133
- } catch (e: any) {
134
- expect(e.message).toMatch('parsed failed!');
135
- resolve();
136
- }
137
- });
138
-
139
- it('should throw error if get mock api has wrong type', resolve => {
140
- try {
141
- createMockHandler({ pwd: path.join(pwd, 'type-error') });
142
- } catch (e: any) {
143
- expect(e.message).toMatch(
144
- 'should be object or function, but got string',
145
- );
146
- resolve();
147
- }
148
- });
149
- });
150
- });
@@ -1,238 +0,0 @@
1
- import path from 'path';
2
- import { defaultsConfig, NormalizedConfig } from '@modern-js/core';
3
- import { ModernServerContext, NextFunction } from '@modern-js/types';
4
- import { webpack } from 'webpack';
5
- import { AGGRED_DIR, RUN_MODE } from '@modern-js/prod-server';
6
- import createServer, { Server } from '../src';
7
- import Watcher from '../src/dev-tools/watcher';
8
- import { ModernDevServer } from '../src/server/dev-server';
9
-
10
- jest.useFakeTimers();
11
- (global as any).setImmediate = () => false;
12
- const appDirectory = path.join(__dirname, './fixtures/pure');
13
- describe('test dev server', () => {
14
- test('should throw error when ', resolve => {
15
- try {
16
- createServer(null as any);
17
- } catch (e: any) {
18
- expect((e as Error).message).toBe(
19
- 'can not start mserver without options',
20
- );
21
- resolve();
22
- }
23
- });
24
-
25
- test('shoule get modern server instance', async () => {
26
- const server = await createServer({
27
- config: {
28
- ...defaultsConfig,
29
- tools: {
30
- devServer: {
31
- proxy: {
32
- '/simple': `http://localhost:8080`,
33
- },
34
- },
35
- },
36
- } as any,
37
- pwd: appDirectory,
38
- dev: true,
39
- });
40
- expect(server instanceof Server).toBe(true);
41
- await server.close();
42
- });
43
-
44
- describe('shoule get dev modern server instance', () => {
45
- test('should init server correctly', async () => {
46
- const server = await createServer({
47
- config: defaultsConfig as NormalizedConfig,
48
- pwd: appDirectory,
49
- dev: true,
50
- });
51
- const modernServer = (server as any).server;
52
-
53
- const {
54
- pwd,
55
- distDir,
56
- workDir,
57
- conf,
58
- handlers,
59
- isDev,
60
- staticGenerate,
61
- presetRoutes,
62
- } = modernServer;
63
- expect(pwd).toBe(appDirectory);
64
- expect(distDir).toBe(path.join(appDirectory, 'dist'));
65
- expect(workDir).toBe(appDirectory);
66
- expect(conf).toBe(defaultsConfig);
67
- expect(handlers).toBeDefined();
68
- expect(isDev).toBeFalsy();
69
- expect(staticGenerate).toBeFalsy();
70
- expect(presetRoutes).toBeUndefined();
71
- await server.close();
72
- });
73
-
74
- test('should add handler correctly', async () => {
75
- const server = await createServer({
76
- config: defaultsConfig as NormalizedConfig,
77
- pwd: appDirectory,
78
- dev: true,
79
- });
80
- const modernServer = (server as any).server;
81
-
82
- const len = modernServer.handlers.length;
83
-
84
- const syncHandler = (ctx: ModernServerContext, next: NextFunction) => {
85
- console.info(ctx.url);
86
- next();
87
- };
88
- modernServer.addHandler(syncHandler);
89
-
90
- const newLen = modernServer.handlers.length;
91
- expect(len + 1).toBe(newLen);
92
- expect(modernServer.handlers[newLen - 1]).not.toBe(syncHandler);
93
-
94
- const asyncHandler = async (
95
- ctx: ModernServerContext,
96
- next: NextFunction,
97
- ) => {
98
- console.info(ctx.url);
99
- next();
100
- };
101
- modernServer.addHandler(asyncHandler);
102
- const nextLen = modernServer.handlers.length;
103
-
104
- expect(newLen + 1).toBe(nextLen);
105
- expect(modernServer.handlers[nextLen - 1]).toBe(asyncHandler);
106
- await server.close();
107
- });
108
-
109
- test('should get request handler correctly', async () => {
110
- const server = await createServer({
111
- config: defaultsConfig as NormalizedConfig,
112
- pwd: appDirectory,
113
- dev: true,
114
- });
115
-
116
- const modernServer: any = (server as any).server;
117
- const handler = modernServer.getRequestHandler();
118
- expect(typeof handler === 'function').toBeTruthy();
119
- await server.close();
120
- });
121
-
122
- test('should get request handler correctly', async () => {
123
- const server = await createServer({
124
- config: defaultsConfig as NormalizedConfig,
125
- pwd: appDirectory,
126
- dev: true,
127
- });
128
-
129
- const modernServer: any = (server as any).server;
130
- const handler = modernServer.getRequestHandler();
131
- expect(typeof handler === 'function').toBeTruthy();
132
- await server.close();
133
- });
134
-
135
- test('should invoke onrepack correctly', async () => {
136
- const server = await createServer({
137
- config: defaultsConfig as NormalizedConfig,
138
- pwd: appDirectory,
139
- dev: true,
140
- });
141
-
142
- const modernServer: ModernDevServer = (server as any).server;
143
- modernServer.onRepack({ routes: [] });
144
-
145
- expect((modernServer as any).router.matchers.length).toBe(0);
146
- server.close();
147
- });
148
-
149
- test('should invoke onserver change correctly', async () => {
150
- const server = await createServer({
151
- config: defaultsConfig as NormalizedConfig,
152
- pwd: appDirectory,
153
- dev: true,
154
- });
155
-
156
- const modernServer = (server as any).server;
157
- modernServer.onServerChange({
158
- filepath: path.join(appDirectory, AGGRED_DIR.mock),
159
- });
160
- expect(modernServer.mockHandler).not.toBeNull();
161
-
162
- modernServer.onServerChange({
163
- filepath: path.join(appDirectory, 'index.js'),
164
- });
165
- expect(modernServer.mockHandler).not.toBeNull();
166
- server.close();
167
- });
168
-
169
- test('should compiler work correctly', async () => {
170
- const compiler = webpack({});
171
- const server = await createServer({
172
- config: defaultsConfig as NormalizedConfig,
173
- pwd: appDirectory,
174
- dev: true,
175
- compiler,
176
- });
177
-
178
- expect(server).toBeDefined();
179
- server.close();
180
- });
181
-
182
- test('should multi compiler work correctly', async () => {
183
- const compiler = webpack([{}, { name: 'client' }]);
184
- const server = await createServer({
185
- config: defaultsConfig as NormalizedConfig,
186
- pwd: appDirectory,
187
- dev: true,
188
- compiler,
189
- });
190
-
191
- expect(server).toBeDefined();
192
- server.close();
193
- });
194
-
195
- test('should watcher work well', async () => {
196
- const devServer = await createServer({
197
- config: defaultsConfig as NormalizedConfig,
198
- pwd: appDirectory,
199
- dev: true,
200
- });
201
-
202
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
203
- // @ts-expect-error
204
- expect(devServer.server.watcher).toBeInstanceOf(Watcher);
205
- await devServer.close();
206
- });
207
- });
208
-
209
- describe('should split server work correctly', () => {
210
- test('should init api server correctly', async () => {
211
- const server = await createServer({
212
- config: defaultsConfig as NormalizedConfig,
213
- pwd: appDirectory,
214
- dev: true,
215
- apiOnly: true,
216
- runMode: RUN_MODE.FULL,
217
- });
218
- const modernServer = (server as any).server;
219
- modernServer.emitRouteHook('reset', {});
220
- expect(modernServer.prepareWebHandler()).toBe(null);
221
- await server.close();
222
- });
223
-
224
- test('should init ssr server correctly', async () => {
225
- const server = await createServer({
226
- config: defaultsConfig as NormalizedConfig,
227
- pwd: appDirectory,
228
- dev: true,
229
- ssrOnly: true,
230
- runMode: RUN_MODE.FULL,
231
- });
232
- const modernServer = (server as any).server;
233
- modernServer.emitRouteHook('reset', {});
234
- expect(modernServer.prepareAPIHandler()).toBe(null);
235
- await server.close();
236
- });
237
- });
238
- });
@@ -1,12 +0,0 @@
1
- {
2
- "extends": "@modern-js/tsconfig/base",
3
- "compilerOptions": {
4
- "declaration": false,
5
- "jsx": "preserve",
6
- "baseUrl": "./",
7
- "isolatedModules": true,
8
- "sourceMap": true
9
- },
10
- "paths": {},
11
- "exclude": ["src/__test__/fixtures/**"]
12
- }
@@ -1,231 +0,0 @@
1
- import path from 'path';
2
- import { fs } from '@modern-js/utils';
3
- import Watcher, { getWatchedFiles } from '../src/dev-tools/watcher';
4
- import { StatsCache } from '../src/dev-tools/watcher/stats-cache';
5
-
6
- jest.useRealTimers();
7
-
8
- describe('watcher', () => {
9
- jest.setTimeout(25000);
10
- const pwd = path.join(__dirname, './fixtures/watch');
11
- const serverDir = path.normalize(path.join(pwd, './tmp-server'));
12
-
13
- beforeAll(() => {
14
- if (fs.existsSync(serverDir)) {
15
- fs.removeSync(serverDir);
16
- }
17
- fs.mkdirSync(serverDir);
18
- });
19
-
20
- afterAll(() => {
21
- fs.removeSync(serverDir);
22
- });
23
-
24
- // const writeFiles = (content: string, filepath: string) => {
25
- // fs.writeFileSync(path.normalize(filepath), content, 'utf8');
26
- // };
27
-
28
- // TODO 容易导致 timeout,暂时注释掉
29
- // test('should emit add', done => {
30
- // const watcher = new Watcher();
31
- // const callback = jest.fn();
32
-
33
- // const watchDir = path.join(serverDir, 'add');
34
- // fs.mkdirSync(watchDir);
35
-
36
- // watcher.listen(
37
- // [`${watchDir}/**/*`],
38
- // {
39
- // ignoreInitial: true,
40
- // ignored: /api\/typings\/.*/,
41
- // },
42
- // async () => {
43
- // try {
44
- // callback();
45
- // expect(callback).toHaveBeenCalledTimes(1);
46
- // await watcher.close();
47
- // } catch (e) {
48
- // console.error(e);
49
- // }
50
- // done();
51
- // },
52
- // );
53
-
54
- // setTimeout(() => writeFiles('test', path.join(watchDir, 'index.js')), 100);
55
- // });
56
-
57
- // TODO 容易导致 timeout,暂时注释掉
58
- // test('should emit unlink', done => {
59
- // const watcher = new Watcher();
60
-
61
- // const callback = jest.fn();
62
- // const watchDir = path.join(serverDir, 'unlink');
63
- // fs.mkdirSync(watchDir);
64
-
65
- // const filepath = path.join(watchDir, 'index.js');
66
- // writeFiles('unlink', filepath);
67
-
68
- // watcher.listen(
69
- // [`${watchDir}/**/*`],
70
- // {
71
- // ignoreInitial: true,
72
- // ignored: /api\/typings\/.*/,
73
- // },
74
- // async () => {
75
- // callback();
76
- // expect(callback).toHaveBeenCalledTimes(1);
77
- // await watcher.close();
78
- // done();
79
- // },
80
- // );
81
-
82
- // setTimeout(() => {
83
- // fs.removeSync(filepath);
84
- // }, 100);
85
- // });
86
-
87
- // TODO 容易导致 timeout,暂时注释掉
88
- // test('should emit change', done => {
89
- // const watcher = new Watcher();
90
-
91
- // const callback = jest.fn();
92
- // const watchDir = path.join(serverDir, 'change');
93
- // fs.mkdirSync(watchDir);
94
-
95
- // const filepath = path.join(watchDir, 'index.js');
96
- // writeFiles('start', filepath);
97
-
98
- // watcher.listen(
99
- // [`${watchDir}/**/*`],
100
- // {
101
- // ignoreInitial: true,
102
- // ignored: /api\/typings\/.*/,
103
- // },
104
- // async () => {
105
- // callback();
106
- // expect(callback).toHaveBeenCalledTimes(1);
107
- // await watcher.close();
108
- // done();
109
- // },
110
- // );
111
-
112
- // setTimeout(() => writeFiles('end', filepath), 100);
113
- // });
114
-
115
- test('should not emit change when typings file changed', done => {
116
- const watcher = new Watcher();
117
- const apiDir = path.normalize(path.join(pwd, './api'));
118
-
119
- const callback = jest.fn();
120
-
121
- if (fs.pathExistsSync(apiDir)) {
122
- fs.removeSync(apiDir);
123
- }
124
-
125
- const clear = () => {
126
- fs.removeSync(apiDir);
127
- };
128
-
129
- fs.mkdirSync(path.normalize(path.join(apiDir, 'typings')), {
130
- recursive: true,
131
- });
132
-
133
- watcher.listen(
134
- [`${apiDir}/**/*`],
135
- {
136
- ignoreInitial: true,
137
- ignored: /api\/typings\/.*/,
138
- },
139
- callback,
140
- );
141
-
142
- setTimeout(async () => {
143
- expect(callback).toHaveBeenCalledTimes(0);
144
- await watcher.close();
145
- clear();
146
- done();
147
- }, 1000);
148
- });
149
- });
150
-
151
- describe('test watcher', () => {
152
- let watcher: any;
153
- const baseDir = path.join(__dirname, 'fixtures');
154
- const watchDir = path.join(baseDir, 'watch/**');
155
- const filepath = path.join(baseDir, 'watch', 'index.ts');
156
- const filepatha = path.join(baseDir, 'watch', 'a.ts');
157
- const txt = path.join(baseDir, 'watch', 'stats.txt');
158
-
159
- afterEach(() => {
160
- if (watcher) {
161
- watcher.close();
162
- }
163
- fs.writeFileSync(txt, '1');
164
- });
165
-
166
- it('should create watcher instance correctly', resolve => {
167
- watcher = new Watcher();
168
- expect(watcher.dependencyTree).toBeNull();
169
- watcher.createDepTree();
170
- expect(watcher.dependencyTree).not.toBeNull();
171
-
172
- expect(watcher.watcher).toBeUndefined();
173
- watcher.listen([watchDir], {}, () => {
174
- // empty
175
- });
176
-
177
- expect(watcher.watcher).toBeDefined();
178
- require(filepath);
179
- expect(watcher.dependencyTree.getNode(filepath)).toBeUndefined();
180
- watcher.updateDepTree();
181
- expect(watcher.dependencyTree.getNode(filepath)).toBeDefined();
182
- watcher.cleanDepCache(filepath);
183
- expect(watcher.dependencyTree.getNode(filepath)).toBeDefined();
184
-
185
- jest.resetModules();
186
- watcher.updateDepTree();
187
- expect(watcher.dependencyTree.getNode(filepath)).toBeUndefined();
188
-
189
- setTimeout(() => {
190
- const fl = getWatchedFiles(watcher.watcher);
191
- expect(fl.includes(filepatha)).toBeTruthy();
192
- expect(fl.includes(filepath)).toBeTruthy();
193
- expect(fl.includes(txt)).toBeTruthy();
194
- resolve();
195
- }, 1000);
196
- });
197
-
198
- it('should stats cache instance work correctly', () => {
199
- const statsCache = new StatsCache();
200
-
201
- // should not exist false before add
202
- expect(statsCache.has(txt)).toBeFalsy();
203
-
204
- // should exist true after add
205
- statsCache.add([txt]);
206
- expect(statsCache.has(txt)).toBeTruthy();
207
-
208
- // should diff correctly
209
- fs.writeFileSync(txt, 'foo');
210
- expect(statsCache.isDiff(txt)).toBeTruthy();
211
-
212
- // should not diff if not refresh
213
- fs.writeFileSync(txt, '1');
214
- expect(statsCache.isDiff(txt)).toBeFalsy();
215
-
216
- // should diff after refresh
217
- fs.writeFileSync(txt, 'foo');
218
- statsCache.refresh(txt);
219
- fs.writeFileSync(txt, '1');
220
- expect(statsCache.isDiff(txt)).toBeTruthy();
221
-
222
- // should diff when content change
223
- statsCache.refresh(txt);
224
- fs.writeFileSync(txt, '2');
225
- expect(statsCache.isDiff(txt)).toBeTruthy();
226
-
227
- // should not exist after del
228
- statsCache.del(txt);
229
- expect(statsCache.has(txt)).toBeFalsy();
230
- });
231
- });