Commit 1ad2227f by liimin

feat(web,mp,platform): 第一方调用点迁移新门面并接入菜单切换取消

platform-core http 改用 createClient({kind:'web-host'}),AbortSignal 透传到 axios;platform-sdk SubAppLifecycle 订阅页面离开/登出/导航事件,调用 cancelRequests 并 queryClient.cancelQueries;web shell BasicLayout 菜单点击广播 PAGE_LEAVE_EVENT 并 cancelRequests。

contracts 新增 PAGE_LEAVE_EVENT 事件、RemoteRequest 增加 signal 字段;4 个 mp lane 与 web points 调用点全部迁移到 createClient/createSigner。
1 parent 3ea667a5
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -18,7 +18,8 @@ import { ...@@ -18,7 +18,8 @@ import {
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createGlsxSha1Signer,两个预设别混用。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const demoGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const demoGateway: GatewayStrategy = {
router: 'rop-scrm-demo/router', router: 'rop-scrm-demo/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'demo-sha1' }), signer: createSigner({ kind: 'rop', id: 'demo-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
/** /**
* points 请求层:@uj/api-core 的客户端工厂。 * points 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL 拼装 / 签名 / * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL 拼装 / 签名 /
* 拦截器(业务码归一 / 登录跳转 / loading / toast)由 api-core 负责。 * 拦截器(业务码归一 / 登录跳转 / loading / toast)由 api-core 负责。
* *
* public API 与旧壳一致:get/post/request(RequestMethods, params, returnAll)、 * public API 与旧壳一致:get/post/request(RequestMethods, params, returnAll)、
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
* · sentry 上报 → events.error + onTransportError * · sentry 上报 → events.error + onTransportError
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { import {
defaultMerchantId, defaultMerchantId,
secretKey, secretKey,
...@@ -29,7 +29,8 @@ const DEFAULT_CRED = { ...@@ -29,7 +29,8 @@ const DEFAULT_CRED = {
secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b', secret: 'c24619ed7fef02a0ae16328146bca5f97cc6493957a2137b',
} }
const client = createRopClient({ const client = createClient({
kind: 'rop',
hosts: { scrm: domain }, hosts: { scrm: domain },
pathEnum, pathEnum,
secretKey, secretKey,
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -18,7 +18,8 @@ import { ...@@ -18,7 +18,8 @@ import {
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createGlsxSha1Signer,两个预设别混用。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const pointsGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const pointsGateway: GatewayStrategy = {
router: 'rop-scrm-points/router', router: 'rop-scrm-points/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'points-sha1' }), signer: createSigner({ kind: 'rop', id: 'points-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -18,7 +18,8 @@ import { ...@@ -18,7 +18,8 @@ import {
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createGlsxSha1Signer,两个预设别混用。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const salesGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const salesGateway: GatewayStrategy = {
router: 'rop-scrm-sales/router', router: 'rop-scrm-sales/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'sales-sha1' }), signer: createSigner({ kind: 'rop', id: 'sales-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
/** /**
* @file ROP 请求签名;序列化依赖 lib/qs(indices / allowDots / encodeValuesOnly)。 * @file ROP 请求签名;序列化依赖 lib/qs(indices / allowDots / encodeValuesOnly)。
* 签名算法与 store/usedcar/points 同源,收敛到 @uj/api-core 的 createSha1Signer; * 签名算法与 store/usedcar/points 同源,收敛到 @uj/api-core 的 createSigner;
* 签完仍返回摊平后的对象,它同时是 wx.request 的请求体(与原实现逐字节一致)。 * 签完仍返回摊平后的对象,它同时是 wx.request 的请求体(与原实现逐字节一致)。
*/ */
import qs from '../lib/qs' import qs from '../lib/qs'
import { createSha1Signer } from '@uj/api-core' import { createSigner } from '@uj/api-core'
import environment from './environment.js' import environment from './environment.js'
const salesSigner = createSha1Signer({ id: 'sales-sha1' }) const salesSigner = createSigner({ kind: 'rop', id: 'sales-sha1' })
const flatten = params => { const flatten = params => {
const objStr = qs.stringify(params, { const objStr = qs.stringify(params, {
......
/** /**
* sales 请求层:@uj/api-core 的客户端工厂。 * sales 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台(wx)、URL 拼装、签名、 * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台(wx)、URL 拼装、签名、
* 拦截器(业务码归一 / 登录重放 / loading / toast)全在 api-core 里,本文件只传环境参数。 * 拦截器(业务码归一 / 登录重放 / loading / toast)全在 api-core 里,本文件只传环境参数。
* public API 与旧壳逐签名一致:get/post/request(params, returnAll, isShowLoading, hostType)、 * public API 与旧壳逐签名一致:get/post/request(params, returnAll, isShowLoading, hostType)、
* reportTrack(params)、getMock(),453 处调用点零改动。 * reportTrack(params)、getMock(),453 处调用点零改动。
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { sign, domain, djDomain, merchantDomain, pathEnum, secretKey, djSecretKey, index } from './http.js' import { sign, domain, djDomain, merchantDomain, pathEnum, secretKey, djSecretKey, index } from './http.js'
import { login } from '~/utils/appFn/index' import { login } from '~/utils/appFn/index'
const client = createRopClient({ const client = createClient({
kind: 'rop',
hosts: { scrm: domain, dj: djDomain, merchant: merchantDomain }, hosts: { scrm: domain, dj: djDomain, merchant: merchantDomain },
pathEnum, pathEnum,
secretKey, secretKey,
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -18,7 +18,8 @@ import { ...@@ -18,7 +18,8 @@ import {
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createGlsxSha1Signer,两个预设别混用。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const storeGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const storeGateway: GatewayStrategy = {
router: 'rop-scrm-store/router', router: 'rop-scrm-store/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'store-sha1' }), signer: createSigner({ kind: 'rop', id: 'store-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
import qs from '../lib/qs' import qs from '../lib/qs'
import { createSha1Signer } from '@uj/api-core' import { createSigner } from '@uj/api-core'
import environment from './environment.js' import environment from './environment.js'
// 签名算法统一收口到 @uj/api-core 的 SHA1 预设;本文件只保留 mp 侧的「参数摊平」规则。 // 签名算法统一收口到 @uj/api-core 的 SHA1 预设;本文件只保留 mp 侧的「参数摊平」规则。
// 迁移时用脚本对老 sign() 逐字节验证过:扁平 / 中文与特殊字符 / noSignAttr / 嵌套对象 / // 迁移时用脚本对老 sign() 逐字节验证过:扁平 / 中文与特殊字符 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined-数字-布尔 / dj 后端形状 共 8 类用例全部一致。 // 数组 / 数组套对象 / null-undefined-数字-布尔 / dj 后端形状 共 8 类用例全部一致。
const storeSigner = createSha1Signer({ id: 'store-sha1' }) const storeSigner = createSigner({ kind: 'rop', id: 'store-sha1' })
/** /**
* 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。 * 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
......
/** /**
* store 请求层:@uj/api-core 的客户端工厂。 * store 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责, * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器都由 api-core 负责,
* 本文件只传域名、凭据、会话与登录回调。 * 本文件只传域名、凭据、会话与登录回调。
* public API 与旧壳一致:get/post/request(params, returnAll, requestPath), * public API 与旧壳一致:get/post/request(params, returnAll, requestPath),
* params 含 method,requestPath 对应 hostType(scrm/dj,缺省 scrm)。 * params 含 method,requestPath 对应 hostType(scrm/dj,缺省 scrm)。
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { sign, domain, djSecretKey, pathEnum, secretKey } from './http.js' import { sign, domain, djSecretKey, pathEnum, secretKey } from './http.js'
import { getSessionId } from '~/utils/cache/storageApi' import { getSessionId } from '~/utils/cache/storageApi'
import network from '~/utils/network' import network from '~/utils/network'
const client = createRopClient({ const client = createClient({
kind: 'rop',
hosts: { scrm: domain.scrm, dj: domain.dj, merchant: domain.merchant }, hosts: { scrm: domain.scrm, dj: domain.dj, merchant: domain.merchant },
pathEnum, pathEnum,
secretKey, secretKey,
......
import { import {
createRpcDispatcher, createRpcDispatcher,
createWxSender, createWxSender,
createSha1Signer, createSigner,
registerGateway, registerGateway,
type GatewayStrategy, type GatewayStrategy,
type GatewayCredential, type GatewayCredential,
...@@ -18,7 +18,8 @@ import { ...@@ -18,7 +18,8 @@ import {
* *
* 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、 * 签名用 api-core 内置 SHA1 预设:原生小程序 RPC 网关走 SHA1(secret 前后包裹、
* appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx * appKey/format/method/v + params 全签、不带 timestamp);web points 子应用同属 glsx
* 家族、同样用 SHA1,但 timestamp 进原文,故走 createGlsxSha1Signer,两个预设别混用。 * 家族、同样用 SHA1,但 timestamp 进原文,故走 createSigner() 不传参(默认 glsx);
* 小程序侧必须显式 createSigner({ kind: 'rop' }),两种签名原文别混用。
* *
* 注意:本文件在微信运行时被 import 时才会执行 createWxSender(); * 注意:本文件在微信运行时被 import 时才会执行 createWxSender();
* 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。 * 类型检查 / lint 不会执行这段代码,因此无需担心 Node 环境下 wx 缺失。
...@@ -29,7 +30,7 @@ export const usedcarGateway: GatewayStrategy = { ...@@ -29,7 +30,7 @@ export const usedcarGateway: GatewayStrategy = {
router: 'rop-scrm-usedcar/router', router: 'rop-scrm-usedcar/router',
tokenHeader: 'token', tokenHeader: 'token',
// 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。 // 原生小程序签名:SHA1 预设;换算法(HMAC / MD5)只改这一行。
signer: createSha1Signer({ id: 'usedcar-sha1' }), signer: createSigner({ kind: 'rop', id: 'usedcar-sha1' }),
// 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。 // 网关级常量参数:并进签名与请求体(会话态 sessionId 等业务参数在调用时再传)。
fixedParams: { locale: 'zh_CN', source: 'dj-wechat' }, fixedParams: { locale: 'zh_CN', source: 'dj-wechat' },
// 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。 // 把对方信封归一成主壳拦截器认得的 { data } / { code, message }。
......
...@@ -13,7 +13,7 @@ const require = createRequire(import.meta.url) ...@@ -13,7 +13,7 @@ const require = createRequire(import.meta.url)
const rootDir = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..') const rootDir = path.resolve(fileURLToPath(new URL('.', import.meta.url)), '..')
const qs = require(path.join(rootDir, 'utils/lib/qs.js')) const qs = require(path.join(rootDir, 'utils/lib/qs.js'))
const sha1 = require(path.join(rootDir, 'utils/lib/sha1.js')) const sha1 = require(path.join(rootDir, 'utils/lib/sha1.js'))
const { createSha1Signer } = require('@uj/api-core') const { createSigner } = require('@uj/api-core')
/** 与 utils/request/http.js flatten 保持一致:qs 摊平成实际发送体(嵌套 a.b / 数组 a[0]) */ /** 与 utils/request/http.js flatten 保持一致:qs 摊平成实际发送体(嵌套 a.b / 数组 a[0]) */
function flatten(params) { function flatten(params) {
...@@ -54,7 +54,7 @@ function legacySign(params, secret, noSignAttr = []) { ...@@ -54,7 +54,7 @@ function legacySign(params, secret, noSignAttr = []) {
return realObj return realObj
} }
const signer = createSha1Signer({ id: 'usedcar-sha1' }) const signer = createSigner({ kind: 'rop', id: 'usedcar-sha1' })
/** 迁移后的加签路径:与 utils/request/http.js sign 同源 */ /** 迁移后的加签路径:与 utils/request/http.js sign 同源 */
async function sign(params, secret, noSignAttr = []) { async function sign(params, secret, noSignAttr = []) {
......
...@@ -65,8 +65,8 @@ async function loadProjectHttpModule(environment) { ...@@ -65,8 +65,8 @@ async function loadProjectHttpModule(environment) {
// http.js 的摘要已收口到 @uj/api-core;data: URL 模块解析不了裸包名,按同一路子注入。 // http.js 的摘要已收口到 @uj/api-core;data: URL 模块解析不了裸包名,按同一路子注入。
source = replaceRequired( source = replaceRequired(
source, source,
/import\s+\{\s*createSha1Signer\s*\}\s*from\s+['"]@uj\/api-core['"];?/, /import\s+\{\s*createSigner\s*\}\s*from\s+['"]@uj\/api-core['"];?/,
`const { createSha1Signer } = globalThis[${JSON.stringify(contextKey)}].apiCore`, `const { createSigner } = globalThis[${JSON.stringify(contextKey)}].apiCore`,
'api-core signer import' 'api-core signer import'
) )
source = replaceRequired( source = replaceRequired(
......
...@@ -5,13 +5,13 @@ ...@@ -5,13 +5,13 @@
*/ */
import environment from './environment.js' import environment from './environment.js'
import qs from '~/utils/lib/qs' import qs from '~/utils/lib/qs'
import { createSha1Signer } from '@uj/api-core' import { createSigner } from '@uj/api-core'
const path = '/rop-dj-car-boutique/router' const path = '/rop-dj-car-boutique/router'
// 与老 sign 的摘要算法字节级一致(迁移时用脚本验过:扁平 / 中文 / noSignAttr / 嵌套对象 / // 与老 sign 的摘要算法字节级一致(迁移时用脚本验过:扁平 / 中文 / noSignAttr / 嵌套对象 /
// 数组 / 数组套对象 / null-undefined / merchants 域名形状 全部通过)。 // 数组 / 数组套对象 / null-undefined / merchants 域名形状 全部通过)。
const usedcarSigner = createSha1Signer({ id: 'usedcar-sha1' }) const usedcarSigner = createSigner({ kind: 'rop', id: 'usedcar-sha1' })
/** /**
* 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。 * 摊平成「实际发送体」:嵌套对象走 a.b、数组走 a[0],值统一 decode 成字符串。
......
/** /**
* usedcar 请求层:@uj/api-core 的客户端工厂。 * usedcar 请求层:@uj/api-core 的客户端工厂。
* *
* 一个 createRopClient({配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器由 api-core 负责。 * 一个 createClient({ kind: 'rop', 配置}) 直接拿到 client;平台 / URL / 签名 / 拦截器由 api-core 负责。
* public API 与旧壳一致:get/post/request(method, data, noSignAttr, requestPath, domainName, failTips)、 * public API 与旧壳一致:get/post/request(method, data, noSignAttr, requestPath, domainName, failTips)、
* getMock()、getApiFoxMock(),46 处调用点零改动。 * getMock()、getApiFoxMock(),46 处调用点零改动。
* *
...@@ -11,7 +11,7 @@ ...@@ -11,7 +11,7 @@
* · 网络失败 / 超时提示改写 → beforeRequest / onTransportError * · 网络失败 / 超时提示改写 → beforeRequest / onTransportError
*/ */
// 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。 // 小程序走主入口具名导出(构建 npm 不保证解析 exports 子路径);web/Node 可用 @uj/api-core/Request。
import { createRopClient } from '@uj/api-core' import { createClient } from '@uj/api-core'
import { sign, domain, path, secretKey } from './http.js' import { sign, domain, path, secretKey } from './http.js'
import util from '~/utils/util.js' import util from '~/utils/util.js'
import { envIndex } from '~/config' import { envIndex } from '~/config'
...@@ -73,10 +73,15 @@ const ropOptions = { ...@@ -73,10 +73,15 @@ const ropOptions = {
} }
// 常规请求:sessionId 可能正在换取(启动 / 登录后),等闸门放行再发。 // 常规请求:sessionId 可能正在换取(启动 / 登录后),等闸门放行再发。
const client = createRopClient({ ...ropOptions, session: { sessionId: () => util.waitSessionId() } }) const client = createClient({
kind: 'rop',
...ropOptions,
session: { sessionId: () => util.waitSessionId() },
})
// 换取会话本身的接口不能等闸门,否则自己把自己锁死。 // 换取会话本身的接口不能等闸门,否则自己把自己锁死。
const sessionFreeClient = createRopClient({ const sessionFreeClient = createClient({
kind: 'rop',
...ropOptions, ...ropOptions,
session: { sessionId: () => util.getSessionId() || '' }, session: { sessionId: () => util.getSessionId() || '' },
}) })
......
import { bus } from 'wujie';
import { PAGE_LEAVE_EVENT } from '@uj/contracts';
import { Layout, Menu, Avatar, Dropdown, Button, Breadcrumb } from 'antd'; import { Layout, Menu, Avatar, Dropdown, Button, Breadcrumb } from 'antd';
import { Suspense, useEffect, useMemo, useState } from 'react'; import { Suspense, useEffect, useMemo, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom'; import { Outlet, useLocation, useNavigate } from 'react-router-dom';
...@@ -16,7 +18,7 @@ import { ...@@ -16,7 +18,7 @@ import {
} from '@ant-design/icons'; } from '@ant-design/icons';
import { useAccess, buildMenus, type MenuGroupDef } from '@/access'; import { useAccess, buildMenus, type MenuGroupDef } from '@/access';
import { useAppStore } from '@/store/useAppStore'; import { useAppStore } from '@/store/useAppStore';
import { menu as menuApi } from '@/api'; import { menu as menuApi, cancelRequests } from '@/api';
import { logoutEverything } from '../subapp-lifecycle'; import { logoutEverything } from '../subapp-lifecycle';
import { Logo } from '@/components/Logo'; import { Logo } from '@/components/Logo';
import { Skeleton } from '@uj/ui'; import { Skeleton } from '@uj/ui';
...@@ -263,7 +265,12 @@ export default function BasicLayout() { ...@@ -263,7 +265,12 @@ export default function BasicLayout() {
onClick={({ key }) => { onClick={({ key }) => {
// 一级标题点击走 onOpenChange、不产生 onClick;这里仍按「分组 key 不导航」兜底, // 一级标题点击走 onOpenChange、不产生 onClick;这里仍按「分组 key 不导航」兜底,
// 防止分组 key 被误当作路由跳进 404。 // 防止分组 key 被误当作路由跳进 404。
if (!key.startsWith(GROUP_KEY_PREFIX)) navigate(key); if (key.startsWith(GROUP_KEY_PREFIX)) return;
// 切菜单先中断上一页的在途请求:alive 保活的子应用不会卸载,旧响应回来会写脏 state。
// 广播给所有保活子应用(各自 cancelRequests),主壳自己的在途请求在这里一并取消。
bus.$emit(PAGE_LEAVE_EVENT);
cancelRequests();
navigate(key);
}} }}
/> />
</div> </div>
......
...@@ -108,7 +108,7 @@ ...@@ -108,7 +108,7 @@
接口方法名、入参字段、返回结构一个字没改;改的是「怎么发出去、怎么读回来」。适配层在 [src/adapter/](file:///D:/work/uj-admin/apps/web/subapps/points/src/adapter/index.ts),回答三件事,每件事只有一种答法: 接口方法名、入参字段、返回结构一个字没改;改的是「怎么发出去、怎么读回来」。适配层在 [src/adapter/](file:///D:/work/uj-admin/apps/web/subapps/points/src/adapter/index.ts),回答三件事,每件事只有一种答法:
1. **一个系统一套策略。** `GatewayId = 'scrm-shopmall' | 'scrm-carlife' | 'dj-smartcarlife'`,各自带 `router` 路径、令牌放哪个头(前两个 `token`,dj 是 `TGT`)、用哪个签名器。第三个系统再接进来时新增一个 `GatewayStrategy`,页面与业务模块不需要知道对方是谁。 1. **一个系统一套策略。** `GatewayId = 'scrm-shopmall' | 'scrm-carlife' | 'dj-smartcarlife'`,各自带 `router` 路径、令牌放哪个头(前两个 `token`,dj 是 `TGT`)、用哪个签名器。第三个系统再接进来时新增一个 `GatewayStrategy`,页面与业务模块不需要知道对方是谁。
2. **签名是可替换的策略,不是散在页面里的代码。** glsx 系用 **SHA1**:`secret + 按 key 升序拼接的 k+v + secret` 取 SHA1,**40 位大写**(不是 MD5,MD5 只有 32 位,曾误用导致验签必挂);timestamp 进签名原文,非字符串参数按 JSON 原文参与拼接。唯一实现是 api-core 的 `createGlsxSha1Signer` 预设(`gateways/glsx.ts` 只声明它),依据是 `glsx-common/src/util.js#createSign` 的默认 `way='sha1'`;真实抓包 golden 值固化在 `packages/api-core/test/glsxSign.test.mjs`。老系统的 `noSignAttr` 换成 `unsignedKeys`。 2. **签名是可替换的策略,不是散在页面里的代码。** glsx 系用 **SHA1**:`secret + 按 key 升序拼接的 k+v + secret` 取 SHA1,**40 位大写**(不是 MD5,MD5 只有 32 位,曾误用导致验签必挂);timestamp 进签名原文,非字符串参数按 JSON 原文参与拼接。唯一实现是 api-core 的 `createSigner()` 不传参默认值(`gateways/glsx.ts` 只声明它),依据是 `glsx-common/src/util.js#createSign` 的默认 `way='sha1'`;真实抓包 golden 值固化在 `packages/api-core/test/glsxSign.test.mjs`。老系统的 `noSignAttr` 换成 `unsignedKeys`。
3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。 3. **返回值归一挂在 `transformResponse` 上。** 老网关 `code:'0'` → 主壳的 `{ data }`,`code:'21'` → `10002` 走统一登出,其他码 → 带人话文案的失败。函数随 props 引用传给主壳,序列化不了它,所以主壳代码一行不用改。
请求仍然全部经 `requestViaHost()` → `window.$wujie.props.request(config)`,铁律「请求层绝不下放」没有被破坏([ARCHITECTURE.md §2](file:///D:/work/uj-admin/ARCHITECTURE.md))。 请求仍然全部经 `requestViaHost()` → `window.$wujie.props.request(config)`,铁律「请求层绝不下放」没有被破坏([ARCHITECTURE.md §2](file:///D:/work/uj-admin/ARCHITECTURE.md))。
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\gateways\glsx.ts * @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\gateways\glsx.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import { createGlsxSha1Signer } from '@uj/api-core'; import { createSigner } from '@uj/api-core';
import type { GatewayId, GatewayStrategy, NormalizedEnvelope, Signer } from '../types'; import type { GatewayId, GatewayStrategy, NormalizedEnvelope, Signer } from '../types';
/** /**
...@@ -30,9 +30,9 @@ const UJ_UNAUTHORIZED_CODE = 10002; ...@@ -30,9 +30,9 @@ const UJ_UNAUTHORIZED_CODE = 10002;
* glsx 的 SHA1 加签:secret 前后包裹、按 key 升序拼接 k+v、sign 40 位大写、timestamp 进原文。 * glsx 的 SHA1 加签:secret 前后包裹、按 key 升序拼接 k+v、sign 40 位大写、timestamp 进原文。
* 依据 glsx-common/src/util.js#createSign 的默认 way='sha1',并经真实抓包 golden 值复算命中: * 依据 glsx-common/src/util.js#createSign 的默认 way='sha1',并经真实抓包 golden 值复算命中:
* sign=689F62277A050D6285B1E38BB2C3DA8D8E518EC9(见 api-core/test/glsxSign.test.mjs)。 * sign=689F62277A050D6285B1E38BB2C3DA8D8E518EC9(见 api-core/test/glsxSign.test.mjs)。
* 这里只用 api-core 的语义化预设 createGlsxSha1Signer,不再手写,也不再用 MD5(32 位,验签必挂)。 * 这里只用 api-core 的语义化预设 createSigner,不再手写,也不再用 MD5(32 位,验签必挂)。
*/ */
export const glsxSha1Signer: Signer = createGlsxSha1Signer(); export const glsxSha1Signer: Signer = createSigner();
/** 主壳 transport 为验签保留原始响应串,所以字符串响应要先解析成对象。 */ /** 主壳 transport 为验签保留原始响应串,所以字符串响应要先解析成对象。 */
function parseRawBody(raw: unknown): unknown { function parseRawBody(raw: unknown): unknown {
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
* @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\rpc.ts * @FilePath: \uj-admin\apps\web\subapps\points\src\adapter\rpc.ts
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import { createRpcGatewayClient } from '@uj/api-core'; import { createClient } from '@uj/api-core';
import { requestViaHost } from '@uj/platform-sdk'; import { requestViaHost } from '@uj/platform-sdk';
import { getLoginSession } from '@/access'; import { getLoginSession } from '@/access';
// 显式 import(而非依赖 barrel 的 re-export 副作用):保证任何调用路径下网关策略都已登记, // 显式 import(而非依赖 barrel 的 re-export 副作用):保证任何调用路径下网关策略都已登记,
...@@ -21,7 +21,7 @@ const LEGACY_TIMEOUT = 180000; ...@@ -21,7 +21,7 @@ const LEGACY_TIMEOUT = 180000;
/** /**
* web 侧与四个原生小程序共用同一个 `@uj/api-core` 门面。 * web 侧与四个原生小程序共用同一个 `@uj/api-core` 门面。
* *
* 一个 createRpcGatewayClient({配置}) 拿到 client;方案(rpcGateway)、fixedParams 合并、 * createClient({配置}) 不传 kind 即最新版方案(rpcGateway);fixedParams 合并、
* 加签、router 落点、令牌头、信封归一全部由 registerGateway 登记的 GatewayStrategy 决定, * 加签、router 落点、令牌头、信封归一全部由 registerGateway 登记的 GatewayStrategy 决定,
* 与小程序 createRpcDispatcher 共用 prepareRpcCall,字节同源。 * 与小程序 createRpcDispatcher 共用 prepareRpcCall,字节同源。
* 平台差异只由 transport 一处表达:web 子应用走主壳注入的 axios(hostSend), * 平台差异只由 transport 一处表达:web 子应用走主壳注入的 axios(hostSend),
...@@ -33,7 +33,7 @@ const LEGACY_TIMEOUT = 180000; ...@@ -33,7 +33,7 @@ const LEGACY_TIMEOUT = 180000;
* · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等), * · errorHandler —— 把门面的 RequestError 还原成主壳原错误(带 code=10002 等),
* 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。 * 保留上层按 code 判断登出的能力。401 登出与网络异常提示由主壳负责,这里不重复 toast。
*/ */
export const request = createRpcGatewayClient({ export const request = createClient({
transport: 'host', transport: 'host',
hostSend: requestViaHost(), hostSend: requestViaHost(),
timeout: LEGACY_TIMEOUT, timeout: LEGACY_TIMEOUT,
......
...@@ -20,3 +20,10 @@ export function busEvents(shortName: string) { ...@@ -20,3 +20,10 @@ export function busEvents(shortName: string) {
} }
export type BusEvents = ReturnType<typeof busEvents>; export type BusEvents = ReturnType<typeof busEvents>;
/**
* 全局「离开当前页面」广播(不带 shortName 前缀):主壳切菜单时发出,
* 所有 alive 保活的子应用都要取消自己上一页的在途请求。
* 子应用内部换页仍走各 name 的 events.navigate,由 SubAppLifecycle 单独处理。
*/
export const PAGE_LEAVE_EVENT = 'uj:page-leave';
...@@ -16,6 +16,8 @@ export interface RemoteRequest { ...@@ -16,6 +16,8 @@ export interface RemoteRequest {
responseType?: 'json' | 'blob' | 'arraybuffer' | 'text'; responseType?: 'json' | 'blob' | 'arraybuffer' | 'text';
transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>; transformResponse?: Array<(raw: unknown, headers: Record<string, string>) => unknown>;
_noVerify?: boolean; _noVerify?: boolean;
/** 中止信号:wujie props 是同源引用传递,可原样跨到主壳 axios(不走 postMessage 序列化)。 */
signal?: AbortSignal;
[key: string]: unknown; [key: string]: unknown;
} }
......
// 统一 HTTP 客户端(web 主壳唯一出口) // 统一 HTTP 客户端(web 主壳唯一出口)
// //
// 这里是 **@uj/api-core 客户端工厂** 的装配点:一个 createWebHostClient({配置}) 拿到 client, // 这里是 **@uj/api-core 客户端工厂** 的装配点:一个 createClient({ kind: 'web-host', 配置}) 拿到 client,
// 只传环境参数 → sender(axios) / baseURL / contextPath / RSA 签名器 / 验签器 / 无损解析器 / 登出回调。 // 只传环境参数 → sender(axios) / baseURL / contextPath / RSA 签名器 / 验签器 / 无损解析器 / 登出回调。
// 方案(webHost)与签名(rsa)由工厂在 api-core 内选好,平台、URL 拼装、业务码归一、 // 方案(webHost)与签名(rsa)由工厂在 api-core 内选好,平台、URL 拼装、业务码归一、
// 错误处理的实现都不在这里,与四个小程序完全同一套门面与策略注册表。 // 错误处理的实现都不在这里,与四个小程序完全同一套门面与策略注册表。
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios'; import axios, { type AxiosInstance, type AxiosRequestConfig } from 'axios';
import { message } from 'antd'; import { message } from 'antd';
import { createWebHostClient, defineSignatureStrategy } from '@uj/api-core'; import { createClient, createStrategy } from '@uj/api-core';
import type { import type {
HeaderSignInput, HeaderSignInput,
HeaderSigner, HeaderSigner,
...@@ -66,6 +66,8 @@ const sender: RequestSender = { ...@@ -66,6 +66,8 @@ const sender: RequestSender = {
timeout: req.timeout, timeout: req.timeout,
responseType: req.responseType as AxiosRequestConfig['responseType'], responseType: req.responseType as AxiosRequestConfig['responseType'],
withCredentials: req.withCredentials === true, withCredentials: req.withCredentials === true,
// 子应用门面创建的 signal 经 props.request 原样传到这里,axios 收到 abort 会真正中断连接。
signal: req.signal,
// transformResponse 由门面统一执行(验签需要原始串),传输层保持恒等。 // transformResponse 由门面统一执行(验签需要原始串),传输层保持恒等。
transformResponse: [(raw: unknown) => raw], transformResponse: [(raw: unknown) => raw],
}); });
...@@ -111,7 +113,7 @@ const signer: HeaderSigner = { ...@@ -111,7 +113,7 @@ const signer: HeaderSigner = {
}; };
// RSA 与小程序 sha1 签名器地位对等:作为一份签名策略直接传给工厂,不需要全局注册名字。 // RSA 与小程序 sha1 签名器地位对等:作为一份签名策略直接传给工厂,不需要全局注册名字。
const rsaSignature = defineSignatureStrategy('rsa', { headerSigner: signer }); const rsaSignature = createStrategy.signature.define('rsa', { headerSigner: signer });
// ---------- 令牌失效(401)的上层处理回调 ---------- // ---------- 令牌失效(401)的上层处理回调 ----------
// http 属于基础设施层,不应反向依赖 store / 路由。 // http 属于基础设施层,不应反向依赖 store / 路由。
...@@ -132,7 +134,8 @@ export function setUnauthorizedHandler(fn: UnauthorizedHandler) { ...@@ -132,7 +134,8 @@ export function setUnauthorizedHandler(fn: UnauthorizedHandler) {
// 工厂装配:全项目唯一一份 web 请求引擎 // 工厂装配:全项目唯一一份 web 请求引擎
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
const client = createWebHostClient({ const client = createClient({
kind: 'web-host',
sender, sender,
baseURL: SIGN_CONFIG.BASE_URL, baseURL: SIGN_CONFIG.BASE_URL,
// 后端统一 context-path:同时进线上 URL 与 canonical 第 2 行,二者因此永远一致。 // 后端统一 context-path:同时进线上 URL 与 canonical 第 2 行,二者因此永远一致。
...@@ -178,8 +181,13 @@ interface HostRequestConfig extends Record<string, unknown> { ...@@ -178,8 +181,13 @@ interface HostRequestConfig extends Record<string, unknown> {
_noVerify?: boolean; _noVerify?: boolean;
timeout?: number; timeout?: number;
withCredentials?: boolean; withCredentials?: boolean;
/** 子应用侧请求的中止信号(由 api-core 门面创建,跨 props.request 引用传递)。 */
signal?: AbortSignal;
} }
/** 主壳侧也暴露统一取消 API:切菜单 / 登出时由 shell 调用。 */
export { cancelRequests, setActiveScope, getActiveScope, activeRequestCount } from '@uj/api-core';
async function request<T = unknown>(config: HostRequestConfig): Promise<T> { async function request<T = unknown>(config: HostRequestConfig): Promise<T> {
const token = getToken(); const token = getToken();
const headers: Record<string, string> = { ...(config.headers ?? {}) }; const headers: Record<string, string> = { ...(config.headers ?? {}) };
......
...@@ -9,6 +9,7 @@ ...@@ -9,6 +9,7 @@
"typecheck": "tsc --noEmit" "typecheck": "tsc --noEmit"
}, },
"dependencies": { "dependencies": {
"@uj/api-core": "workspace:^0.0.0",
"@uj/contracts": "workspace:*", "@uj/contracts": "workspace:*",
"@uj/design-tokens": "workspace:*", "@uj/design-tokens": "workspace:*",
"@uj/ui": "workspace:*", "@uj/ui": "workspace:*",
......
import { useEffect } from 'react'; import { useEffect } from 'react';
import { busEvents } from '@uj/contracts'; import { busEvents, PAGE_LEAVE_EVENT } from '@uj/contracts';
import { cancelRequests, setActiveScope } from '@uj/api-core';
import { queryClient } from './compat/queryClient'; import { queryClient } from './compat/queryClient';
import { shortName, subappBus } from './subapp'; import { shortName, subappBus } from './subapp';
/** /**
* 订阅主壳广播,维护子应用内的会话派生状态。 * 订阅主壳广播,维护子应用内的会话派生状态与请求生命周期。
* *
* 三条必须做的清理: * 必须做的清理:
* - logout / session 变更时清空 QueryClient 缓存,否则换账号后会短暂看到上一个账号的数据; * - logout / session 变更时清空 QueryClient 缓存,否则换账号后会短暂看到上一个账号的数据;
* - 切菜单 / 换页时 abort 掉上一页所有在途请求(alive 保活的子应用不会卸载,
* 旧请求回来仍会 resolve 并写脏 state),并让 react-query 取消对应查询;
* - 不自己清 uj_token / session(那是 host 的真源),子应用只跟随; * - 不自己清 uj_token / session(那是 host 的真源),子应用只跟随;
* - 不在这里发 `$emit(ready)`:握手由各子应用的 App 在订阅建立后发,顺序不能乱。 * - 不在这里发 `$emit(ready)`:握手由各子应用的 App 在订阅建立后发,顺序不能乱。
*
* scope 由 navigate 携带的子路径维护,请求未显式带 scope 时会自动归到当前页;
* 但批量取消一律用 cancelRequests() 无参形式,避免首屏 / 未打标请求漏网。
*/ */
export function SubAppLifecycle() { export function SubAppLifecycle() {
useEffect(() => { useEffect(() => {
...@@ -18,22 +24,46 @@ export function SubAppLifecycle() { ...@@ -18,22 +24,46 @@ export function SubAppLifecycle() {
if (!bus || !name) return; if (!bus || !name) return;
const events = busEvents(name); const events = busEvents(name);
let currentScope: string | undefined;
const onSessionChange = () => { const onSessionChange = () => {
queryClient.clear(); queryClient.clear();
window.dispatchEvent(new CustomEvent('uj:session-changed')); window.dispatchEvent(new CustomEvent('uj:session-changed'));
}; };
const onLogout = () => { const onLogout = () => {
cancelRequests();
queryClient.clear(); queryClient.clear();
}; };
/** 主壳切菜单:所有保活子应用一起取消上一页在途请求。 */
const onPageLeave = () => {
cancelRequests();
void queryClient.cancelQueries();
};
/** 子应用内部换页:主壳 MicroApp 会在 subPath 变化时发这个事件。 */
const onNavigate = (...args: unknown[]) => {
const next = String(args[0] ?? '');
// 首屏握手时主壳会补发一次 navigate,此时没有「上一页」,不要误取消首屏请求。
if (currentScope !== undefined && currentScope !== next) {
cancelRequests();
void queryClient.cancelQueries();
}
currentScope = next;
setActiveScope(next || undefined);
};
bus.$on(events.session, onSessionChange); bus.$on(events.session, onSessionChange);
bus.$on(events.logout, onLogout); bus.$on(events.logout, onLogout);
bus.$on(events.navigate, onNavigate);
bus.$on(PAGE_LEAVE_EVENT, onPageLeave);
// 这里不能同时监听 uj:session-changed:onSessionChange 自己会 dispatch 它, // 这里不能同时监听 uj:session-changed:onSessionChange 自己会 dispatch 它,
// 两个订阅会形成无限回环。自定义事件只给 AccessProvider 刷新权限用。 // 两个订阅会形成无限回环。自定义事件只给 AccessProvider 刷新权限用。
return () => { return () => {
bus.$off(events.session, onSessionChange); bus.$off(events.session, onSessionChange);
bus.$off(events.logout, onLogout); bus.$off(events.logout, onLogout);
bus.$off(events.navigate, onNavigate);
bus.$off(PAGE_LEAVE_EVENT, onPageLeave);
setActiveScope(undefined);
}; };
}, []); }, []);
......
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
"extends": "../typescript-config/react-lib.json", "extends": "../typescript-config/react-lib.json",
"compilerOptions": { "compilerOptions": {
"paths": { "paths": {
"@uj/api-core": ["../api-core/src/index.ts"],
"@uj/contracts": ["../contracts/src/index.ts"], "@uj/contracts": ["../contracts/src/index.ts"],
"@uj/design-tokens": ["../design-tokens/src/index.ts"], "@uj/design-tokens": ["../design-tokens/src/index.ts"],
"@uj/ui": ["../ui/src/index.ts"] "@uj/ui": ["../ui/src/index.ts"]
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!