@solayao/koa-server-kit 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/config.js ADDED
@@ -0,0 +1,295 @@
1
+ /** 字符映射表1:环境变量短/长别名到配置短 key 的映射 */
2
+ const tempKeyMapper = {
3
+ h: 'h',
4
+ host: 'h',
5
+ p: 'p',
6
+ port: 'p',
7
+ u: 'u',
8
+ user: 'u',
9
+ username: 'u',
10
+ pass: 'up',
11
+ password: 'up',
12
+ d: 'd',
13
+ database: 'd',
14
+ db: 'd',
15
+ charset: 'c',
16
+ sentinel_listeners: 'sl',
17
+ sentinel_watchers: 'sw'
18
+ }
19
+
20
+ /** 字符映射表2:反向聚合, 一个短 key 可对应多个别名 */
21
+ const tempKey2Mapper = Object.keys(tempKeyMapper).reduce((t, key) => {
22
+ if (!t.hasOwnProperty(tempKeyMapper[key])) {
23
+ t[tempKeyMapper[key]] = []
24
+ }
25
+
26
+ t[tempKeyMapper[key]].push(key)
27
+
28
+ return t
29
+ }, {})
30
+
31
+ /**
32
+ * 将配置字符串转换成对象后,合并到提供的默认值中
33
+ * 按别名映射解析, 未命中的字段回退到默认值
34
+ * @param {String} envStr 例如 "h 127.0.0.1 | p 3306 | u root | up pwd | d db"
35
+ * @param {Object} defaultVal 默认值
36
+ * @returns {Object}
37
+ */
38
+ export const solGetEnvStrToConfig = (envStr = '', defaultVal = {}) => {
39
+ if (envStr) {
40
+ const tempStrList = envStr.split(/\s*\|\s*/) // 字符串以 | 间隔开
41
+
42
+ const tempEnvObj = tempStrList.reduce((t, str) => {
43
+ const tempConfigMatch = /^(\w+)\s([\s\S]+)$/.exec(str)
44
+ if (tempConfigMatch) {
45
+ const tempKey = tempConfigMatch[1]
46
+ const tempKeyVal = tempConfigMatch[2]
47
+
48
+ if (Array.isArray(tempKey2Mapper[tempKey])) {
49
+ tempKey2Mapper[tempKey].forEach(kIt => {
50
+ if ([null, undefined, ''].includes(t[kIt])) { // 首次赋值
51
+ t[kIt] = tempKeyVal
52
+ } else if (!Array.isArray(t[kIt])) { // 第二次赋值
53
+ t[kIt] = [t[kIt], tempKeyVal]
54
+ } else { // 第二次后续赋值
55
+ t[kIt].push(tempKeyVal)
56
+ }
57
+ })
58
+ }
59
+ }
60
+
61
+ return t
62
+ }, {})
63
+
64
+ return Object.keys(defaultVal).reduce((t, k) => {
65
+ t[k] = ![null, undefined, ''].includes(tempEnvObj[k]) ? tempEnvObj[k] : defaultVal[k]
66
+
67
+ return t
68
+ }, {})
69
+ }
70
+
71
+ // 返回副本, 避免多处配置共享同一对象引用导致互相污染
72
+ return { ...defaultVal }
73
+ }
74
+
75
+ /** 系统默认配置, 由包内统一装配 */
76
+ export const System = {
77
+ API_server_type: 'http://', // API服务器协议类型,包含'http://'或'https://'
78
+ API_server_port: '10000', // API服务器监听的端口号
79
+ API_base_url: '', // API默认前缀 (排除^/public, ^/mock, ^/swagger格式路径)
80
+ System_country: 'zh-cn', // 所在国家的国家代码
81
+
82
+ Use_redis: false, // 是否启用redis, 可选值 false(不启用) one(单一) sentinel(哨兵)
83
+ Use_mysql: false, // 是否启用mysql
84
+ Docker_server_ip: process.env.APP_DOCKER_IP || '', // Docker服务的真实启用地址
85
+
86
+ Route_cache: false, // 是否启用请求缓存,需要Use_redis也同步开启才有效
87
+ Use_fulltext_search: false, // 搜索是否改用FULLTEXT(ngram)索引, 需先在数据库中建立全文索引
88
+ Check_connect_tofucat_system: [] // 系统将使用到的Tofucat系统, 配置会在启动系统后验证连接是否正常
89
+ }
90
+
91
+ /** 默认的Mysql配置 */
92
+ const DEFAULT_MYSQL_CONFIG = {
93
+ host: '127.0.0.1', // 服务器地址
94
+ /** --服务器防火墙记得开放设置的端口号限制----------------------------------------- */
95
+ port: 3306, // 数据库端口号
96
+ user: 'root', // 数据库用户名
97
+ password: '', // 数据库密码
98
+ database: 'test', // 数据库名称
99
+ charset: 'utf8mb4_unicode_ci',
100
+ connectionLimit: 20, // 连接池最大连接数
101
+ waitForConnections: true, // 连接池满时排队等待而非立即报错
102
+ queueLimit: 0, // 排队等待的请求数上限, 0为不限制
103
+ connectTimeout: 10000, // 建立连接超时(毫秒)
104
+ enableKeepAlive: true, // 保持连接, 避免长时间空闲后断连
105
+ keepAliveInitialDelay: 10000
106
+ }
107
+
108
+ /** 读写Mysql配置 */
109
+ export const CuidMysql = solGetEnvStrToConfig(
110
+ process.env.APP_CUID_MYSQL,
111
+ DEFAULT_MYSQL_CONFIG
112
+ )
113
+
114
+ /** 只读Mysql配置 */
115
+ export const ReadOnlyMysql = solGetEnvStrToConfig(
116
+ process.env.APP_READ_ONLY_MYSQL,
117
+ process.env.APP_READ_ONLY_MYSQL ? DEFAULT_MYSQL_CONFIG : {}
118
+ )
119
+
120
+ /** 单一Redis配置 */
121
+ export const OneRedis = solGetEnvStrToConfig(
122
+ process.env.APP_ONE_REDIS,
123
+ {
124
+ host: '127.0.0.1', // Redis host
125
+ /** --服务器防火墙记得开放设置的端口号限制----------------------------------------- */
126
+ port: 6379, // Redis port
127
+ password: '', // Redis Password
128
+ db: 0 // Defaults to 0
129
+ }
130
+ )
131
+
132
+ /**
133
+ * 哨兵Redis配置转换
134
+ * @param {Object} obj
135
+ * @returns {Object}
136
+ */
137
+ const solTransferSentinelConfig = obj => Object.keys(obj).reduce((t, k) => {
138
+ if (k == 'sentinel_listeners' || k == 'sentinel_watchers') {
139
+ if (Array.isArray(obj[k]) && obj[k].length) {
140
+ obj[k].forEach(str => {
141
+ let tempStrList = str.split(' ')
142
+
143
+ if (tempStrList[0] && tempStrList[1]) {
144
+ const PROXY_KEY_STR = '->'
145
+
146
+ const tempHostList = tempStrList[0].split(PROXY_KEY_STR)
147
+ const tempPortList = tempStrList[1].split(PROXY_KEY_STR)
148
+
149
+ const tempVal = {
150
+ host: tempHostList[0],
151
+ port: tempPortList[0]
152
+ }
153
+
154
+ if (tempStrList[2]) {
155
+ tempVal.password = tempStrList[2]
156
+ }
157
+
158
+ t.natMap[`${tempVal.host}:${tempVal.port}`] = {
159
+ ...tempVal,
160
+ host: tempHostList[1] || tempHostList[0],
161
+ port: tempPortList[1] || tempPortList[0]
162
+ }
163
+
164
+ if (k == 'sentinel_listeners') {
165
+ t.sentinels.push(t.natMap[`${tempVal.host}:${tempVal.port}`])
166
+ }
167
+ }
168
+ })
169
+ }
170
+ } else {
171
+ t[k] = obj[k]
172
+ }
173
+ return t
174
+ }, {
175
+ natMap: {},
176
+ sentinels: []
177
+ })
178
+
179
+ /** 哨兵Redis配置 */
180
+ export const SentinelRedis = solTransferSentinelConfig(solGetEnvStrToConfig(
181
+ process.env.APP_SENTINEL_REDIS,
182
+ {
183
+ db: 0, // Defaults to 0
184
+ /** --服务器防火墙记得开放设置的端口号限制----------------------------------------- */
185
+ sentinel_listeners: [], // 监听Sentineler 'host(->trulyHost)? port(->trulyPort)? (password)?'[]
186
+ sentinel_watchers: [] // 被监听Master,Slave 'host(->trulyHost)? port(->trulyPort)? (password)?'[]
187
+ }
188
+ ))
189
+
190
+ /**
191
+ * 获取值的原始类型
192
+ * @param {*} val
193
+ * @returns {String}
194
+ */
195
+ const getPrototypeType = val => {
196
+ const tempMatch = Object.prototype.toString.call(val).match(/^\[object (\w+)\]$/)
197
+ return tempMatch ? tempMatch[1] : ''
198
+ }
199
+
200
+ /**
201
+ * 递归合并配置, data2 覆盖 data1
202
+ * 递归合并配置, 同名键以 data2 为准
203
+ * @param {Object} data1 默认配置
204
+ * @param {Object} data2 私有覆盖配置
205
+ * @returns {Object}
206
+ */
207
+ export const solMergeObject = (data1, data2) => {
208
+ if ([getPrototypeType(data1), getPrototypeType(data2)].every(it => (it == 'Object'))) {
209
+ const tempMergeDataKey = Array.from(new Set([...Object.keys(data1), ...Object.keys(data2)]))
210
+
211
+ return tempMergeDataKey.reduce((total, key) => {
212
+ if ([getPrototypeType(data1[key]), getPrototypeType(data2[key])].every(it => (it == 'Object'))) { // 合并值对应类型为对象
213
+ total[key] = solMergeObject(data1[key], data2[key])
214
+ } else { // 合并值对应类型不一致 或者 类型一致数值不一样,优先采用data2的值
215
+ total[key] = data2[key] !== undefined ? data2[key] : data1[key]
216
+ }
217
+
218
+ return total
219
+ }, {})
220
+ }
221
+
222
+ return {}
223
+ }
224
+
225
+ /**
226
+ * 获取最终配置, 返回默认配置与覆盖项的合并结果
227
+ * 作为 createConfig 返回对象的方法使用时, this 即宿主私有配置对象
228
+ * @param {String} configKey 例如 System / CuidMysql
229
+ * @returns {Object}
230
+ */
231
+ export function solGetConfig(configKey) {
232
+ const source = this || {}
233
+
234
+ const tempObj = {
235
+ ...source,
236
+ System: solMergeObject(System, source.System || {}),
237
+ CuidMysql: solMergeObject(CuidMysql, source.CuidMysql || {}),
238
+ ReadOnlyMysql: solMergeObject(ReadOnlyMysql, source.ReadOnlyMysql || {}),
239
+ OneRedis: solMergeObject(OneRedis, source.OneRedis || {}),
240
+ SentinelRedis: solMergeObject(SentinelRedis, source.SentinelRedis || {})
241
+ }
242
+
243
+ if (tempObj.hasOwnProperty(configKey)) {
244
+ return tempObj[configKey]
245
+ }
246
+
247
+ throw new Error(`属性${configKey}在配置中定义未定义`)
248
+ }
249
+
250
+ /**
251
+ * 组装配置对象, 附带 solGetConfig / solMergeObject 方法
252
+ * @param {Object} overrides 覆盖项
253
+ * @returns {Object} 可直接用于 solGetConfig 取值的配置对象
254
+ */
255
+ export const createConfig = (overrides = {}) => ({
256
+ ...overrides,
257
+ solGetConfig,
258
+ solMergeObject
259
+ })
260
+
261
+ /** 包内已装配好的默认配置, 业务代码直接通过solGetConfig取值 */
262
+ const config = createConfig()
263
+
264
+ /** 配置只允许在createApiServer启动时注入一次, 注入后冻结, 运行时不可修改 */
265
+ let configInjected = false
266
+
267
+ /**
268
+ * 由createApiServer在启动时一次性注入配置特色化并冻结;
269
+ * 重复注入(带实质覆盖项)直接抛错, 保证运行期配置不可变
270
+ * @param {Object} overrides 配置覆盖项
271
+ * @returns {Object} 冻结后的配置单例
272
+ */
273
+ export const applyConfigOnce = (overrides = {}) => {
274
+ const overrideKeys = Object.keys(overrides).filter(key => !['solGetConfig', 'solMergeObject'].includes(key))
275
+
276
+ if (configInjected) {
277
+ if (overrideKeys.length) {
278
+ throw new Error('[koa-server-kit] config 只能在 createApiServer 注入一次, 后续不可修改')
279
+ }
280
+ return config
281
+ }
282
+
283
+ overrideKeys.forEach(key => { config[key] = overrides[key] })
284
+ configInjected = true
285
+
286
+ // 冻结各配置块与顶层, 防止运行时通过 import config 直接改写
287
+ Object.keys(config).forEach(key => {
288
+ if (typeof config[key] === 'object' && config[key] !== null) Object.freeze(config[key])
289
+ })
290
+ Object.freeze(config)
291
+
292
+ return config
293
+ }
294
+
295
+ export default config
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from './config.js'
2
+ export * from './server/index.js'
3
+ export * from './routes/index.js'
4
+ export * from './middleware/index.js'
5
+ export * from './auth/index.js'
6
+ export * from './plugins/index.js'
7
+ export * from './tools/index.js'
@@ -0,0 +1,21 @@
1
+ /** 统一错误响应体, 保留原始HTTP状态码 */
2
+ export const errorRoutesCatch = async (ctx, next) => {
3
+ try {
4
+ await next()
5
+ } catch (err) {
6
+ const status = Number(err.status || err.statusCode || 500)
7
+ const message = status >= 500 ? (err.message || '服务器内部错误') : (err.message || '请求失败')
8
+
9
+ ctx.status = status
10
+ ctx.body = {
11
+ code: status,
12
+ error: message,
13
+ result: {},
14
+ ...(process.env.NODE_ENV === 'development' && err.stack ? { stack: err.stack } : {})
15
+ }
16
+
17
+ ctx.app.emit('error', err, ctx)
18
+ }
19
+ }
20
+
21
+ export default errorRoutesCatch
@@ -0,0 +1,150 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import KoaBody from 'koa-body'
4
+ import KoaStatic from 'koa-static2'
5
+ import jwt from 'koa-jwt'
6
+ import { resolveJwtSecret } from '../auth/JwtSecret.js'
7
+ import { defaultLogger, solLogKoaRoute } from '../tools/LogColor.js'
8
+ import { errorRoutesCatch } from './ErrorRoutesCatch.js'
9
+
10
+ /** 进程内IP限流计数桶, 每分钟清理过期项避免内存增长 */
11
+ const rateBucket = {}
12
+ const rateCleanTimer = setInterval(() => {
13
+ const now = Date.now()
14
+ Object.keys(rateBucket).forEach(key => {
15
+ if (rateBucket[key].start + 60 * 1000 <= now) {
16
+ delete rateBucket[key]
17
+ }
18
+ })
19
+ }, 60 * 1000)
20
+ rateCleanTimer.unref()
21
+
22
+ /** 把字符串/数组形式的IP列表统一成数组 */
23
+ const parseIpList = (list = []) => (Array.isArray(list) ? list : `${list || ''}`.split(/[\s,]+/)).filter(Boolean)
24
+
25
+ /** 注册通用全局中间件, 路径/目录/阈值由options注入 */
26
+ export const createMiddlewareLoader = ({ app, options = {}, adapters = {} } = {}) => {
27
+ const logger = options.logger || defaultLogger
28
+ const log = logger.error ? logger.error.bind(logger) : (...args) => logger.log(...args)
29
+
30
+ const trustedIps = parseIpList(options.currentIps)
31
+ const staticDirs = options.staticDirs || (options.staticDir ? [options.staticDir] : [])
32
+ const jwtSecret = resolveJwtSecret()
33
+ const isDev = !!options.isDev
34
+ const internalTokenPath = options.internalTokenPath || '/public/internal/token'
35
+ const uploadTmpDir = options.uploadTmpDir || path.join(process.cwd(), 'assets/uploads/tmp')
36
+
37
+ // formidable写临时文件前必须确保目录存在, 否则multipart上传直接报错
38
+ fs.mkdirSync(uploadTmpDir, { recursive: true })
39
+
40
+ const register = () => {
41
+ // 1. 全局ctx注入: 宿主配置 + 插件上下文
42
+ app.use(async (ctx, next) => {
43
+ Object.assign(ctx, options.lclCtx || {}, adapters.pluginContext || {})
44
+
45
+ // 补齐ctx.$ips: 信任IP + 实际socket + XFF链, 供CORS与内部token鉴权复用
46
+ const xff = ctx.get('X-Forwarded-For') || ''
47
+ ctx.$ips = [...new Set([
48
+ ...trustedIps,
49
+ ctx.request.ip,
50
+ ...xff.split(',').map(item => item.trim()).filter(Boolean)
51
+ ])].filter(Boolean)
52
+
53
+ await next()
54
+ })
55
+
56
+ // 2. 路径日志输出, 宿主可通过adapters.logger替换
57
+ app.use(adapters.logger || solLogKoaRoute())
58
+
59
+ // 3. CORS: 仅对信任来源回显Origin并允许携带cookie, 不全局放开'*'
60
+ app.use(async (ctx, next) => {
61
+ const origin = ctx.request.header.origin || ''
62
+ const originIp = origin.replace(/^https?:\/\//, '').split(':')[0]
63
+
64
+ if (originIp && (ctx.$ips || []).some(ip => ip === originIp)) {
65
+ ctx.set('Access-Control-Allow-Origin', origin)
66
+ ctx.set('Access-Control-Allow-Credentials', 'true')
67
+ ctx.set('Vary', 'Origin')
68
+ }
69
+
70
+ ctx.set('Access-Control-Allow-Headers', 'Accept, Accept-Language, Content-Language, Content-Type, Authorization, X-Platform-Key, rk, trk')
71
+ ctx.set('Access-Control-Allow-Methods', 'PUT, POST, GET, DELETE, OPTIONS')
72
+
73
+ if (ctx.method === 'OPTIONS') {
74
+ return ctx.status = 204
75
+ }
76
+
77
+ await next()
78
+ })
79
+
80
+ // 4. 安全响应头 + 轻量IP限流(token接口单独收紧到10次/分钟)
81
+ app.use(async (ctx, next) => {
82
+ ctx.set('X-Content-Type-Options', 'nosniff')
83
+ ctx.set('X-Frame-Options', 'DENY')
84
+ ctx.set('Referrer-Policy', 'no-referrer')
85
+
86
+ const ip = ctx.ip || (ctx.request.socket && ctx.request.socket.remoteAddress) || ''
87
+ const now = Date.now()
88
+ const limit = ctx.path.startsWith(internalTokenPath)
89
+ ? (options.internalTokenRateLimitMax || 10)
90
+ : (options.rateLimitMax || 300)
91
+
92
+ if (!rateBucket[ip] || rateBucket[ip].start + 60 * 1000 <= now) {
93
+ rateBucket[ip] = { start: now, count: 0 }
94
+ }
95
+
96
+ rateBucket[ip].count++
97
+ if (rateBucket[ip].count > limit) {
98
+ ctx.throw(429, '请求过于频繁')
99
+ }
100
+
101
+ await next()
102
+ })
103
+
104
+ // 5. body解析: GET/HEAD/DELETE也解析
105
+ app.use(KoaBody({
106
+ multipart: true,
107
+ parsedMethods: ['POST', 'PUT', 'PATCH', 'GET', 'HEAD', 'DELETE'],
108
+ formidable: {
109
+ uploadDir: uploadTmpDir
110
+ },
111
+ jsonLimit: options.jsonLimit || '10mb',
112
+ formLimit: options.formLimit || '10mb',
113
+ textLimit: options.textLimit || '10mb'
114
+ }))
115
+
116
+ // 6. 静态资源: koa-static2第一参数是路由前缀, 第二参数才是目录
117
+ staticDirs.forEach(dir => app.use(KoaStatic('assets', path.resolve(dir))))
118
+
119
+ // 7. 错误捕获必须放在鉴权前, 才能统一处理koa-jwt抛出的401
120
+ app.use(errorRoutesCatch)
121
+
122
+ // 8. JWT鉴权, unless规则可通过options.jwtUnless覆盖
123
+ if (jwtSecret) {
124
+ const defaultCustom = (ctx) => {
125
+ // CORS预检请求不携带Authorization, 必须放行
126
+ if (ctx.method === 'OPTIONS') return true
127
+
128
+ // Swagger全部放开
129
+ if (/^\/swagger/.test(ctx.path)) return true
130
+
131
+ // /public/mock 仅开发环境免鉴权, 生产环境需要合法token
132
+ if (/^\/public\/mock/.test(ctx.path)) return isDev
133
+
134
+ // 其余/public路由免鉴权
135
+ return /^\/public/.test(ctx.path)
136
+ }
137
+
138
+ app.use(jwt({
139
+ secret: jwtSecret,
140
+ debug: isDev
141
+ }).unless({
142
+ custom: typeof options.jwtUnless === 'function' ? options.jwtUnless : defaultCustom
143
+ }))
144
+ }
145
+
146
+ app.on('error', err => log(`[koa] ${err.stack || err.message}`))
147
+ }
148
+
149
+ return { register }
150
+ }
@@ -0,0 +1,2 @@
1
+ export * from './MiddlewareLoader.js'
2
+ export * from './ErrorRoutesCatch.js'
@@ -0,0 +1,130 @@
1
+ import fs from 'fs'
2
+ import path from 'path'
3
+ import { pathToFileURL } from 'url'
4
+ import { defaultLogger } from '../tools/LogColor.js'
5
+
6
+ /**
7
+ * 解析单个插件模块的导出, 兼容三种写法:
8
+ * 1. export default () => ({ key, value }) -> ctx.$key = value
9
+ * 2. export const fn = () => ({ key, value }) -> ctx.$key = value
10
+ * 3. export default { $foo: instance } -> ctx.$foo = instance
11
+ * @returns {Object} 可直接Object.assign到ctx的对象
12
+ */
13
+ const solResolvePlugin = (pluginModule = {}, pluginName = '', logger = defaultLogger) => {
14
+ const log = logger.error ? logger.error.bind(logger) : (...args) => logger.log(...args)
15
+ const tempCandidates = [pluginModule.default, pluginModule.fn, pluginModule]
16
+
17
+ for (const candidate of tempCandidates) {
18
+ if (!candidate) continue
19
+
20
+ let tempExports = candidate
21
+
22
+ // 插件允许导出工厂函数, 调用后拿到要注入的对象
23
+ if (typeof candidate === 'function') {
24
+ try {
25
+ tempExports = candidate()
26
+ } catch (err) {
27
+ log(`[plugin] ${pluginName}初始化失败: ${err.message}`)
28
+ continue
29
+ }
30
+ }
31
+
32
+ if (!tempExports || typeof tempExports !== 'object') continue
33
+
34
+ // 约定一: { key: 'xxx', value: instance } -> { $xxx: instance }
35
+ if (typeof tempExports.key === 'string' && tempExports.key) {
36
+ return { [`$${tempExports.key}`]: tempExports.value }
37
+ }
38
+
39
+ // 约定二: 直接导出映射, 统一补$前缀; 已带$的键保持不变
40
+ const tempKeys = Object.keys(tempExports).filter(key => !['default', 'fn'].includes(key))
41
+ if (tempKeys.length) {
42
+ return tempKeys.reduce((total, key) => {
43
+ total[key.startsWith('$') ? key : `$${key}`] = tempExports[key]
44
+ return total
45
+ }, {})
46
+ }
47
+ }
48
+
49
+ return {}
50
+ }
51
+
52
+ /**
53
+ * 扫描插件目录: 只认每个子目录下的index.js
54
+ * 热更新通过动态import附带时间戳参数绕过模块缓存实现
55
+ */
56
+ const solScanPlugins = async ({
57
+ pluginDir = '',
58
+ logger = defaultLogger,
59
+ hotReload = false
60
+ } = {}) => {
61
+ const tempResult = {}
62
+
63
+ if (!pluginDir || !fs.existsSync(pluginDir)) {
64
+ return tempResult
65
+ }
66
+
67
+ const entries = fs.readdirSync(pluginDir, { withFileTypes: true })
68
+
69
+ for (const entry of entries) {
70
+ // 必须是子目录, 且包含index.js
71
+ if (!entry.isDirectory()) continue
72
+
73
+ const tempEntry = path.join(pluginDir, entry.name, 'index.js')
74
+ if (!fs.existsSync(tempEntry)) continue
75
+
76
+ try {
77
+ const tempSearch = hotReload ? `?t=${Date.now()}` : ''
78
+ const module = await import(`${pathToFileURL(tempEntry).href}${tempSearch}`)
79
+ Object.assign(tempResult, solResolvePlugin(module, entry.name, logger))
80
+ } catch (err) {
81
+ const log = logger.error ? logger.error.bind(logger) : (...args) => logger.log(...args)
82
+ log(`[plugin] ${entry.name}加载失败: ${err.message}`)
83
+ }
84
+ }
85
+
86
+ return tempResult
87
+ }
88
+
89
+ /**
90
+ * 创建插件加载器, 持有内置插件初始化函数与外部插件目录
91
+ * @param {Object} options
92
+ * @param {String} options.pluginDir 外部插件目录绝对路径
93
+ * @param {Function} options.initializer 内置插件初始化函数, 由宿主注入(如api-data initPlugins)
94
+ * @param {Function} options.configure 内置插件配置函数, 由宿主注入(如api-data configureSqls)
95
+ * @returns {Promise<Object>} 注入到ctx的插件对象, 例如 { $mysql, $redis, $custom }
96
+ */
97
+ export const createPluginLoader = ({
98
+ pluginDir = '',
99
+ initializer = null,
100
+ configure = null,
101
+ logger = defaultLogger,
102
+ hotReload = true
103
+ } = {}) => {
104
+ return async () => {
105
+ let tempBuiltin = {}
106
+
107
+ // 1. 内置插件由宿主提供初始化能力, 包本身不绑定api-data
108
+ if (initializer) {
109
+ const tempPlugins = await initializer()
110
+
111
+ // 兼容api-data返回 { mysql, redis } 或直接返回映射
112
+ if (tempPlugins && typeof tempPlugins === 'object') {
113
+ tempBuiltin = Object.keys(tempPlugins).reduce((total, key) => {
114
+ total[key.startsWith('$') ? key : `$${key}`] = tempPlugins[key]
115
+ return total
116
+ }, {})
117
+ }
118
+ }
119
+
120
+ // 2. SQL全局配置同样由宿主注入
121
+ if (configure) {
122
+ await configure()
123
+ }
124
+
125
+ // 3. 外部插件在内置插件之后合并, 同名键可用于覆盖内置实现
126
+ const tempExternal = await solScanPlugins({ pluginDir, logger, hotReload })
127
+
128
+ return { ...tempBuiltin, ...tempExternal }
129
+ }
130
+ }
@@ -0,0 +1 @@
1
+ export * from './PluginLoader.js'