phecda-server 7.1.3 → 7.1.4

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.
@@ -51,6 +51,11 @@
51
51
  "description": "Disable unimport"
52
52
  }
53
53
  ]
54
+ },
55
+ "swc": {
56
+ "type": "object",
57
+ "description": "options passed to @swc-node/core"
58
+
54
59
  }
55
60
  },
56
61
 
@@ -292,9 +292,7 @@ function deepFreeze(object) {
292
292
  }
293
293
  __name(deepFreeze, "deepFreeze");
294
294
  function getParamTypes(Model, key) {
295
- const paramTypes = Reflect.getMetadata("design:paramtypes", Model, key);
296
- if (typeof paramTypes === "function") return paramTypes();
297
- else return paramTypes;
295
+ return Reflect.getMetadata("design:paramtypes", Model, key);
298
296
  }
299
297
  __name(getParamTypes, "getParamTypes");
300
298
 
@@ -292,9 +292,7 @@ function deepFreeze(object) {
292
292
  }
293
293
  _chunk4LLLQOMFjs.__name.call(void 0, deepFreeze, "deepFreeze");
294
294
  function getParamTypes(Model, key) {
295
- const paramTypes = Reflect.getMetadata("design:paramtypes", Model, key);
296
- if (typeof paramTypes === "function") return paramTypes();
297
- else return paramTypes;
295
+ return Reflect.getMetadata("design:paramtypes", Model, key);
298
296
  }
299
297
  _chunk4LLLQOMFjs.__name.call(void 0, getParamTypes, "getParamTypes");
300
298
 
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkJTSD2LIGjs = require('./chunk-JTSD2LIG.js');
9
+ var _chunkYRS4ECPTjs = require('./chunk-YRS4ECPT.js');
10
10
 
11
11
 
12
12
 
@@ -102,7 +102,7 @@ var ServerBase = (_class = class extends _phecdacore.Base {constructor(...args2)
102
102
  static {
103
103
  _chunk4LLLQOMFjs.__name.call(void 0, this, "ServerBase");
104
104
  }
105
- __init() {this.emitter = exports.emitter = _chunkJTSD2LIGjs.emitter}
105
+ __init() {this.emitter = exports.emitter = _chunkYRS4ECPTjs.emitter}
106
106
  log(msg, level = "log") {
107
107
  _chunk4LLLQOMFjs.log.call(void 0, msg, level, this.tag);
108
108
  }
@@ -356,7 +356,7 @@ var OpenAPIGenerator = (_class6 = class extends Generator {constructor(...args5)
356
356
  if (!_optionalChain([http, 'optionalAccess', _3 => _3.type])) return;
357
357
  const path = _chunkOV3UJLGPjs.joinUrl.call(void 0, http.prefix, http.route);
358
358
  if (!this.paths[path]) this.paths[path] = {};
359
- const config = _phecdacore.getMergedMeta.call(void 0, _chunkJTSD2LIGjs.useS.call(void 0, ).getModel(tag), func).openapi;
359
+ const config = _phecdacore.getMergedMeta.call(void 0, _chunkYRS4ECPTjs.useS.call(void 0, ).getModel(tag), func).openapi;
360
360
  this.paths[path][http.type] = {
361
361
  summary: config.summary,
362
362
  description: config.description,
@@ -497,4 +497,4 @@ var DocGenerator = (_class7 = class extends Generator {
497
497
 
498
498
 
499
499
 
500
- exports.Addon = _chunkDPPDWBYOjs.Addon; exports.ApiDoc = _chunkDPPDWBYOjs.ApiDoc; exports.Arg = _chunkDPPDWBYOjs.Arg; exports.BadGatewayException = _chunkOV3UJLGPjs.BadGatewayException; exports.BadRequestException = _chunkOV3UJLGPjs.BadRequestException; exports.BaseParam = _chunkDPPDWBYOjs.BaseParam; exports.Body = _chunkDPPDWBYOjs.Body; exports.ConflictException = _chunkOV3UJLGPjs.ConflictException; exports.Context = _chunkOV3UJLGPjs.Context; exports.Controller = _chunkDPPDWBYOjs.Controller; exports.Ctx = _chunkDPPDWBYOjs.Ctx; exports.CustomResponse = CustomResponse; exports.Define = _chunkDPPDWBYOjs.Define; exports.Delete = _chunkDPPDWBYOjs.Delete; exports.DocGenerator = DocGenerator; exports.ERROR_SYMBOL = _chunk4LLLQOMFjs.ERROR_SYMBOL; exports.Exception = _chunkOV3UJLGPjs.Exception; exports.Factory = _chunkJTSD2LIGjs.Factory; exports.Filter = _chunkDPPDWBYOjs.Filter; exports.ForbiddenException = _chunkOV3UJLGPjs.ForbiddenException; exports.FrameworkException = _chunkOV3UJLGPjs.FrameworkException; exports.Generator = Generator; exports.Get = _chunkDPPDWBYOjs.Get; exports.Guard = _chunkDPPDWBYOjs.Guard; exports.HTTPGenerator = HTTPGenerator; exports.Head = _chunkDPPDWBYOjs.Head; exports.Header = _chunkDPPDWBYOjs.Header; exports.HttpBase = HttpBase; exports.IS_DEV = _chunk4LLLQOMFjs.IS_DEV; exports.IS_ONLY_GENERATE = _chunk4LLLQOMFjs.IS_ONLY_GENERATE; exports.IS_PURE = _chunk4LLLQOMFjs.IS_PURE; exports.IS_STRICT = _chunk4LLLQOMFjs.IS_STRICT; exports.InvalidInputException = _chunkOV3UJLGPjs.InvalidInputException; exports.LOG_LEVEL = _chunk4LLLQOMFjs.LOG_LEVEL; exports.ManyFiles = _chunkDPPDWBYOjs.ManyFiles; exports.Meta = _chunkJTSD2LIGjs.Meta; exports.Mixin = _chunk4LLLQOMFjs.Mixin; exports.NotFoundException = _chunkOV3UJLGPjs.NotFoundException; exports.OneFile = _chunkDPPDWBYOjs.OneFile; exports.OpenAPIGenerator = OpenAPIGenerator; exports.PAddon = PAddon; exports.PExtension = PExtension; exports.PFilter = PFilter; exports.PGuard = PGuard; exports.PPipe = PPipe; exports.PS_EXIT_CODE = _chunk4LLLQOMFjs.PS_EXIT_CODE; exports.Param = _chunkDPPDWBYOjs.Param; exports.Patch = _chunkDPPDWBYOjs.Patch; exports.PayloadLargeException = _chunkOV3UJLGPjs.PayloadLargeException; exports.Pipe = _chunkDPPDWBYOjs.Pipe; exports.Post = _chunkDPPDWBYOjs.Post; exports.Put = _chunkDPPDWBYOjs.Put; exports.Query = _chunkDPPDWBYOjs.Query; exports.Queue = _chunkDPPDWBYOjs.Queue; exports.RPCGenerator = RPCGenerator; exports.Route = _chunkDPPDWBYOjs.Route; exports.Rpc = _chunkDPPDWBYOjs.Rpc; exports.RpcBase = RpcBase; exports.Search = _chunkDPPDWBYOjs.Search; exports.ServerBase = ServerBase; exports.ServerPhecda = _chunkJTSD2LIGjs.ServerPhecda; exports.ServiceUnavailableException = _chunkOV3UJLGPjs.ServiceUnavailableException; exports.TimeoutException = _chunkOV3UJLGPjs.TimeoutException; exports.TimerException = _chunkOV3UJLGPjs.TimerException; exports.UnauthorizedException = _chunkOV3UJLGPjs.UnauthorizedException; exports.UndefinedException = _chunkOV3UJLGPjs.UndefinedException; exports.UnsupportedMediaTypeException = _chunkOV3UJLGPjs.UnsupportedMediaTypeException; exports.ValidateException = _chunkOV3UJLGPjs.ValidateException; exports.WorkerException = _chunkOV3UJLGPjs.WorkerException; exports.addAddon = _chunkOV3UJLGPjs.addAddon; exports.addFilter = _chunkOV3UJLGPjs.addFilter; exports.addGuard = _chunkOV3UJLGPjs.addGuard; exports.addPipe = _chunkOV3UJLGPjs.addPipe; exports.defaultPipe = _chunkOV3UJLGPjs.defaultPipe; exports.defaultServerInject = _chunkJTSD2LIGjs.defaultServerInject; exports.emitter = _chunkJTSD2LIGjs.emitter; exports.getLogger = _chunk4LLLQOMFjs.getLogger; exports.log = _chunk4LLLQOMFjs.log; exports.phecdaNamespace = _chunkJTSD2LIGjs.phecdaNamespace; exports.runMiddleware = _chunk4LLLQOMFjs.runMiddleware; exports.setLogger = _chunk4LLLQOMFjs.setLogger; exports.useS = _chunkJTSD2LIGjs.useS;
500
+ exports.Addon = _chunkDPPDWBYOjs.Addon; exports.ApiDoc = _chunkDPPDWBYOjs.ApiDoc; exports.Arg = _chunkDPPDWBYOjs.Arg; exports.BadGatewayException = _chunkOV3UJLGPjs.BadGatewayException; exports.BadRequestException = _chunkOV3UJLGPjs.BadRequestException; exports.BaseParam = _chunkDPPDWBYOjs.BaseParam; exports.Body = _chunkDPPDWBYOjs.Body; exports.ConflictException = _chunkOV3UJLGPjs.ConflictException; exports.Context = _chunkOV3UJLGPjs.Context; exports.Controller = _chunkDPPDWBYOjs.Controller; exports.Ctx = _chunkDPPDWBYOjs.Ctx; exports.CustomResponse = CustomResponse; exports.Define = _chunkDPPDWBYOjs.Define; exports.Delete = _chunkDPPDWBYOjs.Delete; exports.DocGenerator = DocGenerator; exports.ERROR_SYMBOL = _chunk4LLLQOMFjs.ERROR_SYMBOL; exports.Exception = _chunkOV3UJLGPjs.Exception; exports.Factory = _chunkYRS4ECPTjs.Factory; exports.Filter = _chunkDPPDWBYOjs.Filter; exports.ForbiddenException = _chunkOV3UJLGPjs.ForbiddenException; exports.FrameworkException = _chunkOV3UJLGPjs.FrameworkException; exports.Generator = Generator; exports.Get = _chunkDPPDWBYOjs.Get; exports.Guard = _chunkDPPDWBYOjs.Guard; exports.HTTPGenerator = HTTPGenerator; exports.Head = _chunkDPPDWBYOjs.Head; exports.Header = _chunkDPPDWBYOjs.Header; exports.HttpBase = HttpBase; exports.IS_DEV = _chunk4LLLQOMFjs.IS_DEV; exports.IS_ONLY_GENERATE = _chunk4LLLQOMFjs.IS_ONLY_GENERATE; exports.IS_PURE = _chunk4LLLQOMFjs.IS_PURE; exports.IS_STRICT = _chunk4LLLQOMFjs.IS_STRICT; exports.InvalidInputException = _chunkOV3UJLGPjs.InvalidInputException; exports.LOG_LEVEL = _chunk4LLLQOMFjs.LOG_LEVEL; exports.ManyFiles = _chunkDPPDWBYOjs.ManyFiles; exports.Meta = _chunkYRS4ECPTjs.Meta; exports.Mixin = _chunk4LLLQOMFjs.Mixin; exports.NotFoundException = _chunkOV3UJLGPjs.NotFoundException; exports.OneFile = _chunkDPPDWBYOjs.OneFile; exports.OpenAPIGenerator = OpenAPIGenerator; exports.PAddon = PAddon; exports.PExtension = PExtension; exports.PFilter = PFilter; exports.PGuard = PGuard; exports.PPipe = PPipe; exports.PS_EXIT_CODE = _chunk4LLLQOMFjs.PS_EXIT_CODE; exports.Param = _chunkDPPDWBYOjs.Param; exports.Patch = _chunkDPPDWBYOjs.Patch; exports.PayloadLargeException = _chunkOV3UJLGPjs.PayloadLargeException; exports.Pipe = _chunkDPPDWBYOjs.Pipe; exports.Post = _chunkDPPDWBYOjs.Post; exports.Put = _chunkDPPDWBYOjs.Put; exports.Query = _chunkDPPDWBYOjs.Query; exports.Queue = _chunkDPPDWBYOjs.Queue; exports.RPCGenerator = RPCGenerator; exports.Route = _chunkDPPDWBYOjs.Route; exports.Rpc = _chunkDPPDWBYOjs.Rpc; exports.RpcBase = RpcBase; exports.Search = _chunkDPPDWBYOjs.Search; exports.ServerBase = ServerBase; exports.ServerPhecda = _chunkYRS4ECPTjs.ServerPhecda; exports.ServiceUnavailableException = _chunkOV3UJLGPjs.ServiceUnavailableException; exports.TimeoutException = _chunkOV3UJLGPjs.TimeoutException; exports.TimerException = _chunkOV3UJLGPjs.TimerException; exports.UnauthorizedException = _chunkOV3UJLGPjs.UnauthorizedException; exports.UndefinedException = _chunkOV3UJLGPjs.UndefinedException; exports.UnsupportedMediaTypeException = _chunkOV3UJLGPjs.UnsupportedMediaTypeException; exports.ValidateException = _chunkOV3UJLGPjs.ValidateException; exports.WorkerException = _chunkOV3UJLGPjs.WorkerException; exports.addAddon = _chunkOV3UJLGPjs.addAddon; exports.addFilter = _chunkOV3UJLGPjs.addFilter; exports.addGuard = _chunkOV3UJLGPjs.addGuard; exports.addPipe = _chunkOV3UJLGPjs.addPipe; exports.defaultPipe = _chunkOV3UJLGPjs.defaultPipe; exports.defaultServerInject = _chunkYRS4ECPTjs.defaultServerInject; exports.emitter = _chunkYRS4ECPTjs.emitter; exports.getLogger = _chunk4LLLQOMFjs.getLogger; exports.log = _chunk4LLLQOMFjs.log; exports.phecdaNamespace = _chunkYRS4ECPTjs.phecdaNamespace; exports.runMiddleware = _chunk4LLLQOMFjs.runMiddleware; exports.setLogger = _chunk4LLLQOMFjs.setLogger; exports.useS = _chunkYRS4ECPTjs.useS;
package/dist/index.mjs CHANGED
@@ -6,7 +6,7 @@ import {
6
6
  emitter,
7
7
  phecdaNamespace,
8
8
  useS
9
- } from "./chunk-TQSHE4PZ.mjs";
9
+ } from "./chunk-5MAGRSEM.mjs";
10
10
  import {
11
11
  Addon,
12
12
  ApiDoc,
package/dist/test.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } }
2
2
 
3
- var _chunkJTSD2LIGjs = require('./chunk-JTSD2LIG.js');
3
+ var _chunkYRS4ECPTjs = require('./chunk-YRS4ECPT.js');
4
4
 
5
5
 
6
6
  var _chunk4LLLQOMFjs = require('./chunk-4LLLQOMF.js');
@@ -8,7 +8,7 @@ var _chunk4LLLQOMFjs = require('./chunk-4LLLQOMF.js');
8
8
  // src/test.ts
9
9
  var _phecdacore = require('phecda-core');
10
10
  async function TestFactory(...Modules) {
11
- const { moduleMap, modelMap } = await _chunkJTSD2LIGjs.Factory.call(void 0, Modules);
11
+ const { moduleMap, modelMap } = await _chunkYRS4ECPTjs.Factory.call(void 0, Modules);
12
12
  return {
13
13
  get(Model) {
14
14
  const tag = _phecdacore.getTag.call(void 0, Model);
package/dist/test.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Factory
3
- } from "./chunk-TQSHE4PZ.mjs";
3
+ } from "./chunk-5MAGRSEM.mjs";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-NQ55PA2X.mjs";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "phecda-server",
3
- "version": "7.1.3",
3
+ "version": "7.1.4",
4
4
  "description": "server framework that provide IOC/type-reuse/http&rpc-adaptor",
5
5
  "author": "fgsreally",
6
6
  "license": "MIT",
@@ -1,11 +1,11 @@
1
1
  import { fileURLToPath, pathToFileURL } from 'url'
2
2
  import { writeFile } from 'fs/promises'
3
3
  import {
4
- basename,
5
- dirname,
6
- isAbsolute,
7
- relative,
8
- resolve as resolvePath,
4
+ basename,
5
+ dirname,
6
+ isAbsolute,
7
+ relative,
8
+ resolve as resolvePath,
9
9
  } from 'path'
10
10
  import { createRequire } from 'module'
11
11
  import ts from 'typescript'
@@ -13,7 +13,8 @@ import chokidar from 'chokidar'
13
13
  import Debug from 'debug'
14
14
  import { compile, genUnImportRet, handleClassTypes, slash } from './utils.mjs'
15
15
 
16
- const require = createRequire(import.meta.url)
16
+ const require = createRequire(
17
+ import.meta.url)
17
18
  const debug = Debug('phecda-server/loader')
18
19
 
19
20
  const isLowVersion = parseFloat(process.version.slice(1)) < 18.19
@@ -22,8 +23,8 @@ let port
22
23
  let config
23
24
  const workdir = process.cwd()
24
25
  const configPath = resolvePath(
25
- workdir,
26
- process.env.PS_CONFIG_FILE || 'ps.json',
26
+ workdir,
27
+ process.env.PS_CONFIG_FILE || 'ps.json',
27
28
  )
28
29
 
29
30
  // unimport
@@ -34,337 +35,337 @@ const dtsPath = process.env.PS_DTS_PATH || 'ps.d.ts'
34
35
  const watchFiles = new Set()
35
36
  const filesRecord = new Map()
36
37
  const moduleGraph = {}
37
- // ts
38
+ // ts
38
39
  let tsconfig = {
39
- module: ts.ModuleKind.ESNext,
40
- moduleResolution: ts.ModuleResolutionKind.NodeNext,
40
+ module: ts.ModuleKind.ESNext,
41
+ moduleResolution: ts.ModuleResolutionKind.NodeNext,
41
42
  }
42
43
  const EXTENSIONS = [ts.Extension.Ts, ts.Extension.Tsx, ts.Extension.Mts]
43
44
  const tsconfigPath = resolvePath(process.cwd(), 'tsconfig.json')
44
45
  const tsRet = ts.readConfigFile(tsconfigPath, ts.sys.readFile)
45
46
  if (!tsRet.error) {
46
- const { error, options } = ts.parseJsonConfigFileContent(
47
- tsRet.config,
48
- ts.sys,
49
- dirname(tsconfigPath),
50
- )
51
- if (!error)
52
- tsconfig = options
47
+ const { error, options } = ts.parseJsonConfigFileContent(
48
+ tsRet.config,
49
+ ts.sys,
50
+ dirname(tsconfigPath),
51
+ )
52
+ if (!error)
53
+ tsconfig = options
53
54
  }
54
55
 
55
56
  const moduleResolutionCache = ts.createModuleResolutionCache(
56
- ts.sys.getCurrentDirectory(),
57
- x => x,
58
- tsconfig,
57
+ ts.sys.getCurrentDirectory(),
58
+ x => x,
59
+ tsconfig,
59
60
  )
60
61
  const host = {
61
- fileExists: ts.sys.fileExists,
62
- readFile: ts.sys.readFile,
62
+ fileExists: ts.sys.fileExists,
63
+ readFile: ts.sys.readFile,
63
64
  }
64
65
 
65
66
  if (isLowVersion)
66
- await initialize()
67
+ await initialize()
67
68
 
68
69
  export async function initialize(data) {
69
- if (data)
70
- port = data.port
71
-
72
- debug('read config...')
73
-
74
- config = require(configPath)
75
-
76
- if (!config.paths)
77
- config.paths = {}
78
-
79
- const loaderPath = process.env.PS_LOADER_PATH
80
-
81
- if (loaderPath) {
82
- const loader = await import(loaderPath.startsWith('.') ? resolvePath(workdir, loaderPath) : loaderPath)
83
-
84
- if (typeof loader.load === 'function')
85
- customLoad = loader.load
86
-
87
- if (typeof loader.resolve === 'function')
88
- customResolve = loader.resolve
89
- }
90
- if (IS_DEV) {
91
- chokidar.watch(configPath, { persistent: true }).on('change', () => {
92
- port.postMessage(
93
- JSON.stringify({
94
- type: 'relaunch',
95
- }),
96
- )
97
- })
98
- }
99
-
100
- if (!config.unimport)
101
- return
102
-
103
- unimportRet = await genUnImportRet(config.unimport)
104
- if (unimportRet) {
105
- debug('auto import...')
106
- await unimportRet.init()
107
-
108
- const unimportDtsPath = resolvePath(workdir, dtsPath)
109
- writeFile(
110
- unimportDtsPath,
111
- handleClassTypes(
112
- await unimportRet.generateTypeDeclarations({
113
- resolvePath: (i) => {
114
- if (i.from.startsWith('.') || isAbsolute(i.from)) {
115
- const related = slash(
116
- relative(dirname(unimportDtsPath), i.from).replace(/\.ts(x)?$/, ''),
117
- )
118
-
119
- return !related.startsWith('.') ? `./${related}` : related
120
- }
121
- return i.from
122
- },
123
- }),
124
- ),
125
- )
126
- }
70
+ if (data)
71
+ port = data.port
72
+
73
+ debug('read config...')
74
+
75
+ config = require(configPath)
76
+
77
+ if (!config.paths)
78
+ config.paths = {}
79
+
80
+ const loaderPath = process.env.PS_LOADER_PATH
81
+
82
+ if (loaderPath) {
83
+ const loader = await
84
+ import (loaderPath.startsWith('.') ? resolvePath(workdir, loaderPath) : loaderPath)
85
+
86
+ if (typeof loader.load === 'function')
87
+ customLoad = loader.load
88
+
89
+ if (typeof loader.resolve === 'function')
90
+ customResolve = loader.resolve
91
+ }
92
+ if (IS_DEV) {
93
+ chokidar.watch(configPath, { persistent: true }).on('change', () => {
94
+ port.postMessage(
95
+ JSON.stringify({
96
+ type: 'relaunch',
97
+ }),
98
+ )
99
+ })
100
+ }
101
+
102
+ if (!config.unimport)
103
+ return
104
+
105
+ unimportRet = await genUnImportRet(config.unimport)
106
+ if (unimportRet) {
107
+ debug('auto import...')
108
+ await unimportRet.init()
109
+
110
+ const unimportDtsPath = resolvePath(workdir, dtsPath)
111
+ writeFile(
112
+ unimportDtsPath,
113
+ handleClassTypes(
114
+ await unimportRet.generateTypeDeclarations({
115
+ resolvePath: (i) => {
116
+ if (i.from.startsWith('.') || isAbsolute(i.from)) {
117
+ const related = slash(
118
+ relative(dirname(unimportDtsPath), i.from).replace(/\.ts(x)?$/, ''),
119
+ )
120
+
121
+ return !related.startsWith('.') ? `./${related}` : related
122
+ }
123
+ return i.from
124
+ },
125
+ }),
126
+ ),
127
+ )
128
+ }
127
129
  }
128
130
 
129
131
  function addUrlToGraph(url, parent) {
130
- if (!(url in moduleGraph))
131
- moduleGraph[url] = new Set()
132
+ if (!(url in moduleGraph))
133
+ moduleGraph[url] = new Set()
132
134
 
133
- moduleGraph[url].add(parent)
134
- return url + (filesRecord.has(url) ? `?t=${filesRecord.get(url)}` : '')
135
+ moduleGraph[url].add(parent)
136
+ return url + (filesRecord.has(url) ? `?t=${filesRecord.get(url)}` : '')
135
137
  }
136
138
 
137
139
  function getFileMid(file) {
138
- const filename = basename(file)
139
- const ret = filename.split('.')
140
- if (!['js', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].includes(ret.pop()))
141
- return ''
142
- if (!ret[0])// .dockerfile
143
- return ''
144
-
145
- return ret[1]
140
+ const filename = basename(file)
141
+ const ret = filename.split('.')
142
+ if (!['js', 'mjs', 'cjs', 'ts', 'tsx', 'mts', 'cts'].includes(ret.pop()))
143
+ return ''
144
+ if (!ret[0]) // .dockerfile
145
+ return ''
146
+
147
+ return ret[1]
146
148
  }
147
149
 
148
- export const resolve = async (specifier, context, nextResolve) => {
149
- if (customResolve) {
150
- const url = await customResolve(specifier, context)
151
- if (url) {
152
- return {
153
- format: 'ts',
154
- url,
155
- shortCircuit: true,
156
- }
157
- }
158
- }
150
+ export const resolve = async(specifier, context, nextResolve) => {
151
+ if (customResolve) {
152
+ const url = await customResolve(specifier, context)
153
+ if (url) {
154
+ return {
155
+ format: 'ts',
156
+ url,
157
+ shortCircuit: true,
158
+ }
159
+ }
160
+ }
159
161
 
160
- // entrypoint
161
- if (!context.parentURL)
162
- return nextResolve(specifier)
162
+ // entrypoint
163
+ if (!context.parentURL)
164
+ return nextResolve(specifier)
163
165
 
164
- // @todo skip resolve to improve performance
165
- // if (context.parentURL.includes('/node_modules/') && specifier.includes('/node_modules/'))
166
- // return nextResolve(specifier)
166
+ // @todo skip resolve to improve performance
167
+ // if (context.parentURL.includes('/node_modules/') && specifier.includes('/node_modules/'))
168
+ // return nextResolve(specifier)
167
169
 
168
- const { resolvedModule } = ts.resolveModuleName(
169
- specifier,
170
- fileURLToPath(context.parentURL),
171
- tsconfig,
172
- host,
173
- moduleResolutionCache,
174
- )
175
-
176
- // import among files in local project
177
- if (
178
- resolvedModule
179
- && !resolvedModule.resolvedFileName.includes('/node_modules/')
180
- && EXTENSIONS.includes(resolvedModule.extension)
181
- ) {
182
- const url = addUrlToGraph(
183
- pathToFileURL(resolvedModule.resolvedFileName).href,
184
- context.parentURL.split('?')[0],
185
- )
170
+ const { resolvedModule } = ts.resolveModuleName(
171
+ specifier,
172
+ fileURLToPath(context.parentURL),
173
+ tsconfig,
174
+ host,
175
+ moduleResolutionCache,
176
+ )
186
177
 
187
- const importerMid = getFileMid(context.parentURL)
188
- const sourceMid = getFileMid(resolvedModule.resolvedFileName)
189
- if (config.resolve && importerMid && sourceMid) {
190
- const resolver = config.resolve.find(
191
- item => item.source === sourceMid && item.importer === importerMid,
192
- )
193
- if (resolver) {
194
- return {
195
- format: 'ts',
196
- url: pathToFileURL(resolvePath(workdir, resolver.path)).href,
197
- shortCircuit: true,
178
+ // import among files in local project
179
+ if (
180
+ resolvedModule &&
181
+ !resolvedModule.resolvedFileName.includes('/node_modules/') &&
182
+ EXTENSIONS.includes(resolvedModule.extension)
183
+ ) {
184
+ const url = addUrlToGraph(
185
+ pathToFileURL(resolvedModule.resolvedFileName).href,
186
+ context.parentURL.split('?')[0],
187
+ )
188
+
189
+ const importerMid = getFileMid(context.parentURL)
190
+ const sourceMid = getFileMid(resolvedModule.resolvedFileName)
191
+ if (config.resolve && importerMid && sourceMid) {
192
+ const resolver = config.resolve.find(
193
+ item => item.source === sourceMid && item.importer === importerMid,
194
+ )
195
+ if (resolver) {
196
+ return {
197
+ format: 'ts',
198
+ url: pathToFileURL(resolvePath(workdir, resolver.path)).href,
199
+ shortCircuit: true,
200
+ }
201
+ }
202
+ }
203
+
204
+ return {
205
+ format: 'ts',
206
+ url,
207
+ shortCircuit: true,
208
+ }
198
209
  }
199
- }
200
- }
201
210
 
202
- return {
203
- format: 'ts',
204
- url,
205
- shortCircuit: true,
206
- }
207
- }
211
+ const resolveRet = await nextResolve(specifier)
208
212
 
209
- const resolveRet = await nextResolve(specifier)
213
+ // ts resolve fail in some cases
214
+ if (resolveRet.url && isAbsolute(resolveRet.url)) {
215
+ const [path, query] = resolveRet.url.split('?')
216
+ resolveRet.url = pathToFileURL(path).href + (query ? `?${query}` : '')
217
+ }
210
218
 
211
- // ts resolve fail in some cases
212
- if (resolveRet.url && isAbsolute(resolveRet.url)) {
213
- const [path, query] = resolveRet.url.split('?')
214
- resolveRet.url = pathToFileURL(path).href + (query ? `?${query}` : '')
215
- }
219
+ return resolveRet
220
+ }
221
+ // @todo the first params may be url or path, need to distinguish
216
222
 
217
- return resolveRet
218
- }
219
- // @todo the first params may be url or path, need to distinguish
220
-
221
- export const load = async (url, context, nextLoad) => {
222
- let mode
223
- if (context.importAttributes.ps) {
224
- mode = context.importAttributes.ps
225
- delete context.importAttributes.ps
226
- }
227
-
228
- url = url.split('?')[0]
229
-
230
- if (
231
- !url.includes('/node_modules/')
232
- && url.startsWith('file://')
233
- && !watchFiles.has(url)
234
- && !isLowVersion
235
- ) {
236
- watchFiles.add(url)
237
-
238
- if (IS_DEV && mode !== 'not-hmr') {
239
- if (isModuleFileUrl(url)) {
240
- port.postMessage(
241
- JSON.stringify({
242
- type: 'init',
243
- files: [fileURLToPath(url)],
244
- }),
245
- )
246
- }
223
+ export const load = async(url, context, nextLoad) => {
224
+ let mode
225
+ if (context.importAttributes.ps) {
226
+ mode = context.importAttributes.ps
227
+ delete context.importAttributes.ps
228
+ }
247
229
 
248
- chokidar.watch(fileURLToPath(url), { persistent: true }).on(
249
- 'change',
250
- debounce(() => {
251
- try {
252
- const files = [...findTopScope(url, Date.now())].reverse()
230
+ url = url.split('?')[0]
231
+
232
+ if (!url.includes('/node_modules/') &&
233
+ url.startsWith('file://') &&
234
+ !watchFiles.has(url) &&
235
+ !isLowVersion
236
+ ) {
237
+ watchFiles.add(url)
238
+
239
+ if (IS_DEV && mode !== 'not-hmr') {
240
+ if (isModuleFileUrl(url)) {
241
+ port.postMessage(
242
+ JSON.stringify({
243
+ type: 'init',
244
+ files: [fileURLToPath(url)],
245
+ }),
246
+ )
247
+ }
253
248
 
254
- port.postMessage(
255
- JSON.stringify({
256
- type: 'change',
257
- files,
258
- }),
259
- )
260
- }
261
- catch (e) {
262
- port.postMessage(
263
- JSON.stringify({
264
- type: 'relaunch',
265
- }),
249
+ chokidar.watch(fileURLToPath(url), { persistent: true }).on(
250
+ 'change',
251
+ debounce(() => {
252
+ try {
253
+ const files = [...findTopScope(url, Date.now())].reverse()
254
+
255
+ port.postMessage(
256
+ JSON.stringify({
257
+ type: 'change',
258
+ files,
259
+ }),
260
+ )
261
+ } catch (e) {
262
+ port.postMessage(
263
+ JSON.stringify({
264
+ type: 'relaunch',
265
+ }),
266
+ )
267
+ }
268
+ }),
266
269
  )
267
- }
268
- }),
269
- )
270
+ }
270
271
  }
271
- }
272
- // after hmr
273
- if (customLoad) {
274
- const source = await customLoad(url, context)
275
- if (source) {
276
- return {
277
- format: 'module',
278
- source,
279
- shortCircuit: true,
280
- }
272
+ // after hmr
273
+ if (customLoad) {
274
+ const source = await customLoad(url, context)
275
+ if (source) {
276
+ return {
277
+ format: 'module',
278
+ source,
279
+ shortCircuit: true,
280
+ }
281
+ }
281
282
  }
282
- }
283
- // resolveModuleName failed
284
- // I don't know why it failed
285
- if (!context.format && url.endsWith('.ts'))
286
- context.format = 'ts'
287
283
 
288
- if (context.format === 'ts') {
289
- const { source } = await nextLoad(url, context)
290
-
291
- const code
292
- = typeof source === 'string' ? source : Buffer.from(source).toString()
293
-
294
- const compiled = (await compile(code, url)).replace(/_ts_metadata\(\"design:paramtypes\"\,/g, '_ts_metadata("design:paramtypes",()=>')// handle cycle
295
-
296
- if (unimportRet) {
297
- const { injectImports } = unimportRet
298
-
299
- return {
300
- format: 'module',
301
- source: (
302
- await injectImports(
303
- compiled,
304
- slash(url.startsWith('file://') ? fileURLToPath(url) : url),
305
- )
306
- ).code,
307
- shortCircuit: true,
308
- }
309
- }
310
- return {
311
- format: 'module',
312
- source: compiled,
313
- shortCircuit: true,
284
+
285
+ // resolveModuleName failed
286
+ // I don't know why it failed
287
+ if ( url.endsWith('.ts'))
288
+ context.format = 'ts'
289
+
290
+ // module-typescript???
291
+
292
+ if (context.format === 'ts') {
293
+ const { source } = await nextLoad(url, context)
294
+
295
+ const code = typeof source === 'string' ? source : Buffer.from(source).toString()
296
+
297
+ const compiled = await compile(code, url, config?.swc)
298
+
299
+ if (unimportRet) {
300
+ const { injectImports } = unimportRet
301
+
302
+ return {
303
+ format: 'module',
304
+ source: (
305
+ await injectImports(
306
+ compiled,
307
+ slash(url.startsWith('file://') ? fileURLToPath(url) : url),
308
+ )
309
+ ).code,
310
+ shortCircuit: true,
311
+ }
312
+ }
313
+ return {
314
+ format: 'module',
315
+ source: compiled,
316
+ shortCircuit: true,
317
+ }
318
+ } else {
319
+ return nextLoad(url, context)
314
320
  }
315
- }
316
- else {
317
- return nextLoad(url, context)
318
- }
319
321
  }
320
322
 
321
323
  function findTopScope(url, time, modules = new Set()) {
322
- filesRecord.set(url, time)
323
- if (isModuleFileUrl(url)) {
324
- modules.add(fileURLToPath(url))
325
- }
326
- else {
327
- if (!moduleGraph[url])
328
- throw new Error('root file update')
329
- for (const i of [...moduleGraph[url]]) findTopScope(i, time, modules)
330
- }
331
-
332
- return modules
324
+ filesRecord.set(url, time)
325
+ if (isModuleFileUrl(url)) {
326
+ modules.add(fileURLToPath(url))
327
+ } else {
328
+ if (!moduleGraph[url])
329
+ throw new Error('root file update')
330
+ for (const i of[...moduleGraph[url]]) findTopScope(i, time, modules)
331
+ }
332
+
333
+ return modules
333
334
  }
334
335
 
335
336
  function debounce(cb, timeout = 500) {
336
- let timer
337
- return (...args) => {
338
- if (timer)
339
- return
340
-
341
- timer = setTimeout(() => {
342
- cb(...args)
343
- timer = undefined
344
- }, timeout)
345
- }
337
+ let timer
338
+ return (...args) => {
339
+ if (timer)
340
+ return
341
+
342
+ timer = setTimeout(() => {
343
+ cb(...args)
344
+ timer = undefined
345
+ }, timeout)
346
+ }
346
347
  }
347
348
 
348
349
  export function isModuleFileUrl(url) {
349
- const midName = getFileMid(url)
350
- if (!midName)
351
- return false
352
- if (
353
- [
354
- 'controller',
355
- 'rpc',
356
- 'service',
357
- 'module',
358
- 'extension',
359
- 'ext',
360
- 'guard',
361
- 'addon',
362
- 'filter',
363
- 'pipe',
364
- 'solo',
365
- ].includes(midName)
366
- )
367
- return true
368
-
369
- return config.moduleFile && config.moduleFile.includes(midName)
370
- }
350
+ const midName = getFileMid(url)
351
+ if (!midName)
352
+ return false
353
+ if (
354
+ [
355
+ 'controller',
356
+ 'rpc',
357
+ 'service',
358
+ 'module',
359
+ 'extension',
360
+ 'ext',
361
+ 'guard',
362
+ 'addon',
363
+ 'filter',
364
+ 'pipe',
365
+ 'solo',
366
+ ].includes(midName)
367
+ )
368
+ return true
369
+
370
+ return config.moduleFile && config.moduleFile.includes(midName)
371
+ }
@@ -2,85 +2,58 @@ import { basename } from 'path'
2
2
  import { transform } from '@swc-node/core'
3
3
  import psExports from './export.mjs'
4
4
  const injectInlineSourceMap = ({ code, map }) => {
5
- if (map) {
6
- const base64Map = Buffer.from(map, 'utf8').toString('base64')
7
- const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`
8
- return `${code}\n${sourceMapContent}`
9
- }
10
- return code
5
+ if (map) {
6
+ const base64Map = Buffer.from(map, 'utf8').toString('base64')
7
+ const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`
8
+ return `${code}\n${sourceMapContent}`
9
+ }
10
+ return code
11
11
  }
12
12
 
13
- export async function compile(sourcecode, filename) {
14
- if (filename.endsWith('.d.ts'))
15
- return ''
16
-
17
- const { code, map } = await transform(sourcecode, filename, {
18
- sourcemap: true,
19
- module: 'es6',
20
- emitDecoratorMetadata: true,
21
- experimentalDecorators: true,
22
- esModuleInterop: false,
23
- swc: {
24
-
25
- jsc: {
26
- parser: {
27
- syntax: 'typescript',
28
- importAttributes: true,
29
- decorators: true,
30
- tsx: false,
31
- dynamicImport: true,
32
- strictPropertyInitialization: false,
33
- },
34
- experimental: {
35
- keepImportAssertions: true,
36
- },
37
- transform: {
38
- legacyDecorator: true,
39
- decoratorMetadata: true,
40
- },
41
- // parser: {
42
- // importAttributes: true
43
- // },
44
- // experimental: {
45
- // keepImportAssertions: true
46
- // }
47
- },
48
- },
49
- })
13
+ export async function compile(sourcecode, filename, config = {}) {
14
+ if (filename.endsWith('.d.ts'))
15
+ return ''
16
+
17
+ const { code, map } = await transform(sourcecode, filename, {
18
+ sourcemap: true,
19
+ module: 'es6',
20
+ emitDecoratorMetadata: true,
21
+ experimentalDecorators: true,
22
+ esModuleInterop: false,
23
+ ...config
24
+ })
50
25
 
51
- return injectInlineSourceMap({ code, map })
26
+ return injectInlineSourceMap({ code, map })
52
27
  }
53
28
 
54
29
  export async function genUnImportRet(opts) {
55
- try {
56
- const { createUnimport } = await import('unimport')
57
- return createUnimport({
58
- ...opts,
59
-
60
- presets: [
61
- {
62
- from: 'phecda-server',
63
- imports: psExports,
64
- },
65
- ]
66
- .concat(opts.presets || []),
67
- })
68
- }
69
- catch (e) {
70
- console.error(e)
71
- return false
72
- }
30
+ try {
31
+ const { createUnimport } = await
32
+ import ('unimport')
33
+ return createUnimport({
34
+ ...opts,
35
+
36
+ presets: [{
37
+ from: 'phecda-server',
38
+ imports: psExports,
39
+ }, ]
40
+ .concat(opts.presets || []),
41
+ })
42
+ } catch (e) {
43
+ console.error(e)
44
+ return false
45
+ }
73
46
  }
74
47
 
75
48
  export function handleClassTypes(input) {
76
- return input.replace(/const\s+(\w+)\s*:\s*typeof\s+import\(['"](.+)['"]\)\['(\w+)'\]/g, (_, n, p, e) => {
77
- // TestController in test.controller
78
- if (p.startsWith('./') && (basename(p).replace('.', '').toLowerCase() === e.toLowerCase()))
79
- return `${_}\n type ${n} = InstanceType<typeof import('${p}')['${e}']>`
49
+ return input.replace(/const\s+(\w+)\s*:\s*typeof\s+import\(['"](.+)['"]\)\['(\w+)'\]/g, (_, n, p, e) => {
50
+ // TestController in test.controller
51
+ if (p.startsWith('./') && (basename(p).replace('.', '').toLowerCase() === e.toLowerCase()))
52
+ return `${_}\n type ${n} = InstanceType<typeof import('${p}')['${e}']>`
80
53
 
81
- return _
82
- })
54
+ return _
55
+ })
83
56
  }
84
57
  export function slash(str) {
85
- return str.replace(/\\/g, '/')
86
- }
58
+ return str.replace(/\\/g, '/')
59
+ }