phecda-server 7.0.0-alpha.7 → 7.0.0-alpha.9

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.
Files changed (80) hide show
  1. package/bin/cli.mjs +10 -1
  2. package/dist/{chunk-M5HGFUCV.js → chunk-5RBTN33A.js} +23 -3
  3. package/dist/{chunk-RGSKKTHD.mjs → chunk-7ZGYJ5OW.mjs} +88 -54
  4. package/dist/{chunk-IRXNF6ZE.mjs → chunk-CVPZWDXU.mjs} +39 -30
  5. package/dist/{chunk-MENRZSGW.js → chunk-FX3LDQII.js} +88 -79
  6. package/dist/{chunk-C5BVKEGW.mjs → chunk-FXTJ3BJ6.mjs} +25 -5
  7. package/dist/{chunk-XSMUJ77A.js → chunk-KJUD2BKE.js} +103 -69
  8. package/dist/{chunk-JPSXNDXP.mjs → chunk-ODVWOXVB.mjs} +1 -1
  9. package/dist/{chunk-VYMSCWXC.js → chunk-V5EYXVJT.js} +24 -24
  10. package/dist/{core-DU7gQKSk.d.mts → core-BDkhrEyf.d.mts} +4 -3
  11. package/dist/{core-CzElxZoF.d.ts → core-D_cz0tKa.d.ts} +4 -3
  12. package/dist/helper.d.mts +7 -5
  13. package/dist/helper.d.ts +7 -5
  14. package/dist/helper.js +8 -3
  15. package/dist/helper.mjs +10 -5
  16. package/dist/http/elysia/index.d.mts +4 -4
  17. package/dist/http/elysia/index.d.ts +4 -4
  18. package/dist/http/elysia/index.js +41 -44
  19. package/dist/http/elysia/index.mjs +7 -10
  20. package/dist/http/express/index.d.mts +4 -4
  21. package/dist/http/express/index.d.ts +4 -4
  22. package/dist/http/express/index.js +38 -41
  23. package/dist/http/express/index.mjs +7 -10
  24. package/dist/http/fastify/index.d.mts +4 -4
  25. package/dist/http/fastify/index.d.ts +4 -4
  26. package/dist/http/fastify/index.js +39 -42
  27. package/dist/http/fastify/index.mjs +7 -10
  28. package/dist/http/h3/index.d.mts +4 -4
  29. package/dist/http/h3/index.d.ts +4 -4
  30. package/dist/http/h3/index.js +39 -42
  31. package/dist/http/h3/index.mjs +7 -10
  32. package/dist/http/hono/index.d.mts +4 -4
  33. package/dist/http/hono/index.d.ts +4 -4
  34. package/dist/http/hono/index.js +35 -39
  35. package/dist/http/hono/index.mjs +3 -7
  36. package/dist/http/hyper-express/index.d.mts +4 -4
  37. package/dist/http/hyper-express/index.d.ts +4 -4
  38. package/dist/http/hyper-express/index.js +36 -39
  39. package/dist/http/hyper-express/index.mjs +6 -9
  40. package/dist/http/koa/index.d.mts +4 -4
  41. package/dist/http/koa/index.d.ts +4 -4
  42. package/dist/http/koa/index.js +38 -41
  43. package/dist/http/koa/index.mjs +7 -10
  44. package/dist/index.d.mts +35 -33
  45. package/dist/index.d.ts +35 -33
  46. package/dist/index.js +42 -43
  47. package/dist/index.mjs +15 -16
  48. package/dist/{meta-BTnLXuCa.d.ts → meta-BX5jhe4Z.d.mts} +3 -4
  49. package/dist/{meta-BTnLXuCa.d.mts → meta-BX5jhe4Z.d.ts} +3 -4
  50. package/dist/rpc/bullmq/index.d.mts +4 -4
  51. package/dist/rpc/bullmq/index.d.ts +4 -4
  52. package/dist/rpc/bullmq/index.js +14 -14
  53. package/dist/rpc/bullmq/index.mjs +3 -3
  54. package/dist/rpc/kafka/index.d.mts +4 -4
  55. package/dist/rpc/kafka/index.d.ts +4 -4
  56. package/dist/rpc/kafka/index.js +14 -14
  57. package/dist/rpc/kafka/index.mjs +2 -2
  58. package/dist/rpc/nats/index.d.mts +4 -4
  59. package/dist/rpc/nats/index.d.ts +4 -4
  60. package/dist/rpc/nats/index.js +13 -13
  61. package/dist/rpc/nats/index.mjs +3 -3
  62. package/dist/rpc/rabbitmq/index.d.mts +4 -4
  63. package/dist/rpc/rabbitmq/index.d.ts +4 -4
  64. package/dist/rpc/rabbitmq/index.js +15 -15
  65. package/dist/rpc/rabbitmq/index.mjs +3 -3
  66. package/dist/rpc/redis/index.d.mts +4 -4
  67. package/dist/rpc/redis/index.d.ts +4 -4
  68. package/dist/rpc/redis/index.js +13 -13
  69. package/dist/rpc/redis/index.mjs +3 -3
  70. package/dist/test.d.mts +3 -3
  71. package/dist/test.d.ts +3 -3
  72. package/dist/test.js +6 -6
  73. package/dist/test.mjs +2 -2
  74. package/dist/{types-CbfaGkPA.d.ts → types-B-rUM9Fm.d.mts} +3 -3
  75. package/dist/{types--E-OCZhC.d.ts → types-CMeuFoyd.d.ts} +3 -3
  76. package/dist/{types-BxlzVoRv.d.mts → types-DKVhyZk_.d.mts} +3 -3
  77. package/dist/{types-BYqBeqrs.d.mts → types-MxxtkZXw.d.ts} +3 -3
  78. package/package.json +3 -2
  79. package/register/index.mjs +20 -11
  80. package/register/loader.mjs +13 -28
package/bin/cli.mjs CHANGED
@@ -30,7 +30,7 @@ if (nodeVersion < 18.19) {
30
30
 
31
31
  function startChild(file, args) {
32
32
  child = fork(file, {
33
- env: { NODE_ENV: 'development', ...process.env },
33
+ env: { ...process.env },
34
34
  stdio: 'inherit',
35
35
  execArgv: [
36
36
  nodeVersion < 18.19
@@ -114,9 +114,18 @@ cli
114
114
  .alias('run')
115
115
  .allowUnknownOptions()
116
116
  .alias('run')
117
+ .option('-p,--prod [prod]', 'prod mode', {
118
+ default: false,
119
+ })
117
120
  .action((file, root, options) => {
118
121
  if (root)
119
122
  process.chdir(root)
123
+
124
+ if (options.prod)
125
+ process.env.NODE_ENV = 'production'
126
+ else
127
+ process.env.NODE_ENV = 'development'
128
+
120
129
  process.env.PS_CONFIG_FILE = options.config
121
130
 
122
131
  log('process start!')
@@ -3,11 +3,10 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable:
3
3
 
4
4
  // src/common.ts
5
5
  var ERROR_SYMBOL = "__PS_ERROR__";
6
- var IS_HMR = process.env.NODE_ENV === "development";
6
+ var IS_DEV = process.env.NODE_ENV === "development";
7
7
  var IS_ONLY_GENERATE = !!process.env.PS_GENERATE;
8
8
  var IS_STRICT = !!process.env.PS_STRICT;
9
9
  var LOG_LEVEL = Number(process.env.PS_LOG_LEVEL || 0);
10
- var IS_READY = Symbol("IS_READY");
11
10
  var PS_EXIT_CODE = /* @__PURE__ */ function(PS_EXIT_CODE2) {
12
11
  PS_EXIT_CODE2[PS_EXIT_CODE2["RELAUNCH"] = 2] = "RELAUNCH";
13
12
  PS_EXIT_CODE2[PS_EXIT_CODE2["CODE"] = 4] = "CODE";
@@ -110,6 +109,27 @@ function runMiddleware(ctx, middleware) {
110
109
  }
111
110
  __name(runMiddleware, "runMiddleware");
112
111
 
112
+ // src/hmr.ts
113
+ function HMR(cb) {
114
+ if (IS_DEV) {
115
+ if (!globalThis.__PS_HMR__) globalThis.__PS_HMR__ = [];
116
+ globalThis.__PS_HMR__.push(cb);
117
+ }
118
+ }
119
+ __name(HMR, "HMR");
120
+ async function RELOAD(oldModels, newModels) {
121
+ log("reload module...");
122
+ for (const cb of globalThis.__PS_HMR__) await cb(oldModels, newModels);
123
+ log("reload done");
124
+ }
125
+ __name(RELOAD, "RELOAD");
126
+ function RELAUNCH() {
127
+ if (IS_DEV) process.exit(2);
128
+ }
129
+ __name(RELAUNCH, "RELAUNCH");
130
+
131
+
132
+
113
133
 
114
134
 
115
135
 
@@ -124,4 +144,4 @@ __name(runMiddleware, "runMiddleware");
124
144
 
125
145
 
126
146
 
127
- exports.__name = __name; exports.ERROR_SYMBOL = ERROR_SYMBOL; exports.IS_HMR = IS_HMR; exports.IS_ONLY_GENERATE = IS_ONLY_GENERATE; exports.IS_STRICT = IS_STRICT; exports.LOG_LEVEL = LOG_LEVEL; exports.IS_READY = IS_READY; exports.PS_EXIT_CODE = PS_EXIT_CODE; exports.setLogger = setLogger; exports.getLogger = getLogger; exports.log = log; exports.runMiddleware = runMiddleware; exports.Mixin = _tsmixer.Mixin;
147
+ exports.__name = __name; exports.ERROR_SYMBOL = ERROR_SYMBOL; exports.IS_DEV = IS_DEV; exports.IS_ONLY_GENERATE = IS_ONLY_GENERATE; exports.IS_STRICT = IS_STRICT; exports.LOG_LEVEL = LOG_LEVEL; exports.PS_EXIT_CODE = PS_EXIT_CODE; exports.setLogger = setLogger; exports.getLogger = getLogger; exports.log = log; exports.runMiddleware = runMiddleware; exports.Mixin = _tsmixer.Mixin; exports.HMR = HMR; exports.RELOAD = RELOAD; exports.RELAUNCH = RELAUNCH;
@@ -1,9 +1,9 @@
1
1
  import {
2
- IS_HMR,
2
+ HMR,
3
3
  IS_ONLY_GENERATE,
4
4
  __name,
5
5
  log
6
- } from "./chunk-C5BVKEGW.mjs";
6
+ } from "./chunk-FXTJ3BJ6.mjs";
7
7
 
8
8
  // src/meta.ts
9
9
  var Meta = class {
@@ -21,7 +21,7 @@ var Meta = class {
21
21
  // src/core.ts
22
22
  import "reflect-metadata";
23
23
  import EventEmitter from "node:events";
24
- import { getInject, getMergedMeta, getMetaKey, getMetaParams, getTag, invokeInit, invokeUnmount, isPhecda, setInject } from "phecda-core";
24
+ import { getInject, getMergedMeta, getMetaKey, getMetaParams, getTag, invokeInit, invokeUnmount, setInject } from "phecda-core";
25
25
  import Debug from "debug";
26
26
  var debug = Debug("phecda-server(Factory)");
27
27
  var emitter = new EventEmitter();
@@ -61,63 +61,58 @@ var ServerPhecda = class {
61
61
  }
62
62
  async start(models) {
63
63
  for (const model of models) await this.buildDepModule(model);
64
- const generateCode = /* @__PURE__ */ __name(async () => {
65
- if (IS_HMR) {
66
- return Promise.all(this.generators.map((generator) => {
67
- debug(`generate "${generator.name}" code to ${generator.path}`);
68
- return generator.output(this.meta);
69
- }));
70
- }
71
- }, "generateCode");
72
- generateCode().then(() => {
64
+ this.hmr();
65
+ this.generateCode().then(() => {
73
66
  if (IS_ONLY_GENERATE) process.exit(4);
74
67
  });
75
- if (IS_HMR) {
76
- if (!globalThis.__PS_HMR__) globalThis.__PS_HMR__ = [];
77
- globalThis.__PS_HMR__?.push(async (files) => {
78
- debug("reload files ");
79
- for (const file of files) {
80
- const models2 = await import(file);
81
- for (const i in models2) {
82
- if (isPhecda(models2[i])) await this.add(models2[i]);
83
- }
84
- }
85
- generateCode();
86
- });
87
- }
88
- }
89
- async add(Model) {
90
- const tag = getTag(Model);
91
- const oldInstance = await this.del(tag);
92
- const { module: newModule } = await this.buildDepModule(Model);
93
- if (oldInstance && this.dependenceGraph.has(tag)) {
94
- debug(`replace module "${String(tag)}"`);
95
- [
96
- ...this.dependenceGraph.get(tag)
97
- ].forEach((tag2) => {
98
- const module = this.moduleMap.get(tag2);
99
- for (const key in module) {
100
- if (module[key] === oldInstance) module[key] = newModule;
101
- }
102
- });
103
- }
104
68
  }
105
- async del(tag) {
106
- if (!this.moduleMap.has(tag)) return;
107
- const module = this.moduleMap.get(tag);
108
- debug(`unmount module "${String(tag)}"`);
109
- await invokeUnmount(module);
110
- debug(`del module "${String(tag)}"`);
111
- this.moduleMap.delete(tag);
112
- this.modelMap.delete(module);
113
- for (let i = this.meta.length - 1; i >= 0; i--) {
114
- if (this.meta[i].data.tag === tag) this.meta.splice(i, 1);
115
- }
116
- return module;
69
+ generateCode = /* @__PURE__ */ __name(async () => {
70
+ return Promise.all(this.generators.map((generator) => {
71
+ debug(`generate "${generator.name}" code to ${generator.path}`);
72
+ return generator.output(this.meta);
73
+ }));
74
+ }, "generateCode");
75
+ hmr() {
76
+ HMR(async (oldModels, newModels) => {
77
+ debug("reload models ");
78
+ await this.replace(oldModels, newModels);
79
+ this.generateCode();
80
+ });
117
81
  }
82
+ // async add(Model: Construct) {
83
+ // const tag = getTag(Model)
84
+ // const oldInstance = await this.del(tag)
85
+ // const { module: newModule } = await this.buildDepModule(Model)
86
+ // if (oldInstance && this.dependenceGraph.has(tag)) {
87
+ // debug(`replace module "${String(tag)}"`);
88
+ // [...this.dependenceGraph.get(tag)!].forEach((tag) => {
89
+ // const module = this.moduleMap.get(tag)
90
+ // for (const key in module) {
91
+ // if (module[key] === oldInstance)
92
+ // module[key] = newModule
93
+ // }
94
+ // })
95
+ // }
96
+ // }
97
+ // async del(modelOrTag: Construct | PropertyKey) {
98
+ // const tag = typeof modelOrTag === 'function' ? getTag(modelOrTag) : modelOrTag
99
+ // if (!this.moduleMap.has(tag))
100
+ // return
101
+ // const module = this.moduleMap.get(tag)
102
+ // debug(`unmount module "${String(tag)}"`)
103
+ // await invokeUnmount(module)
104
+ // debug(`del module "${String(tag)}"`)
105
+ // this.moduleMap.delete(tag)
106
+ // this.modelMap.delete(module)
107
+ // for (let i = this.meta.length - 1; i >= 0; i--) {
108
+ // if (this.meta[i].data.tag === tag)
109
+ // this.meta.splice(i, 1)
110
+ // }
111
+ // return module
112
+ // }
118
113
  async destroy() {
119
114
  debug("destroy all");
120
- for (const [tag] of this.moduleMap) await this.del(tag);
115
+ this.replace(Object.values(this.modelMap), []);
121
116
  }
122
117
  createProxyModule(tag) {
123
118
  const that = this;
@@ -133,6 +128,9 @@ var ServerPhecda = class {
133
128
  has(_target, prop) {
134
129
  return Reflect.has(that.moduleMap.get(tag), prop);
135
130
  },
131
+ ownKeys() {
132
+ return Reflect.ownKeys(that.moduleMap.get(tag));
133
+ },
136
134
  getPrototypeOf() {
137
135
  return Reflect.getPrototypeOf(that.moduleMap.get(tag));
138
136
  },
@@ -189,6 +187,42 @@ var ServerPhecda = class {
189
187
  tag
190
188
  };
191
189
  }
190
+ async replace(oldModels, newModels) {
191
+ const oldModules = (await Promise.all(oldModels.map(async (model) => {
192
+ const tag = getTag(model);
193
+ if (!this.has(tag)) return;
194
+ const module = this.moduleMap.get(tag);
195
+ debug(`unmount module "${String(tag)}"`);
196
+ await invokeUnmount(module);
197
+ debug(`del module "${String(tag)}"`);
198
+ this.moduleMap.delete(tag);
199
+ this.modelMap.delete(module);
200
+ for (let i = this.meta.length - 1; i >= 0; i--) {
201
+ if (this.meta[i].data.tag === tag) this.meta.splice(i, 1);
202
+ }
203
+ return module;
204
+ }))).filter((item) => item);
205
+ for (const model of newModels) {
206
+ debug(`mount module: ${model.name}`);
207
+ await this.buildDepModule(model);
208
+ }
209
+ debug("replace old modules");
210
+ for (const module of oldModules) {
211
+ const tag = getTag(module);
212
+ if (this.dependenceGraph.has(tag)) {
213
+ [
214
+ ...this.dependenceGraph.get(tag)
215
+ ].forEach((depTag) => {
216
+ const depModule = this.moduleMap.get(depTag);
217
+ if (depModule) {
218
+ for (const key in depModule) {
219
+ if (depModule[key] === module) depModule[key] = this.moduleMap.get(tag);
220
+ }
221
+ }
222
+ });
223
+ }
224
+ }
225
+ }
192
226
  has(modelOrTag) {
193
227
  return this.moduleMap.has(typeof modelOrTag === "function" ? getTag(modelOrTag) : modelOrTag);
194
228
  }
@@ -1,11 +1,12 @@
1
1
  import {
2
2
  ERROR_SYMBOL,
3
- IS_HMR,
3
+ HMR,
4
+ IS_DEV,
4
5
  IS_STRICT,
5
6
  LOG_LEVEL,
6
7
  __name,
7
8
  log
8
- } from "./chunk-C5BVKEGW.mjs";
9
+ } from "./chunk-FXTJ3BJ6.mjs";
9
10
 
10
11
  // src/helper.ts
11
12
  import pc2 from "picocolors";
@@ -230,10 +231,25 @@ var Context = class _Context {
230
231
  };
231
232
  static guardRecord = {};
232
233
  static addonRecord = {};
234
+ ctx;
235
+ canGetCtx;
233
236
  constructor(data) {
234
237
  this.data = data;
235
- if (IS_HMR)
238
+ this.canGetCtx = true;
239
+ if (IS_DEV)
236
240
  data._context = this;
241
+ const that = this;
242
+ this.ctx = new Proxy(data, {
243
+ get(target, p) {
244
+ if (IS_DEV && !that.canGetCtx) throw new FrameworkException("ctx must be obtained within the same request cycle in controller");
245
+ if (!(p in target)) log(`attribute "${p}" does not exist on ctx, which might be due to a missing AOP role (such as a guard).`, "warn", data.tag);
246
+ return target[p];
247
+ },
248
+ set(target, p, newValue) {
249
+ target[p] = newValue;
250
+ return true;
251
+ }
252
+ });
237
253
  }
238
254
  static getAop(meta, opts) {
239
255
  const { globalGuards = [], globalFilter = "default", globalPipe = "default" } = opts;
@@ -269,14 +285,20 @@ ${pc.red(`Filter ${filter2}[${filter2 || "default"}]`)}`);
269
285
  if (index === guards.length) {
270
286
  const instance = moduleMap.get(tag);
271
287
  if (ctxs) {
272
- ctxs.forEach((ctx) => instance[ctx] = this.data);
288
+ ctxs.forEach((ctx) => instance[ctx] = this.ctx);
273
289
  }
274
290
  const args = await Promise.all(params.map((item, i) => pipe[i]({
275
291
  arg: resolveDep(this.data[item.type], item.key),
276
292
  reflect: paramsType[item.index],
277
293
  ...item
278
- }, this.data)));
294
+ }, this.ctx)));
295
+ if (IS_DEV) {
296
+ Promise.resolve().then(() => {
297
+ this.canGetCtx = false;
298
+ });
299
+ }
279
300
  res = await instance[func](...args);
301
+ this.canGetCtx = true;
280
302
  } else {
281
303
  let nextPromise;
282
304
  async function next() {
@@ -289,7 +311,7 @@ ${pc.red(`Filter ${filter2}[${filter2 || "default"}]`)}`);
289
311
  });
290
312
  }
291
313
  __name(next, "next");
292
- const ret = await guards[index](this.data, next);
314
+ const ret = await guards[index](this.ctx, next);
293
315
  if (ret !== void 0) {
294
316
  res = ret;
295
317
  } else {
@@ -302,7 +324,7 @@ ${pc.red(`Filter ${filter2}[${filter2 || "default"}]`)}`);
302
324
  await nextHandler(0)();
303
325
  return successCb(res);
304
326
  } catch (e) {
305
- const err = await filter(e, this.data);
327
+ const err = await filter(e, this.ctx);
306
328
  return failCb(err);
307
329
  }
308
330
  }
@@ -356,32 +378,12 @@ function addAddon(key, addon, priority = 0) {
356
378
  }
357
379
  __name(addAddon, "addAddon");
358
380
 
359
- // src/hmr.ts
360
- function HMR(cb) {
361
- if (IS_HMR) globalThis.__PS_HMR__?.push(cb);
362
- }
363
- __name(HMR, "HMR");
364
-
365
381
  // src/http/helper.ts
366
382
  function resolveDep(ret, key) {
367
383
  if (key) return ret?.[key];
368
384
  return ret;
369
385
  }
370
386
  __name(resolveDep, "resolveDep");
371
- function argToReq(params, args, headers) {
372
- const req = {
373
- body: {},
374
- query: {},
375
- params: {},
376
- headers
377
- };
378
- params.forEach((param) => {
379
- if (param.key) req[param.type][param.key] = args[param.index];
380
- else req[param.type] = args[param.index];
381
- });
382
- return req;
383
- }
384
- __name(argToReq, "argToReq");
385
387
 
386
388
  // src/rpc/helper.ts
387
389
  import { hostname } from "os";
@@ -498,6 +500,14 @@ function detectAopDep(meta, { guards, addons } = {}, controller = "http") {
498
500
  };
499
501
  }
500
502
  __name(detectAopDep, "detectAopDep");
503
+ function joinUrl(base, ...paths) {
504
+ const joinedPath = [
505
+ base,
506
+ ...paths
507
+ ].filter((p) => p).map((path) => path.replace(/(^\/)/g, "")).join("/");
508
+ return `/${joinedPath}`;
509
+ }
510
+ __name(joinUrl, "joinUrl");
501
511
 
502
512
  export {
503
513
  defaultPipe,
@@ -523,12 +533,11 @@ export {
523
533
  addFilter,
524
534
  addGuard,
525
535
  addAddon,
526
- HMR,
527
536
  resolveDep,
528
- argToReq,
529
537
  genClientQueue,
530
538
  shallowClone,
531
539
  mergeObject,
532
540
  createControllerMetaMap,
533
- detectAopDep
541
+ detectAopDep,
542
+ joinUrl
534
543
  };