@kne/fastify-app-manager 0.1.29 → 0.1.31

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.
@@ -0,0 +1,405 @@
1
+ const fp = require('fastify-plugin');
2
+ const { KIND_LINKED, isLinked, linkedBaseUrl } = require('../utils/appKind');
3
+ const { mergeAppPermissionTree } = require('../utils/permissionSnapshot');
4
+ const { createProxyAuditStore } = require('../utils/proxyAudit');
5
+
6
+ const NAME_RE = /^[a-z0-9]([a-z0-9-]{0,62}[a-z0-9])?$/;
7
+
8
+ const decodeInstallKey = installKey => {
9
+ try {
10
+ return JSON.parse(Buffer.from(String(installKey), 'base64url').toString('utf8'));
11
+ } catch (e) {
12
+ const err = new Error('installKey 无效');
13
+ err.statusCode = 400;
14
+ throw err;
15
+ }
16
+ };
17
+
18
+ const unwrapEnvelope = async response => {
19
+ const text = await response.text();
20
+ let body;
21
+ try {
22
+ body = text ? JSON.parse(text) : {};
23
+ } catch (e) {
24
+ body = { message: text };
25
+ }
26
+ // app-runtime sendJson 可能包一层 { data } 或业务直接返回
27
+ if (body && Object.prototype.hasOwnProperty.call(body, 'data') && body.statusCode == null) {
28
+ return { ok: response.ok, status: response.status, data: body.data, raw: body };
29
+ }
30
+ if (body && body.data !== undefined && (body.statusCode || body.code)) {
31
+ return { ok: response.ok, status: response.status, data: body.data, raw: body };
32
+ }
33
+ return { ok: response.ok, status: response.status, data: body, raw: body };
34
+ };
35
+
36
+ module.exports = fp(async (fastify, options) => {
37
+ const { models } = fastify[options.name];
38
+ const proxyAudit = createProxyAuditStore({ appsRoot: options.appsRoot });
39
+
40
+ const httpError = (statusCode, message) => {
41
+ if (fastify.httpErrors) {
42
+ if (statusCode === 404) throw fastify.httpErrors.notFound(message);
43
+ if (statusCode === 409) throw fastify.httpErrors.conflict(message);
44
+ if (statusCode === 400) throw fastify.httpErrors.badRequest(message);
45
+ if (statusCode === 502) throw fastify.httpErrors.badGateway(message);
46
+ }
47
+ const err = new Error(message);
48
+ err.statusCode = statusCode;
49
+ throw err;
50
+ };
51
+
52
+ const platformOrigin = () => String(options.origin || options.linkOrigin || '').replace(/\/+$/, '');
53
+
54
+ const signAssertion = async audience => {
55
+ if (typeof options.signPlatformAssertion === 'function') {
56
+ return options.signPlatformAssertion({ audience });
57
+ }
58
+ const signer = fastify.oidc?.platformAssertion;
59
+ if (signer?.sign) {
60
+ return signer.sign({ audience });
61
+ }
62
+ httpError(400, '未配置平台断言签发(需宿主接入 createAppOidc / fastify-oidc)');
63
+ };
64
+
65
+ const ensureOidc = async ({ app, remoteBaseUrl }) => {
66
+ if (typeof options.ensureLinkedRegistration === 'function') {
67
+ return options.ensureLinkedRegistration({ app, remoteBaseUrl });
68
+ }
69
+ httpError(400, '未配置 ensureLinkedRegistration,无法完成外部应用 OIDC 登记');
70
+ };
71
+
72
+ const getOpsToken = async (app, scope) => {
73
+ if (typeof options.getOpsServiceToken === 'function') {
74
+ return options.getOpsServiceToken({ app, scope });
75
+ }
76
+ if (typeof options.getServiceToken === 'function') {
77
+ return options.getServiceToken({ app, scope });
78
+ }
79
+ httpError(400, '未配置 getOpsServiceToken,无法代理远程运维接口');
80
+ };
81
+
82
+ const remoteFetch = async (app, { path: opsPath, method = 'GET', query, body, scope, auditAction, actor } = {}) => {
83
+ const baseUrl = linkedBaseUrl(app);
84
+ if (!baseUrl) {
85
+ httpError(400, '应用缺少 options.baseUrl');
86
+ }
87
+ const action = auditAction || opsPath.replace(/^\/app-ops\//, '').replace(/\//g, '.');
88
+ try {
89
+ const token = await getOpsToken(app, scope);
90
+ const url = new URL(opsPath.replace(/^\//, ''), `${baseUrl}/`);
91
+ if (query && typeof query === 'object') {
92
+ for (const [k, v] of Object.entries(query)) {
93
+ if (v !== undefined && v !== null && v !== '') {
94
+ url.searchParams.set(k, String(v));
95
+ }
96
+ }
97
+ }
98
+ const response = await fetch(url, {
99
+ method,
100
+ headers: Object.assign({ authorization: `Bearer ${token}` }, body ? { 'content-type': 'application/json' } : {}),
101
+ body: body ? JSON.stringify(body) : undefined,
102
+ signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
103
+ });
104
+ const { ok, status, data, raw } = await unwrapEnvelope(response);
105
+ if (!ok) {
106
+ const message = data?.message || raw?.message || raw?.data?.message || `远程 ${status}`;
107
+ await proxyAudit
108
+ .append({
109
+ appName: app.name,
110
+ action,
111
+ result: 'error',
112
+ statusCode: status,
113
+ actor,
114
+ detail: message
115
+ })
116
+ .catch(() => {});
117
+ httpError(status >= 400 && status < 600 ? status : 502, message);
118
+ }
119
+ await proxyAudit
120
+ .append({
121
+ appName: app.name,
122
+ action,
123
+ result: 'ok',
124
+ statusCode: 200,
125
+ actor,
126
+ detail: body?.file || query?.file || null
127
+ })
128
+ .catch(() => {});
129
+ return data;
130
+ } catch (e) {
131
+ if (!e.statusCode) {
132
+ await proxyAudit
133
+ .append({
134
+ appName: app.name,
135
+ action,
136
+ result: 'error',
137
+ statusCode: 502,
138
+ actor,
139
+ detail: e.message
140
+ })
141
+ .catch(() => {});
142
+ }
143
+ throw e;
144
+ }
145
+ };
146
+
147
+ const applyPermissionSnapshot = async (app, remotePermissions) => {
148
+ const previous = app.options?.permissionTree || null;
149
+ const tree = mergeAppPermissionTree(app.name, remotePermissions, previous);
150
+ const nextOptions = Object.assign({}, app.options || {}, {
151
+ permissionsSnapshot: remotePermissions,
152
+ permissionTree: tree,
153
+ permissionsSyncedAt: new Date().toISOString()
154
+ });
155
+ await app.update({ options: nextOptions });
156
+ await app.reload();
157
+ if (typeof options.onPermissionsSynced === 'function') {
158
+ await options.onPermissionsSynced({ app, tree, sourceKey: `app:${app.name}` });
159
+ }
160
+ return tree;
161
+ };
162
+
163
+ const assertNameAvailable = async name => {
164
+ const exists = await models.app.findOne({ where: { name } });
165
+ if (exists) {
166
+ httpError(409, `应用 ${name} 已存在`);
167
+ }
168
+ if (typeof options.getPermissionRootCodes === 'function') {
169
+ const roots = await options.getPermissionRootCodes();
170
+ const set = new Set((roots || []).map(String));
171
+ if (set.has(name)) {
172
+ httpError(409, `应用 name ${name} 与本平台权限顶层码冲突,请远程改名后重试`);
173
+ }
174
+ }
175
+ };
176
+
177
+ const slugifyName = raw => {
178
+ const name = String(raw || '')
179
+ .replace(/^@[^/]+\//, '')
180
+ .toLowerCase()
181
+ .replace(/[^a-z0-9-]+/g, '-')
182
+ .replace(/^-+|-+$/g, '')
183
+ .slice(0, 64);
184
+ return name;
185
+ };
186
+
187
+ /**
188
+ * 凭 installKey 导入外部应用:redeem → 建 linked 记录 → OIDC → activate
189
+ */
190
+ const importByInstallKey = async ({ installKey, name: overrideName, label: overrideLabel } = {}) => {
191
+ if (!installKey) {
192
+ httpError(400, 'installKey 必填');
193
+ }
194
+ const key = decodeInstallKey(installKey);
195
+ const origin = platformOrigin();
196
+ if (!origin) {
197
+ httpError(400, '宿主未配置 origin,无法导入外部应用');
198
+ }
199
+ if (String(key.platformOrigin || '').replace(/\/+$/, '') !== origin) {
200
+ httpError(400, 'installKey 不属于本平台(platformOrigin 不匹配)');
201
+ }
202
+ if (key.expiresAt && new Date(key.expiresAt).getTime() < Date.now()) {
203
+ httpError(400, 'installKey 已过期');
204
+ }
205
+ const baseUrl = String(key.baseUrl || '').replace(/\/+$/, '');
206
+ if (!baseUrl) {
207
+ httpError(400, 'installKey 缺少 baseUrl');
208
+ }
209
+ const name = overrideName || slugifyName(key.appName);
210
+ if (!name || !NAME_RE.test(name)) {
211
+ httpError(400, '应用 name 无效:请传合法 slug 或远程改名');
212
+ }
213
+ await assertNameAvailable(name);
214
+
215
+ const assertion = await signAssertion(baseUrl);
216
+ const redeemRes = await fetch(`${baseUrl}/app-ops/link/redeem`, {
217
+ method: 'POST',
218
+ headers: { 'content-type': 'application/json' },
219
+ body: JSON.stringify({
220
+ installId: key.installId,
221
+ installSecret: key.installSecret,
222
+ assertion
223
+ }),
224
+ signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
225
+ });
226
+ const redeemed = await unwrapEnvelope(redeemRes);
227
+ if (!redeemed.ok) {
228
+ httpError(redeemed.status || 502, redeemed.data?.message || '远程 redeem 失败');
229
+ }
230
+ const manifest = redeemed.data || {};
231
+ const label = overrideLabel || manifest.label || key.appLabel || name;
232
+ const entries = Array.isArray(manifest.entries) ? manifest.entries : [{ label: '首页', path: '/', showInCenter: true }];
233
+
234
+ const app = await models.app.create({
235
+ name,
236
+ label,
237
+ kind: KIND_LINKED,
238
+ domain: null,
239
+ icon: manifest.icon || null,
240
+ description: manifest.description || null,
241
+ env: {},
242
+ pm2Config: {},
243
+ options: {
244
+ kind: KIND_LINKED,
245
+ baseUrl,
246
+ linkStatus: 'pending_activate',
247
+ permissionsSnapshot: manifest.permissions || [],
248
+ capabilities: manifest.capabilities || {},
249
+ entries,
250
+ isPublic: true
251
+ },
252
+ port: null,
253
+ status: 'idle',
254
+ rootPath: null,
255
+ pm2Name: null,
256
+ message: null
257
+ });
258
+
259
+ let oidcInfo;
260
+ try {
261
+ oidcInfo = await ensureOidc({ app, remoteBaseUrl: baseUrl });
262
+ const activateAssertion = await signAssertion(baseUrl);
263
+ const activateRes = await fetch(`${baseUrl}/app-ops/link/activate`, {
264
+ method: 'POST',
265
+ headers: { 'content-type': 'application/json' },
266
+ body: JSON.stringify({
267
+ assertion: activateAssertion,
268
+ issuer: oidcInfo.issuer,
269
+ audience: oidcInfo.audience,
270
+ clientId: oidcInfo.clientId,
271
+ serviceClientId: oidcInfo.serviceClientId,
272
+ serviceClientSecret: oidcInfo.serviceClientSecret
273
+ }),
274
+ signal: AbortSignal.timeout(options.linkProxyTimeoutMs || 15000)
275
+ });
276
+ const activated = await unwrapEnvelope(activateRes);
277
+ if (!activated.ok) {
278
+ throw Object.assign(new Error(activated.data?.message || '远程 activate 失败'), { statusCode: activated.status || 502 });
279
+ }
280
+ await app.update({
281
+ status: 'running',
282
+ options: Object.assign({}, app.options, {
283
+ linkStatus: 'paired',
284
+ oidc: {
285
+ issuer: oidcInfo.issuer,
286
+ audience: oidcInfo.audience,
287
+ clientId: oidcInfo.clientId,
288
+ serviceClientId: oidcInfo.serviceClientId,
289
+ serviceClientSecret: oidcInfo.serviceClientSecret
290
+ }
291
+ }),
292
+ message: null
293
+ });
294
+ await app.reload();
295
+ await applyPermissionSnapshot(app, manifest.permissions || []);
296
+ } catch (e) {
297
+ if (typeof options.onAppRemoved === 'function' && oidcInfo) {
298
+ try {
299
+ await options.onAppRemoved({
300
+ app: Object.assign(app.toJSON(), {
301
+ options: Object.assign({}, app.options, { oidc: oidcInfo }),
302
+ env: {
303
+ OIDC_CLIENT_ID: oidcInfo.clientId,
304
+ OIDC_SERVICE_CLIENT_ID: oidcInfo.serviceClientId,
305
+ OIDC_AUDIENCE: oidcInfo.audience
306
+ }
307
+ })
308
+ });
309
+ } catch (cleanupErr) {
310
+ fastify.log.warn({ err: cleanupErr }, 'rollback linked OIDC failed');
311
+ }
312
+ }
313
+ await app.destroy().catch(() => {});
314
+ httpError(e.statusCode || 502, e.message || '导入外部应用失败');
315
+ }
316
+
317
+ return fastify[options.name].services.app.toPublicApp(app);
318
+ };
319
+
320
+ const syncOne = async app => {
321
+ if (!isLinked(app)) {
322
+ return null;
323
+ }
324
+ const baseUrl = linkedBaseUrl(app);
325
+ try {
326
+ await remoteFetch(app, {
327
+ path: '/app-ops/link/status',
328
+ query: { issuer: app.options?.oidc?.issuer },
329
+ scope: 'app-ops:permissions:read'
330
+ });
331
+ const perms = await remoteFetch(app, {
332
+ path: '/app-ops/permissions',
333
+ scope: 'app-ops:permissions:read'
334
+ });
335
+ let readyOk = false;
336
+ try {
337
+ const ready = await fetch(`${baseUrl}/ready`, { signal: AbortSignal.timeout(5000) });
338
+ readyOk = ready.ok;
339
+ } catch (e) {
340
+ readyOk = false;
341
+ }
342
+ await app.update({
343
+ status: readyOk ? 'running' : 'error',
344
+ message: readyOk ? null : '远程健康检查失败',
345
+ options: Object.assign({}, app.options || {}, {
346
+ linkStatus: 'paired'
347
+ })
348
+ });
349
+ await app.reload();
350
+ const remotePerms = perms?.permissions || perms || app.options?.permissionsSnapshot || [];
351
+ await applyPermissionSnapshot(app, remotePerms);
352
+ if (typeof options.ensureLinkedRegistration === 'function') {
353
+ await options.ensureLinkedRegistration({ app, remoteBaseUrl: baseUrl });
354
+ }
355
+ await app.reload();
356
+ return { name: app.name, ok: true, status: app.status };
357
+ } catch (e) {
358
+ // 远程不可达:沿用已有 permissionTree / snapshot,不清空
359
+ await app
360
+ .update({
361
+ status: 'error',
362
+ message: e.message
363
+ })
364
+ .catch(() => {});
365
+ return { name: app.name, ok: false, error: e.message };
366
+ }
367
+ };
368
+
369
+ const syncAllLinked = async () => {
370
+ const apps = await models.app.findAll({ where: { kind: KIND_LINKED } });
371
+ const results = [];
372
+ for (const app of apps) {
373
+ results.push(await syncOne(app));
374
+ }
375
+ return results.filter(Boolean);
376
+ };
377
+
378
+ const proxy = {
379
+ logs: (app, query) => remoteFetch(app, { path: '/app-ops/logs', query, scope: 'app-ops:logs:read' }),
380
+ logFiles: app => remoteFetch(app, { path: '/app-ops/logs/files', scope: 'app-ops:logs:read' }),
381
+ env: app => remoteFetch(app, { path: '/app-ops/env', scope: 'app-ops:env:read' }),
382
+ permissions: app => remoteFetch(app, { path: '/app-ops/permissions', scope: 'app-ops:permissions:read' }),
383
+ dbTables: app => remoteFetch(app, { path: '/app-ops/db/tables', scope: 'app-ops:db:read' }),
384
+ dbRows: (app, query) => remoteFetch(app, { path: '/app-ops/db/rows', query, scope: 'app-ops:db:read' }),
385
+ dbQuery: (app, body) => remoteFetch(app, { path: '/app-ops/db/query', method: 'POST', body, scope: 'app-ops:db:read' }),
386
+ dbSaveRow: (app, body) => remoteFetch(app, { path: '/app-ops/db/row/save', method: 'POST', body, scope: 'app-ops:db:write' }),
387
+ dbRemoveRow: (app, body) => remoteFetch(app, { path: '/app-ops/db/row/remove', method: 'POST', body, scope: 'app-ops:db:write' }),
388
+ migrationsList: app => remoteFetch(app, { path: '/app-ops/migrations/list', scope: 'app-ops:migrations:read' }),
389
+ migrationsContent: (app, query) => remoteFetch(app, { path: '/app-ops/migrations/content', query, scope: 'app-ops:migrations:read' }),
390
+ migrationsAction: (app, body) => remoteFetch(app, { path: '/app-ops/migrations/action', method: 'POST', body, scope: 'app-ops:migrations:execute' })
391
+ };
392
+
393
+ Object.assign(fastify[options.name].services, {
394
+ link: {
395
+ importByInstallKey,
396
+ syncOne,
397
+ syncAllLinked,
398
+ decodeInstallKey,
399
+ proxy,
400
+ remoteFetch,
401
+ listProxyAudit: proxyAudit.list,
402
+ applyPermissionSnapshot
403
+ }
404
+ });
405
+ });
@@ -1,10 +1,12 @@
1
1
  const fp = require('fastify-plugin');
2
2
  const { isValidSqlFileName, readExecutedMigrations, recordMigration, removeMigrationRecord } = require('../utils/migrate');
3
+ const { isLinked } = require('../utils/appKind');
3
4
 
4
5
  module.exports = fp(async (fastify, options) => {
5
6
  const { models } = fastify[options.name];
6
7
  const getDbops = () => fastify[options.name].services.dbops;
7
8
  const getAppService = () => fastify[options.name].services.app;
9
+ const linkedProxy = () => fastify[options.name].services.link.proxy;
8
10
 
9
11
  const httpError = (statusCode, message) => {
10
12
  if (fastify.httpErrors) {
@@ -46,6 +48,10 @@ module.exports = fp(async (fastify, options) => {
46
48
  };
47
49
 
48
50
  const list = async ({ name, versionId }) => {
51
+ const appRow = await models.app.findOne({ where: { name } });
52
+ if (appRow && isLinked(appRow)) {
53
+ return linkedProxy().migrationsList(appRow);
54
+ }
49
55
  const { app, ver } = await resolveVersion({ name, versionId });
50
56
  const files = await getFiles(ver);
51
57
  let executedMap = new Map();
@@ -74,12 +80,20 @@ module.exports = fp(async (fastify, options) => {
74
80
  };
75
81
 
76
82
  const content = async ({ name, versionId, file }) => {
83
+ const appRow = await models.app.findOne({ where: { name } });
84
+ if (appRow && isLinked(appRow)) {
85
+ return linkedProxy().migrationsContent(appRow, { file });
86
+ }
77
87
  const { ver } = await resolveVersion({ name, versionId });
78
88
  const item = await findFile(ver, file);
79
89
  return { name: file, content: item.content || '' };
80
90
  };
81
91
 
82
92
  const save = async ({ name, versionId, file, content: sql }) => {
93
+ const appRow = await models.app.findOne({ where: { name } });
94
+ if (appRow && isLinked(appRow)) {
95
+ httpError(400, '外部关联应用不支持在平台侧编辑迁移脚本');
96
+ }
83
97
  assertFileName(file);
84
98
  const { ver } = await resolveVersion({ name, versionId });
85
99
  const files = (await getFiles(ver)).filter(f => f.name !== file);
@@ -89,6 +103,10 @@ module.exports = fp(async (fastify, options) => {
89
103
  };
90
104
 
91
105
  const remove = async ({ name, versionId, file }) => {
106
+ const appRow = await models.app.findOne({ where: { name } });
107
+ if (appRow && isLinked(appRow)) {
108
+ httpError(400, '外部关联应用不支持在平台侧删除迁移脚本');
109
+ }
92
110
  const { ver } = await resolveVersion({ name, versionId });
93
111
  await findFile(ver, file);
94
112
  await getAppService().saveMigrationFiles(
@@ -133,6 +151,10 @@ module.exports = fp(async (fastify, options) => {
133
151
  };
134
152
 
135
153
  const action = async ({ action: type, ...props }) => {
154
+ const appRow = props.name ? await models.app.findOne({ where: { name: props.name } }) : null;
155
+ if (appRow && isLinked(appRow)) {
156
+ return linkedProxy().migrationsAction(appRow, { file: props.file, action: type });
157
+ }
136
158
  if (type === 'execute') return execute(props);
137
159
  if (type === 'mark') return mark(props);
138
160
  if (type === 'unmark') return unmark(props);
@@ -15,6 +15,8 @@ module.exports = fp(async (fastify, options) => {
15
15
  throw err;
16
16
  };
17
17
 
18
+ const { isLinked, linkedBaseUrl } = require('../utils/appKind');
19
+
18
20
  const getRunningApp = async (name, hook) => {
19
21
  if (typeof options[hook] !== 'function') {
20
22
  httpError(400, `未配置 ${hook},无法访问子应用接口文档(见 README「应用 OIDC 对接」)`);
@@ -26,11 +28,22 @@ module.exports = fp(async (fastify, options) => {
26
28
  return app;
27
29
  };
28
30
 
31
+ const openApiUrl = app => {
32
+ if (isLinked(app)) {
33
+ const base = linkedBaseUrl(app);
34
+ if (!base) {
35
+ httpError(400, `应用 ${app.name} 缺少 options.baseUrl`);
36
+ }
37
+ return `${base}/open-api.json`;
38
+ }
39
+ return `http://${options.upstreamHost}:${app.port}/open-api.json`;
40
+ };
41
+
29
42
  /** 以 open-api:read 服务令牌读取子应用 /open-api.json,原样返回 */
30
43
  const getDocument = async ({ name }) => {
31
44
  const app = await getRunningApp(name, 'getOpenApiToken');
32
45
  const token = await options.getOpenApiToken(app);
33
- const response = await fetch(`http://${options.upstreamHost}:${app.port}/open-api.json`, {
46
+ const response = await fetch(openApiUrl(app), {
34
47
  headers: { authorization: `Bearer ${token}` },
35
48
  signal: AbortSignal.timeout(15000)
36
49
  });
@@ -0,0 +1,33 @@
1
+ const KIND_MANAGED = 'managed';
2
+ const KIND_LINKED = 'linked';
3
+
4
+ const normalizeKind = kind => (kind === KIND_LINKED ? KIND_LINKED : KIND_MANAGED);
5
+
6
+ const isLinked = appLike => {
7
+ if (appLike?.kind != null && appLike.kind !== '') {
8
+ return normalizeKind(appLike.kind) === KIND_LINKED;
9
+ }
10
+ return normalizeKind(appLike?.options?.kind) === KIND_LINKED;
11
+ };
12
+
13
+ const linkedBaseUrl = appLike => {
14
+ const url = appLike?.options?.baseUrl || appLike?.baseUrl;
15
+ return url ? String(url).replace(/\/+$/, '') : null;
16
+ };
17
+
18
+ const assertNotLinked = (appLike, action) => {
19
+ if (isLinked(appLike)) {
20
+ const err = new Error(`外部关联应用不支持${action || '该操作'}`);
21
+ err.statusCode = 400;
22
+ throw err;
23
+ }
24
+ };
25
+
26
+ module.exports = {
27
+ KIND_MANAGED,
28
+ KIND_LINKED,
29
+ normalizeKind,
30
+ isLinked,
31
+ linkedBaseUrl,
32
+ assertNotLinked
33
+ };
@@ -0,0 +1,140 @@
1
+ /**
2
+ * 将远程权限树规范为以 appName 为顶层 code 的 modules 树;
3
+ * 相对上一份快照:仍存在的码保留,远程已删的码标记 stale(不从树中移除,避免角色授予被清掉)。
4
+ */
5
+
6
+ const flattenCodes = (node, acc = new Set()) => {
7
+ if (!node) {
8
+ return acc;
9
+ }
10
+ if (Array.isArray(node)) {
11
+ node.forEach(item => flattenCodes(item, acc));
12
+ return acc;
13
+ }
14
+ if (node.code) {
15
+ acc.add(String(node.code));
16
+ }
17
+ if (Array.isArray(node.modules)) {
18
+ node.modules.forEach(item => flattenCodes(item, acc));
19
+ }
20
+ if (Array.isArray(node.permissions)) {
21
+ node.permissions.forEach(item => flattenCodes(item, acc));
22
+ }
23
+ return acc;
24
+ };
25
+
26
+ const markStaleDeep = (nodes, liveCodes) =>
27
+ (Array.isArray(nodes) ? nodes : []).map(node => {
28
+ const next = Object.assign({}, node);
29
+ if (next.code && !liveCodes.has(String(next.code))) {
30
+ next.stale = true;
31
+ } else if (next.stale) {
32
+ delete next.stale;
33
+ }
34
+ if (Array.isArray(next.modules)) {
35
+ next.modules = markStaleDeep(next.modules, liveCodes);
36
+ }
37
+ if (Array.isArray(next.permissions)) {
38
+ next.permissions = markStaleDeep(next.permissions, liveCodes);
39
+ }
40
+ return next;
41
+ });
42
+
43
+ const asModulesTree = permissions => {
44
+ if (!permissions) {
45
+ return { modules: [] };
46
+ }
47
+ if (Array.isArray(permissions)) {
48
+ return { modules: permissions };
49
+ }
50
+ if (Array.isArray(permissions.modules)) {
51
+ return { modules: permissions.modules };
52
+ }
53
+ return { modules: [] };
54
+ };
55
+
56
+ /**
57
+ * @param {string} appName
58
+ * @param {object|array} remotePermissions 远程返回
59
+ * @param {object|null} previousTree 上一份已规范树(含顶层 appName)
60
+ */
61
+ const mergeAppPermissionTree = (appName, remotePermissions, previousTree = null) => {
62
+ const name = String(appName);
63
+ const remote = asModulesTree(remotePermissions);
64
+ const liveCodes = flattenCodes(remote);
65
+ // 远程子树挂到 appName 顶层下;若远程已自带同名顶层则直接用
66
+ let children = remote.modules;
67
+ if (children.length === 1 && children[0].code === name) {
68
+ children = children[0].modules || children[0].permissions ? [children[0]] : children;
69
+ if (children[0].code === name) {
70
+ const root = Object.assign({}, children[0], { modules: markStaleDeep(children[0].modules || [], liveCodes) });
71
+ // 合并 previous 中已 stale 但仍存在的叶子
72
+ if (previousTree?.modules?.[0]?.code === name) {
73
+ root.modules = mergeMissingStale(root.modules || [], previousTree.modules[0].modules || [], liveCodes);
74
+ }
75
+ return { modules: [root] };
76
+ }
77
+ }
78
+
79
+ let modules = markStaleDeep(children, liveCodes);
80
+ if (previousTree?.modules?.[0]?.code === name) {
81
+ modules = mergeMissingStale(modules, previousTree.modules[0].modules || [], liveCodes);
82
+ }
83
+
84
+ const label = (previousTree?.modules?.[0] && previousTree.modules[0].name) || (remote.modules?.[0] && remote.modules[0].name) || name;
85
+
86
+ return {
87
+ modules: [
88
+ {
89
+ name: label,
90
+ code: name,
91
+ modules
92
+ }
93
+ ]
94
+ };
95
+ };
96
+
97
+ /** 上一份有、本次 live 没有的节点:以 stale 形式保留 */
98
+ const mergeMissingStale = (current, previous, liveCodes) => {
99
+ const byCode = new Map((current || []).filter(n => n.code).map(n => [String(n.code), n]));
100
+ for (const prev of previous || []) {
101
+ if (!prev?.code) {
102
+ continue;
103
+ }
104
+ const code = String(prev.code);
105
+ if (byCode.has(code)) {
106
+ const cur = byCode.get(code);
107
+ if (Array.isArray(prev.modules) || Array.isArray(cur.modules)) {
108
+ cur.modules = mergeMissingStale(cur.modules || [], prev.modules || [], liveCodes);
109
+ }
110
+ if (Array.isArray(prev.permissions) || Array.isArray(cur.permissions)) {
111
+ cur.permissions = mergeMissingStale(cur.permissions || [], prev.permissions || [], liveCodes);
112
+ }
113
+ continue;
114
+ }
115
+ if (!liveCodes.has(code)) {
116
+ byCode.set(
117
+ code,
118
+ Object.assign({}, prev, {
119
+ stale: true,
120
+ modules: prev.modules ? markStaleDeep(prev.modules, liveCodes) : prev.modules,
121
+ permissions: prev.permissions ? markStaleDeep(prev.permissions, liveCodes) : prev.permissions
122
+ })
123
+ );
124
+ }
125
+ }
126
+ return Array.from(byCode.values());
127
+ };
128
+
129
+ const topLevelCodes = tree =>
130
+ (tree?.modules || [])
131
+ .map(m => m.code)
132
+ .filter(Boolean)
133
+ .map(String);
134
+
135
+ module.exports = {
136
+ flattenCodes,
137
+ asModulesTree,
138
+ mergeAppPermissionTree,
139
+ topLevelCodes
140
+ };