From b3c4af6943b2f539201cac94f1751410969e03b1 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Fri, 27 Oct 2023 13:21:48 +0800 Subject: [PATCH 001/101] feat: add dependency --- packages/app/package.json | 12 +++++++--- packages/app/src/__tests__/index.test.ts | 2 +- packages/app/src/index.ts | 24 ++++++++++---------- packages/app/src/mount.ts | 28 +++++++++++------------- packages/app/src/test.ts | 6 ----- 5 files changed, 34 insertions(+), 38 deletions(-) delete mode 100644 packages/app/src/test.ts diff --git a/packages/app/package.json b/packages/app/package.json index da8878d..71a636d 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -29,9 +29,15 @@ "happy-dom": "^6.0.4" }, "dependencies": { - "@tomrpc/import-dir": "^1.2.4", + "@tomrpc/client": "^1.0.0", + "@tomrpc/core": "^1.0.0", + "@tomrpc/mount": "^1.0.0", "debug": "^4.3.4", "desm": "^1.3.0", - "flat": "^6.0.1" + "flat": "^6.0.1", + "jsonwebtoken": "^9.0.2", + "koa-cors": "^0.0.16", + "koa-static": "^5.0.0", + "koa-views": "^8.1.0" } -} +} \ No newline at end of file diff --git a/packages/app/src/__tests__/index.test.ts b/packages/app/src/__tests__/index.test.ts index e0b5549..2ae6c18 100644 --- a/packages/app/src/__tests__/index.test.ts +++ b/packages/app/src/__tests__/index.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import mount from '../mount'; +// import mount from '../mount'; describe('lib', () => { it('should render lib', () => { diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 84a5275..2ce73f9 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -1,6 +1,6 @@ import debug from 'debug'; -import mount from './mount'; +// import mount from './mount'; import { isFunction } from './utils'; const log = debug('@tomrpc/mount'); @@ -10,16 +10,14 @@ const log = debug('@tomrpc/mount'); // a.b => /a/b + function export default async (rpc, dir) => { - const files = await mount(rpc.base, dir); - - log(files); - - Object.keys(files).forEach((key) => { - if (isFunction(files[key])) { - log('add funtion key=' + key); - rpc.fn(key, files[key]); - } else { - console.dir(`key=${key} is not a function`); - } - }); + // const files = await mount(rpc.base, dir); + // log(files); + // Object.keys(files).forEach((key) => { + // if (isFunction(files[key])) { + // log('add funtion key=' + key); + // rpc.fn(key, files[key]); + // } else { + // console.dir(`key=${key} is not a function`); + // } + // }); }; diff --git a/packages/app/src/mount.ts b/packages/app/src/mount.ts index 0120a60..b323636 100644 --- a/packages/app/src/mount.ts +++ b/packages/app/src/mount.ts @@ -1,20 +1,18 @@ -import importDir, { join } from '@tomrpc/import-dir'; -import debug from 'debug'; -import { flatten } from 'flat'; +// import importDir, { join } from '@tomrpc/import-dir'; +// import debug from 'debug'; +// import { flatten } from 'flat'; -const log = debug('@tomrpc/mount'); +// const log = debug('@tomrpc/mount'); -// {a:{a:1, b:2}} -// {a.b:2, a.a:1} -// a.b => /a/b + function +// // {a:{a:1, b:2}} +// // {a.b:2, a.a:1} +// // a.b => /a/b + function export default async (base, dir) => { - const files = await importDir(join(base, dir), { - recurse: true, - extensions: ['.ts', '.js', '.json'], - }); - - log(files); - - return flatten(files); + // const files = await importDir(join(base, dir), { + // recurse: true, + // extensions: ['.ts', '.js', '.json'], + // }); + // log(files); + // return flatten(files); }; diff --git a/packages/app/src/test.ts b/packages/app/src/test.ts deleted file mode 100644 index 656b656..0000000 --- a/packages/app/src/test.ts +++ /dev/null @@ -1,6 +0,0 @@ -import mount from './mount'; - -(async () => { - const files = await mount(import.meta.url, './f'); - console.dir(files); -})(); From 6eeeefc7446dffa8303e0a9c62243526715fa7db Mon Sep 17 00:00:00 2001 From: npmstudy Date: Fri, 27 Oct 2023 14:18:23 +0800 Subject: [PATCH 002/101] chore: add vitest lastest version --- lib2/package.json | 3 ++- package.json | 2 +- packages/app/package.json | 7 ++++--- packages/client/package.json | 3 ++- packages/core/package-lock.json | 3 ++- packages/core/package.json | 3 ++- packages/mount/package.json | 3 ++- 7 files changed, 15 insertions(+), 9 deletions(-) diff --git a/lib2/package.json b/lib2/package.json index e2b6398..66de33f 100644 --- a/lib2/package.json +++ b/lib2/package.json @@ -25,7 +25,8 @@ "awesome-keywords" ], "devDependencies": { - "@vitest/coverage-v8": "^0.34.2", + "@vitest/coverage-v8": "^0.34.6", + "vitest": "^0.34.6", "happy-dom": "^6.0.4" }, "dependencies": { diff --git a/package.json b/package.json index 0162cec..dcabeab 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "tsx": "^3.12.10", "typescript": "^4.9.5", "vite": "^4.4.9", - "vitest": "^0.32.4" + "vitest": "^0.34.6" }, "packageManager": "pnpm@8.6.0", "size-limit": [ diff --git a/packages/app/package.json b/packages/app/package.json index 71a636d..fba3ff1 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -25,7 +25,8 @@ "awesome-keywords" ], "devDependencies": { - "@vitest/coverage-v8": "^0.34.2", + "@vitest/coverage-v8": "^0.34.6", + "vitest": "^0.34.6", "happy-dom": "^6.0.4" }, "dependencies": { @@ -38,6 +39,6 @@ "jsonwebtoken": "^9.0.2", "koa-cors": "^0.0.16", "koa-static": "^5.0.0", - "koa-views": "^8.1.0" + "koa-views": "^8.0.0" } -} \ No newline at end of file +} diff --git a/packages/client/package.json b/packages/client/package.json index 9a007f1..35a5c8f 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -25,7 +25,8 @@ "awesome-keywords" ], "devDependencies": { - "@vitest/coverage-v8": "^0.34.2", + "vitest": "^0.34.6", + "@vitest/coverage-v8": "^0.34.6", "happy-dom": "^6.0.4" }, "dependencies": { diff --git a/packages/core/package-lock.json b/packages/core/package-lock.json index 5c63003..b2c9859 100644 --- a/packages/core/package-lock.json +++ b/packages/core/package-lock.json @@ -14,7 +14,8 @@ "koa": "^2.14.2" }, "devDependencies": { - "@vitest/coverage-v8": "^0.34.2", + "vitest": "^0.34.6", + "@vitest/coverage-v8": "^0.34.6", "happy-dom": "^6.0.4", "supertest": "^6.3.3" } diff --git a/packages/core/package.json b/packages/core/package.json index 1dc2b7a..05bd32d 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -26,7 +26,8 @@ ], "devDependencies": { "@types/koa": "^2.13.10", - "@vitest/coverage-v8": "^0.34.2", + "vitest": "^0.34.6", + "@vitest/coverage-v8": "^0.34.6", "happy-dom": "^6.0.4", "supertest": "^6.3.3" }, diff --git a/packages/mount/package.json b/packages/mount/package.json index 9ce6f4c..7f37744 100644 --- a/packages/mount/package.json +++ b/packages/mount/package.json @@ -25,7 +25,8 @@ "awesome-keywords" ], "devDependencies": { - "@vitest/coverage-v8": "^0.34.2", + "vitest": "^0.34.6", + "@vitest/coverage-v8": "^0.34.6", "happy-dom": "^6.0.4" }, "dependencies": { From ce4feec9db060ffb2496671671c8177965cefba8 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Fri, 27 Oct 2023 17:16:38 +0800 Subject: [PATCH 003/101] chore: add vitest lastest version --- example/src/__tests__/index.test.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 example/src/__tests__/index.test.ts diff --git a/example/src/__tests__/index.test.ts b/example/src/__tests__/index.test.ts new file mode 100644 index 0000000..3b3e787 --- /dev/null +++ b/example/src/__tests__/index.test.ts @@ -0,0 +1,9 @@ +import { describe, expect, it } from 'vitest'; + +// import { lib } from '..'; + +describe('lib', () => { + it('should render lib', () => { + // expect(lib()).toBe('lib'); + }); +}); From d84894fd9abd14a2ec98db66416b6ad565d189a8 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sat, 28 Oct 2023 11:03:47 +0800 Subject: [PATCH 004/101] chore: init first version --- .vscode/launch.json | 12 ++++-- packages/app/README.md | 4 +- packages/app/app.ts | 20 +++++++++ packages/app/package.json | 1 + packages/app/src/index.ts | 84 ++++++++++++++++++++++++++++-------- packages/app/src/load.ts | 21 +++++++++ packages/app/src/mount.ts | 18 -------- packages/app/src/mw/cors.ts | 7 +++ packages/app/src/mw/index.ts | 4 ++ packages/app/src/mw/jwt.ts | 7 +++ packages/app/src/mw/serve.ts | 7 +++ packages/app/src/mw/view.ts | 7 +++ packages/core/src/index.ts | 62 ++++++++++++++++++++++++-- 13 files changed, 210 insertions(+), 44 deletions(-) create mode 100644 packages/app/app.ts create mode 100644 packages/app/src/load.ts delete mode 100644 packages/app/src/mount.ts create mode 100644 packages/app/src/mw/cors.ts create mode 100644 packages/app/src/mw/index.ts create mode 100644 packages/app/src/mw/jwt.ts create mode 100644 packages/app/src/mw/serve.ts create mode 100644 packages/app/src/mw/view.ts diff --git a/.vscode/launch.json b/.vscode/launch.json index ffaacce..64188b7 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -7,14 +7,18 @@ { "type": "node", "request": "launch", - "name": "启动程序", + "name": "Unit test", "skipFiles": [ "/**" ], "program": "${file}", - "outFiles": [ - "${workspaceFolder}/example/**/*.js" + "runtimeArgs": [ + "--loader", + "tsx" + ], + "args": [ + "--test" ] } ] -} \ No newline at end of file +} diff --git a/packages/app/README.md b/packages/app/README.md index 37dfd64..325bbe1 100644 --- a/packages/app/README.md +++ b/packages/app/README.md @@ -16,7 +16,9 @@ tom.json mount: './fn' lifeCyle: { - } + }, + debug: true + logLevel: } ``` diff --git a/packages/app/app.ts b/packages/app/app.ts new file mode 100644 index 0000000..afb5724 --- /dev/null +++ b/packages/app/app.ts @@ -0,0 +1,20 @@ +import { createApp } from './src/index'; + +(async () => { + const rpc = await createApp({ + name: 'tomapp', + base: import.meta.url, + port: 3000, + debug: false, + // mount?: './fn''; + buildin: { + static: { enable: true }, + }, + }); + + rpc.fn('a', function (a) { + return a; + }); + + rpc.start(); +})(); diff --git a/packages/app/package.json b/packages/app/package.json index fba3ff1..560c1f7 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -10,6 +10,7 @@ "main": "./dist/index.js", "module": "./dist/index.mjs", "types": "./dist/index.d.ts", + "type": "module", "files": [ "dist" ], diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 2ce73f9..adfbbd9 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -1,23 +1,71 @@ +import { createServer } from '@tomrpc/core'; +import mount from '@tomrpc/mount'; import debug from 'debug'; -// import mount from './mount'; -import { isFunction } from './utils'; +import { loadBuildinMiddlewaire, loadCustomMiddlewaire } from './load'; const log = debug('@tomrpc/mount'); -// {a:{a:1, b:2}} -// {a.b:2, a.a:1} -// a.b => /a/b + function - -export default async (rpc, dir) => { - // const files = await mount(rpc.base, dir); - // log(files); - // Object.keys(files).forEach((key) => { - // if (isFunction(files[key])) { - // log('add funtion key=' + key); - // rpc.fn(key, files[key]); - // } else { - // console.dir(`key=${key} is not a function`); - // } - // }); -}; +// { +// name:'hi' +// base: import.meta.url +// static: 'public' +// cors: { enable: true } +// view: { enable: true } +// jwt: { enable: true } +// port: 3000 +// mount: './fn' +// lifeCyle: { + +// }, +// debug: true +// logLevel: +// } +interface IConfig { + name: string | 'tomapp'; + base?: string; + port?: number | 3000; + debug?: boolean | false; + mount?: string; + buildin: { + static?: { enable: true }; + cors?: { enable: true }; + view?: { enable: true }; + jwt?: { enable: true }; + }; +} + +export async function createApp(cfg: IConfig) { + const rpc = createServer({ + // base: import.meta.url, + // beforeOne: function (ctx: any, key: string) { + // console.log(ctx.path); + // console.log(ctx.method); + // console.log('beforeOne key=' + key); + // }, + }); + + console.dir(rpc); + + // const mw = await loadBuildinMiddlewaire(rpc); + + // rpc[load].push([someMw]) + // mount with lifecycle + + // await loadCustomMiddlewaire(rpc); + + // console.dir(mount); + // if (cfg.mount) { + // rpc.base = import.meta.url; + // // await mount(rpc, './fn'); + // } + + return Object.assign(rpc, { + start: function () { + if (cfg.debug) { + rpc.dump(); + } + rpc.listen(cfg.port); + }, + }); +} diff --git a/packages/app/src/load.ts b/packages/app/src/load.ts new file mode 100644 index 0000000..381264d --- /dev/null +++ b/packages/app/src/load.ts @@ -0,0 +1,21 @@ +import * as mw from './mw'; + +export async function loadCustomMiddlewaire(rpc?, m?) { + loadMiddleware(rpc, 'load', m); +} + +export async function loadBuildinMiddlewaire(rpc?) { + const buildin = rpc.config.buildin; + for (const key in buildin) { + Object.keys(mw).forEach(function (i) { + console.dir(mw[i]); + const m = mw[i]; + + if (key['enable'] && key === i) loadMiddleware(rpc, m.lifeCycle, m); + }); + } +} + +export async function loadMiddleware(rpc, lifeCycle, mw) { + rpc.hooks[lifeCycle].push(mw); +} diff --git a/packages/app/src/mount.ts b/packages/app/src/mount.ts deleted file mode 100644 index b323636..0000000 --- a/packages/app/src/mount.ts +++ /dev/null @@ -1,18 +0,0 @@ -// import importDir, { join } from '@tomrpc/import-dir'; -// import debug from 'debug'; -// import { flatten } from 'flat'; - -// const log = debug('@tomrpc/mount'); - -// // {a:{a:1, b:2}} -// // {a.b:2, a.a:1} -// // a.b => /a/b + function - -export default async (base, dir) => { - // const files = await importDir(join(base, dir), { - // recurse: true, - // extensions: ['.ts', '.js', '.json'], - // }); - // log(files); - // return flatten(files); -}; diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts new file mode 100644 index 0000000..d6af7cd --- /dev/null +++ b/packages/app/src/mw/cors.ts @@ -0,0 +1,7 @@ +export const cors = { + name: '', + lifeCycle: 'load', + mw: async (ctx: any, next: any) => { + await next(); + }, +}; diff --git a/packages/app/src/mw/index.ts b/packages/app/src/mw/index.ts new file mode 100644 index 0000000..e716b0a --- /dev/null +++ b/packages/app/src/mw/index.ts @@ -0,0 +1,4 @@ +export * from './cors'; +export * from './serve'; +export * from './jwt'; +export * from './view'; diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts new file mode 100644 index 0000000..cdc86db --- /dev/null +++ b/packages/app/src/mw/jwt.ts @@ -0,0 +1,7 @@ +export const jwt = { + name: '', + lifeCycle: 'load', + mw: async (ctx: any, next: any) => { + await next(); + }, +}; diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts new file mode 100644 index 0000000..5633862 --- /dev/null +++ b/packages/app/src/mw/serve.ts @@ -0,0 +1,7 @@ +export const serve = { + name: '', + lifeCycle: 'load', + mw: async (ctx: any, next: any) => { + await next(); + }, +}; diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts new file mode 100644 index 0000000..18b803d --- /dev/null +++ b/packages/app/src/mw/view.ts @@ -0,0 +1,7 @@ +export const view = { + name: '', + lifeCycle: 'load', + mw: async (ctx: any, next: any) => { + await next(); + }, +}; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2cf4443..5795006 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -11,6 +11,48 @@ export const lib = () => 'lib'; const log = debug('@tomrpc/core'); export const LifeCycleConfig = { + hooks: { + before: [], + load: [], + beforeMount: [], + afterMount: [], + after: [], + }, + before: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.before; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + load: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.load; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + after: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.after; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + beforeMount: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.beforeMount; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + afterMount: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.afterMount; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, beforeAll: async (ctx, next) => { log('beforeAll'); await next(); @@ -41,19 +83,33 @@ export const LifeCycleConfig = { export const createServer = function (config?: any) { const _cfg = Object.assign(LifeCycleConfig, config); + + // 在app时用 + this.config = _cfg; + this.base = _cfg.base; + const app = new Koa(); + app.use(bodyParser()); + + this.app = app; + this.use = app.use; + // app.use(_cfg.beforeAll); - app.use(bodyParser()); + + _cfg.before(this); + _cfg.load(this); return Object.assign(this, { rpcFunctions: {}, - app: app, - use: app.use, _mounted: false, listen: function (port?: number) { + _cfg.beforeMount(this); this.mount(); + _cfg.afterMount(this); + _cfg.after(this); app.use(_cfg.afterAll); + this.app.listen(port || 3000); }, add: function (items) { From b47f1568ccbe8901e1f4b154995719f3c378dcda Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sat, 28 Oct 2023 13:12:23 +0800 Subject: [PATCH 005/101] fix: make serve done --- packages/app/app.ts | 4 +++- packages/app/public/a.json | 3 +++ packages/app/src/index.ts | 32 ++++++++++++++++++++------------ packages/app/src/load.ts | 19 ++++++++++++------- packages/app/src/mw/cors.ts | 2 +- packages/app/src/mw/jwt.ts | 2 +- packages/app/src/mw/serve.ts | 9 ++++++--- packages/app/src/mw/view.ts | 2 +- packages/core/src/index.ts | 4 +++- 9 files changed, 50 insertions(+), 27 deletions(-) create mode 100644 packages/app/public/a.json diff --git a/packages/app/app.ts b/packages/app/app.ts index afb5724..2994a64 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -1,3 +1,5 @@ +import { dirname, filename, join } from 'desm'; + import { createApp } from './src/index'; (async () => { @@ -8,7 +10,7 @@ import { createApp } from './src/index'; debug: false, // mount?: './fn''; buildin: { - static: { enable: true }, + serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, }, }); diff --git a/packages/app/public/a.json b/packages/app/public/a.json new file mode 100644 index 0000000..83af786 --- /dev/null +++ b/packages/app/public/a.json @@ -0,0 +1,3 @@ +{ + "a": 123 +} diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index adfbbd9..80e9c15 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -21,6 +21,11 @@ const log = debug('@tomrpc/mount'); // debug: true // logLevel: // } +interface IServe { + enable?: boolean | false; + root: string; + opts: object; +} interface IConfig { name: string | 'tomapp'; base?: string; @@ -28,7 +33,7 @@ interface IConfig { debug?: boolean | false; mount?: string; buildin: { - static?: { enable: true }; + serve?: IServe; cors?: { enable: true }; view?: { enable: true }; jwt?: { enable: true }; @@ -36,18 +41,21 @@ interface IConfig { } export async function createApp(cfg: IConfig) { - const rpc = createServer({ - // base: import.meta.url, - // beforeOne: function (ctx: any, key: string) { - // console.log(ctx.path); - // console.log(ctx.method); - // console.log('beforeOne key=' + key); - // }, - }); - - console.dir(rpc); + const rpc = createServer( + Object.assign( + { + base: import.meta.url, + beforeOne: function (ctx: any, key: string) { + console.log(ctx.path); + console.log(ctx.method); + console.log('beforeOne key=' + key); + }, + }, + cfg + ) + ); - // const mw = await loadBuildinMiddlewaire(rpc); + await loadBuildinMiddlewaire(rpc); // rpc[load].push([someMw]) // mount with lifecycle diff --git a/packages/app/src/load.ts b/packages/app/src/load.ts index 381264d..b6783ef 100644 --- a/packages/app/src/load.ts +++ b/packages/app/src/load.ts @@ -6,16 +6,21 @@ export async function loadCustomMiddlewaire(rpc?, m?) { export async function loadBuildinMiddlewaire(rpc?) { const buildin = rpc.config.buildin; + // console.dir(rpc.config); + // console.dir(buildin); for (const key in buildin) { - Object.keys(mw).forEach(function (i) { - console.dir(mw[i]); - const m = mw[i]; - - if (key['enable'] && key === i) loadMiddleware(rpc, m.lifeCycle, m); - }); + const m = buildin[key]; + console.dir(m); + if (m['enable'] === true) { + // console.dir(buildin[key]); + const _m = mw[key]; + console.dir(_m); + console.dir(_m.lifeCycle); + loadMiddleware(rpc, _m.lifeCycle, _m.mw(m)); + } } } export async function loadMiddleware(rpc, lifeCycle, mw) { - rpc.hooks[lifeCycle].push(mw); + rpc.config.hooks[lifeCycle].push(mw); } diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts index d6af7cd..38f1f11 100644 --- a/packages/app/src/mw/cors.ts +++ b/packages/app/src/mw/cors.ts @@ -1,5 +1,5 @@ export const cors = { - name: '', + name: 'cors', lifeCycle: 'load', mw: async (ctx: any, next: any) => { await next(); diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index cdc86db..4938989 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -1,5 +1,5 @@ export const jwt = { - name: '', + name: 'jwt', lifeCycle: 'load', mw: async (ctx: any, next: any) => { await next(); diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts index 5633862..3f29981 100644 --- a/packages/app/src/mw/serve.ts +++ b/packages/app/src/mw/serve.ts @@ -1,7 +1,10 @@ +import serveMiddleware from 'koa-static'; + export const serve = { - name: '', + name: 'serve', lifeCycle: 'load', - mw: async (ctx: any, next: any) => { - await next(); + mw: (opts) => { + console.dir(opts); + return serveMiddleware(opts.root, opts); }, }; diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts index 18b803d..7a0c31c 100644 --- a/packages/app/src/mw/view.ts +++ b/packages/app/src/mw/view.ts @@ -1,5 +1,5 @@ export const view = { - name: '', + name: 'view', lifeCycle: 'load', mw: async (ctx: any, next: any) => { await next(); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 5795006..c1b1239 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -28,6 +28,7 @@ export const LifeCycleConfig = { load: async (server) => { const app = server.app; const loadMiddlewares = server.config.hooks.load; + console.dir(loadMiddlewares); loadMiddlewares.forEach((mw) => { app.use(mw); }); @@ -98,12 +99,13 @@ export const createServer = function (config?: any) { app.use(_cfg.beforeAll); _cfg.before(this); - _cfg.load(this); return Object.assign(this, { rpcFunctions: {}, _mounted: false, listen: function (port?: number) { + _cfg.load(this); + _cfg.beforeMount(this); this.mount(); _cfg.afterMount(this); From 48c026fd236a918058026a3825d2391539ad8da6 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sat, 28 Oct 2023 13:22:01 +0800 Subject: [PATCH 006/101] fix: make cors done --- packages/app/app.ts | 1 + packages/app/package.json | 5 +++-- packages/app/src/mw/cors.ts | 7 +++++-- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index 2994a64..2e7501d 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -11,6 +11,7 @@ import { createApp } from './src/index'; // mount?: './fn''; buildin: { serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, + cors: { enable: true }, }, }); diff --git a/packages/app/package.json b/packages/app/package.json index 560c1f7..2c42c2f 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -27,10 +27,11 @@ ], "devDependencies": { "@vitest/coverage-v8": "^0.34.6", - "vitest": "^0.34.6", - "happy-dom": "^6.0.4" + "happy-dom": "^6.0.4", + "vitest": "^0.34.6" }, "dependencies": { + "@koa/cors": "^4.0.0", "@tomrpc/client": "^1.0.0", "@tomrpc/core": "^1.0.0", "@tomrpc/mount": "^1.0.0", diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts index 38f1f11..e53f85c 100644 --- a/packages/app/src/mw/cors.ts +++ b/packages/app/src/mw/cors.ts @@ -1,7 +1,10 @@ +import corsMiddleware from '@koa/cors'; + export const cors = { name: 'cors', lifeCycle: 'load', - mw: async (ctx: any, next: any) => { - await next(); + mw: (opts = {}) => { + console.dir(opts); + return corsMiddleware(opts); }, }; From 3b290885e3e86d4ec75c69e6328579abace18bd1 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sat, 28 Oct 2023 13:23:34 +0800 Subject: [PATCH 007/101] fix: make cors done --- packages/app/src/load.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/packages/app/src/load.ts b/packages/app/src/load.ts index b6783ef..2823ba7 100644 --- a/packages/app/src/load.ts +++ b/packages/app/src/load.ts @@ -1,5 +1,3 @@ -import * as mw from './mw'; - export async function loadCustomMiddlewaire(rpc?, m?) { loadMiddleware(rpc, 'load', m); } @@ -8,6 +6,7 @@ export async function loadBuildinMiddlewaire(rpc?) { const buildin = rpc.config.buildin; // console.dir(rpc.config); // console.dir(buildin); + const mw = await import('./mw'); for (const key in buildin) { const m = buildin[key]; console.dir(m); From 8daa498b72efb9c0c7be74d0a8fce4f16e885a76 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sun, 29 Oct 2023 01:02:19 +0800 Subject: [PATCH 008/101] feat: add init with ctx.jwt --- packages/app/app.ts | 6 +++++- packages/app/package.json | 1 + packages/app/src/index.ts | 7 +++++-- packages/app/src/init.ts | 5 +++++ packages/app/src/load.ts | 22 ++++++++++++++++------ packages/app/src/mw/cors.ts | 2 +- packages/app/src/mw/serve.ts | 2 +- packages/core/package.json | 4 ++-- packages/core/src/index.ts | 15 ++++++++++++++- 9 files changed, 50 insertions(+), 14 deletions(-) create mode 100644 packages/app/src/init.ts diff --git a/packages/app/app.ts b/packages/app/app.ts index 2e7501d..b67d725 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -6,13 +6,17 @@ import { createApp } from './src/index'; const rpc = await createApp({ name: 'tomapp', base: import.meta.url, - port: 3000, + port: 3001, debug: false, // mount?: './fn''; buildin: { serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, cors: { enable: true }, }, + beforeAll: async (ctx, next) => { + console.dir(ctx.jwt); + await next(); + }, }); rpc.fn('a', function (a) { diff --git a/packages/app/package.json b/packages/app/package.json index 2c42c2f..1ac5922 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -40,6 +40,7 @@ "flat": "^6.0.1", "jsonwebtoken": "^9.0.2", "koa-cors": "^0.0.16", + "koa-jwt": "^4.0.4", "koa-static": "^5.0.0", "koa-views": "^8.0.0" } diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 80e9c15..4897c01 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -2,9 +2,10 @@ import { createServer } from '@tomrpc/core'; import mount from '@tomrpc/mount'; import debug from 'debug'; -import { loadBuildinMiddlewaire, loadCustomMiddlewaire } from './load'; +import { init } from './init'; +import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; -const log = debug('@tomrpc/mount'); +const log = debug('@tomrpc/app'); // { // name:'hi' @@ -38,6 +39,7 @@ interface IConfig { view?: { enable: true }; jwt?: { enable: true }; }; + beforeAll: any; } export async function createApp(cfg: IConfig) { @@ -55,6 +57,7 @@ export async function createApp(cfg: IConfig) { ) ); + await loadInitMiddleware(rpc, init); await loadBuildinMiddlewaire(rpc); // rpc[load].push([someMw]) diff --git a/packages/app/src/init.ts b/packages/app/src/init.ts new file mode 100644 index 0000000..52cf95b --- /dev/null +++ b/packages/app/src/init.ts @@ -0,0 +1,5 @@ +import jsonwebtoken from 'jsonwebtoken'; +export const init = async function (ctx, next) { + ctx.jwt = jsonwebtoken; + await next(); +}; diff --git a/packages/app/src/load.ts b/packages/app/src/load.ts index 2823ba7..ac793ea 100644 --- a/packages/app/src/load.ts +++ b/packages/app/src/load.ts @@ -1,25 +1,35 @@ +import debug from 'debug'; + +const log = debug('@tomrpc/app'); + export async function loadCustomMiddlewaire(rpc?, m?) { loadMiddleware(rpc, 'load', m); } +export async function loadInitMiddleware(rpc?, m?) { + // console.dir(m); + loadMiddleware(rpc, 'init', m); +} export async function loadBuildinMiddlewaire(rpc?) { const buildin = rpc.config.buildin; - // console.dir(rpc.config); - // console.dir(buildin); + log(rpc.config); + log(buildin); const mw = await import('./mw'); for (const key in buildin) { const m = buildin[key]; - console.dir(m); + log(m); if (m['enable'] === true) { - // console.dir(buildin[key]); + log(buildin[key]); const _m = mw[key]; - console.dir(_m); - console.dir(_m.lifeCycle); + log(_m); + log(_m.lifeCycle); loadMiddleware(rpc, _m.lifeCycle, _m.mw(m)); } } } export async function loadMiddleware(rpc, lifeCycle, mw) { + console.dir(lifeCycle); + console.dir(mw); rpc.config.hooks[lifeCycle].push(mw); } diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts index e53f85c..a75d3c9 100644 --- a/packages/app/src/mw/cors.ts +++ b/packages/app/src/mw/cors.ts @@ -4,7 +4,7 @@ export const cors = { name: 'cors', lifeCycle: 'load', mw: (opts = {}) => { - console.dir(opts); + // console.dir(opts); return corsMiddleware(opts); }, }; diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts index 3f29981..b3fa65f 100644 --- a/packages/app/src/mw/serve.ts +++ b/packages/app/src/mw/serve.ts @@ -4,7 +4,7 @@ export const serve = { name: 'serve', lifeCycle: 'load', mw: (opts) => { - console.dir(opts); + // console.dir(opts); return serveMiddleware(opts.root, opts); }, }; diff --git a/packages/core/package.json b/packages/core/package.json index 05bd32d..508928b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -26,10 +26,10 @@ ], "devDependencies": { "@types/koa": "^2.13.10", - "vitest": "^0.34.6", "@vitest/coverage-v8": "^0.34.6", "happy-dom": "^6.0.4", - "supertest": "^6.3.3" + "supertest": "^6.3.3", + "vitest": "^0.34.6" }, "dependencies": { "@koa/bodyparser": "^5.0.0", diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c1b1239..a28e271 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -12,12 +12,21 @@ const log = debug('@tomrpc/core'); export const LifeCycleConfig = { hooks: { + init: [], before: [], load: [], beforeMount: [], afterMount: [], after: [], }, + init: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.init; + console.log(loadMiddlewares); + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, before: async (server) => { const app = server.app; const loadMiddlewares = server.config.hooks.before; @@ -28,7 +37,7 @@ export const LifeCycleConfig = { load: async (server) => { const app = server.app; const loadMiddlewares = server.config.hooks.load; - console.dir(loadMiddlewares); + console.log(loadMiddlewares); loadMiddlewares.forEach((mw) => { app.use(mw); }); @@ -104,6 +113,8 @@ export const createServer = function (config?: any) { rpcFunctions: {}, _mounted: false, listen: function (port?: number) { + _cfg.init(this); + _cfg.load(this); _cfg.beforeMount(this); @@ -140,6 +151,8 @@ export const createServer = function (config?: any) { const key = ctx.path.replace('/', '').split('/').join('.'); _cfg.beforeOne(ctx, key); + console.dir(ctx.jwt); + const lastKey = key.split('.').pop(); const httpMethods = getHttpMethods(); From 014108167261fe327a267f785c9739e4a08e064b Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sun, 29 Oct 2023 01:11:48 +0800 Subject: [PATCH 009/101] feat: add init with ctx.jwt --- packages/app/src/load.ts | 4 ++-- packages/app/src/mw/jwt.ts | 7 +++++-- packages/core/src/index.ts | 2 -- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/app/src/load.ts b/packages/app/src/load.ts index ac793ea..1c1ea1b 100644 --- a/packages/app/src/load.ts +++ b/packages/app/src/load.ts @@ -29,7 +29,7 @@ export async function loadBuildinMiddlewaire(rpc?) { } export async function loadMiddleware(rpc, lifeCycle, mw) { - console.dir(lifeCycle); - console.dir(mw); + log(lifeCycle); + log(mw); rpc.config.hooks[lifeCycle].push(mw); } diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index 4938989..0b883d3 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -1,7 +1,10 @@ +import koajwt from 'koa-jwt'; + export const jwt = { name: 'jwt', lifeCycle: 'load', - mw: async (ctx: any, next: any) => { - await next(); + mw: (opts) => { + // console.dir(opts); + return koajwt(opts); }, }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a28e271..317bf99 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -151,8 +151,6 @@ export const createServer = function (config?: any) { const key = ctx.path.replace('/', '').split('/').join('.'); _cfg.beforeOne(ctx, key); - console.dir(ctx.jwt); - const lastKey = key.split('.').pop(); const httpMethods = getHttpMethods(); From 958c93a34df19c3b562a64eef932ea54985af9bd Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sun, 29 Oct 2023 11:01:43 +0800 Subject: [PATCH 010/101] feat: add view,but need make view & fn plugable --- packages/app/app.ts | 22 ++++++++++++++++++++-- packages/app/package.json | 1 + packages/app/src/index.ts | 24 ++++++++++++++++++++---- packages/app/src/mw/cors.ts | 4 ++-- packages/app/src/mw/jwt.ts | 2 +- packages/app/src/mw/view.ts | 7 +++++-- packages/app/view/user.html | 3 +++ 7 files changed, 52 insertions(+), 11 deletions(-) create mode 100644 packages/app/view/user.html diff --git a/packages/app/app.ts b/packages/app/app.ts index b67d725..375cd7c 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -12,15 +12,33 @@ import { createApp } from './src/index'; buildin: { serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, cors: { enable: true }, + jwt: { + enable: true, + secret: 'shhhhhh', + debug: true, + unless: ['/public', '/a'], + }, + view: { + enable: true, + root: join(import.meta.url, '.', 'view'), + opts: { + map: { + html: 'ejs', + }, + }, + }, }, beforeAll: async (ctx, next) => { - console.dir(ctx.jwt); + // console.dir(ctx.jwt); await next(); }, }); + // rpc.view vs rpc.fn变成插件 rpc.fn('a', function (a) { - return a; + console.dir(this.render); + // this.render('user', { user: { name: 'alfred' } }); + return { a: a }; }); rpc.start(); diff --git a/packages/app/package.json b/packages/app/package.json index 1ac5922..095881d 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -37,6 +37,7 @@ "@tomrpc/mount": "^1.0.0", "debug": "^4.3.4", "desm": "^1.3.0", + "ejs": "^3.1.9", "flat": "^6.0.1", "jsonwebtoken": "^9.0.2", "koa-cors": "^0.0.16", diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 4897c01..c984386 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -22,10 +22,26 @@ const log = debug('@tomrpc/app'); // debug: true // logLevel: // } +interface ICors { + enable?: boolean | false; + opts?: object; +} interface IServe { enable?: boolean | false; root: string; - opts: object; + opts?: object; +} +interface IView { + enable?: boolean | false; + root: string; + opts?: object; +} +interface IJwt { + enable?: boolean | false; + secret?: string; + issuer?: string; + debug: boolean; + unless?: Array; } interface IConfig { name: string | 'tomapp'; @@ -35,9 +51,9 @@ interface IConfig { mount?: string; buildin: { serve?: IServe; - cors?: { enable: true }; - view?: { enable: true }; - jwt?: { enable: true }; + cors?: ICors; + view?: IView; + jwt?: IJwt; }; beforeAll: any; } diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts index a75d3c9..86243eb 100644 --- a/packages/app/src/mw/cors.ts +++ b/packages/app/src/mw/cors.ts @@ -3,8 +3,8 @@ import corsMiddleware from '@koa/cors'; export const cors = { name: 'cors', lifeCycle: 'load', - mw: (opts = {}) => { + mw: (cfg = { opts: {} }) => { // console.dir(opts); - return corsMiddleware(opts); + return corsMiddleware(cfg.opts); }, }; diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index 0b883d3..5a5d830 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -5,6 +5,6 @@ export const jwt = { lifeCycle: 'load', mw: (opts) => { // console.dir(opts); - return koajwt(opts); + return koajwt(opts).unless({ path: opts.unless }); }, }; diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts index 7a0c31c..cc43f1e 100644 --- a/packages/app/src/mw/view.ts +++ b/packages/app/src/mw/view.ts @@ -1,7 +1,10 @@ +import views from 'koa-views'; + export const view = { name: 'view', lifeCycle: 'load', - mw: async (ctx: any, next: any) => { - await next(); + mw: (cfg) => { + // console.dir(opts); + return views(cfg.root, cfg.opts); }, }; diff --git a/packages/app/view/user.html b/packages/app/view/user.html new file mode 100644 index 0000000..f824178 --- /dev/null +++ b/packages/app/view/user.html @@ -0,0 +1,3 @@ +<% if (user) { %> +

<%= user.name %>

+<% } %> From a62861cef804d839ad03b3fe24993d1644839fde Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 30 Oct 2023 21:25:06 +0800 Subject: [PATCH 011/101] feat: init core2 code & design --- packages/core2/CHANGELOG.md | 13 + packages/core2/README.md | 109 +++ packages/core2/package-lock.json | 988 +++++++++++++++++++++ packages/core2/package.json | 41 + packages/core2/src/__tests__/index.test.ts | 42 + packages/core2/src/core.ts | 31 + packages/core2/src/index.ts | 209 +++++ packages/core2/src/utils.ts | 38 + packages/core2/tsconfig.json | 8 + packages/core2/tsup.config.cjs | 12 + packages/core2/vitest.config.cjs | 10 + 11 files changed, 1501 insertions(+) create mode 100644 packages/core2/CHANGELOG.md create mode 100644 packages/core2/README.md create mode 100644 packages/core2/package-lock.json create mode 100644 packages/core2/package.json create mode 100644 packages/core2/src/__tests__/index.test.ts create mode 100644 packages/core2/src/core.ts create mode 100644 packages/core2/src/index.ts create mode 100644 packages/core2/src/utils.ts create mode 100644 packages/core2/tsconfig.json create mode 100644 packages/core2/tsup.config.cjs create mode 100644 packages/core2/vitest.config.cjs diff --git a/packages/core2/CHANGELOG.md b/packages/core2/CHANGELOG.md new file mode 100644 index 0000000..fcf2e5b --- /dev/null +++ b/packages/core2/CHANGELOG.md @@ -0,0 +1,13 @@ +# @tomrpc/core + +## 1.0.0 + +### Major Changes + +- v0.1.1 + +## 0.1.1 + +### Patch Changes + +- init diff --git a/packages/core2/README.md b/packages/core2/README.md new file mode 100644 index 0000000..6d80dda --- /dev/null +++ b/packages/core2/README.md @@ -0,0 +1,109 @@ +# @tomrpc/core + +## create + +```js +const rpc = createServer({ + beforeOne: function (ctx: any, key: string) { + console.log(ctx.path); + console.log(ctx.method); + console.log('beforeOne key=' + key); + }, +}); + +``` + +## lifecyle + +- beforeAll(中间件) + - beforeEach(中间件) + - beforeOne(普通函数) + - 函数执行 + - afterOne(普通函数) + - afterEach(中间件) +- afterAll(中间件) + +## example + +```js +import { createServer } from '@tomrpc/core'; + +const rpc = createServer({ + beforeOne: function (ctx: any, key: string) { + console.log(ctx.path); + console.log(ctx.method); + console.log('beforeOne key=' + key); + }, +}); + +rpc.fn('a', (a: string) => { + return a; +}); + +rpc.fn('a.a', (a: string, ctx: any) => { + // console.dir(ctx); + if (ctx.method === 'POST') { + console.dir('post'); + return { + a: a, + // b: b, + }; + } else { + console.dir('get' + ctx.method); + return a; + } +}); + +rpc.fn('b', () => { + console.dir('test b'); +}); + +rpc.add({ + c: (a: string) => { + return a; + }, + a: function (a: string, b: string) { + return `${this.path} , ${a} c2 ${b}`; + }, +}); + +// https://bobbyhadz.com/blog/typescript-no-overload-matches-this-call +// rpc.dump(); +// console.dir(rpc.dump()); + +// rpc.mount(); + +rpc.listen(3000); +``` + + +const app = new Koa() + + +const app1 = new Koa() +const app2 = new Koa() +const app3 = new Koa() + +app.mount(app1.prefix,fn) +app.mount(app2.prefix,view) +app.mount(app3.prefix,static) + +=> + +const app = new Koa() + + + +app.plugin({ + prefix, + fn +}) + +return fn={ + name='fn' + init:[], + load:[] + +} +app.plugin(app2.prefix,view) +app.plugin(app3.prefix,static) diff --git a/packages/core2/package-lock.json b/packages/core2/package-lock.json new file mode 100644 index 0000000..b2c9859 --- /dev/null +++ b/packages/core2/package-lock.json @@ -0,0 +1,988 @@ +{ + "name": "@httprpc/core", + "version": "0.0.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "@httprpc/core", + "version": "0.0.1", + "license": "MIT", + "dependencies": { + "@koa/bodyparser": "^5.0.0", + "debug": "^4.3.4", + "koa": "^2.14.2" + }, + "devDependencies": { + "vitest": "^0.34.6", + "@vitest/coverage-v8": "^0.34.6", + "happy-dom": "^6.0.4", + "supertest": "^6.3.3" + } + }, + "../../node_modules/.pnpm/@vitest+coverage-v8@0.34.2/node_modules/@vitest/coverage-v8": { + "version": "0.34.2", + "dev": true, + "license": "MIT", + "dependencies": { + "@ampproject/remapping": "^2.2.1", + "@bcoe/v8-coverage": "^0.2.3", + "istanbul-lib-coverage": "^3.2.0", + "istanbul-lib-report": "^3.0.1", + "istanbul-lib-source-maps": "^4.0.1", + "istanbul-reports": "^3.1.5", + "magic-string": "^0.30.1", + "picocolors": "^1.0.0", + "std-env": "^3.3.3", + "test-exclude": "^6.0.0", + "v8-to-istanbul": "^9.1.0" + }, + "devDependencies": { + "@types/istanbul-lib-coverage": "^2.0.4", + "@types/istanbul-lib-report": "^3.0.0", + "@types/istanbul-lib-source-maps": "^4.0.1", + "@types/istanbul-reports": "^3.0.1", + "pathe": "^1.1.1", + "vite-node": "0.34.2", + "vitest": "0.34.2" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "vitest": ">=0.32.0 <1" + } + }, + "../../node_modules/.pnpm/happy-dom@6.0.4/node_modules/happy-dom": { + "version": "6.0.4", + "dev": true, + "license": "MIT", + "dependencies": { + "css.escape": "^1.5.1", + "he": "^1.2.0", + "node-fetch": "^2.x.x", + "sync-request": "^6.1.0", + "webidl-conversions": "^7.0.0", + "whatwg-encoding": "^2.0.0", + "whatwg-mimetype": "^3.0.0" + }, + "devDependencies": { + "@types/he": "^1.1.2", + "@types/jest": "^27.4.1", + "@types/node": "^15.6.0", + "@types/node-fetch": "^2.6.1", + "@typescript-eslint/eslint-plugin": "^5.16.0", + "@typescript-eslint/parser": "^5.16.0", + "eslint": "^8.11.0", + "eslint-config-prettier": "^8.5.0", + "eslint-plugin-filenames": "^1.3.2", + "eslint-plugin-import": "^2.25.4", + "eslint-plugin-jest": "^26.1.2", + "eslint-plugin-jsdoc": "^38.0.6", + "eslint-plugin-json": "^3.1.0", + "eslint-plugin-prettier": "^4.0.0", + "jest": "^27.5.1", + "prettier": "^2.6.0", + "ts-jest": "^27.1.3", + "typescript": "^4.6.2" + } + }, + "node_modules/@koa/bodyparser": { + "version": "5.0.0", + "resolved": "http://bnpm.byted.org/@koa/bodyparser/-/bodyparser-5.0.0.tgz", + "integrity": "sha512-JEiZVe2e85qPOqA+Nw/SJC5fkFw3XSekh0RSoqz5F6lFYuhEspgqAb972rQRCJesv27QUsz96vU/Vb92wF1GUg==", + "license": "MIT", + "dependencies": { + "co-body": "^6.1.0", + "lodash.merge": "^4.6.2", + "type-is": "^1.6.18" + }, + "engines": { + "node": ">= 16" + } + }, + "node_modules/@vitest/coverage-v8": { + "resolved": "../../node_modules/.pnpm/@vitest+coverage-v8@0.34.2/node_modules/@vitest/coverage-v8", + "link": true + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "http://bnpm.byted.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/asap": { + "version": "2.0.6", + "resolved": "http://bnpm.byted.org/asap/-/asap-2.0.6.tgz", + "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", + "dev": true, + "license": "MIT" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "http://bnpm.byted.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "http://bnpm.byted.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/cache-content-type": { + "version": "1.0.1", + "resolved": "http://bnpm.byted.org/cache-content-type/-/cache-content-type-1.0.1.tgz", + "integrity": "sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==", + "license": "MIT", + "dependencies": { + "mime-types": "^2.1.18", + "ylru": "^1.2.0" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/call-bind": { + "version": "1.0.2", + "resolved": "http://bnpm.byted.org/call-bind/-/call-bind-1.0.2.tgz", + "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.1", + "get-intrinsic": "^1.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/co": { + "version": "4.6.0", + "resolved": "http://bnpm.byted.org/co/-/co-4.6.0.tgz", + "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", + "license": "MIT", + "engines": { + "iojs": ">= 1.0.0", + "node": ">= 0.12.0" + } + }, + "node_modules/co-body": { + "version": "6.1.0", + "resolved": "http://bnpm.byted.org/co-body/-/co-body-6.1.0.tgz", + "integrity": "sha512-m7pOT6CdLN7FuXUcpuz/8lfQ/L77x8SchHCF4G0RBTJO20Wzmhn5Sp4/5WsKy8OSpifBSUrmg83qEqaDHdyFuQ==", + "license": "MIT", + "dependencies": { + "inflation": "^2.0.0", + "qs": "^6.5.2", + "raw-body": "^2.3.3", + "type-is": "^1.6.16" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "http://bnpm.byted.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/component-emitter": { + "version": "1.3.0", + "resolved": "http://bnpm.byted.org/component-emitter/-/component-emitter-1.3.0.tgz", + "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", + "dev": true, + "license": "MIT" + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "http://bnpm.byted.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "license": "MIT", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "http://bnpm.byted.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookiejar": { + "version": "2.1.4", + "resolved": "http://bnpm.byted.org/cookiejar/-/cookiejar-2.1.4.tgz", + "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", + "dev": true, + "license": "MIT" + }, + "node_modules/cookies": { + "version": "0.8.0", + "resolved": "http://bnpm.byted.org/cookies/-/cookies-0.8.0.tgz", + "integrity": "sha512-8aPsApQfebXnuI+537McwYsDtjVxGm8gTIzQI3FDW6t5t/DAhERxtnbEPN/8RX+uZthoz4eCOgloXaE5cYyNow==", + "license": "MIT", + "dependencies": { + "depd": "~2.0.0", + "keygrip": "~1.1.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "http://bnpm.byted.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-equal": { + "version": "1.0.1", + "resolved": "http://bnpm.byted.org/deep-equal/-/deep-equal-1.0.1.tgz", + "integrity": "sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw==", + "license": "MIT" + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "http://bnpm.byted.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/delegates": { + "version": "1.0.0", + "resolved": "http://bnpm.byted.org/delegates/-/delegates-1.0.0.tgz", + "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", + "license": "MIT" + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "http://bnpm.byted.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "http://bnpm.byted.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "license": "MIT", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/dezalgo": { + "version": "1.0.4", + "resolved": "http://bnpm.byted.org/dezalgo/-/dezalgo-1.0.4.tgz", + "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", + "dev": true, + "license": "ISC", + "dependencies": { + "asap": "^2.0.0", + "wrappy": "1" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "http://bnpm.byted.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", + "license": "MIT" + }, + "node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "http://bnpm.byted.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "resolved": "http://bnpm.byted.org/escape-html/-/escape-html-1.0.3.tgz", + "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", + "license": "MIT" + }, + "node_modules/fast-safe-stringify": { + "version": "2.1.1", + "resolved": "http://bnpm.byted.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", + "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", + "dev": true, + "license": "MIT" + }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "http://bnpm.byted.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dev": true, + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/formidable": { + "version": "2.1.2", + "resolved": "http://bnpm.byted.org/formidable/-/formidable-2.1.2.tgz", + "integrity": "sha512-CM3GuJ57US06mlpQ47YcunuUZ9jpm8Vx+P2CGt2j7HpgkKZO/DJYQ0Bobim8G6PFQmK5lOqOOdUXboU+h73A4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dezalgo": "^1.0.4", + "hexoid": "^1.0.0", + "once": "^1.4.0", + "qs": "^6.11.0" + }, + "funding": { + "url": "https://ko-fi.com/tunnckoCore/commissions" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "http://bnpm.byted.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/function-bind": { + "version": "1.1.1", + "resolved": "http://bnpm.byted.org/function-bind/-/function-bind-1.1.1.tgz", + "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", + "license": "MIT" + }, + "node_modules/get-intrinsic": { + "version": "1.2.1", + "resolved": "http://bnpm.byted.org/get-intrinsic/-/get-intrinsic-1.2.1.tgz", + "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.1", + "has": "^1.0.3", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/happy-dom": { + "resolved": "../../node_modules/.pnpm/happy-dom@6.0.4/node_modules/happy-dom", + "link": true + }, + "node_modules/has": { + "version": "1.0.3", + "resolved": "http://bnpm.byted.org/has/-/has-1.0.3.tgz", + "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.1" + }, + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/has-proto": { + "version": "1.0.1", + "resolved": "http://bnpm.byted.org/has-proto/-/has-proto-1.0.1.tgz", + "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "resolved": "http://bnpm.byted.org/has-symbols/-/has-symbols-1.0.3.tgz", + "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.0", + "resolved": "http://bnpm.byted.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", + "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hexoid": { + "version": "1.0.0", + "resolved": "http://bnpm.byted.org/hexoid/-/hexoid-1.0.0.tgz", + "integrity": "sha512-QFLV0taWQOZtvIRIAdBChesmogZrtuXvVWsFHZTk2SU+anspqZ2vMnoLg7IE1+Uk16N19APic1BuF8bC8c2m5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/http-assert": { + "version": "1.5.0", + "resolved": "http://bnpm.byted.org/http-assert/-/http-assert-1.5.0.tgz", + "integrity": "sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==", + "license": "MIT", + "dependencies": { + "deep-equal": "~1.0.1", + "http-errors": "~1.8.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-errors": { + "version": "1.8.1", + "resolved": "http://bnpm.byted.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", + "license": "MIT", + "dependencies": { + "depd": "~1.1.2", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/http-errors/node_modules/depd": { + "version": "1.1.2", + "resolved": "http://bnpm.byted.org/depd/-/depd-1.1.2.tgz", + "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "http://bnpm.byted.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/inflation": { + "version": "2.0.0", + "resolved": "http://bnpm.byted.org/inflation/-/inflation-2.0.0.tgz", + "integrity": "sha512-m3xv4hJYR2oXw4o4Y5l6P5P16WYmazYof+el6Al3f+YlggGj6qT9kImBAnzDelRALnP5d3h4jGBPKzYCizjZZw==", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "http://bnpm.byted.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/is-generator-function": { + "version": "1.0.10", + "resolved": "http://bnpm.byted.org/is-generator-function/-/is-generator-function-1.0.10.tgz", + "integrity": "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==", + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/keygrip": { + "version": "1.1.0", + "resolved": "http://bnpm.byted.org/keygrip/-/keygrip-1.1.0.tgz", + "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", + "license": "MIT", + "dependencies": { + "tsscmp": "1.0.6" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/koa": { + "version": "2.14.2", + "resolved": "http://bnpm.byted.org/koa/-/koa-2.14.2.tgz", + "integrity": "sha512-VFI2bpJaodz6P7x2uyLiX6RLYpZmOJqNmoCst/Yyd7hQlszyPwG/I9CQJ63nOtKSxpt5M7NH67V6nJL2BwCl7g==", + "license": "MIT", + "dependencies": { + "accepts": "^1.3.5", + "cache-content-type": "^1.0.0", + "content-disposition": "~0.5.2", + "content-type": "^1.0.4", + "cookies": "~0.8.0", + "debug": "^4.3.2", + "delegates": "^1.0.0", + "depd": "^2.0.0", + "destroy": "^1.0.4", + "encodeurl": "^1.0.2", + "escape-html": "^1.0.3", + "fresh": "~0.5.2", + "http-assert": "^1.3.0", + "http-errors": "^1.6.3", + "is-generator-function": "^1.0.7", + "koa-compose": "^4.1.0", + "koa-convert": "^2.0.0", + "on-finished": "^2.3.0", + "only": "~0.0.2", + "parseurl": "^1.3.2", + "statuses": "^1.5.0", + "type-is": "^1.6.16", + "vary": "^1.1.2" + }, + "engines": { + "node": "^4.8.4 || ^6.10.1 || ^7.10.1 || >= 8.1.4" + } + }, + "node_modules/koa-compose": { + "version": "4.1.0", + "resolved": "http://bnpm.byted.org/koa-compose/-/koa-compose-4.1.0.tgz", + "integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==", + "license": "MIT" + }, + "node_modules/koa-convert": { + "version": "2.0.0", + "resolved": "http://bnpm.byted.org/koa-convert/-/koa-convert-2.0.0.tgz", + "integrity": "sha512-asOvN6bFlSnxewce2e/DK3p4tltyfC4VM7ZwuTuepI7dEQVcvpyFuBcEARu1+Hxg8DIwytce2n7jrZtRlPrARA==", + "license": "MIT", + "dependencies": { + "co": "^4.6.0", + "koa-compose": "^4.1.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "http://bnpm.byted.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "license": "MIT" + }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "http://bnpm.byted.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "http://bnpm.byted.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "http://bnpm.byted.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "2.6.0", + "resolved": "http://bnpm.byted.org/mime/-/mime-2.6.0.tgz", + "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", + "dev": true, + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "http://bnpm.byted.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "http://bnpm.byted.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/ms": { + "version": "2.1.2", + "resolved": "http://bnpm.byted.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "license": "MIT" + }, + "node_modules/negotiator": { + "version": "0.6.3", + "resolved": "http://bnpm.byted.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/object-inspect": { + "version": "1.12.3", + "resolved": "http://bnpm.byted.org/object-inspect/-/object-inspect-1.12.3.tgz", + "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "http://bnpm.byted.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "license": "MIT", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "http://bnpm.byted.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dev": true, + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/only": { + "version": "0.0.2", + "resolved": "http://bnpm.byted.org/only/-/only-0.0.2.tgz", + "integrity": "sha512-Fvw+Jemq5fjjyWz6CpKx6w9s7xxqo3+JCyM0WXWeCSOboZ8ABkyvP8ID4CZuChA/wxSx+XSJmdOm8rGVyJ1hdQ==" + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "http://bnpm.byted.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/qs": { + "version": "6.11.2", + "resolved": "http://bnpm.byted.org/qs/-/qs-6.11.2.tgz", + "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==", + "license": "BSD-3-Clause", + "dependencies": { + "side-channel": "^1.0.4" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/raw-body": { + "version": "2.5.2", + "resolved": "http://bnpm.byted.org/raw-body/-/raw-body-2.5.2.tgz", + "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "license": "MIT", + "dependencies": { + "bytes": "3.1.2", + "http-errors": "2.0.0", + "iconv-lite": "0.4.24", + "unpipe": "1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/http-errors": { + "version": "2.0.0", + "resolved": "http://bnpm.byted.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "license": "MIT", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/statuses": { + "version": "2.0.1", + "resolved": "http://bnpm.byted.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "http://bnpm.byted.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "http://bnpm.byted.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "7.5.4", + "resolved": "http://bnpm.byted.org/semver/-/semver-7.5.4.tgz", + "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", + "dev": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "resolved": "http://bnpm.byted.org/setprototypeof/-/setprototypeof-1.2.0.tgz", + "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", + "license": "ISC" + }, + "node_modules/side-channel": { + "version": "1.0.4", + "resolved": "http://bnpm.byted.org/side-channel/-/side-channel-1.0.4.tgz", + "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.0", + "get-intrinsic": "^1.0.2", + "object-inspect": "^1.9.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/statuses": { + "version": "1.5.0", + "resolved": "http://bnpm.byted.org/statuses/-/statuses-1.5.0.tgz", + "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/superagent": { + "version": "8.1.2", + "resolved": "http://bnpm.byted.org/superagent/-/superagent-8.1.2.tgz", + "integrity": "sha512-6WTxW1EB6yCxV5VFOIPQruWGHqc3yI7hEmZK6h+pyk69Lk/Ut7rLUY6W/ONF2MjBuGjvmMiIpsrVJ2vjrHlslA==", + "dev": true, + "license": "MIT", + "dependencies": { + "component-emitter": "^1.3.0", + "cookiejar": "^2.1.4", + "debug": "^4.3.4", + "fast-safe-stringify": "^2.1.1", + "form-data": "^4.0.0", + "formidable": "^2.1.2", + "methods": "^1.1.2", + "mime": "2.6.0", + "qs": "^6.11.0", + "semver": "^7.3.8" + }, + "engines": { + "node": ">=6.4.0 <13 || >=14" + } + }, + "node_modules/supertest": { + "version": "6.3.3", + "resolved": "http://bnpm.byted.org/supertest/-/supertest-6.3.3.tgz", + "integrity": "sha512-EMCG6G8gDu5qEqRQ3JjjPs6+FYT1a7Hv5ApHvtSghmOFJYtsU5S+pSb6Y2EUeCEY3CmEL3mmQ8YWlPOzQomabA==", + "dev": true, + "license": "MIT", + "dependencies": { + "methods": "^1.1.2", + "superagent": "^8.0.5" + }, + "engines": { + "node": ">=6.4.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "http://bnpm.byted.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "license": "MIT", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/tsscmp": { + "version": "1.0.6", + "resolved": "http://bnpm.byted.org/tsscmp/-/tsscmp-1.0.6.tgz", + "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", + "license": "MIT", + "engines": { + "node": ">=0.6.x" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "http://bnpm.byted.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "license": "MIT", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "http://bnpm.byted.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vary": { + "version": "1.1.2", + "resolved": "http://bnpm.byted.org/vary/-/vary-1.1.2.tgz", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "license": "MIT", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "http://bnpm.byted.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "http://bnpm.byted.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", + "dev": true, + "license": "ISC" + }, + "node_modules/ylru": { + "version": "1.3.2", + "resolved": "http://bnpm.byted.org/ylru/-/ylru-1.3.2.tgz", + "integrity": "sha512-RXRJzMiK6U2ye0BlGGZnmpwJDPgakn6aNQ0A7gHRbD4I0uvK4TW6UqkK1V0pp9jskjJBAXd3dRrbzWkqJ+6cxA==", + "license": "MIT", + "engines": { + "node": ">= 4.0.0" + } + } + } +} diff --git a/packages/core2/package.json b/packages/core2/package.json new file mode 100644 index 0000000..fe806e6 --- /dev/null +++ b/packages/core2/package.json @@ -0,0 +1,41 @@ +{ + "name": "@tomrpc/core2", + "version": "1.0.0", + "description": "My Awesome lib", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "author": "npmstudy ", + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "tsup src -- --dts-resolve", + "build:fast": "tsup src", + "dev": "tsup src --watch", + "test": "vitest run", + "test:watch": "vitest watch", + "coverage": "vitest run --coverage" + }, + "keywords": [ + "awesome-keywords" + ], + "devDependencies": { + "@types/koa": "^2.13.10", + "@vitest/coverage-v8": "^0.34.6", + "happy-dom": "^6.0.4", + "supertest": "^6.3.3", + "vitest": "^0.34.6" + }, + "dependencies": { + "@koa/bodyparser": "^5.0.0", + "debug": "^4.3.4", + "koa": "^2.14.2", + "koa-compose": "^4.1.0", + "koa-mount": "^4.0.0" + } +} diff --git a/packages/core2/src/__tests__/index.test.ts b/packages/core2/src/__tests__/index.test.ts new file mode 100644 index 0000000..70aa64c --- /dev/null +++ b/packages/core2/src/__tests__/index.test.ts @@ -0,0 +1,42 @@ +import request from 'supertest'; +import { describe, expect, it } from 'vitest'; + +import { lib } from '..'; + +describe('lib', () => { + it('should render lib', () => { + expect(lib()).toBe('lib'); + }); +}); + +// const request = require('supertest'); +// const { test } = require('uvu'); +// // const assert = require('uvu/assert'); + +// const app = {}; //= require('../../app').callback(); + +// test('get /a/a?$p=["hello",22323]', async () => { +// await request(app) +// .get('/a/a?$p=["hello",22323]') +// .expect('Content-Type', /text\/plain/) +// .expect(200) +// .expect('hello+22323'); +// }); + +// test('post /a/a', async () => { +// await request(app) +// .post('/a/a') +// .send(['22hello', '001']) +// .expect('Content-Type', /text\/plain/) +// .expect(200) +// .expect('this is a post'); +// }); + +// test('post /a/b', async () => { +// await request(app) +// .post('/a/b') +// .send(['1', '2']) +// .expect('Content-Type', /json/) +// .expect(200) +// .expect('{"a":"1","b":"2"}'); +// }); diff --git a/packages/core2/src/core.ts b/packages/core2/src/core.ts new file mode 100644 index 0000000..870cf95 --- /dev/null +++ b/packages/core2/src/core.ts @@ -0,0 +1,31 @@ +import debug from 'debug'; +const log = debug('@tomrpc/core'); + +export function mountMiddleware(routers) { + log(routers); + return async (ctx, next) => { + log('mountMiddleware'); + const key = ctx.path.replace('/', '').split('/').join('.'); + + if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { + console.log('not match $p param, no process'); + ctx.body = 'not match $p param, no process'; + } else { + const param = ctx.method === 'POST' ? ctx.request.body : JSON.parse(ctx.query.$p); + + log(key); + log(param); + + if (routers[key]) { + const args = [...param, ctx]; + // console.dir(args); + const result = routers[key].apply(ctx, args); + ctx.body = result; + } else { + const msg = JSON.stringify(ctx, null, 4); + ctx.body = ` not match path ${ctx.path} \n ctx = ${msg}`; + } + await next(); + } + }; +} diff --git a/packages/core2/src/index.ts b/packages/core2/src/index.ts new file mode 100644 index 0000000..317bf99 --- /dev/null +++ b/packages/core2/src/index.ts @@ -0,0 +1,209 @@ +import { bodyParser } from '@koa/bodyparser'; +import debug from 'debug'; +import Koa from 'koa'; +import compose from 'koa-compose'; + +import { mountMiddleware } from './core'; +import { isArrowFunction, getHttpMethods } from './utils'; + +export const lib = () => 'lib'; + +const log = debug('@tomrpc/core'); + +export const LifeCycleConfig = { + hooks: { + init: [], + before: [], + load: [], + beforeMount: [], + afterMount: [], + after: [], + }, + init: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.init; + console.log(loadMiddlewares); + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + before: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.before; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + load: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.load; + console.log(loadMiddlewares); + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + after: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.after; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + beforeMount: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.beforeMount; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + afterMount: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.afterMount; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + beforeAll: async (ctx, next) => { + log('beforeAll'); + await next(); + log('beforeAll end'); + }, + beforeEach: async (ctx, next) => { + log('beforeEach'); + await next(); + log('beforeEach end'); + }, + afterEach: async (ctx, next) => { + log('afterEach'); + await next(); + log('afterEach end'); + }, + afterAll: async (ctx, next) => { + log('afterAll'); + await next(); + log('afterAll end'); + }, + beforeOne: function (ctx, key: string) { + log('beforeOne key=' + key); + }, + afterOne: function (ctx, key: string) { + log('afterOne key=' + key); + }, +}; + +export const createServer = function (config?: any) { + const _cfg = Object.assign(LifeCycleConfig, config); + + // 在app时用 + this.config = _cfg; + this.base = _cfg.base; + + const app = new Koa(); + app.use(bodyParser()); + + this.app = app; + this.use = app.use; + + // + app.use(_cfg.beforeAll); + + _cfg.before(this); + + return Object.assign(this, { + rpcFunctions: {}, + _mounted: false, + listen: function (port?: number) { + _cfg.init(this); + + _cfg.load(this); + + _cfg.beforeMount(this); + this.mount(); + _cfg.afterMount(this); + _cfg.after(this); + app.use(_cfg.afterAll); + + this.app.listen(port || 3000); + }, + add: function (items) { + for (const [name, fn] of Object.entries(items)) { + if (isArrowFunction(fn)) { + console.log( + `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` + ); + } + if (this.rpcFunctions[name]) { + log(`add ${name}: ${fn}`); + console.log(`this.rpcFunctions[${name}] exisit`); + } + + this.rpcFunctions[name] = fn; + } + }, + mount: function () { + log('mount'); + + if (!this._mounted) { + const mw = compose([ + _cfg.beforeEach, + async (ctx, next) => { + log('beforeOne'); + const key = ctx.path.replace('/', '').split('/').join('.'); + _cfg.beforeOne(ctx, key); + + const lastKey = key.split('.').pop(); + const httpMethods = getHttpMethods(); + + const supportMethods = []; + httpMethods.forEach(function (m) { + if (lastKey.indexOf(m) != -1) { + log(m); + supportMethods.push(m); + return m; + } + }); + // console.log(supportMethods); + + if (supportMethods.length === 0) { + log('没有匹配到包含get/post等方法的函数'); + await next(); + } else if (ctx.method === supportMethods[0]) { + log('匹配到包含get/post等方法的函数'); + await next(); + } else { + log('匹配到包含get/post等方法的函数,但method不对'); + ctx.body = + 'process fn:' + + lastKey + + ' , you need send ' + + supportMethods[0] + + ' request from client'; + } + + log('beforeOne end'); + }, + mountMiddleware(this.rpcFunctions), + async (ctx, next) => { + log('afterOne'); + const key = ctx.path.replace('/', '').split('/').join('.'); + _cfg.afterOne(ctx, key); + await next(); + log('afterOne end'); + }, + _cfg.afterEach, + ]); + app.use(mw); + this._mounted = true; + } + }, + dump: function (): void { + for (const [name, fn] of Object.entries(this.rpcFunctions)) { + console.log(`${name}: ${fn}`); + } + }, + + fn: function (name: string, fn: any) { + this.rpcFunctions[name] = fn; + }, + }); +}; diff --git a/packages/core2/src/utils.ts b/packages/core2/src/utils.ts new file mode 100644 index 0000000..fd9264e --- /dev/null +++ b/packages/core2/src/utils.ts @@ -0,0 +1,38 @@ +export const isArrowFunction = (func) => { + if (typeof func === 'function') { + const source = func.toString(); + return /^\([^)]*\)\s*=>/.test(source); + } + return false; +}; + +export function getHttpMethods() { + return [ + 'get', + 'post', + 'put', + 'head', + 'delete', + 'options', + 'trace', + 'copy', + 'lock', + 'mkcol', + 'move', + 'purge', + 'propfind', + 'proppatch', + 'unlock', + 'report', + 'mkactivity', + 'checkout', + 'merge', + 'm-search', + 'notify', + 'subscribe', + 'unsubscribe', + 'patch', + 'search', + 'connect', + ]; +} diff --git a/packages/core2/tsconfig.json b/packages/core2/tsconfig.json new file mode 100644 index 0000000..afc9f0b --- /dev/null +++ b/packages/core2/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "types": [ + "vitest/globals" + ] + } +} diff --git a/packages/core2/tsup.config.cjs b/packages/core2/tsup.config.cjs new file mode 100644 index 0000000..369773b --- /dev/null +++ b/packages/core2/tsup.config.cjs @@ -0,0 +1,12 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig((options) => ({ + entry: 'src/index.ts', + sourcemap: !options.watch, + minify: !options.watch, + // dts: true, + format: ['esm', 'cjs'], + loader: { + '.js': 'jsx', + }, +})); diff --git a/packages/core2/vitest.config.cjs b/packages/core2/vitest.config.cjs new file mode 100644 index 0000000..c4e3ba6 --- /dev/null +++ b/packages/core2/vitest.config.cjs @@ -0,0 +1,10 @@ +/// + +import { defineConfig } from 'vite'; + +export default defineConfig({ + test: { + globals: true, + environment: 'happy-dom', + }, +}); From 5f69537f0b67d5aea7ea8c2c3b3bacbb46d764dd Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 31 Oct 2023 13:49:22 +0800 Subject: [PATCH 012/101] feat: stash --- packages/core2/aa.ts | 99 +++++++++++++++++++++++++++++++++++++++++++ packages/core2/app.ts | 8 ++++ packages/core2/fn.ts | 18 ++++++++ 3 files changed, 125 insertions(+) create mode 100644 packages/core2/aa.ts create mode 100644 packages/core2/app.ts create mode 100644 packages/core2/fn.ts diff --git a/packages/core2/aa.ts b/packages/core2/aa.ts new file mode 100644 index 0000000..5712b27 --- /dev/null +++ b/packages/core2/aa.ts @@ -0,0 +1,99 @@ +import { bodyParser } from '@koa/bodyparser'; +import debug from 'debug'; +import Koa from 'koa'; +import compose from 'koa-compose'; + +class Context { + /** + * @type {Strategy} The Context maintains a reference to one of the Strategy + * objects. The Context does not know the concrete class of a strategy. It + * should work with all strategies via the Strategy interface. + */ + private plugins: Strategy[]; + app; + use; + /** + * Usually, the Context accepts a strategy through the constructor, but also + * provides a setter to change it at runtime. + */ + constructor() { + // init + const app = new Koa(); + app.use(bodyParser()); + + this.app = app; + this.use = app.use; + } + + /** + * Usually, the Context allows replacing a Strategy object at runtime. + */ + public plugin(strategy: Strategy) { + this.plugins.push(strategy); + } + + public mount() { + console.dir('s'); + // mount + for (const plugin of this.plugins) { + console.log(plugin); + } + } + + /** + * The Context delegates some work to the Strategy object instead of + * implementing multiple versions of the algorithm on its own. + */ + public start(): void { + this.mount(); + + console.log("Context: Sorting data using the strategy (not sure how it'll do it)"); + // const result = this.strategy.doAlgorithm(['a', 'b', 'c', 'd', 'e']); + // console.log(result.join(',')); + + // ... + // return listenerCount() + } +} + +/** + * The Strategy interface declares operations common to all supported versions + * of some algorithm. + * + * The Context uses this interface to call the algorithm defined by Concrete + * Strategies. + */ +interface Strategy { + doAlgorithm(data: string[]): string[]; +} + +/** + * Concrete Strategies implement the algorithm while following the base Strategy + * interface. The interface makes them interchangeable in the Context. + */ +class ConcreteStrategyA implements Strategy { + public doAlgorithm(data: string[]): string[] { + return data.sort(); + } +} + +class ConcreteStrategyB implements Strategy { + public doAlgorithm(data: string[]): string[] { + return data.reverse(); + } +} + +/** + * The client code picks a concrete strategy and passes it to the context. The + * client should be aware of the differences between strategies in order to make + * the right choice. + */ +// const context = new Context(new ConcreteStrategyA()); +// console.log('Client: Strategy is set to normal sorting.'); +// context.start(); + +// console.log(''); + +// console.log('Client: Strategy is set to reverse sorting.'); +// context.plugin(new ConcreteStrategyB()); +// context.start(); diff --git a/packages/core2/app.ts b/packages/core2/app.ts new file mode 100644 index 0000000..30dc699 --- /dev/null +++ b/packages/core2/app.ts @@ -0,0 +1,8 @@ +import { createServer } from './src/index'; + +const rpc = createServer({}); + +rpc.plugin(); +rpc.plugin(); + +rpc.listen(3000); diff --git a/packages/core2/fn.ts b/packages/core2/fn.ts new file mode 100644 index 0000000..781f0d4 --- /dev/null +++ b/packages/core2/fn.ts @@ -0,0 +1,18 @@ +import { F } from 'vitest/dist/reporters-5f784f42'; + +export class Fn { + public name: string; + public init: Array; + public load: Array; + + constructor() { + this.name = 'fn'; + this.init = []; + this.load = []; + } + + async render(ctx, next) { + console.dir(''); + await next(); + } +} From 55f2a69d6356bd6ac750a1e612f8c70b107b6781 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 31 Oct 2023 13:50:43 +0800 Subject: [PATCH 013/101] feat: stash --- packages/core2/aa.ts | 52 ++++++++++++++++++++++---------------------- 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/packages/core2/aa.ts b/packages/core2/aa.ts index 5712b27..42dc939 100644 --- a/packages/core2/aa.ts +++ b/packages/core2/aa.ts @@ -67,33 +67,33 @@ interface Strategy { doAlgorithm(data: string[]): string[]; } -/** - * Concrete Strategies implement the algorithm while following the base Strategy - * interface. The interface makes them interchangeable in the Context. - */ -class ConcreteStrategyA implements Strategy { - public doAlgorithm(data: string[]): string[] { - return data.sort(); - } -} +// /** +// * Concrete Strategies implement the algorithm while following the base Strategy +// * interface. The interface makes them interchangeable in the Context. +// */ +// class ConcreteStrategyA implements Strategy { +// public doAlgorithm(data: string[]): string[] { +// return data.sort(); +// } +// } -class ConcreteStrategyB implements Strategy { - public doAlgorithm(data: string[]): string[] { - return data.reverse(); - } -} +// class ConcreteStrategyB implements Strategy { +// public doAlgorithm(data: string[]): string[] { +// return data.reverse(); +// } +// } -/** - * The client code picks a concrete strategy and passes it to the context. The - * client should be aware of the differences between strategies in order to make - * the right choice. - */ -// const context = new Context(new ConcreteStrategyA()); -// console.log('Client: Strategy is set to normal sorting.'); -// context.start(); +// /** +// * The client code picks a concrete strategy and passes it to the context. The +// * client should be aware of the differences between strategies in order to make +// * the right choice. +// */ +// // const context = new Context(new ConcreteStrategyA()); +// // console.log('Client: Strategy is set to normal sorting.'); +// // context.start(); -// console.log(''); +// // console.log(''); -// console.log('Client: Strategy is set to reverse sorting.'); -// context.plugin(new ConcreteStrategyB()); -// context.start(); +// // console.log('Client: Strategy is set to reverse sorting.'); +// // context.plugin(new ConcreteStrategyB()); +// // context.start(); From 6007a11a3542429ba1d29d85c95eec376abe407a Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 31 Oct 2023 13:51:41 +0800 Subject: [PATCH 014/101] feat: stash --- packages/core2/fn.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/core2/fn.ts b/packages/core2/fn.ts index 781f0d4..737e57b 100644 --- a/packages/core2/fn.ts +++ b/packages/core2/fn.ts @@ -1,14 +1,14 @@ import { F } from 'vitest/dist/reporters-5f784f42'; export class Fn { - public name: string; - public init: Array; - public load: Array; + // public name: string; + // public init: Array; + // public load: Array; constructor() { - this.name = 'fn'; - this.init = []; - this.load = []; + // this.name = 'fn'; + // this.init = []; + // this.load = []; } async render(ctx, next) { From 84b344fc81e004221bf6c00d7bcb8cf871d4b3d6 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 31 Oct 2023 22:55:58 +0800 Subject: [PATCH 015/101] feat: init core2 --- packages/core2/aa.ts | 99 --------------- packages/core2/app.ts | 15 ++- packages/core2/demo.ts | 51 ++++++++ packages/core2/fn.ts | 53 ++++++-- packages/core2/server.ts | 241 +++++++++++++++++++++++++++++++++++++ packages/core2/src/base.ts | 77 ++++++++++++ 6 files changed, 422 insertions(+), 114 deletions(-) delete mode 100644 packages/core2/aa.ts create mode 100644 packages/core2/demo.ts create mode 100644 packages/core2/server.ts create mode 100644 packages/core2/src/base.ts diff --git a/packages/core2/aa.ts b/packages/core2/aa.ts deleted file mode 100644 index 42dc939..0000000 --- a/packages/core2/aa.ts +++ /dev/null @@ -1,99 +0,0 @@ -import { bodyParser } from '@koa/bodyparser'; -import debug from 'debug'; -import Koa from 'koa'; -import compose from 'koa-compose'; - -class Context { - /** - * @type {Strategy} The Context maintains a reference to one of the Strategy - * objects. The Context does not know the concrete class of a strategy. It - * should work with all strategies via the Strategy interface. - */ - private plugins: Strategy[]; - app; - use; - /** - * Usually, the Context accepts a strategy through the constructor, but also - * provides a setter to change it at runtime. - */ - constructor() { - // init - const app = new Koa(); - app.use(bodyParser()); - - this.app = app; - this.use = app.use; - } - - /** - * Usually, the Context allows replacing a Strategy object at runtime. - */ - public plugin(strategy: Strategy) { - this.plugins.push(strategy); - } - - public mount() { - console.dir('s'); - // mount - for (const plugin of this.plugins) { - console.log(plugin); - } - } - - /** - * The Context delegates some work to the Strategy object instead of - * implementing multiple versions of the algorithm on its own. - */ - public start(): void { - this.mount(); - - console.log("Context: Sorting data using the strategy (not sure how it'll do it)"); - // const result = this.strategy.doAlgorithm(['a', 'b', 'c', 'd', 'e']); - // console.log(result.join(',')); - - // ... - // return listenerCount() - } -} - -/** - * The Strategy interface declares operations common to all supported versions - * of some algorithm. - * - * The Context uses this interface to call the algorithm defined by Concrete - * Strategies. - */ -interface Strategy { - doAlgorithm(data: string[]): string[]; -} - -// /** -// * Concrete Strategies implement the algorithm while following the base Strategy -// * interface. The interface makes them interchangeable in the Context. -// */ -// class ConcreteStrategyA implements Strategy { -// public doAlgorithm(data: string[]): string[] { -// return data.sort(); -// } -// } - -// class ConcreteStrategyB implements Strategy { -// public doAlgorithm(data: string[]): string[] { -// return data.reverse(); -// } -// } - -// /** -// * The client code picks a concrete strategy and passes it to the context. The -// * client should be aware of the differences between strategies in order to make -// * the right choice. -// */ -// // const context = new Context(new ConcreteStrategyA()); -// // console.log('Client: Strategy is set to normal sorting.'); -// // context.start(); - -// // console.log(''); - -// // console.log('Client: Strategy is set to reverse sorting.'); -// // context.plugin(new ConcreteStrategyB()); -// // context.start(); diff --git a/packages/core2/app.ts b/packages/core2/app.ts index 30dc699..bd3d9c8 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -1,8 +1,13 @@ -import { createServer } from './src/index'; +import Demo from './demo'; +import Fn from './fn'; +import RpcServer from './server'; -const rpc = createServer({}); +const rpc = new RpcServer({}); -rpc.plugin(); -rpc.plugin(); +const fn = new Fn(); +const demo = new Demo(); -rpc.listen(3000); +rpc.plugin(fn); +rpc.plugin(demo); + +rpc.start(2091); diff --git a/packages/core2/demo.ts b/packages/core2/demo.ts new file mode 100644 index 0000000..a739b9d --- /dev/null +++ b/packages/core2/demo.ts @@ -0,0 +1,51 @@ +import Plugable from './src/base'; +export default class Fn extends Plugable { + // public name: string; + + constructor() { + super(); + + this.prefix = '/demo'; + // this.name = 'fn'; + + const a = this.a(); + const b = this.b(); + console.dir(a + ''); + // this.addInit(a); + // this.addInit(b); + + const c = this.c(); + // this.addLoad(c); + } + process() { + return async (ctx, next) => { + console.dir('process child'); + if (ctx.path === '/') { + ctx.body = { '/': 23 }; + } else { + // ctx.body = { '2323api': 23 }; + await next(); + } + }; + } + + a() { + return async (ctx, next) => { + console.dir('a ' + ctx.path); + await next(); + }; + } + b() { + return async (ctx, next) => { + console.dir('b ' + ctx.path); + await next(); + }; + } + + c() { + return async (ctx, next) => { + console.dir('c ' + ctx.path); + await next(); + }; + } +} diff --git a/packages/core2/fn.ts b/packages/core2/fn.ts index 737e57b..e8c00d4 100644 --- a/packages/core2/fn.ts +++ b/packages/core2/fn.ts @@ -1,18 +1,51 @@ -import { F } from 'vitest/dist/reporters-5f784f42'; - -export class Fn { +import Plugable from './src/base'; +export default class Fn extends Plugable { // public name: string; - // public init: Array; - // public load: Array; constructor() { + super(); + + this.prefix = '/api'; // this.name = 'fn'; - // this.init = []; - // this.load = []; + + const a = this.a(); + const b = this.b(); + console.dir(a + ''); + // this.addInit(a); + // this.addInit(b); + + const c = this.c(); + // this.addLoad(c); + } + process() { + return async (ctx, next) => { + console.dir('process child'); + if (ctx.path === '/') { + ctx.body = { '/': 23 }; + } else { + // ctx.body = { '2323api': 23 }; + await next(); + } + }; + } + + a() { + return async (ctx, next) => { + console.dir('a ' + ctx.path); + await next(); + }; + } + b() { + return async (ctx, next) => { + console.dir('b ' + ctx.path); + await next(); + }; } - async render(ctx, next) { - console.dir(''); - await next(); + c() { + return async (ctx, next) => { + console.dir('c ' + ctx.path); + await next(); + }; } } diff --git a/packages/core2/server.ts b/packages/core2/server.ts new file mode 100644 index 0000000..4ec5178 --- /dev/null +++ b/packages/core2/server.ts @@ -0,0 +1,241 @@ +import { bodyParser } from '@koa/bodyparser'; +import debug from 'debug'; +import Koa from 'koa'; +import compose from 'koa-compose'; +const log = debug('@tomrpc/core2'); +import mount from 'koa-mount'; + +import Fn from './fn'; + +export const LifeCycleConfig = { + hooks: { + init: [], + before: [], + load: [], + beforeMount: [], + afterMount: [], + after: [], + default: async (ctx, next) => { + log('default'); + ctx.body = 'no middleware repsonse, please check your route'; + log('default end'); + }, + }, + init: async (server) => { + console.dir('init s'); + // console.dir(server); + const app = server.app; + const loadMiddlewares = server.config.hooks.init; + console.dir(loadMiddlewares); + loadMiddlewares.forEach((mw) => { + const m = async (ctx, next) => { + await next(); + }; + console.dir(m + ''); + console.dir(mw + ''); + app.use(mw); + }); + }, + before: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.before; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + load: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.load; + console.log('load Middlewares'); + console.log(loadMiddlewares); + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + after: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.after; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + beforeMount: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.beforeMount; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + afterMount: async (server) => { + const app = server.app; + const loadMiddlewares = server.config.hooks.afterMount; + loadMiddlewares.forEach((mw) => { + app.use(mw); + }); + }, + beforeAll: async (ctx, next) => { + log('beforeAll'); + await next(); + log('beforeAll end'); + }, + beforeEach: async (ctx, next) => { + log('beforeEach'); + await next(); + log('beforeEach end'); + }, + afterEach: async (ctx, next) => { + log('afterEach'); + await next(); + log('afterEach end'); + }, + afterAll: async (ctx, next) => { + log('afterAll'); + await next(); + log('afterAll end'); + }, + beforeOne: function (ctx, key: string) { + log('beforeOne key=' + key); + }, + afterOne: function (ctx, key: string) { + log('afterOne key=' + key); + }, +}; + +export default class RpcServer { + /** + * @type {Strategy} The Context maintains a reference to one of the Strategy + * objects. The Context does not know the concrete class of a strategy. It + * should work with all strategies via the Strategy interface. + */ + private plugins: Strategy[] = []; + app; + use; + config; + init: []; + load: []; + /** + * Usually, the Context accepts a strategy through the constructor, but also + * provides a setter to change it at runtime. + */ + constructor(cfg) { + // init + this.config = Object.assign(LifeCycleConfig, cfg); + this.app = new Koa(); + this.app.use(bodyParser()); + this.use = this.app.use; + } + + /** + * Usually, the Context allows replacing a Strategy object at runtime. + */ + public plugin(strategy: Strategy) { + this.plugins.push(strategy); + } + + public mount() { + console.dir('mount'); + // hooks + for (const plugin of this.plugins) { + if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); + + console.dir(plugin); + console.dir(this.config.hooks.init); + } + + this.config.init(this); + + for (const plugin of this.plugins) { + if (plugin.load.length > 0) this.config.hooks.load.push(...plugin.load); + console.dir('load plugin'); + console.dir(plugin.load); + console.dir('load end plugin'); + console.dir(this.config.hooks.init); + } + + this.config.load(this); + + // mount app + for (const plugin of this.plugins) { + console.dir('plugin.proxy() ' + plugin.prefix); + console.dir(plugin.proxy()); + // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); + this.app.use(mount(plugin.prefix, plugin.app)); + } + + // 兜底的else + + this.app.use(this.config.hooks.default); + // this.app.use(async (ctx, next) => { + // console.dir(ctx.path); + // ctx.body = { 23: 23 }; + // }); + } + + /** + * The Context delegates some work to the Strategy object instead of + * implementing multiple versions of the algorithm on its own. + */ + public start(port?: number): void { + const _port = port || 3000; + console.dir(_port); + + // this.config.load(this); + + // this.config.beforeMount(this); + this.mount(); + + // this.config.afterMount(this); + // this.config.after(this); + // this.app.use(this.config.afterAll); + + this.app.listen(_port, (err) => { + if (err) { + console.error(err); + } else { + console.log('Koa app listening on ' + _port); + } + }); + } +} + +/** + * The Strategy interface declares operations common to all supported versions + * of some algorithm. + * + * The Context uses this interface to call the algorithm defined by Concrete + * Strategies. + */ +export interface Strategy { + init: any[]; + load: any[]; + prefix; + app; + proxy; + + // doAlgorithm(data: string[]): string[]; +} + +// /** +// * Concrete Strategies implement the algorithm while following the base Strategy +// * interface. The interface makes them interchangeable in the Context. +// */ +// class ConcreteStrategyA implements Strategy { +// public doAlgorithm(data: string[]): string[] { +// return data.sort(); +// } +// } + +// class ConcreteStrategyB implements Strategy { +// public doAlgorithm(data: string[]): string[] { +// return data.reverse(); +// } +// } + +// // console.log('Client: Strategy is set to normal sorting.'); +// // context.start(); + +// // console.log(''); + +// // console.log('Client: Strategy is set to reverse sorting.'); +// // context.plugin(new ConcreteStrategyB()); +// // context.start(); diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts new file mode 100644 index 0000000..d22d64a --- /dev/null +++ b/packages/core2/src/base.ts @@ -0,0 +1,77 @@ +import Koa from 'koa'; +import compose from 'koa-compose'; + +import { Strategy } from '../server'; + +export default class Plugable implements Strategy { + public init: any[] = []; + public load: any[] = []; + public name; + public app; + public prefix; + + constructor() { + this.name = 'fn'; + this.app = new Koa(); + console.dir('base'); + this.init = []; + this.load = []; + this.use(this.getMiddleware()); + } + + proxy() { + return async (ctx, next) => { + console.dir('proxy prefix=' + this.prefix); + if (ctx.path.match(this.prefix)) { + console.dir('proxy ' + ctx.path); + await next(); + console.dir('proxy end ' + ctx.path); + } else { + console.dir('not proxy ' + ctx.path); + await next(); + console.dir('not proxy end ' + ctx.path); + } + }; + } + + getMiddleware() { + const pre = this.pre(); + const process = this.process(); + const after = this.after(); + return compose([pre, process, after]); + } + + pre() { + return async (ctx, next) => { + console.dir('pre'); + await next(); + console.dir('pre end'); + }; + } + after() { + return async (ctx, next) => { + console.dir('after'); + await next(); + console.dir('after end'); + }; + } + process() { + return async (ctx, next) => { + console.dir('process default'); + await next(); + console.dir('process default end'); + }; + } + + use(x) { + this.app.use(x); + } + + addInit(i) { + this.init.push(i); + } + + addLoad(i) { + this.load.push(i); + } +} From e41d673846d17a316e8304effa11c0e1b8ca5c3b Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 31 Oct 2023 22:59:25 +0800 Subject: [PATCH 016/101] feat: bind compose to base --- packages/core2/server.ts | 1 + packages/core2/src/base.ts | 2 ++ 2 files changed, 3 insertions(+) diff --git a/packages/core2/server.ts b/packages/core2/server.ts index 4ec5178..5c55746 100644 --- a/packages/core2/server.ts +++ b/packages/core2/server.ts @@ -211,6 +211,7 @@ export interface Strategy { prefix; app; proxy; + compose; // doAlgorithm(data: string[]): string[]; } diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index d22d64a..8f10015 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -9,6 +9,7 @@ export default class Plugable implements Strategy { public name; public app; public prefix; + public compose; constructor() { this.name = 'fn'; @@ -17,6 +18,7 @@ export default class Plugable implements Strategy { this.init = []; this.load = []; this.use(this.getMiddleware()); + this.compose = compose; } proxy() { From 4bcb6c50009ebe692439399497f16b823e8dc28d Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 1 Nov 2023 00:29:28 +0800 Subject: [PATCH 017/101] chore: remove log --- packages/core2/demo.ts | 2 +- packages/core2/fn.ts | 2 +- packages/core2/server.ts | 29 +++++++++-------------------- packages/core2/src/base.ts | 1 - 4 files changed, 11 insertions(+), 23 deletions(-) diff --git a/packages/core2/demo.ts b/packages/core2/demo.ts index a739b9d..3404413 100644 --- a/packages/core2/demo.ts +++ b/packages/core2/demo.ts @@ -10,7 +10,7 @@ export default class Fn extends Plugable { const a = this.a(); const b = this.b(); - console.dir(a + ''); + // console.dir(a + ''); // this.addInit(a); // this.addInit(b); diff --git a/packages/core2/fn.ts b/packages/core2/fn.ts index e8c00d4..7528c7c 100644 --- a/packages/core2/fn.ts +++ b/packages/core2/fn.ts @@ -10,7 +10,7 @@ export default class Fn extends Plugable { const a = this.a(); const b = this.b(); - console.dir(a + ''); + // console.dir(a + ''); // this.addInit(a); // this.addInit(b); diff --git a/packages/core2/server.ts b/packages/core2/server.ts index 5c55746..480c92c 100644 --- a/packages/core2/server.ts +++ b/packages/core2/server.ts @@ -1,12 +1,9 @@ import { bodyParser } from '@koa/bodyparser'; import debug from 'debug'; import Koa from 'koa'; -import compose from 'koa-compose'; const log = debug('@tomrpc/core2'); import mount from 'koa-mount'; -import Fn from './fn'; - export const LifeCycleConfig = { hooks: { init: [], @@ -22,17 +19,11 @@ export const LifeCycleConfig = { }, }, init: async (server) => { - console.dir('init s'); + console.dir('init'); // console.dir(server); const app = server.app; const loadMiddlewares = server.config.hooks.init; - console.dir(loadMiddlewares); loadMiddlewares.forEach((mw) => { - const m = async (ctx, next) => { - await next(); - }; - console.dir(m + ''); - console.dir(mw + ''); app.use(mw); }); }, @@ -46,8 +37,6 @@ export const LifeCycleConfig = { load: async (server) => { const app = server.app; const loadMiddlewares = server.config.hooks.load; - console.log('load Middlewares'); - console.log(loadMiddlewares); loadMiddlewares.forEach((mw) => { app.use(mw); }); @@ -138,26 +127,26 @@ export default class RpcServer { for (const plugin of this.plugins) { if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); - console.dir(plugin); - console.dir(this.config.hooks.init); + // console.dir(plugin); + // console.dir(this.config.hooks.init); } this.config.init(this); for (const plugin of this.plugins) { if (plugin.load.length > 0) this.config.hooks.load.push(...plugin.load); - console.dir('load plugin'); - console.dir(plugin.load); - console.dir('load end plugin'); - console.dir(this.config.hooks.init); + // console.dir('load plugin'); + // console.dir(plugin.load); + // console.dir('load end plugin'); + // console.dir(this.config.hooks.init); } this.config.load(this); // mount app for (const plugin of this.plugins) { - console.dir('plugin.proxy() ' + plugin.prefix); - console.dir(plugin.proxy()); + // console.dir('plugin.proxy() ' + plugin.prefix); + // console.dir(plugin.proxy()); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); this.app.use(mount(plugin.prefix, plugin.app)); } diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index 8f10015..9b29cbe 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -14,7 +14,6 @@ export default class Plugable implements Strategy { constructor() { this.name = 'fn'; this.app = new Koa(); - console.dir('base'); this.init = []; this.load = []; this.use(this.getMiddleware()); From 9ad6873dfc3ceedc6bc4549ccf50fccb0dc99d7e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 1 Nov 2023 10:52:02 +0800 Subject: [PATCH 018/101] chore: refact --- packages/core2/app.ts | 4 +-- packages/core2/src/base.ts | 16 ++++++++++- packages/core2/{ => src}/fn.ts | 2 +- packages/core2/{ => src}/server.ts | 45 ++---------------------------- 4 files changed, 20 insertions(+), 47 deletions(-) rename packages/core2/{ => src}/fn.ts (96%) rename packages/core2/{ => src}/server.ts (81%) diff --git a/packages/core2/app.ts b/packages/core2/app.ts index bd3d9c8..e74fc49 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -1,6 +1,6 @@ import Demo from './demo'; -import Fn from './fn'; -import RpcServer from './server'; +import Fn from './src/fn'; +import RpcServer from './src/server'; const rpc = new RpcServer({}); diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index 9b29cbe..7b96df5 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -1,7 +1,21 @@ import Koa from 'koa'; import compose from 'koa-compose'; -import { Strategy } from '../server'; +/** + * The Strategy interface declares operations common to all supported versions + * of some algorithm. + * + * The Context uses this interface to call the algorithm defined by Concrete + * Strategies. + */ +export interface Strategy { + init: any[]; + load: any[]; + prefix; + app; + compose; + proxy; +} export default class Plugable implements Strategy { public init: any[] = []; diff --git a/packages/core2/fn.ts b/packages/core2/src/fn.ts similarity index 96% rename from packages/core2/fn.ts rename to packages/core2/src/fn.ts index 7528c7c..81216ff 100644 --- a/packages/core2/fn.ts +++ b/packages/core2/src/fn.ts @@ -1,4 +1,4 @@ -import Plugable from './src/base'; +import Plugable from './base'; export default class Fn extends Plugable { // public name: string; diff --git a/packages/core2/server.ts b/packages/core2/src/server.ts similarity index 81% rename from packages/core2/server.ts rename to packages/core2/src/server.ts index 480c92c..3d4194b 100644 --- a/packages/core2/server.ts +++ b/packages/core2/src/server.ts @@ -4,6 +4,8 @@ import Koa from 'koa'; const log = debug('@tomrpc/core2'); import mount from 'koa-mount'; +import { Strategy } from './base'; + export const LifeCycleConfig = { hooks: { init: [], @@ -186,46 +188,3 @@ export default class RpcServer { }); } } - -/** - * The Strategy interface declares operations common to all supported versions - * of some algorithm. - * - * The Context uses this interface to call the algorithm defined by Concrete - * Strategies. - */ -export interface Strategy { - init: any[]; - load: any[]; - prefix; - app; - proxy; - compose; - - // doAlgorithm(data: string[]): string[]; -} - -// /** -// * Concrete Strategies implement the algorithm while following the base Strategy -// * interface. The interface makes them interchangeable in the Context. -// */ -// class ConcreteStrategyA implements Strategy { -// public doAlgorithm(data: string[]): string[] { -// return data.sort(); -// } -// } - -// class ConcreteStrategyB implements Strategy { -// public doAlgorithm(data: string[]): string[] { -// return data.reverse(); -// } -// } - -// // console.log('Client: Strategy is set to normal sorting.'); -// // context.start(); - -// // console.log(''); - -// // console.log('Client: Strategy is set to reverse sorting.'); -// // context.plugin(new ConcreteStrategyB()); -// // context.start(); From 739c4f0fb39595383346d773fde0824c00118759 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 1 Nov 2023 11:47:03 +0800 Subject: [PATCH 019/101] chore: refact --- packages/core2/src/base.ts | 7 ++++++- packages/core2/src/server.ts | 24 ++++++++---------------- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index 7b96df5..4e8dfe9 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -12,9 +12,12 @@ export interface Strategy { init: any[]; load: any[]; prefix; + name; app; compose; proxy; + server; + serverConfig; } export default class Plugable implements Strategy { @@ -22,11 +25,13 @@ export default class Plugable implements Strategy { public load: any[] = []; public name; public app; + public server; + public serverConfig; public prefix; public compose; constructor() { - this.name = 'fn'; + this.name = 'base'; this.app = new Koa(); this.init = []; this.load = []; diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 3d4194b..5d16dd5 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -50,20 +50,6 @@ export const LifeCycleConfig = { app.use(mw); }); }, - beforeMount: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.beforeMount; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - afterMount: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.afterMount; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, beforeAll: async (ctx, next) => { log('beforeAll'); await next(); @@ -127,6 +113,12 @@ export default class RpcServer { console.dir('mount'); // hooks for (const plugin of this.plugins) { + plugin.server = this; + plugin.serverConfig = this.config; + + // set config namespace + if (plugin.name !== 'base') this.config.plugin[plugin.name] = {}; + if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); // console.dir(plugin); @@ -170,13 +162,13 @@ export default class RpcServer { const _port = port || 3000; console.dir(_port); - // this.config.load(this); + this.config.before(this); // this.config.beforeMount(this); this.mount(); // this.config.afterMount(this); - // this.config.after(this); + this.config.after(this); // this.app.use(this.config.afterAll); this.app.listen(_port, (err) => { From 84a9529679a421b3d01ccf48a5fe7baa37a5f02f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 1 Nov 2023 12:03:44 +0800 Subject: [PATCH 020/101] chore: refact --- packages/core2/app.ts | 4 ++-- packages/core2/demo.ts | 4 ++-- packages/core2/src/base.ts | 5 ++++- packages/core2/src/fn.ts | 8 ++++++-- packages/core2/src/server.ts | 5 ++++- 5 files changed, 18 insertions(+), 8 deletions(-) diff --git a/packages/core2/app.ts b/packages/core2/app.ts index e74fc49..81f999b 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -4,8 +4,8 @@ import RpcServer from './src/server'; const rpc = new RpcServer({}); -const fn = new Fn(); -const demo = new Demo(); +const fn = new Fn({}); +const demo = new Demo({}); rpc.plugin(fn); rpc.plugin(demo); diff --git a/packages/core2/demo.ts b/packages/core2/demo.ts index 3404413..79cec74 100644 --- a/packages/core2/demo.ts +++ b/packages/core2/demo.ts @@ -2,8 +2,8 @@ import Plugable from './src/base'; export default class Fn extends Plugable { // public name: string; - constructor() { - super(); + constructor(cfg?) { + super(cfg); this.prefix = '/demo'; // this.name = 'fn'; diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index 4e8dfe9..236bed4 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -16,6 +16,7 @@ export interface Strategy { app; compose; proxy; + config; server; serverConfig; } @@ -29,8 +30,10 @@ export default class Plugable implements Strategy { public serverConfig; public prefix; public compose; + public config; - constructor() { + constructor(cfg?) { + this.config = Object.assign({}, cfg); this.name = 'base'; this.app = new Koa(); this.init = []; diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index 81216ff..cf50ab5 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -2,8 +2,8 @@ import Plugable from './base'; export default class Fn extends Plugable { // public name: string; - constructor() { - super(); + constructor(cfg?: any) { + super(cfg); this.prefix = '/api'; // this.name = 'fn'; @@ -16,6 +16,10 @@ export default class Fn extends Plugable { const c = this.c(); // this.addLoad(c); + this.server['fn'].add = function (i) { + if (!this.config['functions']) this.config['functions'] = []; + this.config['functions'].push(i); + }; } process() { return async (ctx, next) => { diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 5d16dd5..3f0103f 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -117,7 +117,10 @@ export default class RpcServer { plugin.serverConfig = this.config; // set config namespace - if (plugin.name !== 'base') this.config.plugin[plugin.name] = {}; + if (plugin.name !== 'base') { + console.error('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); + } + this.config.plugin[plugin.name] = plugin.config; if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); From 91b30e7dfa736e0f887d5bcb3fc42921549c3e55 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 1 Nov 2023 13:49:18 +0800 Subject: [PATCH 021/101] chore: refact --- packages/core2/src/fn.ts | 68 +++++++++++++++++++++++++++++++++++----- 1 file changed, 61 insertions(+), 7 deletions(-) diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index cf50ab5..f6fce39 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -1,4 +1,10 @@ +import debug from 'debug'; + import Plugable from './base'; +import { mountMiddleware } from './core'; +import { isArrowFunction, getHttpMethods } from './utils'; +const log = debug('@tomrpc/core'); + export default class Fn extends Plugable { // public name: string; @@ -16,20 +22,68 @@ export default class Fn extends Plugable { const c = this.c(); // this.addLoad(c); - this.server['fn'].add = function (i) { + + this.config['server']['fn'] = function (items) { if (!this.config['functions']) this.config['functions'] = []; - this.config['functions'].push(i); + if (Object.entries(items)) { + for (const [name, fn] of Object.entries(items)) { + if (isArrowFunction(fn)) { + console.log( + `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` + ); + } + if (this.rpcFunctions[name]) { + log(`add ${name}: ${fn}`); + console.log(`this.rpcFunctions[${name}] exisit`); + } + + this.rpcFunctions[name] = fn; + } + } else { + this.config['functions'].push(items); + } }; } process() { + return mountMiddleware(this.config['functions']); + } + + pre() { return async (ctx, next) => { - console.dir('process child'); - if (ctx.path === '/') { - ctx.body = { '/': 23 }; - } else { - // ctx.body = { '2323api': 23 }; + log('beforeOne'); + const key = ctx.path.replace('/', '').split('/').join('.'); + // this.config.beforeOne(ctx, key); + + const lastKey = key.split('.').pop(); + const httpMethods = getHttpMethods(); + + const supportMethods = []; + httpMethods.forEach(function (m) { + if (lastKey.indexOf(m) != -1) { + log(m); + supportMethods.push(m); + return m; + } + }); + // console.log(supportMethods); + + if (supportMethods.length === 0) { + log('没有匹配到包含get/post等方法的函数'); await next(); + } else if (ctx.method === supportMethods[0]) { + log('匹配到包含get/post等方法的函数'); + await next(); + } else { + log('匹配到包含get/post等方法的函数,但method不对'); + ctx.body = + 'process fn:' + + lastKey + + ' , you need send ' + + supportMethods[0] + + ' request from client'; } + + log('beforeOne end'); }; } From 63b5f4cca2412384535ce6db9cee73225818c5ae Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 1 Nov 2023 22:16:21 +0800 Subject: [PATCH 022/101] chore: refact --- packages/core2/app.ts | 4 ++ packages/core2/src/base.ts | 12 ++++- packages/core2/src/core.ts | 3 +- packages/core2/src/fn.ts | 86 +++++++++++++----------------------- packages/core2/src/server.ts | 17 ++++++- 5 files changed, 62 insertions(+), 60 deletions(-) diff --git a/packages/core2/app.ts b/packages/core2/app.ts index 81f999b..d9fa050 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -7,6 +7,10 @@ const rpc = new RpcServer({}); const fn = new Fn({}); const demo = new Demo({}); +fn.fn('/a', function (a) { + return { a: a }; +}); + rpc.plugin(fn); rpc.plugin(demo); diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index 236bed4..1f139a9 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -33,13 +33,20 @@ export default class Plugable implements Strategy { public config; constructor(cfg?) { - this.config = Object.assign({}, cfg); + this.config = Object.assign( + { + bind: {}, + }, + cfg + ); this.name = 'base'; this.app = new Koa(); this.init = []; this.load = []; - this.use(this.getMiddleware()); this.compose = compose; + + // TODO: 此处最好改成mount + this.load.push(this.getMiddleware()); } proxy() { @@ -58,6 +65,7 @@ export default class Plugable implements Strategy { } getMiddleware() { + console.dir('getMiddleware'); const pre = this.pre(); const process = this.process(); const after = this.after(); diff --git a/packages/core2/src/core.ts b/packages/core2/src/core.ts index 870cf95..62d8fac 100644 --- a/packages/core2/src/core.ts +++ b/packages/core2/src/core.ts @@ -1,5 +1,5 @@ import debug from 'debug'; -const log = debug('@tomrpc/core'); +const log = console.log; //debug('@tomrpc/core'); export function mountMiddleware(routers) { log(routers); @@ -15,6 +15,7 @@ export function mountMiddleware(routers) { log(key); log(param); + log(routers[key]); if (routers[key]) { const args = [...param, ctx]; diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index f6fce39..a80d246 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -11,46 +11,42 @@ export default class Fn extends Plugable { constructor(cfg?: any) { super(cfg); + this.name = 'Fn'; this.prefix = '/api'; - // this.name = 'fn'; - - const a = this.a(); - const b = this.b(); - // console.dir(a + ''); - // this.addInit(a); - // this.addInit(b); - - const c = this.c(); - // this.addLoad(c); - - this.config['server']['fn'] = function (items) { - if (!this.config['functions']) this.config['functions'] = []; - if (Object.entries(items)) { - for (const [name, fn] of Object.entries(items)) { - if (isArrowFunction(fn)) { - console.log( - `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` - ); - } - if (this.rpcFunctions[name]) { - log(`add ${name}: ${fn}`); - console.log(`this.rpcFunctions[${name}] exisit`); - } - - this.rpcFunctions[name] = fn; - } - } else { - this.config['functions'].push(items); - } - }; } + fn(key, fn) { + console.dir('=this.config='); + console.dir(this.config); + if (!this.config['functions']) this.config['functions'] = {}; + this.config['functions'][key] = fn; + // if (Object.entries(items)) { + // // for (const [name, fn] of Object.entries(items)) { + // // if (isArrowFunction(fn)) { + // // console.log( + // // `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` + // // ); + // // } + // // if (this.rpcFunctions[name]) { + // // log(`add ${name}: ${fn}`); + // // console.log(`this.rpcFunctions[${name}] exisit`); + // // } + // // this.rpcFunctions[name] = fn; + // // } + // } else { + // this.config['functions'].push(items); + // } + } + process() { - return mountMiddleware(this.config['functions']); + console.dir("this.config['functions']"); + console.dir(this); + console.dir(this.serverConfig); + return mountMiddleware(this); } pre() { return async (ctx, next) => { - log('beforeOne'); + console.log('beforeOne'); const key = ctx.path.replace('/', '').split('/').join('.'); // this.config.beforeOne(ctx, key); @@ -60,7 +56,7 @@ export default class Fn extends Plugable { const supportMethods = []; httpMethods.forEach(function (m) { if (lastKey.indexOf(m) != -1) { - log(m); + console.log(m); supportMethods.push(m); return m; } @@ -68,7 +64,7 @@ export default class Fn extends Plugable { // console.log(supportMethods); if (supportMethods.length === 0) { - log('没有匹配到包含get/post等方法的函数'); + console.log('没有匹配到包含get/post等方法的函数'); await next(); } else if (ctx.method === supportMethods[0]) { log('匹配到包含get/post等方法的函数'); @@ -86,24 +82,4 @@ export default class Fn extends Plugable { log('beforeOne end'); }; } - - a() { - return async (ctx, next) => { - console.dir('a ' + ctx.path); - await next(); - }; - } - b() { - return async (ctx, next) => { - console.dir('b ' + ctx.path); - await next(); - }; - } - - c() { - return async (ctx, next) => { - console.dir('c ' + ctx.path); - await next(); - }; - } } diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 3f0103f..16801ff 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -111,7 +111,8 @@ export default class RpcServer { public mount() { console.dir('mount'); - // hooks + + // setting for (const plugin of this.plugins) { plugin.server = this; plugin.serverConfig = this.config; @@ -120,8 +121,20 @@ export default class RpcServer { if (plugin.name !== 'base') { console.error('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); } - this.config.plugin[plugin.name] = plugin.config; + console.log('mount plugin.config'); + console.log(plugin); + console.log(plugin.config); + console.log(plugin.config.bind); + for (const bindnName in plugin.config.bind) { + console.dir(bindnName); + this[bindnName] = plugin.config['bind'][bindnName]; + } + this.config[plugin.name] = plugin.config; + } + + // hooks + for (const plugin of this.plugins) { if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); // console.dir(plugin); From 3dff5b6103eaa8dd604c9b8b50ea78cf88ae9116 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 2 Nov 2023 12:02:18 +0800 Subject: [PATCH 023/101] chore: log --- packages/core2/src/server.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 16801ff..7e4ba26 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -135,15 +135,16 @@ export default class RpcServer { // hooks for (const plugin of this.plugins) { + console.dir('init stage'); if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); - // console.dir(plugin); // console.dir(this.config.hooks.init); } this.config.init(this); for (const plugin of this.plugins) { + console.dir('load stage'); if (plugin.load.length > 0) this.config.hooks.load.push(...plugin.load); // console.dir('load plugin'); // console.dir(plugin.load); @@ -151,18 +152,19 @@ export default class RpcServer { // console.dir(this.config.hooks.init); } + console.dir('load'); this.config.load(this); // mount app for (const plugin of this.plugins) { - // console.dir('plugin.proxy() ' + plugin.prefix); + console.dir('mount plugin ' + plugin.prefix); // console.dir(plugin.proxy()); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); this.app.use(mount(plugin.prefix, plugin.app)); } // 兜底的else - + console.dir('兜底的else'); this.app.use(this.config.hooks.default); // this.app.use(async (ctx, next) => { // console.dir(ctx.path); From ed5c616dbe0ae7418b27a2167ea4f9c6592f97f6 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 01:39:14 +0800 Subject: [PATCH 024/101] chore: refact --- packages/core2/app.ts | 2 +- packages/core2/src/__tests__/index.test.ts | 4 +- packages/core2/src/base.ts | 12 +- packages/core2/src/core.ts | 32 ---- packages/core2/src/fn.ts | 84 +++++--- packages/core2/src/index.ts | 213 +-------------------- packages/core2/src/server.ts | 22 ++- 7 files changed, 89 insertions(+), 280 deletions(-) delete mode 100644 packages/core2/src/core.ts diff --git a/packages/core2/app.ts b/packages/core2/app.ts index d9fa050..4889d1a 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -1,5 +1,5 @@ import Demo from './demo'; -import Fn from './src/fn'; +import { Fn } from './src/fn'; import RpcServer from './src/server'; const rpc = new RpcServer({}); diff --git a/packages/core2/src/__tests__/index.test.ts b/packages/core2/src/__tests__/index.test.ts index 70aa64c..faeed0e 100644 --- a/packages/core2/src/__tests__/index.test.ts +++ b/packages/core2/src/__tests__/index.test.ts @@ -1,11 +1,11 @@ import request from 'supertest'; import { describe, expect, it } from 'vitest'; -import { lib } from '..'; +// import { lib } from '..'; describe('lib', () => { it('should render lib', () => { - expect(lib()).toBe('lib'); + expect('lib').toBe('lib'); }); }); diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index 1f139a9..f375348 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -49,6 +49,10 @@ export default class Plugable implements Strategy { this.load.push(this.getMiddleware()); } + getConfig(ctx) { + return ctx[this.name]; + } + proxy() { return async (ctx, next) => { console.dir('proxy prefix=' + this.prefix); @@ -65,11 +69,11 @@ export default class Plugable implements Strategy { } getMiddleware() { - console.dir('getMiddleware'); + // console.dir('getMiddleware'); const pre = this.pre(); const process = this.process(); - const after = this.after(); - return compose([pre, process, after]); + const post = this.post(); + return compose([pre, process, post]); } pre() { @@ -79,7 +83,7 @@ export default class Plugable implements Strategy { console.dir('pre end'); }; } - after() { + post() { return async (ctx, next) => { console.dir('after'); await next(); diff --git a/packages/core2/src/core.ts b/packages/core2/src/core.ts deleted file mode 100644 index 62d8fac..0000000 --- a/packages/core2/src/core.ts +++ /dev/null @@ -1,32 +0,0 @@ -import debug from 'debug'; -const log = console.log; //debug('@tomrpc/core'); - -export function mountMiddleware(routers) { - log(routers); - return async (ctx, next) => { - log('mountMiddleware'); - const key = ctx.path.replace('/', '').split('/').join('.'); - - if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { - console.log('not match $p param, no process'); - ctx.body = 'not match $p param, no process'; - } else { - const param = ctx.method === 'POST' ? ctx.request.body : JSON.parse(ctx.query.$p); - - log(key); - log(param); - log(routers[key]); - - if (routers[key]) { - const args = [...param, ctx]; - // console.dir(args); - const result = routers[key].apply(ctx, args); - ctx.body = result; - } else { - const msg = JSON.stringify(ctx, null, 4); - ctx.body = ` not match path ${ctx.path} \n ctx = ${msg}`; - } - await next(); - } - }; -} diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index a80d246..ce0b55f 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -1,11 +1,10 @@ import debug from 'debug'; import Plugable from './base'; -import { mountMiddleware } from './core'; import { isArrowFunction, getHttpMethods } from './utils'; const log = debug('@tomrpc/core'); -export default class Fn extends Plugable { +export class Fn extends Plugable { // public name: string; constructor(cfg?: any) { @@ -15,38 +14,69 @@ export default class Fn extends Plugable { this.prefix = '/api'; } fn(key, fn) { - console.dir('=this.config='); - console.dir(this.config); + // console.dir('=this.config='); + // console.dir(this.config); if (!this.config['functions']) this.config['functions'] = {}; this.config['functions'][key] = fn; - // if (Object.entries(items)) { - // // for (const [name, fn] of Object.entries(items)) { - // // if (isArrowFunction(fn)) { - // // console.log( - // // `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` - // // ); - // // } - // // if (this.rpcFunctions[name]) { - // // log(`add ${name}: ${fn}`); - // // console.log(`this.rpcFunctions[${name}] exisit`); - // // } - // // this.rpcFunctions[name] = fn; - // // } - // } else { - // this.config['functions'].push(items); - // } + } + add(items) { + for (const [name, fn] of Object.entries(items)) { + if (isArrowFunction(fn)) { + console.log( + `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` + ); + } + if (this.config['functions'][name]) { + log(`add ${name}: ${fn}`); + console.log(`this.rpcFunctions[${name}] exisit`); + } + // this.rpcFunctions[name] = fn; + this.config['functions'][name] = fn; + } } process() { - console.dir("this.config['functions']"); - console.dir(this); - console.dir(this.serverConfig); - return mountMiddleware(this); + console.dir('process'); + return this.mount(); } + mount() { + return async (ctx, next) => { + const prefix = this.prefix; + const routers = this.config['functions']; + log(routers); + const path = ctx.path.replace(prefix, ''); + log('mountMiddleware' + ctx.path); + const key = '/' + path.replace('/', '').split('/').join('.'); + + if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { + console.log('not match $p param, no process'); + ctx.body = 'not match $p param, no process'; + } else { + const param = ctx.method === 'POST' ? ctx.request.body : JSON.parse(ctx.query.$p); + + log(key); + log(param); + log(routers[key]); + + if (routers[key]) { + const args = [...param, ctx]; + // console.dir(args); + const result = routers[key].apply(ctx, args); + // console.dir(result); + ctx.body = result; + } else { + const msg = JSON.stringify(ctx, null, 4); + ctx.body = ` not match path ${ctx.path} \n ctx = ${msg}`; + await next(); + } + // + } + }; + } pre() { return async (ctx, next) => { - console.log('beforeOne'); + // console.log('pre'); const key = ctx.path.replace('/', '').split('/').join('.'); // this.config.beforeOne(ctx, key); @@ -56,7 +86,7 @@ export default class Fn extends Plugable { const supportMethods = []; httpMethods.forEach(function (m) { if (lastKey.indexOf(m) != -1) { - console.log(m); + // console.log(m); supportMethods.push(m); return m; } @@ -64,7 +94,7 @@ export default class Fn extends Plugable { // console.log(supportMethods); if (supportMethods.length === 0) { - console.log('没有匹配到包含get/post等方法的函数'); + console.log(ctx.path + ',没有匹配到包含get/post等开头的函数'); await next(); } else if (ctx.method === supportMethods[0]) { log('匹配到包含get/post等方法的函数'); diff --git a/packages/core2/src/index.ts b/packages/core2/src/index.ts index 317bf99..ba3288e 100644 --- a/packages/core2/src/index.ts +++ b/packages/core2/src/index.ts @@ -1,209 +1,4 @@ -import { bodyParser } from '@koa/bodyparser'; -import debug from 'debug'; -import Koa from 'koa'; -import compose from 'koa-compose'; - -import { mountMiddleware } from './core'; -import { isArrowFunction, getHttpMethods } from './utils'; - -export const lib = () => 'lib'; - -const log = debug('@tomrpc/core'); - -export const LifeCycleConfig = { - hooks: { - init: [], - before: [], - load: [], - beforeMount: [], - afterMount: [], - after: [], - }, - init: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.init; - console.log(loadMiddlewares); - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - before: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.before; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - load: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.load; - console.log(loadMiddlewares); - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - after: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.after; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - beforeMount: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.beforeMount; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - afterMount: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.afterMount; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - beforeAll: async (ctx, next) => { - log('beforeAll'); - await next(); - log('beforeAll end'); - }, - beforeEach: async (ctx, next) => { - log('beforeEach'); - await next(); - log('beforeEach end'); - }, - afterEach: async (ctx, next) => { - log('afterEach'); - await next(); - log('afterEach end'); - }, - afterAll: async (ctx, next) => { - log('afterAll'); - await next(); - log('afterAll end'); - }, - beforeOne: function (ctx, key: string) { - log('beforeOne key=' + key); - }, - afterOne: function (ctx, key: string) { - log('afterOne key=' + key); - }, -}; - -export const createServer = function (config?: any) { - const _cfg = Object.assign(LifeCycleConfig, config); - - // 在app时用 - this.config = _cfg; - this.base = _cfg.base; - - const app = new Koa(); - app.use(bodyParser()); - - this.app = app; - this.use = app.use; - - // - app.use(_cfg.beforeAll); - - _cfg.before(this); - - return Object.assign(this, { - rpcFunctions: {}, - _mounted: false, - listen: function (port?: number) { - _cfg.init(this); - - _cfg.load(this); - - _cfg.beforeMount(this); - this.mount(); - _cfg.afterMount(this); - _cfg.after(this); - app.use(_cfg.afterAll); - - this.app.listen(port || 3000); - }, - add: function (items) { - for (const [name, fn] of Object.entries(items)) { - if (isArrowFunction(fn)) { - console.log( - `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` - ); - } - if (this.rpcFunctions[name]) { - log(`add ${name}: ${fn}`); - console.log(`this.rpcFunctions[${name}] exisit`); - } - - this.rpcFunctions[name] = fn; - } - }, - mount: function () { - log('mount'); - - if (!this._mounted) { - const mw = compose([ - _cfg.beforeEach, - async (ctx, next) => { - log('beforeOne'); - const key = ctx.path.replace('/', '').split('/').join('.'); - _cfg.beforeOne(ctx, key); - - const lastKey = key.split('.').pop(); - const httpMethods = getHttpMethods(); - - const supportMethods = []; - httpMethods.forEach(function (m) { - if (lastKey.indexOf(m) != -1) { - log(m); - supportMethods.push(m); - return m; - } - }); - // console.log(supportMethods); - - if (supportMethods.length === 0) { - log('没有匹配到包含get/post等方法的函数'); - await next(); - } else if (ctx.method === supportMethods[0]) { - log('匹配到包含get/post等方法的函数'); - await next(); - } else { - log('匹配到包含get/post等方法的函数,但method不对'); - ctx.body = - 'process fn:' + - lastKey + - ' , you need send ' + - supportMethods[0] + - ' request from client'; - } - - log('beforeOne end'); - }, - mountMiddleware(this.rpcFunctions), - async (ctx, next) => { - log('afterOne'); - const key = ctx.path.replace('/', '').split('/').join('.'); - _cfg.afterOne(ctx, key); - await next(); - log('afterOne end'); - }, - _cfg.afterEach, - ]); - app.use(mw); - this._mounted = true; - } - }, - dump: function (): void { - for (const [name, fn] of Object.entries(this.rpcFunctions)) { - console.log(`${name}: ${fn}`); - } - }, - - fn: function (name: string, fn: any) { - this.rpcFunctions[name] = fn; - }, - }); -}; +export * from './base'; +export * from './fn'; +export * from './server'; +export * from './utils'; diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 7e4ba26..5aa6f43 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -112,6 +112,7 @@ export default class RpcServer { public mount() { console.dir('mount'); + const cfg = {}; // setting for (const plugin of this.plugins) { plugin.server = this; @@ -122,17 +123,28 @@ export default class RpcServer { console.error('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); } console.log('mount plugin.config'); - console.log(plugin); - console.log(plugin.config); - console.log(plugin.config.bind); + // console.log(plugin); + // console.log(plugin.config); + // console.log(plugin.config.bind); for (const bindnName in plugin.config.bind) { console.dir(bindnName); - this[bindnName] = plugin.config['bind'][bindnName]; + // this[bindnName] = plugin.config['bind'][bindnName]; } this.config[plugin.name] = plugin.config; + cfg[plugin.name] = plugin; } + this.app.use(async (ctx, next) => { + // ; + for (const fn in cfg) { + // console.log('--' + fn); + ctx[fn] = cfg[fn]; + } + + await next(); + }); + // hooks for (const plugin of this.plugins) { console.dir('init stage'); @@ -158,7 +170,7 @@ export default class RpcServer { // mount app for (const plugin of this.plugins) { console.dir('mount plugin ' + plugin.prefix); - // console.dir(plugin.proxy()); + // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); this.app.use(mount(plugin.prefix, plugin.app)); } From 8f7822fe115a6f3f1c0e56229da97de18131d82f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 01:48:07 +0800 Subject: [PATCH 025/101] chore: refact --- packages/core2/demo.ts | 2 +- packages/core2/src/base.ts | 2 +- packages/core2/src/fn.ts | 8 +++++--- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/core2/demo.ts b/packages/core2/demo.ts index 79cec74..9af3bba 100644 --- a/packages/core2/demo.ts +++ b/packages/core2/demo.ts @@ -1,4 +1,4 @@ -import Plugable from './src/base'; +import { Plugable } from './src/base'; export default class Fn extends Plugable { // public name: string; diff --git a/packages/core2/src/base.ts b/packages/core2/src/base.ts index f375348..ea1f332 100644 --- a/packages/core2/src/base.ts +++ b/packages/core2/src/base.ts @@ -21,7 +21,7 @@ export interface Strategy { serverConfig; } -export default class Plugable implements Strategy { +export class Plugable implements Strategy { public init: any[] = []; public load: any[] = []; public name; diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index ce0b55f..fe797ac 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -1,6 +1,6 @@ import debug from 'debug'; -import Plugable from './base'; +import { Plugable } from './base'; import { isArrowFunction, getHttpMethods } from './utils'; const log = debug('@tomrpc/core'); @@ -94,8 +94,10 @@ export class Fn extends Plugable { // console.log(supportMethods); if (supportMethods.length === 0) { - console.log(ctx.path + ',没有匹配到包含get/post等开头的函数'); - await next(); + if (ctx.path.indexOf(this.prefix) != -1) { + console.log(ctx.path + ',没有匹配到包含get/post等开头的函数'); + await next(); + } } else if (ctx.method === supportMethods[0]) { log('匹配到包含get/post等方法的函数'); await next(); From b6e6e2a998b0a44342d9d8f7a0d69c47a1852e6d Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 12:10:02 +0800 Subject: [PATCH 026/101] chore: refact --- packages/core2/app.ts | 13 +++++++------ packages/core2/demo.ts | 2 +- packages/core2/src/fn.ts | 5 ++--- packages/core2/src/index.ts | 19 ++++++++++++++++++- packages/core2/src/{base.ts => plugin.ts} | 0 packages/core2/src/server.ts | 4 ++-- 6 files changed, 30 insertions(+), 13 deletions(-) rename packages/core2/src/{base.ts => plugin.ts} (100%) diff --git a/packages/core2/app.ts b/packages/core2/app.ts index 4889d1a..275efab 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -1,17 +1,18 @@ import Demo from './demo'; -import { Fn } from './src/fn'; -import RpcServer from './src/server'; +import { Fn, createServer } from './src/index'; +// import { RpcServer } from './src/server'; -const rpc = new RpcServer({}); +// const rpc = new RpcServer({}); +const rpc = createServer({}); const fn = new Fn({}); const demo = new Demo({}); -fn.fn('/a', function (a) { +rpc['fn']('/a', function (a) { return { a: a }; }); -rpc.plugin(fn); -rpc.plugin(demo); +// rpc.plugin(fn); +// rpc.plugin(demo); rpc.start(2091); diff --git a/packages/core2/demo.ts b/packages/core2/demo.ts index 9af3bba..503992f 100644 --- a/packages/core2/demo.ts +++ b/packages/core2/demo.ts @@ -1,4 +1,4 @@ -import { Plugable } from './src/base'; +import { Plugable } from './src/plugin'; export default class Fn extends Plugable { // public name: string; diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index fe797ac..a19272d 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -1,12 +1,10 @@ import debug from 'debug'; -import { Plugable } from './base'; +import { Plugable } from './plugin'; import { isArrowFunction, getHttpMethods } from './utils'; const log = debug('@tomrpc/core'); export class Fn extends Plugable { - // public name: string; - constructor(cfg?: any) { super(cfg); @@ -42,6 +40,7 @@ export class Fn extends Plugable { mount() { return async (ctx, next) => { + log(this); const prefix = this.prefix; const routers = this.config['functions']; log(routers); diff --git a/packages/core2/src/index.ts b/packages/core2/src/index.ts index ba3288e..a70bc00 100644 --- a/packages/core2/src/index.ts +++ b/packages/core2/src/index.ts @@ -1,4 +1,21 @@ -export * from './base'; +import { Fn } from './fn'; +import { RpcServer } from './server'; +export * from './plugin'; export * from './fn'; export * from './server'; export * from './utils'; + +export function createServer(cfg?: any) { + const rpc = new RpcServer(Object.assign({ fn: {} }, cfg)); + + const fn = new Fn(Object.assign({}, cfg.fn)); + + rpc['fn'] = function (key, fun) { + fn.fn(key, fun); + }; + // rpc['add'] = fn.add; + + rpc.plugin(fn); + + return rpc; +} diff --git a/packages/core2/src/base.ts b/packages/core2/src/plugin.ts similarity index 100% rename from packages/core2/src/base.ts rename to packages/core2/src/plugin.ts diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 5aa6f43..cbe081c 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -4,7 +4,7 @@ import Koa from 'koa'; const log = debug('@tomrpc/core2'); import mount from 'koa-mount'; -import { Strategy } from './base'; +import { Strategy } from './plugin'; export const LifeCycleConfig = { hooks: { @@ -78,7 +78,7 @@ export const LifeCycleConfig = { }, }; -export default class RpcServer { +export class RpcServer { /** * @type {Strategy} The Context maintains a reference to one of the Strategy * objects. The Context does not know the concrete class of a strategy. It From 9700c9ae84071c8ff8d327a288125932acf67f57 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 12:13:24 +0800 Subject: [PATCH 027/101] chore: refact --- packages/core2/README.md | 2 +- packages/core2/app.ts | 8 ++++++++ packages/core2/src/index.ts | 4 +++- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/packages/core2/README.md b/packages/core2/README.md index 6d80dda..e857da1 100644 --- a/packages/core2/README.md +++ b/packages/core2/README.md @@ -73,7 +73,7 @@ rpc.add({ // rpc.mount(); -rpc.listen(3000); +rpc.start(3000); ``` diff --git a/packages/core2/app.ts b/packages/core2/app.ts index 275efab..3e73c4e 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -12,6 +12,14 @@ rpc['fn']('/a', function (a) { return { a: a }; }); +rpc['add']({ + c: (a: string) => { + return a; + }, + a: function (a: string, b: string) { + return `${this.path} , ${a} c2 ${b}`; + }, +}); // rpc.plugin(fn); // rpc.plugin(demo); diff --git a/packages/core2/src/index.ts b/packages/core2/src/index.ts index a70bc00..b6e0fe7 100644 --- a/packages/core2/src/index.ts +++ b/packages/core2/src/index.ts @@ -13,7 +13,9 @@ export function createServer(cfg?: any) { rpc['fn'] = function (key, fun) { fn.fn(key, fun); }; - // rpc['add'] = fn.add; + rpc['add'] = function (items) { + fn.add(items); + }; rpc.plugin(fn); From c0b8e3ac38b9abec58fbaad770d2be60830928f3 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 12:51:08 +0800 Subject: [PATCH 028/101] chore: refact --- packages/core2/README.md | 32 -------------------------------- packages/core2/src/fn.ts | 7 ++++--- 2 files changed, 4 insertions(+), 35 deletions(-) diff --git a/packages/core2/README.md b/packages/core2/README.md index e857da1..812352b 100644 --- a/packages/core2/README.md +++ b/packages/core2/README.md @@ -75,35 +75,3 @@ rpc.add({ rpc.start(3000); ``` - - -const app = new Koa() - - -const app1 = new Koa() -const app2 = new Koa() -const app3 = new Koa() - -app.mount(app1.prefix,fn) -app.mount(app2.prefix,view) -app.mount(app3.prefix,static) - -=> - -const app = new Koa() - - - -app.plugin({ - prefix, - fn -}) - -return fn={ - name='fn' - init:[], - load:[] - -} -app.plugin(app2.prefix,view) -app.plugin(app3.prefix,static) diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index a19272d..d1385bd 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -13,9 +13,10 @@ export class Fn extends Plugable { } fn(key, fn) { // console.dir('=this.config='); - // console.dir(this.config); + // console.dir('fn=' + key); if (!this.config['functions']) this.config['functions'] = {}; - this.config['functions'][key] = fn; + const pre = key.split('')[0] == '/' ? '' : '/'; + this.config['functions'][pre + key] = fn; } add(items) { for (const [name, fn] of Object.entries(items)) { @@ -29,7 +30,7 @@ export class Fn extends Plugable { console.log(`this.rpcFunctions[${name}] exisit`); } // this.rpcFunctions[name] = fn; - this.config['functions'][name] = fn; + this.fn(name, fn); } } From 0d83de053fb19bf54b62e34457d593e201a08425 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 12:53:50 +0800 Subject: [PATCH 029/101] chore: refact --- packages/core2/app.ts | 4 ++-- packages/core2/src/index.ts | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/packages/core2/app.ts b/packages/core2/app.ts index 3e73c4e..ae61a8d 100644 --- a/packages/core2/app.ts +++ b/packages/core2/app.ts @@ -8,11 +8,11 @@ const rpc = createServer({}); const fn = new Fn({}); const demo = new Demo({}); -rpc['fn']('/a', function (a) { +rpc.fn('/a', function (a) { return { a: a }; }); -rpc['add']({ +rpc.add({ c: (a: string) => { return a; }, diff --git a/packages/core2/src/index.ts b/packages/core2/src/index.ts index b6e0fe7..73a46af 100644 --- a/packages/core2/src/index.ts +++ b/packages/core2/src/index.ts @@ -10,14 +10,14 @@ export function createServer(cfg?: any) { const fn = new Fn(Object.assign({}, cfg.fn)); - rpc['fn'] = function (key, fun) { - fn.fn(key, fun); - }; - rpc['add'] = function (items) { - fn.add(items); - }; - rpc.plugin(fn); - return rpc; + return Object.assign(rpc, { + fn: function (key, fun) { + fn.fn(key, fun); + }, + add: function (items) { + fn.add(items); + }, + }); } From 2e0688053afe1a7a8838df806328596d4e3190ab Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 15:24:27 +0800 Subject: [PATCH 030/101] chore: refact --- packages/core2/README.md | 55 ++++++++++++++++++++++++++++++++++++ packages/core2/demo.ts | 18 ++---------- packages/core2/src/fn.ts | 1 - packages/core2/src/server.ts | 20 ++++++------- packages/core2/src/utils.ts | 11 ++++++++ 5 files changed, 79 insertions(+), 26 deletions(-) diff --git a/packages/core2/README.md b/packages/core2/README.md index 812352b..5242e15 100644 --- a/packages/core2/README.md +++ b/packages/core2/README.md @@ -75,3 +75,58 @@ rpc.add({ rpc.start(3000); ``` + +## 实现插件 + +```ts +import { Plugable } from './src/plugin'; +export default class Fn extends Plugable { + constructor(cfg?) { + super(cfg); + this.prefix = '/demo'; + this.name = 'demo'; + const a = this.a(); + + this.addInit(a); + } + process() { + return async (ctx, next) => { + console.dir('process child'); + if (ctx.path === '/') { + ctx.body = { '/': 23 }; + } else { + // ctx.body = { '2323api': 23 }; + await next(); + } + }; + } + a() { + return async (ctx, next) => { + console.dir('a ' + ctx.path); + await next(); + }; + } +} +``` + +生命周期 + +- init:[] 可变数组 +- load:[] 可变数组 +- mount(plugin.prefix, plugin.app) 默认行为,不可操作 +- default 可在server配置里覆写 + +生命周期操作方法,在构造函数中,增加到对应的数组即可 + +- this.addInit(a); +- this.addLoad(b); + +被mount的中间件,实际上执行的是compose([pre, process, post]); + +> 在plugin构造函数里,执行了this.load.push(this.getMiddleware()); + +- pre(可选,返回值是Koa中间件) +- process(可选,返回值是Koa中间件) +- post(可选,返回值是Koa中间件) + + diff --git a/packages/core2/demo.ts b/packages/core2/demo.ts index 503992f..31294aa 100644 --- a/packages/core2/demo.ts +++ b/packages/core2/demo.ts @@ -1,21 +1,16 @@ import { Plugable } from './src/plugin'; export default class Fn extends Plugable { - // public name: string; - constructor(cfg?) { super(cfg); this.prefix = '/demo'; - // this.name = 'fn'; + this.name = ''; const a = this.a(); const b = this.b(); - // console.dir(a + ''); - // this.addInit(a); - // this.addInit(b); - const c = this.c(); - // this.addLoad(c); + this.addInit(a); + this.addInit(b); } process() { return async (ctx, next) => { @@ -41,11 +36,4 @@ export default class Fn extends Plugable { await next(); }; } - - c() { - return async (ctx, next) => { - console.dir('c ' + ctx.path); - await next(); - }; - } } diff --git a/packages/core2/src/fn.ts b/packages/core2/src/fn.ts index d1385bd..86d509b 100644 --- a/packages/core2/src/fn.ts +++ b/packages/core2/src/fn.ts @@ -35,7 +35,6 @@ export class Fn extends Plugable { } process() { - console.dir('process'); return this.mount(); } diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index cbe081c..056e837 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -1,10 +1,8 @@ import { bodyParser } from '@koa/bodyparser'; -import debug from 'debug'; import Koa from 'koa'; -const log = debug('@tomrpc/core2'); import mount from 'koa-mount'; -import { Strategy } from './plugin'; +import { Strategy, log } from './index'; export const LifeCycleConfig = { hooks: { @@ -21,7 +19,7 @@ export const LifeCycleConfig = { }, }, init: async (server) => { - console.dir('init'); + // console.dir('init'); // console.dir(server); const app = server.app; const loadMiddlewares = server.config.hooks.init; @@ -110,7 +108,7 @@ export class RpcServer { } public mount() { - console.dir('mount'); + // console.dir('mount'); const cfg = {}; // setting @@ -122,12 +120,12 @@ export class RpcServer { if (plugin.name !== 'base') { console.error('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); } - console.log('mount plugin.config'); + // console.log('mount plugin.config'); // console.log(plugin); // console.log(plugin.config); // console.log(plugin.config.bind); for (const bindnName in plugin.config.bind) { - console.dir(bindnName); + // console.dir(bindnName); // this[bindnName] = plugin.config['bind'][bindnName]; } @@ -145,7 +143,7 @@ export class RpcServer { await next(); }); - // hooks + // init for (const plugin of this.plugins) { console.dir('init stage'); if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); @@ -153,8 +151,10 @@ export class RpcServer { // console.dir(this.config.hooks.init); } + // use inits middleware this.config.init(this); + // load for (const plugin of this.plugins) { console.dir('load stage'); if (plugin.load.length > 0) this.config.hooks.load.push(...plugin.load); @@ -164,7 +164,7 @@ export class RpcServer { // console.dir(this.config.hooks.init); } - console.dir('load'); + // use loads middleware this.config.load(this); // mount app @@ -190,7 +190,7 @@ export class RpcServer { */ public start(port?: number): void { const _port = port || 3000; - console.dir(_port); + // console.dir(_port); this.config.before(this); diff --git a/packages/core2/src/utils.ts b/packages/core2/src/utils.ts index fd9264e..caaf594 100644 --- a/packages/core2/src/utils.ts +++ b/packages/core2/src/utils.ts @@ -1,3 +1,6 @@ +import debug from 'debug'; +const debugLog = debug('@tomrpc/core'); + export const isArrowFunction = (func) => { if (typeof func === 'function') { const source = func.toString(); @@ -36,3 +39,11 @@ export function getHttpMethods() { 'connect', ]; } + +export function log(msg, debugFlag?) { + if (debugFlag) { + console.log(msg); + } else { + debugLog(msg); + } +} From 97168b818e0b93baec83537dd5325f7b2c7b6f27 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 15:43:31 +0800 Subject: [PATCH 031/101] chore: refact --- packages/core2/README.md | 13 ++++++---- packages/core2/demo.ts | 2 +- packages/core2/src/server.ts | 46 +++++++----------------------------- 3 files changed, 18 insertions(+), 43 deletions(-) diff --git a/packages/core2/README.md b/packages/core2/README.md index 5242e15..1e3b1ae 100644 --- a/packages/core2/README.md +++ b/packages/core2/README.md @@ -111,10 +111,15 @@ export default class Fn extends Plugable { 生命周期 -- init:[] 可变数组 -- load:[] 可变数组 -- mount(plugin.prefix, plugin.app) 默认行为,不可操作 -- default 可在server配置里覆写 +- before:[] 可变数组 + - init:[] 可变数组 + - load:[] 可变数组 + - mount(plugin.prefix, plugin.app) 默认行为,不可操作 + - pre(可选,返回值是 Koa 中间件) + - process(可选,返回值是 Koa 中间件) + - post(可选,返回值是 Koa 中间件) + - config.hooks.default 可在server配置里覆写 +- after:[] 可变数组 生命周期操作方法,在构造函数中,增加到对应的数组即可 diff --git a/packages/core2/demo.ts b/packages/core2/demo.ts index 31294aa..0b89059 100644 --- a/packages/core2/demo.ts +++ b/packages/core2/demo.ts @@ -4,7 +4,7 @@ export default class Fn extends Plugable { super(cfg); this.prefix = '/demo'; - this.name = ''; + this.name = 'demo'; const a = this.a(); const b = this.b(); diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index 056e837..aa25c3b 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -9,8 +9,6 @@ export const LifeCycleConfig = { init: [], before: [], load: [], - beforeMount: [], - afterMount: [], after: [], default: async (ctx, next) => { log('default'); @@ -18,18 +16,19 @@ export const LifeCycleConfig = { log('default end'); }, }, - init: async (server) => { - // console.dir('init'); - // console.dir(server); + + before: async (server) => { const app = server.app; - const loadMiddlewares = server.config.hooks.init; + const loadMiddlewares = server.config.hooks.before; loadMiddlewares.forEach((mw) => { app.use(mw); }); }, - before: async (server) => { + init: async (server) => { + // console.dir('init'); + // console.dir(server); const app = server.app; - const loadMiddlewares = server.config.hooks.before; + const loadMiddlewares = server.config.hooks.init; loadMiddlewares.forEach((mw) => { app.use(mw); }); @@ -48,32 +47,6 @@ export const LifeCycleConfig = { app.use(mw); }); }, - beforeAll: async (ctx, next) => { - log('beforeAll'); - await next(); - log('beforeAll end'); - }, - beforeEach: async (ctx, next) => { - log('beforeEach'); - await next(); - log('beforeEach end'); - }, - afterEach: async (ctx, next) => { - log('afterEach'); - await next(); - log('afterEach end'); - }, - afterAll: async (ctx, next) => { - log('afterAll'); - await next(); - log('afterAll end'); - }, - beforeOne: function (ctx, key: string) { - log('beforeOne key=' + key); - }, - afterOne: function (ctx, key: string) { - log('afterOne key=' + key); - }, }; export class RpcServer { @@ -117,7 +90,7 @@ export class RpcServer { plugin.serverConfig = this.config; // set config namespace - if (plugin.name !== 'base') { + if (plugin.name === 'base') { console.error('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); } // console.log('mount plugin.config'); @@ -194,12 +167,9 @@ export class RpcServer { this.config.before(this); - // this.config.beforeMount(this); this.mount(); - // this.config.afterMount(this); this.config.after(this); - // this.app.use(this.config.afterAll); this.app.listen(_port, (err) => { if (err) { From 618c5bcfdefc39446de0deaaae8ca0ae954eaa93 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 16:04:47 +0800 Subject: [PATCH 032/101] chore: refact --- packages/core2/README.md | 12 ++++++++++++ packages/core2/src/server.ts | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/packages/core2/README.md b/packages/core2/README.md index 1e3b1ae..c42c68c 100644 --- a/packages/core2/README.md +++ b/packages/core2/README.md @@ -135,3 +135,15 @@ export default class Fn extends Plugable { - post(可选,返回值是Koa中间件) +## RpcServer + + +```js +const rpc = new RpcServer({}); + +const fn = new Fn({}); + +rpc.plugin(fn); + +rpc.start(3000) +``` diff --git a/packages/core2/src/server.ts b/packages/core2/src/server.ts index aa25c3b..11e5047 100644 --- a/packages/core2/src/server.ts +++ b/packages/core2/src/server.ts @@ -175,7 +175,7 @@ export class RpcServer { if (err) { console.error(err); } else { - console.log('Koa app listening on ' + _port); + console.log('@tomrpc/core listening on ' + _port); } }); } From d3854d32b517270aacda44ee79bc832179622be8 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 17:02:01 +0800 Subject: [PATCH 033/101] chore: refact --- example/src/app.ts | 5 - packages/core/README.md | 89 +- packages/{core2 => core}/app.ts | 0 packages/{core2 => core}/demo.ts | 0 packages/core/package.json | 3 +- packages/core/src/__tests__/index.test.ts | 4 +- packages/core/src/core.ts | 31 - packages/{core2 => core}/src/fn.ts | 0 packages/core/src/index.ts | 216 +---- packages/{core2 => core}/src/plugin.ts | 0 packages/{core2 => core}/src/server.ts | 0 packages/core/src/utils.ts | 11 + packages/core2/CHANGELOG.md | 13 - packages/core2/README.md | 149 ---- packages/core2/package-lock.json | 988 --------------------- packages/core2/package.json | 41 - packages/core2/src/__tests__/index.test.ts | 42 - packages/core2/src/index.ts | 23 - packages/core2/src/utils.ts | 49 - packages/core2/tsconfig.json | 8 - packages/core2/tsup.config.cjs | 12 - packages/core2/vitest.config.cjs | 10 - 22 files changed, 104 insertions(+), 1590 deletions(-) rename packages/{core2 => core}/app.ts (100%) rename packages/{core2 => core}/demo.ts (100%) delete mode 100644 packages/core/src/core.ts rename packages/{core2 => core}/src/fn.ts (100%) rename packages/{core2 => core}/src/plugin.ts (100%) rename packages/{core2 => core}/src/server.ts (100%) delete mode 100644 packages/core2/CHANGELOG.md delete mode 100644 packages/core2/README.md delete mode 100644 packages/core2/package-lock.json delete mode 100644 packages/core2/package.json delete mode 100644 packages/core2/src/__tests__/index.test.ts delete mode 100644 packages/core2/src/index.ts delete mode 100644 packages/core2/src/utils.ts delete mode 100644 packages/core2/tsconfig.json delete mode 100644 packages/core2/tsup.config.cjs delete mode 100644 packages/core2/vitest.config.cjs diff --git a/example/src/app.ts b/example/src/app.ts index 66bb193..cbf84e5 100644 --- a/example/src/app.ts +++ b/example/src/app.ts @@ -5,11 +5,6 @@ import mount from '@tomrpc/mount'; (async () => { const rpc = createServer({ base: import.meta.url, - beforeOne: function (ctx: any, key: string) { - console.log(ctx.path); - console.log(ctx.method); - console.log('beforeOne key=' + key); - }, }); rpc.fn('getUsers', function (a: string) { diff --git a/packages/core/README.md b/packages/core/README.md index ae25b3c..486a911 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -4,24 +4,11 @@ ```js const rpc = createServer({ - beforeOne: function (ctx: any, key: string) { - console.log(ctx.path); - console.log(ctx.method); - console.log('beforeOne key=' + key); - }, + ... }); ``` -## lifecyle - -- beforeAll(中间件) - - beforeEach(中间件) - - beforeOne(普通函数) - - 函数执行 - - afterOne(普通函数) - - afterEach(中间件) -- afterAll(中间件) ## example @@ -73,5 +60,77 @@ rpc.add({ // rpc.mount(); -rpc.listen(3000); +rpc.start(3000); +``` + +## 实现插件 + +```ts +import { Plugable } from './src/plugin'; +export default class Fn extends Plugable { + constructor(cfg?) { + super(cfg); + this.prefix = '/demo'; + this.name = 'demo'; + const a = this.a(); + + this.addInit(a); + } + process() { + return async (ctx, next) => { + console.dir('process child'); + if (ctx.path === '/') { + ctx.body = { '/': 23 }; + } else { + // ctx.body = { '2323api': 23 }; + await next(); + } + }; + } + a() { + return async (ctx, next) => { + console.dir('a ' + ctx.path); + await next(); + }; + } +} +``` + +生命周期 + +- before:[] 可变数组 + - init:[] 可变数组 + - load:[] 可变数组 + - mount(plugin.prefix, plugin.app) 默认行为,不可操作 + - pre(可选,返回值是 Koa 中间件) + - process(可选,返回值是 Koa 中间件) + - post(可选,返回值是 Koa 中间件) + - config.hooks.default 可在server配置里覆写 +- after:[] 可变数组 + +生命周期操作方法,在构造函数中,增加到对应的数组即可 + +- this.addInit(a); +- this.addLoad(b); + +被mount的中间件,实际上执行的是compose([pre, process, post]); + +> 在plugin构造函数里,执行了this.load.push(this.getMiddleware()); + +- pre(可选,返回值是Koa中间件) +- process(可选,返回值是Koa中间件) +- post(可选,返回值是Koa中间件) + + +## RpcServer + + +```js +const rpc = new RpcServer({}); + +const fn = new Fn({}); + +rpc.plugin(fn); + +rpc.start(3000) ``` diff --git a/packages/core2/app.ts b/packages/core/app.ts similarity index 100% rename from packages/core2/app.ts rename to packages/core/app.ts diff --git a/packages/core2/demo.ts b/packages/core/demo.ts similarity index 100% rename from packages/core2/demo.ts rename to packages/core/demo.ts diff --git a/packages/core/package.json b/packages/core/package.json index 508928b..f1dc0f6 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -35,6 +35,7 @@ "@koa/bodyparser": "^5.0.0", "debug": "^4.3.4", "koa": "^2.14.2", - "koa-compose": "^4.1.0" + "koa-compose": "^4.1.0", + "koa-mount": "^4.0.0" } } diff --git a/packages/core/src/__tests__/index.test.ts b/packages/core/src/__tests__/index.test.ts index 70aa64c..faeed0e 100644 --- a/packages/core/src/__tests__/index.test.ts +++ b/packages/core/src/__tests__/index.test.ts @@ -1,11 +1,11 @@ import request from 'supertest'; import { describe, expect, it } from 'vitest'; -import { lib } from '..'; +// import { lib } from '..'; describe('lib', () => { it('should render lib', () => { - expect(lib()).toBe('lib'); + expect('lib').toBe('lib'); }); }); diff --git a/packages/core/src/core.ts b/packages/core/src/core.ts deleted file mode 100644 index 870cf95..0000000 --- a/packages/core/src/core.ts +++ /dev/null @@ -1,31 +0,0 @@ -import debug from 'debug'; -const log = debug('@tomrpc/core'); - -export function mountMiddleware(routers) { - log(routers); - return async (ctx, next) => { - log('mountMiddleware'); - const key = ctx.path.replace('/', '').split('/').join('.'); - - if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { - console.log('not match $p param, no process'); - ctx.body = 'not match $p param, no process'; - } else { - const param = ctx.method === 'POST' ? ctx.request.body : JSON.parse(ctx.query.$p); - - log(key); - log(param); - - if (routers[key]) { - const args = [...param, ctx]; - // console.dir(args); - const result = routers[key].apply(ctx, args); - ctx.body = result; - } else { - const msg = JSON.stringify(ctx, null, 4); - ctx.body = ` not match path ${ctx.path} \n ctx = ${msg}`; - } - await next(); - } - }; -} diff --git a/packages/core2/src/fn.ts b/packages/core/src/fn.ts similarity index 100% rename from packages/core2/src/fn.ts rename to packages/core/src/fn.ts diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 317bf99..73a46af 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,209 +1,23 @@ -import { bodyParser } from '@koa/bodyparser'; -import debug from 'debug'; -import Koa from 'koa'; -import compose from 'koa-compose'; +import { Fn } from './fn'; +import { RpcServer } from './server'; +export * from './plugin'; +export * from './fn'; +export * from './server'; +export * from './utils'; -import { mountMiddleware } from './core'; -import { isArrowFunction, getHttpMethods } from './utils'; +export function createServer(cfg?: any) { + const rpc = new RpcServer(Object.assign({ fn: {} }, cfg)); -export const lib = () => 'lib'; + const fn = new Fn(Object.assign({}, cfg.fn)); -const log = debug('@tomrpc/core'); + rpc.plugin(fn); -export const LifeCycleConfig = { - hooks: { - init: [], - before: [], - load: [], - beforeMount: [], - afterMount: [], - after: [], - }, - init: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.init; - console.log(loadMiddlewares); - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - before: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.before; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - load: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.load; - console.log(loadMiddlewares); - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - after: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.after; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - beforeMount: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.beforeMount; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - afterMount: async (server) => { - const app = server.app; - const loadMiddlewares = server.config.hooks.afterMount; - loadMiddlewares.forEach((mw) => { - app.use(mw); - }); - }, - beforeAll: async (ctx, next) => { - log('beforeAll'); - await next(); - log('beforeAll end'); - }, - beforeEach: async (ctx, next) => { - log('beforeEach'); - await next(); - log('beforeEach end'); - }, - afterEach: async (ctx, next) => { - log('afterEach'); - await next(); - log('afterEach end'); - }, - afterAll: async (ctx, next) => { - log('afterAll'); - await next(); - log('afterAll end'); - }, - beforeOne: function (ctx, key: string) { - log('beforeOne key=' + key); - }, - afterOne: function (ctx, key: string) { - log('afterOne key=' + key); - }, -}; - -export const createServer = function (config?: any) { - const _cfg = Object.assign(LifeCycleConfig, config); - - // 在app时用 - this.config = _cfg; - this.base = _cfg.base; - - const app = new Koa(); - app.use(bodyParser()); - - this.app = app; - this.use = app.use; - - // - app.use(_cfg.beforeAll); - - _cfg.before(this); - - return Object.assign(this, { - rpcFunctions: {}, - _mounted: false, - listen: function (port?: number) { - _cfg.init(this); - - _cfg.load(this); - - _cfg.beforeMount(this); - this.mount(); - _cfg.afterMount(this); - _cfg.after(this); - app.use(_cfg.afterAll); - - this.app.listen(port || 3000); + return Object.assign(rpc, { + fn: function (key, fun) { + fn.fn(key, fun); }, add: function (items) { - for (const [name, fn] of Object.entries(items)) { - if (isArrowFunction(fn)) { - console.log( - `this.rpcFunctions[${name}] is arrow function, please use ctx as param, not this` - ); - } - if (this.rpcFunctions[name]) { - log(`add ${name}: ${fn}`); - console.log(`this.rpcFunctions[${name}] exisit`); - } - - this.rpcFunctions[name] = fn; - } - }, - mount: function () { - log('mount'); - - if (!this._mounted) { - const mw = compose([ - _cfg.beforeEach, - async (ctx, next) => { - log('beforeOne'); - const key = ctx.path.replace('/', '').split('/').join('.'); - _cfg.beforeOne(ctx, key); - - const lastKey = key.split('.').pop(); - const httpMethods = getHttpMethods(); - - const supportMethods = []; - httpMethods.forEach(function (m) { - if (lastKey.indexOf(m) != -1) { - log(m); - supportMethods.push(m); - return m; - } - }); - // console.log(supportMethods); - - if (supportMethods.length === 0) { - log('没有匹配到包含get/post等方法的函数'); - await next(); - } else if (ctx.method === supportMethods[0]) { - log('匹配到包含get/post等方法的函数'); - await next(); - } else { - log('匹配到包含get/post等方法的函数,但method不对'); - ctx.body = - 'process fn:' + - lastKey + - ' , you need send ' + - supportMethods[0] + - ' request from client'; - } - - log('beforeOne end'); - }, - mountMiddleware(this.rpcFunctions), - async (ctx, next) => { - log('afterOne'); - const key = ctx.path.replace('/', '').split('/').join('.'); - _cfg.afterOne(ctx, key); - await next(); - log('afterOne end'); - }, - _cfg.afterEach, - ]); - app.use(mw); - this._mounted = true; - } - }, - dump: function (): void { - for (const [name, fn] of Object.entries(this.rpcFunctions)) { - console.log(`${name}: ${fn}`); - } - }, - - fn: function (name: string, fn: any) { - this.rpcFunctions[name] = fn; + fn.add(items); }, }); -}; +} diff --git a/packages/core2/src/plugin.ts b/packages/core/src/plugin.ts similarity index 100% rename from packages/core2/src/plugin.ts rename to packages/core/src/plugin.ts diff --git a/packages/core2/src/server.ts b/packages/core/src/server.ts similarity index 100% rename from packages/core2/src/server.ts rename to packages/core/src/server.ts diff --git a/packages/core/src/utils.ts b/packages/core/src/utils.ts index fd9264e..caaf594 100644 --- a/packages/core/src/utils.ts +++ b/packages/core/src/utils.ts @@ -1,3 +1,6 @@ +import debug from 'debug'; +const debugLog = debug('@tomrpc/core'); + export const isArrowFunction = (func) => { if (typeof func === 'function') { const source = func.toString(); @@ -36,3 +39,11 @@ export function getHttpMethods() { 'connect', ]; } + +export function log(msg, debugFlag?) { + if (debugFlag) { + console.log(msg); + } else { + debugLog(msg); + } +} diff --git a/packages/core2/CHANGELOG.md b/packages/core2/CHANGELOG.md deleted file mode 100644 index fcf2e5b..0000000 --- a/packages/core2/CHANGELOG.md +++ /dev/null @@ -1,13 +0,0 @@ -# @tomrpc/core - -## 1.0.0 - -### Major Changes - -- v0.1.1 - -## 0.1.1 - -### Patch Changes - -- init diff --git a/packages/core2/README.md b/packages/core2/README.md deleted file mode 100644 index c42c68c..0000000 --- a/packages/core2/README.md +++ /dev/null @@ -1,149 +0,0 @@ -# @tomrpc/core - -## create - -```js -const rpc = createServer({ - beforeOne: function (ctx: any, key: string) { - console.log(ctx.path); - console.log(ctx.method); - console.log('beforeOne key=' + key); - }, -}); - -``` - -## lifecyle - -- beforeAll(中间件) - - beforeEach(中间件) - - beforeOne(普通函数) - - 函数执行 - - afterOne(普通函数) - - afterEach(中间件) -- afterAll(中间件) - -## example - -```js -import { createServer } from '@tomrpc/core'; - -const rpc = createServer({ - beforeOne: function (ctx: any, key: string) { - console.log(ctx.path); - console.log(ctx.method); - console.log('beforeOne key=' + key); - }, -}); - -rpc.fn('a', (a: string) => { - return a; -}); - -rpc.fn('a.a', (a: string, ctx: any) => { - // console.dir(ctx); - if (ctx.method === 'POST') { - console.dir('post'); - return { - a: a, - // b: b, - }; - } else { - console.dir('get' + ctx.method); - return a; - } -}); - -rpc.fn('b', () => { - console.dir('test b'); -}); - -rpc.add({ - c: (a: string) => { - return a; - }, - a: function (a: string, b: string) { - return `${this.path} , ${a} c2 ${b}`; - }, -}); - -// https://bobbyhadz.com/blog/typescript-no-overload-matches-this-call -// rpc.dump(); -// console.dir(rpc.dump()); - -// rpc.mount(); - -rpc.start(3000); -``` - -## 实现插件 - -```ts -import { Plugable } from './src/plugin'; -export default class Fn extends Plugable { - constructor(cfg?) { - super(cfg); - this.prefix = '/demo'; - this.name = 'demo'; - const a = this.a(); - - this.addInit(a); - } - process() { - return async (ctx, next) => { - console.dir('process child'); - if (ctx.path === '/') { - ctx.body = { '/': 23 }; - } else { - // ctx.body = { '2323api': 23 }; - await next(); - } - }; - } - a() { - return async (ctx, next) => { - console.dir('a ' + ctx.path); - await next(); - }; - } -} -``` - -生命周期 - -- before:[] 可变数组 - - init:[] 可变数组 - - load:[] 可变数组 - - mount(plugin.prefix, plugin.app) 默认行为,不可操作 - - pre(可选,返回值是 Koa 中间件) - - process(可选,返回值是 Koa 中间件) - - post(可选,返回值是 Koa 中间件) - - config.hooks.default 可在server配置里覆写 -- after:[] 可变数组 - -生命周期操作方法,在构造函数中,增加到对应的数组即可 - -- this.addInit(a); -- this.addLoad(b); - -被mount的中间件,实际上执行的是compose([pre, process, post]); - -> 在plugin构造函数里,执行了this.load.push(this.getMiddleware()); - -- pre(可选,返回值是Koa中间件) -- process(可选,返回值是Koa中间件) -- post(可选,返回值是Koa中间件) - - -## RpcServer - - -```js -const rpc = new RpcServer({}); - -const fn = new Fn({}); - -rpc.plugin(fn); - -rpc.start(3000) -``` diff --git a/packages/core2/package-lock.json b/packages/core2/package-lock.json deleted file mode 100644 index b2c9859..0000000 --- a/packages/core2/package-lock.json +++ /dev/null @@ -1,988 +0,0 @@ -{ - "name": "@httprpc/core", - "version": "0.0.1", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "name": "@httprpc/core", - "version": "0.0.1", - "license": "MIT", - "dependencies": { - "@koa/bodyparser": "^5.0.0", - "debug": "^4.3.4", - "koa": "^2.14.2" - }, - "devDependencies": { - "vitest": "^0.34.6", - "@vitest/coverage-v8": "^0.34.6", - "happy-dom": "^6.0.4", - "supertest": "^6.3.3" - } - }, - "../../node_modules/.pnpm/@vitest+coverage-v8@0.34.2/node_modules/@vitest/coverage-v8": { - "version": "0.34.2", - "dev": true, - "license": "MIT", - "dependencies": { - "@ampproject/remapping": "^2.2.1", - "@bcoe/v8-coverage": "^0.2.3", - "istanbul-lib-coverage": "^3.2.0", - "istanbul-lib-report": "^3.0.1", - "istanbul-lib-source-maps": "^4.0.1", - "istanbul-reports": "^3.1.5", - "magic-string": "^0.30.1", - "picocolors": "^1.0.0", - "std-env": "^3.3.3", - "test-exclude": "^6.0.0", - "v8-to-istanbul": "^9.1.0" - }, - "devDependencies": { - "@types/istanbul-lib-coverage": "^2.0.4", - "@types/istanbul-lib-report": "^3.0.0", - "@types/istanbul-lib-source-maps": "^4.0.1", - "@types/istanbul-reports": "^3.0.1", - "pathe": "^1.1.1", - "vite-node": "0.34.2", - "vitest": "0.34.2" - }, - "funding": { - "url": "https://opencollective.com/vitest" - }, - "peerDependencies": { - "vitest": ">=0.32.0 <1" - } - }, - "../../node_modules/.pnpm/happy-dom@6.0.4/node_modules/happy-dom": { - "version": "6.0.4", - "dev": true, - "license": "MIT", - "dependencies": { - "css.escape": "^1.5.1", - "he": "^1.2.0", - "node-fetch": "^2.x.x", - "sync-request": "^6.1.0", - "webidl-conversions": "^7.0.0", - "whatwg-encoding": "^2.0.0", - "whatwg-mimetype": "^3.0.0" - }, - "devDependencies": { - "@types/he": "^1.1.2", - "@types/jest": "^27.4.1", - "@types/node": "^15.6.0", - "@types/node-fetch": "^2.6.1", - "@typescript-eslint/eslint-plugin": "^5.16.0", - "@typescript-eslint/parser": "^5.16.0", - "eslint": "^8.11.0", - "eslint-config-prettier": "^8.5.0", - "eslint-plugin-filenames": "^1.3.2", - "eslint-plugin-import": "^2.25.4", - "eslint-plugin-jest": "^26.1.2", - "eslint-plugin-jsdoc": "^38.0.6", - "eslint-plugin-json": "^3.1.0", - "eslint-plugin-prettier": "^4.0.0", - "jest": "^27.5.1", - "prettier": "^2.6.0", - "ts-jest": "^27.1.3", - "typescript": "^4.6.2" - } - }, - "node_modules/@koa/bodyparser": { - "version": "5.0.0", - "resolved": "http://bnpm.byted.org/@koa/bodyparser/-/bodyparser-5.0.0.tgz", - "integrity": "sha512-JEiZVe2e85qPOqA+Nw/SJC5fkFw3XSekh0RSoqz5F6lFYuhEspgqAb972rQRCJesv27QUsz96vU/Vb92wF1GUg==", - "license": "MIT", - "dependencies": { - "co-body": "^6.1.0", - "lodash.merge": "^4.6.2", - "type-is": "^1.6.18" - }, - "engines": { - "node": ">= 16" - } - }, - "node_modules/@vitest/coverage-v8": { - "resolved": "../../node_modules/.pnpm/@vitest+coverage-v8@0.34.2/node_modules/@vitest/coverage-v8", - "link": true - }, - "node_modules/accepts": { - "version": "1.3.8", - "resolved": "http://bnpm.byted.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", - "license": "MIT", - "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/asap": { - "version": "2.0.6", - "resolved": "http://bnpm.byted.org/asap/-/asap-2.0.6.tgz", - "integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==", - "dev": true, - "license": "MIT" - }, - "node_modules/asynckit": { - "version": "0.4.0", - "resolved": "http://bnpm.byted.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/bytes": { - "version": "3.1.2", - "resolved": "http://bnpm.byted.org/bytes/-/bytes-3.1.2.tgz", - "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/cache-content-type": { - "version": "1.0.1", - "resolved": "http://bnpm.byted.org/cache-content-type/-/cache-content-type-1.0.1.tgz", - "integrity": "sha512-IKufZ1o4Ut42YUrZSo8+qnMTrFuKkvyoLXUywKz9GJ5BrhOFGhLdkx9sG4KAnVvbY6kEcSFjLQul+DVmBm2bgA==", - "license": "MIT", - "dependencies": { - "mime-types": "^2.1.18", - "ylru": "^1.2.0" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/call-bind": { - "version": "1.0.2", - "resolved": "http://bnpm.byted.org/call-bind/-/call-bind-1.0.2.tgz", - "integrity": "sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.1", - "get-intrinsic": "^1.0.2" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/co": { - "version": "4.6.0", - "resolved": "http://bnpm.byted.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "license": "MIT", - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } - }, - "node_modules/co-body": { - "version": "6.1.0", - "resolved": "http://bnpm.byted.org/co-body/-/co-body-6.1.0.tgz", - "integrity": "sha512-m7pOT6CdLN7FuXUcpuz/8lfQ/L77x8SchHCF4G0RBTJO20Wzmhn5Sp4/5WsKy8OSpifBSUrmg83qEqaDHdyFuQ==", - "license": "MIT", - "dependencies": { - "inflation": "^2.0.0", - "qs": "^6.5.2", - "raw-body": "^2.3.3", - "type-is": "^1.6.16" - } - }, - "node_modules/combined-stream": { - "version": "1.0.8", - "resolved": "http://bnpm.byted.org/combined-stream/-/combined-stream-1.0.8.tgz", - "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, - "license": "MIT", - "dependencies": { - "delayed-stream": "~1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/component-emitter": { - "version": "1.3.0", - "resolved": "http://bnpm.byted.org/component-emitter/-/component-emitter-1.3.0.tgz", - "integrity": "sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==", - "dev": true, - "license": "MIT" - }, - "node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "http://bnpm.byted.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", - "license": "MIT", - "dependencies": { - "safe-buffer": "5.2.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/content-type": { - "version": "1.0.5", - "resolved": "http://bnpm.byted.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/cookiejar": { - "version": "2.1.4", - "resolved": "http://bnpm.byted.org/cookiejar/-/cookiejar-2.1.4.tgz", - "integrity": "sha512-LDx6oHrK+PhzLKJU9j5S7/Y3jM/mUHvD/DeI1WQmJn652iPC5Y4TBzC9l+5OMOXlyTTA+SmVUPm0HQUwpD5Jqw==", - "dev": true, - "license": "MIT" - }, - "node_modules/cookies": { - "version": "0.8.0", - "resolved": "http://bnpm.byted.org/cookies/-/cookies-0.8.0.tgz", - "integrity": "sha512-8aPsApQfebXnuI+537McwYsDtjVxGm8gTIzQI3FDW6t5t/DAhERxtnbEPN/8RX+uZthoz4eCOgloXaE5cYyNow==", - "license": "MIT", - "dependencies": { - "depd": "~2.0.0", - "keygrip": "~1.1.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/debug": { - "version": "4.3.4", - "resolved": "http://bnpm.byted.org/debug/-/debug-4.3.4.tgz", - "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", - "license": "MIT", - "dependencies": { - "ms": "2.1.2" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/deep-equal": { - "version": "1.0.1", - "resolved": "http://bnpm.byted.org/deep-equal/-/deep-equal-1.0.1.tgz", - "integrity": "sha512-bHtC0iYvWhyaTzvV3CZgPeZQqCOBGyGsVV7v4eevpdkLHfiSrXUdBG+qAuSz4RI70sszvjQ1QSZ98An1yNwpSw==", - "license": "MIT" - }, - "node_modules/delayed-stream": { - "version": "1.0.0", - "resolved": "http://bnpm.byted.org/delayed-stream/-/delayed-stream-1.0.0.tgz", - "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.4.0" - } - }, - "node_modules/delegates": { - "version": "1.0.0", - "resolved": "http://bnpm.byted.org/delegates/-/delegates-1.0.0.tgz", - "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", - "license": "MIT" - }, - "node_modules/depd": { - "version": "2.0.0", - "resolved": "http://bnpm.byted.org/depd/-/depd-2.0.0.tgz", - "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "http://bnpm.byted.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "license": "MIT", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/dezalgo": { - "version": "1.0.4", - "resolved": "http://bnpm.byted.org/dezalgo/-/dezalgo-1.0.4.tgz", - "integrity": "sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==", - "dev": true, - "license": "ISC", - "dependencies": { - "asap": "^2.0.0", - "wrappy": "1" - } - }, - "node_modules/ee-first": { - "version": "1.1.1", - "resolved": "http://bnpm.byted.org/ee-first/-/ee-first-1.1.1.tgz", - "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==", - "license": "MIT" - }, - "node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "http://bnpm.byted.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/escape-html": { - "version": "1.0.3", - "resolved": "http://bnpm.byted.org/escape-html/-/escape-html-1.0.3.tgz", - "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==", - "license": "MIT" - }, - "node_modules/fast-safe-stringify": { - "version": "2.1.1", - "resolved": "http://bnpm.byted.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "dev": true, - "license": "MIT" - }, - "node_modules/form-data": { - "version": "4.0.0", - "resolved": "http://bnpm.byted.org/form-data/-/form-data-4.0.0.tgz", - "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, - "license": "MIT", - "dependencies": { - "asynckit": "^0.4.0", - "combined-stream": "^1.0.8", - "mime-types": "^2.1.12" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/formidable": { - "version": "2.1.2", - "resolved": "http://bnpm.byted.org/formidable/-/formidable-2.1.2.tgz", - "integrity": "sha512-CM3GuJ57US06mlpQ47YcunuUZ9jpm8Vx+P2CGt2j7HpgkKZO/DJYQ0Bobim8G6PFQmK5lOqOOdUXboU+h73A4g==", - "dev": true, - "license": "MIT", - "dependencies": { - "dezalgo": "^1.0.4", - "hexoid": "^1.0.0", - "once": "^1.4.0", - "qs": "^6.11.0" - }, - "funding": { - "url": "https://ko-fi.com/tunnckoCore/commissions" - } - }, - "node_modules/fresh": { - "version": "0.5.2", - "resolved": "http://bnpm.byted.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/function-bind": { - "version": "1.1.1", - "resolved": "http://bnpm.byted.org/function-bind/-/function-bind-1.1.1.tgz", - "integrity": "sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==", - "license": "MIT" - }, - "node_modules/get-intrinsic": { - "version": "1.2.1", - "resolved": "http://bnpm.byted.org/get-intrinsic/-/get-intrinsic-1.2.1.tgz", - "integrity": "sha512-2DcsyfABl+gVHEfCOaTrWgyt+tb6MSEGmKq+kI5HwLbIYgjgmMcV8KQ41uaKz1xxUcn9tJtgFbQUEVcEbd0FYw==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.1", - "has": "^1.0.3", - "has-proto": "^1.0.1", - "has-symbols": "^1.0.3" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/happy-dom": { - "resolved": "../../node_modules/.pnpm/happy-dom@6.0.4/node_modules/happy-dom", - "link": true - }, - "node_modules/has": { - "version": "1.0.3", - "resolved": "http://bnpm.byted.org/has/-/has-1.0.3.tgz", - "integrity": "sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==", - "license": "MIT", - "dependencies": { - "function-bind": "^1.1.1" - }, - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/has-proto": { - "version": "1.0.1", - "resolved": "http://bnpm.byted.org/has-proto/-/has-proto-1.0.1.tgz", - "integrity": "sha512-7qE+iP+O+bgF9clE5+UoBFzE65mlBiVj3tKCrlNQ0Ogwm0BjpT/gK4SlLYDMybDh5I3TCTKnPPa0oMG7JDYrhg==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-symbols": { - "version": "1.0.3", - "resolved": "http://bnpm.byted.org/has-symbols/-/has-symbols-1.0.3.tgz", - "integrity": "sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==", - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/has-tostringtag": { - "version": "1.0.0", - "resolved": "http://bnpm.byted.org/has-tostringtag/-/has-tostringtag-1.0.0.tgz", - "integrity": "sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==", - "license": "MIT", - "dependencies": { - "has-symbols": "^1.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/hexoid": { - "version": "1.0.0", - "resolved": "http://bnpm.byted.org/hexoid/-/hexoid-1.0.0.tgz", - "integrity": "sha512-QFLV0taWQOZtvIRIAdBChesmogZrtuXvVWsFHZTk2SU+anspqZ2vMnoLg7IE1+Uk16N19APic1BuF8bC8c2m5g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/http-assert": { - "version": "1.5.0", - "resolved": "http://bnpm.byted.org/http-assert/-/http-assert-1.5.0.tgz", - "integrity": "sha512-uPpH7OKX4H25hBmU6G1jWNaqJGpTXxey+YOUizJUAgu0AjLUeC8D73hTrhvDS5D+GJN1DN1+hhc/eF/wpxtp0w==", - "license": "MIT", - "dependencies": { - "deep-equal": "~1.0.1", - "http-errors": "~1.8.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/http-errors": { - "version": "1.8.1", - "resolved": "http://bnpm.byted.org/http-errors/-/http-errors-1.8.1.tgz", - "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", - "license": "MIT", - "dependencies": { - "depd": "~1.1.2", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/http-errors/node_modules/depd": { - "version": "1.1.2", - "resolved": "http://bnpm.byted.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "http://bnpm.byted.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" - }, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/inflation": { - "version": "2.0.0", - "resolved": "http://bnpm.byted.org/inflation/-/inflation-2.0.0.tgz", - "integrity": "sha512-m3xv4hJYR2oXw4o4Y5l6P5P16WYmazYof+el6Al3f+YlggGj6qT9kImBAnzDelRALnP5d3h4jGBPKzYCizjZZw==", - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "http://bnpm.byted.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/is-generator-function": { - "version": "1.0.10", - "resolved": "http://bnpm.byted.org/is-generator-function/-/is-generator-function-1.0.10.tgz", - "integrity": "sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==", - "license": "MIT", - "dependencies": { - "has-tostringtag": "^1.0.0" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/keygrip": { - "version": "1.1.0", - "resolved": "http://bnpm.byted.org/keygrip/-/keygrip-1.1.0.tgz", - "integrity": "sha512-iYSchDJ+liQ8iwbSI2QqsQOvqv58eJCEanyJPJi+Khyu8smkcKSFUCbPwzFcL7YVtZ6eONjqRX/38caJ7QjRAQ==", - "license": "MIT", - "dependencies": { - "tsscmp": "1.0.6" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/koa": { - "version": "2.14.2", - "resolved": "http://bnpm.byted.org/koa/-/koa-2.14.2.tgz", - "integrity": "sha512-VFI2bpJaodz6P7x2uyLiX6RLYpZmOJqNmoCst/Yyd7hQlszyPwG/I9CQJ63nOtKSxpt5M7NH67V6nJL2BwCl7g==", - "license": "MIT", - "dependencies": { - "accepts": "^1.3.5", - "cache-content-type": "^1.0.0", - "content-disposition": "~0.5.2", - "content-type": "^1.0.4", - "cookies": "~0.8.0", - "debug": "^4.3.2", - "delegates": "^1.0.0", - "depd": "^2.0.0", - "destroy": "^1.0.4", - "encodeurl": "^1.0.2", - "escape-html": "^1.0.3", - "fresh": "~0.5.2", - "http-assert": "^1.3.0", - "http-errors": "^1.6.3", - "is-generator-function": "^1.0.7", - "koa-compose": "^4.1.0", - "koa-convert": "^2.0.0", - "on-finished": "^2.3.0", - "only": "~0.0.2", - "parseurl": "^1.3.2", - "statuses": "^1.5.0", - "type-is": "^1.6.16", - "vary": "^1.1.2" - }, - "engines": { - "node": "^4.8.4 || ^6.10.1 || ^7.10.1 || >= 8.1.4" - } - }, - "node_modules/koa-compose": { - "version": "4.1.0", - "resolved": "http://bnpm.byted.org/koa-compose/-/koa-compose-4.1.0.tgz", - "integrity": "sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==", - "license": "MIT" - }, - "node_modules/koa-convert": { - "version": "2.0.0", - "resolved": "http://bnpm.byted.org/koa-convert/-/koa-convert-2.0.0.tgz", - "integrity": "sha512-asOvN6bFlSnxewce2e/DK3p4tltyfC4VM7ZwuTuepI7dEQVcvpyFuBcEARu1+Hxg8DIwytce2n7jrZtRlPrARA==", - "license": "MIT", - "dependencies": { - "co": "^4.6.0", - "koa-compose": "^4.1.0" - }, - "engines": { - "node": ">= 10" - } - }, - "node_modules/lodash.merge": { - "version": "4.6.2", - "resolved": "http://bnpm.byted.org/lodash.merge/-/lodash.merge-4.6.2.tgz", - "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", - "license": "MIT" - }, - "node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "http://bnpm.byted.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dev": true, - "license": "ISC", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "http://bnpm.byted.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "http://bnpm.byted.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime": { - "version": "2.6.0", - "resolved": "http://bnpm.byted.org/mime/-/mime-2.6.0.tgz", - "integrity": "sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/mime-db": { - "version": "1.52.0", - "resolved": "http://bnpm.byted.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "http://bnpm.byted.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", - "license": "MIT", - "dependencies": { - "mime-db": "1.52.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/ms": { - "version": "2.1.2", - "resolved": "http://bnpm.byted.org/ms/-/ms-2.1.2.tgz", - "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", - "license": "MIT" - }, - "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "http://bnpm.byted.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/object-inspect": { - "version": "1.12.3", - "resolved": "http://bnpm.byted.org/object-inspect/-/object-inspect-1.12.3.tgz", - "integrity": "sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "http://bnpm.byted.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", - "license": "MIT", - "dependencies": { - "ee-first": "1.1.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "http://bnpm.byted.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/only": { - "version": "0.0.2", - "resolved": "http://bnpm.byted.org/only/-/only-0.0.2.tgz", - "integrity": "sha512-Fvw+Jemq5fjjyWz6CpKx6w9s7xxqo3+JCyM0WXWeCSOboZ8ABkyvP8ID4CZuChA/wxSx+XSJmdOm8rGVyJ1hdQ==" - }, - "node_modules/parseurl": { - "version": "1.3.3", - "resolved": "http://bnpm.byted.org/parseurl/-/parseurl-1.3.3.tgz", - "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/qs": { - "version": "6.11.2", - "resolved": "http://bnpm.byted.org/qs/-/qs-6.11.2.tgz", - "integrity": "sha512-tDNIz22aBzCDxLtVH++VnTfzxlfeK5CbqohpSqpJgj1Wg/cQbStNAz3NuqCs5vV+pjBsK4x4pN9HlVh7rcYRiA==", - "license": "BSD-3-Clause", - "dependencies": { - "side-channel": "^1.0.4" - }, - "engines": { - "node": ">=0.6" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/raw-body": { - "version": "2.5.2", - "resolved": "http://bnpm.byted.org/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", - "license": "MIT", - "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/raw-body/node_modules/http-errors": { - "version": "2.0.0", - "resolved": "http://bnpm.byted.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", - "license": "MIT", - "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/raw-body/node_modules/statuses": { - "version": "2.0.1", - "resolved": "http://bnpm.byted.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "http://bnpm.byted.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "http://bnpm.byted.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.5.4", - "resolved": "http://bnpm.byted.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dev": true, - "license": "ISC", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/setprototypeof": { - "version": "1.2.0", - "resolved": "http://bnpm.byted.org/setprototypeof/-/setprototypeof-1.2.0.tgz", - "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==", - "license": "ISC" - }, - "node_modules/side-channel": { - "version": "1.0.4", - "resolved": "http://bnpm.byted.org/side-channel/-/side-channel-1.0.4.tgz", - "integrity": "sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==", - "license": "MIT", - "dependencies": { - "call-bind": "^1.0.0", - "get-intrinsic": "^1.0.2", - "object-inspect": "^1.9.0" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/statuses": { - "version": "1.5.0", - "resolved": "http://bnpm.byted.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/superagent": { - "version": "8.1.2", - "resolved": "http://bnpm.byted.org/superagent/-/superagent-8.1.2.tgz", - "integrity": "sha512-6WTxW1EB6yCxV5VFOIPQruWGHqc3yI7hEmZK6h+pyk69Lk/Ut7rLUY6W/ONF2MjBuGjvmMiIpsrVJ2vjrHlslA==", - "dev": true, - "license": "MIT", - "dependencies": { - "component-emitter": "^1.3.0", - "cookiejar": "^2.1.4", - "debug": "^4.3.4", - "fast-safe-stringify": "^2.1.1", - "form-data": "^4.0.0", - "formidable": "^2.1.2", - "methods": "^1.1.2", - "mime": "2.6.0", - "qs": "^6.11.0", - "semver": "^7.3.8" - }, - "engines": { - "node": ">=6.4.0 <13 || >=14" - } - }, - "node_modules/supertest": { - "version": "6.3.3", - "resolved": "http://bnpm.byted.org/supertest/-/supertest-6.3.3.tgz", - "integrity": "sha512-EMCG6G8gDu5qEqRQ3JjjPs6+FYT1a7Hv5ApHvtSghmOFJYtsU5S+pSb6Y2EUeCEY3CmEL3mmQ8YWlPOzQomabA==", - "dev": true, - "license": "MIT", - "dependencies": { - "methods": "^1.1.2", - "superagent": "^8.0.5" - }, - "engines": { - "node": ">=6.4.0" - } - }, - "node_modules/toidentifier": { - "version": "1.0.1", - "resolved": "http://bnpm.byted.org/toidentifier/-/toidentifier-1.0.1.tgz", - "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", - "license": "MIT", - "engines": { - "node": ">=0.6" - } - }, - "node_modules/tsscmp": { - "version": "1.0.6", - "resolved": "http://bnpm.byted.org/tsscmp/-/tsscmp-1.0.6.tgz", - "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", - "license": "MIT", - "engines": { - "node": ">=0.6.x" - } - }, - "node_modules/type-is": { - "version": "1.6.18", - "resolved": "http://bnpm.byted.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", - "license": "MIT", - "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/unpipe": { - "version": "1.0.0", - "resolved": "http://bnpm.byted.org/unpipe/-/unpipe-1.0.0.tgz", - "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/vary": { - "version": "1.1.2", - "resolved": "http://bnpm.byted.org/vary/-/vary-1.1.2.tgz", - "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "http://bnpm.byted.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/yallist": { - "version": "4.0.0", - "resolved": "http://bnpm.byted.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "dev": true, - "license": "ISC" - }, - "node_modules/ylru": { - "version": "1.3.2", - "resolved": "http://bnpm.byted.org/ylru/-/ylru-1.3.2.tgz", - "integrity": "sha512-RXRJzMiK6U2ye0BlGGZnmpwJDPgakn6aNQ0A7gHRbD4I0uvK4TW6UqkK1V0pp9jskjJBAXd3dRrbzWkqJ+6cxA==", - "license": "MIT", - "engines": { - "node": ">= 4.0.0" - } - } - } -} diff --git a/packages/core2/package.json b/packages/core2/package.json deleted file mode 100644 index fe806e6..0000000 --- a/packages/core2/package.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "name": "@tomrpc/core2", - "version": "1.0.0", - "description": "My Awesome lib", - "license": "MIT", - "publishConfig": { - "access": "public" - }, - "author": "npmstudy ", - "main": "./dist/index.js", - "module": "./dist/index.mjs", - "types": "./dist/index.d.ts", - "files": [ - "dist" - ], - "scripts": { - "build": "tsup src -- --dts-resolve", - "build:fast": "tsup src", - "dev": "tsup src --watch", - "test": "vitest run", - "test:watch": "vitest watch", - "coverage": "vitest run --coverage" - }, - "keywords": [ - "awesome-keywords" - ], - "devDependencies": { - "@types/koa": "^2.13.10", - "@vitest/coverage-v8": "^0.34.6", - "happy-dom": "^6.0.4", - "supertest": "^6.3.3", - "vitest": "^0.34.6" - }, - "dependencies": { - "@koa/bodyparser": "^5.0.0", - "debug": "^4.3.4", - "koa": "^2.14.2", - "koa-compose": "^4.1.0", - "koa-mount": "^4.0.0" - } -} diff --git a/packages/core2/src/__tests__/index.test.ts b/packages/core2/src/__tests__/index.test.ts deleted file mode 100644 index faeed0e..0000000 --- a/packages/core2/src/__tests__/index.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import request from 'supertest'; -import { describe, expect, it } from 'vitest'; - -// import { lib } from '..'; - -describe('lib', () => { - it('should render lib', () => { - expect('lib').toBe('lib'); - }); -}); - -// const request = require('supertest'); -// const { test } = require('uvu'); -// // const assert = require('uvu/assert'); - -// const app = {}; //= require('../../app').callback(); - -// test('get /a/a?$p=["hello",22323]', async () => { -// await request(app) -// .get('/a/a?$p=["hello",22323]') -// .expect('Content-Type', /text\/plain/) -// .expect(200) -// .expect('hello+22323'); -// }); - -// test('post /a/a', async () => { -// await request(app) -// .post('/a/a') -// .send(['22hello', '001']) -// .expect('Content-Type', /text\/plain/) -// .expect(200) -// .expect('this is a post'); -// }); - -// test('post /a/b', async () => { -// await request(app) -// .post('/a/b') -// .send(['1', '2']) -// .expect('Content-Type', /json/) -// .expect(200) -// .expect('{"a":"1","b":"2"}'); -// }); diff --git a/packages/core2/src/index.ts b/packages/core2/src/index.ts deleted file mode 100644 index 73a46af..0000000 --- a/packages/core2/src/index.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Fn } from './fn'; -import { RpcServer } from './server'; -export * from './plugin'; -export * from './fn'; -export * from './server'; -export * from './utils'; - -export function createServer(cfg?: any) { - const rpc = new RpcServer(Object.assign({ fn: {} }, cfg)); - - const fn = new Fn(Object.assign({}, cfg.fn)); - - rpc.plugin(fn); - - return Object.assign(rpc, { - fn: function (key, fun) { - fn.fn(key, fun); - }, - add: function (items) { - fn.add(items); - }, - }); -} diff --git a/packages/core2/src/utils.ts b/packages/core2/src/utils.ts deleted file mode 100644 index caaf594..0000000 --- a/packages/core2/src/utils.ts +++ /dev/null @@ -1,49 +0,0 @@ -import debug from 'debug'; -const debugLog = debug('@tomrpc/core'); - -export const isArrowFunction = (func) => { - if (typeof func === 'function') { - const source = func.toString(); - return /^\([^)]*\)\s*=>/.test(source); - } - return false; -}; - -export function getHttpMethods() { - return [ - 'get', - 'post', - 'put', - 'head', - 'delete', - 'options', - 'trace', - 'copy', - 'lock', - 'mkcol', - 'move', - 'purge', - 'propfind', - 'proppatch', - 'unlock', - 'report', - 'mkactivity', - 'checkout', - 'merge', - 'm-search', - 'notify', - 'subscribe', - 'unsubscribe', - 'patch', - 'search', - 'connect', - ]; -} - -export function log(msg, debugFlag?) { - if (debugFlag) { - console.log(msg); - } else { - debugLog(msg); - } -} diff --git a/packages/core2/tsconfig.json b/packages/core2/tsconfig.json deleted file mode 100644 index afc9f0b..0000000 --- a/packages/core2/tsconfig.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "extends": "../../tsconfig.json", - "compilerOptions": { - "types": [ - "vitest/globals" - ] - } -} diff --git a/packages/core2/tsup.config.cjs b/packages/core2/tsup.config.cjs deleted file mode 100644 index 369773b..0000000 --- a/packages/core2/tsup.config.cjs +++ /dev/null @@ -1,12 +0,0 @@ -import { defineConfig } from 'tsup'; - -export default defineConfig((options) => ({ - entry: 'src/index.ts', - sourcemap: !options.watch, - minify: !options.watch, - // dts: true, - format: ['esm', 'cjs'], - loader: { - '.js': 'jsx', - }, -})); diff --git a/packages/core2/vitest.config.cjs b/packages/core2/vitest.config.cjs deleted file mode 100644 index c4e3ba6..0000000 --- a/packages/core2/vitest.config.cjs +++ /dev/null @@ -1,10 +0,0 @@ -/// - -import { defineConfig } from 'vite'; - -export default defineConfig({ - test: { - globals: true, - environment: 'happy-dom', - }, -}); From 8aacd90d8d99123542c44835264f9900ecb7578e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 20:31:24 +0800 Subject: [PATCH 034/101] chore: refact --- packages/core/src/server.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 11e5047..865b4f6 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -6,7 +6,7 @@ import { Strategy, log } from './index'; export const LifeCycleConfig = { hooks: { - init: [], + init: [], // 后面需要改成Set,否则会出现重复问题 before: [], load: [], after: [], From 984d29695caf661f57304b59c8a3504cd3eee59c Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 6 Nov 2023 20:34:34 +0800 Subject: [PATCH 035/101] chore: refact --- packages/core/src/plugin.ts | 1 + packages/core/src/server.ts | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index ea1f332..abc26cc 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -43,6 +43,7 @@ export class Plugable implements Strategy { this.app = new Koa(); this.init = []; this.load = []; + this.prefix = ''; this.compose = compose; // TODO: 此处最好改成mount diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 865b4f6..7fdb5e8 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -145,7 +145,8 @@ export class RpcServer { console.dir('mount plugin ' + plugin.prefix); // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); - this.app.use(mount(plugin.prefix, plugin.app)); + const mw = plugin.prefix != '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); + this.app.use(mw); } // 兜底的else From 4162035a4da2805b6251c40921909f7cf0bd0e18 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 8 Nov 2023 17:08:46 +0800 Subject: [PATCH 036/101] chore: refact --- example/src/app.ts | 2 +- packages/app/app.ts | 2 +- packages/app/f/a.js | 29 +++++++++++++++++++++++++++++ packages/app/f/b/c.js | 6 ++++++ packages/app/src/index.ts | 12 ++++-------- packages/app/src/mw/cors.ts | 21 +++++++++++++-------- packages/app/src/mw/jwt.ts | 21 +++++++++++++-------- packages/app/src/mw/serve.ts | 21 +++++++++++++-------- packages/app/src/mw/view.ts | 21 +++++++++++++-------- packages/app/src/mw2/cors.ts | 26 ++++++++++++++++++++++++++ packages/app/src/mw2/index.ts | 4 ++++ packages/app/src/mw2/jwt.ts | 10 ++++++++++ packages/app/src/mw2/serve.ts | 10 ++++++++++ packages/app/src/mw2/view.ts | 10 ++++++++++ packages/core/app.ts | 2 +- packages/core/src/index.ts | 4 ++++ 16 files changed, 158 insertions(+), 43 deletions(-) create mode 100644 packages/app/f/a.js create mode 100644 packages/app/f/b/c.js create mode 100644 packages/app/src/mw2/cors.ts create mode 100644 packages/app/src/mw2/index.ts create mode 100644 packages/app/src/mw2/jwt.ts create mode 100644 packages/app/src/mw2/serve.ts create mode 100644 packages/app/src/mw2/view.ts diff --git a/example/src/app.ts b/example/src/app.ts index cbf84e5..469fad8 100644 --- a/example/src/app.ts +++ b/example/src/app.ts @@ -62,5 +62,5 @@ import mount from '@tomrpc/mount'; // rpc.mount(); - rpc.listen(3000); + rpc.start(3000); })(); diff --git a/packages/app/app.ts b/packages/app/app.ts index 375cd7c..a828c8b 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -8,7 +8,7 @@ import { createApp } from './src/index'; base: import.meta.url, port: 3001, debug: false, - // mount?: './fn''; + mount: './f', buildin: { serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, cors: { enable: true }, diff --git a/packages/app/f/a.js b/packages/app/f/a.js new file mode 100644 index 0000000..6427bb6 --- /dev/null +++ b/packages/app/f/a.js @@ -0,0 +1,29 @@ +export function a(a) { + return { + a: a, + msg: "getUsers", + }; +} + +export function b(a) { + return { + a: a, + msg: "getUsers", + }; +} + +export const c = function (a) { + return { + a: a, + msg: "getUsers", + }; +}; + +export const f = function d(a) { + return { + a: a, + msg: "getUsers", + }; +}; + +export default "1"; diff --git a/packages/app/f/b/c.js b/packages/app/f/b/c.js new file mode 100644 index 0000000..540314b --- /dev/null +++ b/packages/app/f/b/c.js @@ -0,0 +1,6 @@ +export function a(a) { + return { + a: a, + msg: "getUsers", + }; +} diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index c984386..a932a96 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -63,18 +63,14 @@ export async function createApp(cfg: IConfig) { Object.assign( { base: import.meta.url, - beforeOne: function (ctx: any, key: string) { - console.log(ctx.path); - console.log(ctx.method); - console.log('beforeOne key=' + key); - }, }, cfg ) ); - await loadInitMiddleware(rpc, init); - await loadBuildinMiddlewaire(rpc); + // await mount(rpc, cfg.mount); + // await loadInitMiddleware(rpc, init); + // await loadBuildinMiddlewaire(rpc); // rpc[load].push([someMw]) // mount with lifecycle @@ -92,7 +88,7 @@ export async function createApp(cfg: IConfig) { if (cfg.debug) { rpc.dump(); } - rpc.listen(cfg.port); + rpc.start(cfg.port); }, }); } diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts index 86243eb..9b57d82 100644 --- a/packages/app/src/mw/cors.ts +++ b/packages/app/src/mw/cors.ts @@ -1,10 +1,15 @@ import corsMiddleware from '@koa/cors'; +import { Plugable } from '@tomrpc/core'; -export const cors = { - name: 'cors', - lifeCycle: 'load', - mw: (cfg = { opts: {} }) => { - // console.dir(opts); - return corsMiddleware(cfg.opts); - }, -}; +export class Cors extends Plugable { + constructor(cfg?) { + super(cfg); + + this.prefix = ''; + this.name = 'cors'; + this.init.push(this.a()); + } + a() { + return corsMiddleware(this.config.opts); + } +} diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index 5a5d830..f22691f 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -1,10 +1,15 @@ +import { Plugable } from '@tomrpc/core'; import koajwt from 'koa-jwt'; -export const jwt = { - name: 'jwt', - lifeCycle: 'load', - mw: (opts) => { - // console.dir(opts); - return koajwt(opts).unless({ path: opts.unless }); - }, -}; +export class Jwt extends Plugable { + constructor(cfg?) { + super(cfg); + + this.prefix = ''; + this.name = 'jwt'; + // this.init.push(this.a()); + } + // a() { + // return return koajwt(this.config.opts).unless({ path: this.config.opts.unless }); + // } +} diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts index b3fa65f..4de56a2 100644 --- a/packages/app/src/mw/serve.ts +++ b/packages/app/src/mw/serve.ts @@ -1,10 +1,15 @@ +import { Plugable } from '@tomrpc/core'; import serveMiddleware from 'koa-static'; -export const serve = { - name: 'serve', - lifeCycle: 'load', - mw: (opts) => { - // console.dir(opts); - return serveMiddleware(opts.root, opts); - }, -}; +export class Serve extends Plugable { + constructor(cfg?) { + super(cfg); + + this.prefix = ''; + this.name = 'serve'; + this.init.push(this.a()); + } + a() { + return serveMiddleware(this.config.opts.root, this.config.opts); + } +} diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts index cc43f1e..ca21dc3 100644 --- a/packages/app/src/mw/view.ts +++ b/packages/app/src/mw/view.ts @@ -1,10 +1,15 @@ +import { Plugable } from '@tomrpc/core'; import views from 'koa-views'; -export const view = { - name: 'view', - lifeCycle: 'load', - mw: (cfg) => { - // console.dir(opts); - return views(cfg.root, cfg.opts); - }, -}; +export class View extends Plugable { + constructor(cfg?) { + super(cfg); + + this.prefix = ''; + this.name = 'serve'; + this.init.push(this.a()); + } + a() { + return views(this.config?.opts?.root, this.config?.opts); + } +} diff --git a/packages/app/src/mw2/cors.ts b/packages/app/src/mw2/cors.ts new file mode 100644 index 0000000..c061417 --- /dev/null +++ b/packages/app/src/mw2/cors.ts @@ -0,0 +1,26 @@ +import corsMiddleware from '@koa/cors'; +import { Plugable } from '@tomrpc/core'; + +import { init } from '../init'; + +export const cors = { + name: 'cors', + lifeCycle: 'load', + mw: (cfg = { opts: {} }) => { + // console.dir(opts); + return corsMiddleware(cfg.opts); + }, +}; + +export class Cors extends Plugable { + constructor(cfg?) { + super(cfg); + + this.prefix = ''; + this.name = 'cors'; + this.init.push(this.a()); + } + a() { + return corsMiddleware(this.config.opts); + } +} diff --git a/packages/app/src/mw2/index.ts b/packages/app/src/mw2/index.ts new file mode 100644 index 0000000..e716b0a --- /dev/null +++ b/packages/app/src/mw2/index.ts @@ -0,0 +1,4 @@ +export * from './cors'; +export * from './serve'; +export * from './jwt'; +export * from './view'; diff --git a/packages/app/src/mw2/jwt.ts b/packages/app/src/mw2/jwt.ts new file mode 100644 index 0000000..5a5d830 --- /dev/null +++ b/packages/app/src/mw2/jwt.ts @@ -0,0 +1,10 @@ +import koajwt from 'koa-jwt'; + +export const jwt = { + name: 'jwt', + lifeCycle: 'load', + mw: (opts) => { + // console.dir(opts); + return koajwt(opts).unless({ path: opts.unless }); + }, +}; diff --git a/packages/app/src/mw2/serve.ts b/packages/app/src/mw2/serve.ts new file mode 100644 index 0000000..b3fa65f --- /dev/null +++ b/packages/app/src/mw2/serve.ts @@ -0,0 +1,10 @@ +import serveMiddleware from 'koa-static'; + +export const serve = { + name: 'serve', + lifeCycle: 'load', + mw: (opts) => { + // console.dir(opts); + return serveMiddleware(opts.root, opts); + }, +}; diff --git a/packages/app/src/mw2/view.ts b/packages/app/src/mw2/view.ts new file mode 100644 index 0000000..cc43f1e --- /dev/null +++ b/packages/app/src/mw2/view.ts @@ -0,0 +1,10 @@ +import views from 'koa-views'; + +export const view = { + name: 'view', + lifeCycle: 'load', + mw: (cfg) => { + // console.dir(opts); + return views(cfg.root, cfg.opts); + }, +}; diff --git a/packages/core/app.ts b/packages/core/app.ts index ae61a8d..991bec6 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -1,5 +1,5 @@ import Demo from './demo'; -import { Fn, createServer } from './src/index'; +import { Fn, createServer, Plugable } from './src/index'; // import { RpcServer } from './src/server'; // const rpc = new RpcServer({}); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 73a46af..2cb7e2d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -13,6 +13,10 @@ export function createServer(cfg?: any) { rpc.plugin(fn); return Object.assign(rpc, { + base: '.', + dump: function () { + console.dir('dump'); + }, fn: function (key, fun) { fn.fn(key, fun); }, From b9092e8acb96eb66df25301da191cbb72bdcbd21 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 9 Nov 2023 15:09:04 +0800 Subject: [PATCH 037/101] chore: static ok --- packages/app/src/index.ts | 17 ++++++++++------- packages/app/src/mw/serve.ts | 7 +++++-- packages/app/src/mw2/serve.ts | 2 +- packages/core/src/server.ts | 4 +++- 4 files changed, 19 insertions(+), 11 deletions(-) diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index a932a96..1cf046a 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -4,6 +4,7 @@ import debug from 'debug'; import { init } from './init'; import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; +import { Serve } from './mw/serve'; const log = debug('@tomrpc/app'); @@ -57,7 +58,6 @@ interface IConfig { }; beforeAll: any; } - export async function createApp(cfg: IConfig) { const rpc = createServer( Object.assign( @@ -68,6 +68,9 @@ export async function createApp(cfg: IConfig) { ) ); + const serve = new Serve(cfg.buildin.serve); + rpc.plugin(serve); + // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); @@ -84,11 +87,11 @@ export async function createApp(cfg: IConfig) { // } return Object.assign(rpc, { - start: function () { - if (cfg.debug) { - rpc.dump(); - } - rpc.start(cfg.port); - }, + // start: function () { + // // if (cfg.debug) { + // // rpc.dump(); + // // } + // rpc.start(cfg.port); + // }, }); } diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts index 4de56a2..70dda60 100644 --- a/packages/app/src/mw/serve.ts +++ b/packages/app/src/mw/serve.ts @@ -5,11 +5,14 @@ export class Serve extends Plugable { constructor(cfg?) { super(cfg); - this.prefix = ''; + console.dir(cfg); + + // this.prefix = ''; this.name = 'serve'; this.init.push(this.a()); } a() { - return serveMiddleware(this.config.opts.root, this.config.opts); + console.dir('serve'); + return serveMiddleware(this.config.root, this.config.opts); } } diff --git a/packages/app/src/mw2/serve.ts b/packages/app/src/mw2/serve.ts index b3fa65f..ebd0587 100644 --- a/packages/app/src/mw2/serve.ts +++ b/packages/app/src/mw2/serve.ts @@ -1,6 +1,6 @@ import serveMiddleware from 'koa-static'; -export const serve = { +export const Serve = { name: 'serve', lifeCycle: 'load', mw: (opts) => { diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 7fdb5e8..35005a7 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -145,7 +145,9 @@ export class RpcServer { console.dir('mount plugin ' + plugin.prefix); // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); - const mw = plugin.prefix != '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); + const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); + console.dir(plugin.prefix === ''); + console.dir(mw); this.app.use(mw); } From 7768c2d6ccf36448f299fe0c74bd592efdb5dfd5 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 9 Nov 2023 20:28:50 +0800 Subject: [PATCH 038/101] chore: refact --- packages/app/app.ts | 17 ++++++++++++++++- packages/app/src/index.ts | 8 +++++++- packages/app/src/mw/cors.ts | 5 ++--- packages/app/src/mw/serve.ts | 4 ---- packages/app/src/mw/view.ts | 2 +- packages/core/src/index.ts | 1 + packages/core/src/server.ts | 4 ++-- 7 files changed, 29 insertions(+), 12 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index a828c8b..2b6aa40 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -34,12 +34,27 @@ import { createApp } from './src/index'; }, }); + rpc.app.use(async (ctx, next) => { + if (ctx.path === 'view') { + ctx.render('user', { + user: { + name: 'alfred', + }, + }); + } else { + await next(); + } + }); + // rpc.view vs rpc.fn变成插件 rpc.fn('a', function (a) { - console.dir(this.render); + console.dir(rpc.fn); + console.dir(this); // this.render('user', { user: { name: 'alfred' } }); return { a: a }; }); + console.dir(rpc); + rpc.start(); })(); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 1cf046a..f2e55c8 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -4,7 +4,7 @@ import debug from 'debug'; import { init } from './init'; import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; -import { Serve } from './mw/serve'; +import { Serve, Cors, View } from './mw/index'; const log = debug('@tomrpc/app'); @@ -68,9 +68,15 @@ export async function createApp(cfg: IConfig) { ) ); + const cors = new Cors(cfg.buildin.cors); + rpc.plugin(cors); + const serve = new Serve(cfg.buildin.serve); rpc.plugin(serve); + const view = new View(cfg.buildin.view); + rpc.plugin(view); + // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts index 9b57d82..0b6c9c2 100644 --- a/packages/app/src/mw/cors.ts +++ b/packages/app/src/mw/cors.ts @@ -4,12 +4,11 @@ import { Plugable } from '@tomrpc/core'; export class Cors extends Plugable { constructor(cfg?) { super(cfg); - - this.prefix = ''; + console.dir(this.config); this.name = 'cors'; this.init.push(this.a()); } a() { - return corsMiddleware(this.config.opts); + return corsMiddleware(this.config); } } diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts index 70dda60..7ee38e5 100644 --- a/packages/app/src/mw/serve.ts +++ b/packages/app/src/mw/serve.ts @@ -4,10 +4,6 @@ import serveMiddleware from 'koa-static'; export class Serve extends Plugable { constructor(cfg?) { super(cfg); - - console.dir(cfg); - - // this.prefix = ''; this.name = 'serve'; this.init.push(this.a()); } diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts index ca21dc3..4c8412f 100644 --- a/packages/app/src/mw/view.ts +++ b/packages/app/src/mw/view.ts @@ -10,6 +10,6 @@ export class View extends Plugable { this.init.push(this.a()); } a() { - return views(this.config?.opts?.root, this.config?.opts); + return views(this.config?.root, this.config); } } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 2cb7e2d..79858e8 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -19,6 +19,7 @@ export function createServer(cfg?: any) { }, fn: function (key, fun) { fn.fn(key, fun); + console.dir(fn); }, add: function (items) { fn.add(items); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 35005a7..b4ff006 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -146,8 +146,8 @@ export class RpcServer { // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); - console.dir(plugin.prefix === ''); - console.dir(mw); + // console.dir(plugin.prefix === ''); + // console.dir(mw); this.app.use(mw); } From 4f537ec754ed5113888162dbe6e9f5bc63008092 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 13 Nov 2023 20:42:06 +0800 Subject: [PATCH 039/101] fix: add view --- packages/app/app.ts | 23 ++++++++++------------- packages/app/src/index.ts | 13 ++++++------- packages/app/view/{user.html => user.ejs} | 1 + packages/core/src/index.ts | 9 +++++++++ 4 files changed, 26 insertions(+), 20 deletions(-) rename packages/app/view/{user.html => user.ejs} (93%) diff --git a/packages/app/app.ts b/packages/app/app.ts index 2b6aa40..c906eaa 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -34,27 +34,24 @@ import { createApp } from './src/index'; }, }); - rpc.app.use(async (ctx, next) => { - if (ctx.path === 'view') { - ctx.render('user', { - user: { - name: 'alfred', - }, - }); - } else { - await next(); - } + rpc.render('/view', async (ctx, next) => { + // console.dir('view'); + ctx.state = { + session: ctx.session, + title: 'app', + }; + await ctx.render('user.ejs', { user: { name: 'alfred' } }); }); // rpc.view vs rpc.fn变成插件 rpc.fn('a', function (a) { - console.dir(rpc.fn); - console.dir(this); + // console.dir(rpc.fn); + // console.dir(this); // this.render('user', { user: { name: 'alfred' } }); return { a: a }; }); - console.dir(rpc); + // console.dir(rpc); rpc.start(); })(); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index f2e55c8..d208eee 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -1,4 +1,4 @@ -import { createServer } from '@tomrpc/core'; +import { createServer, combine } from '@tomrpc/core'; import mount from '@tomrpc/mount'; import debug from 'debug'; @@ -93,11 +93,10 @@ export async function createApp(cfg: IConfig) { // } return Object.assign(rpc, { - // start: function () { - // // if (cfg.debug) { - // // rpc.dump(); - // // } - // rpc.start(cfg.port); - // }, + render: function (tpl, cb) { + const mw = combine([cb]); + console.dir(rpc.config); + rpc.load.push(mw); + }, }); } diff --git a/packages/app/view/user.html b/packages/app/view/user.ejs similarity index 93% rename from packages/app/view/user.html rename to packages/app/view/user.ejs index f824178..cc08007 100644 --- a/packages/app/view/user.html +++ b/packages/app/view/user.ejs @@ -1,3 +1,4 @@ <% if (user) { %>

<%= user.name %>

<% } %> +123 diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 79858e8..8cbdb75 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,10 +1,15 @@ +import compose from 'koa-compose'; + import { Fn } from './fn'; import { RpcServer } from './server'; + export * from './plugin'; export * from './fn'; export * from './server'; export * from './utils'; +export const combine = compose; + export function createServer(cfg?: any) { const rpc = new RpcServer(Object.assign({ fn: {} }, cfg)); @@ -14,6 +19,10 @@ export function createServer(cfg?: any) { return Object.assign(rpc, { base: '.', + init: rpc['config']['hooks']['init'], + before: rpc['config']['hooks']['before'], + load: rpc['config']['hooks']['load'], + after: rpc['config']['hooks']['after'], dump: function () { console.dir('dump'); }, From c6df21f16dde81c18f969caef667cb703d5b7c4f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 13 Nov 2023 21:28:46 +0800 Subject: [PATCH 040/101] fix: add jwt test --- packages/app/app.ts | 12 +++++++++++- packages/app/src/index.ts | 10 ++++++++-- packages/app/src/mw/jwt.ts | 8 ++++---- 3 files changed, 23 insertions(+), 7 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index c906eaa..72c897e 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -16,7 +16,7 @@ import { createApp } from './src/index'; enable: true, secret: 'shhhhhh', debug: true, - unless: ['/public', '/a'], + unless: ['/public', '/api/*'], }, view: { enable: true, @@ -34,6 +34,16 @@ import { createApp } from './src/index'; }, }); + rpc.jwt(async (ctx, next) => { + // console.dir('view'); + await next(); + // if (['/', '/view', '/api*'].some((e) => ctx.path.match(e))) { + // await next(); + // } else { + // ctx.body = { jwt: 'not jwt' }; + // } + }); + rpc.render('/view', async (ctx, next) => { // console.dir('view'); ctx.state = { diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index d208eee..b6b89b7 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -4,7 +4,7 @@ import debug from 'debug'; import { init } from './init'; import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; -import { Serve, Cors, View } from './mw/index'; +import { Serve, Cors, View, Jwt } from './mw/index'; const log = debug('@tomrpc/app'); @@ -77,6 +77,8 @@ export async function createApp(cfg: IConfig) { const view = new View(cfg.buildin.view); rpc.plugin(view); + const jwt = new Jwt(cfg.buildin.view); + rpc.plugin(jwt); // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); @@ -93,9 +95,13 @@ export async function createApp(cfg: IConfig) { // } return Object.assign(rpc, { - render: function (tpl, cb) { + jwt: function (cb) { const mw = combine([cb]); console.dir(rpc.config); + rpc.init.push(mw); + }, + render: function (path, cb) { + const mw = combine([cb]); rpc.load.push(mw); }, }); diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index f22691f..099fa29 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -7,9 +7,9 @@ export class Jwt extends Plugable { this.prefix = ''; this.name = 'jwt'; - // this.init.push(this.a()); + this.init.push(this.a()); + } + a() { + return koajwt(this.config.opts).unless({ path: this.config.opts.unless }); } - // a() { - // return return koajwt(this.config.opts).unless({ path: this.config.opts.unless }); - // } } From ef4adffcf86d72322fcee32ffb09dfb32f87e01e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 14 Nov 2023 12:02:30 +0800 Subject: [PATCH 041/101] fix: add jwt doc --- packages/app/README.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/app/README.md b/packages/app/README.md index 325bbe1..35445f3 100644 --- a/packages/app/README.md +++ b/packages/app/README.md @@ -31,3 +31,17 @@ const rpc = createServer(cfg); rpc.start(); ``` + +jwt豁免 + +```js + rpc.jwt(async (ctx, next) => { + // console.dir('view'); + await next(); + // if (['/', '/view', '/api*'].some((e) => ctx.path.match(e))) { + // await next(); + // } else { + // ctx.body = { jwt: 'not jwt' }; + // } + }); +``` From a77e8dc9a14355765132b733c0737b7198b4d46f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 14 Nov 2023 22:48:10 +0800 Subject: [PATCH 042/101] fix: add jwt --- packages/app/app.ts | 8 ++++++-- packages/app/src/index.ts | 4 ++-- packages/app/src/mw/jwt.ts | 5 ++++- packages/app/src/mw2/cors.ts | 26 -------------------------- packages/app/src/mw2/index.ts | 4 ---- packages/app/src/mw2/jwt.ts | 10 ---------- packages/app/src/mw2/serve.ts | 10 ---------- packages/app/src/mw2/view.ts | 10 ---------- packages/core/app.ts | 4 +++- packages/core/src/fn.ts | 8 +++++++- packages/core/src/server.ts | 14 ++++++++++++-- 11 files changed, 34 insertions(+), 69 deletions(-) delete mode 100644 packages/app/src/mw2/cors.ts delete mode 100644 packages/app/src/mw2/index.ts delete mode 100644 packages/app/src/mw2/jwt.ts delete mode 100644 packages/app/src/mw2/serve.ts delete mode 100644 packages/app/src/mw2/view.ts diff --git a/packages/app/app.ts b/packages/app/app.ts index 72c897e..f90bbcf 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -1,4 +1,5 @@ import { dirname, filename, join } from 'desm'; +import jwt from 'jsonwebtoken'; import { createApp } from './src/index'; @@ -16,7 +17,7 @@ import { createApp } from './src/index'; enable: true, secret: 'shhhhhh', debug: true, - unless: ['/public', '/api/*'], + unless: { path: ['/public', '/view', '/', '/api/*'] }, }, view: { enable: true, @@ -35,7 +36,10 @@ import { createApp } from './src/index'; }); rpc.jwt(async (ctx, next) => { - // console.dir('view'); + const secret = 'shhhhhh'; + const token = jwt.sign({ foo: 'bar' }, secret); + console.dir(ctx.path); + await next(); // if (['/', '/view', '/api*'].some((e) => ctx.path.match(e))) { // await next(); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index b6b89b7..e750c80 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -42,7 +42,7 @@ interface IJwt { secret?: string; issuer?: string; debug: boolean; - unless?: Array; + unless?: any; } interface IConfig { name: string | 'tomapp'; @@ -77,7 +77,7 @@ export async function createApp(cfg: IConfig) { const view = new View(cfg.buildin.view); rpc.plugin(view); - const jwt = new Jwt(cfg.buildin.view); + const jwt = new Jwt(cfg.buildin.jwt); rpc.plugin(jwt); // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index 099fa29..95984e9 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -4,12 +4,15 @@ import koajwt from 'koa-jwt'; export class Jwt extends Plugable { constructor(cfg?) { super(cfg); + console.dir('jwt = '); + console.dir(this.config); this.prefix = ''; this.name = 'jwt'; this.init.push(this.a()); } a() { - return koajwt(this.config.opts).unless({ path: this.config.opts.unless }); + console.dir(this.config); + return koajwt(this.config).unless({ path: this.config.unless }); } } diff --git a/packages/app/src/mw2/cors.ts b/packages/app/src/mw2/cors.ts deleted file mode 100644 index c061417..0000000 --- a/packages/app/src/mw2/cors.ts +++ /dev/null @@ -1,26 +0,0 @@ -import corsMiddleware from '@koa/cors'; -import { Plugable } from '@tomrpc/core'; - -import { init } from '../init'; - -export const cors = { - name: 'cors', - lifeCycle: 'load', - mw: (cfg = { opts: {} }) => { - // console.dir(opts); - return corsMiddleware(cfg.opts); - }, -}; - -export class Cors extends Plugable { - constructor(cfg?) { - super(cfg); - - this.prefix = ''; - this.name = 'cors'; - this.init.push(this.a()); - } - a() { - return corsMiddleware(this.config.opts); - } -} diff --git a/packages/app/src/mw2/index.ts b/packages/app/src/mw2/index.ts deleted file mode 100644 index e716b0a..0000000 --- a/packages/app/src/mw2/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './cors'; -export * from './serve'; -export * from './jwt'; -export * from './view'; diff --git a/packages/app/src/mw2/jwt.ts b/packages/app/src/mw2/jwt.ts deleted file mode 100644 index 5a5d830..0000000 --- a/packages/app/src/mw2/jwt.ts +++ /dev/null @@ -1,10 +0,0 @@ -import koajwt from 'koa-jwt'; - -export const jwt = { - name: 'jwt', - lifeCycle: 'load', - mw: (opts) => { - // console.dir(opts); - return koajwt(opts).unless({ path: opts.unless }); - }, -}; diff --git a/packages/app/src/mw2/serve.ts b/packages/app/src/mw2/serve.ts deleted file mode 100644 index ebd0587..0000000 --- a/packages/app/src/mw2/serve.ts +++ /dev/null @@ -1,10 +0,0 @@ -import serveMiddleware from 'koa-static'; - -export const Serve = { - name: 'serve', - lifeCycle: 'load', - mw: (opts) => { - // console.dir(opts); - return serveMiddleware(opts.root, opts); - }, -}; diff --git a/packages/app/src/mw2/view.ts b/packages/app/src/mw2/view.ts deleted file mode 100644 index cc43f1e..0000000 --- a/packages/app/src/mw2/view.ts +++ /dev/null @@ -1,10 +0,0 @@ -import views from 'koa-views'; - -export const view = { - name: 'view', - lifeCycle: 'load', - mw: (cfg) => { - // console.dir(opts); - return views(cfg.root, cfg.opts); - }, -}; diff --git a/packages/core/app.ts b/packages/core/app.ts index 991bec6..58ccbfd 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -5,7 +5,9 @@ import { Fn, createServer, Plugable } from './src/index'; // const rpc = new RpcServer({}); const rpc = createServer({}); -const fn = new Fn({}); +const fn = new Fn({ + prefix: ['/api', '/apk'], +}); const demo = new Demo({}); rpc.fn('/a', function (a) { diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index 86d509b..ec7614c 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -8,8 +8,14 @@ export class Fn extends Plugable { constructor(cfg?: any) { super(cfg); + console.dir(this.config); + this.name = 'Fn'; - this.prefix = '/api'; + if (this.config.prefix === '') { + this.prefix = '/api'; + } + + console.dir(this.config); } fn(key, fn) { // console.dir('=this.config='); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index b4ff006..e8e1e1f 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -145,10 +145,20 @@ export class RpcServer { console.dir('mount plugin ' + plugin.prefix); // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); - const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); + + if (Array.isArray(plugin.prefix) === true) { + console.dir('prefix is array' + plugin.prefix); + plugin.prefix.forEach((path) => { + console.dir('mount path' + path); + const i = mount(path, plugin.app); + this.app.use(path, i); + }); + } else { + const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); + this.app.use(mw); + } // console.dir(plugin.prefix === ''); // console.dir(mw); - this.app.use(mw); } // 兜底的else From 78873a8eef2ad7e9aabf2d4c18ec37e73f0417b3 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 15 Nov 2023 12:00:19 +0800 Subject: [PATCH 043/101] chore: stash --- .vscode/launch.json | 11 ++++++++++- packages/core/app.ts | 9 ++++----- packages/core/src/fn.ts | 7 +++---- packages/core/src/plugin.ts | 3 ++- packages/core/src/server.ts | 23 +++++++++++++++-------- 5 files changed, 34 insertions(+), 19 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 64188b7..de75022 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -4,6 +4,15 @@ // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 "version": "0.2.0", "configurations": [ + { + "name": "Attach by Process ID", + "processId": "${command:PickProcess}", + "request": "attach", + "skipFiles": [ + "/**" + ], + "type": "node" + }, { "type": "node", "request": "launch", @@ -21,4 +30,4 @@ ] } ] -} +} \ No newline at end of file diff --git a/packages/core/app.ts b/packages/core/app.ts index 58ccbfd..08ede24 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -3,12 +3,11 @@ import { Fn, createServer, Plugable } from './src/index'; // import { RpcServer } from './src/server'; // const rpc = new RpcServer({}); -const rpc = createServer({}); - -const fn = new Fn({ - prefix: ['/api', '/apk'], +const rpc = createServer({ + fn: { + prefix: ['/apk', '/aaa'], + }, }); -const demo = new Demo({}); rpc.fn('/a', function (a) { return { a: a }; diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index ec7614c..4666e43 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -8,14 +8,13 @@ export class Fn extends Plugable { constructor(cfg?: any) { super(cfg); - console.dir(this.config); + // console.dir(this.config); this.name = 'Fn'; - if (this.config.prefix === '') { + if (this.prefix === '') { this.prefix = '/api'; } - - console.dir(this.config); + // console.dir(this.config); } fn(key, fn) { // console.dir('=this.config='); diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index abc26cc..9437dd5 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -43,7 +43,8 @@ export class Plugable implements Strategy { this.app = new Koa(); this.init = []; this.load = []; - this.prefix = ''; + this.prefix = this.config.prefix ? this.config.prefix : ''; + this.compose = compose; // TODO: 此处最好改成mount diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index e8e1e1f..f9e38f0 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -1,5 +1,6 @@ import { bodyParser } from '@koa/bodyparser'; import Koa from 'koa'; +import compose from 'koa-compose'; import mount from 'koa-mount'; import { Strategy, log } from './index'; @@ -145,15 +146,21 @@ export class RpcServer { console.dir('mount plugin ' + plugin.prefix); // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); - - if (Array.isArray(plugin.prefix) === true) { - console.dir('prefix is array' + plugin.prefix); - plugin.prefix.forEach((path) => { - console.dir('mount path' + path); - const i = mount(path, plugin.app); - this.app.use(path, i); - }); + const that = this.app; + if (Array.isArray(plugin.config.prefix) === true) { + console.dir('prefix is array ' + plugin.config.prefix); + + for (const i in plugin.config.prefix) { + const path = plugin.config.prefix[i]; + console.dir('mount path = ' + path); + const mw = mount(path, plugin.app); + console.dir(mw); + // console.dir(this); + this.app.use(mw); + } } else { + console.dir('prefix is string ' + plugin.prefix); + const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); this.app.use(mw); } From ff442d186263bef6451669e4dda3080021dfff7e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 15 Nov 2023 16:41:52 +0800 Subject: [PATCH 044/101] chore: revert cant make prefix from string to array --- packages/core/app.ts | 2 +- packages/core/src/fn.ts | 1 + packages/core/src/index.ts | 2 +- packages/core/src/plugin.ts | 1 + packages/core/src/server.ts | 25 +++++++------------------ 5 files changed, 11 insertions(+), 20 deletions(-) diff --git a/packages/core/app.ts b/packages/core/app.ts index 08ede24..1a24c78 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -5,7 +5,7 @@ import { Fn, createServer, Plugable } from './src/index'; // const rpc = new RpcServer({}); const rpc = createServer({ fn: { - prefix: ['/apk', '/aaa'], + prefix: '/apk2', }, }); diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index 4666e43..abb4812 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -49,6 +49,7 @@ export class Fn extends Plugable { const prefix = this.prefix; const routers = this.config['functions']; log(routers); + const path = ctx.path.replace(prefix, ''); log('mountMiddleware' + ctx.path); const key = '/' + path.replace('/', '').split('/').join('.'); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 8cbdb75..46dc665 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -28,7 +28,7 @@ export function createServer(cfg?: any) { }, fn: function (key, fun) { fn.fn(key, fun); - console.dir(fn); + // console.dir(fn); }, add: function (items) { fn.add(items); diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 9437dd5..b883f4d 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -31,6 +31,7 @@ export class Plugable implements Strategy { public prefix; public compose; public config; + public _prefix; constructor(cfg?) { this.config = Object.assign( diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index f9e38f0..72cb6e3 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -143,27 +143,16 @@ export class RpcServer { // mount app for (const plugin of this.plugins) { - console.dir('mount plugin ' + plugin.prefix); + // console.dir('mount plugin ' + plugin.prefix); // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); - const that = this.app; - if (Array.isArray(plugin.config.prefix) === true) { - console.dir('prefix is array ' + plugin.config.prefix); - - for (const i in plugin.config.prefix) { - const path = plugin.config.prefix[i]; - console.dir('mount path = ' + path); - const mw = mount(path, plugin.app); - console.dir(mw); - // console.dir(this); - this.app.use(mw); - } - } else { - console.dir('prefix is string ' + plugin.prefix); - const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); - this.app.use(mw); - } + // console.dir('prefix is string ' + plugin.prefix); + + const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); + // console.dir(this); + this.app.use(mw); + // console.dir(plugin.prefix === ''); // console.dir(mw); } From ab44ca8661bd3ca9e0a80d287820fea6ff6d8603 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 15 Nov 2023 16:50:48 +0800 Subject: [PATCH 045/101] chore: stash --- packages/app/src/mw/cors.ts | 1 + packages/app/src/mw/jwt.ts | 5 ++--- packages/app/src/mw/serve.ts | 2 +- packages/app/src/mw/view.ts | 3 ++- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts index 0b6c9c2..dfded24 100644 --- a/packages/app/src/mw/cors.ts +++ b/packages/app/src/mw/cors.ts @@ -9,6 +9,7 @@ export class Cors extends Plugable { this.init.push(this.a()); } a() { + console.dir('register Cors'); return corsMiddleware(this.config); } } diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index 95984e9..dbc1e30 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -4,15 +4,14 @@ import koajwt from 'koa-jwt'; export class Jwt extends Plugable { constructor(cfg?) { super(cfg); - console.dir('jwt = '); - console.dir(this.config); + // console.dir(this.config); this.prefix = ''; this.name = 'jwt'; this.init.push(this.a()); } a() { - console.dir(this.config); + console.dir('register jwt'); return koajwt(this.config).unless({ path: this.config.unless }); } } diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts index 7ee38e5..44c2806 100644 --- a/packages/app/src/mw/serve.ts +++ b/packages/app/src/mw/serve.ts @@ -8,7 +8,7 @@ export class Serve extends Plugable { this.init.push(this.a()); } a() { - console.dir('serve'); + console.dir('register Serve'); return serveMiddleware(this.config.root, this.config.opts); } } diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts index 4c8412f..5461490 100644 --- a/packages/app/src/mw/view.ts +++ b/packages/app/src/mw/view.ts @@ -6,10 +6,11 @@ export class View extends Plugable { super(cfg); this.prefix = ''; - this.name = 'serve'; + this.name = 'view'; this.init.push(this.a()); } a() { + console.dir('register View'); return views(this.config?.root, this.config); } } From f506fa6b315709a9fbe697c582e0086735eb6677 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 15 Nov 2023 19:48:53 +0800 Subject: [PATCH 046/101] chore: stash --- packages/app/app.ts | 34 +++++++++++++++++----------------- packages/app/src/index.ts | 5 ++--- packages/core/src/fn.ts | 2 +- packages/core/src/plugin.ts | 16 ---------------- 4 files changed, 20 insertions(+), 37 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index f90bbcf..7362720 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -17,7 +17,7 @@ import { createApp } from './src/index'; enable: true, secret: 'shhhhhh', debug: true, - unless: { path: ['/public', '/view', '/', '/api/*'] }, + unless: { path: ['/view'] }, }, view: { enable: true, @@ -29,24 +29,20 @@ import { createApp } from './src/index'; }, }, }, - beforeAll: async (ctx, next) => { - // console.dir(ctx.jwt); - await next(); - }, }); - rpc.jwt(async (ctx, next) => { - const secret = 'shhhhhh'; - const token = jwt.sign({ foo: 'bar' }, secret); - console.dir(ctx.path); + // rpc.jwt(async (ctx, next) => { + // const secret = 'shhhhhh'; + // const token = jwt.sign({ foo: 'bar' }, secret); + // console.dir(ctx.path); - await next(); - // if (['/', '/view', '/api*'].some((e) => ctx.path.match(e))) { - // await next(); - // } else { - // ctx.body = { jwt: 'not jwt' }; - // } - }); + // await next(); + // // if (['/', '/view', '/api*'].some((e) => ctx.path.match(e))) { + // // await next(); + // // } else { + // // ctx.body = { jwt: 'not jwt' }; + // // } + // }); rpc.render('/view', async (ctx, next) => { // console.dir('view'); @@ -54,7 +50,11 @@ import { createApp } from './src/index'; session: ctx.session, title: 'app', }; - await ctx.render('user.ejs', { user: { name: 'alfred' } }); + if (ctx.path === '/view') { + await ctx.render('user.ejs', { user: { name: 'alfred' } }); + } else { + await next(); + } }); // rpc.view vs rpc.fn变成插件 diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index e750c80..004c6e8 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -56,7 +56,6 @@ interface IConfig { view?: IView; jwt?: IJwt; }; - beforeAll: any; } export async function createApp(cfg: IConfig) { const rpc = createServer( @@ -78,7 +77,7 @@ export async function createApp(cfg: IConfig) { rpc.plugin(view); const jwt = new Jwt(cfg.buildin.jwt); - rpc.plugin(jwt); + // rpc.plugin(jwt); // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); @@ -97,7 +96,7 @@ export async function createApp(cfg: IConfig) { return Object.assign(rpc, { jwt: function (cb) { const mw = combine([cb]); - console.dir(rpc.config); + // console.dir(rpc.config); rpc.init.push(mw); }, render: function (path, cb) { diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index abb4812..d9ebca3 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -66,7 +66,7 @@ export class Fn extends Plugable { if (routers[key]) { const args = [...param, ctx]; - // console.dir(args); + console.dir(`call fn ${ctx.path}, with [${param}]`); const result = routers[key].apply(ctx, args); // console.dir(result); ctx.body = result; diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index b883f4d..beb507d 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -15,7 +15,6 @@ export interface Strategy { name; app; compose; - proxy; config; server; serverConfig; @@ -56,21 +55,6 @@ export class Plugable implements Strategy { return ctx[this.name]; } - proxy() { - return async (ctx, next) => { - console.dir('proxy prefix=' + this.prefix); - if (ctx.path.match(this.prefix)) { - console.dir('proxy ' + ctx.path); - await next(); - console.dir('proxy end ' + ctx.path); - } else { - console.dir('not proxy ' + ctx.path); - await next(); - console.dir('not proxy end ' + ctx.path); - } - }; - } - getMiddleware() { // console.dir('getMiddleware'); const pre = this.pre(); From aad4fc0eeb04d8527a763cb4d931a8546ce303df Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 15 Nov 2023 20:10:36 +0800 Subject: [PATCH 047/101] chore: stash --- packages/core/app.ts | 2 +- packages/core/src/server.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/app.ts b/packages/core/app.ts index 1a24c78..5a189ee 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -5,7 +5,7 @@ import { Fn, createServer, Plugable } from './src/index'; // const rpc = new RpcServer({}); const rpc = createServer({ fn: { - prefix: '/apk2', + // prefix: '/apk2', }, }); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 72cb6e3..b3dd8ed 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -150,7 +150,7 @@ export class RpcServer { // console.dir('prefix is string ' + plugin.prefix); const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); - // console.dir(this); + console.dir(plugin.prefix); this.app.use(mw); // console.dir(plugin.prefix === ''); From fbf2e21682348571c96c31f56ce0f62bca030494 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 15 Nov 2023 21:01:15 +0800 Subject: [PATCH 048/101] chore: stash --- packages/core/src/fn.ts | 4 ++-- packages/core/src/server.ts | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index d9ebca3..13d6222 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -115,8 +115,8 @@ export class Fn extends Plugable { supportMethods[0] + ' request from client'; } - - log('beforeOne end'); + await next(); + // log('beforeOne end'); }; } } diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index b3dd8ed..920a7ad 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -72,6 +72,9 @@ export class RpcServer { this.app = new Koa(); this.app.use(bodyParser()); this.use = this.app.use; + this.app.use(async (ctx, next) => { + await next(); + }); } /** @@ -180,6 +183,10 @@ export class RpcServer { this.config.after(this); + this.app.use(function (ctx, next) { + ctx.body = 'default'; + }); + this.app.listen(_port, (err) => { if (err) { console.error(err); From d063d425bbac129e91be6b405eefec8af737c2f1 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 16 Nov 2023 11:53:15 +0800 Subject: [PATCH 049/101] chore: stash --- packages/core/src/fn.ts | 5 ++--- packages/core/src/server.ts | 5 +---- 2 files changed, 3 insertions(+), 7 deletions(-) diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index 13d6222..61d0f2e 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -2,7 +2,7 @@ import debug from 'debug'; import { Plugable } from './plugin'; import { isArrowFunction, getHttpMethods } from './utils'; -const log = debug('@tomrpc/core'); +const log = console.dir; //debug('@tomrpc/core'); export class Fn extends Plugable { constructor(cfg?: any) { @@ -45,7 +45,7 @@ export class Fn extends Plugable { mount() { return async (ctx, next) => { - log(this); + // log(this); const prefix = this.prefix; const routers = this.config['functions']; log(routers); @@ -115,7 +115,6 @@ export class Fn extends Plugable { supportMethods[0] + ' request from client'; } - await next(); // log('beforeOne end'); }; } diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 920a7ad..7a04bb4 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -72,9 +72,6 @@ export class RpcServer { this.app = new Koa(); this.app.use(bodyParser()); this.use = this.app.use; - this.app.use(async (ctx, next) => { - await next(); - }); } /** @@ -146,7 +143,7 @@ export class RpcServer { // mount app for (const plugin of this.plugins) { - // console.dir('mount plugin ' + plugin.prefix); + console.dir('mount plugin ' + plugin.prefix); // console.dir(plugin); // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); From 93dae59752558995fa1b05a2285b0662ada6a30e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 16 Nov 2023 14:40:35 +0800 Subject: [PATCH 050/101] chore: stash --- packages/core/src/fn.ts | 31 +++++++++++++++++-------------- packages/core/src/plugin.ts | 14 ++++++++------ 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index 61d0f2e..ba811c6 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -2,19 +2,18 @@ import debug from 'debug'; import { Plugable } from './plugin'; import { isArrowFunction, getHttpMethods } from './utils'; -const log = console.dir; //debug('@tomrpc/core'); +const log = debug('@tomrpc/core/fn'); export class Fn extends Plugable { constructor(cfg?: any) { super(cfg); - // console.dir(this.config); - this.name = 'Fn'; if (this.prefix === '') { this.prefix = '/api'; } - // console.dir(this.config); + + this.app.use(this.compose([this.before(), this.mount(), this.default()])); } fn(key, fn) { // console.dir('=this.config='); @@ -39,18 +38,22 @@ export class Fn extends Plugable { } } - process() { - return this.mount(); + default() { + return async (ctx, next) => { + log('default'); + ctx.body = '[fn plugin] no fn repsonse, please check your fn if exist'; + log('default end'); + }; } mount() { return async (ctx, next) => { - // log(this); + log(this); const prefix = this.prefix; const routers = this.config['functions']; log(routers); - const path = ctx.path.replace(prefix, ''); + const path = ctx.path; //.replace(prefix, ''); log('mountMiddleware' + ctx.path); const key = '/' + path.replace('/', '').split('/').join('.'); @@ -79,9 +82,9 @@ export class Fn extends Plugable { } }; } - pre() { + before() { return async (ctx, next) => { - // console.log('pre'); + log('pre'); const key = ctx.path.replace('/', '').split('/').join('.'); // this.config.beforeOne(ctx, key); @@ -99,10 +102,10 @@ export class Fn extends Plugable { // console.log(supportMethods); if (supportMethods.length === 0) { - if (ctx.path.indexOf(this.prefix) != -1) { - console.log(ctx.path + ',没有匹配到包含get/post等开头的函数'); - await next(); - } + // if (ctx.path.indexOf(this.prefix) != -1) { + log(ctx.path + ',没有匹配到包含get/post等开头的函数'); + await next(); + // } } else if (ctx.method === supportMethods[0]) { log('匹配到包含get/post等方法的函数'); await next(); diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index beb507d..b4ffd1a 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -1,6 +1,8 @@ +import debug from 'debug'; import Koa from 'koa'; import compose from 'koa-compose'; +const log = debug('@tomrpc/core/plugin'); /** * The Strategy interface declares operations common to all supported versions * of some algorithm. @@ -65,23 +67,23 @@ export class Plugable implements Strategy { pre() { return async (ctx, next) => { - console.dir('pre'); + log('pre'); await next(); - console.dir('pre end'); + log('pre end'); }; } post() { return async (ctx, next) => { - console.dir('after'); + log('after'); await next(); - console.dir('after end'); + log('after end'); }; } process() { return async (ctx, next) => { - console.dir('process default'); + log('process default'); await next(); - console.dir('process default end'); + log('process default end'); }; } From 4cb5628130982a597e8d80c556f0b133a0ada95f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 16 Nov 2023 15:02:42 +0800 Subject: [PATCH 051/101] chore: refact --- packages/core/src/fn.ts | 2 -- packages/core/src/server.ts | 2 +- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index ba811c6..d7612d6 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -49,7 +49,6 @@ export class Fn extends Plugable { mount() { return async (ctx, next) => { log(this); - const prefix = this.prefix; const routers = this.config['functions']; log(routers); @@ -86,7 +85,6 @@ export class Fn extends Plugable { return async (ctx, next) => { log('pre'); const key = ctx.path.replace('/', '').split('/').join('.'); - // this.config.beforeOne(ctx, key); const lastKey = key.split('.').pop(); const httpMethods = getHttpMethods(); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 7a04bb4..85faf14 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -13,7 +13,7 @@ export const LifeCycleConfig = { after: [], default: async (ctx, next) => { log('default'); - ctx.body = 'no middleware repsonse, please check your route'; + ctx.body = '[core server] no middleware repsonse, please check your route'; log('default end'); }, }, From 5fede97af141b8f8d6ba99763dfe2d222108080f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 16 Nov 2023 17:13:12 +0800 Subject: [PATCH 052/101] chore: refact --- packages/core/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/README.md b/packages/core/README.md index 486a911..4028492 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -74,7 +74,7 @@ export default class Fn extends Plugable { this.name = 'demo'; const a = this.a(); - this.addInit(a); + this.use(a); } process() { return async (ctx, next) => { From f5646e591c37be359d12179e9de261bfa3d5d8fd Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 21 Nov 2023 09:45:22 +0800 Subject: [PATCH 053/101] chore: refact --- example/package.json | 2 +- example/src/app.ts | 4 +-- packages/app/CHANGELOG.md | 13 +++++++ packages/app/package.json | 10 +++--- packages/app/src/index.ts | 18 +++++----- packages/app/src/load.ts | 30 ++++++++-------- packages/app/src/mw/cors.ts | 15 -------- packages/app/src/mw/index.ts | 4 --- packages/app/src/mw/jwt.ts | 17 --------- packages/app/src/mw/serve.ts | 14 -------- packages/app/src/mw/view.ts | 16 --------- packages/app/tsup.config.cjs | 1 + packages/client/CHANGELOG.md | 6 ++++ packages/client/package.json | 5 +-- packages/core/CHANGELOG.md | 6 ++++ packages/core/README.md | 20 +++++++++++ packages/core/app.ts | 8 ++++- packages/core/package.json | 4 +-- packages/core/proxy.ts | 15 ++++++++ packages/core/src/__tests__/index.test.ts | 42 ----------------------- packages/core/src/index.ts | 1 + packages/core/src/plugin.ts | 8 +++-- packages/core/src/proxy.ts | 29 ++++++++++++++++ packages/core/src/server.ts | 35 ++++++++++++++++--- packages/core/tsup.config.cjs | 3 +- packages/mount/CHANGELOG.md | 6 ++++ packages/mount/package.json | 4 +-- packages/mount/tsup.config.cjs | 1 + 28 files changed, 181 insertions(+), 156 deletions(-) delete mode 100644 packages/app/src/mw/cors.ts delete mode 100644 packages/app/src/mw/index.ts delete mode 100644 packages/app/src/mw/jwt.ts delete mode 100644 packages/app/src/mw/serve.ts delete mode 100644 packages/app/src/mw/view.ts create mode 100644 packages/core/proxy.ts delete mode 100644 packages/core/src/__tests__/index.test.ts create mode 100644 packages/core/src/proxy.ts diff --git a/example/package.json b/example/package.json index 9c096ba..a111b7f 100644 --- a/example/package.json +++ b/example/package.json @@ -28,4 +28,4 @@ "react": "^18.2.0", "react-dom": "^18.2.0" } -} +} \ No newline at end of file diff --git a/example/src/app.ts b/example/src/app.ts index 469fad8..1fae8f8 100644 --- a/example/src/app.ts +++ b/example/src/app.ts @@ -1,6 +1,6 @@ /* @ts-ignore */ import { createServer } from '@tomrpc/core'; -import mount from '@tomrpc/mount'; +// import mount from '@tomrpc/mount'; (async () => { const rpc = createServer({ @@ -54,7 +54,7 @@ import mount from '@tomrpc/mount'; // console.dir(mount); rpc.base = import.meta.url; - await mount(rpc, './fn'); + // await mount(rpc, './fn'); // https://bobbyhadz.com/blog/typescript-no-overload-matches-this-call // rpc.dump(); diff --git a/packages/app/CHANGELOG.md b/packages/app/CHANGELOG.md index 2303f0f..492dd20 100644 --- a/packages/app/CHANGELOG.md +++ b/packages/app/CHANGELOG.md @@ -1,5 +1,18 @@ # @tomrpc/mount +## 2.0.0 + +### Major Changes + +- test + +### Patch Changes + +- Updated dependencies + - @tomrpc/client@2.0.0 + - @tomrpc/mount@2.0.0 + - @tomrpc/core@2.0.0 + ## 1.0.0 ### Major Changes diff --git a/packages/app/package.json b/packages/app/package.json index 095881d..4fbc606 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/app", - "version": "1.0.0", + "version": "2.0.0", "description": "My Awesome lib", "license": "MIT", "publishConfig": { @@ -32,9 +32,9 @@ }, "dependencies": { "@koa/cors": "^4.0.0", - "@tomrpc/client": "^1.0.0", - "@tomrpc/core": "^1.0.0", - "@tomrpc/mount": "^1.0.0", + "@tomrpc/client": "^2.0.0", + "@tomrpc/core": "^2.0.0", + "@tomrpc/mount": "workspace:^", "debug": "^4.3.4", "desm": "^1.3.0", "ejs": "^3.1.9", @@ -45,4 +45,4 @@ "koa-static": "^5.0.0", "koa-views": "^8.0.0" } -} +} \ No newline at end of file diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 004c6e8..98ab04e 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -1,10 +1,10 @@ import { createServer, combine } from '@tomrpc/core'; -import mount from '@tomrpc/mount'; +// import mount from '@tomrpc/mount'; import debug from 'debug'; import { init } from './init'; import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; -import { Serve, Cors, View, Jwt } from './mw/index'; +// import { Serve, Cors, View, Jwt } from './mw/index'; const log = debug('@tomrpc/app'); @@ -67,16 +67,16 @@ export async function createApp(cfg: IConfig) { ) ); - const cors = new Cors(cfg.buildin.cors); - rpc.plugin(cors); + // const cors = new Cors(cfg.buildin.cors); + // rpc.plugin(cors); - const serve = new Serve(cfg.buildin.serve); - rpc.plugin(serve); + // const serve = new Serve(cfg.buildin.serve); + // rpc.plugin(serve); - const view = new View(cfg.buildin.view); - rpc.plugin(view); + // const view = new View(cfg.buildin.view); + // rpc.plugin(view); - const jwt = new Jwt(cfg.buildin.jwt); + // const jwt = new Jwt(cfg.buildin.jwt); // rpc.plugin(jwt); // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); diff --git a/packages/app/src/load.ts b/packages/app/src/load.ts index 1c1ea1b..e7c9e9b 100644 --- a/packages/app/src/load.ts +++ b/packages/app/src/load.ts @@ -11,21 +11,21 @@ export async function loadInitMiddleware(rpc?, m?) { } export async function loadBuildinMiddlewaire(rpc?) { - const buildin = rpc.config.buildin; - log(rpc.config); - log(buildin); - const mw = await import('./mw'); - for (const key in buildin) { - const m = buildin[key]; - log(m); - if (m['enable'] === true) { - log(buildin[key]); - const _m = mw[key]; - log(_m); - log(_m.lifeCycle); - loadMiddleware(rpc, _m.lifeCycle, _m.mw(m)); - } - } + // const buildin = rpc.config.buildin; + // log(rpc.config); + // log(buildin); + // const mw = await import('./mw'); + // for (const key in buildin) { + // const m = buildin[key]; + // log(m); + // if (m['enable'] === true) { + // log(buildin[key]); + // const _m = mw[key]; + // log(_m); + // log(_m.lifeCycle); + // loadMiddleware(rpc, _m.lifeCycle, _m.mw(m)); + // } + // } } export async function loadMiddleware(rpc, lifeCycle, mw) { diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts deleted file mode 100644 index dfded24..0000000 --- a/packages/app/src/mw/cors.ts +++ /dev/null @@ -1,15 +0,0 @@ -import corsMiddleware from '@koa/cors'; -import { Plugable } from '@tomrpc/core'; - -export class Cors extends Plugable { - constructor(cfg?) { - super(cfg); - console.dir(this.config); - this.name = 'cors'; - this.init.push(this.a()); - } - a() { - console.dir('register Cors'); - return corsMiddleware(this.config); - } -} diff --git a/packages/app/src/mw/index.ts b/packages/app/src/mw/index.ts deleted file mode 100644 index e716b0a..0000000 --- a/packages/app/src/mw/index.ts +++ /dev/null @@ -1,4 +0,0 @@ -export * from './cors'; -export * from './serve'; -export * from './jwt'; -export * from './view'; diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts deleted file mode 100644 index dbc1e30..0000000 --- a/packages/app/src/mw/jwt.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { Plugable } from '@tomrpc/core'; -import koajwt from 'koa-jwt'; - -export class Jwt extends Plugable { - constructor(cfg?) { - super(cfg); - // console.dir(this.config); - - this.prefix = ''; - this.name = 'jwt'; - this.init.push(this.a()); - } - a() { - console.dir('register jwt'); - return koajwt(this.config).unless({ path: this.config.unless }); - } -} diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts deleted file mode 100644 index 44c2806..0000000 --- a/packages/app/src/mw/serve.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Plugable } from '@tomrpc/core'; -import serveMiddleware from 'koa-static'; - -export class Serve extends Plugable { - constructor(cfg?) { - super(cfg); - this.name = 'serve'; - this.init.push(this.a()); - } - a() { - console.dir('register Serve'); - return serveMiddleware(this.config.root, this.config.opts); - } -} diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts deleted file mode 100644 index 5461490..0000000 --- a/packages/app/src/mw/view.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { Plugable } from '@tomrpc/core'; -import views from 'koa-views'; - -export class View extends Plugable { - constructor(cfg?) { - super(cfg); - - this.prefix = ''; - this.name = 'view'; - this.init.push(this.a()); - } - a() { - console.dir('register View'); - return views(this.config?.root, this.config); - } -} diff --git a/packages/app/tsup.config.cjs b/packages/app/tsup.config.cjs index 364f815..e67b529 100644 --- a/packages/app/tsup.config.cjs +++ b/packages/app/tsup.config.cjs @@ -9,4 +9,5 @@ export default defineConfig((options) => ({ loader: { '.js': 'jsx', }, + clean: true, })); diff --git a/packages/client/CHANGELOG.md b/packages/client/CHANGELOG.md index c669c77..b7e5158 100644 --- a/packages/client/CHANGELOG.md +++ b/packages/client/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/client +## 2.0.0 + +### Major Changes + +- test + ## 1.0.0 ### Major Changes diff --git a/packages/client/package.json b/packages/client/package.json index 35a5c8f..36581e1 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/client", - "version": "1.0.0", + "version": "2.0.0", "description": "My Awesome lib", "license": "MIT", "publishConfig": { @@ -17,6 +17,7 @@ "build": "tsup src -- --dts-resolve", "build:fast": "tsup src", "start": "tsup src --watch", + "dev": "tsup src --watch", "test": "vitest run", "test:watch": "vitest watch", "coverage": "vitest run --coverage" @@ -33,4 +34,4 @@ "debug": "^4.3.4", "isomorphic-unfetch": "^4.0.2" } -} +} \ No newline at end of file diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index fcf2e5b..2dc08ce 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/core +## 2.0.0 + +### Major Changes + +- test + ## 1.0.0 ### Major Changes diff --git a/packages/core/README.md b/packages/core/README.md index 4028492..df4d324 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -121,6 +121,26 @@ export default class Fn extends Plugable { - process(可选,返回值是Koa中间件) - post(可选,返回值是Koa中间件) +## 实现Proxy + +```ts +import { Proxy } from './src/proxy'; +export default class TestProxy extends Proxy { + constructor(cfg?) { + super(cfg); + + this.config.proxy.inject = 'before'; + this.config.proxy.before = ['fn']; + } + proxy() { + return async (ctx, next) => { + console.dir('TestProxy process child' + ctx.path); + await next(); + }; + } +} +``` + ## RpcServer diff --git a/packages/core/app.ts b/packages/core/app.ts index 5a189ee..c5d9a4e 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -1,4 +1,4 @@ -import Demo from './demo'; +import TestProxy from './proxy'; import { Fn, createServer, Plugable } from './src/index'; // import { RpcServer } from './src/server'; @@ -9,6 +9,12 @@ const rpc = createServer({ }, }); +const tp = new TestProxy({}); + +rpc.plugin(tp); + +console.dir(rpc); + rpc.fn('/a', function (a) { return { a: a }; }); diff --git a/packages/core/package.json b/packages/core/package.json index f1dc0f6..9ff37d5 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/core", - "version": "1.0.0", + "version": "2.0.0", "description": "My Awesome lib", "license": "MIT", "publishConfig": { @@ -38,4 +38,4 @@ "koa-compose": "^4.1.0", "koa-mount": "^4.0.0" } -} +} \ No newline at end of file diff --git a/packages/core/proxy.ts b/packages/core/proxy.ts new file mode 100644 index 0000000..a9d1937 --- /dev/null +++ b/packages/core/proxy.ts @@ -0,0 +1,15 @@ +import { Proxy } from './src/proxy'; +export default class TestProxy extends Proxy { + constructor(cfg?) { + super(cfg); + + this.config.proxy.inject = 'before'; + this.config.proxy.before = ['fn']; + } + proxy() { + return async (ctx, next) => { + console.dir('TestProxy process child' + ctx.path); + await next(); + }; + } +} diff --git a/packages/core/src/__tests__/index.test.ts b/packages/core/src/__tests__/index.test.ts deleted file mode 100644 index faeed0e..0000000 --- a/packages/core/src/__tests__/index.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -import request from 'supertest'; -import { describe, expect, it } from 'vitest'; - -// import { lib } from '..'; - -describe('lib', () => { - it('should render lib', () => { - expect('lib').toBe('lib'); - }); -}); - -// const request = require('supertest'); -// const { test } = require('uvu'); -// // const assert = require('uvu/assert'); - -// const app = {}; //= require('../../app').callback(); - -// test('get /a/a?$p=["hello",22323]', async () => { -// await request(app) -// .get('/a/a?$p=["hello",22323]') -// .expect('Content-Type', /text\/plain/) -// .expect(200) -// .expect('hello+22323'); -// }); - -// test('post /a/a', async () => { -// await request(app) -// .post('/a/a') -// .send(['22hello', '001']) -// .expect('Content-Type', /text\/plain/) -// .expect(200) -// .expect('this is a post'); -// }); - -// test('post /a/b', async () => { -// await request(app) -// .post('/a/b') -// .send(['1', '2']) -// .expect('Content-Type', /json/) -// .expect(200) -// .expect('{"a":"1","b":"2"}'); -// }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 46dc665..ee735e4 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -4,6 +4,7 @@ import { Fn } from './fn'; import { RpcServer } from './server'; export * from './plugin'; +export * from './proxy'; export * from './fn'; export * from './server'; export * from './utils'; diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index b4ffd1a..ea89332 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -10,16 +10,17 @@ const log = debug('@tomrpc/core/plugin'); * The Context uses this interface to call the algorithm defined by Concrete * Strategies. */ -export interface Strategy { +export declare interface Strategy { init: any[]; load: any[]; prefix; name; app; compose; - config; server; serverConfig; + config: any; + proxy?(): any; } export class Plugable implements Strategy { @@ -31,7 +32,8 @@ export class Plugable implements Strategy { public serverConfig; public prefix; public compose; - public config; + public config: any; + public _prefix; constructor(cfg?) { diff --git a/packages/core/src/proxy.ts b/packages/core/src/proxy.ts new file mode 100644 index 0000000..5cc420c --- /dev/null +++ b/packages/core/src/proxy.ts @@ -0,0 +1,29 @@ +import debug from 'debug'; + +import { Plugable, Strategy } from './plugin'; +import { isArrowFunction, getHttpMethods } from './utils'; +const log = debug('@tomrpc/core/fn'); + +const ProxyDefaultConfig = { + proxy: { + inject: 'before', //init | load | before | after + before: [], + }, +}; + +export class Proxy extends Plugable implements Strategy { + public inject; + + constructor(cfg?: any) { + super(Object.assign(ProxyDefaultConfig, cfg)); + //this.app.use(this.compose([this.before(), this.mount(), this.default()])); + } + + proxy() { + return async (ctx, next) => { + log('proxy default'); + await next(); + log('proxy default end'); + }; + } +} diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 85faf14..5552c5d 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -59,6 +59,11 @@ export class RpcServer { private plugins: Strategy[] = []; app; use; + proxy = { + init: [], + load: [], + before: {}, + }; config; init: []; load: []; @@ -117,7 +122,28 @@ export class RpcServer { await next(); }); + // proxy + for (const plugin of this.plugins) { + console.dir('init proxy stage'); + if (plugin.config.proxy) { + if (plugin.config.proxy.inject === 'init') { + this.proxy.init.push(plugin.proxy()); + } + if (plugin.config.proxy.inject === 'load') { + this.proxy.load.push(plugin.proxy()); + } + if (plugin.config.proxy.inject === 'before') { + for (const i in plugin.config.proxy.before) { + const name = plugin.config.proxy.before[i]; + if (!this.proxy.before[name.toLowerCase()]) this.proxy.before[name.toLowerCase()] = []; + this.proxy.before[name.toLowerCase()].push(plugin.proxy()); + } + } + } + } + // init + this.config.hooks.init = this.proxy.init; for (const plugin of this.plugins) { console.dir('init stage'); if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); @@ -129,6 +155,7 @@ export class RpcServer { this.config.init(this); // load + this.config.hooks.load = this.proxy.load; for (const plugin of this.plugins) { console.dir('load stage'); if (plugin.load.length > 0) this.config.hooks.load.push(...plugin.load); @@ -144,14 +171,12 @@ export class RpcServer { // mount app for (const plugin of this.plugins) { console.dir('mount plugin ' + plugin.prefix); - // console.dir(plugin); - // this.app.use(compose([plugin.proxy(), mount(plugin.prefix, plugin.app)])); - // console.dir('prefix is string ' + plugin.prefix); + const mw = this.proxy.before[plugin.name.toLowerCase()] || []; - const mw = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); + const app = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); console.dir(plugin.prefix); - this.app.use(mw); + this.app.use(compose([...mw, app])); // console.dir(plugin.prefix === ''); // console.dir(mw); diff --git a/packages/core/tsup.config.cjs b/packages/core/tsup.config.cjs index 369773b..313978f 100644 --- a/packages/core/tsup.config.cjs +++ b/packages/core/tsup.config.cjs @@ -4,9 +4,10 @@ export default defineConfig((options) => ({ entry: 'src/index.ts', sourcemap: !options.watch, minify: !options.watch, - // dts: true, + dts: true, format: ['esm', 'cjs'], loader: { '.js': 'jsx', }, + clean: true, })); diff --git a/packages/mount/CHANGELOG.md b/packages/mount/CHANGELOG.md index 2303f0f..5e9518e 100644 --- a/packages/mount/CHANGELOG.md +++ b/packages/mount/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/mount +## 2.0.0 + +### Major Changes + +- test + ## 1.0.0 ### Major Changes diff --git a/packages/mount/package.json b/packages/mount/package.json index 7f37744..3797131 100644 --- a/packages/mount/package.json +++ b/packages/mount/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/mount", - "version": "1.0.0", + "version": "2.0.0", "description": "My Awesome lib", "license": "MIT", "publishConfig": { @@ -35,4 +35,4 @@ "desm": "^1.3.0", "flat": "^6.0.1" } -} +} \ No newline at end of file diff --git a/packages/mount/tsup.config.cjs b/packages/mount/tsup.config.cjs index 364f815..e67b529 100644 --- a/packages/mount/tsup.config.cjs +++ b/packages/mount/tsup.config.cjs @@ -9,4 +9,5 @@ export default defineConfig((options) => ({ loader: { '.js': 'jsx', }, + clean: true, })); From 77dfd92a030bda341dead6d82000b6a57b21d034 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 21 Nov 2023 16:48:21 +0800 Subject: [PATCH 054/101] chore: stash --- packages/app/app.ts | 2 +- packages/app/src/index.ts | 18 +++++++++--------- packages/app/src/mw/cors.ts | 14 ++++++++++++++ packages/app/src/mw/index.ts | 4 ++++ packages/app/src/mw/jwt.ts | 14 ++++++++++++++ packages/app/src/mw/serve.ts | 14 ++++++++++++++ packages/app/src/mw/view.ts | 14 ++++++++++++++ packages/app/tsup.config.cjs | 7 ++----- packages/core/tsup.config.cjs | 3 --- 9 files changed, 72 insertions(+), 18 deletions(-) create mode 100644 packages/app/src/mw/cors.ts create mode 100644 packages/app/src/mw/index.ts create mode 100644 packages/app/src/mw/jwt.ts create mode 100644 packages/app/src/mw/serve.ts create mode 100644 packages/app/src/mw/view.ts diff --git a/packages/app/app.ts b/packages/app/app.ts index 7362720..a4e7835 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -45,7 +45,7 @@ import { createApp } from './src/index'; // }); rpc.render('/view', async (ctx, next) => { - // console.dir('view'); + console.dir('view'); ctx.state = { session: ctx.session, title: 'app', diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 98ab04e..1345482 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -4,7 +4,7 @@ import debug from 'debug'; import { init } from './init'; import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; -// import { Serve, Cors, View, Jwt } from './mw/index'; +import { Serve, Cors, View, Jwt } from './mw/index'; const log = debug('@tomrpc/app'); @@ -67,17 +67,17 @@ export async function createApp(cfg: IConfig) { ) ); - // const cors = new Cors(cfg.buildin.cors); - // rpc.plugin(cors); + const cors = new Cors(cfg.buildin.cors); + rpc.plugin(cors); - // const serve = new Serve(cfg.buildin.serve); - // rpc.plugin(serve); + const serve = new Serve(cfg.buildin.serve); + rpc.plugin(serve); - // const view = new View(cfg.buildin.view); - // rpc.plugin(view); + const view = new View(cfg.buildin.view); + rpc.plugin(view); - // const jwt = new Jwt(cfg.buildin.jwt); - // rpc.plugin(jwt); + const jwt = new Jwt(cfg.buildin.jwt); + rpc.plugin(jwt); // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); diff --git a/packages/app/src/mw/cors.ts b/packages/app/src/mw/cors.ts new file mode 100644 index 0000000..c6d91cf --- /dev/null +++ b/packages/app/src/mw/cors.ts @@ -0,0 +1,14 @@ +import corsMiddleware from '@koa/cors'; +import { Proxy } from '@tomrpc/core'; + +export class Cors extends Proxy { + constructor(cfg?) { + super(cfg); + + this.config.proxy.inject = 'before'; + this.config.proxy.before = ['fn']; + } + proxy() { + return corsMiddleware(this.config); + } +} diff --git a/packages/app/src/mw/index.ts b/packages/app/src/mw/index.ts new file mode 100644 index 0000000..e716b0a --- /dev/null +++ b/packages/app/src/mw/index.ts @@ -0,0 +1,4 @@ +export * from './cors'; +export * from './serve'; +export * from './jwt'; +export * from './view'; diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts new file mode 100644 index 0000000..f546867 --- /dev/null +++ b/packages/app/src/mw/jwt.ts @@ -0,0 +1,14 @@ +import { Proxy } from '@tomrpc/core'; +import koajwt from 'koa-jwt'; + +export class Jwt extends Proxy { + constructor(cfg?) { + super(cfg); + + this.config.proxy.inject = 'before'; + this.config.proxy.before = ['fn']; + } + proxy() { + return koajwt(this.config).unless({ path: this.config.unless }); + } +} diff --git a/packages/app/src/mw/serve.ts b/packages/app/src/mw/serve.ts new file mode 100644 index 0000000..caf2d6a --- /dev/null +++ b/packages/app/src/mw/serve.ts @@ -0,0 +1,14 @@ +import { Proxy } from '@tomrpc/core'; +import serveMiddleware from 'koa-static'; + +export class Serve extends Proxy { + constructor(cfg?) { + super(cfg); + + this.config.proxy.inject = 'init'; + // this.config.proxy.before = ['fn']; + } + proxy() { + return serveMiddleware(this.config.root, this.config.opts); + } +} diff --git a/packages/app/src/mw/view.ts b/packages/app/src/mw/view.ts new file mode 100644 index 0000000..3563ae5 --- /dev/null +++ b/packages/app/src/mw/view.ts @@ -0,0 +1,14 @@ +import { Proxy } from '@tomrpc/core'; +import views from 'koa-views'; + +export class View extends Proxy { + constructor(cfg?) { + super(cfg); + + this.config.proxy.inject = 'init'; + // this.config.proxy.before = ['fn']; + } + proxy() { + return views(this.config?.root, this.config); + } +} diff --git a/packages/app/tsup.config.cjs b/packages/app/tsup.config.cjs index e67b529..0991647 100644 --- a/packages/app/tsup.config.cjs +++ b/packages/app/tsup.config.cjs @@ -4,10 +4,7 @@ export default defineConfig((options) => ({ entry: 'src/index.ts', sourcemap: !options.watch, minify: !options.watch, - dts: true, - format: ['esm'], - loader: { - '.js': 'jsx', - }, + // dts: true, + format: ['esm', 'cjs'], clean: true, })); diff --git a/packages/core/tsup.config.cjs b/packages/core/tsup.config.cjs index 313978f..0ec5063 100644 --- a/packages/core/tsup.config.cjs +++ b/packages/core/tsup.config.cjs @@ -6,8 +6,5 @@ export default defineConfig((options) => ({ minify: !options.watch, dts: true, format: ['esm', 'cjs'], - loader: { - '.js': 'jsx', - }, clean: true, })); From 3b70bf6405ccc2193d1060e173af0d4436e69a65 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 21 Nov 2023 18:00:56 +0800 Subject: [PATCH 055/101] chore: stash --- packages/app/app.ts | 2 +- packages/app/src/index.ts | 9 +++++---- packages/core/proxy.ts | 2 +- packages/core/src/server.ts | 2 ++ 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index a4e7835..ddbc1bb 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -65,7 +65,7 @@ import { createApp } from './src/index'; return { a: a }; }); - // console.dir(rpc); + console.dir(rpc); rpc.start(); })(); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 1345482..ed7719e 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -77,7 +77,7 @@ export async function createApp(cfg: IConfig) { rpc.plugin(view); const jwt = new Jwt(cfg.buildin.jwt); - rpc.plugin(jwt); + // rpc.plugin(jwt); // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); @@ -95,13 +95,14 @@ export async function createApp(cfg: IConfig) { return Object.assign(rpc, { jwt: function (cb) { - const mw = combine([cb]); + // const mw = combine([cb]); // console.dir(rpc.config); - rpc.init.push(mw); + // rpc.init.push(mw); }, render: function (path, cb) { + console.dir('render'); const mw = combine([cb]); - rpc.load.push(mw); + rpc.app.use(mw); }, }); } diff --git a/packages/core/proxy.ts b/packages/core/proxy.ts index a9d1937..c23da3b 100644 --- a/packages/core/proxy.ts +++ b/packages/core/proxy.ts @@ -3,7 +3,7 @@ export default class TestProxy extends Proxy { constructor(cfg?) { super(cfg); - this.config.proxy.inject = 'before'; + this.config.proxy.inject = 'init'; this.config.proxy.before = ['fn']; } proxy() { diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 5552c5d..c844be9 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -125,8 +125,10 @@ export class RpcServer { // proxy for (const plugin of this.plugins) { console.dir('init proxy stage'); + if (plugin.config.proxy) { if (plugin.config.proxy.inject === 'init') { + console.dir('plugin.config.proxy.inject init'); this.proxy.init.push(plugin.proxy()); } if (plugin.config.proxy.inject === 'load') { From f9a1cf44b64f0097001b4bcca609bb16285c69df Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 21 Nov 2023 21:05:52 +0800 Subject: [PATCH 056/101] chore: stash --- packages/app/src/index.ts | 1 + packages/app/tsup.config.cjs | 2 +- packages/core/src/index.ts | 1 + packages/core/src/server.ts | 3 +++ packages/core/tsup.config.cjs | 2 +- 5 files changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index ed7719e..cab060e 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -75,6 +75,7 @@ export async function createApp(cfg: IConfig) { const view = new View(cfg.buildin.view); rpc.plugin(view); + console.dir(view); const jwt = new Jwt(cfg.buildin.jwt); // rpc.plugin(jwt); diff --git a/packages/app/tsup.config.cjs b/packages/app/tsup.config.cjs index 0991647..4a4d4cb 100644 --- a/packages/app/tsup.config.cjs +++ b/packages/app/tsup.config.cjs @@ -6,5 +6,5 @@ export default defineConfig((options) => ({ minify: !options.watch, // dts: true, format: ['esm', 'cjs'], - clean: true, + // clean: true, })); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index ee735e4..a3fa03b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -15,6 +15,7 @@ export function createServer(cfg?: any) { const rpc = new RpcServer(Object.assign({ fn: {} }, cfg)); const fn = new Fn(Object.assign({}, cfg.fn)); + console.dir('createServer'); rpc.plugin(fn); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index c844be9..e459c96 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -125,6 +125,7 @@ export class RpcServer { // proxy for (const plugin of this.plugins) { console.dir('init proxy stage'); + // console.dir(plugin); if (plugin.config.proxy) { if (plugin.config.proxy.inject === 'init') { @@ -132,9 +133,11 @@ export class RpcServer { this.proxy.init.push(plugin.proxy()); } if (plugin.config.proxy.inject === 'load') { + console.dir('plugin.config.proxy.inject load'); this.proxy.load.push(plugin.proxy()); } if (plugin.config.proxy.inject === 'before') { + console.dir('plugin.config.proxy.inject before'); for (const i in plugin.config.proxy.before) { const name = plugin.config.proxy.before[i]; if (!this.proxy.before[name.toLowerCase()]) this.proxy.before[name.toLowerCase()] = []; diff --git a/packages/core/tsup.config.cjs b/packages/core/tsup.config.cjs index 0ec5063..177ad89 100644 --- a/packages/core/tsup.config.cjs +++ b/packages/core/tsup.config.cjs @@ -6,5 +6,5 @@ export default defineConfig((options) => ({ minify: !options.watch, dts: true, format: ['esm', 'cjs'], - clean: true, + // clean: true, })); From 0f927a35c51a0267228847dddae5a90d2faf2c02 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 27 Nov 2023 21:19:00 +0800 Subject: [PATCH 057/101] chore: stash --- package.json | 3 ++- packages/core/app.ts | 11 +++++++++-- packages/core/proxy.ts | 17 ++++++++++++++++- 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index dcabeab..d46f0a5 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "license": "MIT", "devDependencies": { "@commitlint/config-conventional": "^17.7.0", + "@microsoft/api-extractor": "^7.38.3", "@size-limit/preset-small-lib": "^8.2.6", "@types/node": "^18.17.9", "@typescript-eslint/eslint-plugin": "^5.62.0", @@ -39,7 +40,7 @@ "nx": "16.3.2", "prettier": "^2.8.8", "size-limit": "^8.2.6", - "tsup": "^7.2.0", + "tsup": "^8.0.1", "tsx": "^3.12.10", "typescript": "^4.9.5", "vite": "^4.4.9", diff --git a/packages/core/app.ts b/packages/core/app.ts index c5d9a4e..f5d76f7 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -1,4 +1,4 @@ -import TestProxy from './proxy'; +import { TestProxy, TestProxy2 } from './proxy'; import { Fn, createServer, Plugable } from './src/index'; // import { RpcServer } from './src/server'; @@ -12,8 +12,15 @@ const rpc = createServer({ const tp = new TestProxy({}); rpc.plugin(tp); +// console.dir(rpc.plugins[1]['config']); +const tp2 = new TestProxy2({}); -console.dir(rpc); +rpc.plugin(tp2); + +console.dir('rpc2'); +// console.dir(rpc.plugins[1]['config']); + +// console.dir(rpc.plugins[2]['config']); rpc.fn('/a', function (a) { return { a: a }; diff --git a/packages/core/proxy.ts b/packages/core/proxy.ts index c23da3b..c1e7584 100644 --- a/packages/core/proxy.ts +++ b/packages/core/proxy.ts @@ -1,5 +1,5 @@ import { Proxy } from './src/proxy'; -export default class TestProxy extends Proxy { +export class TestProxy extends Proxy { constructor(cfg?) { super(cfg); @@ -13,3 +13,18 @@ export default class TestProxy extends Proxy { }; } } + +export class TestProxy2 extends Proxy { + constructor(cfg?) { + super(cfg); + + this.config.proxy.inject = 'before'; + this.config.proxy.before = ['fn']; + } + proxy() { + return async (ctx, next) => { + console.dir('TestProxy process child' + ctx.path); + await next(); + }; + } +} From 8a51c3d8f675f3ac55e4b74f29bf915cecf99930 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 27 Nov 2023 23:47:39 +0800 Subject: [PATCH 058/101] chore: refact --- packages/app/app.ts | 2 +- packages/app/src/index.ts | 7 ++++--- packages/app/src/utils.ts | 32 ++++++++++++++++++++++++++++++++ packages/core/app.ts | 2 +- packages/core/src/index.ts | 9 +++++---- packages/core/src/plugin.ts | 4 +++- packages/core/src/proxy.ts | 4 ++-- packages/core/src/server.ts | 6 ++++-- packages/core/src/utils.ts | 32 ++++++++++++++++++++++++++++++++ 9 files changed, 84 insertions(+), 14 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index ddbc1bb..a4e7835 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -65,7 +65,7 @@ import { createApp } from './src/index'; return { a: a }; }); - console.dir(rpc); + // console.dir(rpc); rpc.start(); })(); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index cab060e..e8572fa 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -5,6 +5,7 @@ import debug from 'debug'; import { init } from './init'; import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; import { Serve, Cors, View, Jwt } from './mw/index'; +import { mergeDeep } from './utils'; const log = debug('@tomrpc/app'); @@ -59,7 +60,7 @@ interface IConfig { } export async function createApp(cfg: IConfig) { const rpc = createServer( - Object.assign( + mergeDeep( { base: import.meta.url, }, @@ -75,10 +76,10 @@ export async function createApp(cfg: IConfig) { const view = new View(cfg.buildin.view); rpc.plugin(view); - console.dir(view); + // console.dir(view); const jwt = new Jwt(cfg.buildin.jwt); - // rpc.plugin(jwt); + rpc.plugin(jwt); // await mount(rpc, cfg.mount); // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); diff --git a/packages/app/src/utils.ts b/packages/app/src/utils.ts index cc7822e..9bdee5e 100644 --- a/packages/app/src/utils.ts +++ b/packages/app/src/utils.ts @@ -16,3 +16,35 @@ export function isFunction(fn) { fn === window.prompt)) ); } + +/** + * Simple object check. + * @param item + * @returns {boolean} + */ +export function isObject(item) { + return item && typeof item === 'object' && !Array.isArray(item); +} + +/** + * Deep merge two objects. + * @param target + * @param ...sources + */ +export function mergeDeep(target, ...sources) { + if (!sources.length) return target; + const source = sources.shift(); + + if (isObject(target) && isObject(source)) { + for (const key in source) { + if (isObject(source[key])) { + if (!target[key]) Object.assign(target, { [key]: {} }); + mergeDeep(target[key], source[key]); + } else { + Object.assign(target, { [key]: source[key] }); + } + } + } + + return mergeDeep(target, ...sources); +} diff --git a/packages/core/app.ts b/packages/core/app.ts index f5d76f7..159b217 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -17,7 +17,7 @@ const tp2 = new TestProxy2({}); rpc.plugin(tp2); -console.dir('rpc2'); +// console.dir('rpc2'); // console.dir(rpc.plugins[1]['config']); // console.dir(rpc.plugins[2]['config']); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index a3fa03b..ba2b7b4 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,6 +2,7 @@ import compose from 'koa-compose'; import { Fn } from './fn'; import { RpcServer } from './server'; +import { mergeDeep } from './utils'; export * from './plugin'; export * from './proxy'; @@ -12,14 +13,14 @@ export * from './utils'; export const combine = compose; export function createServer(cfg?: any) { - const rpc = new RpcServer(Object.assign({ fn: {} }, cfg)); + const rpc = new RpcServer(mergeDeep({ fn: {} }, cfg)); - const fn = new Fn(Object.assign({}, cfg.fn)); - console.dir('createServer'); + const fn = new Fn(mergeDeep({}, cfg.fn)); + // console.dir('createServer'); rpc.plugin(fn); - return Object.assign(rpc, { + return mergeDeep(rpc, { base: '.', init: rpc['config']['hooks']['init'], before: rpc['config']['hooks']['before'], diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index ea89332..72b038d 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -2,6 +2,8 @@ import debug from 'debug'; import Koa from 'koa'; import compose from 'koa-compose'; +import { mergeDeep } from './utils'; + const log = debug('@tomrpc/core/plugin'); /** * The Strategy interface declares operations common to all supported versions @@ -37,7 +39,7 @@ export class Plugable implements Strategy { public _prefix; constructor(cfg?) { - this.config = Object.assign( + this.config = mergeDeep( { bind: {}, }, diff --git a/packages/core/src/proxy.ts b/packages/core/src/proxy.ts index 5cc420c..314572a 100644 --- a/packages/core/src/proxy.ts +++ b/packages/core/src/proxy.ts @@ -1,7 +1,7 @@ import debug from 'debug'; import { Plugable, Strategy } from './plugin'; -import { isArrowFunction, getHttpMethods } from './utils'; +import { isArrowFunction, getHttpMethods, mergeDeep } from './utils'; const log = debug('@tomrpc/core/fn'); const ProxyDefaultConfig = { @@ -15,7 +15,7 @@ export class Proxy extends Plugable implements Strategy { public inject; constructor(cfg?: any) { - super(Object.assign(ProxyDefaultConfig, cfg)); + super(mergeDeep(ProxyDefaultConfig, cfg)); //this.app.use(this.compose([this.before(), this.mount(), this.default()])); } diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index e459c96..52f78dc 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -4,6 +4,7 @@ import compose from 'koa-compose'; import mount from 'koa-mount'; import { Strategy, log } from './index'; +import { mergeDeep } from './utils'; export const LifeCycleConfig = { hooks: { @@ -26,11 +27,12 @@ export const LifeCycleConfig = { }); }, init: async (server) => { - // console.dir('init'); + console.dir('init'); // console.dir(server); const app = server.app; const loadMiddlewares = server.config.hooks.init; loadMiddlewares.forEach((mw) => { + console.dir(mw); app.use(mw); }); }, @@ -73,7 +75,7 @@ export class RpcServer { */ constructor(cfg) { // init - this.config = Object.assign(LifeCycleConfig, cfg); + this.config = mergeDeep(LifeCycleConfig, cfg); this.app = new Koa(); this.app.use(bodyParser()); this.use = this.app.use; diff --git a/packages/core/src/utils.ts b/packages/core/src/utils.ts index caaf594..c2da1b2 100644 --- a/packages/core/src/utils.ts +++ b/packages/core/src/utils.ts @@ -47,3 +47,35 @@ export function log(msg, debugFlag?) { debugLog(msg); } } + +/** + * Simple object check. + * @param item + * @returns {boolean} + */ +export function isObject(item) { + return item && typeof item === 'object' && !Array.isArray(item); +} + +/** + * Deep merge two objects. + * @param target + * @param ...sources + */ +export function mergeDeep(target, ...sources) { + if (!sources.length) return target; + const source = sources.shift(); + + if (isObject(target) && isObject(source)) { + for (const key in source) { + if (isObject(source[key])) { + if (!target[key]) Object.assign(target, { [key]: {} }); + mergeDeep(target[key], source[key]); + } else { + Object.assign(target, { [key]: source[key] }); + } + } + } + + return mergeDeep(target, ...sources); +} From c8466fccb229cf304cef0ecfce1a5408bc51200e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 11:29:15 +0800 Subject: [PATCH 059/101] chore: stash --- packages/app/app.ts | 6 ++++++ packages/app/src/index.ts | 3 ++- packages/core/src/server.ts | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index a4e7835..c54b4c1 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -17,6 +17,12 @@ import { createApp } from './src/index'; enable: true, secret: 'shhhhhh', debug: true, + getToken: () => { + const token = jwt.sign({ foo: 'bar' }, 'bad'); + console.dir('token'); + console.dir(token); + return token; + }, unless: { path: ['/view'] }, }, view: { diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index e8572fa..48831fd 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -44,6 +44,7 @@ interface IJwt { issuer?: string; debug: boolean; unless?: any; + getToken; } interface IConfig { name: string | 'tomapp'; @@ -103,7 +104,7 @@ export async function createApp(cfg: IConfig) { }, render: function (path, cb) { console.dir('render'); - const mw = combine([cb]); + const mw = combine([view.proxy(), cb]); rpc.app.use(mw); }, }); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 52f78dc..5c8e7dd 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -32,7 +32,7 @@ export const LifeCycleConfig = { const app = server.app; const loadMiddlewares = server.config.hooks.init; loadMiddlewares.forEach((mw) => { - console.dir(mw); + // console.dir(mw); app.use(mw); }); }, From 5b0d0d7a34bdbff570d088e158a2c8765f85beee Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 15:12:11 +0800 Subject: [PATCH 060/101] chore: refact --- packages/app/src/index.ts | 19 ++++--------------- packages/core/src/server.ts | 23 +++++++++++------------ 2 files changed, 15 insertions(+), 27 deletions(-) diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 48831fd..99eaadc 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -75,8 +75,7 @@ export async function createApp(cfg: IConfig) { const serve = new Serve(cfg.buildin.serve); rpc.plugin(serve); - const view = new View(cfg.buildin.view); - rpc.plugin(view); + // rpc.plugin(view); // console.dir(view); const jwt = new Jwt(cfg.buildin.jwt); @@ -85,25 +84,15 @@ export async function createApp(cfg: IConfig) { // await loadInitMiddleware(rpc, init); // await loadBuildinMiddlewaire(rpc); - // rpc[load].push([someMw]) - // mount with lifecycle - - // await loadCustomMiddlewaire(rpc); - - // console.dir(mount); - // if (cfg.mount) { - // rpc.base = import.meta.url; - // // await mount(rpc, './fn'); - // } - - return Object.assign(rpc, { + return mergeDeep(rpc, { jwt: function (cb) { // const mw = combine([cb]); // console.dir(rpc.config); // rpc.init.push(mw); }, render: function (path, cb) { - console.dir('render'); + // console.dir('render'); + const view = new View(cfg.buildin.view); const mw = combine([view.proxy(), cb]); rpc.app.use(mw); }, diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 5c8e7dd..70160dc 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -27,7 +27,7 @@ export const LifeCycleConfig = { }); }, init: async (server) => { - console.dir('init'); + log('init'); // console.dir(server); const app = server.app; const loadMiddlewares = server.config.hooks.init; @@ -99,7 +99,7 @@ export class RpcServer { // set config namespace if (plugin.name === 'base') { - console.error('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); + log('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); } // console.log('mount plugin.config'); // console.log(plugin); @@ -126,20 +126,20 @@ export class RpcServer { // proxy for (const plugin of this.plugins) { - console.dir('init proxy stage'); + // console.dir('init proxy stage'); // console.dir(plugin); if (plugin.config.proxy) { if (plugin.config.proxy.inject === 'init') { - console.dir('plugin.config.proxy.inject init'); + log('plugin.config.proxy.inject init'); this.proxy.init.push(plugin.proxy()); } if (plugin.config.proxy.inject === 'load') { - console.dir('plugin.config.proxy.inject load'); + log('plugin.config.proxy.inject load'); this.proxy.load.push(plugin.proxy()); } if (plugin.config.proxy.inject === 'before') { - console.dir('plugin.config.proxy.inject before'); + log('plugin.config.proxy.inject before'); for (const i in plugin.config.proxy.before) { const name = plugin.config.proxy.before[i]; if (!this.proxy.before[name.toLowerCase()]) this.proxy.before[name.toLowerCase()] = []; @@ -152,9 +152,8 @@ export class RpcServer { // init this.config.hooks.init = this.proxy.init; for (const plugin of this.plugins) { - console.dir('init stage'); + log('init stage'); if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); - // console.dir(this.config.hooks.init); } @@ -164,7 +163,7 @@ export class RpcServer { // load this.config.hooks.load = this.proxy.load; for (const plugin of this.plugins) { - console.dir('load stage'); + log('load stage'); if (plugin.load.length > 0) this.config.hooks.load.push(...plugin.load); // console.dir('load plugin'); // console.dir(plugin.load); @@ -177,12 +176,12 @@ export class RpcServer { // mount app for (const plugin of this.plugins) { - console.dir('mount plugin ' + plugin.prefix); + log('mount plugin ' + plugin.prefix); const mw = this.proxy.before[plugin.name.toLowerCase()] || []; const app = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); - console.dir(plugin.prefix); + log(plugin.prefix); this.app.use(compose([...mw, app])); // console.dir(plugin.prefix === ''); @@ -190,7 +189,7 @@ export class RpcServer { } // 兜底的else - console.dir('兜底的else'); + log('兜底的else'); this.app.use(this.config.hooks.default); // this.app.use(async (ctx, next) => { // console.dir(ctx.path); From e85b4c58e0daf129cc2c6c61a50ace4c7966d187 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 15:17:41 +0800 Subject: [PATCH 061/101] chore: refact --- packages/app/CHANGELOG.md | 10 ++++++++++ packages/app/package.json | 6 +++--- packages/client/CHANGELOG.md | 6 ++++++ packages/client/package.json | 2 +- packages/core/CHANGELOG.md | 6 ++++++ packages/core/package.json | 2 +- packages/mount/CHANGELOG.md | 6 ++++++ packages/mount/package.json | 2 +- 8 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/app/CHANGELOG.md b/packages/app/CHANGELOG.md index 492dd20..0359bec 100644 --- a/packages/app/CHANGELOG.md +++ b/packages/app/CHANGELOG.md @@ -1,5 +1,15 @@ # @tomrpc/mount +## 2.0.1 + +### Patch Changes + +- test +- Updated dependencies + - @tomrpc/client@2.0.1 + - @tomrpc/mount@2.0.1 + - @tomrpc/core@2.0.1 + ## 2.0.0 ### Major Changes diff --git a/packages/app/package.json b/packages/app/package.json index 4fbc606..a2cf98b 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/app", - "version": "2.0.0", + "version": "2.0.1", "description": "My Awesome lib", "license": "MIT", "publishConfig": { @@ -32,8 +32,8 @@ }, "dependencies": { "@koa/cors": "^4.0.0", - "@tomrpc/client": "^2.0.0", - "@tomrpc/core": "^2.0.0", + "@tomrpc/client": "^2.0.1", + "@tomrpc/core": "^2.0.1", "@tomrpc/mount": "workspace:^", "debug": "^4.3.4", "desm": "^1.3.0", diff --git a/packages/client/CHANGELOG.md b/packages/client/CHANGELOG.md index b7e5158..fd92b8c 100644 --- a/packages/client/CHANGELOG.md +++ b/packages/client/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/client +## 2.0.1 + +### Patch Changes + +- test + ## 2.0.0 ### Major Changes diff --git a/packages/client/package.json b/packages/client/package.json index 36581e1..a58917d 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/client", - "version": "2.0.0", + "version": "2.0.1", "description": "My Awesome lib", "license": "MIT", "publishConfig": { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 2dc08ce..dcfc41c 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/core +## 2.0.1 + +### Patch Changes + +- test + ## 2.0.0 ### Major Changes diff --git a/packages/core/package.json b/packages/core/package.json index 9ff37d5..feeab37 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/core", - "version": "2.0.0", + "version": "2.0.1", "description": "My Awesome lib", "license": "MIT", "publishConfig": { diff --git a/packages/mount/CHANGELOG.md b/packages/mount/CHANGELOG.md index 5e9518e..046860f 100644 --- a/packages/mount/CHANGELOG.md +++ b/packages/mount/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/mount +## 2.0.1 + +### Patch Changes + +- test + ## 2.0.0 ### Major Changes diff --git a/packages/mount/package.json b/packages/mount/package.json index 3797131..106be34 100644 --- a/packages/mount/package.json +++ b/packages/mount/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/mount", - "version": "2.0.0", + "version": "2.0.1", "description": "My Awesome lib", "license": "MIT", "publishConfig": { From 36fcf2cc44eeb371dc975f7f0593ceae832fdf3c Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 18:03:38 +0800 Subject: [PATCH 062/101] chore: add test --- packages/core/app.ts | 2 +- packages/core/package.json | 1 - packages/core/src/__tests__/index.test.ts | 45 +++++++++++++++++++++++ packages/core/src/server.ts | 28 ++++++++++---- 4 files changed, 66 insertions(+), 10 deletions(-) create mode 100644 packages/core/src/__tests__/index.test.ts diff --git a/packages/core/app.ts b/packages/core/app.ts index 159b217..8897e4e 100644 --- a/packages/core/app.ts +++ b/packages/core/app.ts @@ -1,5 +1,5 @@ import { TestProxy, TestProxy2 } from './proxy'; -import { Fn, createServer, Plugable } from './src/index'; +import { createServer } from './src/index'; // import { RpcServer } from './src/server'; // const rpc = new RpcServer({}); diff --git a/packages/core/package.json b/packages/core/package.json index feeab37..1615115 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -27,7 +27,6 @@ "devDependencies": { "@types/koa": "^2.13.10", "@vitest/coverage-v8": "^0.34.6", - "happy-dom": "^6.0.4", "supertest": "^6.3.3", "vitest": "^0.34.6" }, diff --git a/packages/core/src/__tests__/index.test.ts b/packages/core/src/__tests__/index.test.ts new file mode 100644 index 0000000..42184d9 --- /dev/null +++ b/packages/core/src/__tests__/index.test.ts @@ -0,0 +1,45 @@ +import supertest from 'supertest'; +import { describe, expect, it, beforeAll } from 'vitest'; + +import { TestProxy, TestProxy2 } from '../../proxy'; +import { createServer } from '../index'; +// import { RpcServer } from './src/server'; + +// const rpc = new RpcServer({}); +const rpc = createServer({ + fn: { + // prefix: '/apk2', + }, +}); + +rpc.fn('/a', function (a) { + return { a: a }; +}); +// import mount from '../mount'; + +// beforeAll(async () => { +// // called once before all tests run +// await startMocking(); + +// // clean up function, called once after all tests run +// return async () => { +// await stopMocking(); +// }; +// }); + +rpc.prepare(); + +const request = supertest(rpc.callback()); + +describe('app', async () => { + it('should first app', async () => { + const res = await request.get('/api/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); + + it('should render lib', () => { + expect('lib').toBe('lib'); + }); +}); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 70160dc..2caa50b 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -198,24 +198,36 @@ export class RpcServer { } /** - * The Context delegates some work to the Strategy object instead of - * implementing multiple versions of the algorithm on its own. + * make app ready, add before hook & mount & after hook */ - public start(port?: number): void { - const _port = port || 3000; - // console.dir(_port); - + public prepare(): void { this.config.before(this); this.mount(); this.config.after(this); - this.app.use(function (ctx, next) { + // never see it + this.app.use(function (ctx) { ctx.body = 'default'; }); + } + + public callback(): void { + this.prepare(); + + return this.app.callback(); + } + + /** + * Start @tomrpc/core server with port + */ + public start(port?: number): void { + // make app ready + this.prepare(); - this.app.listen(_port, (err) => { + const _port = port || 3000; + return this.app.listen(_port, (err) => { if (err) { console.error(err); } else { From 0997e803c5ab8cd1f42908d1e0b01eac883d3c31 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 18:04:28 +0800 Subject: [PATCH 063/101] chore: add test --- packages/core/src/__tests__/index.test.ts | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/packages/core/src/__tests__/index.test.ts b/packages/core/src/__tests__/index.test.ts index 42184d9..e050be5 100644 --- a/packages/core/src/__tests__/index.test.ts +++ b/packages/core/src/__tests__/index.test.ts @@ -3,9 +3,7 @@ import { describe, expect, it, beforeAll } from 'vitest'; import { TestProxy, TestProxy2 } from '../../proxy'; import { createServer } from '../index'; -// import { RpcServer } from './src/server'; -// const rpc = new RpcServer({}); const rpc = createServer({ fn: { // prefix: '/apk2', @@ -15,19 +13,6 @@ const rpc = createServer({ rpc.fn('/a', function (a) { return { a: a }; }); -// import mount from '../mount'; - -// beforeAll(async () => { -// // called once before all tests run -// await startMocking(); - -// // clean up function, called once after all tests run -// return async () => { -// await stopMocking(); -// }; -// }); - -rpc.prepare(); const request = supertest(rpc.callback()); From 3b1ea0b5d00e7685f7165a5e093ec5f7f12f3af9 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 18:05:17 +0800 Subject: [PATCH 064/101] chore: add test --- packages/core/src/__tests__/index.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/__tests__/index.test.ts b/packages/core/src/__tests__/index.test.ts index e050be5..f81ecb0 100644 --- a/packages/core/src/__tests__/index.test.ts +++ b/packages/core/src/__tests__/index.test.ts @@ -1,7 +1,7 @@ import supertest from 'supertest'; -import { describe, expect, it, beforeAll } from 'vitest'; +import { describe, expect, it } from 'vitest'; -import { TestProxy, TestProxy2 } from '../../proxy'; +// import { TestProxy, TestProxy2 } from '../../proxy'; import { createServer } from '../index'; const rpc = createServer({ From 97f84007843334096add18e6e3820aedc48cbbc5 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 21:15:54 +0800 Subject: [PATCH 065/101] chore: add test --- packages/core/proxy.ts | 2 +- packages/core/src/__tests__/app.test.ts | 26 ++++++++++++++++++ packages/core/src/__tests__/index.test.ts | 31 +++++---------------- packages/core/src/__tests__/proxy.test.ts | 33 +++++++++++++++++++++++ 4 files changed, 67 insertions(+), 25 deletions(-) create mode 100644 packages/core/src/__tests__/app.test.ts create mode 100644 packages/core/src/__tests__/proxy.test.ts diff --git a/packages/core/proxy.ts b/packages/core/proxy.ts index c1e7584..8194f7e 100644 --- a/packages/core/proxy.ts +++ b/packages/core/proxy.ts @@ -23,7 +23,7 @@ export class TestProxy2 extends Proxy { } proxy() { return async (ctx, next) => { - console.dir('TestProxy process child' + ctx.path); + console.dir('TestProxy2 process child' + ctx.path); await next(); }; } diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts new file mode 100644 index 0000000..ec319ea --- /dev/null +++ b/packages/core/src/__tests__/app.test.ts @@ -0,0 +1,26 @@ +import supertest from 'supertest'; +import { describe, expect, it } from 'vitest'; + +// import { TestProxy, TestProxy2 } from '../../proxy'; +import { createServer } from '../index'; + +describe('app', async () => { + const rpc = createServer({ + fn: { + // prefix: '/apk2', + }, + }); + + rpc.fn('/a', function (a) { + return { a: a }; + }); + + const request = supertest(rpc.callback()); + + it('should first app', async () => { + const res = await request.get('/api/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); +}); diff --git a/packages/core/src/__tests__/index.test.ts b/packages/core/src/__tests__/index.test.ts index f81ecb0..6c3b7a6 100644 --- a/packages/core/src/__tests__/index.test.ts +++ b/packages/core/src/__tests__/index.test.ts @@ -1,30 +1,13 @@ -import supertest from 'supertest'; -import { describe, expect, it } from 'vitest'; - -// import { TestProxy, TestProxy2 } from '../../proxy'; -import { createServer } from '../index'; - -const rpc = createServer({ - fn: { - // prefix: '/apk2', - }, -}); - -rpc.fn('/a', function (a) { - return { a: a }; -}); - -const request = supertest(rpc.callback()); +import { describe, expect, it, vi } from 'vitest'; describe('app', async () => { - it('should first app', async () => { - const res = await request.get('/api/a?$p=["hello"]'); - expect(res.type).toEqual('application/json'); - expect(res.status).toEqual(200); - expect(res.body).toEqual({ a: 'hello' }); - }); - it('should render lib', () => { expect('lib').toBe('lib'); }); + + it('mock console.dir', () => { + const spy = vi.spyOn(console, 'dir'); + console.dir('2323'); + expect(spy).toHaveBeenCalled(); + }); }); diff --git a/packages/core/src/__tests__/proxy.test.ts b/packages/core/src/__tests__/proxy.test.ts new file mode 100644 index 0000000..5455fed --- /dev/null +++ b/packages/core/src/__tests__/proxy.test.ts @@ -0,0 +1,33 @@ +import supertest from 'supertest'; +import { describe, expect, it, vi } from 'vitest'; + +import { TestProxy, TestProxy2 } from '../../proxy'; +import { createServer } from '../index'; + +describe('proxy', async () => { + const rpc = createServer({ + fn: { + // prefix: '/apk2', + }, + }); + + rpc.fn('/a', function (a) { + return { a: a }; + }); + + const tp = new TestProxy({}); + + rpc.plugin(tp); + + const request = supertest(rpc.callback()); + + it('should first app', async () => { + const spy = vi.spyOn(console, 'dir'); + const res = await request.get('/api/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + + expect(spy).toHaveBeenCalled(); + }); +}); From a99a6a8ff04e47233517c0c1c75846bb6e9518d8 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 21:21:14 +0800 Subject: [PATCH 066/101] chore: add test --- packages/core/README.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/packages/core/README.md b/packages/core/README.md index df4d324..ce7a121 100644 --- a/packages/core/README.md +++ b/packages/core/README.md @@ -16,10 +16,8 @@ const rpc = createServer({ import { createServer } from '@tomrpc/core'; const rpc = createServer({ - beforeOne: function (ctx: any, key: string) { - console.log(ctx.path); - console.log(ctx.method); - console.log('beforeOne key=' + key); + fn: { + prefix: '/apk', }, }); From 37b483a3c20aba6a3277363e8c01d417b1dcaa0e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 28 Nov 2023 21:35:21 +0800 Subject: [PATCH 067/101] chore: add test --- packages/core/src/proxy.ts | 5 +++-- packages/core/src/utils.ts | 2 ++ 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/core/src/proxy.ts b/packages/core/src/proxy.ts index 314572a..b396df4 100644 --- a/packages/core/src/proxy.ts +++ b/packages/core/src/proxy.ts @@ -1,7 +1,8 @@ import debug from 'debug'; import { Plugable, Strategy } from './plugin'; -import { isArrowFunction, getHttpMethods, mergeDeep } from './utils'; +import { mergeDeep } from './utils'; +import type { JSONValue } from './utils'; const log = debug('@tomrpc/core/fn'); const ProxyDefaultConfig = { @@ -14,7 +15,7 @@ const ProxyDefaultConfig = { export class Proxy extends Plugable implements Strategy { public inject; - constructor(cfg?: any) { + constructor(cfg?: JSONValue) { super(mergeDeep(ProxyDefaultConfig, cfg)); //this.app.use(this.compose([this.before(), this.mount(), this.default()])); } diff --git a/packages/core/src/utils.ts b/packages/core/src/utils.ts index c2da1b2..8221243 100644 --- a/packages/core/src/utils.ts +++ b/packages/core/src/utils.ts @@ -79,3 +79,5 @@ export function mergeDeep(target, ...sources) { return mergeDeep(target, ...sources); } + +export type JSONValue = string | number | boolean | { [x: string]: JSONValue } | Array; From ec3b64928aecae92b0bf472ae24831a370c0cb87 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 11:58:23 +0800 Subject: [PATCH 068/101] chore: refact --- packages/core/src/index.ts | 11 +++---- packages/core/src/plugin.ts | 16 +++++++--- packages/core/src/proxy.ts | 1 - packages/core/src/server.ts | 64 +++++++++++++------------------------ 4 files changed, 38 insertions(+), 54 deletions(-) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index ba2b7b4..4fcf6db 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,3 +1,4 @@ +import debug from 'debug'; import compose from 'koa-compose'; import { Fn } from './fn'; @@ -10,14 +11,12 @@ export * from './fn'; export * from './server'; export * from './utils'; +const log = debug('@tomrpc/core/index'); export const combine = compose; export function createServer(cfg?: any) { const rpc = new RpcServer(mergeDeep({ fn: {} }, cfg)); - const fn = new Fn(mergeDeep({}, cfg.fn)); - // console.dir('createServer'); - rpc.plugin(fn); return mergeDeep(rpc, { @@ -26,14 +25,12 @@ export function createServer(cfg?: any) { before: rpc['config']['hooks']['before'], load: rpc['config']['hooks']['load'], after: rpc['config']['hooks']['after'], - dump: function () { - console.dir('dump'); - }, fn: function (key, fun) { + log('use rpc.fn add fn =' + key); fn.fn(key, fun); - // console.dir(fn); }, add: function (items) { + log('use rpc.add add fn =' + items); fn.add(items); }, }); diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index 72b038d..f7d8ad1 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -9,7 +9,7 @@ const log = debug('@tomrpc/core/plugin'); * The Strategy interface declares operations common to all supported versions * of some algorithm. * - * The Context uses this interface to call the algorithm defined by Concrete + * The Server uses this interface to call the algorithm defined by Concrete * Strategies. */ export declare interface Strategy { @@ -53,16 +53,20 @@ export class Plugable implements Strategy { this.compose = compose; - // TODO: 此处最好改成mount + // load can before mount this.load.push(this.getMiddleware()); } - + /** + * ? + */ getConfig(ctx) { return ctx[this.name]; } - + /** + * move middleware to load stage, use template pattern & compose + */ getMiddleware() { - // console.dir('getMiddleware'); + log('getMiddleware'); const pre = this.pre(); const process = this.process(); const post = this.post(); @@ -76,6 +80,7 @@ export class Plugable implements Strategy { log('pre end'); }; } + post() { return async (ctx, next) => { log('after'); @@ -83,6 +88,7 @@ export class Plugable implements Strategy { log('after end'); }; } + process() { return async (ctx, next) => { log('process default'); diff --git a/packages/core/src/proxy.ts b/packages/core/src/proxy.ts index b396df4..0779d9c 100644 --- a/packages/core/src/proxy.ts +++ b/packages/core/src/proxy.ts @@ -17,7 +17,6 @@ export class Proxy extends Plugable implements Strategy { constructor(cfg?: JSONValue) { super(mergeDeep(ProxyDefaultConfig, cfg)); - //this.app.use(this.compose([this.before(), this.mount(), this.default()])); } proxy() { diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 2caa50b..58eda6f 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -52,12 +52,12 @@ export const LifeCycleConfig = { }, }; +/** + * @type {RpcServer} The Server maintains a server to bind one of the Strategy + * objects. The Server does not know the concrete class of a strategy. It + * should work with all strategies via the Strategy interface. + */ export class RpcServer { - /** - * @type {Strategy} The Context maintains a reference to one of the Strategy - * objects. The Context does not know the concrete class of a strategy. It - * should work with all strategies via the Strategy interface. - */ private plugins: Strategy[] = []; app; use; @@ -70,7 +70,7 @@ export class RpcServer { init: []; load: []; /** - * Usually, the Context accepts a strategy through the constructor, but also + * Usually, the Server accepts a strategy through the constructor, but also * provides a setter to change it at runtime. */ constructor(cfg) { @@ -82,15 +82,14 @@ export class RpcServer { } /** - * Usually, the Context allows replacing a Strategy object at runtime. + * Usually, the Server allows replacing a Strategy object at runtime. */ public plugin(strategy: Strategy) { this.plugins.push(strategy); } public mount() { - // console.dir('mount'); - + log('mount'); const cfg = {}; // setting for (const plugin of this.plugins) { @@ -101,34 +100,22 @@ export class RpcServer { if (plugin.name === 'base') { log('plugin name 没有修改,可能会出现serverConfig获取问题,请关注'); } - // console.log('mount plugin.config'); - // console.log(plugin); - // console.log(plugin.config); - // console.log(plugin.config.bind); - for (const bindnName in plugin.config.bind) { - // console.dir(bindnName); - // this[bindnName] = plugin.config['bind'][bindnName]; - } this.config[plugin.name] = plugin.config; cfg[plugin.name] = plugin; } - this.app.use(async (ctx, next) => { - // ; - for (const fn in cfg) { - // console.log('--' + fn); - ctx[fn] = cfg[fn]; - } + // this.app.use(async (ctx, next) => { + // for (const fn in cfg) { + // // console.log('--' + fn); + // ctx[fn] = cfg[fn]; + // } - await next(); - }); + // await next(); + // }); // proxy for (const plugin of this.plugins) { - // console.dir('init proxy stage'); - // console.dir(plugin); - if (plugin.config.proxy) { if (plugin.config.proxy.inject === 'init') { log('plugin.config.proxy.inject init'); @@ -154,7 +141,6 @@ export class RpcServer { for (const plugin of this.plugins) { log('init stage'); if (plugin.init.length > 0) this.config.hooks.init.push(...plugin.init); - // console.dir(this.config.hooks.init); } // use inits middleware @@ -165,10 +151,6 @@ export class RpcServer { for (const plugin of this.plugins) { log('load stage'); if (plugin.load.length > 0) this.config.hooks.load.push(...plugin.load); - // console.dir('load plugin'); - // console.dir(plugin.load); - // console.dir('load end plugin'); - // console.dir(this.config.hooks.init); } // use loads middleware @@ -183,28 +165,26 @@ export class RpcServer { const app = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); log(plugin.prefix); this.app.use(compose([...mw, app])); - - // console.dir(plugin.prefix === ''); - // console.dir(mw); } // 兜底的else log('兜底的else'); this.app.use(this.config.hooks.default); - // this.app.use(async (ctx, next) => { - // console.dir(ctx.path); - // ctx.body = { 23: 23 }; - // }); } /** * make app ready, add before hook & mount & after hook */ - public prepare(): void { + private prepare(): void { + log('prepare'); + + // before this.config.before(this); + // mount plugin with strategy this.mount(); + // after this.config.after(this); // never see it @@ -214,6 +194,7 @@ export class RpcServer { } public callback(): void { + log('callback'); this.prepare(); return this.app.callback(); @@ -223,6 +204,7 @@ export class RpcServer { * Start @tomrpc/core server with port */ public start(port?: number): void { + log('start'); // make app ready this.prepare(); From 28494b3acca364421a2f6285ca748d3ab2eb3563 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 12:05:26 +0800 Subject: [PATCH 069/101] chore: refact --- packages/core/src/index.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 4fcf6db..b85f6e0 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -14,6 +14,19 @@ export * from './utils'; const log = debug('@tomrpc/core/index'); export const combine = compose; +interface IConfig { + name: string | 'tomapp'; + base?: string; + port?: number | 3000; + debug?: boolean | false; + mount?: string; + buildin: { + // serve?: IServe; + // cors?: ICors; + // view?: IView; + // jwt?: IJwt; + }; +} export function createServer(cfg?: any) { const rpc = new RpcServer(mergeDeep({ fn: {} }, cfg)); const fn = new Fn(mergeDeep({}, cfg.fn)); From f0d299128df1dfdb709e834bb2e014fe0e6d6d8f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 15:02:16 +0800 Subject: [PATCH 070/101] chore: refact --- packages/core/src/server.ts | 42 ++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 58eda6f..c3176b5 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -1,5 +1,5 @@ import { bodyParser } from '@koa/bodyparser'; -import Koa from 'koa'; +import Koa, { Middleware } from 'koa'; import compose from 'koa-compose'; import mount from 'koa-mount'; @@ -19,39 +19,53 @@ export const LifeCycleConfig = { }, }, - before: async (server) => { + before: async (server: RpcServer) => { const app = server.app; const loadMiddlewares = server.config.hooks.before; - loadMiddlewares.forEach((mw) => { + loadMiddlewares.forEach((mw: Middleware) => { app.use(mw); }); }, - init: async (server) => { + init: async (server: RpcServer) => { log('init'); // console.dir(server); const app = server.app; const loadMiddlewares = server.config.hooks.init; - loadMiddlewares.forEach((mw) => { + loadMiddlewares.forEach((mw: Middleware) => { // console.dir(mw); app.use(mw); }); }, - load: async (server) => { + load: async (server: RpcServer) => { const app = server.app; const loadMiddlewares = server.config.hooks.load; - loadMiddlewares.forEach((mw) => { + loadMiddlewares.forEach((mw: Middleware) => { app.use(mw); }); }, - after: async (server) => { + after: async (server: RpcServer) => { const app = server.app; const loadMiddlewares = server.config.hooks.after; - loadMiddlewares.forEach((mw) => { + loadMiddlewares.forEach((mw: Middleware) => { app.use(mw); }); }, }; +interface IConfig { + name: string | 'tomapp'; + hooks?: { + init: Array; + before: Array; + load: Array; + after: Array; + default(): Promise; + }; + before?(server: RpcServer): Promise; + init?(server: RpcServer): Promise; + load?(server: RpcServer): Promise; + after?(server: RpcServer): Promise; +} /** * @type {RpcServer} The Server maintains a server to bind one of the Strategy * objects. The Server does not know the concrete class of a strategy. It @@ -73,7 +87,7 @@ export class RpcServer { * Usually, the Server accepts a strategy through the constructor, but also * provides a setter to change it at runtime. */ - constructor(cfg) { + constructor(cfg?: IConfig) { // init this.config = mergeDeep(LifeCycleConfig, cfg); this.app = new Koa(); @@ -84,11 +98,11 @@ export class RpcServer { /** * Usually, the Server allows replacing a Strategy object at runtime. */ - public plugin(strategy: Strategy) { + public plugin(strategy: Strategy): void { this.plugins.push(strategy); } - public mount() { + public mount(): void { log('mount'); const cfg = {}; // setting @@ -188,7 +202,7 @@ export class RpcServer { this.config.after(this); // never see it - this.app.use(function (ctx) { + this.app.use(function (ctx: Koa.BaseContext) { ctx.body = 'default'; }); } @@ -209,7 +223,7 @@ export class RpcServer { this.prepare(); const _port = port || 3000; - return this.app.listen(_port, (err) => { + return this.app.listen(_port, (err: Error) => { if (err) { console.error(err); } else { From 6eca0eed294e3664803041ee9a58a58e2dfc2585 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 15:23:16 +0800 Subject: [PATCH 071/101] chore: refact --- packages/core/src/server.ts | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index c3176b5..dfdd1f7 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -1,5 +1,6 @@ import { bodyParser } from '@koa/bodyparser'; import Koa, { Middleware } from 'koa'; +import Application from 'koa'; import compose from 'koa-compose'; import mount from 'koa-mount'; @@ -73,7 +74,7 @@ interface IConfig { */ export class RpcServer { private plugins: Strategy[] = []; - app; + app: Application; use; proxy = { init: [], @@ -189,7 +190,7 @@ export class RpcServer { /** * make app ready, add before hook & mount & after hook */ - private prepare(): void { + private prepare() { log('prepare'); // before @@ -207,7 +208,7 @@ export class RpcServer { }); } - public callback(): void { + public callback() { log('callback'); this.prepare(); @@ -217,18 +218,14 @@ export class RpcServer { /** * Start @tomrpc/core server with port */ - public start(port?: number): void { + public start(port?: number) { log('start'); // make app ready this.prepare(); const _port = port || 3000; - return this.app.listen(_port, (err: Error) => { - if (err) { - console.error(err); - } else { - console.log('@tomrpc/core listening on ' + _port); - } + return this.app.listen(_port, (): void => { + console.log('@tomrpc/core listening on ' + _port); }); } } From 1526571359c5ae62d046f3ffffdb75894e0f623e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 17:05:49 +0800 Subject: [PATCH 072/101] chore: refact --- packages/core/src/__tests__/fn.test.ts | 56 ++++++++++++++++++++++++++ packages/core/src/fn.ts | 23 ++++++++--- packages/core/src/index.ts | 22 ++++------ packages/core/src/server.ts | 8 ++-- 4 files changed, 85 insertions(+), 24 deletions(-) create mode 100644 packages/core/src/__tests__/fn.test.ts diff --git a/packages/core/src/__tests__/fn.test.ts b/packages/core/src/__tests__/fn.test.ts new file mode 100644 index 0000000..1740c39 --- /dev/null +++ b/packages/core/src/__tests__/fn.test.ts @@ -0,0 +1,56 @@ +import supertest from 'supertest'; +import { describe, expect, it } from 'vitest'; + +// import { TestProxy, TestProxy2 } from '../../proxy'; +import { Fn } from '../index'; + +describe('app', async () => { + // const rpc = createServer({ + // fn: { + // // prefix: '/apk2', + // }, + // }); + + // rpc.fn('/a', function (a) { + // return { a: a }; + // }); + + // const request = supertest(rpc.callback()); + + it('init default', async () => { + const fn = new Fn(); + expect(fn.name).toEqual('Fn'); + expect(fn.config.prefix).toEqual('/api'); + }); + + it('should config prefix', async () => { + const fn = new Fn({ prefix: '/apk' }); + expect(fn.config.prefix).toEqual('/apk'); + }); + + it('use fn add a function', async () => { + const fn = new Fn({ prefix: '/apk' }); + + fn.fn('/a', function (a) { + return { a: a }; + }); + const count = Object.keys(fn.config['functions']).length; + expect(1).to.equal(count); + }); + + it('use add method add a function', async () => { + const fn = new Fn({ prefix: '/apk' }); + + fn.add({ + c: (a: string) => { + return a; + }, + a: function (a: string, b: string) { + return `${this.path} , ${a} c2 ${b}`; + }, + }); + + const count = Object.keys(fn.config['functions']).length; + expect(2).to.equal(count); + }); +}); diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index d7612d6..287f657 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -1,17 +1,28 @@ import debug from 'debug'; import { Plugable } from './plugin'; -import { isArrowFunction, getHttpMethods } from './utils'; +import { mergeDeep, isArrowFunction, getHttpMethods } from './utils'; const log = debug('@tomrpc/core/fn'); +export interface IFnConfig { + name?: string; + prefix?: string; +} + export class Fn extends Plugable { - constructor(cfg?: any) { - super(cfg); + constructor(cfg?: IFnConfig) { + super( + mergeDeep( + { + prefix: '/api', + functions: [], + }, + cfg + ) + ); this.name = 'Fn'; - if (this.prefix === '') { - this.prefix = '/api'; - } + this.prefix = this.config.prefix; this.app.use(this.compose([this.before(), this.mount(), this.default()])); } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index b85f6e0..403ff8d 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,8 +1,8 @@ import debug from 'debug'; import compose from 'koa-compose'; -import { Fn } from './fn'; -import { RpcServer } from './server'; +import { Fn, IFnConfig } from './fn'; +import { RpcServer, IRpcServerConfig } from './server'; import { mergeDeep } from './utils'; export * from './plugin'; @@ -14,20 +14,14 @@ export * from './utils'; const log = debug('@tomrpc/core/index'); export const combine = compose; -interface IConfig { - name: string | 'tomapp'; +interface IServerConfig { base?: string; - port?: number | 3000; - debug?: boolean | false; - mount?: string; - buildin: { - // serve?: IServe; - // cors?: ICors; - // view?: IView; - // jwt?: IJwt; - }; + fn?: IFnConfig; } -export function createServer(cfg?: any) { + +type IIndexServerConfig = IRpcServerConfig & IServerConfig; + +export function createServer(cfg?: IIndexServerConfig) { const rpc = new RpcServer(mergeDeep({ fn: {} }, cfg)); const fn = new Fn(mergeDeep({}, cfg.fn)); rpc.plugin(fn); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index dfdd1f7..7916e6b 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -53,8 +53,8 @@ export const LifeCycleConfig = { }, }; -interface IConfig { - name: string | 'tomapp'; +export interface IRpcServerConfig { + name?: string | 'tomapp'; hooks?: { init: Array; before: Array; @@ -88,7 +88,7 @@ export class RpcServer { * Usually, the Server accepts a strategy through the constructor, but also * provides a setter to change it at runtime. */ - constructor(cfg?: IConfig) { + constructor(cfg?: IRpcServerConfig) { // init this.config = mergeDeep(LifeCycleConfig, cfg); this.app = new Koa(); @@ -178,7 +178,7 @@ export class RpcServer { const mw = this.proxy.before[plugin.name.toLowerCase()] || []; const app = plugin.prefix === '' ? mount(plugin.app) : mount(plugin.prefix, plugin.app); - log(plugin.prefix); + // log(plugin.config.prefix); this.app.use(compose([...mw, app])); } From b38abb1c7b7c73b4731fca98f4906f3ca029cec1 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 19:44:40 +0800 Subject: [PATCH 073/101] chore: refact --- packages/core/src/__tests__/app.test.ts | 26 +++++++++++++++++++++++- packages/core/src/__tests__/fn.test.ts | 27 ++++++++++++++----------- 2 files changed, 40 insertions(+), 13 deletions(-) diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index ec319ea..05e2340 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -15,12 +15,36 @@ describe('app', async () => { return { a: a }; }); + rpc.fn('/b', function (a) { + if (this.method === 'POST') { + return { a: a, method: 'post' }; + } + if (this.method === 'GET') { + return { a: a, method: 'get' }; + } + }); + const request = supertest(rpc.callback()); - it('should first app', async () => { + it('should acess /a', async () => { const res = await request.get('/api/a?$p=["hello"]'); expect(res.type).toEqual('application/json'); expect(res.status).toEqual(200); expect(res.body).toEqual({ a: 'hello' }); }); + + it('should acess GET /b', async () => { + const res = await request.get('/api/b?$p=["hello1"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello1', method: 'get' }); + }); + + it('should acess POST /b', async () => { + const res = await request.post('/api/b').send(['hello']).set('Accept', 'application/json'); + + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello', method: 'post' }); + }); }); diff --git a/packages/core/src/__tests__/fn.test.ts b/packages/core/src/__tests__/fn.test.ts index 1740c39..ab57a9a 100644 --- a/packages/core/src/__tests__/fn.test.ts +++ b/packages/core/src/__tests__/fn.test.ts @@ -5,18 +5,6 @@ import { describe, expect, it } from 'vitest'; import { Fn } from '../index'; describe('app', async () => { - // const rpc = createServer({ - // fn: { - // // prefix: '/apk2', - // }, - // }); - - // rpc.fn('/a', function (a) { - // return { a: a }; - // }); - - // const request = supertest(rpc.callback()); - it('init default', async () => { const fn = new Fn(); expect(fn.name).toEqual('Fn'); @@ -53,4 +41,19 @@ describe('app', async () => { const count = Object.keys(fn.config['functions']).length; expect(2).to.equal(count); }); + + it('use fn add a function', async () => { + const fn = new Fn({ prefix: '/apk' }); + + fn.fn('/a', function (a) { + return { a: a }; + }); + + const request = supertest(fn.app.callback()); + + const res = await request.get('/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); }); From 990e3801bce1e7aae8f5a670e8210b4183bb75c4 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 19:47:20 +0800 Subject: [PATCH 074/101] chore: refact --- packages/core/src/fn.ts | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index 287f657..ca232c7 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -44,7 +44,6 @@ export class Fn extends Plugable { log(`add ${name}: ${fn}`); console.log(`this.rpcFunctions[${name}] exisit`); } - // this.rpcFunctions[name] = fn; this.fn(name, fn); } } @@ -94,7 +93,7 @@ export class Fn extends Plugable { } before() { return async (ctx, next) => { - log('pre'); + log('before'); const key = ctx.path.replace('/', '').split('/').join('.'); const lastKey = key.split('.').pop(); @@ -103,18 +102,15 @@ export class Fn extends Plugable { const supportMethods = []; httpMethods.forEach(function (m) { if (lastKey.indexOf(m) != -1) { - // console.log(m); + log(m); supportMethods.push(m); return m; } }); - // console.log(supportMethods); if (supportMethods.length === 0) { - // if (ctx.path.indexOf(this.prefix) != -1) { log(ctx.path + ',没有匹配到包含get/post等开头的函数'); await next(); - // } } else if (ctx.method === supportMethods[0]) { log('匹配到包含get/post等方法的函数'); await next(); @@ -127,7 +123,7 @@ export class Fn extends Plugable { supportMethods[0] + ' request from client'; } - // log('beforeOne end'); + log('beforeOne end'); }; } } From 45e8df613c02f6603486249cf433afee50026ff4 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 19:54:49 +0800 Subject: [PATCH 075/101] chore: refact --- packages/core/src/__tests__/app.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index 05e2340..f9fcdb0 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -24,6 +24,14 @@ describe('app', async () => { } }); + rpc.fn('com.yourcompony.a', function (a: string) { + return { a: a }; + }); + + rpc.fn('com.yourcompony.b', function (a: string) { + return `${this.path} , ${a} `; + }); + const request = supertest(rpc.callback()); it('should acess /a', async () => { @@ -47,4 +55,11 @@ describe('app', async () => { expect(res.status).toEqual(200); expect(res.body).toEqual({ a: 'hello', method: 'post' }); }); + + it('should acess com.yourcompony.b', async () => { + const res = await request.get('/api/com/yourcompony/b?$p=["hello"]'); + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('/com/yourcompony/b , hello '); + }); }); From 802aa73fabe5a5591b020cbdc035c415557c442e Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 22:38:34 +0800 Subject: [PATCH 076/101] chore: refact --- packages/core/src/__tests__/app.test.ts | 1 - packages/core/src/__tests__/proxy.test.ts | 48 +++++++++++++++++------ 2 files changed, 37 insertions(+), 12 deletions(-) diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index f9fcdb0..23ce06c 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -1,7 +1,6 @@ import supertest from 'supertest'; import { describe, expect, it } from 'vitest'; -// import { TestProxy, TestProxy2 } from '../../proxy'; import { createServer } from '../index'; describe('app', async () => { diff --git a/packages/core/src/__tests__/proxy.test.ts b/packages/core/src/__tests__/proxy.test.ts index 5455fed..82d7d6a 100644 --- a/packages/core/src/__tests__/proxy.test.ts +++ b/packages/core/src/__tests__/proxy.test.ts @@ -5,23 +5,49 @@ import { TestProxy, TestProxy2 } from '../../proxy'; import { createServer } from '../index'; describe('proxy', async () => { - const rpc = createServer({ - fn: { - // prefix: '/apk2', - }, - }); + it('should enable proxy1', async () => { + const rpc = createServer({ + fn: { + // prefix: '/apk2', + }, + }); + + rpc.fn('/a', function (a) { + return { a: a }; + }); + + const tp = new TestProxy({}); + + rpc.plugin(tp); + + const request = supertest(rpc.callback()); + + const spy = vi.spyOn(console, 'dir'); + const res = await request.get('/api/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); - rpc.fn('/a', function (a) { - return { a: a }; + expect(spy).toHaveBeenCalled(); }); - const tp = new TestProxy({}); + it('should enable proxy2', async () => { + const rpc = createServer({ + fn: { + // prefix: '/apk2', + }, + }); + + rpc.fn('/a', function (a) { + return { a: a }; + }); + + const tp = new TestProxy2({}); - rpc.plugin(tp); + rpc.plugin(tp); - const request = supertest(rpc.callback()); + const request = supertest(rpc.callback()); - it('should first app', async () => { const spy = vi.spyOn(console, 'dir'); const res = await request.get('/api/a?$p=["hello"]'); expect(res.type).toEqual('application/json'); From 8690af9145bcebe31b2c8d83e3eeff19e2f02d0b Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 22:39:10 +0800 Subject: [PATCH 077/101] chore: refact --- packages/core/src/__tests__/app.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index 23ce06c..f82d473 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -33,21 +33,21 @@ describe('app', async () => { const request = supertest(rpc.callback()); - it('should acess /a', async () => { + it('should access /a', async () => { const res = await request.get('/api/a?$p=["hello"]'); expect(res.type).toEqual('application/json'); expect(res.status).toEqual(200); expect(res.body).toEqual({ a: 'hello' }); }); - it('should acess GET /b', async () => { + it('should access GET /b', async () => { const res = await request.get('/api/b?$p=["hello1"]'); expect(res.type).toEqual('application/json'); expect(res.status).toEqual(200); expect(res.body).toEqual({ a: 'hello1', method: 'get' }); }); - it('should acess POST /b', async () => { + it('should access POST /b', async () => { const res = await request.post('/api/b').send(['hello']).set('Accept', 'application/json'); expect(res.type).toEqual('application/json'); @@ -55,7 +55,7 @@ describe('app', async () => { expect(res.body).toEqual({ a: 'hello', method: 'post' }); }); - it('should acess com.yourcompony.b', async () => { + it('should access com.yourcompony.b', async () => { const res = await request.get('/api/com/yourcompony/b?$p=["hello"]'); expect(res.type).toEqual('text/plain'); expect(res.status).toEqual(200); From b8ad612a6c2c122ed00797d0add42ac0c1b3b0e0 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 22:41:35 +0800 Subject: [PATCH 078/101] chore: refact --- packages/core/src/__tests__/app.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index f82d473..e156314 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -23,11 +23,11 @@ describe('app', async () => { } }); - rpc.fn('com.yourcompony.a', function (a: string) { + rpc.fn('com.yourcompany.a', function (a: string) { return { a: a }; }); - rpc.fn('com.yourcompony.b', function (a: string) { + rpc.fn('com.yourcompany.b', function (a: string) { return `${this.path} , ${a} `; }); @@ -55,10 +55,10 @@ describe('app', async () => { expect(res.body).toEqual({ a: 'hello', method: 'post' }); }); - it('should access com.yourcompony.b', async () => { - const res = await request.get('/api/com/yourcompony/b?$p=["hello"]'); + it('should access com.yourcompany.b', async () => { + const res = await request.get('/api/com/yourcompany/b?$p=["hello"]'); expect(res.type).toEqual('text/plain'); expect(res.status).toEqual(200); - expect(res.text).toEqual('/com/yourcompony/b , hello '); + expect(res.text).toEqual('/com/yourcompany/b , hello '); }); }); From b041871f37ae1c3692a079f4f09a5fd9fccab5d2 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 22:42:53 +0800 Subject: [PATCH 079/101] chore: refact --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 378ee5d..54d8fcf 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ console.dir(res); this === koa ctx ```js -rpc.fn('com.yourcompony.a', function (a: string) { +rpc.fn('com.yourcompany.a', function (a: string) { return return `${this.path} , ${a} `; }); ``` @@ -89,7 +89,7 @@ rpc.fn('com.yourcompony.a', function (a: string) { server ```js -rpc.fn('com.yourcompony.a', function (a: string) { +rpc.fn('com.yourcompany.a', function (a: string) { if (this.method === 'post'){ return return `${this.path} , ${a} `; } @@ -104,7 +104,7 @@ import { createClient } from '@tomrpc/client'; const client = createClient({ host: '127.0.0.1', port: 3000, - namespace: 'com.yourcompony', + namespace: 'com.yourcompany', methodFilter: function (lastKey: string) { if (lastKey === 'a') { return 'post'; From 73a0f551400f5619d7046afd103b8222b8f95fa3 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Wed, 29 Nov 2023 23:05:47 +0800 Subject: [PATCH 080/101] chore: refact --- packages/core/src/__tests__/proxy.test.ts | 19 ++++++++++++++++++- packages/core/src/proxy.ts | 19 ++++++++++++++----- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/packages/core/src/__tests__/proxy.test.ts b/packages/core/src/__tests__/proxy.test.ts index 82d7d6a..6f08c41 100644 --- a/packages/core/src/__tests__/proxy.test.ts +++ b/packages/core/src/__tests__/proxy.test.ts @@ -1,8 +1,9 @@ +import debug from 'debug'; import supertest from 'supertest'; import { describe, expect, it, vi } from 'vitest'; import { TestProxy, TestProxy2 } from '../../proxy'; -import { createServer } from '../index'; +import { createServer, Proxy } from '../index'; describe('proxy', async () => { it('should enable proxy1', async () => { @@ -56,4 +57,20 @@ describe('proxy', async () => { expect(spy).toHaveBeenCalled(); }); + + it('should enable proxy2', async () => { + const tp = new Proxy({}); + tp.app.use(tp.proxy()); + + tp.app.use(async (ctx) => { + ctx.body = { a: 'a' }; + }); + + const request = supertest(tp.app.callback()); + + const res = await request.get('/'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'a' }); + }); }); diff --git a/packages/core/src/proxy.ts b/packages/core/src/proxy.ts index 0779d9c..9aacc57 100644 --- a/packages/core/src/proxy.ts +++ b/packages/core/src/proxy.ts @@ -1,8 +1,9 @@ import debug from 'debug'; +import Koa from 'koa'; -import { Plugable, Strategy } from './plugin'; +import { Plugable } from './plugin'; import { mergeDeep } from './utils'; -import type { JSONValue } from './utils'; + const log = debug('@tomrpc/core/fn'); const ProxyDefaultConfig = { @@ -12,15 +13,23 @@ const ProxyDefaultConfig = { }, }; -export class Proxy extends Plugable implements Strategy { +export interface IProxyConfig { + name?: string | 'tomapp'; + proxy?: { + inject: 'init' | 'load' | 'before' | 'after'; + before: []; + }; +} + +export class Proxy extends Plugable { public inject; - constructor(cfg?: JSONValue) { + constructor(cfg?: IProxyConfig) { super(mergeDeep(ProxyDefaultConfig, cfg)); } proxy() { - return async (ctx, next) => { + return async (ctx: Koa.BaseContext, next) => { log('proxy default'); await next(); log('proxy default end'); From ec91697d51dece90f95c3327af90ba93f26e3319 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 30 Nov 2023 11:59:49 +0800 Subject: [PATCH 081/101] chore: refact --- packages/core/src/__tests__/app.test.ts | 13 ++++ packages/core/src/__tests__/fn.test.ts | 87 ++++++++++++++++++++++- packages/core/src/__tests__/proxy.test.ts | 40 ++++++++++- packages/core/src/fn.ts | 10 ++- packages/core/src/plugin.ts | 7 +- 5 files changed, 146 insertions(+), 11 deletions(-) diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index e156314..95de2d0 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -31,6 +31,12 @@ describe('app', async () => { return `${this.path} , ${a} `; }); + rpc.add({ + '/add': function (a: string, b: string) { + return { a: a }; + }, + }); + const request = supertest(rpc.callback()); it('should access /a', async () => { @@ -40,6 +46,13 @@ describe('app', async () => { expect(res.body).toEqual({ a: 'hello' }); }); + it('should access /add', async () => { + const res = await request.get('/api/add?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); + it('should access GET /b', async () => { const res = await request.get('/api/b?$p=["hello1"]'); expect(res.type).toEqual('application/json'); diff --git a/packages/core/src/__tests__/fn.test.ts b/packages/core/src/__tests__/fn.test.ts index ab57a9a..5e0df7d 100644 --- a/packages/core/src/__tests__/fn.test.ts +++ b/packages/core/src/__tests__/fn.test.ts @@ -1,5 +1,6 @@ +import Koa from 'koa'; import supertest from 'supertest'; -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; // import { TestProxy, TestProxy2 } from '../../proxy'; import { Fn } from '../index'; @@ -42,6 +43,19 @@ describe('app', async () => { expect(2).to.equal(count); }); + it('use default response', async () => { + const fn = new Fn({ prefix: '/apk' }); + const app = new Koa(); + + app.use(fn.default()); + const request = supertest(app.callback()); + + const res = await request.get('/'); + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('[fn plugin] no fn repsonse, please check your fn if exist'); + }); + it('use fn add a function', async () => { const fn = new Fn({ prefix: '/apk' }); @@ -56,4 +70,75 @@ describe('app', async () => { expect(res.status).toEqual(200); expect(res.body).toEqual({ a: 'hello' }); }); + + // it('use fn add a function', async () => { + // const fn = new Fn({ prefix: '/apk' }); + + // fn.fn('/postAbc', function (a) { + // return { a: a }; + // }); + + // const request = supertest(fn.app.callback()); + + // const res = await request.post('/postAbc').send(['hello']).set('Accept', 'application/json'); + + // console.dir(res); + + // expect(res.type).toEqual('application/json'); + // expect(res.status).toEqual(200); + // expect(res.body).toEqual({ a: 'hello' }); + // }); + + it('use fn add a lock function', async () => { + const fn = new Fn({ prefix: '/apk' }); + + fn.fn('/getAbc', function (a) { + return { a: a }; + }); + fn.fn('/Abclock', function (a) { + return { a: a }; + }); + + const request = supertest(fn.app.callback()); + + const res = await request.get('/Abclock?$p=["hello"]'); + + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('process fn:Abclock , you need send lock request from client'); + }); + + it('use fn add two function with the same path', async () => { + const spy = vi.spyOn(console, 'log'); + const fn = new Fn({ prefix: '/apk' }); + + fn.fn('/a', function (a) { + return { a: a }; + }); + + fn.add({ + '/a': function (a: string, b: string) { + return `${this.path} , ${a} c2 ${b}`; + }, + }); + + expect(spy).toHaveBeenCalled(); + }); + + it('use fn add arrow function', async () => { + const spy = vi.spyOn(console, 'log'); + const fn = new Fn({ prefix: '/apk' }); + + fn.fn('/a', (a) => { + return { a: a }; + }); + + fn.add({ + '/a': (a: string, b: string, ctx) => { + return `${ctx.path} , ${a} c2 ${b}`; + }, + }); + + expect(spy).toHaveBeenCalled(); + }); }); diff --git a/packages/core/src/__tests__/proxy.test.ts b/packages/core/src/__tests__/proxy.test.ts index 6f08c41..5e00487 100644 --- a/packages/core/src/__tests__/proxy.test.ts +++ b/packages/core/src/__tests__/proxy.test.ts @@ -3,7 +3,7 @@ import supertest from 'supertest'; import { describe, expect, it, vi } from 'vitest'; import { TestProxy, TestProxy2 } from '../../proxy'; -import { createServer, Proxy } from '../index'; +import { createServer, Proxy, combine } from '../index'; describe('proxy', async () => { it('should enable proxy1', async () => { @@ -62,7 +62,7 @@ describe('proxy', async () => { const tp = new Proxy({}); tp.app.use(tp.proxy()); - tp.app.use(async (ctx) => { + tp.use(async (ctx) => { ctx.body = { a: 'a' }; }); @@ -73,4 +73,40 @@ describe('proxy', async () => { expect(res.status).toEqual(200); expect(res.body).toEqual({ a: 'a' }); }); + + it('should enable proxy2', async () => { + const tp = new Proxy({}); + // tp.app.use(tp.proxy()); + + tp.addInit(async (ctx) => { + ctx.body = { a: 'a' }; + }); + + tp.app.use(combine(tp.init)); + + const request = supertest(tp.app.callback()); + + const res = await request.get('/'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'a' }); + }); + + it('should enable proxy2', async () => { + const tp = new Proxy({}); + tp.app.use(tp.proxy()); + + tp.addLoad(async (ctx) => { + ctx.body = { a: 'a' }; + }); + + tp.app.use(combine(tp.load)); + + const request = supertest(tp.app.callback()); + + const res = await request.get('/'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'a' }); + }); }); diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index ca232c7..fc9dfc3 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -98,6 +98,8 @@ export class Fn extends Plugable { const lastKey = key.split('.').pop(); const httpMethods = getHttpMethods(); + console.dir('lastKey'); + console.dir(lastKey); const supportMethods = []; httpMethods.forEach(function (m) { @@ -108,11 +110,15 @@ export class Fn extends Plugable { } }); + console.dir('supportMethods'); + console.dir(ctx.method); + console.dir(supportMethods); + if (supportMethods.length === 0) { log(ctx.path + ',没有匹配到包含get/post等开头的函数'); await next(); - } else if (ctx.method === supportMethods[0]) { - log('匹配到包含get/post等方法的函数'); + } else if (ctx.method.toLowerCase() === supportMethods[0]) { + console.log('匹配到包含get/post等方法的函数'); await next(); } else { log('匹配到包含get/post等方法的函数,但method不对'); diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index f7d8ad1..e8abbc8 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -56,12 +56,7 @@ export class Plugable implements Strategy { // load can before mount this.load.push(this.getMiddleware()); } - /** - * ? - */ - getConfig(ctx) { - return ctx[this.name]; - } + /** * move middleware to load stage, use template pattern & compose */ From 24cf95b55322d5562de3dda4e99b493974de7675 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 30 Nov 2023 17:26:05 +0800 Subject: [PATCH 082/101] chore: refact --- packages/core/src/__tests__/app.test.ts | 23 +++++++++++++ packages/core/src/__tests__/fn.test.ts | 12 +++---- packages/core/src/__tests__/utils.test.ts | 39 +++++++++++++++++++++++ packages/core/src/fn.ts | 10 +++--- packages/core/src/server.ts | 1 + packages/core/src/utils.ts | 3 +- 6 files changed, 75 insertions(+), 13 deletions(-) create mode 100644 packages/core/src/__tests__/utils.test.ts diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index 95de2d0..4dbd6f7 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -39,6 +39,14 @@ describe('app', async () => { const request = supertest(rpc.callback()); + it('should start === rpc.callback', async () => { + const request2 = supertest(rpc.start(3000)); + const res = await request2.get('/api/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); + it('should access /a', async () => { const res = await request.get('/api/a?$p=["hello"]'); expect(res.type).toEqual('application/json'); @@ -46,6 +54,21 @@ describe('app', async () => { expect(res.body).toEqual({ a: 'hello' }); }); + it('should access no routers[key]', async () => { + // if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { + const res = await request.get('/api/a123'); + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('not match $p param, no process'); + }); + + it('should access no routers[key]', async () => { + const res = await request.get('/api/a123?$p=["hello"]'); + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('[fn plugin] no fn repsonse, please check your fn if exist'); + }); + it('should access /add', async () => { const res = await request.get('/api/add?$p=["hello"]'); expect(res.type).toEqual('application/json'); diff --git a/packages/core/src/__tests__/fn.test.ts b/packages/core/src/__tests__/fn.test.ts index 5e0df7d..313221e 100644 --- a/packages/core/src/__tests__/fn.test.ts +++ b/packages/core/src/__tests__/fn.test.ts @@ -71,7 +71,7 @@ describe('app', async () => { expect(res.body).toEqual({ a: 'hello' }); }); - // it('use fn add a function', async () => { + // it('use fn add a get function', async () => { // const fn = new Fn({ prefix: '/apk' }); // fn.fn('/postAbc', function (a) { @@ -81,12 +81,10 @@ describe('app', async () => { // const request = supertest(fn.app.callback()); // const res = await request.post('/postAbc').send(['hello']).set('Accept', 'application/json'); - - // console.dir(res); - - // expect(res.type).toEqual('application/json'); + // // console.dir(res); + // expect(res.type).toEqual('text/plain'); // expect(res.status).toEqual(200); - // expect(res.body).toEqual({ a: 'hello' }); + // expect(res.text).toEqual('process fn:Abclock , you need send lock request from client'); // }); it('use fn add a lock function', async () => { @@ -102,7 +100,7 @@ describe('app', async () => { const request = supertest(fn.app.callback()); const res = await request.get('/Abclock?$p=["hello"]'); - + // console.dir(res); expect(res.type).toEqual('text/plain'); expect(res.status).toEqual(200); expect(res.text).toEqual('process fn:Abclock , you need send lock request from client'); diff --git a/packages/core/src/__tests__/utils.test.ts b/packages/core/src/__tests__/utils.test.ts new file mode 100644 index 0000000..78f8c69 --- /dev/null +++ b/packages/core/src/__tests__/utils.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { isArrowFunction, log } from '../index'; + +describe('app', async () => { + it('should render lib', () => { + expect('lib').toBe('lib'); + }); + + it('isArrowFunction = true', () => { + const a = (b) => { + return b; + }; + const result = isArrowFunction(a); + + expect(result).toBe(true); + }); + + it('isArrowFunction = false', () => { + const a = function (b) { + return b; + }; + const result = isArrowFunction(a); + + expect(result).toBe(false); + }); + + it('isArrowFunction = false', () => { + const result = isArrowFunction('a'); + + expect(result).toBe(false); + }); + + it('mock log', () => { + const spy = vi.spyOn(console, 'log'); + log('2323', true); + expect(spy).toHaveBeenCalled(); + }); +}); diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index fc9dfc3..9cfa67a 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -98,8 +98,8 @@ export class Fn extends Plugable { const lastKey = key.split('.').pop(); const httpMethods = getHttpMethods(); - console.dir('lastKey'); - console.dir(lastKey); + // console.dir('lastKey'); + // console.dir(lastKey); const supportMethods = []; httpMethods.forEach(function (m) { @@ -110,9 +110,9 @@ export class Fn extends Plugable { } }); - console.dir('supportMethods'); - console.dir(ctx.method); - console.dir(supportMethods); + // console.dir('supportMethods'); + // console.dir(ctx.method); + // console.dir(supportMethods); if (supportMethods.length === 0) { log(ctx.path + ',没有匹配到包含get/post等开头的函数'); diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 7916e6b..b1793de 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -218,6 +218,7 @@ export class RpcServer { /** * Start @tomrpc/core server with port */ + /* v8 ignore next 3 */ public start(port?: number) { log('start'); // make app ready diff --git a/packages/core/src/utils.ts b/packages/core/src/utils.ts index 8221243..f39d019 100644 --- a/packages/core/src/utils.ts +++ b/packages/core/src/utils.ts @@ -5,8 +5,9 @@ export const isArrowFunction = (func) => { if (typeof func === 'function') { const source = func.toString(); return /^\([^)]*\)\s*=>/.test(source); + } else { + return false; } - return false; }; export function getHttpMethods() { From 56a6e23b0cf88cbda216521e6bd2f4fdc30bfaf0 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 30 Nov 2023 17:29:26 +0800 Subject: [PATCH 083/101] chore: refact --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 017d9cd..b86d391 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,7 +7,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - node: ['18.x'] + node: ['20.x'] os: [ubuntu-latest] steps: From 48810d80891f8a34d519634e7a0e672265d6023c Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 30 Nov 2023 17:33:38 +0800 Subject: [PATCH 084/101] chore: refact --- .github/workflows/ci.yml | 34 ++++++++++++++++++---------------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b86d391..106ebd4 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,24 +1,17 @@ -name: CI -on: [push] +name: Node.js CI + +on: ['push', 'pull_request'] + jobs: build: - name: Build, lint, and test on Node ${{ matrix.node }} and ${{ matrix.os }} - - runs-on: ${{ matrix.os }} - strategy: - matrix: - node: ['20.x'] - os: [ubuntu-latest] + runs-on: ubuntu-latest steps: - - name: Checkout repo - uses: actions/checkout@v2 - - - name: Use Node ${{ matrix.node }} - uses: actions/setup-node@v1 + - uses: actions/checkout@v4 + - name: Use Node.js + uses: actions/setup-node@v3 with: - node-version: ${{ matrix.node }} - + node-version: '20.x' - name: Install PNPM run: npm install -g pnpm @@ -31,5 +24,14 @@ jobs: - name: Test run: npm run test + - name: Coverage + run: npm run coverage + - name: Build run: npm run build + - name: Upload coverage reports to Codecov + uses: codecov/codecov-action@v3 + env: + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + with: + file: ./coverage/lcov.info From 9737a1ec471f0785e9d406ff055523a3ab0f37d0 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Thu, 30 Nov 2023 22:34:54 +0800 Subject: [PATCH 085/101] chore: refact --- packages/app/app.ts | 24 ++++++++++++------------ packages/core/src/__tests__/app.test.ts | 2 +- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index c54b4c1..dbad115 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -13,18 +13,18 @@ import { createApp } from './src/index'; buildin: { serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, cors: { enable: true }, - jwt: { - enable: true, - secret: 'shhhhhh', - debug: true, - getToken: () => { - const token = jwt.sign({ foo: 'bar' }, 'bad'); - console.dir('token'); - console.dir(token); - return token; - }, - unless: { path: ['/view'] }, - }, + // jwt: { + // enable: true, + // secret: 'shhhhhh', + // debug: true, + // getToken: () => { + // const token = jwt.sign({ foo: 'bar' }, 'bad'); + // console.dir('token'); + // console.dir(token); + // return token; + // }, + // unless: { path: ['/view'] }, + // }, view: { enable: true, root: join(import.meta.url, '.', 'view'), diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index 4dbd6f7..b5f9280 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -40,7 +40,7 @@ describe('app', async () => { const request = supertest(rpc.callback()); it('should start === rpc.callback', async () => { - const request2 = supertest(rpc.start(3000)); + const request2 = supertest(rpc.start(30001)); const res = await request2.get('/api/a?$p=["hello"]'); expect(res.type).toEqual('application/json'); expect(res.status).toEqual(200); From ebb29766e2ba08f8926b5067e84b09b7f5b25492 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Fri, 1 Dec 2023 20:49:49 +0800 Subject: [PATCH 086/101] chore: refact --- packages/client/package.json | 2 +- packages/client/src/__tests__/index.test.ts | 65 ++++++++++++++++++++- 2 files changed, 64 insertions(+), 3 deletions(-) diff --git a/packages/client/package.json b/packages/client/package.json index a58917d..17b5c40 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -28,7 +28,7 @@ "devDependencies": { "vitest": "^0.34.6", "@vitest/coverage-v8": "^0.34.6", - "happy-dom": "^6.0.4" + "@tomrpc/core": "workspace:*" }, "dependencies": { "debug": "^4.3.4", diff --git a/packages/client/src/__tests__/index.test.ts b/packages/client/src/__tests__/index.test.ts index 26d095d..1455e9a 100644 --- a/packages/client/src/__tests__/index.test.ts +++ b/packages/client/src/__tests__/index.test.ts @@ -1,9 +1,70 @@ +import { createServer } from '@tomrpc/core'; import { describe, expect, it } from 'vitest'; -import { lib } from '..'; +import { createClient } from '..'; describe('lib', () => { + const rpc = createServer({ + fn: { + // prefix: '/apk2', + }, + }); + + rpc.fn('/a', function (a) { + return { a: a }; + }); + + rpc.fn('/b', function (a) { + if (this.method === 'POST') { + return { a: a, method: 'post' }; + } + if (this.method === 'GET') { + return { a: a, method: 'get' }; + } + }); + + rpc.fn('com.yourcompany.a', function (a: string) { + return { a: a }; + }); + + rpc.fn('com.yourcompany.b', function (a: string) { + return `${this.path} , ${a} `; + }); + + rpc.add({ + '/add': function (a: string, b: string) { + return { a: a }; + }, + }); + + // const request = supertest(rpc.callback()); + + it('should start === rpc.callback', async () => { + rpc.start(30001); + // const res = await request2.get('/api/a?$p=["hello"]'); + // expect(res.type).toEqual('application/json'); + // expect(res.status).toEqual(200); + // expect(res.body).toEqual({ a: 'hello' }); + + const client = createClient({ + host: '127.0.0.1', + port: 30001, + // namespace: 'a', + // methodFilter: function (lastKey: string) { + // if (lastKey === 'a') { + // return 'post'; + // } else { + // return 'get'; + // } + // }, + }); + + // const res1 = await client.a('hello'); + // console.dir(res1); + // const res = await client.postUsers('hello postUsers'); + // console.dir(res); + }); it('should render lib', () => { - expect(lib()).toBe('lib'); + // expect(lib()).toBe('lib'); }); }); From cbdc30695e9994db750f3f1dd306350692c1a4ae Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 4 Dec 2023 20:48:30 +0800 Subject: [PATCH 087/101] chore: refact --- packages/app/src/mw/jwt.ts | 6 +++--- packages/client/package.json | 8 +++++--- packages/client/src/__tests__/index.test.ts | 21 +++++++++++++++++++-- packages/client/src/client.ts | 14 ++++++++++---- packages/client/src/proxy.ts | 2 +- packages/client/test.ts | 6 +++--- 6 files changed, 41 insertions(+), 16 deletions(-) diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index f546867..feb6c93 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -8,7 +8,7 @@ export class Jwt extends Proxy { this.config.proxy.inject = 'before'; this.config.proxy.before = ['fn']; } - proxy() { - return koajwt(this.config).unless({ path: this.config.unless }); - } + // proxy() { + // // return koajwt(this.config).unless({ path: this.config.unless }); + // } } diff --git a/packages/client/package.json b/packages/client/package.json index 17b5c40..821afd4 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -26,12 +26,14 @@ "awesome-keywords" ], "devDependencies": { - "vitest": "^0.34.6", + "@tomrpc/core": "workspace:*", "@vitest/coverage-v8": "^0.34.6", - "@tomrpc/core": "workspace:*" + "vitest": "^0.34.6" }, "dependencies": { "debug": "^4.3.4", - "isomorphic-unfetch": "^4.0.2" + "isomorphic-unfetch": "^4.0.2", + "node-fetch": "^3.3.2", + "ofetch": "^1.3.3" } } \ No newline at end of file diff --git a/packages/client/src/__tests__/index.test.ts b/packages/client/src/__tests__/index.test.ts index 1455e9a..b09868e 100644 --- a/packages/client/src/__tests__/index.test.ts +++ b/packages/client/src/__tests__/index.test.ts @@ -1,4 +1,7 @@ import { createServer } from '@tomrpc/core'; +// import fetch1 from 'isomorphic-unfetch'; +import fetch1 from 'node-fetch'; +import { ofetch } from 'ofetch'; import { describe, expect, it } from 'vitest'; import { createClient } from '..'; @@ -59,12 +62,26 @@ describe('lib', () => { // }, }); + console.dir(client); // const res1 = await client.a('hello'); + const res = await ofetch('http://127.0.0.1:3000/a.json'); + console.dir(res); // console.dir(res1); // const res = await client.postUsers('hello postUsers'); // console.dir(res); }); - it('should render lib', () => { - // expect(lib()).toBe('lib'); + // it.only('should render lib', async () => { + // const res = await ofetch('https://jsonplaceholder.typicode.com/todos/1'); + // console.dir(res); + // expect('lib').toBe('lib'); + // }); + + it.only('should render lib', async () => { + const res = ofetch('http://127.0.0.1:3000/a.json', { + method: 'GET', + parseResponse: JSON.parse, + }); + console.dir(res); + expect('lib').toBe('lib'); }); }); diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 5b1afed..cf4d379 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -1,7 +1,9 @@ import debug from 'debug'; -import fetch from 'isomorphic-unfetch'; +// import fetch1 from 'isomorphic-unfetch'; +import fetch1 from 'node-fetch'; +import { ofetch } from 'ofetch'; -const log = debug('@tomrpc/client'); +const log = console.dir; //debug('@tomrpc/client'); /** * @@ -19,12 +21,14 @@ export class TomClient { private config; private host = '127.0.0.1'; private port = '3000'; + private prefix = '/api'; constructor(config) { log(config); // ... this.config = config; if (config.host) this.host = config.host; if (config.port) this.port = config.port; + if (config.prefix) this.prefix = config.prefix; } async get(key: string, ...r: unknown[]) { @@ -32,10 +36,12 @@ export class TomClient { // console.dir(key); // ... const path = key.split('.').join('/'); - const url = `http://${this.host}:${this.port}/${path}?$p=${JSON.stringify(r)}`; + const url = `http://${this.host}:${this.port}${this.prefix}/${path}?$p=${JSON.stringify(r)}`; log(url); - const response = await fetch(url); + console.dir(ofetch + ' - - - '); + const response = await ofetch(url); + log(response); const data = await response.text(); log(data); return data; diff --git a/packages/client/src/proxy.ts b/packages/client/src/proxy.ts index ff30e23..9a83661 100644 --- a/packages/client/src/proxy.ts +++ b/packages/client/src/proxy.ts @@ -1,6 +1,6 @@ import debug from 'debug'; -const log = debug('@tomrpc/client'); +const log = console.dir; //debug('@tomrpc/client'); import { TomClient } from '.'; import { getHttpMethods } from './utils'; diff --git a/packages/client/test.ts b/packages/client/test.ts index d9044f9..843669e 100644 --- a/packages/client/test.ts +++ b/packages/client/test.ts @@ -4,7 +4,7 @@ const main = async () => { const client = createClient({ host: '127.0.0.1', port: 3000, - namespace: 'a', + // namespace: 'a', methodFilter: function (lastKey: string) { if (lastKey === 'a') { return 'post'; @@ -34,9 +34,9 @@ const post = async () => { // }, }); - const res1 = await client.getUsers('hello getUsers'); + const res1 = await client.a('hello getUsers'); console.dir(res1); - const res = await client.postUsers('hello postUsers'); + const res = await client.a('hello postUsers'); console.dir(res); // const b = await client.a('hello'); From 081c96d1016b951efa3df6dd2694e8065f9a6c78 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 5 Dec 2023 20:31:05 +0800 Subject: [PATCH 088/101] chore: refact --- packages/client/package.json | 6 ++---- packages/client/src/__tests__/index.test.ts | 19 ++++++------------- packages/client/src/client.ts | 10 +++++----- packages/client/vitest.config.cjs | 2 +- 4 files changed, 14 insertions(+), 23 deletions(-) diff --git a/packages/client/package.json b/packages/client/package.json index 821afd4..362346b 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -28,12 +28,10 @@ "devDependencies": { "@tomrpc/core": "workspace:*", "@vitest/coverage-v8": "^0.34.6", - "vitest": "^0.34.6" + "vitest": "^1.0.1" }, "dependencies": { "debug": "^4.3.4", - "isomorphic-unfetch": "^4.0.2", - "node-fetch": "^3.3.2", - "ofetch": "^1.3.3" + "isomorphic-unfetch": "^4.0.2" } } \ No newline at end of file diff --git a/packages/client/src/__tests__/index.test.ts b/packages/client/src/__tests__/index.test.ts index b09868e..41cb83c 100644 --- a/packages/client/src/__tests__/index.test.ts +++ b/packages/client/src/__tests__/index.test.ts @@ -1,7 +1,8 @@ import { createServer } from '@tomrpc/core'; +import fetch from 'isomorphic-unfetch'; // import fetch1 from 'isomorphic-unfetch'; -import fetch1 from 'node-fetch'; -import { ofetch } from 'ofetch'; + +// import { ofetch } from 'ofetch'; import { describe, expect, it } from 'vitest'; import { createClient } from '..'; @@ -64,8 +65,9 @@ describe('lib', () => { console.dir(client); // const res1 = await client.a('hello'); - const res = await ofetch('http://127.0.0.1:3000/a.json'); - console.dir(res); + const res = await fetch('http://127.0.0.1:30001/api/a?$p=["hello"]'); + const s = await res.json(); + console.dir(s); // console.dir(res1); // const res = await client.postUsers('hello postUsers'); // console.dir(res); @@ -75,13 +77,4 @@ describe('lib', () => { // console.dir(res); // expect('lib').toBe('lib'); // }); - - it.only('should render lib', async () => { - const res = ofetch('http://127.0.0.1:3000/a.json', { - method: 'GET', - parseResponse: JSON.parse, - }); - console.dir(res); - expect('lib').toBe('lib'); - }); }); diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index cf4d379..ae49b47 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -1,7 +1,7 @@ import debug from 'debug'; -// import fetch1 from 'isomorphic-unfetch'; -import fetch1 from 'node-fetch'; -import { ofetch } from 'ofetch'; +import fetch from 'isomorphic-unfetch'; + +// import { ofetch } from 'ofetch'; const log = console.dir; //debug('@tomrpc/client'); @@ -39,8 +39,8 @@ export class TomClient { const url = `http://${this.host}:${this.port}${this.prefix}/${path}?$p=${JSON.stringify(r)}`; log(url); - console.dir(ofetch + ' - - - '); - const response = await ofetch(url); + // console.dir(ofetch + ' - - - '); + const response = await fetch(url); log(response); const data = await response.text(); log(data); diff --git a/packages/client/vitest.config.cjs b/packages/client/vitest.config.cjs index c4e3ba6..4b260c7 100644 --- a/packages/client/vitest.config.cjs +++ b/packages/client/vitest.config.cjs @@ -5,6 +5,6 @@ import { defineConfig } from 'vite'; export default defineConfig({ test: { globals: true, - environment: 'happy-dom', + // environment: 'happy-dom', }, }); From 3c8a88cbb79fe39a4ef15f5affc1daf9bf656875 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 5 Dec 2023 21:13:45 +0800 Subject: [PATCH 089/101] chore: refact --- packages/client/src/__tests__/index.test.ts | 86 ++++++++++++++++----- packages/client/src/client.ts | 23 +++--- packages/client/src/proxy.ts | 30 ++++++- packages/client/src/utils.ts | 32 ++++++++ 4 files changed, 140 insertions(+), 31 deletions(-) diff --git a/packages/client/src/__tests__/index.test.ts b/packages/client/src/__tests__/index.test.ts index 41cb83c..6776ebb 100644 --- a/packages/client/src/__tests__/index.test.ts +++ b/packages/client/src/__tests__/index.test.ts @@ -1,8 +1,5 @@ import { createServer } from '@tomrpc/core'; import fetch from 'isomorphic-unfetch'; -// import fetch1 from 'isomorphic-unfetch'; - -// import { ofetch } from 'ofetch'; import { describe, expect, it } from 'vitest'; import { createClient } from '..'; @@ -17,6 +14,9 @@ describe('lib', () => { rpc.fn('/a', function (a) { return { a: a }; }); + rpc.fn('/text', function (a) { + return a; + }); rpc.fn('/b', function (a) { if (this.method === 'POST') { @@ -43,8 +43,36 @@ describe('lib', () => { // const request = supertest(rpc.callback()); - it('should start === rpc.callback', async () => { + it('should GET return json', async () => { rpc.start(30001); + + const client = createClient({ + host: '127.0.0.1', + port: 30001, + // namespace: 'a', + // methodFilter: function (lastKey: string) { + // if (lastKey === 'a') { + // return 'post'; + // } else { + // return 'get'; + // } + // }, + }); + + // console.dir(client); + const res1 = await client.a('hello', 'json'); + // const res1 = await req.json(); + + expect(res1['a']).toBe('hello'); + + const res = await fetch('http://127.0.0.1:30001/api/a?$p=["hello"]'); + const s = await res.json(); + // console.dir(s); + expect(s['a']).toBe('hello'); + }); + + it('should GET return text', async () => { + rpc.start(30002); // const res = await request2.get('/api/a?$p=["hello"]'); // expect(res.type).toEqual('application/json'); // expect(res.status).toEqual(200); @@ -52,7 +80,7 @@ describe('lib', () => { const client = createClient({ host: '127.0.0.1', - port: 30001, + port: 30002, // namespace: 'a', // methodFilter: function (lastKey: string) { // if (lastKey === 'a') { @@ -63,18 +91,40 @@ describe('lib', () => { // }, }); - console.dir(client); - // const res1 = await client.a('hello'); - const res = await fetch('http://127.0.0.1:30001/api/a?$p=["hello"]'); - const s = await res.json(); - console.dir(s); - // console.dir(res1); - // const res = await client.postUsers('hello postUsers'); - // console.dir(res); + // console.dir(client); + const res1 = await client.b('hello', 'text'); + // const res1 = await req.json(); + console.dir(res1); + + expect(res1).toBe('hello'); + }); + + it.only('should POST return json', async () => { + rpc.start(30002); + // const res = await request2.get('/api/a?$p=["hello"]'); + // expect(res.type).toEqual('application/json'); + // expect(res.status).toEqual(200); + // expect(res.body).toEqual({ a: 'hello' }); + + const client = createClient({ + host: '127.0.0.1', + port: 30002, + // namespace: 'a', + methodFilter: function (lastKey: string) { + if (lastKey === 'b') { + return 'post'; + } else { + return 'get'; + } + }, + }); + + // console.dir(client); + const res1 = await client.b('hello'); + // const res1 = await req.json(); + console.dir(res1); + + expect(res1['a']).toBe('hello'); + expect(res1['method']).toBe('post'); }); - // it.only('should render lib', async () => { - // const res = await ofetch('https://jsonplaceholder.typicode.com/todos/1'); - // console.dir(res); - // expect('lib').toBe('lib'); - // }); }); diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index ae49b47..500fb60 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -1,9 +1,6 @@ import debug from 'debug'; import fetch from 'isomorphic-unfetch'; - -// import { ofetch } from 'ofetch'; - -const log = console.dir; //debug('@tomrpc/client'); +const log = debug('@tomrpc/client'); /** * @@ -42,23 +39,27 @@ export class TomClient { // console.dir(ofetch + ' - - - '); const response = await fetch(url); log(response); - const data = await response.text(); - log(data); - return data; + // const data = await response.json(); + // log(data); + return response; } async post(key: string, ...r: unknown[]) { + console.dir(' - post- - '); // ... const path = key.split('.').join('/'); - const response = await fetch(`http://${this.host}:${this.port}/${path}`, { + const url = `http://${this.host}:${this.port}${this.prefix}/${path}`; + + log(url); + const response = await fetch(url, { method: 'post', body: JSON.stringify(r), headers: { 'Content-Type': 'application/json' }, }); - const data = await response.text(); - log(data); - return data; + // const data = await response.text(); + // log(data); + return response; } } diff --git a/packages/client/src/proxy.ts b/packages/client/src/proxy.ts index 9a83661..b11a51d 100644 --- a/packages/client/src/proxy.ts +++ b/packages/client/src/proxy.ts @@ -3,7 +3,7 @@ import debug from 'debug'; const log = console.dir; //debug('@tomrpc/client'); import { TomClient } from '.'; -import { getHttpMethods } from './utils'; +import { getHttpMethods, mergeDeep } from './utils'; export const defaultConfig = { methodFilter: function (lastKey: string) { @@ -33,8 +33,34 @@ export const defaultConfig = { if (supportMethods.length > 0) method = supportMethods[0]; log(lastKey); log(method); + + // console.dir('parms'); + // console.dir(parms); + let type1 = 'json'; + const a = (val) => val === parms[parms.length - 1]; + if (['json', 'text'].some(a)) { + // console.dir('dfd '); + type1 = parms.pop(); + } + const _p = [key.replace('default.', ''), ...parms]; - return await o[method](..._p); + + const response = await o[method](..._p); + + let data; + switch (type1) { + case 'json': + data = await response.json(); + break; + case 'text': + data = await response.text(); + break; + default: + data = await response.json(); + break; + } + + return data; }, }; diff --git a/packages/client/src/utils.ts b/packages/client/src/utils.ts index 6404732..4c6e2a7 100644 --- a/packages/client/src/utils.ts +++ b/packages/client/src/utils.ts @@ -28,3 +28,35 @@ export function getHttpMethods() { 'connect', ]; } + +/** + * Simple object check. + * @param item + * @returns {boolean} + */ +export function isObject(item) { + return item && typeof item === 'object' && !Array.isArray(item); +} + +/** + * Deep merge two objects. + * @param target + * @param ...sources + */ +export function mergeDeep(target, ...sources) { + if (!sources.length) return target; + const source = sources.shift(); + + if (isObject(target) && isObject(source)) { + for (const key in source) { + if (isObject(source[key])) { + if (!target[key]) Object.assign(target, { [key]: {} }); + mergeDeep(target[key], source[key]); + } else { + Object.assign(target, { [key]: source[key] }); + } + } + } + + return mergeDeep(target, ...sources); +} From dcb7783e36bbebc8f661545f5e9f1b1aa34011f0 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 5 Dec 2023 21:15:54 +0800 Subject: [PATCH 090/101] chore: refact --- packages/client/src/client.ts | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 500fb60..945cfd3 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -29,24 +29,21 @@ export class TomClient { } async get(key: string, ...r: unknown[]) { - // console.dir('client get request'); - // console.dir(key); - // ... + log('client get request'); + const path = key.split('.').join('/'); const url = `http://${this.host}:${this.port}${this.prefix}/${path}?$p=${JSON.stringify(r)}`; log(url); - // console.dir(ofetch + ' - - - '); + const response = await fetch(url); - log(response); - // const data = await response.json(); - // log(data); + return response; } async post(key: string, ...r: unknown[]) { - console.dir(' - post- - '); - // ... + log('client post request'); + const path = key.split('.').join('/'); const url = `http://${this.host}:${this.port}${this.prefix}/${path}`; @@ -58,8 +55,6 @@ export class TomClient { headers: { 'Content-Type': 'application/json' }, }); - // const data = await response.text(); - // log(data); return response; } } From 1a6a5e311f5c4d1d54152c3451be4c6d28ca0751 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 5 Dec 2023 21:22:39 +0800 Subject: [PATCH 091/101] chore: refact --- packages/client/README.md | 27 ++++++++++++++-- packages/client/src/__tests__/index.test.ts | 34 +++------------------ packages/client/src/proxy.ts | 4 +-- packages/client/src/utils.ts | 32 ------------------- 4 files changed, 31 insertions(+), 66 deletions(-) diff --git a/packages/client/README.md b/packages/client/README.md index 3ab49b0..76c2f18 100644 --- a/packages/client/README.md +++ b/packages/client/README.md @@ -29,6 +29,31 @@ rpc.fn('a', (a: string) => { }); ``` +## 返回类型 + +方法的第二个参数是返回类型,默认返回json。 + +返回json + +```js +const res = await client.a('hello'); +console.dir(res); + +or + +const res = await client.a('hello','json'); +console.dir(res); + +``` + +返回text,只有1种办法 + +```js +const res = await client.a('hello','text'); +console.dir(res); +``` + + ## 扩展 默认用 get 方法,如果想用 post,可以通过 methodFilter 来配置 @@ -51,8 +76,6 @@ const client = createClient({ 比如a.a,你的lastKey就是a,这里把namespace去掉,更简单。 - - ## test ``` diff --git a/packages/client/src/__tests__/index.test.ts b/packages/client/src/__tests__/index.test.ts index 6776ebb..f1b268d 100644 --- a/packages/client/src/__tests__/index.test.ts +++ b/packages/client/src/__tests__/index.test.ts @@ -41,22 +41,12 @@ describe('lib', () => { }, }); - // const request = supertest(rpc.callback()); - it('should GET return json', async () => { rpc.start(30001); const client = createClient({ host: '127.0.0.1', port: 30001, - // namespace: 'a', - // methodFilter: function (lastKey: string) { - // if (lastKey === 'a') { - // return 'post'; - // } else { - // return 'get'; - // } - // }, }); // console.dir(client); @@ -73,42 +63,26 @@ describe('lib', () => { it('should GET return text', async () => { rpc.start(30002); - // const res = await request2.get('/api/a?$p=["hello"]'); - // expect(res.type).toEqual('application/json'); - // expect(res.status).toEqual(200); - // expect(res.body).toEqual({ a: 'hello' }); const client = createClient({ host: '127.0.0.1', port: 30002, - // namespace: 'a', - // methodFilter: function (lastKey: string) { - // if (lastKey === 'a') { - // return 'post'; - // } else { - // return 'get'; - // } - // }, }); // console.dir(client); - const res1 = await client.b('hello', 'text'); + const res1 = await client.text('hello', 'text'); // const res1 = await req.json(); console.dir(res1); expect(res1).toBe('hello'); }); - it.only('should POST return json', async () => { - rpc.start(30002); - // const res = await request2.get('/api/a?$p=["hello"]'); - // expect(res.type).toEqual('application/json'); - // expect(res.status).toEqual(200); - // expect(res.body).toEqual({ a: 'hello' }); + it('should POST return json', async () => { + rpc.start(30003); const client = createClient({ host: '127.0.0.1', - port: 30002, + port: 30003, // namespace: 'a', methodFilter: function (lastKey: string) { if (lastKey === 'b') { diff --git a/packages/client/src/proxy.ts b/packages/client/src/proxy.ts index b11a51d..bb15e5f 100644 --- a/packages/client/src/proxy.ts +++ b/packages/client/src/proxy.ts @@ -1,9 +1,9 @@ import debug from 'debug'; -const log = console.dir; //debug('@tomrpc/client'); +const log = debug('@tomrpc/client'); import { TomClient } from '.'; -import { getHttpMethods, mergeDeep } from './utils'; +import { getHttpMethods } from './utils'; export const defaultConfig = { methodFilter: function (lastKey: string) { diff --git a/packages/client/src/utils.ts b/packages/client/src/utils.ts index 4c6e2a7..6404732 100644 --- a/packages/client/src/utils.ts +++ b/packages/client/src/utils.ts @@ -28,35 +28,3 @@ export function getHttpMethods() { 'connect', ]; } - -/** - * Simple object check. - * @param item - * @returns {boolean} - */ -export function isObject(item) { - return item && typeof item === 'object' && !Array.isArray(item); -} - -/** - * Deep merge two objects. - * @param target - * @param ...sources - */ -export function mergeDeep(target, ...sources) { - if (!sources.length) return target; - const source = sources.shift(); - - if (isObject(target) && isObject(source)) { - for (const key in source) { - if (isObject(source[key])) { - if (!target[key]) Object.assign(target, { [key]: {} }); - mergeDeep(target[key], source[key]); - } else { - Object.assign(target, { [key]: source[key] }); - } - } - } - - return mergeDeep(target, ...sources); -} From 97e604e2a8a700053dbf1b519561b668668f88c1 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 5 Dec 2023 21:34:20 +0800 Subject: [PATCH 092/101] chore: refact --- packages/client/src/client.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/client/src/client.ts b/packages/client/src/client.ts index 945cfd3..64a778d 100644 --- a/packages/client/src/client.ts +++ b/packages/client/src/client.ts @@ -4,6 +4,7 @@ const log = debug('@tomrpc/client'); /** * +https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#response_objects * http://127.0.0.1:3000/a?$p=[%22hello%22,%22world%22] From 976a975515c1f5987afdb3b1921884a2318e9d3f Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 5 Dec 2023 21:42:17 +0800 Subject: [PATCH 093/101] chore: refact --- package.json | 4 ++-- packages/app/package.json | 4 ++-- packages/client/package.json | 2 +- packages/core/package.json | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index d46f0a5..7a0e6d6 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,7 @@ "tsx": "^3.12.10", "typescript": "^4.9.5", "vite": "^4.4.9", - "vitest": "^0.34.6" + "vitest": "^1.0.1" }, "packageManager": "pnpm@8.6.0", "size-limit": [ @@ -60,4 +60,4 @@ "dependencies": { "@changesets/cli": "^2.26.2" } -} +} \ No newline at end of file diff --git a/packages/app/package.json b/packages/app/package.json index a2cf98b..64e30b4 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -26,9 +26,9 @@ "awesome-keywords" ], "devDependencies": { - "@vitest/coverage-v8": "^0.34.6", + "@vitest/coverage-v8": "^1.0.1", "happy-dom": "^6.0.4", - "vitest": "^0.34.6" + "vitest": "^1.0.1" }, "dependencies": { "@koa/cors": "^4.0.0", diff --git a/packages/client/package.json b/packages/client/package.json index 362346b..c059c97 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -27,7 +27,7 @@ ], "devDependencies": { "@tomrpc/core": "workspace:*", - "@vitest/coverage-v8": "^0.34.6", + "@vitest/coverage-v8": "^1.0.1", "vitest": "^1.0.1" }, "dependencies": { diff --git a/packages/core/package.json b/packages/core/package.json index 1615115..4ef9cda 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -26,9 +26,9 @@ ], "devDependencies": { "@types/koa": "^2.13.10", - "@vitest/coverage-v8": "^0.34.6", + "@vitest/coverage-v8": "^1.0.1", "supertest": "^6.3.3", - "vitest": "^0.34.6" + "vitest": "^1.0.1" }, "dependencies": { "@koa/bodyparser": "^5.0.0", From 94ad39a882eaa5a162428d0fce3a37d1f1e780c5 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Sat, 9 Dec 2023 16:50:38 +0800 Subject: [PATCH 094/101] fix: use plugin when the config exist --- packages/app/src/index.ts | 24 ++++++++++++------------ packages/app/src/mw/jwt.ts | 6 +++--- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 99eaadc..2163147 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -69,20 +69,20 @@ export async function createApp(cfg: IConfig) { ) ); - const cors = new Cors(cfg.buildin.cors); - rpc.plugin(cors); + if (cfg.buildin.cors) { + const cors = new Cors(cfg.buildin.cors); + rpc.plugin(cors); + } - const serve = new Serve(cfg.buildin.serve); - rpc.plugin(serve); + if (cfg.buildin.serve) { + const serve = new Serve(cfg.buildin.serve); + rpc.plugin(serve); + } - // rpc.plugin(view); - // console.dir(view); - - const jwt = new Jwt(cfg.buildin.jwt); - rpc.plugin(jwt); - // await mount(rpc, cfg.mount); - // await loadInitMiddleware(rpc, init); - // await loadBuildinMiddlewaire(rpc); + if (cfg.buildin.jwt) { + const jwt = new Jwt(cfg.buildin.jwt); + rpc.plugin(jwt); + } return mergeDeep(rpc, { jwt: function (cb) { diff --git a/packages/app/src/mw/jwt.ts b/packages/app/src/mw/jwt.ts index feb6c93..f546867 100644 --- a/packages/app/src/mw/jwt.ts +++ b/packages/app/src/mw/jwt.ts @@ -8,7 +8,7 @@ export class Jwt extends Proxy { this.config.proxy.inject = 'before'; this.config.proxy.before = ['fn']; } - // proxy() { - // // return koajwt(this.config).unless({ path: this.config.unless }); - // } + proxy() { + return koajwt(this.config).unless({ path: this.config.unless }); + } } From 04c3ef6304b389dd68c4d7614f59a6a13ac4976d Mon Sep 17 00:00:00 2001 From: npmstudy Date: Mon, 11 Dec 2023 19:50:44 +0800 Subject: [PATCH 095/101] build: v2.0.2 add tests --- packages/app/CHANGELOG.md | 10 ++++++++++ packages/app/package.json | 6 +++--- packages/client/CHANGELOG.md | 6 ++++++ packages/client/package.json | 2 +- packages/core/CHANGELOG.md | 6 ++++++ packages/core/package.json | 2 +- packages/mount/CHANGELOG.md | 6 ++++++ packages/mount/package.json | 2 +- 8 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/app/CHANGELOG.md b/packages/app/CHANGELOG.md index 0359bec..638a314 100644 --- a/packages/app/CHANGELOG.md +++ b/packages/app/CHANGELOG.md @@ -1,5 +1,15 @@ # @tomrpc/mount +## 2.0.2 + +### Patch Changes + +- add test +- Updated dependencies + - @tomrpc/client@2.0.2 + - @tomrpc/mount@2.0.2 + - @tomrpc/core@2.0.2 + ## 2.0.1 ### Patch Changes diff --git a/packages/app/package.json b/packages/app/package.json index 64e30b4..d05b86f 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/app", - "version": "2.0.1", + "version": "2.0.2", "description": "My Awesome lib", "license": "MIT", "publishConfig": { @@ -32,8 +32,8 @@ }, "dependencies": { "@koa/cors": "^4.0.0", - "@tomrpc/client": "^2.0.1", - "@tomrpc/core": "^2.0.1", + "@tomrpc/client": "^2.0.2", + "@tomrpc/core": "^2.0.2", "@tomrpc/mount": "workspace:^", "debug": "^4.3.4", "desm": "^1.3.0", diff --git a/packages/client/CHANGELOG.md b/packages/client/CHANGELOG.md index fd92b8c..32d4c4d 100644 --- a/packages/client/CHANGELOG.md +++ b/packages/client/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/client +## 2.0.2 + +### Patch Changes + +- add test + ## 2.0.1 ### Patch Changes diff --git a/packages/client/package.json b/packages/client/package.json index c059c97..2c8963d 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/client", - "version": "2.0.1", + "version": "2.0.2", "description": "My Awesome lib", "license": "MIT", "publishConfig": { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index dcfc41c..092ae08 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/core +## 2.0.2 + +### Patch Changes + +- add test + ## 2.0.1 ### Patch Changes diff --git a/packages/core/package.json b/packages/core/package.json index 4ef9cda..ae0b94b 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/core", - "version": "2.0.1", + "version": "2.0.2", "description": "My Awesome lib", "license": "MIT", "publishConfig": { diff --git a/packages/mount/CHANGELOG.md b/packages/mount/CHANGELOG.md index 046860f..1e2d4b7 100644 --- a/packages/mount/CHANGELOG.md +++ b/packages/mount/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/mount +## 2.0.2 + +### Patch Changes + +- add test + ## 2.0.1 ### Patch Changes diff --git a/packages/mount/package.json b/packages/mount/package.json index 106be34..94dafde 100644 --- a/packages/mount/package.json +++ b/packages/mount/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/mount", - "version": "2.0.1", + "version": "2.0.2", "description": "My Awesome lib", "license": "MIT", "publishConfig": { From bcb3d7cef5a76e2c55ac29b1050a935025392e20 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 12 Dec 2023 14:13:35 +0800 Subject: [PATCH 096/101] chore: refact mergeDeep to class --- package.json | 12 ++- packages/app/package.json | 3 +- packages/app/src/__tests__/app.test.ts | 109 +++++++++++++++++++++++ packages/app/src/__tests__/index.test.ts | 14 +-- packages/app/src/index.ts | 78 ++++++++-------- packages/core/src/index.ts | 54 ++++++----- packages/core/src/server.ts | 24 ++--- 7 files changed, 216 insertions(+), 78 deletions(-) create mode 100644 packages/app/src/__tests__/app.test.ts diff --git a/package.json b/package.json index 7a0e6d6..3697568 100644 --- a/package.json +++ b/package.json @@ -59,5 +59,13 @@ ], "dependencies": { "@changesets/cli": "^2.26.2" - } -} \ No newline at end of file + }, + "version": "1.0.0", + "main": "commitlint.config.js", + "directories": { + "doc": "docs", + "example": "example" + }, + "keywords": [], + "author": "" +} diff --git a/packages/app/package.json b/packages/app/package.json index d05b86f..0f733f4 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -26,8 +26,9 @@ "awesome-keywords" ], "devDependencies": { + "@types/koa": "^2.13.10", "@vitest/coverage-v8": "^1.0.1", - "happy-dom": "^6.0.4", + "supertest": "^6.3.3", "vitest": "^1.0.1" }, "dependencies": { diff --git a/packages/app/src/__tests__/app.test.ts b/packages/app/src/__tests__/app.test.ts new file mode 100644 index 0000000..f6fcc9a --- /dev/null +++ b/packages/app/src/__tests__/app.test.ts @@ -0,0 +1,109 @@ +import supertest from 'supertest'; +import { describe, expect, it } from 'vitest'; + +import { createApp, AppServer } from '../index'; + +describe('app', async () => { + const rpc: AppServer = await createApp({ + name: 'tomapp', + base: import.meta.url, + port: 3001, + debug: false, + mount: './f', + }); + + rpc.fn('a', function (a) { + // console.dir(rpc.fn); + // console.dir(this); + // this.render('user', { user: { name: 'alfred' } }); + return { a: a }; + }); + + rpc.fn('/a', function (a) { + return { a: a }; + }); + + rpc.fn('/b', function (a) { + if (this.method === 'POST') { + return { a: a, method: 'post' }; + } + if (this.method === 'GET') { + return { a: a, method: 'get' }; + } + }); + + rpc.fn('com.yourcompany.a', function (a: string) { + return { a: a }; + }); + + rpc.fn('com.yourcompany.b', function (a: string) { + return `${this.path} , ${a} `; + }); + + rpc.add({ + '/add': function (a: string, b: string) { + return { a: a }; + }, + }); + + const request = supertest(rpc.callback()); + + it('should start === rpc.callback', async () => { + const request2 = supertest(rpc.start(30001)); + const res = await request2.get('/api/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); + + it('should access /a', async () => { + const res = await request.get('/api/a?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); + + it('should access no routers[key]', async () => { + // if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { + const res = await request.get('/api/a123'); + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('not match $p param, no process'); + }); + + it('should access no routers[key]', async () => { + const res = await request.get('/api/a123?$p=["hello"]'); + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('[fn plugin] no fn repsonse, please check your fn if exist'); + }); + + it('should access /add', async () => { + const res = await request.get('/api/add?$p=["hello"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello' }); + }); + + it('should access GET /b', async () => { + const res = await request.get('/api/b?$p=["hello1"]'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello1', method: 'get' }); + }); + + it('should access POST /b', async () => { + const res = await request.post('/api/b').send(['hello']).set('Accept', 'application/json'); + + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 'hello', method: 'post' }); + }); + + it('should access com.yourcompany.b', async () => { + const res = await request.get('/api/com/yourcompany/b?$p=["hello"]'); + expect(res.type).toEqual('text/plain'); + expect(res.status).toEqual(200); + expect(res.text).toEqual('/com/yourcompany/b , hello '); + }); +}); diff --git a/packages/app/src/__tests__/index.test.ts b/packages/app/src/__tests__/index.test.ts index 2ae6c18..6c3b7a6 100644 --- a/packages/app/src/__tests__/index.test.ts +++ b/packages/app/src/__tests__/index.test.ts @@ -1,9 +1,13 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it, vi } from 'vitest'; -// import mount from '../mount'; - -describe('lib', () => { +describe('app', async () => { it('should render lib', () => { - // expect(lib()).toBe('lib'); + expect('lib').toBe('lib'); + }); + + it('mock console.dir', () => { + const spy = vi.spyOn(console, 'dir'); + console.dir('2323'); + expect(spy).toHaveBeenCalled(); }); }); diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 2163147..6d2682b 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -1,5 +1,7 @@ -import { createServer, combine } from '@tomrpc/core'; +import { createServer, combine, RpcServer } from '@tomrpc/core'; +import type { IIndexServerConfig } from '@tomrpc/core'; // import mount from '@tomrpc/mount'; +import exp from 'constants'; import debug from 'debug'; import { init } from './init'; @@ -46,55 +48,59 @@ interface IJwt { unless?: any; getToken; } -interface IConfig { - name: string | 'tomapp'; +interface IAppConfig1 { + name?: string | 'tomapp'; base?: string; port?: number | 3000; debug?: boolean | false; mount?: string; - buildin: { + buildin?: { serve?: IServe; cors?: ICors; view?: IView; jwt?: IJwt; }; } -export async function createApp(cfg: IConfig) { - const rpc = createServer( - mergeDeep( - { - base: import.meta.url, - }, - cfg - ) - ); - if (cfg.buildin.cors) { - const cors = new Cors(cfg.buildin.cors); - rpc.plugin(cors); - } +type IAppConfig = IAppConfig1 & IIndexServerConfig; - if (cfg.buildin.serve) { - const serve = new Serve(cfg.buildin.serve); - rpc.plugin(serve); - } +export class AppServer extends RpcServer { + constructor(cfg?: IAppConfig) { + super(cfg); + + if (cfg?.buildin?.cors) { + const cors = new Cors(cfg?.buildin?.cors); + this.plugin(cors); + } + + if (cfg?.buildin?.serve) { + const serve = new Serve(cfg?.buildin?.serve); + this.plugin(serve); + } - if (cfg.buildin.jwt) { - const jwt = new Jwt(cfg.buildin.jwt); - rpc.plugin(jwt); + if (cfg?.buildin?.jwt) { + const jwt = new Jwt(cfg?.buildin?.jwt); + this.plugin(jwt); + } } - return mergeDeep(rpc, { - jwt: function (cb) { - // const mw = combine([cb]); - // console.dir(rpc.config); - // rpc.init.push(mw); - }, - render: function (path, cb) { - // console.dir('render'); - const view = new View(cfg.buildin.view); + public render(path, cb): void { + // console.dir('render'); + if (this.config?.buildin?.view) { + const view = new View(this.config?.buildin?.view); const mw = combine([view.proxy(), cb]); - rpc.app.use(mw); - }, - }); + this.app.use(mw); + } + } +} + +export function createApp(cfg?: IAppConfig): AppServer { + return new AppServer( + mergeDeep( + { + base: import.meta.url, + }, + cfg || {} + ) + ); } diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 403ff8d..ca42b6b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -2,7 +2,7 @@ import debug from 'debug'; import compose from 'koa-compose'; import { Fn, IFnConfig } from './fn'; -import { RpcServer, IRpcServerConfig } from './server'; +import { BaseRpcServer, IRpcServerConfig } from './server'; import { mergeDeep } from './utils'; export * from './plugin'; @@ -14,31 +14,41 @@ export * from './utils'; const log = debug('@tomrpc/core/index'); export const combine = compose; -interface IServerConfig { +export interface IServerConfig { base?: string; fn?: IFnConfig; } -type IIndexServerConfig = IRpcServerConfig & IServerConfig; +export type IIndexServerConfig = IRpcServerConfig & IServerConfig; + +export class RpcServer extends BaseRpcServer { + private fnPlugin; + public base; + public before; + public after; + + constructor(cfg?: IIndexServerConfig) { + super(cfg); + this.fnPlugin = new Fn(mergeDeep({}, cfg.fn)); + this.plugin(this.fnPlugin); + + this.base = '.'; + this.init = this['config']['hooks']['init']; + this.before = this['config']['hooks']['before']; + this.load = this['config']['hooks']['load']; + this.after = this['config']['hooks']['after']; + } + + public fn(key, fun) { + log('use rpc.fn add fn =' + key); + this.fnPlugin.fn(key, fun); + } + public add(items) { + log('use rpc.add add fn =' + items); + this.fnPlugin.add(items); + } +} export function createServer(cfg?: IIndexServerConfig) { - const rpc = new RpcServer(mergeDeep({ fn: {} }, cfg)); - const fn = new Fn(mergeDeep({}, cfg.fn)); - rpc.plugin(fn); - - return mergeDeep(rpc, { - base: '.', - init: rpc['config']['hooks']['init'], - before: rpc['config']['hooks']['before'], - load: rpc['config']['hooks']['load'], - after: rpc['config']['hooks']['after'], - fn: function (key, fun) { - log('use rpc.fn add fn =' + key); - fn.fn(key, fun); - }, - add: function (items) { - log('use rpc.add add fn =' + items); - fn.add(items); - }, - }); + return new RpcServer(mergeDeep({ fn: {} }, cfg)); } diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index b1793de..5649c6c 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -20,14 +20,14 @@ export const LifeCycleConfig = { }, }, - before: async (server: RpcServer) => { + before: async (server: BaseRpcServer) => { const app = server.app; const loadMiddlewares = server.config.hooks.before; loadMiddlewares.forEach((mw: Middleware) => { app.use(mw); }); }, - init: async (server: RpcServer) => { + init: async (server: BaseRpcServer) => { log('init'); // console.dir(server); const app = server.app; @@ -37,14 +37,14 @@ export const LifeCycleConfig = { app.use(mw); }); }, - load: async (server: RpcServer) => { + load: async (server: BaseRpcServer) => { const app = server.app; const loadMiddlewares = server.config.hooks.load; loadMiddlewares.forEach((mw: Middleware) => { app.use(mw); }); }, - after: async (server: RpcServer) => { + after: async (server: BaseRpcServer) => { const app = server.app; const loadMiddlewares = server.config.hooks.after; loadMiddlewares.forEach((mw: Middleware) => { @@ -62,17 +62,17 @@ export interface IRpcServerConfig { after: Array; default(): Promise; }; - before?(server: RpcServer): Promise; - init?(server: RpcServer): Promise; - load?(server: RpcServer): Promise; - after?(server: RpcServer): Promise; + before?(server: BaseRpcServer): Promise; + init?(server: BaseRpcServer): Promise; + load?(server: BaseRpcServer): Promise; + after?(server: BaseRpcServer): Promise; } /** * @type {RpcServer} The Server maintains a server to bind one of the Strategy * objects. The Server does not know the concrete class of a strategy. It * should work with all strategies via the Strategy interface. */ -export class RpcServer { +export class BaseRpcServer { private plugins: Strategy[] = []; app: Application; use; @@ -81,9 +81,9 @@ export class RpcServer { load: [], before: {}, }; - config; - init: []; - load: []; + public config; + public init: []; + public load: []; /** * Usually, the Server accepts a strategy through the constructor, but also * provides a setter to change it at runtime. From 9d9d33572d07ab7a3e297f6c89fbbdf1227d9aa3 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 12 Dec 2023 14:14:58 +0800 Subject: [PATCH 097/101] build: v2.0.3 --- packages/app/CHANGELOG.md | 10 ++++++++++ packages/app/package.json | 6 +++--- packages/client/CHANGELOG.md | 6 ++++++ packages/client/package.json | 2 +- packages/core/CHANGELOG.md | 6 ++++++ packages/core/package.json | 2 +- packages/mount/CHANGELOG.md | 6 ++++++ packages/mount/package.json | 2 +- 8 files changed, 34 insertions(+), 6 deletions(-) diff --git a/packages/app/CHANGELOG.md b/packages/app/CHANGELOG.md index 638a314..7665509 100644 --- a/packages/app/CHANGELOG.md +++ b/packages/app/CHANGELOG.md @@ -1,5 +1,15 @@ # @tomrpc/mount +## 2.0.3 + +### Patch Changes + +- test +- Updated dependencies + - @tomrpc/client@2.0.3 + - @tomrpc/mount@2.0.3 + - @tomrpc/core@2.0.3 + ## 2.0.2 ### Patch Changes diff --git a/packages/app/package.json b/packages/app/package.json index 0f733f4..51156ba 100644 --- a/packages/app/package.json +++ b/packages/app/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/app", - "version": "2.0.2", + "version": "2.0.3", "description": "My Awesome lib", "license": "MIT", "publishConfig": { @@ -33,8 +33,8 @@ }, "dependencies": { "@koa/cors": "^4.0.0", - "@tomrpc/client": "^2.0.2", - "@tomrpc/core": "^2.0.2", + "@tomrpc/client": "^2.0.3", + "@tomrpc/core": "^2.0.3", "@tomrpc/mount": "workspace:^", "debug": "^4.3.4", "desm": "^1.3.0", diff --git a/packages/client/CHANGELOG.md b/packages/client/CHANGELOG.md index 32d4c4d..bf7e449 100644 --- a/packages/client/CHANGELOG.md +++ b/packages/client/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/client +## 2.0.3 + +### Patch Changes + +- test + ## 2.0.2 ### Patch Changes diff --git a/packages/client/package.json b/packages/client/package.json index 2c8963d..e6d845d 100644 --- a/packages/client/package.json +++ b/packages/client/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/client", - "version": "2.0.2", + "version": "2.0.3", "description": "My Awesome lib", "license": "MIT", "publishConfig": { diff --git a/packages/core/CHANGELOG.md b/packages/core/CHANGELOG.md index 092ae08..631588d 100644 --- a/packages/core/CHANGELOG.md +++ b/packages/core/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/core +## 2.0.3 + +### Patch Changes + +- test + ## 2.0.2 ### Patch Changes diff --git a/packages/core/package.json b/packages/core/package.json index ae0b94b..72092b6 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/core", - "version": "2.0.2", + "version": "2.0.3", "description": "My Awesome lib", "license": "MIT", "publishConfig": { diff --git a/packages/mount/CHANGELOG.md b/packages/mount/CHANGELOG.md index 1e2d4b7..34906fa 100644 --- a/packages/mount/CHANGELOG.md +++ b/packages/mount/CHANGELOG.md @@ -1,5 +1,11 @@ # @tomrpc/mount +## 2.0.3 + +### Patch Changes + +- test + ## 2.0.2 ### Patch Changes diff --git a/packages/mount/package.json b/packages/mount/package.json index 94dafde..093ab19 100644 --- a/packages/mount/package.json +++ b/packages/mount/package.json @@ -1,6 +1,6 @@ { "name": "@tomrpc/mount", - "version": "2.0.2", + "version": "2.0.3", "description": "My Awesome lib", "license": "MIT", "publishConfig": { From d47fb7ba7404ef49ad119a6cfe72e3333da8e9b1 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 12 Dec 2023 14:29:17 +0800 Subject: [PATCH 098/101] test: add /view test case and passed --- packages/app/src/__tests__/app.test.ts | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/packages/app/src/__tests__/app.test.ts b/packages/app/src/__tests__/app.test.ts index f6fcc9a..bfc3c3e 100644 --- a/packages/app/src/__tests__/app.test.ts +++ b/packages/app/src/__tests__/app.test.ts @@ -1,3 +1,5 @@ +import { dirname, filename, join } from 'desm'; +import jwt from 'jsonwebtoken'; import supertest from 'supertest'; import { describe, expect, it } from 'vitest'; @@ -10,6 +12,31 @@ describe('app', async () => { port: 3001, debug: false, mount: './f', + buildin: { + serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, + cors: { enable: true }, + // jwt: { + // enable: true, + // secret: 'shhhhhh', + // debug: true, + // getToken: () => { + // const token = jwt.sign({ foo: 'bar' }, 'bad'); + // console.dir('token'); + // console.dir(token); + // return token; + // }, + // unless: { path: ['/view'] }, + // }, + view: { + enable: true, + root: join(import.meta.url, '../..', 'view'), + opts: { + map: { + html: 'ejs', + }, + }, + }, + }, }); rpc.fn('a', function (a) { @@ -46,6 +73,19 @@ describe('app', async () => { }, }); + rpc.render('/view', async (ctx, next) => { + console.dir('view'); + ctx.state = { + session: ctx.session, + title: 'app', + }; + if (ctx.path === '/view') { + await ctx.render('user.ejs', { user: { name: 'alfred' } }); + } else { + await next(); + } + }); + const request = supertest(rpc.callback()); it('should start === rpc.callback', async () => { @@ -63,6 +103,14 @@ describe('app', async () => { expect(res.body).toEqual({ a: 'hello' }); }); + it.only('should access /view', async () => { + const res = await request.get('/view'); + expect(res.type).toEqual('text/html'); + expect(res.status).toEqual(200); + + expect(res.text).toEqual(`\n

alfred

\n\n123\n`); + }); + it('should access no routers[key]', async () => { // if (!['POST', 'PUT', 'PATCH'].includes(ctx.method) && !ctx.query.$p) { const res = await request.get('/api/a123'); From 08f3c998c3bcacfbb7d319a26b85bf8aaa0d3ec2 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 12 Dec 2023 15:49:46 +0800 Subject: [PATCH 099/101] test: add /a.json (serve middlewaire) test case and passed --- packages/app/src/__tests__/app.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/app/src/__tests__/app.test.ts b/packages/app/src/__tests__/app.test.ts index bfc3c3e..68403f1 100644 --- a/packages/app/src/__tests__/app.test.ts +++ b/packages/app/src/__tests__/app.test.ts @@ -13,7 +13,7 @@ describe('app', async () => { debug: false, mount: './f', buildin: { - serve: { enable: true, root: join(import.meta.url, '.', 'public'), opts: {} }, + serve: { enable: true, root: join(import.meta.url, '../..', 'public'), opts: {} }, cors: { enable: true }, // jwt: { // enable: true, @@ -103,6 +103,13 @@ describe('app', async () => { expect(res.body).toEqual({ a: 'hello' }); }); + it('should access /a.json', async () => { + const res = await request.get('/a.json'); + expect(res.type).toEqual('application/json'); + expect(res.status).toEqual(200); + expect(res.body).toEqual({ a: 123 }); + }); + it.only('should access /view', async () => { const res = await request.get('/view'); expect(res.type).toEqual('text/html'); From 1e5cfc68cdac6c7ddc313d43f2e56b373788f8b7 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 12 Dec 2023 16:06:53 +0800 Subject: [PATCH 100/101] chore: refact --- packages/app/app.ts | 3 +-- packages/app/src/__tests__/app.test.ts | 3 +-- packages/app/src/index.ts | 28 ++++++--------------- packages/app/src/load.ts | 2 +- packages/client/src/__tests__/index.test.ts | 2 +- packages/core/src/__tests__/app.test.ts | 2 +- packages/core/src/__tests__/proxy.test.ts | 2 +- packages/core/src/fn.ts | 2 +- packages/core/src/plugin.ts | 6 ++--- packages/core/src/server.ts | 2 +- packages/mount/src/__tests__/index.test.ts | 4 +-- 11 files changed, 20 insertions(+), 36 deletions(-) diff --git a/packages/app/app.ts b/packages/app/app.ts index dbad115..d13d1d9 100644 --- a/packages/app/app.ts +++ b/packages/app/app.ts @@ -1,5 +1,4 @@ -import { dirname, filename, join } from 'desm'; -import jwt from 'jsonwebtoken'; +import { join } from 'desm'; import { createApp } from './src/index'; diff --git a/packages/app/src/__tests__/app.test.ts b/packages/app/src/__tests__/app.test.ts index 68403f1..dbdc032 100644 --- a/packages/app/src/__tests__/app.test.ts +++ b/packages/app/src/__tests__/app.test.ts @@ -1,5 +1,4 @@ -import { dirname, filename, join } from 'desm'; -import jwt from 'jsonwebtoken'; +import { join } from 'desm'; import supertest from 'supertest'; import { describe, expect, it } from 'vitest'; diff --git a/packages/app/src/index.ts b/packages/app/src/index.ts index 6d2682b..a75113a 100644 --- a/packages/app/src/index.ts +++ b/packages/app/src/index.ts @@ -1,31 +1,13 @@ -import { createServer, combine, RpcServer } from '@tomrpc/core'; -import type { IIndexServerConfig } from '@tomrpc/core'; +import { combine, RpcServer } from '@tomrpc/core'; +import type { IIndexServerConfig, JSONValue } from '@tomrpc/core'; // import mount from '@tomrpc/mount'; -import exp from 'constants'; import debug from 'debug'; -import { init } from './init'; -import { loadBuildinMiddlewaire, loadInitMiddleware } from './load'; import { Serve, Cors, View, Jwt } from './mw/index'; import { mergeDeep } from './utils'; const log = debug('@tomrpc/app'); -// { -// name:'hi' -// base: import.meta.url -// static: 'public' -// cors: { enable: true } -// view: { enable: true } -// jwt: { enable: true } -// port: 3000 -// mount: './fn' -// lifeCyle: { - -// }, -// debug: true -// logLevel: -// } interface ICors { enable?: boolean | false; opts?: object; @@ -45,7 +27,7 @@ interface IJwt { secret?: string; issuer?: string; debug: boolean; - unless?: any; + unless?: JSONValue; getToken; } interface IAppConfig1 { @@ -66,19 +48,23 @@ type IAppConfig = IAppConfig1 & IIndexServerConfig; export class AppServer extends RpcServer { constructor(cfg?: IAppConfig) { + log('AppServer constructor'); super(cfg); if (cfg?.buildin?.cors) { + log('cors enable'); const cors = new Cors(cfg?.buildin?.cors); this.plugin(cors); } if (cfg?.buildin?.serve) { + log('serve enable'); const serve = new Serve(cfg?.buildin?.serve); this.plugin(serve); } if (cfg?.buildin?.jwt) { + log('jwt enable'); const jwt = new Jwt(cfg?.buildin?.jwt); this.plugin(jwt); } diff --git a/packages/app/src/load.ts b/packages/app/src/load.ts index e7c9e9b..5f5c0ee 100644 --- a/packages/app/src/load.ts +++ b/packages/app/src/load.ts @@ -12,7 +12,7 @@ export async function loadInitMiddleware(rpc?, m?) { export async function loadBuildinMiddlewaire(rpc?) { // const buildin = rpc.config.buildin; - // log(rpc.config); + log(rpc.config); // log(buildin); // const mw = await import('./mw'); // for (const key in buildin) { diff --git a/packages/client/src/__tests__/index.test.ts b/packages/client/src/__tests__/index.test.ts index f1b268d..7fcd8a6 100644 --- a/packages/client/src/__tests__/index.test.ts +++ b/packages/client/src/__tests__/index.test.ts @@ -36,7 +36,7 @@ describe('lib', () => { }); rpc.add({ - '/add': function (a: string, b: string) { + '/add': function (a: string) { return { a: a }; }, }); diff --git a/packages/core/src/__tests__/app.test.ts b/packages/core/src/__tests__/app.test.ts index b5f9280..0e378e2 100644 --- a/packages/core/src/__tests__/app.test.ts +++ b/packages/core/src/__tests__/app.test.ts @@ -32,7 +32,7 @@ describe('app', async () => { }); rpc.add({ - '/add': function (a: string, b: string) { + '/add': function (a: string) { return { a: a }; }, }); diff --git a/packages/core/src/__tests__/proxy.test.ts b/packages/core/src/__tests__/proxy.test.ts index 5e00487..9d684cd 100644 --- a/packages/core/src/__tests__/proxy.test.ts +++ b/packages/core/src/__tests__/proxy.test.ts @@ -1,4 +1,4 @@ -import debug from 'debug'; +// import debug from 'debug'; import supertest from 'supertest'; import { describe, expect, it, vi } from 'vitest'; diff --git a/packages/core/src/fn.ts b/packages/core/src/fn.ts index 9cfa67a..f38dbca 100644 --- a/packages/core/src/fn.ts +++ b/packages/core/src/fn.ts @@ -49,7 +49,7 @@ export class Fn extends Plugable { } default() { - return async (ctx, next) => { + return async (ctx) => { log('default'); ctx.body = '[fn plugin] no fn repsonse, please check your fn if exist'; log('default end'); diff --git a/packages/core/src/plugin.ts b/packages/core/src/plugin.ts index e8abbc8..0ece437 100644 --- a/packages/core/src/plugin.ts +++ b/packages/core/src/plugin.ts @@ -70,7 +70,7 @@ export class Plugable implements Strategy { pre() { return async (ctx, next) => { - log('pre'); + log('pre ' + ctx.path); await next(); log('pre end'); }; @@ -78,7 +78,7 @@ export class Plugable implements Strategy { post() { return async (ctx, next) => { - log('after'); + log('after ' + ctx.path); await next(); log('after end'); }; @@ -86,7 +86,7 @@ export class Plugable implements Strategy { process() { return async (ctx, next) => { - log('process default'); + log('process default ' + ctx.path); await next(); log('process default end'); }; diff --git a/packages/core/src/server.ts b/packages/core/src/server.ts index 5649c6c..906090c 100644 --- a/packages/core/src/server.ts +++ b/packages/core/src/server.ts @@ -13,7 +13,7 @@ export const LifeCycleConfig = { before: [], load: [], after: [], - default: async (ctx, next) => { + default: async (ctx) => { log('default'); ctx.body = '[core server] no middleware repsonse, please check your route'; log('default end'); diff --git a/packages/mount/src/__tests__/index.test.ts b/packages/mount/src/__tests__/index.test.ts index e0b5549..502d424 100644 --- a/packages/mount/src/__tests__/index.test.ts +++ b/packages/mount/src/__tests__/index.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from 'vitest'; -import mount from '../mount'; +// import mount from '../mount'; describe('lib', () => { it('should render lib', () => { - // expect(lib()).toBe('lib'); + expect('lib').toBe('lib'); }); }); From fe4348fa26f19c2867fe4c662871455e840abd96 Mon Sep 17 00:00:00 2001 From: npmstudy Date: Tue, 12 Dec 2023 16:08:47 +0800 Subject: [PATCH 101/101] chore: refact --- packages/app/src/__tests__/app.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/app/src/__tests__/app.test.ts b/packages/app/src/__tests__/app.test.ts index dbdc032..128a4b0 100644 --- a/packages/app/src/__tests__/app.test.ts +++ b/packages/app/src/__tests__/app.test.ts @@ -67,7 +67,7 @@ describe('app', async () => { }); rpc.add({ - '/add': function (a: string, b: string) { + '/add': function (a: string) { return { a: a }; }, });