@modern-js/plugin-express 1.2.0 → 1.3.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/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # @modern-js/plugin-express
2
2
 
3
+ ## 1.3.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 83166714: change .npmignore
8
+ - Updated dependencies [83166714]
9
+ - Updated dependencies [c3de9882]
10
+ - Updated dependencies [33ff48af]
11
+ - @modern-js/core@1.3.2
12
+ - @modern-js/adapter-helpers@1.2.1
13
+ - @modern-js/bff-runtime@1.2.1
14
+ - @modern-js/bff-utils@1.2.2
15
+ - @modern-js/server-plugin@1.2.1
16
+ - @modern-js/utils@1.2.2
17
+
18
+ ## 1.3.0
19
+
20
+ ### Minor Changes
21
+
22
+ - cfe11628: Make Modern.js self bootstraping
23
+
24
+ ### Patch Changes
25
+
26
+ - 146dcd85: modify server framework plugin hook types and hook context
27
+ - 146dcd85: modify server framework plugin hook types
28
+ - 146dcd85: fix test case in babel compiler
29
+ - Updated dependencies [2da09c69]
30
+ - Updated dependencies [fc71e36f]
31
+ - Updated dependencies [146dcd85]
32
+ - Updated dependencies [c3d46ee4]
33
+ - Updated dependencies [cfe11628]
34
+ - Updated dependencies [146dcd85]
35
+ - Updated dependencies [8e7603ee]
36
+ - Updated dependencies [146dcd85]
37
+ - @modern-js/utils@1.2.0
38
+ - @modern-js/core@1.3.0
39
+ - @modern-js/bff-runtime@1.2.0
40
+ - @modern-js/adapter-helpers@1.2.0
41
+ - @modern-js/bff-utils@1.2.0
42
+ - @modern-js/server-plugin@1.2.0
43
+
44
+ ## 1.2.1
45
+
46
+ ### Patch Changes
47
+
48
+ - ad107726: feat: new action support apppend type define
49
+
3
50
  ## 1.2.0
4
51
 
5
52
  ### Minor Changes
@@ -62,7 +62,7 @@ export default createPlugin(() => ({
62
62
  app = await findAppModule(apiDir);
63
63
 
64
64
  if (!app || !app.use) {
65
- console.warn('There is not api/app.ts.');
65
+ // console.warn('There is not api/app.ts.');
66
66
  app = express();
67
67
  }
68
68
 
@@ -84,7 +84,7 @@ var _default = (0, _serverPlugin.createPlugin)(() => ({
84
84
  app = await findAppModule(apiDir);
85
85
 
86
86
  if (!app || !app.use) {
87
- console.warn('There is not api/app.ts.');
87
+ // console.warn('There is not api/app.ts.');
88
88
  app = (0, _express.default)();
89
89
  }
90
90
 
package/jest.config.js ADDED
@@ -0,0 +1,8 @@
1
+ const sharedConfig = require('@scripts/jest-config');
2
+
3
+ /** @type {import('@jest/types').Config.InitialOptions} */
4
+ module.exports = {
5
+ // eslint-disable-next-line node/no-unsupported-features/es-syntax
6
+ ...sharedConfig,
7
+ rootDir: __dirname,
8
+ };
package/modern.config.js CHANGED
@@ -1,10 +1,2 @@
1
1
  /** @type {import('@modern-js/module-tools').UserConfig} */
2
- module.exports = {
3
- testing: {
4
- jest: {
5
- collectCoverage: true,
6
- collectCoverageFrom: ['src/**/*.ts'],
7
- coveragePathIgnorePatterns: ['/node_modules/'],
8
- },
9
- },
10
- };
2
+ module.exports = {};
package/package.json CHANGED
@@ -11,26 +11,31 @@
11
11
  "modern",
12
12
  "modern.js"
13
13
  ],
14
- "version": "1.2.0",
14
+ "version": "1.3.1",
15
15
  "jsnext:source": "./src/index.ts",
16
16
  "types": "./dist/types/index.d.ts",
17
17
  "main": "./dist/js/node/index.js",
18
18
  "module": "./dist/js/treeshaking/index.js",
19
19
  "jsnext:modern": "./dist/js/modern/index.js",
20
20
  "exports": {
21
+ "./types": "./types.d.ts",
21
22
  ".": {
22
23
  "node": {
24
+ "jsnext:source": "./src/index.ts",
23
25
  "import": "./dist/js/modern/index.js",
24
26
  "require": "./dist/js/node/index.js"
25
27
  },
26
28
  "default": "./dist/js/treeshaking/index.js"
27
29
  },
28
- "./cli": "./dist/js/node/cli/index.js"
30
+ "./cli": {
31
+ "jsnext:source": "./src/cli/index.ts",
32
+ "default": "./dist/js/node/cli/index.js"
33
+ }
29
34
  },
30
35
  "dependencies": {
31
36
  "@babel/runtime": "^7.15.3",
32
- "@modern-js/adapter-helpers": "^1.1.1",
33
- "@modern-js/utils": "^1.1.5",
37
+ "@modern-js/adapter-helpers": "^1.2.1",
38
+ "@modern-js/utils": "^1.2.2",
34
39
  "cookie-parser": "^1.4.5",
35
40
  "finalhandler": "^1.1.2",
36
41
  "formidable": "^1.2.2",
@@ -38,8 +43,8 @@
38
43
  },
39
44
  "devDependencies": {
40
45
  "express": "^4.17.1",
41
- "@modern-js/server-utils": "^1.1.2",
42
- "@modern-js/bff-runtime": "^1.1.1",
46
+ "@modern-js/server-utils": "^1.2.1",
47
+ "@modern-js/bff-runtime": "^1.2.1",
43
48
  "@types/cookie-parser": "^1.4.2",
44
49
  "@types/express": "^4.17.13",
45
50
  "@types/finalhandler": "^1.1.1",
@@ -50,11 +55,12 @@
50
55
  "@types/type-is": "^1.6.3",
51
56
  "supertest": "^6.1.6",
52
57
  "typescript": "^4",
53
- "@modern-js/bff-utils": "^1.1.1",
54
- "@modern-js/core": "^1.2.0",
55
- "@modern-js/server-plugin": "^1.1.3",
56
- "@modern-js/plugin-testing": "^1.1.1",
57
- "@modern-js/module-tools": "^1.1.2"
58
+ "@modern-js/bff-utils": "^1.2.2",
59
+ "@modern-js/core": "^1.3.2",
60
+ "@modern-js/server-plugin": "^1.2.1",
61
+ "@scripts/build": "0.0.0",
62
+ "jest": "^27",
63
+ "@scripts/jest-config": "0.0.0"
58
64
  },
59
65
  "modernConfig": {
60
66
  "output": {
@@ -62,20 +68,21 @@
62
68
  }
63
69
  },
64
70
  "peerDependencies": {
65
- "@modern-js/bff-utils": "^1.1.1",
66
- "@modern-js/core": "^1.2.0",
67
- "@modern-js/server-plugin": "^1.1.3",
68
- "@modern-js/bff-runtime": "^1.1.1",
71
+ "@modern-js/bff-utils": "^1.2.2",
72
+ "@modern-js/core": "^1.3.2",
73
+ "@modern-js/server-plugin": "^1.2.1",
74
+ "@modern-js/bff-runtime": "^1.2.1",
69
75
  "express": "^4.17.1"
70
76
  },
71
77
  "publishConfig": {
72
78
  "registry": "https://registry.npmjs.org/",
73
- "access": "public"
79
+ "access": "public",
80
+ "types": "./dist/types/index.d.ts"
74
81
  },
75
82
  "scripts": {
76
83
  "new": "modern new",
77
84
  "build": "modern build",
78
- "test": "modern test"
85
+ "test": "jest --passWithNoTests"
79
86
  },
80
87
  "readme": "\n<p align=\"center\">\n <a href=\"https://modernjs.dev\" target=\"blank\"><img src=\"https://lf3-static.bytednsdoc.com/obj/eden-cn/ylaelkeh7nuhfnuhf/modernjs-cover.png\" width=\"300\" alt=\"Modern.js Logo\" /></a>\n</p>\n<p align=\"center\">\n现代 Web 工程体系\n <br/>\n <a href=\"https://modernjs.dev\" target=\"blank\">\n modernjs.dev\n </a>\n</p>\n<p align=\"center\">\n The meta-framework suite designed from scratch for frontend-focused modern web development\n</p>\n\n# Introduction\n\n> The doc site ([modernjs.dev](https://modernjs.dev)) and articles are only available in Chinese for now, we are planning to add English versions soon.\n\n- [Modern.js: Hello, World!](https://zhuanlan.zhihu.com/p/426707646)\n\n## Getting Started\n\n- [Quick Start](https://modernjs.dev/docs/start)\n- [Guides](https://modernjs.dev/docs/guides)\n- [API References](https://modernjs.dev/docs/apis)\n\n## Contributing\n\n- [Contributing Guide](https://github.com/modern-js-dev/modern.js/blob/main/CONTRIBUTING.md)\n"
81
88
  }
@@ -1,7 +1,7 @@
1
1
  // eslint-disable-next-line eslint-comments/disable-enable-pair
2
2
  /* eslint-disable react-hooks/rules-of-hooks */
3
3
  import { match } from '@modern-js/bff-runtime';
4
- import { useContext } from '@/context';
4
+ import { useContext } from '../../../../../src/context';
5
5
 
6
6
  // eslint-disable-next-line arrow-body-style
7
7
  export const get = ({ query }: { query: Record<string, unknown> }) => {
@@ -1,7 +1,7 @@
1
1
  // eslint-disable-next-line eslint-comments/disable-enable-pair
2
2
  /* eslint-disable react-hooks/rules-of-hooks */
3
3
  import { match } from '@modern-js/bff-runtime';
4
- import { useContext } from '@/context';
4
+ import { useContext } from '../../../../../../src/context';
5
5
 
6
6
  export const get = ({ query }: { query: Record<string, unknown> }) => ({
7
7
  query,
@@ -1,5 +1,5 @@
1
1
  import path from 'path';
2
- import express, { Request, Response } from 'express';
2
+ import express from 'express';
3
3
  import request from 'supertest';
4
4
  import { serverManager } from '@modern-js/server-plugin';
5
5
  import { INTROSPECTION_ROUTE_PATH } from '@modern-js/bff-utils';
@@ -333,7 +333,7 @@ describe('support as async handler', () => {
333
333
  config: { middleware: [wrapMiddleware] },
334
334
  });
335
335
 
336
- const asyncHandler = async (req: Request, res: Response) => {
336
+ const asyncHandler = async (req: any, res: any) => {
337
337
  await apiHandler(req, res);
338
338
  order.push(3);
339
339
  };
@@ -7,8 +7,6 @@
7
7
  "isolatedModules": true,
8
8
  "sourceMap": true
9
9
  },
10
- "paths": {
11
- "@/*": ["../src/*"]
12
- },
10
+ "paths": {},
13
11
  "exclude": ["src/__test__/fixtures/**"]
14
12
  }
@@ -3,7 +3,7 @@ import { Buffer } from 'buffer';
3
3
  import { Request, Response } from 'express';
4
4
  import request from 'supertest';
5
5
  import { serverManager } from '@modern-js/server-plugin';
6
- import plugin from '@/plugin';
6
+ import plugin from '../src/plugin';
7
7
  import './common';
8
8
 
9
9
  const pwd = path.join(__dirname, './fixtures/function-mode');
package/types.d.ts CHANGED
@@ -1,8 +1,19 @@
1
1
  /// <reference path="./dist/types/index.d.ts" />
2
2
 
3
3
  declare module '@modern-js/runtime/server' {
4
- import { Request, Response } from 'express';
4
+ import { Request, Response, RequestHandler } from 'express';
5
+
6
+ type ExpressOptions = {
7
+ addMiddleware: (...input: RequestHandler[]) => void;
8
+ };
9
+
10
+ type ExpressAttacher = (options: ExpressOptions) => void;
5
11
 
6
12
  type Context = { req: Request; res: Response };
13
+
7
14
  export function useContext(): Context;
15
+
16
+ export function hook(attacher: ExpressAttacher): ExpressAttacher;
17
+
18
+ export * from '@modern-js/bff-runtime';
8
19
  }
package/src/cli/index.ts DELETED
@@ -1,85 +0,0 @@
1
- import * as path from 'path';
2
- import { useAppContext, createPlugin } from '@modern-js/core';
3
- import { createRuntimeExportsUtils } from '@modern-js/utils';
4
-
5
- export default createPlugin(
6
- () => {
7
- let bffExportsUtils: any;
8
- const runtimeModulePath = path.resolve(__dirname, '../runtime');
9
-
10
- return {
11
- config() {
12
- // eslint-disable-next-line react-hooks/rules-of-hooks
13
- const appContext = useAppContext();
14
- const { appDirectory } = appContext;
15
- bffExportsUtils = createRuntimeExportsUtils(
16
- appContext.internalDirectory,
17
- 'server',
18
- );
19
-
20
- const serverRuntimePath = bffExportsUtils.getPath();
21
-
22
- // Look up one level, because the artifacts after build have dist directories
23
- let relativeRuntimePath = path.join(
24
- '../',
25
- path.relative(appDirectory, serverRuntimePath),
26
- );
27
-
28
- if (
29
- process.env.NODE_ENV === 'development' ||
30
- process.env.NODE_ENV === 'test'
31
- ) {
32
- relativeRuntimePath = `./${path.relative(
33
- appDirectory,
34
- serverRuntimePath,
35
- )}`;
36
- }
37
-
38
- return {
39
- source: {
40
- alias: {
41
- '@modern-js/runtime/server': relativeRuntimePath,
42
- },
43
- },
44
- };
45
- },
46
- modifyEntryImports(input) {
47
- // eslint-disable-next-line react-hooks/rules-of-hooks
48
- const { appDirectory } = useAppContext();
49
- const runtimePath = require.resolve(`@modern-js/runtime`, {
50
- paths: [appDirectory],
51
- });
52
-
53
- const currentFile = bffExportsUtils.getPath();
54
-
55
- const runtimeDir = path.dirname(runtimePath);
56
-
57
- const relativeBffPath = path.relative(
58
- path.dirname(currentFile),
59
- path.join(runtimeDir, './exports/server'),
60
- );
61
- const relativeRuntimeModulePath = path.relative(
62
- path.dirname(currentFile),
63
- runtimeModulePath,
64
- );
65
-
66
- const relativeFramePath = path.relative(
67
- path.dirname(currentFile),
68
- require.resolve('express'),
69
- );
70
-
71
- bffExportsUtils.addExport(`const bffRuntime = require('${relativeBffPath}');
72
- const pluginRuntime = require('${relativeRuntimeModulePath}');
73
- const express = require('${relativeFramePath}')
74
- module.exports = {
75
- express: express,
76
- ...bffRuntime,
77
- ...pluginRuntime
78
- }
79
- `);
80
- return input;
81
- },
82
- };
83
- },
84
- { name: '@modern-js/plugin-express' },
85
- );
package/src/context.ts DELETED
@@ -1,8 +0,0 @@
1
- import { createStorage } from '@modern-js/adapter-helpers';
2
- import { Request, Response } from 'express';
3
-
4
- export type Context = { req: Request; res: Response };
5
-
6
- const { run, useContext } = createStorage<Context>();
7
-
8
- export { run, useContext };
package/src/index.ts DELETED
@@ -1,5 +0,0 @@
1
- // eslint-disable-next-line filenames/match-exported
2
- import plugin from './plugin';
3
-
4
- export * from './context';
5
- export default plugin;
package/src/plugin.ts DELETED
@@ -1,157 +0,0 @@
1
- import * as path from 'path';
2
- import express, { RequestHandler, Express } from 'express';
3
- import type { Request, Response } from 'express';
4
- import cookieParser from 'cookie-parser';
5
- import { createPlugin } from '@modern-js/server-plugin';
6
- import { requireModule } from '@modern-js/bff-utils';
7
- import { fs, createDebugger } from '@modern-js/utils';
8
- import finalhandler from 'finalhandler';
9
- import { run } from './context';
10
- import registerRoutes from './registerRoutes';
11
-
12
- const debug = createDebugger('express');
13
-
14
- interface FrameConfig {
15
- middleware: (RequestHandler | string)[];
16
- }
17
-
18
- export type Mode = 'function' | 'framework';
19
-
20
- const findAppModule = async (apiDir: string) => {
21
- const exts = ['.ts', '.js'];
22
- const paths = exts.map(ext => path.resolve(apiDir, `app${ext}`));
23
-
24
- for (const filename of paths) {
25
- if (await fs.pathExists(filename)) {
26
- return requireModule(filename);
27
- }
28
- }
29
-
30
- return null;
31
- };
32
-
33
- const initMiddlewares = (
34
- middleware: (RequestHandler | string)[],
35
- app: Express,
36
- ) => {
37
- middleware.forEach(middlewareItem => {
38
- const middlewareFunc =
39
- typeof middlewareItem === 'string'
40
- ? requireModule(middlewareItem)
41
- : middlewareItem;
42
- app.use(middlewareFunc);
43
- });
44
- };
45
-
46
- const useRun = (app: Express) => {
47
- app.use((req, res, next) => {
48
- run({ req, res }, next);
49
- });
50
- };
51
-
52
- const initApp = (app: express.Express) => {
53
- app.use(cookieParser());
54
- app.use(express.text());
55
- app.use(express.urlencoded({ extended: true }));
56
- app.use(express.json());
57
- return app;
58
- };
59
-
60
- export default createPlugin(
61
- () => ({
62
- // eslint-disable-next-line max-statements
63
- async prepareApiServer({ pwd, mode, config }) {
64
- let app: Express;
65
- const apiDir = path.join(pwd, './api');
66
- if (mode === 'framework') {
67
- app = await findAppModule(apiDir);
68
-
69
- if (!app || !app.use) {
70
- console.warn('There is not api/app.ts.');
71
- app = express();
72
- }
73
- initApp(app);
74
-
75
- if (config) {
76
- const { middleware } = config as FrameConfig;
77
- initMiddlewares(middleware, app);
78
- }
79
- // eslint-disable-next-line react-hooks/rules-of-hooks
80
- useRun(app);
81
-
82
- registerRoutes(app);
83
- } else if (mode === 'function') {
84
- app = express();
85
- initApp(app);
86
-
87
- if (config) {
88
- const { middleware } = config as FrameConfig;
89
- initMiddlewares(middleware, app);
90
- }
91
-
92
- // eslint-disable-next-line react-hooks/rules-of-hooks
93
- useRun(app);
94
-
95
- registerRoutes(app);
96
- } else {
97
- throw new Error(`mode must be function or framework`);
98
- }
99
-
100
- return (req, res) =>
101
- new Promise((resolve, reject) => {
102
- const handler = (err: any) => {
103
- if (err) {
104
- return reject(err);
105
- }
106
- // finalhanlder will trigger 'finish' event
107
- return finalhandler(req, res, {})(null);
108
- // return resolve();
109
- };
110
-
111
- res.on('finish', (err: Error) => {
112
- if (err) {
113
- return reject(err);
114
- }
115
- return resolve();
116
- });
117
- return app(req as Request, res as Response, handler);
118
- });
119
- },
120
-
121
- prepareWebServer({ config }) {
122
- const app = express();
123
- initApp(app);
124
- if (config) {
125
- const { middleware } = config as FrameConfig;
126
- debug('web middleware', middleware);
127
- initMiddlewares(middleware, app);
128
- }
129
-
130
- return (req, res) =>
131
- new Promise((resolve, reject) => {
132
- const handler = (err: string) => {
133
- if (err) {
134
- return reject(err);
135
- }
136
- if (res.headersSent && res.statusCode !== 200) {
137
- finalhandler(req, res, {})(null);
138
- }
139
- return resolve();
140
- };
141
-
142
- // when user call res.send
143
- res.on('finish', (err: Error) => {
144
- if (err) {
145
- return reject(err);
146
- }
147
- return resolve();
148
- });
149
- return app(req as Request, res as Response, handler);
150
- });
151
- },
152
- }),
153
- {
154
- name: '@modern-js/plugin-express',
155
- pre: ['@modern-js/plugin-bff'],
156
- },
157
- ) as any;
@@ -1,119 +0,0 @@
1
- import { HttpMethod, useAPIHandlerInfos } from '@modern-js/bff-utils';
2
- import { isSchemaHandler, InputType } from '@modern-js/bff-runtime';
3
- import {
4
- Express,
5
- Request,
6
- Response,
7
- RequestHandler,
8
- NextFunction,
9
- } from 'express';
10
- import typeIs from 'type-is';
11
- import formidable from 'formidable';
12
- import { sortDynamicRoutes } from '@modern-js/adapter-helpers';
13
- import { createDebugger } from '@modern-js/utils';
14
-
15
- const debug = createDebugger('express');
16
-
17
- const registerRoutes = (app: Express) => {
18
- // eslint-disable-next-line react-hooks/rules-of-hooks
19
- const handlerInfos = useAPIHandlerInfos();
20
- sortDynamicRoutes(handlerInfos);
21
- debug('handlerInfos', handlerInfos);
22
-
23
- handlerInfos.forEach(({ path, handler, method, name }) => {
24
- const wrapedHandler: RequestHandler = async (
25
- req: Request,
26
- res: Response,
27
- next: NextFunction,
28
- ) => {
29
- const input = await getInputFromRequest(req);
30
-
31
- if (isSchemaHandler(handler)) {
32
- const result = await handler(input);
33
- if (result.type !== 'HandleSuccess') {
34
- if (result.type === 'InputValidationError') {
35
- res.status(400);
36
- } else {
37
- res.status(500);
38
- }
39
- return res.json(result.message);
40
- } else {
41
- res.status(200);
42
- return res.json(result.value);
43
- }
44
- } else {
45
- const args = Object.values(input.params as any).concat(input);
46
-
47
- try {
48
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
49
- // @ts-expect-error
50
- const body = await handler(...args);
51
-
52
- // this should never happen
53
- if (res.headersSent) {
54
- return await Promise.resolve();
55
- }
56
-
57
- res.status(200);
58
- return res.json(body);
59
- } catch (e) {
60
- return next(e);
61
- }
62
- }
63
- };
64
-
65
- Object.defineProperties(
66
- wrapedHandler,
67
- Object.getOwnPropertyDescriptors(handler),
68
- );
69
-
70
- if (isNormalMethod(method)) {
71
- const routeName = method.toLowerCase();
72
- (app as any)[routeName](path || name, wrapedHandler);
73
- } else {
74
- throw new Error(`Unknown HTTP Method: ${method}`);
75
- }
76
- });
77
- };
78
-
79
- const isNormalMethod = (method: string): method is HttpMethod =>
80
- Object.keys(HttpMethod).includes(method);
81
-
82
- export default registerRoutes;
83
-
84
- const getInputFromRequest = async (request: Request): Promise<InputType> => {
85
- const draft: Record<string, any> = {
86
- params: request.params,
87
- query: request.query,
88
- headers: request.headers,
89
- cookies: request.headers.cookie,
90
- };
91
-
92
- if (typeIs(request, ['application/json'])) {
93
- draft.data = request.body;
94
- } else if (typeIs(request, ['multipart/form-data'])) {
95
- draft.formData = await resvoleFormData(request);
96
- } else if (typeIs(request, ['application/x-www-form-urlencoded'])) {
97
- draft.formUrlencoded = request.body;
98
- } else {
99
- draft.body = request.body;
100
- }
101
-
102
- return draft as any;
103
- };
104
-
105
- const resvoleFormData = (request: Request): Promise<Record<string, any>> => {
106
- const form = formidable({ multiples: true });
107
- return new Promise((resolve, reject) => {
108
- form.parse(request, (err, fields, files) => {
109
- if (err) {
110
- reject(err);
111
- }
112
-
113
- resolve({
114
- ...fields,
115
- ...files,
116
- });
117
- });
118
- });
119
- };
package/src/runtime.ts DELETED
@@ -1 +0,0 @@
1
- export { useContext } from './context';
@@ -1,5 +0,0 @@
1
- import { hook } from '@modern-js/server-utils';
2
-
3
- export default hook(({ addMiddleware }) => {
4
- addMiddleware('@koa/api');
5
- });