Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
ujia
/
uj-admin
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit 6b00df2c
authored
Nov 18, 2026
by
chenwq
Browse Files
Options
Browse Files
Tag
Download
Plain Diff
Merge branch 'v1.0.0' of
http://192.168.3.233:8090/ujia/uj-admin
into v1.0.0
2 parents
4f2a3c71
b6e8df68
Pipeline
#519
for
6b00df2c
failed
in 0 seconds
Changes
20
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
Showing
20 changed files
with
1069 additions
and
31 deletions
apps/web/subapps/store/src/features/store/formatters.ts
apps/web/subapps/usedcar/src/pages/Assessment/assessment.css
apps/web/subapps/usedcar/src/pages/Delivery/index.tsx
apps/web/subapps/usedcar/src/pages/Handover/CreateHandoverModal.tsx
apps/web/subapps/usedcar/src/pages/Handover/HandoverDetailModal.tsx
apps/web/subapps/usedcar/src/pages/Leads/leads.css
apps/web/subapps/usedcar/src/pages/Ledger/VehicleLedger.tsx
apps/web/subapps/usedcar/src/pages/Operation/components/ImportContractModal.tsx
apps/web/subapps/usedcar/src/pages/Operation/contractDetail.css
apps/web/subapps/usedcar/src/pages/Vehicles/VehicleDetail.tsx
docs/PORT_CONVERSION.md
package.json
packages/contracts/src/download-center.ts
packages/design-tokens/src/palette.ts
packages/design-tokens/src/tokens.css
packages/download-center/src/deliver.ts
packages/download-center/src/handlers/simple.ts
packages/download-center/src/types.ts
scripts/audit-module.mjs
scripts/check-boundaries.mjs
apps/web/subapps/store/src/features/store/formatters.ts
View file @
6b00df2
...
...
@@ -48,6 +48,10 @@ export function formatPolicyValue(value: unknown, unit?: string): string {
return
unit
===
'RATIO'
?
`
${
decimal
}
%`
:
decimal
;
}
/**
* §15.3② 刻意分叉:老接口返回的已是本地时间串,这里只做 `T→空格` 归一,绝不 new Date 换时区。
* biz 的 formatDateTime 是给确定 UTC ISO 的新接口用的,两者不可互相替换(见 PORT_CONVERSION.md)。
*/
export
function
formatDateTime
(
value
?:
string
|
null
):
string
{
return
value
?.
trim
().
replace
(
'T'
,
' '
)
||
EMPTY
;
}
...
...
apps/web/subapps/usedcar/src/pages/Assessment/assessment.css
View file @
6b00df2
...
...
@@ -5,7 +5,7 @@
object-fit
:
cover
;
object-position
:
center
;
border-radius
:
4px
;
background
:
#f5f5f5
;
background
:
var
(
--uj-surface-3
)
;
}
.uc-assess-detail
{
display
:
grid
;
...
...
@@ -20,7 +20,7 @@
gap
:
12px
;
}
.uc-assess-history__item
{
border-left
:
2px
solid
#1677ff
;
border-left
:
2px
solid
var
(
--uj-primary
)
;
padding-left
:
14px
;
}
.uc-assess-history__head
{
...
...
@@ -34,7 +34,7 @@
gap
:
8px
;
}
.uc-assess-files
a
{
color
:
#1677ff
;
color
:
var
(
--uj-primary
)
;
}
.uc-assess-readonly-form__grid
{
display
:
grid
;
...
...
apps/web/subapps/usedcar/src/pages/Delivery/index.tsx
View file @
6b00df2
...
...
@@ -8,6 +8,7 @@ import {
PageShell,
SearchForm,
type ActionSchema,
type DataTableColumn,
type FieldSchema,
type RowActionSchema,
} from '@/components';
...
...
@@ -178,7 +179,13 @@ export default function Delivery() {
['成交时间', 'transactionTime', 160],
['预约提车时间', 'scheduledTime', 160],
['实际交付时间', 'actualTime', 160],
].map(([title, dataIndex, width]) => ({ title, dataIndex, width, line: 1, render: txt }));
].map(([title, dataIndex, width]): DataTableColumn<Row> => ({
title,
dataIndex,
width,
line: 1,
render: txt,
}));
columns.push(
{
title: '交付状态',
...
...
apps/web/subapps/usedcar/src/pages/Handover/CreateHandoverModal.tsx
View file @
6b00df2
import { useEffect, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { UButton, UCheckbox, UImage, UModal, UResult, USelect, UUpload, useUMessage } from '@uj/ui';
import { DataTable } from '@/components';
import { DataTable
, type DataTableColumn
} from '@/components';
import { staffHandoverApi } from '@/api';
import { errorDetail } from '@/utils/error';
import { uploadFileUrl } from '@/lib/ossUpload';
...
...
@@ -198,7 +198,7 @@ export default function CreateHandoverModal({
['车型', 'carModel'],
['车牌', 'licensePlate'],
]
.map(([title, dataIndex]) => ({
.map(([title, dataIndex])
: DataTableColumn<Asset>
=> ({
title,
dataIndex,
width: 180,
...
...
apps/web/subapps/usedcar/src/pages/Handover/HandoverDetailModal.tsx
View file @
6b00df2
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { UAlert, UButton, UImage, UModal } from '@uj/ui';
import { CombiForm, DataTable, type FieldSchema } from '@/components';
import { CombiForm, DataTable, type
DataTableColumn, type
FieldSchema } from '@/components';
import { staffHandoverApi } from '@/api';
import { errorDetail } from '@/utils/error';
import './handover.css';
...
...
@@ -31,7 +31,13 @@ export default function HandoverDetailModal({
['门店', 'sellerMerchantName'],
['车型', 'carModel'],
['车牌', 'licensePlate'],
].map(([title, dataIndex]) => ({ title, dataIndex, width: 160, line: 1, render: text }));
].map(([title, dataIndex]): DataTableColumn<Record<string, unknown>> => ({
title,
dataIndex,
width: 160,
line: 1,
render: text,
}));
columns.push(
{
title: '当时协议状态',
...
...
apps/web/subapps/usedcar/src/pages/Leads/leads.css
View file @
6b00df2
.uc-lead-reminder
{
margin
:
0
0
12px
;
color
:
#d48806
;
}
.uc-lead-reminder
strong
{
color
:
#cf1322
;
font-weight
:
500
;
}
.uc-lead-reminder
{
margin
:
0
0
12px
;
color
:
var
(
--uj-warning
)
;
}
.uc-lead-reminder
strong
{
color
:
var
(
--uj-error
)
;
font-weight
:
500
;
}
.uc-lead-level
{
display
:
inline-flex
;
align-items
:
center
;
gap
:
7px
;
}
.uc-lead-level
b
{
display
:
inline-grid
;
place-items
:
center
;
width
:
22px
;
height
:
22px
;
border-radius
:
50%
;
color
:
#fff
;
background
:
#8c8c8c
;
}
.uc-lead-level--o
b
{
background
:
#c04dff
;
}
.uc-lead-level--h
b
{
background
:
#f7a900
;
}
.uc-lead-level--a
b
{
background
:
#55b896
;
}
.uc-lead-level--b
b
{
background
:
#5fbdff
;
}
.uc-lead-level--c
b
{
background
:
#54dfff
;
}
.uc-lead-detail
{
display
:
grid
;
gap
:
16px
;
}
.uc-lead-detail__top
{
display
:
grid
;
grid-template-columns
:
minmax
(
0
,
1
fr
)
300px
;
gap
:
16px
;
}
.uc-lead-detail__title
{
margin
:
0
0
14px
;
font-size
:
15px
;
}
.uc-lead-detail__empty
{
padding
:
28px
;
text-align
:
center
;
color
:
var
(
--uj-text-3
);
}
.uc-lead-follow
{
display
:
grid
;
gap
:
12px
;
}
.uc-lead-follow__item
{
border-left
:
2px
solid
#1677ff
;
padding-left
:
14px
;
}
.uc-lead-follow__head
{
display
:
flex
;
justify-content
:
space-between
;
margin-bottom
:
8px
;
}
.uc-lead-follow__body
{
background
:
#f5f7fa
;
padding
:
12px
;
border-radius
:
6px
;
display
:
grid
;
gap
:
6px
;
}
.uc-lead-follow__body
span
{
color
:
var
(
--uj-text-2
);
}
.uc-lead-follow__body
b
{
color
:
var
(
--uj-text-1
);
font-weight
:
400
;
}
.uc-lead-level
b
{
display
:
inline-grid
;
place-items
:
center
;
width
:
22px
;
height
:
22px
;
border-radius
:
50%
;
color
:
var
(
--uj-on-primary
);
background
:
var
(
--uj-lead-none
)
;
}
.uc-lead-level--o
b
{
background
:
var
(
--uj-lead-o
);
}
.uc-lead-level--h
b
{
background
:
var
(
--uj-lead-h
);
}
.uc-lead-level--a
b
{
background
:
var
(
--uj-lead-a
);
}
.uc-lead-level--b
b
{
background
:
var
(
--uj-lead-b
);
}
.uc-lead-level--c
b
{
background
:
var
(
--uj-lead-c
)
;
}
.uc-lead-detail
{
display
:
grid
;
gap
:
16px
;
}
.uc-lead-detail__top
{
display
:
grid
;
grid-template-columns
:
minmax
(
0
,
1
fr
)
300px
;
gap
:
16px
;
}
.uc-lead-detail__title
{
margin
:
0
0
14px
;
font-size
:
15px
;
}
.uc-lead-detail__empty
{
padding
:
28px
;
text-align
:
center
;
color
:
var
(
--uj-text-3
);
}
.uc-lead-follow
{
display
:
grid
;
gap
:
12px
;
}
.uc-lead-follow__item
{
border-left
:
2px
solid
var
(
--uj-primary
);
padding-left
:
14px
;
}
.uc-lead-follow__head
{
display
:
flex
;
justify-content
:
space-between
;
margin-bottom
:
8px
;
}
.uc-lead-follow__body
{
background
:
var
(
--uj-surface-3
)
;
padding
:
12px
;
border-radius
:
6px
;
display
:
grid
;
gap
:
6px
;
}
.uc-lead-follow__body
span
{
color
:
var
(
--uj-text-2
);
}
.uc-lead-follow__body
b
{
color
:
var
(
--uj-text-1
);
font-weight
:
400
;
}
@media
(
max-width
:
900px
)
{
.uc-lead-detail__top
{
grid-template-columns
:
1
fr
;
}
}
apps/web/subapps/usedcar/src/pages/Ledger/VehicleLedger.tsx
View file @
6b00df2
import { useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import type { Dayjs } from 'dayjs';
import { UAlert, U
Button, U
Card, UTag } from '@uj/ui';
import { UAlert, UCard, UTag } from '@uj/ui';
import { downloadCenter } from '@uj/platform-sdk';
import { DataTable, SearchForm, type FieldSchema } from '@/components';
import { DataTable, SearchForm, type
DataTableColumn, type
FieldSchema } from '@/components';
import { vehicleLedgerApi } from '@/api';
import { useAccess } from '@/access';
import { UC } from '@/permissions/codes';
...
...
@@ -133,7 +133,7 @@ export default function VehicleLedger() {
['车辆类型', 'vehicleType'],
['是否对账', 'isReconciled'],
];
const columns = plain.map(([title, dataIndex]) => ({
const columns = plain.map(([title, dataIndex])
: DataTableColumn<Row>
=> ({
title,
dataIndex,
width: 150,
...
...
apps/web/subapps/usedcar/src/pages/Operation/components/ImportContractModal.tsx
View file @
6b00df2
...
...
@@ -128,13 +128,22 @@ export default function ImportContractModal({
description={
<div>
<div>
成功记录 <span style={{ color: '
#2cca74
' }}>{result.succ ?? 0}</span>
{' '}失败记录 <span style={{ color: '
#eb4e4e
' }}>{result.fail ?? 0}</span>
成功记录 <span style={{ color: '
var(--uj-success)
' }}>{result.succ ?? 0}</span>
{' '}失败记录 <span style={{ color: '
var(--uj-error)
' }}>{result.fail ?? 0}</span>
</div>
{result.failDownloadUrl ? (
<UButton
type="link"
onClick={() => window.open(result.failDownloadUrl, '_blank')}
onClick={() =>
downloadCenter.url({
source: 'usedcar',
sourceLabel: '运营管理 / 合同管理 / 导入结果',
label: '合同导入失败记录',
url: result.failDownloadUrl!,
fileName: '合同导入失败记录.xlsx',
dedupeKey: `usedcar-contract-import-fail-${result.failDownloadUrl}`,
})
}
style={{ paddingLeft: 0 }}
>
导出失败记录
...
...
apps/web/subapps/usedcar/src/pages/Operation/contractDetail.css
View file @
6b00df2
...
...
@@ -10,7 +10,7 @@
.uc-contract-detail__thumb
{
width
:
72px
;
height
:
72px
;
object-fit
:
cover
;
border-radius
:
6px
;
cursor
:
zoom-in
;
border
:
1px
solid
var
(
--uj-border
,
#e5e7eb
);
}
.uc-contract-detail__signer
+
.uc-contract-detail__signer
{
margin-top
:
8px
;
}
.uc-contract-detail__logs
{
display
:
grid
;
gap
:
10px
;
}
.uc-contract-detail__log
{
display
:
flex
;
gap
:
20px
;
align-items
:
center
;
border-left
:
2px
solid
#1677ff
;
padding-left
:
14px
;
color
:
var
(
--uj-text-2
);
}
.uc-contract-detail__log
{
display
:
flex
;
gap
:
20px
;
align-items
:
center
;
border-left
:
2px
solid
var
(
--uj-primary
)
;
padding-left
:
14px
;
color
:
var
(
--uj-text-2
);
}
.uc-contract-detail__log
b
{
color
:
var
(
--uj-text-1
);
font-weight
:
500
;
}
@media
(
max-width
:
900px
)
{
.uc-contract-detail__field
{
grid-template-columns
:
1
fr
;
}
...
...
apps/web/subapps/usedcar/src/pages/Vehicles/VehicleDetail.tsx
View file @
6b00df2
...
...
@@ -2,6 +2,7 @@ import { useEffect, useMemo, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import dayjs, { type Dayjs } from 'dayjs';
import { UAlert, UButton, UCard, UDatePicker, UForm, UModal, UResult, useUMessage } from '@uj/ui';
import { downloadCenter } from '@uj/platform-sdk';
import { CombiForm, PageShell, type FieldSchema } from '@/components';
import { useAccess } from '@/access';
import { carManagementApi } from '@/api';
...
...
@@ -74,7 +75,17 @@ function FilePreview({ value }: { value: unknown }) {
<UButton
type="link"
size="small"
onClick={() => window.open(url, '_blank', 'noopener,noreferrer')}
onClick={() =>
downloadCenter.url({
source: 'usedcar',
sourceLabel: '二手车管理 / 车辆管理 / 附件预览',
label: name,
url,
preview: true,
silent: true,
dedupeKey: `usedcar-vehicle-preview-${url}`,
})
}
>
预览
</UButton>
...
...
docs/PORT_CONVERSION.md
View file @
6b00df2
...
...
@@ -407,6 +407,8 @@ downloadCenter.register({ ... }); // 显式 kind / 自定义 kind 的统一登
公共字段(
`CommonDownloadInput`
):
`source`
、
`label`
、
`fileName`
、
`autoDownload`
(默认 true;false 只进面板供点击)、
`silent`
(默认 false)、
`dedupeKey`
(防连点去重)、
`channel`
(多网关,见 14.6)。
`async-export`
另可覆盖:
`submitMethod`
/
`queryMethod`
/
`pollInterval`
(默认 3000ms)/
`timeoutMs`
(默认 10 分钟)。
`url`
另可传
`preview: true`
:
**可见新标签预览,不落盘**
——给「看一眼附件」这类动作使用(对应 14.7 的纯外链预览场景)。
落地由主壳
`deliver.openPreview()`
统一执行,子应用只登记任务、不自己
`window.open`
。
**`url` kind 会在执行前归一明文地址**
:HTTPS 主壳 +
`http://`
直链时,
`packages/download-center/src/deliver.ts`
的
`upgradeInsecureUrl()`
把协议换成 https
**并丢掉原 HTTP 业务端口**
(回单
`http://qcimg01.glsx.com.cn:7060/...`
→
`https://qcimg01.glsx.com.cn/...`
,443 上返回同一份文件)。业务页只管把后端给的地址原样交给
`downloadCenter.url()`
,
**不要自己改协议**
。
...
...
package.json
View file @
6b00df2
...
...
@@ -28,6 +28,7 @@
"boundaries"
:
"node scripts/check-boundaries.mjs"
,
"tokens"
:
"node scripts/check-tokens.mjs"
,
"reconcile"
:
"node scripts/reconcile.mjs"
,
"audit:module"
:
"node scripts/audit-module.mjs"
,
"release"
:
"node scripts/release/release.mjs"
,
"release:affected"
:
"node scripts/release/release-affected.mjs"
,
"release:gen"
:
"node scripts/release/release-gen.mjs"
,
...
...
packages/contracts/src/download-center.ts
View file @
6b00df2
...
...
@@ -76,6 +76,11 @@ export interface UrlPayload {
url
:
string
;
/** 默认 true:新标签页打开,避免把主壳路由导航走。 */
openInNewTab
?:
boolean
;
/**
* 预览模式(默认 false):只开可见新标签,不落盘。
* 给「看一眼附件」这类动作用;下载仍由主壳统一执行,子应用不自己 window.open。
*/
preview
?:
boolean
;
}
/** 前端本地 Blob。Blob 不可序列化,仅主壳页面直调;不进持久化。 */
...
...
packages/design-tokens/src/palette.ts
View file @
6b00df2
...
...
@@ -63,6 +63,18 @@ export const palette = {
info
:
'#D6E2FB'
,
neutral
:
'#E4E8EF'
,
},
/**
* 线索等级标识色:老系统 O/H/A/B/C 五档的业务分类色,不是语义色。
* 五档必须彼此可区分,不能拿 success/warning 之类替代,故单列一族。
*/
leadLevel
:
{
none
:
'#8C8C8C'
,
o
:
'#C04DFF'
,
h
:
'#F7A900'
,
a
:
'#55B896'
,
b
:
'#5FBDFF'
,
c
:
'#54DFFF'
,
},
}
as
const
;
export
const
radius
=
{
...
...
packages/design-tokens/src/tokens.css
View file @
6b00df2
...
...
@@ -62,6 +62,14 @@
--uj-neutral-soft
:
#f2f4f8
;
--uj-neutral-border
:
#e4e8ef
;
/* ---- 线索等级标识色:老系统 O/H/A/B/C 五档,业务分类色,不随语义色切换 ---- */
--uj-lead-none
:
#8c8c8c
;
--uj-lead-o
:
#c04dff
;
--uj-lead-h
:
#f7a900
;
--uj-lead-a
:
#55b896
;
--uj-lead-b
:
#5fbdff
;
--uj-lead-c
:
#54dfff
;
/* ---- 高度:两级静置 + 一级抬起(hover)+ 浮层。短投射、低扩散,干脆不飘 ---- */
--uj-shadow-card
:
0
1px
2px
rgba
(
16
,
24
,
40
,
0.05
),
0
2px
6px
-2px
rgba
(
16
,
24
,
40
,
0.08
);
--uj-shadow-raise
:
0
2px
4px
rgba
(
16
,
24
,
40
,
0.06
),
0
8px
20px
-12px
rgba
(
16
,
24
,
40
,
0.18
);
...
...
packages/download-center/src/deliver.ts
View file @
6b00df2
...
...
@@ -259,6 +259,27 @@ export function openUrl(url: string, openInNewTab = true): void {
link
.
remove
();
}
/**
* 可见新标签预览。与 openUrl 的隐藏 iframe 不同,这里必须真开一个用户看得见的标签页;
* 只在主壳内调用,子应用只经 downloadCenter.url({ preview: true }) 登记。
*/
export
function
openPreview
(
url
:
string
):
void
{
const
target
=
upgradeInsecureUrl
(
url
);
assertDownloadableUrl
(
target
);
const
win
=
window
.
open
(
target
,
'_blank'
,
'noopener,noreferrer'
);
if
(
!
win
)
{
// 被弹窗拦截器挡下:再试一次用户手势内的 <a target=_blank>,绝不退回当前标签跳转,
// 否则一次预览会把整个主壳导航走。
const
link
=
document
.
createElement
(
'a'
);
link
.
href
=
target
;
link
.
target
=
'_blank'
;
link
.
rel
=
'noopener,noreferrer'
;
document
.
body
.
appendChild
(
link
);
link
.
click
();
link
.
remove
();
}
}
export
function
blobFromArrayBuffer
(
buffer
:
ArrayBuffer
,
mime
:
string
):
Blob
{
return
new
Blob
([
buffer
],
{
type
:
mime
||
'application/octet-stream'
});
}
...
...
@@ -302,6 +323,7 @@ export function invalidDownload(payload: unknown): Error {
export
const
deliverTools
:
DeliverTools
=
{
saveBlob
,
openUrl
,
openPreview
,
parseFileName
,
sanitizeFileName
,
};
packages/download-center/src/handlers/simple.ts
View file @
6b00df2
...
...
@@ -5,7 +5,12 @@ import type {
DownloadResult
,
UrlPayload
,
}
from
'../types'
;
import
{
assertDownloadableUrl
,
blobFromBase64
,
probeDownloadUrl
,
upgradeInsecureUrl
}
from
'../deliver'
;
import
{
assertDownloadableUrl
,
blobFromBase64
,
probeDownloadUrl
,
upgradeInsecureUrl
,
}
from
'../deliver'
;
/** 从 URL 路径末段推断文件名(预签名 URL 的 query 不参与)。 */
function
fileNameFromUrl
(
url
:
string
):
string
{
...
...
@@ -44,6 +49,10 @@ export const urlHandler: DownloadHandler = {
if
(
probe
.
kind
===
'error'
)
throw
new
Error
(
probe
.
message
);
if
(
probe
.
kind
===
'ok'
)
{
if
(
payload
.
preview
)
{
ctx
.
deliver
.
openPreview
(
url
);
return
{
fileUrl
:
url
,
fileName
:
probe
.
fileName
,
bytes
:
probe
.
bytes
,
note
:
'已打开预览'
};
}
// 探测成功即直接用响应体落盘,不再重复发一次 iframe 请求。
if
(
task
.
input
.
autoDownload
!==
false
)
{
ctx
.
deliver
.
saveBlob
(
probe
.
blob
,
probe
.
fileName
);
...
...
@@ -59,10 +68,16 @@ export const urlHandler: DownloadHandler = {
// opaque:跨域无 CORS 的 OSS 预签名地址,无法探测,退回原 iframe 行为。
// 这类地址的加载失败浏览器不让 JS 感知,是既定限制,不能因此误判为失败。
assertDownloadableUrl
(
url
);
if
(
task
.
input
.
autoDownload
!==
false
)
{
if
(
payload
.
preview
)
{
ctx
.
deliver
.
openPreview
(
url
);
}
else
if
(
task
.
input
.
autoDownload
!==
false
)
{
ctx
.
deliver
.
openUrl
(
url
,
payload
.
openInNewTab
??
true
);
}
return
{
fileUrl
:
url
,
fileName
,
note
:
'已打开下载地址'
};
return
{
fileUrl
:
url
,
fileName
,
note
:
payload
.
preview
?
'已打开预览'
:
'已打开下载地址'
,
};
},
};
...
...
@@ -91,8 +106,4 @@ export const base64Handler: DownloadHandler = {
},
};
export
const
builtinHandlers
:
DownloadHandler
[]
=
[
urlHandler
,
blobHandler
,
base64Handler
,
];
export
const
builtinHandlers
:
DownloadHandler
[]
=
[
urlHandler
,
blobHandler
,
base64Handler
];
packages/download-center/src/types.ts
View file @
6b00df2
...
...
@@ -26,6 +26,8 @@ export interface DeliverTools {
saveBlob
(
blob
:
Blob
,
fileName
:
string
):
void
;
/** 打开自带鉴权的 URL(新标签页,避免主壳被导航走)。 */
openUrl
(
url
:
string
,
openInNewTab
?:
boolean
):
void
;
/** 可见新标签预览:与 openUrl 的隐藏 iframe 落盘不同,只给用户看,不触发下载。 */
openPreview
(
url
:
string
):
void
;
/** 从 content-disposition 解析并清洗文件名。 */
parseFileName
(
disposition
:
string
,
fallback
:
string
):
string
;
/** 清洗文件名中的非法字符与 C0 控制字符。 */
...
...
scripts/audit-module.mjs
0 → 100644
View file @
6b00df2
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* 模块 / 菜单规范巡检器。
*
* 真源:docs/PORT_CONVERSION.md(§1 铁律、§3 UI、§4 请求、§5 主题、§6 筛选、
* §7 列表、§8 权限、§9 骨架、§13 菜单对齐、§14 下载、§15 共享层)、ARCHITECTURE.md。
* 与本脚本并列的 check-boundaries / check-tokens / reconcile 是「全仓 CI 门禁」;
* 本脚本解决的是「只看某个模块 / 某条菜单」且「能自动改的当场改」。
*
* 设计原则:
* 1. 只报有真源可查的约束,不发明规范;
* 2. 每条 finding 带 spec 条款号与文件行号,可逐条反驳;
* 3. 自动修复只做确定性改写(import 名、令牌值、权限码补齐、入口类名),
* 涉及语义判断的(下载方式、网关、页面结构)只报不改;
* 4. 修复前把原文件备份到 .tmp/audit-backup/<时间戳>/,改完可用 git diff 复核。
*
* 用法:
* node scripts/audit-module.mjs <target> [options]
* target: 子应用名(usedcar) | 菜单路由(/usedcar/assessment) | menu_code(1002603)
* | 子应用/页面(usedcar/Assessment) | 目录路径 | --all
* options: --fix 应用可自动修复项(默认只检查)
* --dry-run 只打印将做的改写,不落盘
* --json 机器可读输出
*/
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8');
const exists = (rel) => fs.existsSync(path.join(ROOT, rel));
const rel = (abs) => path.relative(ROOT, abs).split(path.sep).join('/');
const argv = process.argv.slice(2);
const FLAGS = {
fix: argv.includes('--fix'),
dryRun: argv.includes('--dry-run'),
json: argv.includes('--json'),
all: argv.includes('--all'),
};
const target = argv.find((a) => !a.startsWith('--'));
/* ------------------------------------------------------------------ */
/* 磁盘事实:UI 导出 / 令牌 / 图标 / 菜单 SQL */
/* ------------------------------------------------------------------ */
function exportedNames(file) {
if (!exists(file)) return new Set();
const text = read(file);
const names = new Set();
for (const m of text.matchAll(
/export\s+(?:type\s+)?\{([\s\S]*?)\}\s*(?:from\s*['"][^'"]+['"])?\s*;/g,
)) {
for (const part of m[1].split(',')) {
const clean = part.trim().replace(/^type\s+/, '');
const name = clean
.split(/\s+as\s+/)
.pop()
?.trim();
if (name && /^[A-Za-z_$][\w$]*$/.test(name)) names.add(name);
}
}
for (const m of text.matchAll(/export\s+(?:const|function|class)\s+(\w+)/g)) names.add(m[1]);
return names;
}
const UI_EXPORTS = exportedNames('packages/ui/src/index.ts');
const BIZ_EXPORTS = exportedNames('packages/biz/src/components/index.ts');
// antd 值组件 → @uj/ui 导出名。只收确实已在 packages/ui/src/index.ts 存在的名字。
const ANTD_TO_U = {
Button: 'UButton',
Input: 'UInput',
Select: 'USelect',
Cascader: 'UCascader',
Form: 'UForm',
Typography: 'UTypography',
Card: 'UCard',
Tag: 'UTag',
Image: 'UImage',
Alert: 'UAlert',
Modal: 'UModal',
Drawer: 'UDrawer',
Table: 'UTable',
Upload: 'UUpload',
Tabs: 'UTabs',
Checkbox: 'UCheckbox',
List: 'UList',
Tooltip: 'UTooltip',
Result: 'UResult',
Empty: 'UEmpty',
Steps: 'USteps',
Timeline: 'UTimeline',
Dropdown: 'UDropdown',
DatePicker: 'UDatePicker',
Radio: 'URadio',
Switch: 'USwitch',
Descriptions: 'UDescriptions',
Skeleton: 'Skeleton',
};
const U_MAP = Object.fromEntries(Object.entries(ANTD_TO_U).filter(([, u]) => UI_EXPORTS.has(u)));
// tokens.css:hex → css 变量名;一个 hex 对应多个变量时不可自动替换。
const TOKEN_BY_HEX = new Map();
{
const css = exists('packages/design-tokens/src/tokens.css')
? read('packages/design-tokens/src/tokens.css')
: '';
for (const m of css.matchAll(/(--[\w-]+)\s*:\s*(#[0-9a-fA-F]{6})\b/g)) {
const hex = m[2].slice(1).toLowerCase();
if (!TOKEN_BY_HEX.has(hex)) TOKEN_BY_HEX.set(hex, []);
TOKEN_BY_HEX.get(hex).push(m[1]);
}
}
const ICON_MAP_KEYS = (() => {
const file = 'apps/web/shell/src/layouts/SideNav.tsx';
if (!exists(file)) return new Set();
const block = /const iconMap[^=]*=\s*\{([\s\S]*?)\n\};/.exec(read(file))?.[1] ?? '';
return new Set([...block.matchAll(/^\s{2}(\w+):\s*</gm)].map((m) => m[1]));
})();
/** 解析 scripts/*menu*.sql 的 menu_type=2/3 行(含 finance 的 UPDATE 形式)。 */
function parseMenuRows() {
const rows = new Map(); // menu_id -> row
const dir = path.join(ROOT, 'scripts');
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.sql') && !/rollback/i.test(f));
for (const file of files) {
const sql = fs.readFileSync(path.join(dir, file), 'utf8');
// INSERT 形式:(id, 'code', parent, 'name', type, perm, product, route, icon, ...)
const rowRe =
/\(\s*(\d+)\s*,\s*'([^']*)'\s*,\s*(?:NULL|'[^']*')\s*,\s*'([^']*)'\s*,\s*([123])\s*,\s*(NULL|'[^']*')\s*,\s*'([^']*)'\s*,\s*(NULL|'[^']*')\s*,\s*(NULL|'[^']*')/g;
for (const m of sql.matchAll(rowRe)) {
const unq = (s) => (s === 'NULL' ? null : s.replace(/^'|'$/g, ''));
rows.set(Number(m[1]), {
id: Number(m[1]),
code: m[2],
name: m[3],
type: Number(m[4]),
perm: unq(m[5]),
route: unq(m[7]),
icon: unq(m[8]),
file,
});
}
// UPDATE 形式(finance 迁移:原地改 5 行)
for (const block of sql.split(/UPDATE\s+`sys_menu`/).slice(1)) {
const id = /\bWHERE\s+`menu_id`\s*=\s*(\d+)/.exec(block)?.[1];
if (!id) continue;
const set = (field) =>
new RegExp('`' + field + "`\\s*=\\s*\\'([^\\']*)\\'").exec(block)?.[1] ?? null;
const prev = rows.get(Number(id)) ?? { id: Number(id), file };
rows.set(Number(id), {
...prev,
code: set('menu_code') ?? prev.code,
name: set('menu_name') ?? prev.name,
type: prev.type ?? 2,
perm: set('perm_code') ?? prev.perm,
route: set('route') ?? prev.route,
icon: set('icon') ?? prev.icon,
file,
});
}
}
return [...rows.values()];
}
const MENU_ROWS = parseMenuRows();
function collect(dir, exts, out = []) {
if (!fs.existsSync(dir)) return out;
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
if (['node_modules', 'dist', '.turbo', 'out'].includes(e.name)) continue;
const full = path.join(dir, e.name);
if (e.isDirectory()) collect(full, exts, out);
else if (exts.some((x) => e.name.endsWith(x))) out.push(full);
}
return out;
}
const SUBAPP_ROOT = path.join(ROOT, 'apps/web/subapps');
const SUBAPPS = fs.existsSync(SUBAPP_ROOT)
? fs
.readdirSync(SUBAPP_ROOT, { withFileTypes: true })
.filter((e) => e.isDirectory())
.map((e) => e.name)
: [];
/* ------------------------------------------------------------------ */
/* 目标解析 */
/* ------------------------------------------------------------------ */
function subappMeta(name) {
const dir = path.join(SUBAPP_ROOT, name);
if (!fs.existsSync(dir)) return null;
const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
return { name, dir, route: pkg.uj?.route ?? name, pkg };
}
function pageTable(app) {
const appTs = path.join(app.dir, 'src/App.tsx');
if (!fs.existsSync(appTs)) return new Map();
const text = fs.readFileSync(appTs, 'utf8');
const imports = new Map();
for (const m of text.matchAll(/import\s+(\w+)\s+from\s+'(\.[^']+)';/g)) {
imports.set(m[1], m[2]);
}
const out = new Map();
const routes = /const\s+ROUTES[^=]*=\s*\[([\s\S]*?)\]\s*;/.exec(text)?.[1] ?? '';
for (const m of routes.matchAll(/\{\s*path:\s*'([^']+)'\s*,\s*Page:\s*(\w+)\s*\}/g)) {
out.set(m[1], imports.get(m[2]) ?? null);
}
const pages = /const\s+PAGES[^=]*=\s*\{([\s\S]*?)\}\s+as\s+const;/.exec(text)?.[1] ?? '';
for (const m of pages.matchAll(/^\s*([\w-]+):\s*(\w+),/gm)) {
out.set(m[1], imports.get(m[2]) ?? null);
}
return out;
}
function resolveTarget() {
const apps = [];
const focusFiles = new Set();
const focusRows = [];
const notes = [];
if (FLAGS.all || !target) {
for (const name of SUBAPPS) apps.push(subappMeta(name));
notes.push(`全子应用:${apps.map((a) => a.name).join(' / ')}`);
return { apps, focusFiles, focusRows, notes };
}
let app = null;
let pageSeg = null;
// Git Bash(MSYS) 会把以 / 开头的参数改写成 D:/.../finance/payment;
// 同时支持 /finance/payment、finance/payment 与 MSYS 改写后的绝对路径。
let normTarget = target;
const hit = SUBAPPS.find(
(n) => normTarget === n || normTarget.endsWith('/' + n) || normTarget.includes('/' + n + '/'),
);
if (hit && normTarget !== hit) {
const idx = normTarget.lastIndexOf('/' + hit + '/');
normTarget = idx >= 0 ? normTarget.slice(idx + 1) : hit;
}
if (normTarget.startsWith('/')) {
const norm = normTarget.replace(/\/+$/, '');
const row = MENU_ROWS.find((r) => r.route === norm && r.type === 2);
if (!row) throw new Error(`菜单 SQL 里没有 route=${norm} 的页面行(menu_type=2)`);
const seg = norm.split('/').filter(Boolean);
app = subappMeta(seg[0]);
pageSeg = seg.slice(1).join('/');
focusRows.push(row);
notes.push(`菜单:${row.name}(menu_code ${row.code} / ${norm})`);
} else if (/^\d+$/.test(target)) {
const row = MENU_ROWS.find((r) => r.code === target);
if (!row) throw new Error(`菜单 SQL 里没有 menu_code=${target}`);
const seg = (row.route ?? '').split('/').filter(Boolean);
app = subappMeta(seg[0]);
pageSeg = seg.slice(1).join('/');
focusRows.push(row);
notes.push(`菜单:${row.name}(${row.code})`);
} else if (normTarget.includes('/')) {
const [name, ...rest] = normTarget.split('/');
app = subappMeta(name);
pageSeg = rest.join('/') || null;
for (const r of MENU_ROWS) {
if (r.type !== 2 || !r.route) continue;
const s = r.route.split('/').filter(Boolean);
if (s[0] === name && s.slice(1).join('/') === pageSeg) focusRows.push(r);
}
} else {
app = subappMeta(normTarget);
if (!app)
throw new Error(`未知目标 ${target};可用:${SUBAPPS.join(' / ')},或菜单路由 /<域>/<页>`);
}
if (!app) throw new Error(`目标 ${target} 对应的子应用不存在`);
apps.push(app);
if (pageSeg) {
const table = pageTable(app);
const spec = table.get(pageSeg);
if (spec) {
const base = path.resolve(app.dir, 'src', spec.replace(/^\.\//, ''));
const hit = [base + '.tsx', path.join(base, 'index.tsx')].find((p) => fs.existsSync(p));
if (hit) focusFiles.add(hit);
}
// 路由表里没有的页面目标(如尚未登记菜单的新页 / 组件文件)按目录约定兜底解析,
// 否则会退化成扫描整个模块——与目标语义不符。
if (!focusFiles.size) {
const seg = pageSeg.split('/').filter(Boolean);
const bases = [path.join(app.dir, 'src/pages', ...seg), path.join(app.dir, 'src', ...seg)];
for (const base of bases) {
const hit = [base + '.tsx', path.join(base, 'index.tsx')].find((p) => fs.existsSync(p));
if (hit) {
focusFiles.add(hit);
break;
}
}
}
// 页面级巡检覆盖该页目录全部源码(index.tsx + 同目录 css / 子组件),
// 不能只看入口文件——样式与弹窗组件恰恰是铁律最容易破的地方。
for (const p of [...focusFiles]) {
const dir = fs.existsSync(p) && fs.statSync(p).isDirectory() ? p : path.dirname(p);
for (const f of collect(dir, ['.ts', '.tsx', '.css'])) focusFiles.add(f);
}
for (const r of MENU_ROWS) {
if (r.type !== 2) continue;
const s = (r.route ?? '').split('/').filter(Boolean);
if (s[0] === app.route && s.slice(1).join('/') === pageSeg) focusRows.push(r);
}
notes.push(
`聚焦页面:${pageSeg}${focusFiles.size ? ' → ' + rel([...focusFiles][0]) : '(未找到页面文件)'}`,
);
const menuNote = focusRows.find((r) => r.type === 2);
if (menuNote) notes.unshift(`菜单:${menuNote.name}(menu_code ${menuNote.code})`);
} else {
notes.push(`模块:${app.name}(route 前缀 /${app.route})`);
}
return { apps, focusFiles, focusRows, notes };
}
/* ------------------------------------------------------------------ */
/* finding 收集 */
/* ------------------------------------------------------------------ */
const findings = [];
function add(rule, spec, severity, file, line, message, edits = [], extra = {}) {
findings.push({
rule,
spec,
severity,
file: file ? rel(file) : null,
line,
message,
edits,
...extra,
});
}
function lineOf(text, index) {
return text.slice(0, index).split('\n').length;
}
/**
* 只把注释抹成空格,保留长度、换行与字符串字面量。
* 源色值常出现在「已改用令牌」的说明注释里(finance/Payment/constant.ts 就有三处),
* 直接对全文扫 hex 会把合规代码误报成违规。返回值与原串等长,edit 区间仍可复用。
*/
function maskComments(text, isCss) {
const out = text.split('');
const blank = (i) => {
if (out[i] !== '\n' && out[i] !== '\r') out[i] = ' ';
};
let state = 'code';
let quote = '';
for (let i = 0; i < text.length; i++) {
const c = text[i];
const n = text[i + 1];
if (state === 'code') {
if (c === '/' && n === '*') {
blank(i);
blank(i + 1);
state = 'block';
i++;
continue;
}
if (!isCss && c === '/' && n === '/') {
blank(i);
blank(i + 1);
state = 'line';
i++;
continue;
}
if (c === "'" || c === '"' || c === '`') {
state = 'str';
quote = c;
}
continue;
}
if (state === 'block') {
blank(i);
if (c === '*' && n === '/') {
blank(i + 1);
state = 'code';
i++;
}
continue;
}
if (state === 'line') {
blank(i);
if (c === '\n') state = 'code';
continue;
}
// 字符串:其中的 # 仍是真实色值,不能抹;只跳过转义。
if (c === '\\') {
i++;
continue;
}
if (c === quote) state = 'code';
}
return out.join('');
}
function varSpans(text) {
const spans = [];
for (const m of text.matchAll(/var\([^)]*\)/g)) spans.push([m.index, m.index + m[0].length]);
return spans;
}
function checkFile(file) {
const raw = fs.readFileSync(file, 'utf8');
const isCss = file.endsWith('.css');
const isTs = /\.(ts|tsx)$/.test(file);
const text = maskComments(raw, isCss);
// §1.1 / §1.2 / §1.8:与 scripts/check-boundaries.mjs 同口径(子应用侧)。
if (isTs) {
const boundary = [
[
'host-runtime',
/@uj\/platform-core/,
'引用 host 独占运行时 @uj/platform-core;改用 @uj/platform-sdk(§2)',
],
[
'virtual-key',
/virtual:(client-private-key|server-public-key)/,
'子应用不得注入 PEM 虚拟模块(§2)',
],
[
'secret-env',
/VITE_(CLIENT_PRIVATE_KEY|SERVER_PUBLIC_KEY|API_TARGET|SIGN_ENABLED|STRICT_VERIFY)/,
'签名/后端 env 只属于 shell(§2)',
],
[
'wujie-core',
/from\s+['"]wujie['"]/,
'子应用只用 window.$wujie.bus / props,不直 import wujie(§2)',
],
[
'axios-runtime',
/^import\s+(?!type\s)[^;]*from\s+['"]axios['"]/m,
'运行时 import axios;请求必须经 props.request(§1.1)',
],
['cross-subapp', /@uj\/web-/, '禁止引用主壳或其它子应用包(§2)'],
[
'download-direct',
/\bcreateObjectURL\s*\(|\bwindow\.open\s*\(|\.download\s*=\s*[^=]|\ba\.click\s*\(/,
'自行落地文件;下载必须经 downloadCenter(§1.8 / §14)',
],
];
for (const [id, re, msg] of boundary) {
const m = re.exec(text);
if (m) add(`boundary/${id}`, '§1 / §2 / §14', 'error', file, lineOf(text, m.index), msg);
}
// §1.3 / §3:值导入只能来自 @uj/ui 的 U*;type-only 允许(仓库现状即如此)。
const antdRe = /import\s*\{([^}]+)\}\s*from\s*['"]antd['"]\s*;?/g;
for (const m of text.matchAll(antdRe)) {
const specs = m[1]
.split(',')
.map((s) => s.trim())
.filter(Boolean);
const values = specs.filter((s) => !/^type\s/.test(s));
if (!values.length) continue; // 纯 type import,放行
const bad = values.filter((s) => /\s+as\s+/.test(s) || !U_MAP[s]);
const where = { file, line: lineOf(text, m.index) };
if (bad.length) {
add(
'ui/antd-import',
'§1.3 / §3',
'error',
where.file,
where.line,
`从 antd 值导入 ${bad.join(', ')};必须用 @uj/ui 的 U*(缺失先在 packages/ui 建再导出)`,
);
continue;
}
const names = values.map((s) => U_MAP[s]);
const memberUsed = values.filter((s) => new RegExp('\\b' + s + '\\.').test(text));
if (memberUsed.length) {
add(
'ui/antd-import',
'§1.3 / §3',
'error',
where.file,
where.line,
`antd 组件 ${memberUsed.join(', ')} 存在成员用法(如 Form.Item),需人工改为 UFormItem 等,不自动改`,
);
continue;
}
const replacement = `import { ${names.join(', ')} } from '@uj/ui';`;
const edits = [{ start: m.index, end: m.index + m[0].length, text: replacement }];
for (const s of values) {
const re = new RegExp('\\b' + s + '\\b', 'g');
for (const u of text.matchAll(re)) {
if (u.index >= m.index && u.index < m.index + m[0].length) continue;
edits.push({ start: u.index, end: u.index + s.length, text: U_MAP[s] });
}
}
add(
'ui/antd-import',
'§1.3 / §3',
'error',
where.file,
where.line,
`从 antd 值导入 ${values.join(', ')} → 改为 @uj/ui ${names.join(', ')}`,
edits,
{ auto: true, hint: `import ${values.join('/')} → ${names.join('/')}` },
);
}
// §3 反幻觉:@uj/ui / @/components 的命名导入必须真实存在。
for (const [mod, set] of [
['@uj/ui', UI_EXPORTS],
['@/components', BIZ_EXPORTS],
]) {
if (!set.size) continue;
for (const m of text.matchAll(
new RegExp(`import\\s*\\{([^}]+)\\}\\s*from\\s*['"]${mod.replace('/', '\\/')}['"]`, 'g'),
)) {
for (const part of m[1].split(',')) {
const name = part
.trim()
.replace(/^type\s+/, '')
.split(/\s+as\s+/)[0];
if (name && !set.has(name)) {
add(
'ui/export-missing',
'§3 / §12',
'error',
file,
lineOf(text, m.index),
`从 ${mod} 导入了未导出的 ${name};先建 U* / 业务组件再引`,
);
}
}
}
}
// §1.7:rowSelection 的 selectedRowKeys 禁止 .map(String) 强转。
if (/rowSelection/.test(text) && /selectedRowKeys[\s\S]{0,120}\.map\(String\)/.test(text)) {
const m = /\.map\(String\)/.exec(text);
add(
'table/key-cast',
'§1.7 / §7',
'error',
file,
lineOf(text, m.index),
'selectedRowKeys 与 rowKey 必须同类型;禁止 keys.map(String) 强转',
);
}
// §1.9 / §15.2:共享方法不得在子应用里写第二份。
for (const m of text.matchAll(
/\bfunction\s+(errorDetail|goTo|loadRemoteConfig|openExportUrl|formatDateTime)\s*\(/g,
)) {
const after = text.slice(m.index, m.index + 500);
// §15.3② 明示的刻意分叉(老接口时间串只做 T→空格,不换时区):源码已标注条款就不报。
// 标注在注释里,得看原文——text 已经把注释抹掉了。
if (/15\.3/.test(raw.slice(Math.max(0, m.index - 400), m.index))) continue;
// 薄委托适配器:体内已直接走 downloadCenter,不是「第二份实现」。
if (m[1] === 'openExportUrl' && /downloadCenter\./.test(after)) continue;
add(
'util/duplicate',
'§1.9 / §15.2',
'warn',
file,
lineOf(text, m.index),
`${m[1]} 已收进 @uj/biz 或 @uj/platform-sdk,别写第二份(§15.3 的刻意分叉除外)`,
);
}
}
// §1.4 / §5:硬编码颜色;var(..., #fallback) 里的回退值不算。
const spans = isTs || isCss ? varSpans(text) : [];
for (const m of text.matchAll(/#[0-9a-fA-F]{3,8}\b/g)) {
if (spans.some(([s, e]) => m.index >= s && m.index < e)) continue;
let hex = m[0].slice(1).toLowerCase();
if (/^[0-9a-f]{3}$/.test(hex)) hex = [...hex].map((c) => c + c).join('');
if (!/^[0-9a-f]{6}$/.test(hex)) continue;
const toks = TOKEN_BY_HEX.get(hex) ?? [];
const where = { file, line: lineOf(text, m.index) };
if (toks.length === 1) {
add(
'theme/hardcoded-color',
'§1.4 / §5',
'error',
where.file,
where.line,
`写死颜色 ${m[0]} → var(${toks[0]})`,
[{ start: m.index, end: m.index + m[0].length, text: `var(${toks[0]})` }],
{ auto: true, hint: `${m[0]} → var(${toks[0]})` },
);
} else if (toks.length > 1) {
add(
'theme/hardcoded-color',
'§1.4 / §5',
'error',
where.file,
where.line,
`写死颜色 ${m[0]};tokens.css 有 ${toks.length} 个同值变量 ${toks.join(' / ')},需人工选语义`,
);
} else {
add(
'theme/hardcoded-color',
'§1.4 / §5',
'error',
where.file,
where.line,
`写死颜色 ${m[0]};tokens.css 无同值令牌,先在 palette.ts + tokens.css 定义再引`,
);
}
}
// §1.5:只有 .ant-* 自己作为选择器主体才算裸用(会覆盖 antd 内部样式)。
// 「.ant-drawer-body .uj-xxx」只是拿 antd 容器做祖先限定来抬特异性,动的是自己的类,放行。
if (isCss) {
for (const m of text.matchAll(/(^|\n)\s*([^{}]+)\{/g)) {
const bare = m[2].split(',').some((part) => {
const chain = part
.trim()
.split(/\s+|>|\+|~/)
.filter(Boolean);
// 整条链都是 .ant-* 才算裸用;带 .uj-xxx / .uc-xxx 自有类祖先的是局部限定,放行。
return chain.length > 0 && chain.every((s) => /^\.ant-/.test(s));
});
if (bare) {
add(
'theme/ant-selector',
'§1.5',
'warn',
file,
lineOf(text, m.index),
'裸 .ant-* 选择器;确认未覆盖 antd 内部盒模型/几何',
);
break;
}
}
}
}
/** 入口骨架:tokens.css 导入 + uj-scope 根类名(§5)。 */
function checkEntry(app) {
const main = path.join(app.dir, 'src/main.tsx');
if (fs.existsSync(main)) {
const text = fs.readFileSync(main, 'utf8');
if (!text.includes('@uj/design-tokens/tokens.css')) {
add(
'entry/tokens-css',
'§5',
'error',
main,
1,
'main.tsx 未 import @uj/design-tokens/tokens.css',
[{ start: 0, end: 0, text: "import '@uj/design-tokens/tokens.css';\n" }],
{ auto: true, hint: '顶部补 tokens.css import' },
);
}
}
const appTs = path.join(app.dir, 'src/App.tsx');
if (fs.existsSync(appTs)) {
const text = fs.readFileSync(appTs, 'utf8');
const m = /<div className="([^"]*uj-[a-z-]+-app[^"]*)">/.exec(text);
if (m && !/\buj-scope\b/.test(m[1])) {
add(
'entry/uj-scope',
'§5',
'error',
appTs,
lineOf(text, m.index),
`根节点 className="${m[1]}" 缺 uj-scope,CSS 变量不生效`,
[
{
start: m.index + '<div className="'.length,
end: m.index + '<div className="'.length + m[1].length,
text: `uj-scope ${m[1]}`,
},
],
{ auto: true, hint: '根节点补 uj-scope' },
);
}
}
}
/** 菜单 → 子应用 → 路由表 → 页面文件 → 权限码(§13 / §8 / §9)。 */
function checkMenu(app, rows) {
const pkgRoute = app.route;
const table = pageTable(app);
const mine = rows.filter((r) => r.type === 2 && (r.route ?? '').startsWith(`/${pkgRoute}/`));
// 这批 SQL 只登记了 points / usedcar / finance 三个域;store / system 不在菜单 SQL 里,
// 没行可对齐不等于违规。仅当该域确实出现在 SQL 中却没有页面行时才告警。
const inSql = rows.some((r) => (r.route ?? '').startsWith(`/${pkgRoute}`));
if (!mine.length && inSql) {
add(
'menu/no-page-row',
'§13',
'warn',
null,
0,
`菜单 SQL 里没有 /${pkgRoute}/ 开头的页面行(menu_type=2)`,
);
}
for (const r of mine) {
const seg = r.route.split('/').filter(Boolean);
const tail = seg.slice(1).join('/');
const spec = table.get(tail);
if (!spec) {
add(
'menu/route-missing',
'§13.2 / §9',
'error',
path.join(app.dir, 'src/App.tsx'),
0,
`菜单 ${r.code} 的 ${r.route} 在 App.tsx 页面表里没有「${tail}」条目(点进去会白屏/UEmpty)`,
);
continue;
}
const base = path.resolve(app.dir, 'src', spec.replace(/^\.\//, ''));
const hit = [base + '.tsx', path.join(base, 'index.tsx')].find((p) => fs.existsSync(p));
if (!hit) {
add(
'menu/page-file-missing',
'§13.2',
'error',
path.join(app.dir, 'src/App.tsx'),
0,
`菜单 ${r.code}→页面「${tail}」映射到 ${rel(base)},但文件不存在`,
);
}
if (r.icon && !ICON_MAP_KEYS.has(r.icon)) {
add(
'menu/icon-unregistered',
'§13.1',
'warn',
null,
0,
`菜单 ${r.code} 图标 ${r.icon} 未登记在 SideNav iconMap;dev 告警后静默回落`,
);
}
}
// 权限码表对账:SQL 中本域 perm_code 必须逐字出现在 codes.ts。
const codesFile = path.join(app.dir, 'src/permissions/codes.ts');
if (fs.existsSync(codesFile)) {
const text = fs.readFileSync(codesFile, 'utf8');
const body = /export const \w+\s*=\s*\{([\s\S]*?)\n\}\s+as\s+const;/.exec(text)?.[1] ?? '';
const declared = new Set(
[...body.matchAll(/['"]([\w-]+:[\w-]+(?::[\w-]+)?)['"]/g)].map((m) => m[1]),
);
const expected = new Set(
rows.filter((r) => r.perm && r.perm.startsWith(`${pkgRoute}:`)).map((r) => r.perm),
);
const close = /\n\}\s+as\s+const;/.exec(text);
for (const code of expected) {
if (declared.has(code)) continue;
const parts = code.split(':').slice(1);
const key = parts.join('_').toUpperCase().replace(/-/g, '_');
const keyTaken = new RegExp(`\\b${key}\\s*:`).test(body);
const where = { file: codesFile, line: close ? lineOf(text, close.index) : 1 };
if (keyTaken || !close) {
add(
'menu/perm-code-missing',
'§8 / §13.4',
'error',
where.file,
where.line,
`菜单 SQL 有权限码 ${code},${rel(codesFile)} 缺失;键名 ${key} 已占用,需人工处理`,
);
continue;
}
const insert = `\n // [audit 自动补齐] ${code}\n ${key}: '${code}',`;
add(
'menu/perm-code-missing',
'§8 / §13.4',
'error',
where.file,
where.line,
`菜单 SQL 有权限码 ${code},补进 ${rel(codesFile)}`,
[{ start: close.index, end: close.index, text: insert }],
{ auto: true, hint: `+ ${key}: '${code}'` },
);
}
for (const code of declared) {
if (!expected.has(code)) {
add(
'menu/perm-code-orphan',
'§8 / §13.4',
'warn',
codesFile,
0,
`${rel(codesFile)} 的权限码 ${code} 在菜单 SQL 中不存在(可能已迁移,见 §16)`,
);
}
}
// 页面源码里硬编码的域权限码也必须在表里。
const files = collect(path.join(app.dir, 'src'), ['.ts', '.tsx']);
for (const f of files) {
const t = fs.readFileSync(f, 'utf8');
// 权限码口径:域前缀 + 小写 kebab 段(§8 `资源:动作`)。localStorage 键如
// finance:devSessionId 含大写,不是权限码,必须排除——否则每次都误报两条。
const codeRe = new RegExp(`['"](${pkgRoute}:[a-z][a-z0-9-]*(?::[a-z][a-z0-9-]*)*)['"]`, 'g');
for (const m of t.matchAll(codeRe)) {
const code = m[1];
if (!code.includes(':') || code.split(':').length < 2) continue;
if (declared.has(code) || expected.has(code)) continue;
add(
'perm/undeclared',
'§8',
'error',
f,
lineOf(t, m.index),
`页面硬编码未登记的权限码 ${code}`,
);
}
}
}
}
/* ------------------------------------------------------------------ */
/* 修复落盘 */
/* ------------------------------------------------------------------ */
function applyFixes() {
const byFile = new Map();
for (const f of findings) {
if (!f.auto || !f.file || !f.edits?.length) continue;
if (!byFile.has(f.file)) byFile.set(f.file, []);
byFile.get(f.file).push(...f.edits);
}
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const changed = [];
for (const [file, edits] of byFile) {
const abs = path.join(ROOT, file);
const before = fs.readFileSync(abs, 'utf8');
let after = before;
const sorted = [...edits].sort((a, b) => b.start - a.start);
for (const e of sorted) {
if (e.end > before.length || e.start < 0 || e.start > e.end) {
throw new Error(`修复区间越界 ${file}: ${e.start}-${e.end}`);
}
after = after.slice(0, e.start) + e.text + after.slice(e.end);
}
if (after === before) continue;
if (FLAGS.dryRun) {
changed.push({ file, status: 'dry-run' });
continue;
}
const backup = path.join(ROOT, '.tmp/audit-backup', stamp, file);
fs.mkdirSync(path.dirname(backup), { recursive: true });
fs.writeFileSync(backup, before);
fs.writeFileSync(abs, after);
changed.push({ file, backup: rel(backup), status: 'fixed' });
}
return changed;
}
/* ------------------------------------------------------------------ */
/* 主流程 */
/* ------------------------------------------------------------------ */
let resolved;
try {
resolved = resolveTarget();
} catch (err) {
console.error(`[audit] ${err.message}`);
process.exit(2);
}
for (const app of resolved.apps.filter(Boolean)) {
const files = resolved.focusFiles.size
? [...resolved.focusFiles].filter((f) => f.startsWith(app.dir))
: collect(path.join(app.dir, 'src'), ['.ts', '.tsx', '.css']);
for (const f of files) checkFile(f);
checkEntry(app);
checkMenu(app, MENU_ROWS);
}
findings.sort(
(a, b) =>
(a.file ?? '').localeCompare(b.file ?? '') || a.line - b.line || a.rule.localeCompare(b.rule),
);
let changed = [];
if (FLAGS.fix) changed = applyFixes();
if (FLAGS.json) {
console.log(
JSON.stringify(
{
target: target ?? '--all',
notes: resolved.notes,
findings,
changed,
},
null,
2,
),
);
} else {
console.log(`[audit] 目标:${resolved.notes.join(';')}`);
console.log(
`[audit] 菜单 SQL 行 ${MENU_ROWS.length} / tokens ${TOKEN_BY_HEX.size} / UI 导出 ${UI_EXPORTS.size}`,
);
console.log('');
for (const f of findings) {
const icon = f.severity === 'error' ? '✗' : '⚠';
const fixable = f.auto ? ' [可自动修复]' : '';
console.log(`${icon} [${f.rule}] ${f.spec} ${f.file ?? '(全局)'}:${f.line || '-'}`);
console.log(` ${f.message}${fixable}`);
if (f.hint) console.log(` → ${f.hint}`);
}
const errs = findings.filter((f) => f.severity === 'error').length;
const warns = findings.filter((f) => f.severity === 'warn').length;
const autos = findings.filter((f) => f.auto).length;
console.log('');
console.log(`[audit] 错误 ${errs} / 告警 ${warns} / 可自动修复 ${autos}`);
for (const c of changed) {
console.log(
`[audit] ${c.status === 'dry-run' ? '将修改' : '已修改'} ${c.file}${c.backup ? `(备份 ${c.backup})` : ''}`,
);
}
if (FLAGS.fix && !FLAGS.dryRun) {
console.log('[audit] 修复后请跑 git diff 复核,再跑 pnpm verify。');
}
}
const remaining = findings.filter(
(f) => f.severity === 'error' && !(FLAGS.fix && f.auto && !FLAGS.dryRun),
);
process.exit(remaining.length ? 1 : 0);
scripts/check-boundaries.mjs
View file @
6b00df2
...
...
@@ -102,11 +102,20 @@ for (const appDir of subappDirs) {
}
// CSS:裸 .ant-* 覆盖会改 antd 内部盒模型,项目约定一律走 ConfigProvider token。
//
旧仓迁过来的 CSS 里可能已有,先只告警,待样式归类中逐条清理
。
//
「.uj-xxx .ant-yyy」这类带自有类祖先的局部限定只动自己的样式,与新巡检脚本同口径放行
。
for (const file of collect(path.join(appDir, 'src'), ['.css'])) {
const text = fs.readFileSync(file, 'utf8');
const rel = path.relative(ROOT, file).split(path.sep).join('/');
if (/^\s*\.ant-/.test(text) || /\n\s*\.ant-/.test(text)) {
const bareAnt = [...text.matchAll(/(^|\n)\s*([^{}]+)\{/g)].some((m) =>
m[2].split(',').some((part) => {
const chain = part
.trim()
.split(/\s+|>|\+|~/)
.filter(Boolean);
return chain.length > 0 && chain.every((s) => /^\.ant-/.test(s));
}),
);
if (bareAnt) {
warnings.push(`[css] ${rel}: 含裸 .ant-* 选择器,确认未覆盖组件内部几何属性`);
}
}
...
...
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment