phecda-server 4.1.1 → 4.1.2-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/h3/index.js.map +1 -1
- package/dist/server/h3/index.mjs.map +1 -1
- package/package.json +2 -1
- package/register/loader.mjs +118 -100
- package/register/unimport.mjs +15 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/server/h3/bind.ts"],"names":["defineRequestMiddleware","eventHandler","getQuery","getRequestHeaders","getRouterParams","readBody","setHeaders","setResponseStatus","bindApp","router","moduleMap","meta","options","globalGuards","globalInterceptors","route","plugins","isAopDepInject","guards","interceptors","APP_SYMBOL","prePlugin","event","MODULE_SYMBOL","META_SYMBOL","metaMap","Map","handleMeta","clear","item","tag","method","http","data","type","methodTag","set","createRoute","post","onRequest","Context","usePlugin","map","p","handler","body","strict","errorHandler","e","error","filterRecord","default","status","Array","isArray","BadRequestException","Promise","all","resolve","get","contextData","parallel","context","name","split","paramsType","handlers","params","filter","instance","useGuard","cache","useInterceptor","undefined","args","usePipe","key","pipe","pipeOpts","index","arg","reflect","funcData","usePostInterceptor","forEach","useFilter","i","header","some","resolveDep","ret","err","IS_DEV","globalThis","__PS_HMR__","push"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAASA,yBAAyBC,cAAcC,UAAUC,mBAAmBC,iBAAiBC,UAAUC,YAAYC,yBAAyB;AAsCtI,SAASC,QAAQC,QAAgB,EAAEC,WAAWC,KAAI,GAAyCC,UAAmB,CAAC,GAAG;AACvH,QAAM,EAAEC,cAAcC,oBAAoBC,OAAOC,QAAO,IAAK;IAAED,OAAO;IAAsBF,cAAc,CAAA;IAAIC,oBAAoB,CAAA;IAAIE,SAAS,CAAA;IAAI,GAAGJ;EAAQ;AAI9JK,iBAAeN,MAAM;IACnBK;IACAE,QAAQL;IACRM,cAAcL;EAChB,CAAA;AAICL,SAAeW,cAAc;IAAEV;IAAWC;EAAK;AAGhD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AkBmB,KAAAA;AACxB;gBACF;AACE0D,wBAAMnC;cACV;AAEA,qBAAO;gBAAEmC,KAAKS,WAAWT,KAAKJ,GAAAA;gBAAMC;gBAAMC;gBAAUF;gBAAK1C;gBAAM6C;gBAAOE,SAAShB,WAAWc;cAAO;YACnG,CAAA,CAAA;AAEAV,qBAASP,UAAUF;AACnB,kBAAMsB,WAAW,MAAMb,SAAStC,QAAO,GAAI2C,IAAAA;AAC3C,kBAAMgB,MAAM,MAAM5B,QAAQqB,mBAAmBD,QAAAA;AAE7C,mBAAOQ;UACT,SACO1C,GAAP;AACEkB,qBAASkB,QAAQxC,CAAAA,YAAWA,QAAQK,QAAQD,CAAAA,CAAAA;AAC5C,kBAAM2C,MAAM,MAAM7B,QAAQuB,UAAUrC,GAAGoB,MAAAA;AACvC7D,8BAAkBe,OAAOqE,IAAIvC,MAAM;AACnC,mBAAOuC;UACT;QACF;MACF,CAAA,CAAA;IACF;EACF;AA3JetD;AA6JfV,aAAAA;AACAU,cAAAA;AACA,MAAIuD,QAAQ;AACVC,eAAWC,YAAYC,KAAK,YAAY;AACtC9E,qBAAeN,MAAM;QACnBK;QACAE,QAAQL;QACRM,cAAcL;MAChB,CAAA;AACAa,iBAAAA;IACF,CAAA;EACF;AACF;AAzMgBnB","sourcesContent":["import { defineRequestMiddleware, eventHandler, getQuery, getRequestHeaders, getRouterParams, readBody, setHeaders, setResponseStatus } from 'h3'\nimport type { H3Event, Router } from 'h3'\nimport { resolveDep } from '../../helper'\nimport { APP_SYMBOL, IS_DEV, META_SYMBOL, MODULE_SYMBOL } from '../../common'\nimport type { Factory } from '../../core'\nimport { BadRequestException } from '../../exception'\nimport type { Meta } from '../../meta'\nimport { Context, isAopDepInject } from '../../context'\nimport { P } from '../../types'\n\nexport interface H3Ctx extends P.BaseContext {\n type: 'h3'\n event: H3Event\n\n parallel: boolean\n\n}\nexport interface Options {\n\n /**\n * 专用路由的值,默认为/__PHECDA_SERVER__,处理phecda-client发出的合并请求\n */\n route?: string\n /**\n * 全局守卫\n */\n globalGuards?: string[]\n /**\n * 全局拦截器\n */\n globalInterceptors?: string[]\n /**\n * 专用路由的中间件(work for merge request),全局中间件请在bindApp以外设置\n */\n plugins?: string[]\n\n}\n\nexport function bindApp(router: Router, { moduleMap, meta }: Awaited<ReturnType<typeof Factory>>, options: Options = {}) {\n const { globalGuards, globalInterceptors, route, plugins } = { route: '/__PHECDA_SERVER__', globalGuards: [], globalInterceptors: [], plugins: [], ...options } as Required<Options>\n\n\n\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInterceptors,\n });\n\n\n\n (router as any)[APP_SYMBOL] = { moduleMap, meta }\n\n\n const prePlugin=defineRequestMiddleware((event) => {\n (event as any)[MODULE_SYMBOL] = moduleMap;\n (event as any)[META_SYMBOL] = meta\n })\n const metaMap = new Map<string, Meta>()\n function handleMeta() {\n metaMap.clear()\n for (const item of meta) {\n const { tag, method, http } = item.data\n if (!http?.type)\n continue\n const methodTag = `${tag}-${method}`\n metaMap.set(methodTag, item)\n }\n }\n\n async function createRoute() {\n\n\n router.post(route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const body = await readBody(event, { strict: true })\n async function errorHandler(e: any) {\n const error = await Context.filterRecord.default(e)\n setResponseStatus(event, error.status)\n return error\n }\n \n if (!Array.isArray(body))\n return errorHandler(new BadRequestException('data format should be an array'))\n \n try {\n return Promise.all(body.map((item: any) => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const { tag } = item\n const meta = metaMap.get(tag)!\n if (!meta)\n return resolve(await Context.filterRecord.default(new BadRequestException(`\"${tag}\" doesn't exist`)))\n \n const contextData = {\n type: 'h3' as const,\n event,\n meta,\n moduleMap,\n parallel: true,\n tag\n }\n const context = new Context<H3Ctx>(contextData)\n const [name, method] = tag.split('-')\n const {\n paramsType,\n handlers,\n data: {\n params,\n guards,\n interceptors, filter,\n },\n } = metaMap.get(tag)!\n \n const instance = moduleMap.get(name)\n \n try {\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return resolve(cache)\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n return { arg: item.args[index], type, key, pipe, pipeOpts, index, reflect: paramsType[index] }\n })) as any\n instance.context = contextData\n const funcData = await moduleMap.get(name)[method](...args)\n resolve(await context.usePostInterceptor(funcData))\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n resolve(await context.useFilter(e, filter))\n }\n })\n }))\n }\n \n catch (e) {\n return errorHandler(e)\n }\n }\n }))\n\n\n\n for (const i of meta) {\n const { method, http, header, tag } = i.data\n\n if (!http?.type)\n continue\n\n const methodTag = `${tag}-${method}`\n\n const {\n paramsType,\n handlers,\n data: {\n interceptors,\n guards,\n params,\n plugins,\n filter,\n },\n } = metaMap.get(methodTag)!\n\n\n \n router[http.type](http.route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const instance = moduleMap.get(tag)!\n \n const contextData = {\n type: 'h3' as const,\n meta: i,\n event,\n moduleMap,\n parallel: false,\n tag: methodTag\n }\n const context = new Context<H3Ctx>(contextData)\n \n try {\n setHeaders(event, header)\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return cache\n \n const body = params.some(item => item.type === 'body') ? await readBody(event, { strict: true }) : undefined\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n let arg: any\n \n switch (type) {\n case 'params':\n arg = getRouterParams(event)\n break\n case 'query':\n arg = getQuery(event)\n break\n case 'header':\n arg = getRequestHeaders(event)\n break\n default:\n arg = body\n }\n \n return { arg: resolveDep(arg, key), pipe, pipeOpts, key, type, index, reflect: paramsType[index] }\n }))\n \n instance.context = contextData\n const funcData = await instance[method](...args)\n const ret = await context.usePostInterceptor(funcData)\n \n return ret\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n const err = await context.useFilter(e, filter)\n setResponseStatus(event, err.status)\n return err\n }\n },\n }))\n }\n }\n\n handleMeta()\n createRoute()\n if (IS_DEV) {\n globalThis.__PS_HMR__?.push(async () => {\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInterceptors,\n })\n handleMeta()\n })\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/server/h3/bind.ts"],"names":["defineRequestMiddleware","eventHandler","getQuery","getRequestHeaders","getRouterParams","readBody","setHeaders","setResponseStatus","bindApp","router","moduleMap","meta","options","globalGuards","globalInterceptors","route","plugins","isAopDepInject","guards","interceptors","APP_SYMBOL","prePlugin","event","MODULE_SYMBOL","META_SYMBOL","metaMap","Map","handleMeta","clear","item","tag","method","http","data","type","methodTag","set","createRoute","post","onRequest","Context","usePlugin","map","p","handler","body","strict","errorHandler","e","error","filterRecord","default","status","Array","isArray","BadRequestException","Promise","all","resolve","get","contextData","parallel","context","name","split","paramsType","handlers","params","filter","instance","useGuard","cache","useInterceptor","undefined","args","usePipe","key","pipe","pipeOpts","index","arg","reflect","funcData","usePostInterceptor","forEach","useFilter","i","header","some","resolveDep","ret","err","IS_DEV","globalThis","__PS_HMR__","push"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAASA,yBAAyBC,cAAcC,UAAUC,mBAAmBC,iBAAiBC,UAAUC,YAAYC,yBAAyB;AAqCtI,SAASC,QAAQC,QAAgB,EAAEC,WAAWC,KAAI,GAAyCC,UAAmB,CAAC,GAAG;AACvH,QAAM,EAAEC,cAAcC,oBAAoBC,OAAOC,QAAO,IAAK;IAAED,OAAO;IAAsBF,cAAc,CAAA;IAAIC,oBAAoB,CAAA;IAAIE,SAAS,CAAA;IAAI,GAAGJ;EAAQ;AAI9JK,iBAAeN,MAAM;IACnBK;IACAE,QAAQL;IACRM,cAAcL;EAChB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,SAASoB,KAAAA;AACf;gBACF,KAAK;AACH0D,wBAAM7E,kBAAkBmB,KAAAA;AACxB;gBACF;AACE0D,wBAAMnC;cACV;AAEA,qBAAO;gBAAEmC,KAAKS,WAAWT,KAAKJ,GAAAA;gBAAMC;gBAAMC;gBAAUF;gBAAK1C;gBAAM6C;gBAAOE,SAAShB,WAAWc;cAAO;YACnG,CAAA,CAAA;AAEAV,qBAASP,UAAUF;AACnB,kBAAMsB,WAAW,MAAMb,SAAStC,QAAO,GAAI2C,IAAAA;AAC3C,kBAAMgB,MAAM,MAAM5B,QAAQqB,mBAAmBD,QAAAA;AAE7C,mBAAOQ;UACT,SACO1C,GAAP;AACEkB,qBAASkB,QAAQxC,CAAAA,YAAWA,QAAQK,QAAQD,CAAAA,CAAAA;AAC5C,kBAAM2C,MAAM,MAAM7B,QAAQuB,UAAUrC,GAAGoB,MAAAA;AACvC7D,8BAAkBe,OAAOqE,IAAIvC,MAAM;AACnC,mBAAOuC;UACT;QACF;MACF,CAAA,CAAA;IACF;EACF;AA3JetD;AA6JfV,aAAAA;AACAU,cAAAA;AACA,MAAIuD,QAAQ;AACVC,eAAWC,YAAYC,KAAK,YAAY;AACtC9E,qBAAeN,MAAM;QACnBK;QACAE,QAAQL;QACRM,cAAcL;MAChB,CAAA;AACAa,iBAAAA;IACF,CAAA;EACF;AACF;AAzMgBnB","sourcesContent":["import { defineRequestMiddleware, eventHandler, getQuery, getRequestHeaders, getRouterParams, readBody, setHeaders, setResponseStatus } from 'h3'\nimport type { H3Event, Router } from 'h3'\nimport { resolveDep } from '../../helper'\nimport { APP_SYMBOL, IS_DEV, META_SYMBOL, MODULE_SYMBOL } from '../../common'\nimport type { Factory } from '../../core'\nimport { BadRequestException } from '../../exception'\nimport type { Meta } from '../../meta'\nimport { Context, isAopDepInject } from '../../context'\nimport { P } from '../../types'\n\nexport interface H3Ctx extends P.BaseContext {\n type: 'h3'\n event: H3Event\n parallel: boolean\n\n}\nexport interface Options {\n\n /**\n * 专用路由的值,默认为/__PHECDA_SERVER__,处理phecda-client发出的合并请求\n */\n route?: string\n /**\n * 全局守卫\n */\n globalGuards?: string[]\n /**\n * 全局拦截器\n */\n globalInterceptors?: string[]\n /**\n * 专用路由的中间件(work for merge request),全局中间件请在bindApp以外设置\n */\n plugins?: string[]\n\n}\n\nexport function bindApp(router: Router, { moduleMap, meta }: Awaited<ReturnType<typeof Factory>>, options: Options = {}) {\n const { globalGuards, globalInterceptors, route, plugins } = { route: '/__PHECDA_SERVER__', globalGuards: [], globalInterceptors: [], plugins: [], ...options } as Required<Options>\n\n\n\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInterceptors,\n });\n\n\n\n (router as any)[APP_SYMBOL] = { moduleMap, meta }\n\n\n const prePlugin=defineRequestMiddleware((event) => {\n (event as any)[MODULE_SYMBOL] = moduleMap;\n (event as any)[META_SYMBOL] = meta\n })\n const metaMap = new Map<string, Meta>()\n function handleMeta() {\n metaMap.clear()\n for (const item of meta) {\n const { tag, method, http } = item.data\n if (!http?.type)\n continue\n const methodTag = `${tag}-${method}`\n metaMap.set(methodTag, item)\n }\n }\n\n async function createRoute() {\n\n\n router.post(route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const body = await readBody(event, { strict: true })\n async function errorHandler(e: any) {\n const error = await Context.filterRecord.default(e)\n setResponseStatus(event, error.status)\n return error\n }\n \n if (!Array.isArray(body))\n return errorHandler(new BadRequestException('data format should be an array'))\n \n try {\n return Promise.all(body.map((item: any) => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const { tag } = item\n const meta = metaMap.get(tag)!\n if (!meta)\n return resolve(await Context.filterRecord.default(new BadRequestException(`\"${tag}\" doesn't exist`)))\n \n const contextData = {\n type: 'h3' as const,\n event,\n meta,\n moduleMap,\n parallel: true,\n tag\n }\n const context = new Context<H3Ctx>(contextData)\n const [name, method] = tag.split('-')\n const {\n paramsType,\n handlers,\n data: {\n params,\n guards,\n interceptors, filter,\n },\n } = metaMap.get(tag)!\n \n const instance = moduleMap.get(name)\n \n try {\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return resolve(cache)\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n return { arg: item.args[index], type, key, pipe, pipeOpts, index, reflect: paramsType[index] }\n })) as any\n instance.context = contextData\n const funcData = await moduleMap.get(name)[method](...args)\n resolve(await context.usePostInterceptor(funcData))\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n resolve(await context.useFilter(e, filter))\n }\n })\n }))\n }\n \n catch (e) {\n return errorHandler(e)\n }\n }\n }))\n\n\n\n for (const i of meta) {\n const { method, http, header, tag } = i.data\n\n if (!http?.type)\n continue\n\n const methodTag = `${tag}-${method}`\n\n const {\n paramsType,\n handlers,\n data: {\n interceptors,\n guards,\n params,\n plugins,\n filter,\n },\n } = metaMap.get(methodTag)!\n\n\n \n router[http.type](http.route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const instance = moduleMap.get(tag)!\n \n const contextData = {\n type: 'h3' as const,\n meta: i,\n event,\n moduleMap,\n parallel: false,\n tag: methodTag\n }\n const context = new Context<H3Ctx>(contextData)\n \n try {\n setHeaders(event, header)\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return cache\n \n const body = params.some(item => item.type === 'body') ? await readBody(event, { strict: true }) : undefined\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n let arg: any\n \n switch (type) {\n case 'params':\n arg = getRouterParams(event)\n break\n case 'query':\n arg = getQuery(event)\n break\n case 'header':\n arg = getRequestHeaders(event)\n break\n default:\n arg = body\n }\n \n return { arg: resolveDep(arg, key), pipe, pipeOpts, key, type, index, reflect: paramsType[index] }\n }))\n \n instance.context = contextData\n const funcData = await instance[method](...args)\n const ret = await context.usePostInterceptor(funcData)\n \n return ret\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n const err = await context.useFilter(e, filter)\n setResponseStatus(event, err.status)\n return err\n }\n },\n }))\n }\n }\n\n handleMeta()\n createRoute()\n if (IS_DEV) {\n globalThis.__PS_HMR__?.push(async () => {\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInterceptors,\n })\n handleMeta()\n })\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/server/h3/bind.ts"],"sourcesContent":["import { defineRequestMiddleware, eventHandler, getQuery, getRequestHeaders, getRouterParams, readBody, setHeaders, setResponseStatus } from 'h3'\nimport type { H3Event, Router } from 'h3'\nimport { resolveDep } from '../../helper'\nimport { APP_SYMBOL, IS_DEV, META_SYMBOL, MODULE_SYMBOL } from '../../common'\nimport type { Factory } from '../../core'\nimport { BadRequestException } from '../../exception'\nimport type { Meta } from '../../meta'\nimport { Context, isAopDepInject } from '../../context'\nimport { P } from '../../types'\n\nexport interface H3Ctx extends P.BaseContext {\n type: 'h3'\n event: H3Event\n\n parallel: boolean\n\n}\nexport interface Options {\n\n /**\n * 专用路由的值,默认为/__PHECDA_SERVER__,处理phecda-client发出的合并请求\n */\n route?: string\n /**\n * 全局守卫\n */\n globalGuards?: string[]\n /**\n * 全局拦截器\n */\n globalInterceptors?: string[]\n /**\n * 专用路由的中间件(work for merge request),全局中间件请在bindApp以外设置\n */\n plugins?: string[]\n\n}\n\nexport function bindApp(router: Router, { moduleMap, meta }: Awaited<ReturnType<typeof Factory>>, options: Options = {}) {\n const { globalGuards, globalInterceptors, route, plugins } = { route: '/__PHECDA_SERVER__', globalGuards: [], globalInterceptors: [], plugins: [], ...options } as Required<Options>\n\n\n\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInterceptors,\n });\n\n\n\n (router as any)[APP_SYMBOL] = { moduleMap, meta }\n\n\n const prePlugin=defineRequestMiddleware((event) => {\n (event as any)[MODULE_SYMBOL] = moduleMap;\n (event as any)[META_SYMBOL] = meta\n })\n const metaMap = new Map<string, Meta>()\n function handleMeta() {\n metaMap.clear()\n for (const item of meta) {\n const { tag, method, http } = item.data\n if (!http?.type)\n continue\n const methodTag = `${tag}-${method}`\n metaMap.set(methodTag, item)\n }\n }\n\n async function createRoute() {\n\n\n router.post(route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const body = await readBody(event, { strict: true })\n async function errorHandler(e: any) {\n const error = await Context.filterRecord.default(e)\n setResponseStatus(event, error.status)\n return error\n }\n \n if (!Array.isArray(body))\n return errorHandler(new BadRequestException('data format should be an array'))\n \n try {\n return Promise.all(body.map((item: any) => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const { tag } = item\n const meta = metaMap.get(tag)!\n if (!meta)\n return resolve(await Context.filterRecord.default(new BadRequestException(`\"${tag}\" doesn't exist`)))\n \n const contextData = {\n type: 'h3' as const,\n event,\n meta,\n moduleMap,\n parallel: true,\n tag\n }\n const context = new Context<H3Ctx>(contextData)\n const [name, method] = tag.split('-')\n const {\n paramsType,\n handlers,\n data: {\n params,\n guards,\n interceptors, filter,\n },\n } = metaMap.get(tag)!\n \n const instance = moduleMap.get(name)\n \n try {\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return resolve(cache)\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n return { arg: item.args[index], type, key, pipe, pipeOpts, index, reflect: paramsType[index] }\n })) as any\n instance.context = contextData\n const funcData = await moduleMap.get(name)[method](...args)\n resolve(await context.usePostInterceptor(funcData))\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n resolve(await context.useFilter(e, filter))\n }\n })\n }))\n }\n \n catch (e) {\n return errorHandler(e)\n }\n }\n }))\n\n\n\n for (const i of meta) {\n const { method, http, header, tag } = i.data\n\n if (!http?.type)\n continue\n\n const methodTag = `${tag}-${method}`\n\n const {\n paramsType,\n handlers,\n data: {\n interceptors,\n guards,\n params,\n plugins,\n filter,\n },\n } = metaMap.get(methodTag)!\n\n\n \n router[http.type](http.route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const instance = moduleMap.get(tag)!\n \n const contextData = {\n type: 'h3' as const,\n meta: i,\n event,\n moduleMap,\n parallel: false,\n tag: methodTag\n }\n const context = new Context<H3Ctx>(contextData)\n \n try {\n setHeaders(event, header)\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return cache\n \n const body = params.some(item => item.type === 'body') ? await readBody(event, { strict: true }) : undefined\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n let arg: any\n \n switch (type) {\n case 'params':\n arg = getRouterParams(event)\n break\n case 'query':\n arg = getQuery(event)\n break\n case 'header':\n arg = getRequestHeaders(event)\n break\n default:\n arg = body\n }\n \n return { arg: resolveDep(arg, key), pipe, pipeOpts, key, type, index, reflect: paramsType[index] }\n }))\n \n instance.context = contextData\n const funcData = await instance[method](...args)\n const ret = await context.usePostInterceptor(funcData)\n \n return ret\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n const err = await context.useFilter(e, filter)\n setResponseStatus(event, err.status)\n return err\n }\n },\n }))\n }\n }\n\n handleMeta()\n createRoute()\n if (IS_DEV) {\n globalThis.__PS_HMR__?.push(async () => {\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInterceptors,\n })\n handleMeta()\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAAA,SAASA,yBAAyBC,cAAcC,UAAUC,mBAAmBC,iBAAi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KK,SAAS,MAAA,IAAU,MAAMa,SAASzB,OAAO;cAAE0B,QAAQ;YAAK,CAAA,IAAK4B;AACnG,kBAAMC,OAAO,MAAMZ,QAAQa,QAAQR,OAAO3B,IAAI,CAAC,EAAET,MAAM6C,KAAKC,MAAMC,UAAUC,MAAK,MAAO;AACtF,kBAAIC;AAEJ,sBAAQjD,MAAAA;gBACN,KAAK;AACHiD,wBAAMU,gBAAgBvE,KAAAA;AACtB;gBACF,KAAK;AACH6D,wBAAMW,SAASxE,KAAAA;AACf;gBACF,KAAK;AACH6D,wBAAMY,kBAAkBzE,KAAAA;AACxB;gBACF;AACE6D,wBAAMrC;cACV;AAEA,qBAAO;gBAAEqC,KAAKa,WAAWb,KAAKJ,GAAAA;gBAAMC;gBAAMC;gBAAUF;gBAAK7C;gBAAMgD;gBAAOE,SAAShB,WAAWc;cAAO;YACnG,CAAA,CAAA;AAEAV,qBAASP,UAAUF;AACnB,kBAAMsB,WAAW,MAAMb,SAASzC,QAAO,GAAI8C,IAAAA;AAC3C,kBAAMoB,MAAM,MAAMhC,QAAQqB,mBAAmBD,QAAAA;AAE7C,mBAAOY;UACT,SACO/C,GAAP;AACEmB,qBAASkB,QAAQ1C,CAAAA,YAAWA,QAAQM,QAAQD,CAAAA,CAAAA;AAC5C,kBAAMgD,MAAM,MAAMjC,QAAQuB,UAAUtC,GAAGqB,MAAAA;AACvCjB,8BAAkBhC,OAAO4E,IAAI3C,MAAM;AACnC,mBAAO2C;UACT;QACF;MACF,CAAA,CAAA;IACF;EACF;AA3Je7D;AA6JfV,aAAAA;AACAU,cAAAA;AACA,MAAI8D,QAAQ;AACVC,eAAWC,YAAYC,KAAK,YAAY;AACtCtF,qBAAeN,MAAM;QACnBK;QACAE,QAAQL;QACRM,cAAcL;MAChB,CAAA;AACAc,iBAAAA;IACF,CAAA;EACF;AACF;AAzMgBpB;","names":["defineRequestMiddleware","eventHandler","getQuery","getRequestHeaders","getRouterParams","readBody","setHeaders","setResponseStatus","bindApp","router","moduleMap","meta","options","globalGuards","globalInterceptors","route","plugins","isAopDepInject","guards","interceptors","APP_SYMBOL","prePlugin","defineRequestMiddleware","event","MODULE_SYMBOL","META_SYMBOL","metaMap","Map","handleMeta","clear","item","tag","method","http","data","type","methodTag","set","createRoute","post","eventHandler","onRequest","Context","usePlugin","map","p","handler","body","readBody","strict","errorHandler","e","error","filterRecord","default","setResponseStatus","status","Array","isArray","BadRequestException","Promise","all","resolve","get","contextData","parallel","context","name","split","paramsType","handlers","params","filter","instance","useGuard","cache","useInterceptor","undefined","args","usePipe","key","pipe","pipeOpts","index","arg","reflect","funcData","usePostInterceptor","forEach","useFilter","i","header","setHeaders","some","getRouterParams","getQuery","getRequestHeaders","resolveDep","ret","err","IS_DEV","globalThis","__PS_HMR__","push"]}
|
|
1
|
+
{"version":3,"sources":["../../../src/server/h3/bind.ts"],"sourcesContent":["import { defineRequestMiddleware, eventHandler, getQuery, getRequestHeaders, getRouterParams, readBody, setHeaders, setResponseStatus } from 'h3'\nimport type { H3Event, Router } from 'h3'\nimport { resolveDep } from '../../helper'\nimport { APP_SYMBOL, IS_DEV, META_SYMBOL, MODULE_SYMBOL } from '../../common'\nimport type { Factory } from '../../core'\nimport { BadRequestException } from '../../exception'\nimport type { Meta } from '../../meta'\nimport { Context, isAopDepInject } from '../../context'\nimport { P } from '../../types'\n\nexport interface H3Ctx extends P.BaseContext {\n type: 'h3'\n event: H3Event\n parallel: boolean\n\n}\nexport interface Options {\n\n /**\n * 专用路由的值,默认为/__PHECDA_SERVER__,处理phecda-client发出的合并请求\n */\n route?: string\n /**\n * 全局守卫\n */\n globalGuards?: string[]\n /**\n * 全局拦截器\n */\n globalInterceptors?: string[]\n /**\n * 专用路由的中间件(work for merge request),全局中间件请在bindApp以外设置\n */\n plugins?: string[]\n\n}\n\nexport function bindApp(router: Router, { moduleMap, meta }: Awaited<ReturnType<typeof Factory>>, options: Options = {}) {\n const { globalGuards, globalInterceptors, route, plugins } = { route: '/__PHECDA_SERVER__', globalGuards: [], globalInterceptors: [], plugins: [], ...options } as Required<Options>\n\n\n\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInterceptors,\n });\n\n\n\n (router as any)[APP_SYMBOL] = { moduleMap, meta }\n\n\n const prePlugin=defineRequestMiddleware((event) => {\n (event as any)[MODULE_SYMBOL] = moduleMap;\n (event as any)[META_SYMBOL] = meta\n })\n const metaMap = new Map<string, Meta>()\n function handleMeta() {\n metaMap.clear()\n for (const item of meta) {\n const { tag, method, http } = item.data\n if (!http?.type)\n continue\n const methodTag = `${tag}-${method}`\n metaMap.set(methodTag, item)\n }\n }\n\n async function createRoute() {\n\n\n router.post(route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const body = await readBody(event, { strict: true })\n async function errorHandler(e: any) {\n const error = await Context.filterRecord.default(e)\n setResponseStatus(event, error.status)\n return error\n }\n \n if (!Array.isArray(body))\n return errorHandler(new BadRequestException('data format should be an array'))\n \n try {\n return Promise.all(body.map((item: any) => {\n // eslint-disable-next-line no-async-promise-executor\n return new Promise(async (resolve) => {\n const { tag } = item\n const meta = metaMap.get(tag)!\n if (!meta)\n return resolve(await Context.filterRecord.default(new BadRequestException(`\"${tag}\" doesn't exist`)))\n \n const contextData = {\n type: 'h3' as const,\n event,\n meta,\n moduleMap,\n parallel: true,\n tag\n }\n const context = new Context<H3Ctx>(contextData)\n const [name, method] = tag.split('-')\n const {\n paramsType,\n handlers,\n data: {\n params,\n guards,\n interceptors, filter,\n },\n } = metaMap.get(tag)!\n \n const instance = moduleMap.get(name)\n \n try {\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return resolve(cache)\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n return { arg: item.args[index], type, key, pipe, pipeOpts, index, reflect: paramsType[index] }\n })) as any\n instance.context = contextData\n const funcData = await moduleMap.get(name)[method](...args)\n resolve(await context.usePostInterceptor(funcData))\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n resolve(await context.useFilter(e, filter))\n }\n })\n }))\n }\n \n catch (e) {\n return errorHandler(e)\n }\n }\n }))\n\n\n\n for (const i of meta) {\n const { method, http, header, tag } = i.data\n\n if (!http?.type)\n continue\n\n const methodTag = `${tag}-${method}`\n\n const {\n paramsType,\n handlers,\n data: {\n interceptors,\n guards,\n params,\n plugins,\n filter,\n },\n } = metaMap.get(methodTag)!\n\n\n \n router[http.type](http.route, eventHandler({\n onRequest:[prePlugin,...Context.usePlugin(plugins).map((p)=>defineRequestMiddleware(p))],\n handler:async (event) => {\n const instance = moduleMap.get(tag)!\n \n const contextData = {\n type: 'h3' as const,\n meta: i,\n event,\n moduleMap,\n parallel: false,\n tag: methodTag\n }\n const context = new Context<H3Ctx>(contextData)\n \n try {\n setHeaders(event, header)\n await context.useGuard([...globalGuards, ...guards])\n const cache = await context.useInterceptor([...globalInterceptors, ...interceptors])\n if (cache !== undefined)\n return cache\n \n const body = params.some(item => item.type === 'body') ? await readBody(event, { strict: true }) : undefined\n const args = await context.usePipe(params.map(({ type, key, pipe, pipeOpts, index }) => {\n let arg: any\n \n switch (type) {\n case 'params':\n arg = getRouterParams(event)\n break\n case 'query':\n arg = getQuery(event)\n break\n case 'header':\n arg = getRequestHeaders(event)\n break\n default:\n arg = body\n }\n \n return { arg: resolveDep(arg, key), pipe, pipeOpts, key, type, index, reflect: paramsType[index] }\n }))\n \n instance.context = contextData\n const funcData = await instance[method](...args)\n const ret = await context.usePostInterceptor(funcData)\n \n return ret\n }\n catch (e: any) {\n handlers.forEach(handler => handler.error?.(e))\n const err = await context.useFilter(e, filter)\n setResponseStatus(event, err.status)\n return err\n }\n },\n }))\n }\n }\n\n handleMeta()\n createRoute()\n if (IS_DEV) {\n globalThis.__PS_HMR__?.push(async () => {\n isAopDepInject(meta, {\n plugins,\n guards: globalGuards,\n interceptors: globalInter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;IACF,CAAA;EACF;AACF;AAzMgBpB;","names":["defineRequestMiddleware","eventHandler","getQuery","getRequestHeaders","getRouterParams","readBody","setHeaders","setResponseStatus","bindApp","router","moduleMap","meta","options","globalGuards","globalInterceptors","route","plugins","isAopDepInject","guards","interceptors","APP_SYMBOL","prePlugin","defineRequestMiddleware","event","MODULE_SYMBOL","META_SYMBOL","metaMap","Map","handleMeta","clear","item","tag","method","http","data","type","methodTag","set","createRoute","post","eventHandler","onRequest","Context","usePlugin","map","p","handler","body","readBody","strict","errorHandler","e","error","filterRecord","default","setResponseStatus","status","Array","isArray","BadRequestException","Promise","all","resolve","get","contextData","parallel","context","name","split","paramsType","handlers","params","filter","instance","useGuard","cache","useInterceptor","undefined","args","usePipe","key","pipe","pipeOpts","index","arg","reflect","funcData","usePostInterceptor","forEach","useFilter","i","header","setHeaders","some","getRouterParams","getQuery","getRequestHeaders","resolveDep","ret","err","IS_DEV","globalThis","__PS_HMR__","push"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "phecda-server",
|
|
3
|
-
"version": "4.1.
|
|
3
|
+
"version": "4.1.2-alpha.0",
|
|
4
4
|
"description": "provide express middlewares, `nestjs` format",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"module": "dist/index.mjs",
|
|
@@ -106,6 +106,7 @@
|
|
|
106
106
|
"supertest": "^6.3.3",
|
|
107
107
|
"tsup": "^6.5.0",
|
|
108
108
|
"typescript": "^5.2.2",
|
|
109
|
+
"unimport": "^3.7.1",
|
|
109
110
|
"vite": "^4.0.0"
|
|
110
111
|
},
|
|
111
112
|
"dependencies": {
|
package/register/loader.mjs
CHANGED
|
@@ -1,184 +1,202 @@
|
|
|
1
|
-
import { fileURLToPath, pathToFileURL } from
|
|
2
|
-
import { watch } from
|
|
3
|
-
import { extname, isAbsolute, relative } from
|
|
4
|
-
import ts from
|
|
5
|
-
import { compile } from
|
|
6
|
-
|
|
1
|
+
import { fileURLToPath, pathToFileURL } from "url";
|
|
2
|
+
import { watch, writeFileSync } from "fs";
|
|
3
|
+
import { extname, isAbsolute, relative } from "path";
|
|
4
|
+
import ts from "typescript";
|
|
5
|
+
import { compile } from "./compile.mjs";
|
|
6
|
+
import { genUnImportRet } from "./unimport.mjs";
|
|
7
|
+
let port;
|
|
7
8
|
|
|
8
9
|
// this part is important or not?
|
|
9
|
-
const EXTENSIONS = [ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Mts]
|
|
10
|
+
const EXTENSIONS = [ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Mts];
|
|
10
11
|
const tsconfig = {
|
|
11
12
|
module: ts.ModuleKind.ESNext,
|
|
12
13
|
moduleResolution: ts.ModuleResolutionKind.NodeNext,
|
|
13
|
-
}
|
|
14
|
+
};
|
|
14
15
|
const moduleResolutionCache = ts.createModuleResolutionCache(
|
|
15
16
|
ts.sys.getCurrentDirectory(),
|
|
16
|
-
x => x,
|
|
17
|
-
tsconfig
|
|
18
|
-
)
|
|
17
|
+
(x) => x,
|
|
18
|
+
tsconfig
|
|
19
|
+
);
|
|
19
20
|
const host = {
|
|
20
21
|
fileExists: ts.sys.fileExists,
|
|
21
22
|
readFile: ts.sys.readFile,
|
|
22
|
-
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
let unimportRet;
|
|
23
26
|
|
|
24
27
|
export async function initialize(data) {
|
|
25
|
-
port = data.port
|
|
28
|
+
port = data.port;
|
|
29
|
+
|
|
30
|
+
unimportRet = await genUnImportRet();
|
|
31
|
+
|
|
32
|
+
if (unimportRet) {
|
|
33
|
+
writeFileSync("ps.d.ts", await unimportRet.generateTypeDeclarations());
|
|
34
|
+
}
|
|
26
35
|
}
|
|
27
36
|
|
|
28
|
-
const watchFiles = new Set()
|
|
29
|
-
const filesRecord = new Map()
|
|
30
|
-
const moduleGraph = {}
|
|
37
|
+
const watchFiles = new Set();
|
|
38
|
+
const filesRecord = new Map();
|
|
39
|
+
const moduleGraph = {};
|
|
31
40
|
|
|
32
|
-
let entryUrl
|
|
41
|
+
let entryUrl;
|
|
33
42
|
|
|
34
43
|
function addUrlToGraph(url, parent) {
|
|
35
|
-
if (!(url in moduleGraph))
|
|
36
|
-
moduleGraph[url] = new Set()
|
|
44
|
+
if (!(url in moduleGraph)) moduleGraph[url] = new Set();
|
|
37
45
|
|
|
38
|
-
moduleGraph[url].add(parent)
|
|
39
|
-
return url + (filesRecord.has(url) ? `?t=${filesRecord.get(url)}` :
|
|
46
|
+
moduleGraph[url].add(parent);
|
|
47
|
+
return url + (filesRecord.has(url) ? `?t=${filesRecord.get(url)}` : "");
|
|
40
48
|
}
|
|
41
49
|
|
|
42
50
|
export const resolve = async (specifier, context, nextResolve) => {
|
|
43
51
|
// entrypoint
|
|
44
52
|
if (!context.parentURL) {
|
|
45
|
-
entryUrl = specifier
|
|
53
|
+
entryUrl = specifier;
|
|
46
54
|
return {
|
|
47
|
-
format: EXTENSIONS.some(ext => specifier.endsWith(ext))
|
|
48
|
-
?
|
|
55
|
+
format: EXTENSIONS.some((ext) => specifier.endsWith(ext))
|
|
56
|
+
? "ts"
|
|
49
57
|
: undefined,
|
|
50
58
|
url: specifier,
|
|
51
59
|
shortCircuit: true,
|
|
52
|
-
}
|
|
60
|
+
};
|
|
53
61
|
}
|
|
54
|
-
if (/^file:\/\/\//.test(specifier) && extname(specifier) ===
|
|
55
|
-
const url = addUrlToGraph(specifier, context.parentURL.split(
|
|
62
|
+
if (/^file:\/\/\//.test(specifier) && extname(specifier) === ".ts") {
|
|
63
|
+
const url = addUrlToGraph(specifier, context.parentURL.split("?")[0]);
|
|
56
64
|
|
|
57
65
|
return {
|
|
58
|
-
format:
|
|
66
|
+
format: "ts",
|
|
59
67
|
url,
|
|
60
68
|
shortCircuit: true,
|
|
61
|
-
}
|
|
69
|
+
};
|
|
62
70
|
}
|
|
63
71
|
|
|
64
72
|
if (
|
|
65
|
-
context.parentURL.includes(
|
|
66
|
-
|
|
73
|
+
context.parentURL.includes("/node_modules/phecda-server") &&
|
|
74
|
+
isAbsolute(specifier)
|
|
67
75
|
) {
|
|
68
76
|
specifier = relative(fileURLToPath(entryUrl), specifier)
|
|
69
|
-
.replace(/\.ts$/,
|
|
70
|
-
.slice(1)
|
|
71
|
-
context.parentURL = entryUrl
|
|
77
|
+
.replace(/\.ts$/, "")
|
|
78
|
+
.slice(1);
|
|
79
|
+
context.parentURL = entryUrl;
|
|
72
80
|
}
|
|
73
81
|
// import/require from external library
|
|
74
|
-
if (context.parentURL.includes(
|
|
75
|
-
return nextResolve(specifier)
|
|
82
|
+
if (context.parentURL.includes("/node_modules/"))
|
|
83
|
+
return nextResolve(specifier);
|
|
76
84
|
|
|
77
85
|
const { resolvedModule } = ts.resolveModuleName(
|
|
78
86
|
specifier,
|
|
79
87
|
fileURLToPath(context.parentURL),
|
|
80
88
|
tsconfig,
|
|
81
89
|
host,
|
|
82
|
-
moduleResolutionCache
|
|
83
|
-
)
|
|
90
|
+
moduleResolutionCache
|
|
91
|
+
);
|
|
84
92
|
// import from local project to local project TS file
|
|
85
93
|
if (
|
|
86
|
-
resolvedModule
|
|
87
|
-
|
|
88
|
-
|
|
94
|
+
resolvedModule &&
|
|
95
|
+
!resolvedModule.resolvedFileName.includes("/node_modules/") &&
|
|
96
|
+
EXTENSIONS.includes(resolvedModule.extension)
|
|
89
97
|
) {
|
|
90
|
-
const url = addUrlToGraph(
|
|
98
|
+
const url = addUrlToGraph(
|
|
99
|
+
pathToFileURL(resolvedModule.resolvedFileName).href,
|
|
100
|
+
context.parentURL.split("?")[0]
|
|
101
|
+
);
|
|
91
102
|
|
|
92
103
|
return {
|
|
93
|
-
format:
|
|
104
|
+
format: "ts",
|
|
94
105
|
url,
|
|
95
106
|
shortCircuit: true,
|
|
96
|
-
}
|
|
107
|
+
};
|
|
97
108
|
}
|
|
98
|
-
return nextResolve(specifier)
|
|
99
|
-
}
|
|
109
|
+
return nextResolve(specifier);
|
|
110
|
+
};
|
|
100
111
|
|
|
101
112
|
export const load = async (url, context, nextLoad) => {
|
|
102
|
-
url = url.split(
|
|
113
|
+
url = url.split("?")[0];
|
|
103
114
|
if (
|
|
104
|
-
!url.includes(
|
|
105
|
-
|
|
106
|
-
|
|
115
|
+
!url.includes("/node_modules/") &&
|
|
116
|
+
url.startsWith("file://") &&
|
|
117
|
+
!watchFiles.has(url)
|
|
107
118
|
) {
|
|
108
|
-
watchFiles.add(url)
|
|
119
|
+
watchFiles.add(url);
|
|
109
120
|
|
|
110
121
|
watch(
|
|
111
122
|
fileURLToPath(url),
|
|
112
123
|
debounce((type) => {
|
|
113
|
-
if (type ===
|
|
124
|
+
if (type === "change") {
|
|
114
125
|
try {
|
|
115
|
-
const files = [...findTopScope(url, Date.now())].reverse()
|
|
126
|
+
const files = [...findTopScope(url, Date.now())].reverse();
|
|
116
127
|
port.postMessage(
|
|
117
128
|
JSON.stringify({
|
|
118
|
-
type:
|
|
129
|
+
type: "change",
|
|
119
130
|
files,
|
|
120
|
-
})
|
|
121
|
-
)
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
process.exit(3)
|
|
131
|
+
})
|
|
132
|
+
);
|
|
133
|
+
} catch (e) {
|
|
134
|
+
process.exit(3);
|
|
125
135
|
}
|
|
126
136
|
}
|
|
127
|
-
})
|
|
128
|
-
)
|
|
137
|
+
})
|
|
138
|
+
);
|
|
129
139
|
}
|
|
130
140
|
|
|
131
|
-
if (context.format ===
|
|
132
|
-
const { source } = await nextLoad(url, context)
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
141
|
+
if (context.format === "ts") {
|
|
142
|
+
const { source } = await nextLoad(url, context);
|
|
143
|
+
|
|
144
|
+
const code =
|
|
145
|
+
typeof source === "string" ? source : Buffer.from(source).toString();
|
|
146
|
+
const compiled = await compile(code, url);
|
|
147
|
+
if (unimportRet && isModuleFileUrl(url)) {
|
|
148
|
+
const { injectImports } = unimportRet;
|
|
149
|
+
return {
|
|
150
|
+
format: "module",
|
|
151
|
+
source: (await injectImports(compiled)).code,
|
|
152
|
+
shortCircuit: true,
|
|
153
|
+
};
|
|
154
|
+
}
|
|
136
155
|
return {
|
|
137
|
-
format:
|
|
156
|
+
format: "module",
|
|
138
157
|
source: compiled,
|
|
139
158
|
shortCircuit: true,
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
return nextLoad(url, context)
|
|
159
|
+
};
|
|
160
|
+
} else {
|
|
161
|
+
return nextLoad(url, context);
|
|
144
162
|
}
|
|
145
|
-
}
|
|
163
|
+
};
|
|
146
164
|
|
|
147
165
|
function findTopScope(url, time, modules = new Set()) {
|
|
148
|
-
filesRecord.set(url, time)
|
|
149
|
-
if (
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|| url.endsWith('.rpc.ts')
|
|
155
|
-
|| url.endsWith('.guard.ts')
|
|
156
|
-
|| url.endsWith('.interceptor.ts')
|
|
157
|
-
|| url.endsWith('.pipe.ts')
|
|
158
|
-
|| url.endsWith('.plugin.ts')
|
|
159
|
-
|| url.endsWith('.filter.ts')
|
|
160
|
-
|
|
161
|
-
) {
|
|
162
|
-
modules.add(fileURLToPath(url))
|
|
163
|
-
}
|
|
164
|
-
else {
|
|
165
|
-
if (!moduleGraph[url])
|
|
166
|
-
throw new Error('root file update')
|
|
167
|
-
for (const i of [...moduleGraph[url]]) findTopScope(i, time, modules)
|
|
166
|
+
filesRecord.set(url, time);
|
|
167
|
+
if (isModuleFileUrl(url)) {
|
|
168
|
+
modules.add(fileURLToPath(url));
|
|
169
|
+
} else {
|
|
170
|
+
if (!moduleGraph[url]) throw new Error("root file update");
|
|
171
|
+
for (const i of [...moduleGraph[url]]) findTopScope(i, time, modules);
|
|
168
172
|
}
|
|
169
173
|
|
|
170
|
-
return modules
|
|
174
|
+
return modules;
|
|
171
175
|
}
|
|
172
176
|
|
|
173
177
|
function debounce(cb, timeout = 500) {
|
|
174
|
-
let timer
|
|
178
|
+
let timer;
|
|
175
179
|
return (...args) => {
|
|
176
|
-
if (timer)
|
|
177
|
-
return
|
|
180
|
+
if (timer) return;
|
|
178
181
|
|
|
179
182
|
timer = setTimeout(() => {
|
|
180
|
-
cb(...args)
|
|
181
|
-
timer = undefined
|
|
182
|
-
}, timeout)
|
|
183
|
-
}
|
|
183
|
+
cb(...args);
|
|
184
|
+
timer = undefined;
|
|
185
|
+
}, timeout);
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
export function isModuleFileUrl(url) {
|
|
190
|
+
return (
|
|
191
|
+
url.endsWith(".controller.ts") ||
|
|
192
|
+
url.endsWith(".service.ts") ||
|
|
193
|
+
url.endsWith(".route.ts") ||
|
|
194
|
+
url.endsWith(".module.ts") ||
|
|
195
|
+
url.endsWith(".rpc.ts") ||
|
|
196
|
+
url.endsWith(".guard.ts") ||
|
|
197
|
+
url.endsWith(".interceptor.ts") ||
|
|
198
|
+
url.endsWith(".pipe.ts") ||
|
|
199
|
+
url.endsWith(".plugin.ts") ||
|
|
200
|
+
url.endsWith(".filter.ts")
|
|
201
|
+
);
|
|
184
202
|
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export async function genUnImportRet() {
|
|
2
|
+
try {
|
|
3
|
+
const allExports = Object.keys(await import("../dist/index.mjs"));
|
|
4
|
+
const { createUnimport } = await import("unimport");
|
|
5
|
+
|
|
6
|
+
return createUnimport({
|
|
7
|
+
imports: allExports.map((k) => {
|
|
8
|
+
return { name: k, from: "phecda-server" };
|
|
9
|
+
}),
|
|
10
|
+
});
|
|
11
|
+
} catch (e) {
|
|
12
|
+
console.log(e)
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|