phecda-server 4.0.0 → 4.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-UEH6FW5I.js → chunk-7E4FZ7TC.js} +13 -8
- package/dist/chunk-7E4FZ7TC.js.map +1 -0
- package/dist/{chunk-BP7CKHPK.js → chunk-B22W7BG7.js} +70 -19
- package/dist/chunk-B22W7BG7.js.map +1 -0
- package/dist/{chunk-MFGAP3PV.mjs → chunk-KVUJ3VJZ.mjs} +7 -2
- package/dist/{chunk-MFGAP3PV.mjs.map → chunk-KVUJ3VJZ.mjs.map} +1 -1
- package/dist/{chunk-3PXRNECS.mjs → chunk-O2H7ERZR.mjs} +67 -16
- package/dist/chunk-O2H7ERZR.mjs.map +1 -0
- package/dist/{chunk-FPN7NODB.mjs → chunk-PIRUVYEF.mjs} +4 -2
- package/dist/chunk-PIRUVYEF.mjs.map +1 -0
- package/dist/{chunk-62QDU5FJ.js → chunk-PU3LWJ2C.js} +4 -2
- package/dist/chunk-PU3LWJ2C.js.map +1 -0
- package/dist/index.d.ts +15 -8
- package/dist/index.js +43 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +37 -14
- package/dist/index.mjs.map +1 -1
- package/dist/rpc/rabbitmq/index.js +10 -5
- package/dist/rpc/rabbitmq/index.js.map +1 -1
- package/dist/rpc/rabbitmq/index.mjs +8 -3
- package/dist/rpc/rabbitmq/index.mjs.map +1 -1
- package/dist/rpc/redis/index.js +10 -5
- package/dist/rpc/redis/index.js.map +1 -1
- package/dist/rpc/redis/index.mjs +8 -3
- package/dist/rpc/redis/index.mjs.map +1 -1
- package/dist/server/express/index.js +22 -16
- package/dist/server/express/index.js.map +1 -1
- package/dist/server/express/index.mjs +9 -3
- package/dist/server/express/index.mjs.map +1 -1
- package/dist/server/fastify/index.js +20 -14
- package/dist/server/fastify/index.js.map +1 -1
- package/dist/server/fastify/index.mjs +9 -3
- package/dist/server/fastify/index.mjs.map +1 -1
- package/dist/server/h3/index.js +22 -16
- package/dist/server/h3/index.js.map +1 -1
- package/dist/server/h3/index.mjs +9 -3
- package/dist/server/h3/index.mjs.map +1 -1
- package/dist/test.js +4 -4
- package/dist/test.mjs +2 -2
- package/package.json +1 -1
- package/register/loader.mjs +0 -1
- package/dist/chunk-3PXRNECS.mjs.map +0 -1
- package/dist/chunk-62QDU5FJ.js.map +0 -1
- package/dist/chunk-BP7CKHPK.js.map +0 -1
- package/dist/chunk-FPN7NODB.mjs.map +0 -1
- package/dist/chunk-UEH6FW5I.js.map +0 -1
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
|
|
4
4
|
|
|
5
|
-
var
|
|
5
|
+
var _chunkPU3LWJ2Cjs = require('./chunk-PU3LWJ2C.js');
|
|
6
6
|
|
|
7
7
|
|
|
8
8
|
var _chunkIIGNGFDCjs = require('./chunk-IIGNGFDC.js');
|
|
@@ -123,6 +123,11 @@ async function Factory(Modules, opts = {}) {
|
|
|
123
123
|
const { http, rpc } = opts;
|
|
124
124
|
_phecdacore.injectProperty.call(void 0, "watcher", ({ eventName, instance, key, options }) => {
|
|
125
125
|
const fn = typeof instance[key] === "function" ? instance[key].bind(instance) : (v) => instance[key] = v;
|
|
126
|
+
if (!instance[_chunkPU3LWJ2Cjs.UNMOUNT_SYMBOL])
|
|
127
|
+
instance[_chunkPU3LWJ2Cjs.UNMOUNT_SYMBOL] = [];
|
|
128
|
+
instance[_chunkPU3LWJ2Cjs.UNMOUNT_SYMBOL].push(() => {
|
|
129
|
+
emitter.off(eventName, fn);
|
|
130
|
+
});
|
|
126
131
|
if (_optionalChain([options, 'optionalAccess', _2 => _2.once]))
|
|
127
132
|
emitter.once(eventName, fn);
|
|
128
133
|
else
|
|
@@ -134,11 +139,11 @@ async function Factory(Modules, opts = {}) {
|
|
|
134
139
|
return;
|
|
135
140
|
debug(`update module "${tag}"`);
|
|
136
141
|
const instance = moduleMap.get(tag);
|
|
137
|
-
if (_optionalChain([instance, 'optionalAccess', _5 => _5[
|
|
138
|
-
for (const cb of instance[
|
|
142
|
+
if (_optionalChain([instance, 'optionalAccess', _5 => _5[_chunkPU3LWJ2Cjs.UNMOUNT_SYMBOL]])) {
|
|
143
|
+
for (const cb of instance[_chunkPU3LWJ2Cjs.UNMOUNT_SYMBOL])
|
|
139
144
|
await cb();
|
|
140
145
|
}
|
|
141
|
-
|
|
146
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `Module ${_picocolors2.default.yellow(`[${tag}]`)} unmount`);
|
|
142
147
|
moduleMap.delete(tag);
|
|
143
148
|
constructorMap.delete(tag);
|
|
144
149
|
for (let i = meta.length - 1; i >= 0; i--) {
|
|
@@ -170,7 +175,7 @@ async function Factory(Modules, opts = {}) {
|
|
|
170
175
|
throw new Error(`exist Circular-Dependency or Multiple modules with the same name/tag [tag] ${tag}--[module] ${Module}`);
|
|
171
176
|
if (constructorMap.get(tag) !== Module && !constructorSet.has(Module)) {
|
|
172
177
|
constructorSet.add(Module);
|
|
173
|
-
|
|
178
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `Synonym module: Module taged "${tag}" has been loaded before, so phecda-server won't load Module "${Module.name}"`, "warn");
|
|
174
179
|
}
|
|
175
180
|
return {
|
|
176
181
|
instance,
|
|
@@ -194,7 +199,7 @@ async function Factory(Modules, opts = {}) {
|
|
|
194
199
|
meta.push(...getMetaFromInstance(instance, tag, Module.name));
|
|
195
200
|
await _phecdacore.registerAsync.call(void 0, instance);
|
|
196
201
|
moduleMap.set(tag, instance);
|
|
197
|
-
|
|
202
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `Module ${_picocolors2.default.yellow(`[${tag}]`)} mount"`);
|
|
198
203
|
constructorMap.set(tag, Module);
|
|
199
204
|
return {
|
|
200
205
|
instance,
|
|
@@ -211,7 +216,7 @@ async function Factory(Modules, opts = {}) {
|
|
|
211
216
|
}
|
|
212
217
|
_chunkIIGNGFDCjs.__name.call(void 0, writeCode, "writeCode");
|
|
213
218
|
writeCode();
|
|
214
|
-
if (
|
|
219
|
+
if (_chunkPU3LWJ2Cjs.IS_DEV) {
|
|
215
220
|
globalThis.__PS_HMR__ = async (file) => {
|
|
216
221
|
debug(`reload file ${file}`);
|
|
217
222
|
const module = await Promise.resolve().then(() => require(file));
|
|
@@ -318,4 +323,4 @@ _chunkIIGNGFDCjs.__name.call(void 0, initState, "initState");
|
|
|
318
323
|
|
|
319
324
|
|
|
320
325
|
exports.Meta = Meta; exports.generateRPCCode = generateRPCCode; exports.generateHTTPCode = generateHTTPCode; exports.Injectable = Injectable; exports.emitter = emitter; exports.Factory = Factory;
|
|
321
|
-
//# sourceMappingURL=chunk-
|
|
326
|
+
//# sourceMappingURL=chunk-7E4FZ7TC.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/meta.ts","../src/compiler/rpc.ts","../src/compiler/http.ts","../src/core.ts"],"names":["Meta","data","handlers","paramsType","constructor","Compiler","classMap","getContent","content","name","Object","values","reduce","p","c","addMethod","args","rpc","method","tag","type","isEvent","generateRPCCode","meta","compiler","i","http","params","url","route","replace","_","js","key","generateHTTPCode","fs","EventEmitter","Empty","getExposeKey","getHandler","getState","injectProperty","isPhecda","registerAsync","Debug","pc","Injectable","target","debug","emitter","Factory","Modules","opts","moduleMap","Map","constructorMap","constructorSet","WeakSet","moduleGraph","eventName","instance","options","fn","bind","v","UNMOUNT_SYMBOL","push","off","once","on","update","Module","prototype","__TAG__","has","get","cb","log","yellow","delete","length","splice","newModule","buildNestModule","forEach","module","set","paramtypes","getParamTypes","Error","add","undefined","paramtypesInstances","sub","subTag","Set","getMetaFromInstance","writeCode","promises","writeFile","map","item","IS_DEV","globalThis","__PS_HMR__","file","__PS_WRITEMETA__","vars","filter","baseState","initState","state","unshift","index","define","header","plugins","guards","interceptors","Reflect","getMetadata"],"mappings":";;;;;;;;;;AAEO,IAAMA,OAAN,MAAMA;EACQC;EAAqBC;EAA8BC;EAAtEC,YAAmBH,MAAqB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I,CAACH,MAAMI;AACTJ,UAAMI,SAAS,CAAC;AAClB,MAAI,CAACJ,MAAMK;AACTL,UAAMK,UAAU,CAAA;AAClB,MAAI,CAACL,MAAMM;AACTN,UAAMM,SAAS,CAAA;AACjB,MAAI,CAACN,MAAMO;AACTP,UAAMO,eAAe,CAAA;AACzB;AAXSR","sourcesContent":["import type { P } from './types'\n\nexport class Meta {\n constructor(public data: P.Meta, public handlers: P.Handler[], public paramsType: any[]) {\n\n }\n}\n","import type { P } from '../types'\n\nclass Compiler {\n classMap: Record<string, { [key: string]: string }> = {}\n constructor() { }\n\n getContent() {\n let content = ''\n\n for (const name in this.classMap) {\n content += `\n export class ${name}{\n ${Object.values(this.classMap[name]).reduce((p, c) => p + c)}\n }`\n }\n return content\n }\n\n addMethod(args: P.Meta) {\n const {\n rpc, name, method, tag,\n } = args\n if (!rpc || !rpc.type)\n return\n if (!this.classMap[name])\n this.classMap[name] = {}\n this.classMap[name][method] = `\n ${method}(){\n return {tag:'${tag}-${method}',isEvent:${!!rpc.isEvent},rpc:[${rpc.type.reduce((p, c) => {\n return `${p}\"${c}\",`\n }, '')}]}\n\n }\n `\n }\n}\n\nexport function generateRPCCode(meta: P.Meta[]) {\n const compiler = new Compiler()\n\n for (const i of meta)\n compiler.addMethod(i)\n return compiler.getContent()\n}\n","import type { P } from '../types'\n\nclass Compiler {\n classMap: Record<string, { [key: string]: string }> = {}\n constructor() { }\n\n getContent() {\n let content = ''\n\n for (const name in this.classMap) {\n content += `\n export class ${name}{\n ${Object.values(this.classMap[name]).reduce((p, c) => p + c)}\n }`\n }\n return content\n }\n\n // createRequest() {\n // let content = 'import {useC} from \\'phecda-server\\'\\n'\n // for (const name in this.classMap)\n // content += `export const {${Object.keys(this.classMap[name]).join(',')}}=useC(${name})\\n`\n // return content\n // }\n\n addMethod(args: P.Meta) {\n const {\n http, name, method, params, tag,\n } = args\n if (!http)\n return\n const url = http.route.replace(/\\/\\:([^\\/]*)/g, (_, js) => `/{{${js}}}`)\n if (!this.classMap[name])\n this.classMap[name] = {}\n this.classMap[name][method] = `\n ${method}(...args){\nconst ret={tag:\"${tag}-${method}\",body:{},headers:{},query:{},params:{},method:\"${http.type}\",url:\"${url}\",args}\n\n${params.reduce((p, c, i) => `${p}ret.${c.type}${c.key ? `['${c.key}']` : ''}=args[${i}]\\n${c.type === 'params' ? `ret.url=ret.url.replace('{{${c.key}}}',args[${i}])` : ''}\\n`, '')}\nreturn ret\n }\n `\n }\n}\n\nexport function generateHTTPCode(meta: P.Meta[]) {\n const compiler = new Compiler()\n\n for (const i of meta)\n compiler.addMethod(i)\n return compiler.getContent()\n}\n","import 'reflect-metadata'\nimport fs from 'fs'\nimport EventEmitter from 'node:events'\nimport type { Phecda } from 'phecda-core'\nimport { Empty, getExposeKey, getHandler, getState, injectProperty, isPhecda, registerAsync } from 'phecda-core'\nimport Debug from 'debug'\nimport pc from 'picocolors'\nimport type { Construct, Emitter, P } from './types'\nimport { Meta } from './meta'\nimport { log } from './utils'\nimport { IS_DEV, UNMOUNT_SYMBOL } from './common'\nimport { generateHTTPCode, generateRPCCode } from './compiler'\nexport function Injectable() {\n return (target: any) => Empty(target)\n}\nconst debug = Debug('phecda-server')\n// TODO: support both emitter types and origin emitter type in future\nexport const emitter: Emitter = new EventEmitter() as any\n\nexport async function Factory(Modules: (new (...args: any) => any)[], opts: {\n\n // HTTP generate code path\n http?: string\n // rpc generate code path\n rpc?: string\n} = {}) {\n const moduleMap = new Map<string, InstanceType<Construct>>()\n const meta: Meta[] = []\n const constructorMap = new Map()\n\n // only work for warn\n const constructorSet = new WeakSet()\n const moduleGraph = new Map<string, Set<string>>()\n const { http, rpc } = opts\n injectProperty('watcher', ({ eventName, instance, key, options }: { eventName: string; instance: any; key: string; options?: { once: boolean } }) => {\n const fn = typeof instance[key] === 'function' ? instance[key].bind(instance) : (v: any) => instance[key] = v\n\n // work for hmr\n if (!instance[UNMOUNT_SYMBOL])\n instance[UNMOUNT_SYMBOL] = []\n\n instance[UNMOUNT_SYMBOL].push(() => {\n (emitter as any).off(eventName, fn)\n })\n\n if (options?.once)\n (emitter as any).once(eventName, fn)\n\n else\n (emitter as any).on(eventName, fn)\n })\n\n async function update(Module: Construct) {\n const tag = Module.prototype?.__TAG__ || Module.name\n if (!moduleMap.has(tag))\n return\n debug(`update module \"${tag}\"`)\n\n const instance = moduleMap.get(tag)\n\n if (instance?.[UNMOUNT_SYMBOL]) {\n for (const cb of instance[UNMOUNT_SYMBOL])\n await cb()\n }\n log(`Module ${pc.yellow(`[${tag}]`)} unmount`)\n moduleMap.delete(tag)\n constructorMap.delete(tag)\n for (let i = meta.length - 1; i >= 0; i--) {\n if (meta[i].data.tag === tag)\n meta.splice(i, 1)\n }\n\n const { instance: newModule } = await buildNestModule(Module)\n if (moduleGraph.has(tag)) {\n [...moduleGraph.get(tag)!].forEach((tag) => {\n const module = moduleMap.get(tag)\n for (const key in module) {\n if (module[key] === instance)\n module[key] = newModule\n }\n })\n }\n\n moduleMap.set(tag, newModule)\n }\n async function buildNestModule(Module: Construct) {\n const paramtypes = getParamTypes(Module) as Construct[]\n let instance: InstanceType<Construct>\n const tag = Module.prototype?.__TAG__ || Module.name\n if (moduleMap.has(tag)) {\n instance = moduleMap.get(tag)\n if (!instance)\n throw new Error(`exist Circular-Dependency or Multiple modules with the same name/tag [tag] ${tag}--[module] ${Module}`)\n\n if (constructorMap.get(tag) !== Module && !constructorSet.has(Module)) {\n constructorSet.add(Module)// a module will only warn once\n log(`Synonym module: Module taged \"${tag}\" has been loaded before, so phecda-server won't load Module \"${Module.name}\"`, 'warn')\n }\n return { instance, tag }\n }\n moduleMap.set(tag, undefined)\n if (paramtypes) {\n const paramtypesInstances = [] as any[]\n for (const i in paramtypes) {\n const { instance: sub, tag: subTag } = await buildNestModule(paramtypes[i])\n paramtypesInstances[i] = sub\n if (!moduleGraph.has(subTag))\n moduleGraph.set(subTag, new Set())\n moduleGraph.get(subTag)!.add(tag)\n }\n instance = new Module(...paramtypesInstances)\n }\n else {\n instance = new Module()\n }\n meta.push(...getMetaFromInstance(instance, tag, Module.name))\n await registerAsync(instance)\n moduleMap.set(tag, instance)\n log(`Module ${pc.yellow(`[${tag}]`)} mount\"`)\n constructorMap.set(tag, Module)\n return { instance, tag }\n }\n\n for (const Module of Modules)\n await buildNestModule(Module)\n\n function writeCode() {\n debug('write code')\n\n http && fs.promises.writeFile(http, generateHTTPCode(meta.map(item => item.data)))\n rpc && fs.promises.writeFile(rpc, generateRPCCode(meta.map(item => item.data)))\n }\n\n writeCode()\n if (IS_DEV) {\n // @ts-expect-error globalThis\n globalThis.__PS_HMR__ = async (file: string) => {\n debug(`reload file ${file}`)\n const module = await import(file)\n for (const i in module) {\n if (isPhecda(module[i]))\n await update(module[i])\n }\n }\n // @ts-expect-error globalThis\n globalThis.__PS_WRITEMETA__ = writeCode\n }\n\n return {\n moduleMap,\n meta,\n constructorMap,\n update,\n }\n}\n\nfunction getMetaFromInstance(instance: Phecda, tag: string, name: string) {\n const vars = getExposeKey(instance).filter(item => item !== '__CLASS')\n const baseState = (getState(instance, '__CLASS') || {}) as P.Meta\n initState(baseState)\n\n return vars.map((i) => {\n const meta = {} as P.Meta\n const state = (getState(instance, i) || {}) as P.Meta\n initState(state)\n if (state.http) {\n meta.http = {\n route: (baseState.http?.route || '') + (state.http.route),\n type: state.http.type,\n }\n }\n if (baseState.rpc)\n meta.rpc = baseState.rpc\n if (state.rpc) {\n meta.rpc = {\n ...meta.rpc,\n ...state.rpc,\n }\n }\n\n meta.name = name\n meta.tag = tag\n meta.method = i as string\n const params = [] as any[]\n for (const i of state.params || []) {\n params.unshift(i)\n if (i.index === 0)\n break\n }\n\n meta.params = params\n meta.define = { ...baseState.define, ...state.define }\n meta.header = { ...baseState.header, ...state.header }\n meta.plugins = [...new Set([...baseState.plugins, ...state.plugins])]\n meta.guards = [...new Set([...baseState.guards, ...state.guards])]\n meta.interceptors = [...new Set([...baseState.interceptors, ...state.interceptors])]\n\n return new Meta(meta as unknown as P.Meta, getHandler(instance, i), getParamTypes(instance, i as string) || [])\n })\n}\n\nfunction getParamTypes(Module: any, key?: string | symbol) {\n return Reflect.getMetadata('design:paramtypes', Module, key!)\n}\n\nfunction initState(state: any) {\n if (!state.define)\n state.define = {}\n if (!state.header)\n state.header = {}\n if (!state.plugins)\n state.plugins = []\n if (!state.guards)\n state.guards = []\n if (!state.interceptors)\n state.interceptors = []\n}\n"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); var _class;
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _class;
|
|
2
2
|
|
|
3
3
|
|
|
4
|
-
|
|
4
|
+
|
|
5
|
+
var _chunkPU3LWJ2Cjs = require('./chunk-PU3LWJ2C.js');
|
|
5
6
|
|
|
6
7
|
|
|
7
8
|
|
|
@@ -163,14 +164,17 @@ var FrameworkException = class extends Exception {
|
|
|
163
164
|
};
|
|
164
165
|
_chunkIIGNGFDCjs.__name.call(void 0, FrameworkException, "FrameworkException");
|
|
165
166
|
|
|
167
|
+
// src/context.ts
|
|
168
|
+
var _picocolors = require('picocolors'); var _picocolors2 = _interopRequireDefault(_picocolors);
|
|
169
|
+
|
|
166
170
|
// src/filter.ts
|
|
167
171
|
var defaultFilter = /* @__PURE__ */ _chunkIIGNGFDCjs.__name.call(void 0, (e) => {
|
|
168
172
|
if (!(e instanceof Exception)) {
|
|
169
|
-
|
|
173
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, e.message, "error");
|
|
170
174
|
console.error(e.stack);
|
|
171
175
|
e = new UndefinedException(e.message || e);
|
|
172
176
|
} else {
|
|
173
|
-
|
|
177
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `[${e.constructor.name}] ${e.message}`, "error");
|
|
174
178
|
console.error(e.stack);
|
|
175
179
|
}
|
|
176
180
|
return e.data;
|
|
@@ -191,7 +195,7 @@ var Histroy = (_class = class {constructor() { _class.prototype.__init.call(this
|
|
|
191
195
|
_chunkIIGNGFDCjs.__name.call(void 0, Histroy, "Histroy");
|
|
192
196
|
|
|
193
197
|
// src/context.ts
|
|
194
|
-
var
|
|
198
|
+
var guardRecord = {};
|
|
195
199
|
var _Context = class {
|
|
196
200
|
|
|
197
201
|
|
|
@@ -203,11 +207,17 @@ var _Context = class {
|
|
|
203
207
|
this.tag = tag;
|
|
204
208
|
this.data = data;
|
|
205
209
|
this.history = new Histroy();
|
|
206
|
-
if (
|
|
210
|
+
if (_chunkPU3LWJ2Cjs.IS_DEV)
|
|
207
211
|
data._context = this;
|
|
208
212
|
}
|
|
209
213
|
usePipe(args) {
|
|
210
214
|
return Promise.all(args.map((item) => {
|
|
215
|
+
if (item.pipe && !_Context.pipeRecord[item.pipe]) {
|
|
216
|
+
if (_chunkPU3LWJ2Cjs.IS_STRICT)
|
|
217
|
+
throw new FrameworkException(`can't find pipe named '${item.pipe}'`);
|
|
218
|
+
else
|
|
219
|
+
return _Context.pipeRecord.default(item, this.tag, this.data);
|
|
220
|
+
}
|
|
211
221
|
return _Context.pipeRecord[item.pipe || "default"](item, this.tag, this.data);
|
|
212
222
|
}));
|
|
213
223
|
}
|
|
@@ -217,12 +227,12 @@ var _Context = class {
|
|
|
217
227
|
async useGuard(guards) {
|
|
218
228
|
for (const guard of guards) {
|
|
219
229
|
if (this.history.record(guard, "guard")) {
|
|
220
|
-
if (!(guard in _Context.
|
|
221
|
-
if (
|
|
230
|
+
if (!(guard in _Context.guardRecord)) {
|
|
231
|
+
if (_chunkPU3LWJ2Cjs.IS_STRICT)
|
|
222
232
|
throw new FrameworkException(`can't find guard named '${guard}'`);
|
|
223
233
|
continue;
|
|
224
234
|
}
|
|
225
|
-
if (!await _Context.
|
|
235
|
+
if (!await _Context.guardRecord[guard](this.tag, this.data))
|
|
226
236
|
throw new ForbiddenException(`Guard exception--${guard}`);
|
|
227
237
|
}
|
|
228
238
|
}
|
|
@@ -236,12 +246,12 @@ var _Context = class {
|
|
|
236
246
|
const ret = [];
|
|
237
247
|
for (const interceptor of interceptors) {
|
|
238
248
|
if (this.history.record(interceptor, "interceptor")) {
|
|
239
|
-
if (!(interceptor in _Context.
|
|
240
|
-
if (
|
|
249
|
+
if (!(interceptor in _Context.interceptorRecord)) {
|
|
250
|
+
if (_chunkPU3LWJ2Cjs.IS_STRICT)
|
|
241
251
|
throw new FrameworkException(`can't find interceptor named '${interceptor}'`);
|
|
242
252
|
continue;
|
|
243
253
|
}
|
|
244
|
-
const postInterceptor = await _Context.
|
|
254
|
+
const postInterceptor = await _Context.interceptorRecord[interceptor](this.tag, this.data);
|
|
245
255
|
if (postInterceptor !== void 0) {
|
|
246
256
|
if (typeof postInterceptor === "function")
|
|
247
257
|
ret.push(postInterceptor);
|
|
@@ -256,7 +266,7 @@ var _Context = class {
|
|
|
256
266
|
const ret = [];
|
|
257
267
|
for (const m of plugins) {
|
|
258
268
|
if (!(m in _Context.pluginRecord)) {
|
|
259
|
-
if (
|
|
269
|
+
if (_chunkPU3LWJ2Cjs.IS_STRICT)
|
|
260
270
|
throw new FrameworkException(`can't find middleware named '${m}'`);
|
|
261
271
|
continue;
|
|
262
272
|
}
|
|
@@ -271,8 +281,8 @@ _chunkIIGNGFDCjs.__publicField.call(void 0, Context, "filter", defaultFilter);
|
|
|
271
281
|
_chunkIIGNGFDCjs.__publicField.call(void 0, Context, "pipeRecord", {
|
|
272
282
|
default: defaultPipe
|
|
273
283
|
});
|
|
274
|
-
_chunkIIGNGFDCjs.__publicField.call(void 0, Context, "
|
|
275
|
-
_chunkIIGNGFDCjs.__publicField.call(void 0, Context, "
|
|
284
|
+
_chunkIIGNGFDCjs.__publicField.call(void 0, Context, "guardRecord", {});
|
|
285
|
+
_chunkIIGNGFDCjs.__publicField.call(void 0, Context, "interceptorRecord", {});
|
|
276
286
|
_chunkIIGNGFDCjs.__publicField.call(void 0, Context, "pluginRecord", {});
|
|
277
287
|
function addPlugin(key, handler) {
|
|
278
288
|
Context.pluginRecord[key] = handler;
|
|
@@ -287,13 +297,54 @@ function setFilter(filter) {
|
|
|
287
297
|
}
|
|
288
298
|
_chunkIIGNGFDCjs.__name.call(void 0, setFilter, "setFilter");
|
|
289
299
|
function addGuard(key, handler) {
|
|
290
|
-
Context.
|
|
300
|
+
Context.guardRecord[key] = handler;
|
|
291
301
|
}
|
|
292
302
|
_chunkIIGNGFDCjs.__name.call(void 0, addGuard, "addGuard");
|
|
293
303
|
function addInterceptor(key, handler) {
|
|
294
|
-
Context.
|
|
304
|
+
Context.interceptorRecord[key] = handler;
|
|
295
305
|
}
|
|
296
306
|
_chunkIIGNGFDCjs.__name.call(void 0, addInterceptor, "addInterceptor");
|
|
307
|
+
function isAopDepInject(meta, { guards, interceptors, plugins } = {}) {
|
|
308
|
+
const pluginSet = new Set(plugins);
|
|
309
|
+
const guardSet = new Set(guards);
|
|
310
|
+
const interceptorSet = new Set(interceptors);
|
|
311
|
+
const pipeSet = /* @__PURE__ */ new Set();
|
|
312
|
+
meta.forEach(({ data }) => {
|
|
313
|
+
data.interceptors.forEach((i) => interceptorSet.add(i));
|
|
314
|
+
data.guards.forEach((i) => guardSet.add(i));
|
|
315
|
+
data.plugins.forEach((i) => pluginSet.add(i));
|
|
316
|
+
data.params.forEach((i) => {
|
|
317
|
+
if (i.pipe)
|
|
318
|
+
pipeSet.add(i.pipe);
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
[
|
|
322
|
+
...pluginSet
|
|
323
|
+
].forEach((i) => {
|
|
324
|
+
if (!Context.pluginRecord[i])
|
|
325
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `${_picocolors2.default.white(`Plugin [${i}]`)} doesn't exist`, "warn");
|
|
326
|
+
});
|
|
327
|
+
[
|
|
328
|
+
...guardSet
|
|
329
|
+
].forEach((i) => {
|
|
330
|
+
if (!Context.guardRecord[i])
|
|
331
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `${_picocolors2.default.red(`Guard [${i}]`)} doesn't exist`, "warn");
|
|
332
|
+
});
|
|
333
|
+
[
|
|
334
|
+
...interceptorSet
|
|
335
|
+
].forEach((i) => {
|
|
336
|
+
if (!Context.interceptorRecord[i])
|
|
337
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `${_picocolors2.default.cyan(`Interceptor [${i}]`)} doesn't exist`, "warn");
|
|
338
|
+
});
|
|
339
|
+
[
|
|
340
|
+
...pipeSet
|
|
341
|
+
].forEach((i) => {
|
|
342
|
+
if (!Context.pipeRecord[i])
|
|
343
|
+
_chunkPU3LWJ2Cjs.log.call(void 0, `${_picocolors2.default.blue(`Pipe [${i}]`)} doesn't exist`, "warn");
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
_chunkIIGNGFDCjs.__name.call(void 0, isAopDepInject, "isAopDepInject");
|
|
347
|
+
|
|
297
348
|
|
|
298
349
|
|
|
299
350
|
|
|
@@ -320,5 +371,5 @@ _chunkIIGNGFDCjs.__name.call(void 0, addInterceptor, "addInterceptor");
|
|
|
320
371
|
|
|
321
372
|
|
|
322
373
|
|
|
323
|
-
exports.Exception = Exception; exports.ValidateException = ValidateException; exports.defaultPipe = defaultPipe; exports.UndefinedException = UndefinedException; exports.ForbiddenException = ForbiddenException; exports.BadRequestException = BadRequestException; exports.NotFoundException = NotFoundException; exports.ConflictException = ConflictException; exports.BadGatewayException = BadGatewayException; exports.InvalidInputException = InvalidInputException; exports.UnsupportedMediaTypeException = UnsupportedMediaTypeException; exports.PayloadLargeException = PayloadLargeException; exports.TimeoutException = TimeoutException; exports.UnauthorizedException = UnauthorizedException; exports.ServiceUnavailableException = ServiceUnavailableException; exports.FrameworkException = FrameworkException; exports.defaultFilter = defaultFilter; exports.
|
|
324
|
-
//# sourceMappingURL=chunk-
|
|
374
|
+
exports.Exception = Exception; exports.ValidateException = ValidateException; exports.defaultPipe = defaultPipe; exports.UndefinedException = UndefinedException; exports.ForbiddenException = ForbiddenException; exports.BadRequestException = BadRequestException; exports.NotFoundException = NotFoundException; exports.ConflictException = ConflictException; exports.BadGatewayException = BadGatewayException; exports.InvalidInputException = InvalidInputException; exports.UnsupportedMediaTypeException = UnsupportedMediaTypeException; exports.PayloadLargeException = PayloadLargeException; exports.TimeoutException = TimeoutException; exports.UnauthorizedException = UnauthorizedException; exports.ServiceUnavailableException = ServiceUnavailableException; exports.FrameworkException = FrameworkException; exports.defaultFilter = defaultFilter; exports.guardRecord = guardRecord; exports.Context = Context; exports.addPlugin = addPlugin; exports.addPipe = addPipe; exports.setFilter = setFilter; exports.addGuard = addGuard; exports.addInterceptor = addInterceptor; exports.isAopDepInject = isAopDepInject;
|
|
375
|
+
//# sourceMappingURL=chunk-B22W7BG7.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/exception/base.ts","../src/exception/validate.ts","../src/pipe.ts","../src/exception/undefine.ts","../src/exception/forbidden.ts","../src/exception/bad-request.ts","../src/exception/not-found.ts","../src/exception/conflict.ts","../src/exception/bad-gateway.ts","../src/exception/invalid-input.ts","../src/exception/media-type.ts","../src/exception/payload-large.ts","../src/exception/timeout.ts","../src/exception/unauthorized.ts","../src/exception/unavailable-service.ts","../src/exception/framework.ts","../src/context.ts","../src/filter.ts","../src/history.ts"],"names":["Exception","Error","message","status","description","constructor","data","error","ValidateException","isPhecda","plainToClass","transformClass","defaultPipe","arg","reflect","index","instance","err","length","Number","Boolean","includes","Object","is","NaN","UndefinedException","ForbiddenException","BadRequestException","NotFoundException","ConflictException","BadGatewayException","InvalidInputException","UnsupportedMediaTypeException","PayloadLargeException","TimeoutException","UnauthorizedException","ServiceUnavailableException","FrameworkException","pc","defaultFilter","e","log","console","stack","name","Histroy","guard","interceptor","record","type","push","guardRecord","Context","tag","method","params","history","postInterceptors","IS_DEV","_context","usePipe","args","Promise","all","map","item","pipe","pipeRecord","IS_STRICT","default","useFilter","filter","useGuard","guards","usePostInterceptor","ret","cb","useInterceptor","interceptors","interceptorRecord","postInterceptor","undefined","usePlugin","plugins","m","pluginRecord","addPlugin","key","handler","addPipe","setFilter","addGuard","addInterceptor","isAopDepInject","meta","pluginSet","Set","guardSet","interceptorSet","pipeSet","forEach","i","add","white","red","cyan","blue"],"mappings":";;;;;;;;;;;AAAO,IAAMA,YAAN,cAAwBC,MAAAA;EACVC;EAAwBC;EAAuBC;EAAlEC,YAAmBH,SAAwBC,QAAuBC,cAAc,kBAAkB;AAChG,UAAMF,OAAAA;mBADWA;kBAAwBC;uBAAuBC;EAElE;EAEA,IAAIE,OAAO;AACT,WAAO;MAAEJ,SAAS,KAAKA;MAASE,aAAa,KAAKA;MAAaD,QAAQ,KAAKA;MAAQI,OAAO;IAAK;EAClG;AACF;AARaP;;;ACEN,IAAMQ,oBAAN,cAAgCR,UAAAA;EACrCK,YAAYH,SAAiB;AAC3B,UAAMA,SAAS,KAAK,oBAAA;EACtB;AACF;AAJaM;;;ACFb,SAASC,UAAUC,cAAcC,sBAAsB;AAKhD,IAAMC,cAAsB,8BAAO,EAAEC,KAAKC,SAASC,MAAK,MAAY;AACzE,MAAIN,SAASK,OAAAA,GAAU;AACrB,UAAME,WAAWN,aAAaI,SAASD,GAAAA;AACvC,UAAMI,MAAM,MAAMN,eAAeK,QAAAA;AACjC,QAAIC,IAAIC,SAAS;AACf,YAAM,IAAIV,kBAAkBS,IAAI,EAAE;AAEpCJ,UAAMG;EACR,OACK;AACH,QAAI;MAACG;MAAQC;MAASC,SAASP,OAAAA,GAAU;AACvCD,YAAMC,QAAQD,GAAAA;AAEd,UAAIC,YAAYK,UAAUG,OAAOC,GAAGV,KAAKW,GAAAA;AACvC,cAAM,IAAIhB,kBAAkB,aAAaW,OAAOJ,KAAAA,IAAS,sBAAsB;IACnF;EACF;AACA,SAAOF;AACT,GAlBmC;;;ACH5B,IAAMY,qBAAN,cAAiCzB,UAAAA;EACtCK,YAAYH,SAAiB;AAC3B,UAAMA,SAAS,KAAK,iBAAA;EACtB;AACF;AAJauB;;;ACAN,IAAMC,qBAAN,cAAiC1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AAAA,CAAAA;AACtC/F,SAAK6E,QAAQiB,QAAQC,CAAAA,MAAKN,UAAUO,IAAID,CAAAA,CAAAA;AACxC/F,SAAKiD,OAAO6C,QAAQ,CAACC,MAAM;AACzB,UAAIA,EAAEnC;AACJiC,gBAAQG,IAAID,EAAEnC,IAAI;IACtB,CAAA;EACF,CAAA;AAEA;OAAI6B;IAAWK,QAAQ,CAACC,MAAM;AAC5B,QAAI,CAACjD,QAAQiC,aAAagB;AACxB5D,UAAI,GAAGH,GAAGiE,MAAM,WAAWF,IAAI,mBAAmB,MAAA;EACtD,CAAA;AACA;OAAIJ;IAAUG,QAAQ,CAACC,MAAM;AAC3B,QAAI,CAACjD,QAAQD,YAAYkD;AACvB5D,UAAI,GAAGH,GAAGkE,IAAI,UAAUH,IAAI,mBAAmB,MAAA;EACnD,CAAA;AACA;OAAIH;IAAgBE,QAAQ,CAACC,MAAM;AACjC,QAAI,CAACjD,QAAQ2B,kBAAkBsB;AAC7B5D,UAAI,GAAGH,GAAGmE,KAAK,gBAAgBJ,IAAI,mBAAmB,MAAA;EAC1D,CAAA;AACA;OAAIF;IAASC,QAAQ,CAACC,MAAM;AAC1B,QAAI,CAACjD,QAAQe,WAAWkC;AACtB5D,UAAI,GAAGH,GAAGoE,KAAK,SAASL,IAAI,mBAAmB,MAAA;EACnD,CAAA;AACF;AApCgBR","sourcesContent":["export class Exception extends Error {\n constructor(public message: string, public status: number, public description = 'Http exception') {\n super(message)\n }\n\n get data() {\n return { message: this.message, description: this.description, status: this.status, error: true }\n }\n}\n","import { Exception } from './base'\n\nexport class ValidateException extends Exception {\n constructor(message: string) {\n super(message, 400, 'Validate exception')\n }\n}\n","import { isPhecda, plainToClass, transformClass } from 'phecda-core'\nimport { ValidateException } from './exception/validate'\n\nimport type { P } from './types'\n\nexport const defaultPipe: P.Pipe = async ({ arg, reflect, index }: any) => {\n if (isPhecda(reflect)) {\n const instance = plainToClass(reflect, arg)\n const err = await transformClass(instance)\n if (err.length > 0)\n throw new ValidateException(err[0])\n\n arg = instance\n }\n else {\n if ([Number, Boolean].includes(reflect)) {\n arg = reflect(arg)\n\n if (reflect === Number && Object.is(arg, NaN))\n throw new ValidateException(`parameter ${Number(index) + 1} should be a number`)\n }\n }\n return arg\n}\n","import { Exception } from './base'\n\nexport class UndefinedException extends Exception {\n constructor(message: string) {\n super(message, 500, 'Undefined error')\n }\n}\n","import { Exception } from './base'\n\nexport class ForbiddenException extends Exception {\n constructor(message: string) {\n super(message, 403, 'Forbidden resource')\n }\n}\n","import { Exception } from './base'\n\nexport class BadRequestException extends Exception {\n constructor(message: string) {\n super(message, 400, 'Bad Request')\n }\n}\n","import { Exception } from './base'\n\nexport class NotFoundException extends Exception {\n constructor(message: string) {\n super(message, 404, 'Not Found')\n }\n}\n","import { Exception } from './base'\n\nexport class ConflictException extends Exception {\n constructor(message: string) {\n super(message, 409, 'Conflict')\n }\n}\n","import { Exception } from './base'\n\nexport class BadGatewayException extends Exception {\n constructor(message: string) {\n super(message, 502, 'Bad Gatrway')\n }\n}\n","import { Exception } from './base'\n\nexport class InvalidInputException extends Exception {\n constructor(message: string) {\n super(message, 502, 'Invalid Input')\n }\n}\n","import { Exception } from './base'\n\nexport class UnsupportedMediaTypeException extends Exception {\n constructor(message: string) {\n super(message, 415, 'Unsupported Media Type')\n }\n}\n","import { Exception } from './base'\n\nexport class PayloadLargeException extends Exception {\n constructor(message: string) {\n super(message, 413, 'Payload Too Large')\n }\n}\n","import { Exception } from './base'\n\nexport class TimeoutException extends Exception {\n constructor(message: string) {\n super(message, 408, 'Request Timeout',\n )\n }\n}\n","import { Exception } from './base'\n\nexport class UnauthorizedException extends Exception {\n constructor(message: string) {\n super(message, 401, 'Unauthorized')\n }\n}\n","import { Exception } from './base'\n\nexport class ServiceUnavailableException extends Exception {\n constructor(message: string) {\n super(message, 503, 'Service Unavailable')\n }\n}\n","import { Exception } from './base'\n\nexport class FrameworkException extends Exception {\n constructor(message: string) {\n super(`[phecda-server] ${message}`, 500, 'Framework Error')\n }\n}\n","import pc from 'picocolors'\nimport { defaultPipe } from './pipe'\nimport { ForbiddenException, FrameworkException } from './exception'\nimport { defaultFilter } from './filter'\nimport { Histroy } from './history'\nimport type { P } from './types'\nimport { IS_DEV, IS_STRICT } from './common'\nimport type { Meta } from './meta'\nimport { log } from './utils'\nexport const guardRecord = {} as Record<string, P.Guard>\n\nexport class Context<Data = any> {\n method: string\n params: string[]\n history = new Histroy()\n\n static filter: P.Filter = defaultFilter\n static pipeRecord: Record<string, P.Pipe> = {\n default: defaultPipe,\n }\n\n static guardRecord: Record<string, P.Guard> = {}\n static interceptorRecord: Record<string, P.Interceptor> = {}\n\n static pluginRecord: Record<string, any> = {}\n postInterceptors: Function[]\n\n constructor(public tag: string, public data: Data) {\n if (IS_DEV)\n // @ts-expect-error work for debug\n data._context = this\n }\n\n usePipe(args: { arg: any; pipe?: string; pipeOpts?: any; type: string; key: string; index: number; reflect: any }[]) {\n return Promise.all(args.map((item) => {\n if (item.pipe && !Context.pipeRecord[item.pipe]) {\n if (IS_STRICT)\n throw new FrameworkException(`can't find pipe named '${item.pipe}'`)\n\n else\n return Context.pipeRecord.default(item, this.tag, this.data)\n }\n\n return Context.pipeRecord[item.pipe || 'default'](item, this.tag, this.data)\n }))\n }\n\n useFilter(arg: any) {\n return Context.filter(arg, this.tag, this.data)\n }\n\n async useGuard(guards: string[]) {\n for (const guard of guards) {\n if (this.history.record(guard, 'guard')) {\n if (!(guard in Context.guardRecord)) {\n if (IS_STRICT)\n throw new FrameworkException(`can't find guard named '${guard}'`)\n continue\n }\n if (!await Context.guardRecord[guard](this.tag, this.data))\n throw new ForbiddenException(`Guard exception--${guard}`)\n }\n }\n }\n\n async usePostInterceptor(ret: any) {\n for (const cb of this.postInterceptors)\n ret = await cb(ret) || ret\n\n return ret\n }\n\n async useInterceptor(interceptors: string[]) {\n const ret = []\n for (const interceptor of interceptors) {\n if (this.history.record(interceptor, 'interceptor')) {\n if (!(interceptor in Context.interceptorRecord)) {\n if (IS_STRICT)\n throw new FrameworkException(`can't find interceptor named '${interceptor}'`)\n\n continue\n }\n const postInterceptor = await Context.interceptorRecord[interceptor](this.tag, this.data)\n if (postInterceptor !== undefined) {\n if (typeof postInterceptor === 'function')\n ret.push(postInterceptor)\n\n else\n return postInterceptor\n }\n }\n }\n this.postInterceptors = ret\n }\n\n static usePlugin(plugins: string[]) {\n const ret = []\n for (const m of plugins) {\n if (!(m in Context.pluginRecord)) {\n if (IS_STRICT)\n throw new FrameworkException(`can't find middleware named '${m}'`)\n\n continue\n }\n ret.push(Context.pluginRecord[m])\n }\n return ret as any[]\n }\n}\nexport function addPlugin<C>(key: string, handler: C) {\n Context.pluginRecord[key] = handler\n}\n\nexport function addPipe(key: string, pipe: P.Pipe) {\n Context.pipeRecord[key] = pipe\n}\n\nexport function setFilter(filter: P.Filter) {\n Context.filter = filter\n}\n\nexport function addGuard(key: string, handler: P.Guard) {\n Context.guardRecord[key] = handler\n}\n\nexport function addInterceptor(key: string, handler: P.Interceptor) {\n Context.interceptorRecord[key] = handler\n}\n\nexport function isAopDepInject(meta: Meta[], { guards, interceptors, plugins }: {\n guards?: string[]\n interceptors?: string[]\n plugins?: string[]\n} = {}) {\n const pluginSet = new Set<string>(plugins)\n\n const guardSet = new Set<string>(guards)\n const interceptorSet = new Set<string>(interceptors)\n const pipeSet = new Set<string>()\n meta.forEach(({ data }) => {\n data.interceptors.forEach(i => interceptorSet.add(i))\n data.guards.forEach(i => guardSet.add(i))\n data.plugins.forEach(i => pluginSet.add(i))\n data.params.forEach((i) => {\n if (i.pipe)\n pipeSet.add(i.pipe)\n })\n });\n\n [...pluginSet].forEach((i) => {\n if (!Context.pluginRecord[i])\n log(`${pc.white(`Plugin [${i}]`)} doesn't exist`, 'warn')\n });\n [...guardSet].forEach((i) => {\n if (!Context.guardRecord[i])\n log(`${pc.red(`Guard [${i}]`)} doesn't exist`, 'warn')\n });\n [...interceptorSet].forEach((i) => {\n if (!Context.interceptorRecord[i])\n log(`${pc.cyan(`Interceptor [${i}]`)} doesn't exist`, 'warn')\n });\n [...pipeSet].forEach((i) => {\n if (!Context.pipeRecord[i])\n log(`${pc.blue(`Pipe [${i}]`)} doesn't exist`, 'warn')\n })\n}\n","import { Exception, UndefinedException } from './exception'\nimport type { P } from './types'\nimport { log } from './utils'\n\nexport const defaultFilter: P.Filter = (e: any) => {\n if (!(e instanceof Exception)) {\n log(e.message, 'error')\n console.error(e.stack)\n e = new UndefinedException(e.message || e)\n }\n else {\n log(`[${e.constructor.name}] ${e.message}`, 'error')\n console.error(e.stack)\n }\n\n return e.data\n}\n","export class Histroy {\n guard: string[] = []\n interceptor: string[] = []\n record(name: string, type: 'guard' | 'interceptor') {\n if (!this[type].includes(name)) {\n this[type].push(name)\n return true\n }\n return false\n }\n}\n"]}
|
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
IS_DEV,
|
|
3
3
|
UNMOUNT_SYMBOL,
|
|
4
4
|
log
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-PIRUVYEF.mjs";
|
|
6
6
|
import {
|
|
7
7
|
__name
|
|
8
8
|
} from "./chunk-Q4FA4TAV.mjs";
|
|
@@ -123,6 +123,11 @@ async function Factory(Modules, opts = {}) {
|
|
|
123
123
|
const { http, rpc } = opts;
|
|
124
124
|
injectProperty("watcher", ({ eventName, instance, key, options }) => {
|
|
125
125
|
const fn = typeof instance[key] === "function" ? instance[key].bind(instance) : (v) => instance[key] = v;
|
|
126
|
+
if (!instance[UNMOUNT_SYMBOL])
|
|
127
|
+
instance[UNMOUNT_SYMBOL] = [];
|
|
128
|
+
instance[UNMOUNT_SYMBOL].push(() => {
|
|
129
|
+
emitter.off(eventName, fn);
|
|
130
|
+
});
|
|
126
131
|
if (options?.once)
|
|
127
132
|
emitter.once(eventName, fn);
|
|
128
133
|
else
|
|
@@ -318,4 +323,4 @@ export {
|
|
|
318
323
|
emitter,
|
|
319
324
|
Factory
|
|
320
325
|
};
|
|
321
|
-
//# sourceMappingURL=chunk-
|
|
326
|
+
//# sourceMappingURL=chunk-KVUJ3VJZ.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/meta.ts","../src/compiler/rpc.ts","../src/compiler/http.ts","../src/core.ts"],"sourcesContent":["import type { P } from './types'\n\nexport class Meta {\n constructor(public data: P.Meta, public handlers: P.Handler[], public paramsType: any[]) {\n\n }\n}\n","import type { P } from '../types'\n\nclass Compiler {\n classMap: Record<string, { [key: string]: string }> = {}\n constructor() { }\n\n getContent() {\n let content = ''\n\n for (const name in this.classMap) {\n content += `\n export class ${name}{\n ${Object.values(this.classMap[name]).reduce((p, c) => p + c)}\n }`\n }\n return content\n }\n\n addMethod(args: P.Meta) {\n const {\n rpc, name, method, tag,\n } = args\n if (!rpc || !rpc.type)\n return\n if (!this.classMap[name])\n this.classMap[name] = {}\n this.classMap[name][method] = `\n ${method}(){\n return {tag:'${tag}-${method}',isEvent:${!!rpc.isEvent},rpc:[${rpc.type.reduce((p, c) => {\n return `${p}\"${c}\",`\n }, '')}]}\n\n }\n `\n }\n}\n\nexport function generateRPCCode(meta: P.Meta[]) {\n const compiler = new Compiler()\n\n for (const i of meta)\n compiler.addMethod(i)\n return compiler.getContent()\n}\n","import type { P } from '../types'\n\nclass Compiler {\n classMap: Record<string, { [key: string]: string }> = {}\n constructor() { }\n\n getContent() {\n let content = ''\n\n for (const name in this.classMap) {\n content += `\n export class ${name}{\n ${Object.values(this.classMap[name]).reduce((p, c) => p + c)}\n }`\n }\n return content\n }\n\n // createRequest() {\n // let content = 'import {useC} from \\'phecda-server\\'\\n'\n // for (const name in this.classMap)\n // content += `export const {${Object.keys(this.classMap[name]).join(',')}}=useC(${name})\\n`\n // return content\n // }\n\n addMethod(args: P.Meta) {\n const {\n http, name, method, params, tag,\n } = args\n if (!http)\n return\n const url = http.route.replace(/\\/\\:([^\\/]*)/g, (_, js) => `/{{${js}}}`)\n if (!this.classMap[name])\n this.classMap[name] = {}\n this.classMap[name][method] = `\n ${method}(...args){\nconst ret={tag:\"${tag}-${method}\",body:{},headers:{},query:{},params:{},method:\"${http.type}\",url:\"${url}\",args}\n\n${params.reduce((p, c, i) => `${p}ret.${c.type}${c.key ? `['${c.key}']` : ''}=args[${i}]\\n${c.type === 'params' ? `ret.url=ret.url.replace('{{${c.key}}}',args[${i}])` : ''}\\n`, '')}\nreturn ret\n }\n `\n }\n}\n\nexport function generateHTTPCode(meta: P.Meta[]) {\n const compiler = new Compiler()\n\n for (const i of meta)\n compiler.addMethod(i)\n return compiler.getContent()\n}\n","import 'reflect-metadata'\nimport fs from 'fs'\nimport EventEmitter from 'node:events'\nimport type { Phecda } from 'phecda-core'\nimport { Empty, getExposeKey, getHandler, getState, injectProperty, isPhecda, registerAsync } from 'phecda-core'\nimport Debug from 'debug'\nimport pc from 'picocolors'\nimport type { Construct, Emitter, P } from './types'\nimport { Meta } from './meta'\nimport { log } from './utils'\nimport { IS_DEV, UNMOUNT_SYMBOL } from './common'\nimport { generateHTTPCode, generateRPCCode } from './compiler'\nexport function Injectable() {\n return (target: any) => Empty(target)\n}\nconst debug = Debug('phecda-server')\n// TODO: support both emitter types and origin emitter type in future\nexport const emitter: Emitter = new EventEmitter() as any\n\nexport async function Factory(Modules: (new (...args: any) => any)[], opts: {\n\n // HTTP generate code path\n http?: string\n // rpc generate code path\n rpc?: string\n} = {}) {\n const moduleMap = new Map<string, InstanceType<Construct>>()\n const meta: Meta[] = []\n const constructorMap = new Map()\n\n // only work for warn\n const constructorSet = new WeakSet()\n const moduleGraph = new Map<string, Set<string>>()\n const { http, rpc } = opts\n injectProperty('watcher', ({ eventName, instance, key, options }: { eventName: string; instance: any; key: string; options?: { once: boolean } }) => {\n const fn = typeof instance[key] === 'function' ? instance[key].bind(instance) : (v: any) => instance[key] = v\n\n if (options?.once)\n (emitter as any).once(eventName, fn)\n\n else\n (emitter as any).on(eventName, fn)\n })\n\n async function update(Module: Construct) {\n const tag = Module.prototype?.__TAG__ || Module.name\n if (!moduleMap.has(tag))\n return\n debug(`update module \"${tag}\"`)\n\n const instance = moduleMap.get(tag)\n\n if (instance?.[UNMOUNT_SYMBOL]) {\n for (const cb of instance[UNMOUNT_SYMBOL])\n await cb()\n }\n log(`Module ${pc.yellow(`[${tag}]`)} unmount`)\n moduleMap.delete(tag)\n constructorMap.delete(tag)\n for (let i = meta.length - 1; i >= 0; i--) {\n if (meta[i].data.tag === tag)\n meta.splice(i, 1)\n }\n\n const { instance: newModule } = await buildNestModule(Module)\n if (moduleGraph.has(tag)) {\n [...moduleGraph.get(tag)!].forEach((tag) => {\n const module = moduleMap.get(tag)\n for (const key in module) {\n if (module[key] === instance)\n module[key] = newModule\n }\n })\n }\n\n moduleMap.set(tag, newModule)\n }\n async function buildNestModule(Module: Construct) {\n const paramtypes = getParamTypes(Module) as Construct[]\n let instance: InstanceType<Construct>\n const tag = Module.prototype?.__TAG__ || Module.name\n if (moduleMap.has(tag)) {\n instance = moduleMap.get(tag)\n if (!instance)\n throw new Error(`exist Circular-Dependency or Multiple modules with the same name/tag [tag] ${tag}--[module] ${Module}`)\n\n if (constructorMap.get(tag) !== Module && !constructorSet.has(Module)) {\n constructorSet.add(Module)// a module will only warn once\n log(`Synonym module: Module taged \"${tag}\" has been loaded before, so phecda-server won't load Module \"${Module.name}\"`, 'warn')\n }\n return { instance, tag }\n }\n moduleMap.set(tag, undefined)\n if (paramtypes) {\n const paramtypesInstances = [] as any[]\n for (const i in paramtypes) {\n const { instance: sub, tag: subTag } = await buildNestModule(paramtypes[i])\n paramtypesInstances[i] = sub\n if (!moduleGraph.has(subTag))\n moduleGraph.set(subTag, new Set())\n moduleGraph.get(subTag)!.add(tag)\n }\n instance = new Module(...paramtypesInstances)\n }\n else {\n instance = new Module()\n }\n meta.push(...getMetaFromInstance(instance, tag, Module.name))\n await registerAsync(instance)\n moduleMap.set(tag, instance)\n log(`Module ${pc.yellow(`[${tag}]`)} mount\"`)\n constructorMap.set(tag, Module)\n return { instance, tag }\n }\n\n for (const Module of Modules)\n await buildNestModule(Module)\n\n function writeCode() {\n debug('write code')\n\n http && fs.promises.writeFile(http, generateHTTPCode(meta.map(item => item.data)))\n rpc && fs.promises.writeFile(rpc, generateRPCCode(meta.map(item => item.data)))\n }\n\n writeCode()\n if (IS_DEV) {\n // @ts-expect-error globalThis\n globalThis.__PS_HMR__ = async (file: string) => {\n debug(`reload file ${file}`)\n const module = await import(file)\n for (const i in module) {\n if (isPhecda(module[i]))\n await update(module[i])\n }\n }\n // @ts-expect-error globalThis\n globalThis.__PS_WRITEMETA__ = writeCode\n }\n\n return {\n moduleMap,\n meta,\n constructorMap,\n update,\n }\n}\n\nfunction getMetaFromInstance(instance: Phecda, tag: string, name: string) {\n const vars = getExposeKey(instance).filter(item => item !== '__CLASS')\n const baseState = (getState(instance, '__CLASS') || {}) as P.Meta\n initState(baseState)\n\n return vars.map((i) => {\n const meta = {} as P.Meta\n const state = (getState(instance, i) || {}) as P.Meta\n initState(state)\n if (state.http) {\n meta.http = {\n route: (baseState.http?.route || '') + (state.http.route),\n type: state.http.type,\n }\n }\n if (baseState.rpc)\n meta.rpc = baseState.rpc\n if (state.rpc) {\n meta.rpc = {\n ...meta.rpc,\n ...state.rpc,\n }\n }\n\n meta.name = name\n meta.tag = tag\n meta.method = i as string\n const params = [] as any[]\n for (const i of state.params || []) {\n params.unshift(i)\n if (i.index === 0)\n break\n }\n\n meta.params = params\n meta.define = { ...baseState.define, ...state.define }\n meta.header = { ...baseState.header, ...state.header }\n meta.plugins = [...new Set([...baseState.plugins, ...state.plugins])]\n meta.guards = [...new Set([...baseState.guards, ...state.guards])]\n meta.interceptors = [...new Set([...baseState.interceptors, ...state.interceptors])]\n\n return new Meta(meta as unknown as P.Meta, getHandler(instance, i), getParamTypes(instance, i as string) || [])\n })\n}\n\nfunction getParamTypes(Module: any, key?: string | symbol) {\n return Reflect.getMetadata('design:paramtypes', Module, key!)\n}\n\nfunction initState(state: any) {\n if (!state.define)\n state.define = {}\n if (!state.header)\n state.header = {}\n if (!state.plugins)\n state.plugins = []\n if (!state.guards)\n state.guards = []\n if (!state.interceptors)\n state.interceptors = []\n}\n"],"mappings":";;;;;;;;;;AAEO,IAAMA,OAAN,MAAMA;EACQC;EAAqBC;EAA8BC;EAAtEC,YAAmBH,MAAqBC,UAA8BC,YAAmB;gBAAtEF;oBAAqBC;sBAA8BC;EAEtE;AACF;AAJaH;;;ACAb,IAAMK,WAAN,6BAAMA,UAAAA;EACJC,WAAsD,CAAC;EACvDC,cAAc;EAAE;EAEhBC,aAAa;AACX,QAAIC,UAAU;AAEd,eAAWC,QAAQ,KAAKJ,UAAU;AAChCG,iBAAW;uBACMC;cACTC,OAAOC,OAAO,KAAKN,SAASI,KAAK,EAAEG,OAAO,CAACC,GAAGC,MAAMD,IAAIC,CAAAA;;IAElE;AACA,WAAON;EACT;EAEAO,UAAUC,MAAc;AACtB,UAAM,EACJC,KAAKR,MAAMS,QAAQC,IAAG,IACpBH;AACJ,QAAI,CAACC,OAAO,CAACA,IAAIG;AACf;AACF,QAAI,CAAC,KAAKf,SAASI;AACjB,WAAKJ,SAASI,QAAQ,CAAC;AACzB,SAAKJ,SAASI,MAAMS,UAAU;MAC5BA;qBACeC,OAAOD,mBAAmB,CAAC,CAACD,IAAII,gBAAgBJ,IAAIG,KAAKR,OAAO,CAACC,GAAGC,MAAM;AACvF,aAAO,GAAGD,KAAKC;IACjB,GAAG,EAAA;;;;EAIP;AACF,GAjCA;AAmCO,SAASQ,gBAAgBC,MAAgB;AAC9C,QAAMC,WAAW,IAAIpB,SAAAA;AAErB,aAAWqB,KAAKF;AACdC,aAAST,UAAUU,CAAAA;AACrB,SAAOD,SAASjB,WAAU;AAC5B;AANgBe;;;ACnChB,IAAMI,YAAN,6BAAMA,UAAAA;EACJC,WAAsD,CAAC;EACvDC,cAAc;EAAE;EAEhBC,aAAa;AACX,QAAIC,UAAU;AAEd,eAAWC,QAAQ,KAAKJ,UAAU;AAChCG,iBAAW;uBACMC;cACTC,OAAOC,O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AMQ;AACTR,UAAMQ,SAAS,CAAC;AAClB,MAAI,CAACR,MAAMS;AACTT,UAAMS,UAAU,CAAA;AAClB,MAAI,CAACT,MAAMU;AACTV,UAAMU,SAAS,CAAA;AACjB,MAAI,CAACV,MAAMW;AACTX,UAAMW,eAAe,CAAA;AACzB;AAXSZ;","names":["Meta","data","handlers","paramsType","constructor","Compiler","classMap","constructor","getContent","content","name","Object","values","reduce","p","c","addMethod","args","rpc","method","tag","type","isEvent","generateRPCCode","meta","compiler","i","Compiler","classMap","constructor","getContent","content","name","Object","values","reduce","p","c","addMethod","args","http","method","params","tag","url","route","replace","_","js","type","i","key","generateHTTPCode","meta","compiler","fs","EventEmitter","Empty","getExposeKey","getHandler","getState","injectProperty","isPhecda","registerAsync","Debug","pc","Injectable","target","Empty","debug","Debug","emitter","EventEmitter","Factory","Modules","opts","moduleMap","Map","meta","constructorMap","constructorSet","WeakSet","moduleGraph","http","rpc","injectProperty","eventName","instance","key","options","fn","bind","v","once","on","update","Module","tag","prototype","__TAG__","name","has","get","UNMOUNT_SYMBOL","cb","log","pc","yellow","delete","i","length","data","splice","newModule","buildNestModule","forEach","module","set","paramtypes","getParamTypes","Error","add","undefined","paramtypesInstances","sub","subTag","Set","push","getMetaFromInstance","registerAsync","writeCode","fs","promises","writeFile","generateHTTPCode","map","item","generateRPCCode","IS_DEV","globalThis","__PS_HMR__","file","isPhecda","__PS_WRITEMETA__","vars","getExposeKey","filter","baseState","getState","initState","state","route","type","method","params","unshift","index","define","header","plugins","guards","interceptors","Meta","getHandler","Reflect","getMetadata"]}
|
|
1
|
+
{"version":3,"sources":["../src/meta.ts","../src/compiler/rpc.ts","../src/compiler/http.ts","../src/core.ts"],"sourcesContent":["import type { P } from './types'\n\nexport class Meta {\n constructor(public data: P.Meta, public handlers: P.Handler[], public paramsType: any[]) {\n\n }\n}\n","import type { P } from '../types'\n\nclass Compiler {\n classMap: Record<string, { [key: string]: string }> = {}\n constructor() { }\n\n getContent() {\n let content = ''\n\n for (const name in this.classMap) {\n content += `\n export class ${name}{\n ${Object.values(this.classMap[name]).reduce((p, c) => p + c)}\n }`\n }\n return content\n }\n\n addMethod(args: P.Meta) {\n const {\n rpc, name, method, tag,\n } = args\n if (!rpc || !rpc.type)\n return\n if (!this.classMap[name])\n this.classMap[name] = {}\n this.classMap[name][method] = `\n ${method}(){\n return {tag:'${tag}-${method}',isEvent:${!!rpc.isEvent},rpc:[${rpc.type.reduce((p, c) => {\n return `${p}\"${c}\",`\n }, '')}]}\n\n }\n `\n }\n}\n\nexport function generateRPCCode(meta: P.Meta[]) {\n const compiler = new Compiler()\n\n for (const i of meta)\n compiler.addMethod(i)\n return compiler.getContent()\n}\n","import type { P } from '../types'\n\nclass Compiler {\n classMap: Record<string, { [key: string]: string }> = {}\n constructor() { }\n\n getContent() {\n let content = ''\n\n for (const name in this.classMap) {\n content += `\n export class ${name}{\n ${Object.values(this.classMap[name]).reduce((p, c) => p + c)}\n }`\n }\n return content\n }\n\n // createRequest() {\n // let content = 'import {useC} from \\'phecda-server\\'\\n'\n // for (const name in this.classMap)\n // content += `export const {${Object.keys(this.classMap[name]).join(',')}}=useC(${name})\\n`\n // return content\n // }\n\n addMethod(args: P.Meta) {\n const {\n http, name, method, params, tag,\n } = args\n if (!http)\n return\n const url = http.route.replace(/\\/\\:([^\\/]*)/g, (_, js) => `/{{${js}}}`)\n if (!this.classMap[name])\n this.classMap[name] = {}\n this.classMap[name][method] = `\n ${method}(...args){\nconst ret={tag:\"${tag}-${method}\",body:{},headers:{},query:{},params:{},method:\"${http.type}\",url:\"${url}\",args}\n\n${params.reduce((p, c, i) => `${p}ret.${c.type}${c.key ? `['${c.key}']` : ''}=args[${i}]\\n${c.type === 'params' ? `ret.url=ret.url.replace('{{${c.key}}}',args[${i}])` : ''}\\n`, '')}\nreturn ret\n }\n `\n }\n}\n\nexport function generateHTTPCode(meta: P.Meta[]) {\n const compiler = new Compiler()\n\n for (const i of meta)\n compiler.addMethod(i)\n return compiler.getContent()\n}\n","import 'reflect-metadata'\nimport fs from 'fs'\nimport EventEmitter from 'node:events'\nimport type { Phecda } from 'phecda-core'\nimport { Empty, getExposeKey, getHandler, getState, injectProperty, isPhecda, registerAsync } from 'phecda-core'\nimport Debug from 'debug'\nimport pc from 'picocolors'\nimport type { Construct, Emitter, P } from './types'\nimport { Meta } from './meta'\nimport { log } from './utils'\nimport { IS_DEV, UNMOUNT_SYMBOL } from './common'\nimport { generateHTTPCode, generateRPCCode } from './compiler'\nexport function Injectable() {\n return (target: any) => Empty(target)\n}\nconst debug = Debug('phecda-server')\n// TODO: support both emitter types and origin emitter type in future\nexport const emitter: Emitter = new EventEmitter() as any\n\nexport async function Factory(Modules: (new (...args: any) => any)[], opts: {\n\n // HTTP generate code path\n http?: string\n // rpc generate code path\n rpc?: string\n} = {}) {\n const moduleMap = new Map<string, InstanceType<Construct>>()\n const meta: Meta[] = []\n const constructorMap = new Map()\n\n // only work for warn\n const constructorSet = new WeakSet()\n const moduleGraph = new Map<string, Set<string>>()\n const { http, rpc } = opts\n injectProperty('watcher', ({ eventName, instance, key, options }: { eventName: string; instance: any; key: string; options?: { once: boolean } }) => {\n const fn = typeof instance[key] === 'function' ? instance[key].bind(instance) : (v: any) => instance[key] = v\n\n // work for hmr\n if (!instance[UNMOUNT_SYMBOL])\n instance[UNMOUNT_SYMBOL] = []\n\n instance[UNMOUNT_SYMBOL].push(() => {\n (emitter as any).off(eventName, fn)\n })\n\n if (options?.once)\n (emitter as any).once(eventName, fn)\n\n else\n (emitter as any).on(eventName, fn)\n })\n\n async function update(Module: Construct) {\n const tag = Module.prototype?.__TAG__ || Module.name\n if (!moduleMap.has(tag))\n return\n debug(`update module \"${tag}\"`)\n\n const instance = moduleMap.get(tag)\n\n if (instance?.[UNMOUNT_SYMBOL]) {\n for (const cb of instance[UNMOUNT_SYMBOL])\n await cb()\n }\n log(`Module ${pc.yellow(`[${tag}]`)} unmount`)\n moduleMap.delete(tag)\n constructorMap.delete(tag)\n for (let i = meta.length - 1; i >= 0; i--) {\n if (meta[i].data.tag === tag)\n meta.splice(i, 1)\n }\n\n const { instance: newModule } = await buildNestModule(Module)\n if (moduleGraph.has(tag)) {\n [...moduleGraph.get(tag)!].forEach((tag) => {\n const module = moduleMap.get(tag)\n for (const key in module) {\n if (module[key] === instance)\n module[key] = newModule\n }\n })\n }\n\n moduleMap.set(tag, newModule)\n }\n async function buildNestModule(Module: Construct) {\n const paramtypes = getParamTypes(Module) as Construct[]\n let instance: InstanceType<Construct>\n const tag = Module.prototype?.__TAG__ || Module.name\n if (moduleMap.has(tag)) {\n instance = moduleMap.get(tag)\n if (!instance)\n throw new Error(`exist Circular-Dependency or Multiple modules with the same name/tag [tag] ${tag}--[module] ${Module}`)\n\n if (constructorMap.get(tag) !== Module && !constructorSet.has(Module)) {\n constructorSet.add(Module)// a module will only warn once\n log(`Synonym module: Module taged \"${tag}\" has been loaded before, so phecda-server won't load Module \"${Module.name}\"`, 'warn')\n }\n return { instance, tag }\n }\n moduleMap.set(tag, undefined)\n if (paramtypes) {\n const paramtypesInstances = [] as any[]\n for (const i in paramtypes) {\n const { instance: sub, tag: subTag } = await buildNestModule(paramtypes[i])\n paramtypesInstances[i] = sub\n if (!moduleGraph.has(subTag))\n moduleGraph.set(subTag, new Set())\n moduleGraph.get(subTag)!.add(tag)\n }\n instance = new Module(...paramtypesInstances)\n }\n else {\n instance = new Module()\n }\n meta.push(...getMetaFromInstance(instance, tag, Module.name))\n await registerAsync(instance)\n moduleMap.set(tag, instance)\n log(`Module ${pc.yellow(`[${tag}]`)} mount\"`)\n constructorMap.set(tag, Module)\n return { instance, tag }\n }\n\n for (const Module of Modules)\n await buildNestModule(Module)\n\n function writeCode() {\n debug('write code')\n\n http && fs.promises.writeFile(http, generateHTTPCode(meta.map(item => item.data)))\n rpc && fs.promises.writeFile(rpc, generateRPCCode(meta.map(item => item.data)))\n }\n\n writeCode()\n if (IS_DEV) {\n // @ts-expect-error globalThis\n globalThis.__PS_HMR__ = async (file: string) => {\n debug(`reload file ${file}`)\n const module = await import(file)\n for (const i in module) {\n if (isPhecda(module[i]))\n await update(module[i])\n }\n }\n // @ts-expect-error globalThis\n globalThis.__PS_WRITEMETA__ = writeCode\n }\n\n return {\n moduleMap,\n meta,\n constructorMap,\n update,\n }\n}\n\nfunction getMetaFromInstance(instance: Phecda, tag: string, name: string) {\n const vars = getExposeKey(instance).filter(item => item !== '__CLASS')\n const baseState = (getState(instance, '__CLASS') || {}) as P.Meta\n initState(baseState)\n\n return vars.map((i) => {\n const meta = {} as P.Meta\n const state = (getState(instance, i) || {}) as P.Meta\n initState(state)\n if (state.http) {\n meta.http = {\n route: (baseState.http?.route || '') + (state.http.route),\n type: state.http.type,\n }\n }\n if (baseState.rpc)\n meta.rpc = baseState.rpc\n if (state.rpc) {\n meta.rpc = {\n ...meta.rpc,\n ...state.rpc,\n }\n }\n\n meta.name = name\n meta.tag = tag\n meta.method = i as string\n const params = [] as any[]\n for (const i of state.params || []) {\n params.unshift(i)\n if (i.index === 0)\n break\n }\n\n meta.params = params\n meta.define = { ...baseState.define, ...state.define }\n meta.header = { ...baseState.header, ...state.header }\n meta.plugins = [...new Set([...baseState.plugins, ...state.plugins])]\n meta.guards = [...new Set([...baseState.guards, ...state.guards])]\n meta.interceptors = [...new Set([...baseState.interceptors, ...state.interceptors])]\n\n return new Meta(meta as unknown as P.Meta, getHandler(instance, i), getParamTypes(instance, i as string) || [])\n })\n}\n\nfunction getParamTypes(Module: any, key?: string | symbol) {\n return Reflect.getMetadata('design:paramtypes', Module, key!)\n}\n\nfunction initState(state: any) {\n if (!state.define)\n state.define = {}\n if (!state.header)\n state.header = {}\n if (!state.plugins)\n state.plugins = []\n if (!state.guards)\n state.guards = []\n if (!state.interceptors)\n state.interceptors = []\n}\n"],"mappings":";;;;;;;;;;AAEO,IAAMA,OAAN,MAAMA;EACQC;EAAqBC;EAA8BC;EAAtEC,YAAmBH,MAAqBC,UAA8BC,YAAmB;gBAAtEF;oBAAqBC;sBAA8B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,MAAI,CAACT,MAAMU;AACTV,UAAMU,SAAS,CAAA;AACjB,MAAI,CAACV,MAAMW;AACTX,UAAMW,eAAe,CAAA;AACzB;AAXSZ;","names":["Meta","data","handlers","paramsType","constructor","Compiler","classMap","constructor","getContent","content","name","Object","values","reduce","p","c","addMethod","args","rpc","method","tag","type","isEvent","generateRPCCode","meta","compiler","i","Compiler","classMap","constructor","getContent","content","name","Object","values","reduce","p","c","addMethod","args","http","method","params","tag","url","route","replace","_","js","type","i","key","generateHTTPCode","meta","compiler","fs","EventEmitter","Empty","getExposeKey","getHandler","getState","injectProperty","isPhecda","registerAsync","Debug","pc","Injectable","target","Empty","debug","Debug","emitter","EventEmitter","Factory","Modules","opts","moduleMap","Map","meta","constructorMap","constructorSet","WeakSet","moduleGraph","http","rpc","injectProperty","eventName","instance","key","options","fn","bind","v","UNMOUNT_SYMBOL","push","off","once","on","update","Module","tag","prototype","__TAG__","name","has","get","cb","log","pc","yellow","delete","i","length","data","splice","newModule","buildNestModule","forEach","module","set","paramtypes","getParamTypes","Error","add","undefined","paramtypesInstances","sub","subTag","Set","getMetaFromInstance","registerAsync","writeCode","fs","promises","writeFile","generateHTTPCode","map","item","generateRPCCode","IS_DEV","globalThis","__PS_HMR__","file","isPhecda","__PS_WRITEMETA__","vars","getExposeKey","filter","baseState","getState","initState","state","route","type","method","params","unshift","index","define","header","plugins","guards","interceptors","Meta","getHandler","Reflect","getMetadata"]}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
IS_DEV,
|
|
3
|
+
IS_STRICT,
|
|
3
4
|
log
|
|
4
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-PIRUVYEF.mjs";
|
|
5
6
|
import {
|
|
6
7
|
__name,
|
|
7
8
|
__publicField
|
|
@@ -163,6 +164,9 @@ var FrameworkException = class extends Exception {
|
|
|
163
164
|
};
|
|
164
165
|
__name(FrameworkException, "FrameworkException");
|
|
165
166
|
|
|
167
|
+
// src/context.ts
|
|
168
|
+
import pc from "picocolors";
|
|
169
|
+
|
|
166
170
|
// src/filter.ts
|
|
167
171
|
var defaultFilter = /* @__PURE__ */ __name((e) => {
|
|
168
172
|
if (!(e instanceof Exception)) {
|
|
@@ -191,7 +195,7 @@ var Histroy = class {
|
|
|
191
195
|
__name(Histroy, "Histroy");
|
|
192
196
|
|
|
193
197
|
// src/context.ts
|
|
194
|
-
var
|
|
198
|
+
var guardRecord = {};
|
|
195
199
|
var _Context = class {
|
|
196
200
|
tag;
|
|
197
201
|
data;
|
|
@@ -208,6 +212,12 @@ var _Context = class {
|
|
|
208
212
|
}
|
|
209
213
|
usePipe(args) {
|
|
210
214
|
return Promise.all(args.map((item) => {
|
|
215
|
+
if (item.pipe && !_Context.pipeRecord[item.pipe]) {
|
|
216
|
+
if (IS_STRICT)
|
|
217
|
+
throw new FrameworkException(`can't find pipe named '${item.pipe}'`);
|
|
218
|
+
else
|
|
219
|
+
return _Context.pipeRecord.default(item, this.tag, this.data);
|
|
220
|
+
}
|
|
211
221
|
return _Context.pipeRecord[item.pipe || "default"](item, this.tag, this.data);
|
|
212
222
|
}));
|
|
213
223
|
}
|
|
@@ -217,12 +227,12 @@ var _Context = class {
|
|
|
217
227
|
async useGuard(guards) {
|
|
218
228
|
for (const guard of guards) {
|
|
219
229
|
if (this.history.record(guard, "guard")) {
|
|
220
|
-
if (!(guard in _Context.
|
|
221
|
-
if (
|
|
230
|
+
if (!(guard in _Context.guardRecord)) {
|
|
231
|
+
if (IS_STRICT)
|
|
222
232
|
throw new FrameworkException(`can't find guard named '${guard}'`);
|
|
223
233
|
continue;
|
|
224
234
|
}
|
|
225
|
-
if (!await _Context.
|
|
235
|
+
if (!await _Context.guardRecord[guard](this.tag, this.data))
|
|
226
236
|
throw new ForbiddenException(`Guard exception--${guard}`);
|
|
227
237
|
}
|
|
228
238
|
}
|
|
@@ -236,12 +246,12 @@ var _Context = class {
|
|
|
236
246
|
const ret = [];
|
|
237
247
|
for (const interceptor of interceptors) {
|
|
238
248
|
if (this.history.record(interceptor, "interceptor")) {
|
|
239
|
-
if (!(interceptor in _Context.
|
|
240
|
-
if (
|
|
249
|
+
if (!(interceptor in _Context.interceptorRecord)) {
|
|
250
|
+
if (IS_STRICT)
|
|
241
251
|
throw new FrameworkException(`can't find interceptor named '${interceptor}'`);
|
|
242
252
|
continue;
|
|
243
253
|
}
|
|
244
|
-
const postInterceptor = await _Context.
|
|
254
|
+
const postInterceptor = await _Context.interceptorRecord[interceptor](this.tag, this.data);
|
|
245
255
|
if (postInterceptor !== void 0) {
|
|
246
256
|
if (typeof postInterceptor === "function")
|
|
247
257
|
ret.push(postInterceptor);
|
|
@@ -256,7 +266,7 @@ var _Context = class {
|
|
|
256
266
|
const ret = [];
|
|
257
267
|
for (const m of plugins) {
|
|
258
268
|
if (!(m in _Context.pluginRecord)) {
|
|
259
|
-
if (
|
|
269
|
+
if (IS_STRICT)
|
|
260
270
|
throw new FrameworkException(`can't find middleware named '${m}'`);
|
|
261
271
|
continue;
|
|
262
272
|
}
|
|
@@ -271,8 +281,8 @@ __publicField(Context, "filter", defaultFilter);
|
|
|
271
281
|
__publicField(Context, "pipeRecord", {
|
|
272
282
|
default: defaultPipe
|
|
273
283
|
});
|
|
274
|
-
__publicField(Context, "
|
|
275
|
-
__publicField(Context, "
|
|
284
|
+
__publicField(Context, "guardRecord", {});
|
|
285
|
+
__publicField(Context, "interceptorRecord", {});
|
|
276
286
|
__publicField(Context, "pluginRecord", {});
|
|
277
287
|
function addPlugin(key, handler) {
|
|
278
288
|
Context.pluginRecord[key] = handler;
|
|
@@ -287,13 +297,53 @@ function setFilter(filter) {
|
|
|
287
297
|
}
|
|
288
298
|
__name(setFilter, "setFilter");
|
|
289
299
|
function addGuard(key, handler) {
|
|
290
|
-
Context.
|
|
300
|
+
Context.guardRecord[key] = handler;
|
|
291
301
|
}
|
|
292
302
|
__name(addGuard, "addGuard");
|
|
293
303
|
function addInterceptor(key, handler) {
|
|
294
|
-
Context.
|
|
304
|
+
Context.interceptorRecord[key] = handler;
|
|
295
305
|
}
|
|
296
306
|
__name(addInterceptor, "addInterceptor");
|
|
307
|
+
function isAopDepInject(meta, { guards, interceptors, plugins } = {}) {
|
|
308
|
+
const pluginSet = new Set(plugins);
|
|
309
|
+
const guardSet = new Set(guards);
|
|
310
|
+
const interceptorSet = new Set(interceptors);
|
|
311
|
+
const pipeSet = /* @__PURE__ */ new Set();
|
|
312
|
+
meta.forEach(({ data }) => {
|
|
313
|
+
data.interceptors.forEach((i) => interceptorSet.add(i));
|
|
314
|
+
data.guards.forEach((i) => guardSet.add(i));
|
|
315
|
+
data.plugins.forEach((i) => pluginSet.add(i));
|
|
316
|
+
data.params.forEach((i) => {
|
|
317
|
+
if (i.pipe)
|
|
318
|
+
pipeSet.add(i.pipe);
|
|
319
|
+
});
|
|
320
|
+
});
|
|
321
|
+
[
|
|
322
|
+
...pluginSet
|
|
323
|
+
].forEach((i) => {
|
|
324
|
+
if (!Context.pluginRecord[i])
|
|
325
|
+
log(`${pc.white(`Plugin [${i}]`)} doesn't exist`, "warn");
|
|
326
|
+
});
|
|
327
|
+
[
|
|
328
|
+
...guardSet
|
|
329
|
+
].forEach((i) => {
|
|
330
|
+
if (!Context.guardRecord[i])
|
|
331
|
+
log(`${pc.red(`Guard [${i}]`)} doesn't exist`, "warn");
|
|
332
|
+
});
|
|
333
|
+
[
|
|
334
|
+
...interceptorSet
|
|
335
|
+
].forEach((i) => {
|
|
336
|
+
if (!Context.interceptorRecord[i])
|
|
337
|
+
log(`${pc.cyan(`Interceptor [${i}]`)} doesn't exist`, "warn");
|
|
338
|
+
});
|
|
339
|
+
[
|
|
340
|
+
...pipeSet
|
|
341
|
+
].forEach((i) => {
|
|
342
|
+
if (!Context.pipeRecord[i])
|
|
343
|
+
log(`${pc.blue(`Pipe [${i}]`)} doesn't exist`, "warn");
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
__name(isAopDepInject, "isAopDepInject");
|
|
297
347
|
|
|
298
348
|
export {
|
|
299
349
|
Exception,
|
|
@@ -313,12 +363,13 @@ export {
|
|
|
313
363
|
ServiceUnavailableException,
|
|
314
364
|
FrameworkException,
|
|
315
365
|
defaultFilter,
|
|
316
|
-
|
|
366
|
+
guardRecord,
|
|
317
367
|
Context,
|
|
318
368
|
addPlugin,
|
|
319
369
|
addPipe,
|
|
320
370
|
setFilter,
|
|
321
371
|
addGuard,
|
|
322
|
-
addInterceptor
|
|
372
|
+
addInterceptor,
|
|
373
|
+
isAopDepInject
|
|
323
374
|
};
|
|
324
|
-
//# sourceMappingURL=chunk-
|
|
375
|
+
//# sourceMappingURL=chunk-O2H7ERZR.mjs.map
|