Commit 9ebc8a7f by limin

release: v1.0.0 初始版本

0 parents
Showing 259 changed files with 4831 additions and 0 deletions
node_modules
# 子包自己的 node_modules 同样必须排除:pnpm 会为每个 workspace 包建一层。
# 不写这条的话,本地装过依赖的机器构建时会把 Windows 的二进制(如 esbuild)拷进 Linux 镜像。
**/node_modules
dist
**/dist
.git
.gitignore
*.log
# 不要把本地演示账号拷进镜像:容器内用 volume 或 BOOTSTRAP_USER 初始化
packages/server/data
# .env.production 必须进上下文:它是线上高德 Key 的唯一通道(运维拿不到 --build-arg)。
# 排除的是带本机值的 .local 那一层,以及根 .env(后端运行期密钥,不该烘进镜像)。
.env
.env.local
.env.*.local
coverage
docs
# 本地临时目录 / 构建缓存
.tmp
*.tsbuildinfo
.workbuddy
.DS_Store
Thumbs.db
# ============================================================================
# 高德地图 JS API 2.0 凭证
# ----------------------------------------------------------------------------
# 1. 到 https://console.amap.com/dev/key/app 申请「Web端(JS API)」类型的 Key
# 2. 安全密钥:2021-12-02 之后新申请的 Key 必须配套使用,否则会报 INVALID_USER_SCODE
# 3. 域名白名单:Key 需绑定本项目实际访问域名(本地开发填 localhost / 127.0.0.1),
# 否则会报 INVALID_USER_DOMAIN 并白屏
#
# 复制本文件为 .env.local 后填写(.env.local 已在 .gitignore 中,不会入库)
# ============================================================================
VITE_AMAP_KEY=
VITE_AMAP_SECURITY_CODE=
# 高德加载失败时的兜底排查提示开关(true 时控制台输出详细诊断信息)
VITE_AMAP_DEBUG=true
# ============================================================================
# 登录后台服务(packages/server)配置
# ----------------------------------------------------------------------------
# AUTH_SECRET:JWT 签发密钥,生产环境务必设为强随机值(如 openssl rand -hex 32)
# 未设置时服务会回退到不安全的开发默认密钥并告警
# SERVER_PORT:登录服务监听端口,需与 vite.config.ts 中 server.proxy 的 target 一致
#
# 复制本文件为 .env.local 后填写(.env.local 已在 .gitignore 中,不会入库)
# ============================================================================
AUTH_SECRET=
SERVER_PORT=8787
# 生产构建期配置:这个文件**随仓库入库**,是唯一能把线上高德 Key 带进镜像的通道。
#
# 为什么入库:CI 由运维用 docker compose 构建,人拿不到 docker exec / --build-arg,
# 所以值只能来自构建上下文里的文件。Vite 在 mode=production 时自动读 .env.production,
# 优先级低于 shell 环境变量、高于 .env.local(详见 vite loadEnv),所以本地调试不受影响。
#
# 为什么可以入库:JS API Key 本来就必须出现在浏览器产物里,靠域名白名单约束,不是密钥。
# 真正不能进来的东西(AUTH_SECRET、账号密码)不写在这里:Vite 只把 VITE_ 前缀的变量打进产物,
# 后端读的是另一份 .env(被 .gitignore 排除),两者不要混。
VITE_AMAP_KEY=11b1dc16a79ade95fa0ef28246f4d518
VITE_AMAP_SECURITY_CODE=fc17677e508becf6ceb8aad81d442015
# 生产关掉诊断输出,避免把加载失败细节铺到访客控制台
VITE_AMAP_DEBUG=false
node_modules/
dist/
dist-ssr/
*.log
_pnpm.log
_tsc.log
# 本地验证脚本与截图(headless Chrome 拍图、分位探针),不进仓库
.tmp/
.DS_Store
Thumbs.db
.idea/
.vscode/*
!.vscode/extensions.json
coverage/
# 本地环境变量(含 AUTH_SECRET 等密钥),不入库;保留 .env.example
# 例外:.env.production 必须入库 —— 它是 CI 构建期唯一能拿到高德 Key 的通道(值本来就会烘进前端产物)。
.env
.env.local
.env.*.local
# 登录服务运行数据(账号哈希),不入库;用 pnpm --filter @hm/server add:account 生成
packages/server/data/accounts.json
# 补齐工具的本机运行记录与产物(可能含业务数据),不入库
packages/tools/data-complete/ui-state.json
packages/tools/data-complete/cache/
packages/tools/data-complete/out/
packages/tools/data-complete/.temp/
packages/tools/data-complete/**/*.已补全.*
packages/tools/data-complete/**/*处理日志.*
# 本机 AI 工作记录与预览产物,不进新仓
.workbuddy/
# TypeScript 增量构建缓存
*.tsbuildinfo
registry=https://registry.npmmirror.com
strict-peer-dependencies=false
auto-install-peers=true
shamefully-hoist=false
node_modules
dist
public/data
data/raw
pnpm-lock.yaml
*.md
{
"semi": true,
"singleQuote": true,
"printWidth": 100,
"tabWidth": 2,
"trailingComma": "all",
"arrowParens": "always",
"endOfLine": "lf"
}
# 单进程同源托管:前端静态(dist/) + 登录 API(/api) 同容器同端口(8787)。
# 账号数据挂宿主机目录(见 docker-compose.yml 的 volumes),重建容器不丢。
#
# 构建耗时要点(改之前先读):
# 1) 依赖清单(package.json / lockfile / .npmrc)单独 COPY 成一层,源码靠后 COPY。
# 这样改业务代码只重跑后面的 build,install 层直接命中缓存。别把 `COPY . .` 挪到 install 前面。
# 2) pnpm store 用 BuildKit cache mount 挂在 /pnpm-store,builder 与 runner 共用同一个 id。
# runner 阶段的安装于是全部走本地硬链接,不联网。需要 Docker 20.10+(compose v2 默认开 BuildKit);
# 如果构建机是老的 legacy builder,会报 `--mount` 未知参数,此时去掉两处 --mount 即可降级。
# 3) runner 只装 @hm/server 的生产依赖(约 90 个包),不再全量装一遍前端工具链(约 470 个)。
# tsx 已按运行期依赖归入 packages/server 的 dependencies,才能被 --prod 带上。
# 4) 新增 workspace 包时,把它的 package.json 补进下面两处 COPY 清单,否则 install 会因解析不到而失败。
# ---- 构建前端 ----
FROM harbortest.glsx.com.cn/node/node:22.21.1-alpine3.21 AS builder
WORKDIR /app
ENV NODE_ENV=production
ENV SERVER_PORT=8787
RUN corepack enable
RUN npm config set registry https://registry.npmmirror.com/
COPY . .
RUN pnpm install
# 高德 Key 由仓库根的 .env.production 提供(Vite 在 production 模式自动读),这里不需要 --build-arg。
# 别把 ARG 加回来:未定义时它会插值成空串导出给构建,空串压过文件里的值,产物反倒变成 NO_KEY。
RUN pnpm build
# ---- 运行 ----
# FROM harbortest.glsx.com.cn/node/node:22.21.1-alpine3.21 AS runner
# WORKDIR /app
# ENV NODE_ENV=production
# ENV SERVER_PORT=8787
# RUN corepack enable
# # 只拷运行所需源码与前端产物,重新解析依赖(含 tsx 以运行 .ts)
# COPY pnpm-lock.yaml package.json pnpm-workspace.yaml ./
# COPY packages ./packages
# COPY src ./src
# COPY public ./public
# COPY index.html vite.config.ts tsconfig.json tsconfig.node.json ./
# COPY --from=builder /app/dist ./dist
# RUN pnpm install
# 账号目录挂为 volume(见 docker-compose.yml),避免写入镜像层
VOLUME ["/app/packages/server/data"]
EXPOSE 8787
CMD ["pnpm", "--filter", "@hm/server", "start"]
\ No newline at end of file \ No newline at end of file
This diff is collapsed. Click to expand it.
{
"_comment": "聚合网格配置。网格边长用『屏幕像素』而不是经纬度定义:聚合的视觉目标本来就是『圆圈之间隔多少像素』,用像素表述后换算成经纬度,网格密度自动跟着缩放级别走。",
"minZoom": 9,
"maxZoom": 18,
"tileSize": 256,
"gridPx": 48,
"viewportPadRatio": 0.5,
"_why_gridPx": "48px 是『热力分辨率』与『数字不重叠』的折中。热力权重点数 = 桶数,桶数 ∝ 1/gridPx²:64px 时视口内只有约 500 个权重点,热力会糊成一片色团、丢掉细节;24px 时数字底衬(直径最大约 40px)会互相压住。48px 下视口内约 880 个权重点,热力仍保有层次,数字之间也还留有 8px 以上间隙。",
"_why_shared": "⚠️ 热力层与聚合圆圈层【必须共用这一套网格】,不能各自配一套。初版给了两套(cluster 64px 视口驱动 / heat 24px 全量降采样 + 桶数封顶翻倍),结果高缩放级别下两层网格尺寸不同(4W 数据在 z18 下热力网格被翻倍到 96px)→ 同一个点被分进不同的桶 → 桶中心(取桶内均值)不一致 → 放大到只剩 1、2 个点时,聚合散点画的是精确点位,热力斑却落在 96px 网格的均值上,肉眼可见错位几十像素。共用一套网格后两层桶成员完全相同,中心 100% 重合。",
"_why_viewport": "视口驱动聚合:只对视口(外扩边距)内的点分桶,于是桶数天然收敛到屏幕格子数量级(约 width/64 × height/64 ≈ 500 个),与数据总量、缩放级别都无关——这是 20W 点在 z18 下不至于退化成 20 万个单点圆圈的根因。也因此不再需要『桶数封顶 + 网格翻倍』那套自适应收敛逻辑。viewportPadRatio 按视口尺寸的倍数外扩,用来吸收拖动过程中新露出的区域,避免边缘长时间空带。"
}
services:
heatmap:
build:
context: .
# 不要在这里加 args:高德 Key 由仓库根的 .env.production 提供(见 Dockerfile 上方注释)。
# 未定义的 "${VITE_AMAP_KEY}" 会插值成空串导出给构建,空串压过文件里的值 → NO_KEY 产物。
ports:
- "8876:8787"
# pnpm 当 PID 1 时 SIGTERM 未必转发给 node 子进程,滚动更新会等满超时被 SIGKILL
init: true
environment:
SERVER_PORT: "8787"
# 临时未配:留空时服务用代码里的默认密钥签名,能登录但不安全。运维到位后换成强随机值
# (openssl rand -hex 32)并重启容器 —— 换密钥会让已登录的人重新登录一次,属预期。
AUTH_SECRET: "${AUTH_SECRET}"
# 临时:账号表文件不存在时,服务首次启动就按这两行建 admin。
# 生效前提:/data/soft/nodejs_project/cx-backend-data 下没有 accounts.json(有就不覆盖,
# 哪怕里面是空数组)。要重新初始化就让运维删掉那个文件。
# 上线稳定后把这两行改回 "${BOOTSTRAP_USER:-}" / "${BOOTSTRAP_PASSWORD:-}",别让密码留在仓库里。
BOOTSTRAP_USER: "${BOOTSTRAP_USER:-}"
BOOTSTRAP_PASSWORD: "${BOOTSTRAP_PASSWORD:-}"
volumes:
# 账号持久化
- /data/soft/nodejs_project/cx-backend-data:/app/packages/server/data
cpus: 2
mem_limit: 2g
restart: unless-stopped
import tseslint from '@typescript-eslint/parser';
import reactHooks from 'eslint-plugin-react-hooks';
import prettier from 'eslint-config-prettier';
export default [
{
ignores: ['dist/**', 'node_modules/**', 'public/data/**', 'data/raw/**', 'packages/ui/dist/**'],
},
{
files: ['**/*.{ts,tsx}'],
languageOptions: {
parser: tseslint,
parserOptions: {
ecmaVersion: 2022,
sourceType: 'module',
ecmaFeatures: { jsx: true },
},
},
plugins: {
'react-hooks': reactHooks,
},
rules: {
...reactHooks.configs.recommended.rules,
'no-console': ['warn', { allow: ['warn', 'error', 'info'] }],
'@typescript-eslint/no-unused-vars': 'off',
},
},
prettier,
];
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="智能网联监管平台 · 风险热力图" />
<!-- 内联 favicon:不引外部文件,省掉 dev / 部署时对 /favicon.ico 的 404 请求 -->
<link
rel="icon"
href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%234655a2'/%3E%3Ccircle cx='16' cy='16' r='7' fill='%23ff7a45'/%3E%3C/svg%3E"
/>
<title>智能网联监管平台 · 风险热力图</title>
<!--
内联加载占位:dev 冷启动(重启后)首屏模块还没 ready 时,浏览器会白着等。
这段 HTML+内联样式在首字节解析后立刻绘制一个「加载中」占位,React 挂载后
会替换掉 #root 的内容,所以不会影响正常运行。至少把白屏变成可见的等待。
-->
<style>
#hm-splash {
position: fixed;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 18px;
background: #0e1116;
color: #c7ced9;
font: 14px/1.6 system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
}
#hm-splash__ring {
width: 42px;
height: 42px;
border: 3px solid rgba(255, 255, 255, 0.15);
border-top-color: #ff7a45;
border-radius: 50%;
animation: hm-spin 0.9s linear infinite;
}
@keyframes hm-spin {
to {
transform: rotate(360deg);
}
}
#hm-splash__txt {
letter-spacing: 0.05em;
opacity: 0.85;
}
</style>
</head>
<body>
<div id="root">
<div id="hm-splash">
<div id="hm-splash__ring"></div>
<div id="hm-splash__txt">智能网联监管平台 · 风险热力图 · 加载中…</div>
</div>
</div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
{
"name": "sz-icv-heatmap",
"private": true,
"version": "1.0.0",
"type": "module",
"description": "智能网联监管平台 · 风险热力图(方案 C:热力底色 + 上层聚合数字)",
"packageManager": "pnpm@10.8.1",
"engines": {
"node": "^22.22.2 || ^24.15.0 || >=26.0.0"
},
"scripts": {
"dev": "concurrently -n web,api -c blue,green \"vite\" \"cd packages/server && pnpm dev\"",
"fill": "node --disable-warning=ExperimentalWarning packages/tools/data-complete/src/desktop.ts",
"dev:web": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview",
"typecheck": "tsc --noEmit",
"test": "vitest run",
"lint": "eslint src packages",
"format": "prettier --write .",
"format:check": "prettier --check .",
"server": "pnpm --filter @hm/server dev",
"start": "pnpm build && pnpm --filter @hm/server start",
"dev:all": "pnpm dev",
"prepare": "husky"
},
"dependencies": {
"@ant-design/icons": "^6.3.4",
"@hm/map-overlay": "workspace:^0.1.0",
"@hm/ui": "workspace:^0.1.0",
"antd": "^6.6.5",
"dayjs": "^1.11.13",
"react": "^19.3.0",
"react-dom": "^19.3.0",
"react-router-dom": "^7.18.4",
"xlsx": "^0.18.5",
"zustand": "^5.0.0"
},
"devDependencies": {
"@testing-library/jest-dom": "^7.0.1",
"@testing-library/react": "^16.3.3",
"@types/node": "^26.6.5",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
"@typescript-eslint/parser": "^8",
"@vitejs/plugin-react": "^4.3.4",
"concurrently": "^9.1.0",
"eslint": "^9",
"eslint-config-prettier": "^9",
"eslint-plugin-react-hooks": "^5",
"husky": "^9",
"jsdom": "^30.1.1",
"lint-staged": "^15",
"prettier": "^3",
"typescript": "^5.6.3",
"vite": "^6.0.0",
"vitest": "^5.0.2"
},
"lint-staged": {
"**/*.{ts,tsx,js,mjs,json,css,md}": [
"prettier --write"
]
},
"pnpm": {
"onlyBuiltDependencies": [
"esbuild"
]
}
}
{
"name": "@hm/clean-adapters",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "出险数据清洗的「壳」:xlsx/csv 解码、GeoJSON 加载器、行归一化、Worker host。纯算法见 @hm/clean-core。",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.json"
},
"dependencies": {
"@hm/clean-core": "workspace:*",
"xlsx": "^0.18.5"
},
"devDependencies": {
"typescript": "^5.6.3"
},
"engines": {
"node": ">=18"
}
}
/**
* @hm/clean-adapters —— 清洗算法(@hm/clean-core)的「壳」集合。
*
* 算法包只管纯函数;这一层负责把它接进真实世界:
* - xlsx / csv 解码(decodeIncidentFile)
* - 几何资源加载(loadLandMaskFromUrl / loadCorridorsFromUrl)
* - 行归一化(normalizeIncidentTable:列映射 + 地址拆解 → CleanRow[])
* - 端到端编排(runClean:解码 → 归一化 → 清洗 → 报告 + 标注)
* - Worker 宿主(cleanWorkerHandler:把清洗挂到 Web Worker)
*/
export { decodeIncidentFile } from './xlsx';
export type { RawTable } from './xlsx';
export { loadLandMaskFromUrl, loadCorridorsFromUrl } from './loaders';
export { normalizeIncidentTable } from './normalize';
export type { NormalizeResult } from './normalize';
export { runClean } from './runClean';
export type { RunCleanInput, RunCleanResult, AnnotatedRow } from './runClean';
export { cleanWorkerHandler } from './worker';
export type { CleanWorkerRequest, CleanWorkerResponse } from './worker';
/**
* 几何资源加载器(适配器层,壳的一部分)。
*
* 把「一份 GeoJSON 文件」变成 @hm/clean-core 能直接吃的几何对象:
* 陆地掩膜(WGS-84 海岸线)/ 海上合法走廊(WGS-84)。解析纯函数来自 clean-core,
* 这里只负责「拿数据」(fetch / 读路径),让算法包继续零 IO。
*
* 浏览器里传相对 URL(如 `/geo/shenzhen-land.geojson`),Node CLI 里传本地文件路径或 http(s) URL。
* 同一份实现两边通用,因为现代 Node 与浏览器都有全局 `fetch`。
*/
import { loadLandMask, loadCorridors, type NamedPolys, type CorridorFeature } from '@hm/clean-core';
async function fetchJson(urlOrPath: string): Promise<unknown> {
// 本地文件路径(以 / 或盘符或相对路径且非 http(s))走 fs 读取,避免在 Node 里把路径当 URL fetch
if (/^(https?:)?\/\//i.test(urlOrPath) || urlOrPath.startsWith('http')) {
const res = await fetch(urlOrPath);
if (!res.ok) throw new Error(`加载几何失败 ${urlOrPath}:HTTP ${res.status}`);
return (await res.json()) as unknown;
}
// 文件:动态 import node:fs(浏览器里不会走到这条分支)
const { readFile } = await import('node:fs/promises');
const buf = await readFile(urlOrPath.replace(/^file:\/\//, ''));
return JSON.parse(buf.toString('utf-8'));
}
/** 加载陆地掩膜(优先海岸线)。失败抛错,由调用方决定降级还是中断。 */
export async function loadLandMaskFromUrl(urlOrPath: string): Promise<NamedPolys[]> {
return loadLandMask(await fetchJson(urlOrPath));
}
/** 加载海上合法走廊。失败抛错,由调用方决定降级还是中断。 */
export async function loadCorridorsFromUrl(urlOrPath: string): Promise<CorridorFeature[]> {
return loadCorridors(await fetchJson(urlOrPath));
}
/**
* 行归一化(适配器层,壳的一部分,但属于「把源数据整理成算法能吃的形状」)。
*
* 清洗算法(@hm/clean-core 的 `cleanRows`)只接受已经解析好的 `CleanRow[]`:
* 案件号、原始地址、GCJ-02 经纬度、以及已解析的 行政区 / 街道 / 道路 字符串。
* 这一层干的就是「xlsx 的脏行 → CleanRow[]」之间的那段——列名认领、地址拆解、
* 行政区归一、道路名现解析。它用的是深圳口径(与 app 的 ingestCore 同一套列名别名与地址规则),
* 跨城市换宿主时这一份需按当地行政区字典重校准。
*
* 注:街道维度这里只取「街道列」的值(缺列即记「未识别」),不做地址残段反推街道名
* (app 端那一份反推依赖每个区的街道词表,体量较大)。这不影响落水判定的结果
* (落水只看坐标 + 掩膜 + 走廊),只影响「街道低频」这一类的计数口径。
*/
import type { RawTable } from './xlsx';
import { UNRESOLVED_LABEL, roadOfAddress, type CleanRow } from '@hm/clean-core';
export interface NormalizeResult {
/** 通过结构性校验、可进入清洗的行 */
rows: CleanRow[];
/** 被拒收的行(案件号非法 / 坐标非数值 / 超出深圳范围 / 空行) */
rejected: Array<{ reason: string; count: number; sample?: string }>;
/** 原始总行数(含表头) */
totalRows: number;
}
/* ------------------------------- 列名映射 ------------------------------- */
type ColumnKey = 'caseNo' | 'address' | 'lng' | 'lat' | 'district' | 'street' | 'road';
const COLUMN_ALIASES: Record<ColumnKey, string[]> = {
caseNo: ['案件号', '案件编号', '报案号'],
address: ['出险地点', '出险地址', '事故地点'],
lng: ['经度', 'lng', 'lon', 'longitude'],
lat: ['纬度', '维度', 'lat', 'latitude'],
district: ['行政区'],
street: ['街道'],
road: ['道路'],
};
function buildColumnMap(header: string[]): Record<ColumnKey, number> {
const cells = header.map((v) => String(v ?? '').trim().toLowerCase());
const find = (aliases: string[]) => {
for (const a of aliases.map((x) => x.trim().toLowerCase())) {
const i = cells.findIndex((c) => c === a);
if (i >= 0) return i;
}
return cells.findIndex((c) => COLUMN_ALIASES_caseInsensitive(c, aliases));
};
const map = {
caseNo: find(COLUMN_ALIASES.caseNo),
address: find(COLUMN_ALIASES.address),
lng: find(COLUMN_ALIASES.lng),
lat: find(COLUMN_ALIASES.lat),
district: find(COLUMN_ALIASES.district),
street: find(COLUMN_ALIASES.street),
road: find(COLUMN_ALIASES.road),
};
const mandatoryOk = [map.caseNo, map.address, map.lng, map.lat].every((i) => i >= 0);
return mandatoryOk
? map
: { caseNo: 0, address: 1, lng: 2, lat: 3, district: -1, street: -1, road: -1 };
}
function COLUMN_ALIASES_caseInsensitive(cell: string, aliases: string[]): boolean {
return aliases.some((a) => cell.includes(a.toLowerCase()));
}
/* ------------------------------- 地址拆解 ------------------------------- */
const DISTRICT_NAMES = [
'福田区', '罗湖区', '南山区', '宝安区', '龙岗区', '盐田区',
'龙华区', '坪山区', '光明区', '大鹏新区', '深汕特别合作区',
];
const DISTRICT_ALIAS: Array<[string, string]> = [
['光明新区', '光明区'],
['龙华新区', '龙华区'],
['坪山新区', '坪山区'],
];
const DISTRICT_TAIL = /[区县旗]$/;
const districtNamesByLen = [...DISTRICT_NAMES].sort((a, b) => b.length - a.length);
const districtAliasByLen = [...DISTRICT_ALIAS].sort((a, b) => b[0].length - a[0].length);
const ROAD_HEAD = /^(路|街|道|巷|里|桥|大道|大街|公路)/;
/** 区名短写 → 行政区名(与 app 的 ingestCore 同一套生成规则:剥尾巴、排除撞车与前缀冲突) */
const districtShortNames: Array<[string, string]> = (() => {
const grouped = new Map<string, string[]>();
for (const name of DISTRICT_NAMES) {
const short = name.replace(/(?:新区|区|县|旗)$/, '');
if (short === name || short.length < 2) continue;
const owners = grouped.get(short);
if (owners) owners.push(name);
else grouped.set(short, [name]);
}
const out: Array<[string, string]> = [];
for (const [short, owners] of grouped) {
if (owners.length !== 1) continue;
if (DISTRICT_NAMES.some((n) => n !== owners[0] && n.startsWith(short))) continue;
out.push([short, owners[0]]);
}
return out.sort((a, b) => b[0].length - a[0].length);
})();
function canonicalDistrict(name: string): string {
return DISTRICT_ALIAS.find(([from]) => from === name)?.[1] ?? name;
}
function joinRest(head: string, tail: string): string {
if (!head) return tail;
return tail ? `${head}-${tail}` : head;
}
function splitAddress(parts: string[]): { district: string; rest: string } {
const peel = (
seg: string,
tailRest: string,
allowTail: boolean,
): { district: string; rest: string } | null => {
if (!seg) return null;
const known = districtNamesByLen.find((n) => seg.startsWith(n));
if (known) return { district: known, rest: joinRest(seg.slice(known.length), tailRest) };
const alias = districtAliasByLen.find(([from]) => seg.startsWith(from));
if (alias) return { district: alias[1], rest: joinRest(seg.slice(alias[0].length), tailRest) };
const short = districtShortNames.find(([from]) => seg.startsWith(from));
if (short) {
const rest = seg.slice(short[0].length);
if (!ROAD_HEAD.test(rest)) return { district: short[1], rest: joinRest(rest, tailRest) };
}
if (allowTail && DISTRICT_TAIL.test(seg)) {
return { district: canonicalDistrict(seg), rest: tailRest };
}
return null;
};
const head = peel(parts[2] ?? '', parts.slice(3).join('-'), true);
if (head) return head;
for (let i = 0; i < parts.length; i += 1) {
const hit = peel(parts[i], parts.slice(i + 1).join('-'), false);
if (hit) return hit;
}
return { district: '', rest: parts.join('-') };
}
/* ------------------------------- 主入口 ------------------------------- */
const SANITY_BOX = { minLng: 113.6, maxLng: 114.7, minLat: 22.3, maxLat: 23.0 };
export function normalizeIncidentTable(table: RawTable): NormalizeResult {
const col = buildColumnMap(table.header);
const rejected = new Map<string, number>();
const rejectedSamples = new Map<string, string>();
const addReject = (reason: string, label: string) => {
rejected.set(reason, (rejected.get(reason) ?? 0) + 1);
if (!rejectedSamples.has(reason)) rejectedSamples.set(reason, label);
};
const rows: CleanRow[] = [];
for (const cells of table.rows) {
const get = (i: number) => (i >= 0 ? String(cells[i] ?? '').trim() : '');
const caseNo = get(col.caseNo);
const address = get(col.address);
const lngRaw = get(col.lng);
const latRaw = get(col.lat);
if (!caseNo && !address && !lngRaw && !latRaw) continue; // 空行
if (!/^\d{15,24}$/.test(caseNo)) {
addReject('案件号非纯数字或长度异常', `${caseNo} | ${address}`);
continue;
}
const lng = Number(lngRaw);
const lat = Number(latRaw);
if (!Number.isFinite(lng) || !Number.isFinite(lat)) {
addReject('经纬度非数值', `${caseNo} | ${address}`);
continue;
}
if (lng < SANITY_BOX.minLng || lng > SANITY_BOX.maxLng || lat < SANITY_BOX.minLat || lat > SANITY_BOX.maxLat) {
addReject('经纬度超出深圳合理范围', `${caseNo} | ${address}`);
continue;
}
const parts = address.split('-').map((s) => s.trim()).filter(Boolean);
const addrSplit = splitAddress(parts);
let district = col.district >= 0 ? get(col.district) : '';
if (district) district = canonicalDistrict(district);
if (!district) district = addrSplit.district;
const detail = addrSplit.rest;
let street = col.street >= 0 ? get(col.street) : '';
if (!street) street = UNRESOLVED_LABEL;
let road = col.road >= 0 ? get(col.road) : '';
if (!road) road = roadOfAddress(detail);
rows.push({ caseNo, address, lng, lat, district, street, road });
}
const rejectedList = Array.from(rejected.entries()).map(([reason, count]) => ({
reason,
count,
sample: rejectedSamples.get(reason),
}));
return { rows, rejected: rejectedList, totalRows: table.rows.length };
}
/**
* 端到端清洗编排(适配器层)。
*
* 把「字节 → 报告 + 标注」这一整条链路串起来:解码(xlsx/csv)→ 归一化(列映射 / 地址拆解)→
* 调用 @hm/clean-core 的 `cleanRows` 跑 8 类判定 → 汇总成分组报告 + 逐行标注。
* 这是 B 阶段(CLI / Worker)真正调用的入口;app 端目前仍用自己那份 ingestion(行为等价),
* 后续可平滑切到这套编排。
*/
import {
cleanRows,
FLAG,
type CleanRow,
type NamedPolys,
type CorridorFeature,
type CleanThresholds,
type CleanClassKey,
} from '@hm/clean-core';
import { decodeIncidentFile, type RawTable } from './xlsx';
import { normalizeIncidentTable } from './normalize';
const CLASS_KEYS: CleanClassKey[] = [
'MISSING',
'MISSING_PARTIAL',
'OUTSIDE',
'OFFSHORE_NEAR',
'OFFSHORE_FAR',
'ISO_200',
'ISO_500',
'ISO_1000',
'SPARSE',
'SPARSE_STREET',
'SMALL',
];
const KEY_BITS: Array<[CleanClassKey, number]> = CLASS_KEYS.map((k) => [k, FLAG[k]]);
export interface RunCleanInput {
/** 文件名(用于解码分支判断 xlsx/csv) */
fileName?: string;
/** 原始文件字节 */
bytes?: Uint8Array | ArrayBuffer;
/** 已解码的表(与 bytes 二选一,bytes 优先) */
table?: RawTable;
/** 陆地掩膜(WGS-84)。不传 = 跳过落水判定并提示 */
landMask?: NamedPolys[] | null;
/** 海上合法走廊(WGS-84) */
corridors?: CorridorFeature[] | null;
/** 案件坐标所用坐标系,默认 GCJ-02 */
coordSystem?: 'GCJ-02' | 'WGS-84';
/** 阈值覆盖 */
thresholds?: Partial<CleanThresholds>;
/** 每类保留样例条数 */
maxSamples?: number;
}
export interface AnnotatedRow {
caseNo: string;
address: string;
lng: number;
lat: number;
/** 逐行处置位掩码 */
flags: number;
/** 命中的类别键(人类可读) */
classes: string[];
}
export interface RunCleanResult {
fileName: string;
totalRows: number;
validRows: number;
/** 被拒收的行(结构性坏行,不进清洗) */
rejected: Array<{ reason: string; count: number; sample?: string }>;
/** 分组报告 */
classes: Array<{ key: string; label: string; count: number; defaultOn: boolean }>;
warnings: string[];
counts: { sparseRoads: number; sparseStreets: number; offshoreCorridorExempt: number };
/** 逐行标注(仅有效行) */
rows: AnnotatedRow[];
}
export function runClean(input: RunCleanInput): RunCleanResult {
const table =
input.table ??
(input.bytes && input.fileName
? decodeIncidentFile(input.fileName, input.bytes)
: null);
if (!table) throw new Error('runClean 需要 bytes+fileName 或 table 之一');
const norm = normalizeIncidentTable(table);
const res = cleanRows(norm.rows, {
landMask: input.landMask ?? undefined,
corridors: input.corridors ?? null,
coordSystem: input.coordSystem,
thresholds: input.thresholds,
maxSamples: input.maxSamples,
});
const annotated: AnnotatedRow[] = norm.rows.map((r: CleanRow, i) => {
const f = res.flags[i];
const classes = KEY_BITS.filter(([, b]) => (f & b) !== 0).map(([k]) => k);
return {
caseNo: r.caseNo,
address: r.address,
lng: r.lng,
lat: r.lat,
flags: f,
classes,
};
});
return {
fileName: table.fileName,
totalRows: norm.totalRows,
validRows: norm.rows.length,
rejected: norm.rejected,
classes: res.classes.map((c) => ({
key: c.key,
label: c.label,
count: c.count,
defaultOn: c.defaultOn,
})),
warnings: res.warnings,
counts: res.counts,
rows: annotated,
};
}
/**
* 清洗 Worker 宿主(适配器层)。
*
* 把 `runClean` 挂到 Web Worker 的 onmessage 上,让解码后的重计算(几何判定 / 邻域扫描)
* 脱离主线程、不卡 UI。主线程侧负责「解码文件 + 拉几何」,把算好的 table / 几何对象
* postMessage 过来;Worker 只跑纯计算,回传标注结果。
*
* 用法(主线程):
* const worker = new Worker(new URL('./clean.worker.ts', import.meta.url), { type: 'module' });
* worker.onmessage = (e) => { if (e.data?.type === 'clean-done') ... };
* worker.postMessage({ type: 'clean', id: 1, payload: { table, landMask, corridors } });
*
* 在 Worker 文件里只需:
* import { cleanWorkerHandler } from '@hm/clean-adapters/worker';
* cleanWorkerHandler(self as unknown as DedicatedWorkerGlobalScope);
*/
import { runClean, type RunCleanResult } from './runClean';
import type { RawTable } from './xlsx';
import type { NamedPolys, CorridorFeature, CleanThresholds } from '@hm/clean-core';
export interface CleanWorkerRequest {
type: 'clean';
id: number | string;
payload: {
table: RawTable;
landMask?: NamedPolys[] | null;
corridors?: CorridorFeature[] | null;
coordSystem?: 'GCJ-02' | 'WGS-84';
thresholds?: Partial<CleanThresholds>;
maxSamples?: number;
};
}
export type CleanWorkerResponse =
| { type: 'clean-done'; id: number | string; result: RunCleanResult }
| { type: 'clean-error'; id: number | string; message: string };
/**
* 把一个 Worker 的全局对象挂上清洗处理。幂等:重复调用只是重新绑定 onmessage。
*/
export function cleanWorkerHandler(self: DedicatedWorkerGlobalScope): void {
self.onmessage = (ev: MessageEvent<CleanWorkerRequest>) => {
const msg = ev.data;
if (!msg || msg.type !== 'clean') return;
try {
const result = runClean({
table: msg.payload.table,
landMask: msg.payload.landMask ?? undefined,
corridors: msg.payload.corridors ?? null,
coordSystem: msg.payload.coordSystem,
thresholds: msg.payload.thresholds,
maxSamples: msg.payload.maxSamples,
});
const resp: CleanWorkerResponse = { type: 'clean-done', id: msg.id, result };
self.postMessage(resp);
} catch (err) {
const resp: CleanWorkerResponse = {
type: 'clean-error',
id: msg.id,
message: err instanceof Error ? err.message : String(err),
};
self.postMessage(resp);
}
};
}
/**
* xlsx / csv 解码(适配器层,壳的一部分)。
*
* 这是把「用户上传的字节」变成「表头 + 行数组」的地方 —— 它不属于清洗算法(@hm/clean-core),
* 而是算法跑之前的 IO 预处理。算法包因此保持纯净、可被任意宿主复用;解码这层则由各自的壳负责。
*
* 与 app 的 ingestCore 同一套口径:
* - xlsx / xls / zip 走 SheetJS(`type: 'array'` 必须喂 Uint8Array);
* - csv 走自研严格 UTF-8 解码,失败退 GBK(Excel 另存的 CSV 常见),避免中文乱码把区/街道全判成「未识别」。
*/
import * as XLSX from 'xlsx';
export interface RawTable {
fileName: string;
/** 表头(去空白后的字符串) */
header: string[];
/** 数据行(已剥掉表头),每格是字符串或数字 */
rows: Array<Array<string | number>>;
}
/** ZIP 魔数 PK\x03\x04 → Excel;否则按 CSV 文本处理 */
function looksLikeZip(bytes: Uint8Array): boolean {
return bytes.length > 1 && bytes[0] === 0x50 && bytes[1] === 0x4b;
}
function splitXlsx(bytes: Uint8Array): Array<Array<unknown>> {
const wb = XLSX.read(bytes, { type: 'array', cellDates: false });
const sheetName = wb.SheetNames[0];
if (!sheetName) throw new Error('文件里没有可读的工作表');
return XLSX.utils.sheet_to_json<unknown[]>(wb.Sheets[sheetName], {
header: 1,
raw: true,
blankrows: false,
defval: '',
});
}
/** CSV 解码:严格 UTF-8,失败退 GBK */
function decodeCsv(bytes: Uint8Array): string {
const stripBom = (s: string) => (s.charCodeAt(0) === 0xfeff ? s.slice(1) : s);
try {
return stripBom(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
} catch {
try {
return stripBom(new TextDecoder('gbk').decode(bytes));
} catch (err) {
throw new Error(`CSV 编码无法识别(既不是 UTF-8 也不是 GBK):${String(err)}`);
}
}
}
function splitCsvLineQuoted(line: string): string[] {
const out: string[] = [];
let cur = '';
let inQuote = false;
for (let i = 0; i < line.length; i += 1) {
const ch = line[i];
if (inQuote) {
if (ch === '"') {
if (line[i + 1] === '"') {
cur += '"';
i += 1;
} else {
inQuote = false;
}
} else cur += ch;
} else if (ch === '"') {
inQuote = true;
} else if (ch === ',') {
out.push(cur);
cur = '';
} else cur += ch;
}
out.push(cur);
return out;
}
function splitCsv(text: string): string[][] {
const lines = text.split(/\r?\n/);
const rows: string[][] = [];
let w = 0;
const hasQuote = text.indexOf('"') >= 0;
for (let i = 0; i < lines.length; i += 1) {
const line = lines[i];
if (!line) continue;
rows[w++] = hasQuote ? splitCsvLineQuoted(line) : line.split(',');
}
rows.length = w;
return rows;
}
/**
* 解码一份出险数据文件为 RawTable。
* @param fileName 用于判断后缀(.xlsx/.xls 走 SheetJS,否则按 CSV)
* @param bytes 文件原始字节(Uint8Array 或 ArrayBuffer 均可)
*/
export function decodeIncidentFile(fileName: string, bytes: Uint8Array | ArrayBuffer): RawTable {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
const isExcel = /\.xlsx$/i.test(fileName) || /\.xls$/i.test(fileName) || looksLikeZip(view);
const raw = isExcel ? splitXlsx(view) : splitCsv(decodeCsv(view));
if (raw.length < 2) throw new Error('文件里只有表头或完全是空的');
const header = raw[0].map((v) => String(v ?? '').trim());
const rows: Array<Array<string | number>> = raw
.slice(1)
.map((r) => r.map((v) => (typeof v === 'string' || typeof v === 'number' ? v : String(v ?? ''))));
return { fileName, header, rows };
}
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"],
"module": "ESNext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"verbatimModuleSyntax": true,
"types": ["node"],
"baseUrl": ".",
"paths": {
"@hm/clean-core": ["../clean-core/src/index.ts"]
}
},
"include": ["src"]
}
{
"name": "@hm/clean-cli",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "出险数据清洗命令行工具:输入 xlsx + 陆地掩膜 geojson + 海上走廊 geojson,输出报告(md) + 标注(csv/json)。",
"bin": {
"clean-cli": "dist/index.js"
},
"scripts": {
"typecheck": "tsc --noEmit -p tsconfig.json",
"dev": "tsx src/index.ts",
"build": "tsc -p tsconfig.json"
},
"dependencies": {
"@hm/clean-adapters": "workspace:*",
"@hm/clean-core": "workspace:*"
},
"devDependencies": {
"tsx": "^4.19.2",
"typescript": "^5.6.3"
},
"engines": {
"node": ">=18"
}
}
/**
* clean-cli —— 出险数据清洗命令行。
*
* 用法:
* clean-cli <input.xlsx|input.csv>
* [--land <shenzhen-land.geojson>] 陆地掩膜(WGS-84),默认 public/geo/shenzhen-land.geojson
* [--corridors <corridors.geojson>] 海上合法走廊,默认 public/geo/shenzhen-offshore-corridors.geojson
* [--out <dir>] 输出目录,默认 ./clean-output
* [--coord-system GCJ-02|WGS-84] 案件坐标坐标系,默认 GCJ-02
* [--sparse-road N] [--sparse-street N] [--small-radius M] [--small-threshold N]
*
* 输出:
* clean-output/report.md 人类可读的清洗报告(总量 / 拒收 / 各类计数 / 提示)
* clean-output/annotations.csv 逐行标注(案件号 / 地址 / 经纬度 / 位掩码 / 命中类别)
* clean-output/annotations.json 完整结构化结果
*
* 算法全部来自 @hm/clean-core,本工具只是把「文件 → 报告」这一段壳做好。
*/
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
import { runClean, loadLandMaskFromUrl, loadCorridorsFromUrl, type RunCleanResult } from '@hm/clean-adapters';
import type { CleanThresholds } from '@hm/clean-core';
interface CliOptions {
input: string;
land: string;
corridors: string;
out: string;
coordSystem: 'GCJ-02' | 'WGS-84';
thresholds: Partial<CleanThresholds>;
}
function parseArgs(argv: string[]): CliOptions {
const opts: CliOptions = {
input: '',
land: 'public/geo/shenzhen-land.geojson',
corridors: 'public/geo/shenzhen-offshore-corridors.geojson',
out: './clean-output',
coordSystem: 'GCJ-02',
thresholds: {},
};
const num = (v: string | undefined, fallback: number): number => {
const n = Number(v);
return Number.isFinite(n) ? n : fallback;
};
for (let i = 0; i < argv.length; i += 1) {
const a = argv[i];
switch (a) {
case '--land': opts.land = argv[++i] ?? opts.land; break;
case '--corridors': opts.corridors = argv[++i] ?? opts.corridors; break;
case '--out': opts.out = argv[++i] ?? opts.out; break;
case '--coord-system': opts.coordSystem = (argv[++i] as 'GCJ-02' | 'WGS-84') ?? opts.coordSystem; break;
case '--sparse-road': opts.thresholds.sparseRoad = num(argv[++i], 1); break;
case '--sparse-street': opts.thresholds.sparseStreet = num(argv[++i], 1); break;
case '--small-radius': opts.thresholds.smallRadiusM = num(argv[++i], 1000); break;
case '--small-threshold': opts.thresholds.smallThreshold = num(argv[++i], 10); break;
case '-h':
case '--help':
printHelp();
process.exit(0);
default:
if (!a.startsWith('-') && !opts.input) opts.input = a;
else if (a.startsWith('--')) console.warn(`[warn] 未知参数 ${a},已忽略`);
}
}
if (!opts.input) {
console.error('错误:缺少输入文件(xlsx / csv)。用 --help 查看用法。');
process.exit(2);
}
return opts;
}
function printHelp(): void {
console.log(`clean-cli <input.xlsx|input.csv>
[--land <geojson>] 陆地掩膜(WGS-84),默认 public/geo/shenzhen-land.geojson
[--corridors <geojson>] 海上合法走廊,默认 public/geo/shenzhen-offshore-corridors.geojson
[--out <dir>] 输出目录,默认 ./clean-output
[--coord-system GCJ-02|WGS-84] 案件坐标坐标系,默认 GCJ-02
[--sparse-road N] [--sparse-street N] [--small-radius M] [--small-threshold N]`);
}
function csvCell(v: string | number): string {
const s = String(v ?? '');
return /[",\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
}
function toCsv(result: RunCleanResult): string {
const header = ['caseNo', 'address', 'lng', 'lat', 'flags', 'classes'];
const lines = [header.join(',')];
for (const r of result.rows) {
lines.push(
[r.caseNo, r.address, r.lng, r.lat, r.flags, r.classes.join('|')].map(csvCell).join(','),
);
}
return lines.join('\n');
}
function toMarkdown(result: RunCleanResult): string {
const L: string[] = [];
L.push(`# 出险数据清洗报告`);
L.push('');
L.push(`- 文件:${result.fileName}`);
L.push(`- 原始行数:${result.totalRows}`);
L.push(`- 进入清洗:${result.validRows}`);
const rejected = result.rejected.reduce((s, r) => s + r.count, 0);
L.push(`- 结构性拒收:${rejected}`);
L.push('');
if (result.rejected.length) {
L.push(`## 拒收原因`);
L.push('');
L.push(`| 原因 | 数量 | 样例 |`);
L.push(`| --- | --- | --- |`);
for (const r of result.rejected) L.push(`| ${r.reason} | ${r.count} | ${r.sample ?? ''} |`);
L.push('');
}
L.push(`## 各类处置(勾选后剔除)`);
L.push('');
L.push(`| 类别 | 说明 | 数量 | 默认勾选 |`);
L.push(`| --- | --- | --- | --- |`);
for (const c of result.classes) {
if (c.count > 0) L.push(`| ${c.key} | ${c.label} | ${c.count} | ${c.defaultOn ? '是' : '否'} |`);
}
L.push('');
L.push(`## 汇总`);
L.push('');
L.push(`- 道路低频涉及路数:${result.counts.sparseRoads}`);
L.push(`- 街道低频涉及街道数:${result.counts.sparseStreets}`);
L.push(`- 海上合法走廊豁免落水点:${result.counts.offshoreCorridorExempt}`);
if (result.warnings.length) {
L.push('');
L.push(`## 提示`);
for (const w of result.warnings) L.push(`- ${w}`);
}
return L.join('\n');
}
async function main(): Promise<void> {
const opts = parseArgs(process.argv.slice(2));
console.log(`[clean-cli] 读取输入:${opts.input}`);
const bytes = readFileSync(opts.input);
let landMask = null as Awaited<ReturnType<typeof loadLandMaskFromUrl>> | null;
if (existsSync(opts.land)) {
console.log(`[clean-cli] 加载陆地掩膜:${opts.land}`);
landMask = await loadLandMaskFromUrl(opts.land);
} else {
console.warn(`[clean-cli] 未找到陆地掩膜 ${opts.land},落水判定将跳过`);
}
let corridors = null as Awaited<ReturnType<typeof loadCorridorsFromUrl>> | null;
if (existsSync(opts.corridors)) {
console.log(`[clean-cli] 加载海上合法走廊:${opts.corridors}`);
corridors = await loadCorridorsFromUrl(opts.corridors);
} else {
console.warn(`[clean-cli] 未找到海上走廊 ${opts.corridors},落水点不享受走廊豁免`);
}
const result = runClean({
fileName: opts.input,
bytes,
landMask: landMask ?? undefined,
corridors,
coordSystem: opts.coordSystem,
thresholds: opts.thresholds,
});
mkdirSync(opts.out, { recursive: true });
writeFileSync(`${opts.out}/report.md`, toMarkdown(result), 'utf-8');
writeFileSync(`${opts.out}/annotations.csv`, toCsv(result), 'utf-8');
writeFileSync(`${opts.out}/annotations.json`, JSON.stringify(result, null, 2), 'utf-8');
console.log(
`[clean-cli] 完成:进入清洗 ${result.validRows} 行,报告见 ${opts.out}/report.md、标注见 ${opts.out}/annotations.csv`,
);
}
main().catch((err) => {
console.error('[clean-cli] 失败:', err instanceof Error ? err.message : err);
process.exit(1);
});
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable", "WebWorker"],
"module": "ESNext",
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true,
"moduleDetection": "force",
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"verbatimModuleSyntax": true,
"types": ["node"],
"baseUrl": ".",
"paths": {
"@hm/clean-core": ["../clean-core/src/index.ts"],
"@hm/clean-adapters": ["../clean-adapters/src/index.ts"]
}
},
"include": ["src"]
}
{
"name": "@hm/clean-core",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "出险数据清洗算法内核:坐标系归一(GCJ-02↔WGS-84)、陆地/合法走廊判定、处置分级(位掩码)、低频/孤立/小热点标记。纯函数,无 DOM / 网络 / 全局状态 / 第三方依赖,可被任意宿主(前端、Worker、Node CLI)复用。",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit"
},
"engines": {
"node": ">=18"
}
}
/**
* 道路名解析与字典下标的纯函数层(从宿主项目的 aggregate/dims 抽取,自包含)。
*
* 清洗内核只需要其中两样:
* - ROAD_UNRESOLVED:道路字典里「读不出路名」那一档的下标(markSparseRoads 用它跳过这一档);
* - roadOfAddress / buildRoadIndex:CLI / 适配器从地址残段现解析道路名时用。
* 其余时段 / 夜间档等维度与「清洗」无关,不进纯算法包。
*/
/** 地址字典里「读不出路名」那一档的下标(它不进名次,只报起数) */
export const ROAD_UNRESOLVED = 0;
/**
* 道路后缀,按长度从长到短排。
*
* 同一个位置先试长的:「人民大道」要读成「人民 + 大道」,
* 先匹配到「道」以外的短后缀就会把名字切错。
*/
const ROAD_SUFFIXES = [
'高速公路',
'城市快速路',
'快速路',
'高架桥',
'立交桥',
'立交',
'匝道',
'隧道',
'大桥',
'辅路',
'环路',
'大道',
'公路',
'国道',
'省道',
'县道',
'乡道',
'高速',
'街',
'路',
'巷',
];
/**
* 主名不许跨过去的字:地址层级、门牌、楼层这些都不是路名的一部分。
*
* 有了这一列,「南山区科技园南路」取到的是「科技园南路」而不是「南山区科技园南路」,
* 「西乡街道海山路」取到的是「海山路」而不是把行政街道一起吞进路名。
* 「街道」之所以能挡住,靠的是这里同时列了「街」和「道」,不靠正则里的负向断言。
*/
const NAME_BREAK = '省市区县号栋幢座层室街道路巷';
/** 写着「这条路没有名字」的开头。它们读得出后缀,读不出是哪条路 */
const NAMELESS = ['无名', '未命名', '未名', '暂无'];
/** 主名的字符面:中日韩汉字 + 字母数字(「S308省道」这类编号写法要留得住) */
function isNameChar(c: string): boolean {
return /[一-鿿A-Za-z0-9]/.test(c);
}
/** 在这个位置上找最长的道路后缀;找不到返回 0(长度,单位:字) */
function suffixAt(text: string, pos: number): number {
for (const s of ROAD_SUFFIXES) {
if (text.startsWith(s, pos)) {
// 「街道」是行政单位不是路段:把它念成路名,几乎每条地址都能命中,
// 结果就是冒出一条并不存在的路还霸占榜首。街后面跟道时整档跳过。
if (s === '街' && text.startsWith('道', pos + 1)) continue;
return s.length;
}
}
return 0;
}
/**
* 取地址里第一个写得完整的道路名,取不到返回空串。
*
* 走法是从左往右找后缀,找到就把主名往左吃:主名最长 10 个字,遇到 NAME_BREAK
* 立刻收(层级、门牌不是路名),遇到不是姓名的字(标点、空格)也收。
* 主名为空或整条不足 3 个字时接着往后找下一个后缀 ——「无名路」不能算读出来,
* 但「无名路旁的深南大道」还是该归到深南大道。
*/
export function roadOfAddress(detail: string): string {
if (!detail) return '';
const len = detail.length;
for (let pos = 0; pos < len; pos += 1) {
const sl = suffixAt(detail, pos);
if (sl === 0) continue;
// 主名往左吃,最多 10 个字:层级、门牌这些字(NAME_BREAK)和标点空格都是断路
const floor = Math.max(0, pos - 10);
let start = pos;
for (let k = pos - 1; k >= floor; k -= 1) {
const c = detail[k];
if (NAME_BREAK.indexOf(c) >= 0 || !isNameChar(c)) break;
start = k;
}
const name = detail.slice(start, pos);
if (name.length === 0 || name.length + sl < 3) {
pos += sl - 1;
continue;
}
const road = name + detail.slice(pos, pos + sl);
if (NAMELESS.some((p) => road.startsWith(p))) {
pos += sl - 1;
continue;
}
return road;
}
return '';
}
/**
* 把每条地址字典项归到一条道路(或读不出那一档)。
*
* 键落在「地址字典」而不是「案件」上:几十万条地址里的不同写法只有几千条,
* 扫一遍字典就把逐行的字符串匹配从热循环里彻底拿掉了 —— 与区名、街道名同一套思路。
* 下标 0 固定留给「读不出路名」,其余按首次出现顺序编号,names 与下标一一对应。
*/
export function buildRoadIndex(details: string[]): { names: string[]; ofDetail: Int32Array } {
const names: string[] = [''];
const ofDetail = new Int32Array(details.length);
const seen = new Map<string, number>();
for (let i = 0; i < details.length; i += 1) {
const road = roadOfAddress(details[i] ?? '');
if (!road) {
ofDetail[i] = ROAD_UNRESOLVED;
continue;
}
let id = seen.get(road);
if (id === undefined) {
id = names.length;
names.push(road);
seen.set(road, id);
}
ofDetail[i] = id;
}
return { names, ofDetail };
}
/**
* 坐标系互转:WGS-84(GPS 真值,Natural Earth 等国际数据源用的就是它)↔ GCJ-02
* (俗称「火星坐标 / 高德坐标」—— 国内地图与国内地理数据默认使用的加密偏移系)。
*
* 两套系是同一个东西的两个名字:**火星坐标 = 高德坐标 = GCJ-02**。真正要区分的是
* 它和 WGS-84 的差,国内任一点的坐标在 GCJ-02 下相对 WGS-84 会偏移约 300–700m
* (深圳一带约 0.004–0.006° 经度、0.001° 纬度,即 ~500m)。
*
* 本项目的坐标系分布(写这段代码时已经钉死):
* - 出险案件坐标:GCJ-02(见 ingestCore 写进 meta 的 `coordSystem: 'GCJ-02'`),
* 且全程无任何转换直接喂给高德底图 —— 数据本就是 GCJ-02,否则全城点位会整体漂 ~500m;
* - 行政区边界 shenzhen.geojson:高德 DistrictSearch 导出,GCJ-02;
* - 陆地掩膜 shenzhen-land.geojson:Natural Earth 10m 陆地裁剪,WGS-84。
*
* 所以「坐标落水 / 域外」判定必须把案件点(GCJ-02)先归一化到 WGS-84,再和 WGS-84 的
* 陆地掩膜做射线法。不转的话两套系差 ~500m,会把离真实海岸线几百米内的近岸点判反
* (岸上的点误杀、海上的点漏抓)。转换只在 `classifyOffshore` 一处发生,
* 几何判定 `offshoreVerdict` 始终保持「入参即 WGS-84」的纯几何契约。
*
* 该模块是纯函数,不碰 DOM / 网络 / 全局状态,被清洗内核与各渲染层共用。
*/
const GCJ_A = 6378245.0; // 长半轴
const GCJ_EE = 0.00669342162296594323; // 第一偏心率平方
const PI = Math.PI;
/** 是否在中国境外(GCJ-02 偏移只在中国陆域及近海生效,境外原样返回)。 */
export function outOfChina(lng: number, lat: number): boolean {
return lng < 72.004 || lng > 137.8347 || lat < 0.8293 || lat > 55.8271;
}
function transformLat(x: number, y: number): number {
let r =
-100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
r += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
r += ((20.0 * Math.sin(y * PI) + 40.0 * Math.sin((y / 3.0) * PI)) * 2.0) / 3.0;
r += ((160.0 * Math.sin((y / 12.0) * PI) + 320 * Math.sin((y * PI) / 30.0)) * 2.0) / 3.0;
return r;
}
function transformLng(x: number, y: number): number {
let r = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
r += ((20.0 * Math.sin(6.0 * x * PI) + 20.0 * Math.sin(2.0 * x * PI)) * 2.0) / 3.0;
r += ((20.0 * Math.sin(x * PI) + 40.0 * Math.sin((x / 3.0) * PI)) * 2.0) / 3.0;
r += ((150.0 * Math.sin((x / 12.0) * PI) + 300.0 * Math.sin((x / 30.0) * PI)) * 2.0) / 3.0;
return r;
}
/** WGS-84 → GCJ-02(正向,确定式;境外原样返回)。 */
export function wgs84ToGcj02(lng: number, lat: number): [number, number] {
if (outOfChina(lng, lat)) return [lng, lat];
let dLat = transformLat(lng - 105.0, lat - 35.0);
let dLng = transformLng(lng - 105.0, lat - 35.0);
const radLat = (lat / 180.0) * PI;
let magic = Math.sin(radLat);
magic = 1 - GCJ_EE * magic * magic;
const sqrtMagic = Math.sqrt(magic);
dLat = (dLat * 180.0) / (((GCJ_A * (1 - GCJ_EE)) / (magic * sqrtMagic)) * PI);
dLng = (dLng * 180.0) / ((GCJ_A / sqrtMagic) * Math.cos(radLat) * PI);
return [lng + dLng, lat + dLat];
}
/** GCJ-02 → WGS-84(逆向,迭代 2 次足够收敛;境外原样返回)。 */
export function gcj02ToWgs84(lng: number, lat: number): [number, number] {
if (outOfChina(lng, lat)) return [lng, lat];
let wLng = lng;
let wLat = lat;
for (let i = 0; i < 2; i++) {
const [gLng, gLat] = wgs84ToGcj02(wLng, wLat);
wLng -= gLng - lng;
wLat -= gLat - lat;
}
return [wLng, wLat];
}
/**
* 海上合法走廊(offshore legal corridors)—— 纯几何解析与命中判定,无 IO。
*
* 这是「坐标落水 / 域外」的第二道防线:**第一道**用陆地掩膜把所有海上点标出来
* (见 offshoreVerdict),**这一道**再把其中「落在已知合法跨海构筑物上」的点豁免掉 ——
* 不让深中通道、深圳湾大桥、盐田港、大铲湾码头这类点混进「疑似漂移」清单里让导入人逐条复核。
* 距离阈值救不了它们(深中通道西人工岛离岸 6km、孖洲岛 2.3km,1000m 拐点只会把它们全判成远海),
* 必须按几何命中。
*
* 数据是一份离线 GeoJSON(Polygon / LineString / Point),走廊以 **WGS-84** 存储
* (与陆地掩膜同一套系)。命中判定与全项目米↔度换算同一套口径(等距圆柱近似)。
*
* 容灾:解析失败由调用方处理(`parseCorridors` 抛错),命中判定对 null 直接返回未命中,
* 退化成「只用陆地掩膜」,不会误杀也不会卡住。
*/
/** 1° 经线米数(与全项目米↔度换算同一口径) */
const M_PER_EQUATOR = 111_195;
/** 1° 纬线米数 */
const M_PER_DEG_LAT = 110_700;
import { pointInPolygon, type LngLat, type ShapePolygon } from './polygon';
/** 一条海上合法走廊:线(path)或面(polygon,用于岛/港区整体),外加缓冲半径 */
export interface CorridorFeature {
/** 可读名,写进报告给人审计(深中通道 / 盐田国际集装箱码头 …) */
name: string;
/** 缓冲半径(米):点到线 / 面边界 ≤ 此值即视为落在合法构筑物上 */
bufferM: number;
/** 折线集合,每条折线是一串 WGS-84 [lng,lat]。单点(Point)就是一条退化成点的折线 */
paths: LngLat[][];
/** 可选面(Polygon 的环数组),整片视为合法(岛 / 港区陆域)。点在面内或距边界 ≤ bufferM 即命中 */
polygon?: LngLat[][];
}
export interface CorridorMatch {
hit: boolean;
name: string;
}
/* ------------------------------- 解析 GeoJSON ------------------------------- */
/**
* 把离线 GeoJSON 解析成 CorridorFeature[]。
*
* 支持三种几何:LineString / MultiLineString(缓冲沿线)、Point(退化为单点 + 缓冲)、
* Polygon(整片合法,点在面内或距边界 ≤ bufferM)。每条 feature 用 properties.name 命名、
* properties.bufferM 覆盖默认缓冲(缺省 200m)。
*/
export function parseCorridors(raw: unknown): CorridorFeature[] {
const fc = raw as { type?: string; features?: unknown[] };
if (!fc || fc.type !== 'FeatureCollection' || !Array.isArray(fc.features)) {
throw new Error('走廊数据不是 FeatureCollection');
}
const out: CorridorFeature[] = [];
for (const f of fc.features) {
const feature = f as {
properties?: Record<string, unknown>;
geometry?: { type?: string; coordinates?: unknown };
};
const props = feature.properties ?? {};
const name = typeof props.name === 'string' && props.name ? props.name : '海上合法构筑物';
const bufferM = Number.isFinite(Number(props.bufferM)) ? Number(props.bufferM) : 200;
const geom = feature.geometry;
if (!geom || !geom.type || !Array.isArray(geom.coordinates)) continue;
const paths: LngLat[][] = [];
let polygon: LngLat[][] | undefined;
if (geom.type === 'LineString') {
paths.push(coordsToLngLat(geom.coordinates));
} else if (geom.type === 'MultiLineString') {
for (const line of geom.coordinates as unknown[]) paths.push(coordsToLngLat(line));
} else if (geom.type === 'Point') {
// Point 的 coordinates 是单个位置 [lng,lat](不是位置数组),单独处理
const c = geom.coordinates as unknown[];
if (Array.isArray(c) && c.length >= 2) {
const lng = Number(c[0]);
const lat = Number(c[1]);
if (Number.isFinite(lng) && Number.isFinite(lat)) paths.push([[lng, lat]]);
}
} else if (geom.type === 'Polygon') {
polygon = (geom.coordinates as unknown[]).map((ring) => coordsToLngLat(ring));
} else {
continue; // 其余类型(MultiPolygon 等)暂时不支持,跳过这条不影响其它
}
if (paths.length === 0 && !polygon) continue;
out.push({ name, bufferM, paths, polygon });
}
return out;
}
function coordsToLngLat(raw: unknown): LngLat[] {
if (!Array.isArray(raw)) return [];
const out: LngLat[] = [];
for (const pos of raw) {
if (!Array.isArray(pos) || pos.length < 2) continue;
const lng = Number(pos[0]);
const lat = Number(pos[1]);
if (!Number.isFinite(lng) || !Number.isFinite(lat)) continue;
out.push([lng, lat]);
}
return out;
}
/* ------------------------------- 命中判定 ------------------------------- */
/**
* 一个 WGS-84 点是否落在任一合法走廊内(含缓冲)。
*
* 距离用本地等距圆柱近似:把经纬度按「该点纬度」投影成米,再算点到折线 / 面边界的欧氏距离。
* 与全项目米↔度换算同一套口径。
*
* @param lng 已归一化到 WGS-84 的经度(案件点请先 gcj02ToWgs84)
* @param lat 已归一化到 WGS-84 的纬度
* @param corridors null 时(数据未就绪)直接返回未命中,交回上层按陆地掩膜处理
*/
export function pointInLegalCorridor(
lng: number,
lat: number,
corridors: CorridorFeature[] | null,
): CorridorMatch {
if (!corridors) return { hit: false, name: '' };
// 该点所在纬度下的经线米数(随纬度收缩)
const kx = M_PER_EQUATOR * Math.cos((lat * Math.PI) / 180);
const ky = M_PER_DEG_LAT;
const px = lng * kx;
const py = lat * ky;
for (const c of corridors) {
// 面:点在面内即命中(整片合法),否则看距边界多近
if (c.polygon) {
const poly: ShapePolygon = { rings: c.polygon };
if (pointInPolygon(lng, lat, poly)) return { hit: true, name: c.name };
if (distToPolygonBoundaryM(px, py, c.polygon, kx, ky) <= c.bufferM) {
return { hit: true, name: c.name };
}
}
// 线(含 Point 退化成的单点):距任一折线段 ≤ bufferM 即命中
for (const path of c.paths) {
if (distToPathM(px, py, path, kx, ky) <= c.bufferM) return { hit: true, name: c.name };
}
}
return { hit: false, name: '' };
}
/** 点到一条折线的距离(米),投影后逐段取最短 */
function distToPathM(
px: number,
py: number,
path: LngLat[],
kx: number,
ky: number,
): number {
if (path.length === 0 || !path[0]) return Infinity;
if (path.length === 1) {
const ax = path[0][0] * kx;
const ay = path[0][1] * ky;
return Math.hypot(px - ax, py - ay);
}
let best = Infinity;
for (let i = 1; i < path.length; i += 1) {
const ax = path[i - 1][0] * kx;
const ay = path[i - 1][1] * ky;
const bx = path[i][0] * kx;
const by = path[i][1] * ky;
const d = distToSegmentM(px, py, ax, ay, bx, by);
if (d < best) best = d;
}
return best;
}
/** 点到一个 Polygon(所有环的线段)的距离(米) */
function distToPolygonBoundaryM(
px: number,
py: number,
rings: LngLat[][],
kx: number,
ky: number,
): number {
let best = Infinity;
for (const ring of rings) {
const d = distToPathM(px, py, ring, kx, ky);
if (d < best) best = d;
}
return best;
}
/** 点到线段的最短距离(投影空间,米) */
function distToSegmentM(
px: number,
py: number,
ax: number,
ay: number,
bx: number,
by: number,
): number {
const dx = bx - ax;
const dy = by - ay;
const len2 = dx * dx + dy * dy;
let t = len2 > 0 ? ((px - ax) * dx + (py - ay) * dy) / len2 : 0;
if (t < 0) t = 0;
else if (t > 1) t = 1;
const cx = ax + t * dx;
const cy = ay + t * dy;
return Math.hypot(px - cx, py - cy);
}
/**
* 「坐标落没落在陆域上」—— 清洗用来抓海上 / 域外点的核心判据(纯几何,无 IO)。
*
* 与「辖区归属」(纯地址文本,见 classifyOffshore 的 C 类互补说明)是两套互补口径:
* - 辖区归属管「地址写明外市」(东莞市 / 凤岗镇),坐标不参与;
* - 这里管「地址写的是深圳、坐标却不在任何陆域多边形内」——
* 典型就是出险地址写着「大鹏新区大鹏街道」「南山区蛇口街道」(正确的深圳辖区名,C 类放行),
* 坐标却飘到了海上。
*
* ⚠️ 掩膜必须是**真正的陆地(海岸线)多边形**,不是行政区边界:
* AMap 行政区边界(shenzhen.geojson)会把沿海区的**水域**也划进区界,导致
* 「坐标在不在行政区多边形内」完全分不出海上点。所以调用方应优先喂陆地掩膜
* (shenzhen-land.geojson,Natural Earth 陆地裁剪),没有时才降级到行政区边界。
*
* @returns onLand 是否落在本陆域多边形内;distM 离最近陆界多少米
* (onLand 时为 0,offshore 时才算——那才是要交代给导入人的数)。
*/
import {
boundsOf,
distanceToBoundaryM,
pointInPolygon,
type LngLat,
type NamedPolys,
type ShapeBounds,
type ShapePolygon,
} from './polygon';
export function offshoreVerdict(
lng: number,
lat: number,
shapes: NamedPolys[],
): { onLand: boolean; distM: number; judged: boolean } {
const { polys, ob } = prepShapes(shapes);
// bbox 守卫:点落在掩膜覆盖区外时**无法判定** —— 既不判海上也不假装陆地,
// 交回上层「不标不剔」(旧版在这里按陆地处理,会漏判南边 22.25 以下、或掩膜换成只盖深圳后的海域)。
if (lng < ob.minLng || lng > ob.maxLng || lat < ob.minLat || lat > ob.maxLat) {
return { onLand: true, distM: 0, judged: false };
}
for (const { p, b } of polys) {
if (lng < b.minLng || lng > b.maxLng || lat < b.minLat || lat > b.maxLat) continue;
if (pointInPolygon(lng, lat, p)) return { onLand: true, distM: 0, judged: true };
}
// 落在所有陆块之外:算到最近陆界的距离,交给导入人判断(码头 / 跨海大桥等合法点会靠距离分辨)
const distM = distanceToBoundaryM(
lng,
lat,
polys.map((x) => x.p),
);
return { onLand: false, distM, judged: true };
}
/**
* 掩膜多边形按引用缓存:同一次导入 4 万多点共用同一份 `shapes`,逐点只做 bbox 预筛 +
* 一次射线法,不会把每个点都拿去和 28 块陆块逐边比。整体包围框用来做「覆盖区外即按陆地」的守卫。
*/
interface Prepped {
polys: Array<{ p: ShapePolygon; b: ShapeBounds }>;
ob: ShapeBounds;
}
let _cachedShapes: NamedPolys[] | null = null;
let _cachedPrep: Prepped | null = null;
function prepShapes(shapes: NamedPolys[]): Prepped {
if (_cachedShapes === shapes && _cachedPrep) return _cachedPrep;
const polys: Prepped['polys'] = [];
const ob: ShapeBounds = { minLng: Infinity, maxLng: -Infinity, minLat: Infinity, maxLat: -Infinity };
for (const s of shapes) {
for (const p of s.polys) {
const b = boundsOf([p]);
polys.push({ p, b });
if (b.minLng < ob.minLng) ob.minLng = b.minLng;
if (b.maxLng > ob.maxLng) ob.maxLng = b.maxLng;
if (b.minLat < ob.minLat) ob.minLat = b.minLat;
if (b.maxLat > ob.maxLat) ob.maxLat = b.maxLat;
}
}
_cachedShapes = shapes;
_cachedPrep = { polys, ob };
return _cachedPrep;
}
/* ------------------------------- 几何解析(无 IO) ------------------------------- */
/**
* 把区界 / 陆地掩膜 的 FeatureCollection 解析成 `NamedPolys[]`。
*
* 纯函数:不碰 fetch、不依赖字典匹配(那是主线程画区界时才有的事)。清洗跑在 Worker 里,
* 只关心「这个点在不在这一堆多边形里」,所以走这条入口。
* 解析几何这一段(`readFeatures` / `readPolygons` / `readRings`)与区界聚焦必须同一份 ——
* 尤其 MultiPolygon 按块分组那一条,漏了就是整块判不进去。
*/
export function parseDistrictGeometry(raw: unknown): NamedPolys[] {
const out: NamedPolys[] = [];
for (const feature of parseGeoFeatures(raw)) {
const name = typeof feature.name === 'string' ? feature.name.trim() : '';
const polys = parseGeometryPolys(feature.geometry);
if (!name || polys.length === 0) continue;
out.push({ name, polys, bbox: boundsOf(polys) });
}
return out;
}
/**
* 把 FeatureCollection 拆成「properties 平铺 + geometry」的记录数组。
*
* 单独导出是给**区界聚焦**(宿主主线程画区界)复用:那边除了几何还要 properties 里的
* adcode / centroid 来定位标签,不能只拿 `NamedPolys`。解码规则必须与清洗侧同一份 ——
* 尤其下面 `parseGeometryPolys` 的 MultiPolygon 按块分组那一条,漏了就是整块判不进去。
*/
export function parseGeoFeatures(raw: unknown): Array<Record<string, unknown>> {
const fc = raw as { type?: string; features?: unknown };
if (!fc || fc.type !== 'FeatureCollection' || !Array.isArray(fc.features)) {
throw new Error('区界数据不是 FeatureCollection');
}
const out: Array<Record<string, unknown>> = [];
for (const f of fc.features) {
const feature = f as { properties?: Record<string, unknown>; geometry?: unknown };
const props = feature.properties ?? {};
out.push({ ...props, geometry: feature.geometry });
}
return out;
}
/**
* Polygon 的 coordinates 是「环的数组」,MultiPolygon 是「多边形的数组」,这里统一成后者。
*
* ⚠️ 必须保留「块」的分组:龙岗区是 2 块,第二块就是大鹏半岛。把各块的环平铺成一条数组,
* 第二块的外环会被当成「洞」,整块判不进去 —— 这个坑踩过一次,第一版探针因此把大鹏半岛的
* 504 条案子全判成了域外。
*/
export function parseGeometryPolys(geometry: unknown): ShapePolygon[] {
const g = geometry as { type?: string; coordinates?: unknown } | undefined;
if (!g || (g.type !== 'Polygon' && g.type !== 'MultiPolygon') || !Array.isArray(g.coordinates)) {
return [];
}
const polys: ShapePolygon[] = [];
const lists: unknown[] = g.type === 'Polygon' ? [g.coordinates] : g.coordinates;
for (const ringsRaw of lists) {
const rings = readRings(ringsRaw);
if (rings.length > 0) polys.push({ rings });
}
return polys;
}
/** 环必须至少 4 个位置(三角形闭合后就是 4 个),坐标必须是有限数;不闭合的补上首点 */
function readRings(ringsRaw: unknown): LngLat[][] {
if (!Array.isArray(ringsRaw)) return [];
const rings: LngLat[][] = [];
for (const ringRaw of ringsRaw) {
if (!Array.isArray(ringRaw)) continue;
const pts: LngLat[] = [];
for (const pos of ringRaw) {
if (!Array.isArray(pos) || pos.length < 2) continue;
const lng = Number(pos[0]);
const lat = Number(pos[1]);
if (!Number.isFinite(lng) || !Number.isFinite(lat)) continue;
pts.push([lng, lat]);
}
if (pts.length < 3) continue;
const head = pts[0];
const tail = pts[pts.length - 1];
if (head[0] !== tail[0] || head[1] !== tail[1]) pts.push([head[0], head[1]]);
if (pts.length >= 4) rings.push(pts);
}
return rings;
}
/**
* 多边形几何的纯函数层:射线法命中判定 + 点到边界的距离。
*
* 判定只在这里写一遍,清洗内核与主线程的区界聚焦都从这里取 `pointInPolygon`,
* 否则会出现「清洗判它落在区外剔掉了,区界聚焦里点它又算区内」这种自己打自己的账。
*
* 坐标顺序与 GeoJSON 一致:[经度, 纬度]。
*
* 本文件自包含:米↔度换算常量在文件内联(不依赖任何外部包),使整包可被任意宿主直接复用。
*/
/** 1° 经线米数(与全项目米↔度换算同一口径) */
const M_PER_EQUATOR = 111_195;
/** 1° 纬线米数。等距圆柱近似,百米尺度上误差可忽略 */
export const M_PER_DEG_LAT = 110_700;
/** 一个经纬度点,顺序与 GeoJSON 一致:[经度, 纬度] */
export type LngLat = [number, number];
/** 一个多边形:第一条环是外沿,后面的环是洞 */
export interface ShapePolygon {
rings: LngLat[][];
}
/** 一块有名地界的几何描述:名字 + 它的全部块 + 并集外接框 */
export interface NamedPolys {
name: string;
polys: ShapePolygon[];
bbox: ShapeBounds;
}
/** 一组多边形的并集外接框 */
export interface ShapeBounds {
minLng: number;
maxLng: number;
minLat: number;
maxLat: number;
}
/**
* 射线法:从这一点往经度负方向发一条射线,数它穿过几次环,奇数次在里面。
*
* 边的取舍用「半开」判据(yi > lat 与 yj > lat 不同才参与),而不是判相交:
* 环的顶点正好落在射线高度上时,两条邻边里只有一条会被算进来,
* 否则同一个顶点会被数两遍,把界外的点算成界内 —— 清洗里就是把该留的案子剔掉了。
*/
export function pointInRing(lng: number, lat: number, ring: LngLat[]): boolean {
let inside = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
const [xi, yi] = ring[i];
const [xj, yj] = ring[j];
if (yi > lat === yj > lat) continue;
const t = (lat - yi) / (yj - yi);
if (lng < xi + t * (xj - xi)) inside = !inside;
}
return inside;
}
/** 一个多边形:在外环里、且不在任何一个洞里 */
export function pointInPolygon(lng: number, lat: number, poly: ShapePolygon): boolean {
const outer = poly.rings[0];
if (!outer || !pointInRing(lng, lat, outer)) return false;
for (let i = 1; i < poly.rings.length; i += 1) {
if (pointInRing(lng, lat, poly.rings[i])) return false;
}
return true;
}
/** 一组多边形里任何一个命中都算命中(一个区可能有多块:离岛与飞地) */
export function pointInPolygons(lng: number, lat: number, polys: ShapePolygon[]): boolean {
return polys.some((p) => pointInPolygon(lng, lat, p));
}
/** 每度经度在指定纬度上对应的米数 */
export function metersPerDegLng(lat: number): number {
return M_PER_EQUATOR * Math.cos((lat * Math.PI) / 180);
}
/** 点到一组多边形边界的最短距离(米) */
export function distanceToBoundaryM(lng: number, lat: number, polys: ShapePolygon[]): number {
const kx = metersPerDegLng(lat);
let best = Infinity;
for (const poly of polys) {
for (const ring of poly.rings) {
for (let i = 1; i < ring.length; i += 1) {
const [x0, y0] = ring[i - 1];
const [x1, y1] = ring[i];
const d = distToSegmentM(
(lng - x0) * kx,
(lat - y0) * M_PER_DEG_LAT,
(x1 - x0) * kx,
(y1 - y0) * M_PER_DEG_LAT,
);
if (d < best) best = d;
}
}
}
return best;
}
/** 点到线段的最短距离(米)。线段用「相对起点的米数」表示,避免大数相减丢精度 */
function distToSegmentM(
px: number,
py: number,
dx: number,
dy: number,
): number {
const len2 = dx * dx + dy * dy;
let t = len2 > 0 ? (px * dx + py * dy) / len2 : 0;
t = t < 0 ? 0 : t > 1 ? 1 : t;
const ex = px - t * dx;
const ey = py - t * dy;
return Math.sqrt(ex * ex + ey * ey);
}
/** 一组多边形的并集外接框 */
export function boundsOf(polys: ShapePolygon[]): ShapeBounds {
const b: ShapeBounds = { minLng: Infinity, maxLng: -Infinity, minLat: Infinity, maxLat: -Infinity };
for (const poly of polys) {
for (const ring of poly.rings) {
for (const [lng, lat] of ring) {
if (lng < b.minLng) b.minLng = lng;
if (lng > b.maxLng) b.maxLng = lng;
if (lat < b.minLat) b.minLat = lat;
if (lat > b.maxLat) b.maxLat = lat;
}
}
}
return b;
}
/**
* @hm/clean-core —— 出险数据清洗算法内核(可移植纯算法包)。
*
* 这个包不含任何 DOM / fetch / 全局状态 / 第三方依赖,因此同一个包既能跑在浏览器 Worker 里
* (实时导入解析),也能跑在 Node CLI 里(离线批量清洗)。宿主(heatmap app)与 B 阶段的
* `clean-adapters` / `clean-cli` 都从这里取算法。
*
* 包分层:
* - geo/* : 坐标系互转、多边形几何、落水判定、海上合法走廊(全是纯函数)
* - cleanRules : 8 类处置规则的核心判据(FLAG 位掩码 + 各 classify/mark*)
* - cleanRows : 编排入口(CleanRow[] → flags + classes + warnings),可移植套件的高层 API
* - dims : 道路名解析(roadOfAddress / buildRoadIndex)
* - types : 数据契约子集(CleanClassKey / CleanSample / CleanClass / UNRESOLVED_LABEL)
*/
/* 数据契约子集 */
export { UNRESOLVED_LABEL } from './types';
export type { CleanClassKey, CleanSample, CleanClass } from './types';
/* 坐标系互转 */
export { gcj02ToWgs84, wgs84ToGcj02, outOfChina } from './geo/coord';
/* 多边形几何 */
export {
pointInRing,
pointInPolygon,
pointInPolygons,
metersPerDegLng,
distanceToBoundaryM,
boundsOf,
} from './geo/polygon';
export type { LngLat, ShapePolygon, NamedPolys, ShapeBounds } from './geo/polygon';
/* 落水 / 域外几何 */
export {
offshoreVerdict,
parseDistrictGeometry,
parseGeoFeatures,
parseGeometryPolys,
} from './geo/offshoreVerdict';
export type { CorridorMatch } from './geo/corridors';
/* 海上合法走廊 */
export { parseCorridors, pointInLegalCorridor } from './geo/corridors';
export type { CorridorFeature } from './geo/corridors';
/* 道路解析 */
export { ROAD_UNRESOLVED, roadOfAddress, buildRoadIndex } from './dims';
/* 规则内核 */
export {
FLAG,
ISO_RADII,
ISO_FLAGS,
SPARSE_DEFAULT_THRESHOLD,
SPARSE_STREET_DEFAULT_THRESHOLD,
SPARSE_STREET_MIN,
SPARSE_STREET_MAX,
isStreetUnresolved,
streetNameOf,
SMALL_DEFAULT_RADIUS_M,
SMALL_DEFAULT_THRESHOLD,
SMALL_RADIUS_MAX,
SMALL_THRESHOLD_MAX,
OFFSHORE_FAR_DIST_M,
flagOfMissing,
missingDimLabels,
presentDimLabels,
classifyRegion,
classifyOffshore,
markIsolated,
markSparseRoads,
markSparseStreets,
markSmallClusters,
CLASS_DEFAULTS,
CLASS_INFO,
} from './cleanRules';
export type {
RegionVerdict,
SparseRoadInput,
SparseRoadResult,
SparseStreetInput,
SparseStreetResult,
SmallClusterInput,
SmallClusterResult,
} from './cleanRules';
/* 编排入口 */
export { cleanRows, loadLandMask, loadCorridors } from './cleanRows';
export type {
CleanRow,
CleanContext,
CleanThresholds,
CleanResult,
} from './cleanRows';
/**
* 清洗内核用到的数据契约子集(自包含,不依赖宿主的 aggregate/types)。
*
* 只放清洗算法真正需要的类型与常量,避免把整张数据契约(含聚合结果、Worker 消息等
* 一堆与「清洗」无关的东西)拉进纯算法包。宿主项目(heatmap)仍保留自己更全的
* `aggregate/types.ts`,两边同名类型结构一致、可互赋值。
*/
/**
* 地址里读不出区名 / 街道名时登记的占位名。街道字典项形如「宝安区|未识别」。
*
* 它不是一个地名,是「这条地址没写出这个名字」这件事的记号。凡把字典值念给使用者听
* (位置串、明细卡、抽屉标题、筛选选项、拼回去的地址)都先过清洗内核的判定,
* 直接念会出现「有一条叫未识别的街最危险」这种读法。
*/
export const UNRESOLVED_LABEL = '未识别';
/** 清洗类别键。位掩码的值见 cleanRules.FLAG,这里的键只用于报告分组 */
export type CleanClassKey =
| 'MISSING'
| 'MISSING_PARTIAL'
| 'OUTSIDE'
| 'OFFSHORE_NEAR'
| 'OFFSHORE_FAR'
| 'ISO_200'
| 'ISO_500'
| 'ISO_1000'
| 'SPARSE'
| 'SPARSE_STREET'
| 'SMALL';
/** 一条被分到某一类的记录,报告里点开就能看到它为什么落在这里 */
export interface CleanSample {
caseNo: string;
address: string;
lng: number;
lat: number;
/** 这一条的具体判据(距边界多少米、缺的是哪一档……) */
note: string;
}
/** 一类的处置结论 */
export interface CleanClass {
key: CleanClassKey;
label: string;
/** 判定依据,界面上逐字念给导入人看 */
reason: string;
count: number;
fixed: boolean;
defaultOn: boolean;
samples: CleanSample[];
}
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"types": []
},
"include": ["src"]
}
{
"name": "@hm/map-overlay",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "自绘地图图层内核(面向不旋转的 2D 墨卡托底图):每帧投影、画布出帧与跳过、尺寸与 backing store、手势减载标记、图层骨架。不含业务口径(配色、分格规则、数据契约)",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts"
},
"scripts": {
"typecheck": "tsc --noEmit"
}
}
/**
* 墨卡托投影里的三个常数。
*
* 为什么要单列:图层要的是「这一度经度在这屏上占多少像素」,米制栅格要的是「一米在屏幕上占多少像素」,
* 两边必须同源,否则会出现「圆盘按一个尺度长、方格按另一个尺度画」那种对不上的画面。
* 内核只留这三条纯几何常数;配色、分格边长、标签档位是业务口径,不进来。
*
* 用的是**球形**墨卡托(2D 瓦片底图的通行口径:AMap 2D、MapLibre、Leaflet 的 EPSG:3857 都是这一套):
* 纬度只用 tan(π/4+φ/2) 那一支积分式换算,不带椭球修正。与椭球口径之差在 0.3% 一档,
* 对屏幕上的方格与几十米的圆盘都读不出来;换底图时只要它也是球形墨卡托,数就还是同一套。
*/
/** 赤道上 1° 经线对应的米数(与下面 M_PER_DEG_LAT 同一条口径) */
export const M_PER_EQUATOR = 111_195;
/**
* 1° 纬线对应的米数。取常数而不是随纬度变:
* 分格边长要在 Worker 里算、在屏幕上画,两头都得是同一个数。
*/
export const M_PER_DEG_LAT = 110_700;
/**
* 一级缩放下的世界宽度(CSS 像素)。每升一级翻一倍。
*
* ⚠️ 这是**底图给定的常数**,不是可选参数:内核的一切屏幕换算都按它折半/翻倍,
* 而「点一定落在某个 48px 方格里」这件事只有在这个数与底图一致时才成立。
* AMap / MapLibre / Leaflet 的栅格瓦片默认都是 256。
*/
export const TILE_SIZE = 256;
import { M_PER_EQUATOR, TILE_SIZE } from './constants';
/**
* 内核向底图要的四件事。
*
* AMap.Map 结构上就满足这个形状(不要求它 implements 什么)。换 MapLibre / Leaflet 时
* 只要写一个同样形状的适配器 —— 这四下调用是全内核唯一碰底图对象的地方。
*
* ⚠️ 前提是 2D、不旋转、不倾斜:`getZoom()` 要能在动画途中给小数(帧判定要用它),
* `lngLatToContainer` 要按容器像素返回。旋转或倾斜之后屏幕坐标不再是经纬度的这个函数,
* 每帧两次乘加的那套换算就不成立了(见 Frame 的注释)。
*/
export interface OverlayMap {
getSize(): { width: number; height: number };
getCenter(): { getLng(): number; getLat(): number };
/** 当前缩放级别(动画途中是小数) */
getZoom(): number;
/** 经纬度 → 容器像素。每帧只准问一次中心点,见 Frame.set */
lngLatToContainer(lnglat: [number, number]): { x: number; y: number };
}
/** 屏幕换算的比例尺口径 */
export interface FrameScale {
/** 一级缩放的世界宽度(CSS 像素),见 constants 里 TILE_SIZE 那段 */
tileSize: number;
/** 米 → 像素的参考纬度:底图覆盖的城市中心纬度 */
referenceLat: number;
}
/** 深圳纬度。业务层要改参考纬度就自己传一份 FrameScale */
export const DEFAULT_SCALE: FrameScale = { tileSize: TILE_SIZE, referenceLat: 22.5 };
/**
* 墨卡托纬度:tan(π/4 + φ/2) 的自然对数。
*
* 存这个数而不是存像素,是因为它与缩放无关 —— 喂一次数据算一次,缩放时只需换比例尺。
* 纬度截到 ±85°,与墨卡托 Web 瓦片的可用区间一致(超出会趋向无穷)。
*/
export function mercY(latDeg: number): number {
const phi = (Math.max(-85, Math.min(85, latDeg)) * Math.PI) / 180;
return Math.log(Math.tan(Math.PI / 4 + phi / 2));
}
/** 这一级缩放下的世界宽度(CSS 像素):每升一级翻一倍 */
export function worldPx(zoom: number, tileSize: number = TILE_SIZE): number {
return tileSize * Math.pow(2, zoom);
}
/** 这一级缩放下每度经度占多少 CSS 像素(格子的边长、点之间的屏距都从它推) */
export function pxPerDegLng(zoom: number, tileSize: number = TILE_SIZE): number {
return worldPx(zoom, tileSize) / 360;
}
/**
* 一帧的投影基准。
*
* 为什么要有这一层 —— 投影如果逐点问底图(每点一次 `lngLatToContainer`),一帧几百到两千次调用
* 就是几百到两千次「造 LngLat、投影、返回新对象」的分配。拖动时这项是逐帧付的钱,空闲时也在付
* (底图每帧回调覆盖物),于是「地图拖着拖着就越来越沉」。
*
* 改法是把投影拆成「一次换算 + 每帧两次乘加」:
* 墨卡托下屏幕位置只由 (缩放, 中心) 决定,
* x = 中心像素x + (经度 − 中心经度) × 每度像素,
* y = 中心像素y + (中心的那一支墨卡托纬度 − 这一点的) × 每像素纬度因子。
* 每一点的纬度因子(mercY)与缩放无关,所以喂数据时算好存下来,每帧只剩减法和乘法。
*
* ⚠️ 中心那一点的位置仍然向底图问一次(每帧一次,不是每点一次):这样原点由底图自己说,
* 而不是我们假设它在画布正中。地图带偏移、容器尺寸与 getSize() 不一致时,
* 画出来的东西不会整屏错位。
*/
export class Frame {
/** 缩放级别(动画途中是小数) */
zoom = 0;
/** 每度经度的像素 */
pxPerDegLng = 0;
/** 米 → 屏幕像素(按参考纬度:圆盘半径、方格边长这些米制口径都换它) */
pxPerMeter = 0;
private originX = 0;
private originY = 0;
private centerLng = 0;
private centerMercY = 0;
private pxPerMercY = 0;
set(
map: OverlayMap,
zoom: number,
centerLng: number,
centerLat: number,
scale: FrameScale,
): void {
this.zoom = zoom;
this.centerLng = centerLng;
this.centerMercY = mercY(centerLat);
const world = worldPx(zoom, scale.tileSize);
this.pxPerDegLng = world / 360;
this.pxPerMercY = world / (2 * Math.PI);
this.pxPerMeter =
this.pxPerDegLng / (M_PER_EQUATOR * Math.cos((scale.referenceLat * Math.PI) / 180));
// 每帧唯一的一次投影调用:把原点交给底图本身
const p = map.lngLatToContainer([centerLng, centerLat]);
this.originX = p.x;
this.originY = p.y;
}
/** 经度 → 屏幕 x */
x(lng: number): number {
return this.originX + (lng - this.centerLng) * this.pxPerDegLng;
}
/** mercY(纬度) → 屏幕 y。纬度值请在喂数据时用 mercY() 算好存下来 */
y(mercLatitude: number): number {
return this.originY + (this.centerMercY - mercLatitude) * this.pxPerMercY;
}
}
/**
* 量一段文字在画布上占多少像素。
*
* 用的是一块专门的量字画布(64×64,只建一次),不是各层自己那块绘制画布:
* 底衬半径要在喂数据时算好,而那一趟常常发生在绘制画布还没尺寸的时候(层刚建、
* 或收起后交还过 backing store)。拿 0×0 的画布去 measureText 是「也许还给宽度」的灰区,
* 量不到就只能按字数估,表现是底衬集体缩到最小一档 —— 一类没人会去查的视觉退化。
*
* 返回 null 表示量不了(无 canvas 的环境,例如测试里的 jsdom),调用方自备估算值。
*/
let measurer: CanvasRenderingContext2D | null = null;
let measurerTried = false;
export function textWidth(font: string, text: string): number | null {
if (!measurerTried) {
measurerTried = true;
const canvas = document.createElement('canvas');
canvas.width = 64;
canvas.height = 64;
measurer = canvas.getContext('2d');
}
if (!measurer) return null;
measurer.font = font;
return measurer.measureText(text).width;
}
/**
* 地图手势(拖动 / 缩放进行中)的状态。
*
* 为什么是宿主持有的一份状态,而不是包里的模块级布尔:这份标记的读者是各层的 `draw()`,
* 它们由底图的每帧回调驱动,跟界面框架没有任何关系。但「一个页面两块地图」是真实存在的
* (主图 + 缩略图),全局状态会让两块地图的减载互相误伤。所以内核只提供状态本身,
* 一份实例配一张地图;谁写、谁读由宿主接起来。
*
* 两个标记各管一头:
* - `active`:地图正在动(手按着、惯性滑行、缩放动画途中)。
* - `fast`:**这一趟手势已定档为快拖**(判据见 viewPos 的 `viewShiftPx` / `FAST_MOVE_PX`,
* 定档的取舍见下面 `set`)。简笔帧与「快拖时整层摘掉」都只跟这一条走。
*
* ⚠️ `fast` 由宿主按帧定,而且是**单调的**:连续几帧挪过门限就置上,之后一趟里不再翻回去,
* 只有收尾(真的停下)才清。为什么不能逐帧翻档 —— 同一个拖动动作量出来的每帧位移本来就在
* 门限上下抖(6px、14px、5px、12px),翻一次档屏上的数字就闪一下,减载本身成了闪源。
* 另外,事件一来只把位移**累加**起来、到 rAF 那一拍才比门限(底图一帧之内可能连发好几个
* drag / mapmove,按事件各比一次会把一帧的位移拆成几小段,于是「明明甩得很快却判成不快」)。
* 这样各层读到的也是同一个数 —— 不会出现这一层简笔、那一层全量的一帧内分裂。
*
* 写的人只有一个:宿主绑的地图事件(dragstart / zoomstart 开,moveend / zoomend 关)。
* 读的人在帧里现读,不订阅、不回调解耦 —— 帧本来就是「此刻地图在不在动」的最新现场。
*
* ⚠️ 关闭时必须让各层重画一帧(宿主收尾那句 invalidate):手势期画的是简笔帧,
* 而松手那一下地图往往正好停在最后一帧的位置上,CanvasSurface.begin 会判「视图没变」
* 整帧跳过 —— 于是屏上永远留着没有数字的那一帧。这不是理论情况,惯性滑动收尾就是它。
*/
export interface GestureState {
/** 地图此刻在不在动(拖动 / 缩放 / 惯性滑行途中) */
active(): boolean;
/**
* 这一帧该不该减载(简笔、或整层摘掉)。
*
* 判据是「在动 **且** 这一趟已定档为快拖」两条一起:慢速拖动是用户在挪图找位置,
* 那一屏的数字与圆圈要留着,否则「拖一下什么都没了」会被读成数据丢了。
* 一旦定档,这一趟里每一帧都算减载帧 —— 包括后来慢下来的那几帧,闪就只闪这一次切换。
*/
light(): boolean;
/** 开 / 关这一趟手势。`movedFast` 只在 on 为真时有意义 */
set(on: boolean, movedFast?: boolean): void;
}
export function createGestureState(): GestureState {
let active = false;
let fast = false;
return {
active: () => active,
light: () => active && fast,
set: (on, movedFast = false) => {
active = on;
fast = on && movedFast;
},
};
}
import { TILE_SIZE } from './constants';
import { pxPerDegLng } from './frame';
/**
* 屏幕锁定的分格几何:格子边长用**屏幕像素**定义,再按当前缩放换算成经纬度。
*
* 为什么要按屏幕定义而不是按米定义:
* Web 墨卡托下「一度经度占多少像素」只随缩放翻倍(`pxPerDegLng`),
* 而「一度纬度占多少像素」在同一缩放处还要除以 cos(纬度) —— 纬度越高,同一度数被拉得越长。
* 于是 `gridPx ÷ 每度像素` 出来的那一格,在屏幕上任何缩放、任何纬度都近似是个固定像素的正方形。
* 换成按米定义(比如"200 米一格"),高纬度处的格子在屏幕上会明显变扁,
* 缩放一变疏密就跳,读图的人看到的"一片密"到底是数据密还是格子粗 —— 分不开了。
*
* ⚠️ 这里的换算必须与 `Frame` 那一套同源(同一个 `tileSize`、同一支墨卡托纬度)。
* 两边不一致会出现「格子按一个尺度算、点按另一个尺度画」,表现为点集体偏离格心。
*
* ⚠️ 分格与命中判定的边界归属:`floor` 的半开区间,边界上的点归右/上那一格,
* 相邻两格不重复计。同一条表达式在分桶和命中两处用(见 `cellAt`),
* 这是「屏幕上那个圈写着 336、点进去就一定是 336 行」的根据。
*/
/** 一个点的位置(真实经纬度,度数)。分桶与命中都用这个形状 */
export interface GeoPoint {
lng: number;
lat: number;
}
/** 一格的经纬度边长(度) */
export interface GridCell {
dLng: number;
dLat: number;
}
/**
* 一度纬度在这一缩放下占多少屏幕像素。
*
* 墨卡托纬度对纬度的导数是 sec(φ),所以它就是「每度经度像素 ÷ cos(φ)」——
* 与 `Frame` 里 `pxPerDegLng × pxPerMercY` 那一路是同一个结论,不是另一套近似。
* 纬度截到 ±85°,与 `mercY` 同一口径。
*/
export function pxPerDegLat(zoom: number, latDeg: number, tileSize: number = TILE_SIZE): number {
const lat = Math.max(-85, Math.min(85, latDeg));
return pxPerDegLng(zoom, tileSize) / Math.cos((lat * Math.PI) / 180);
}
/** 给定「屏幕上的格子边长(CSS 像素)」与视图,算出这一格的经纬度边长 */
export function cellAtZoom(
zoom: number,
gridPx: number,
latDeg: number,
tileSize: number = TILE_SIZE,
): GridCell {
return {
dLng: gridPx / pxPerDegLng(zoom, tileSize),
dLat: gridPx / pxPerDegLat(zoom, latDeg, tileSize),
};
}
/** 一格的屏幕直径(CSS 像素):画这一格的方框、判断它在不在屏幕上都用它 */
export function cellWidthPx(zoom: number, cell: GridCell, tileSize: number = TILE_SIZE): number {
return cell.dLng * pxPerDegLng(zoom, tileSize);
}
/**
* 格子编号 → 单值 key。
*
* 经度方向用 2^21 作进制(而不是字符串拼接):一次乘法加一次加法,
* 分几十万点时这点差别会显现出来。
* 越界条件是 gy ≥ 2^21,即 dLat < 180/2^21 ≈ 8.6e-5 度(约 9.5 米)——
* 屏幕格子的边长不会细到那一档(z18 上 24px 的格子 dLat ≈ 1.4e-4,还有两个数量级余量)。
*/
export const KEY_SHIFT = 2097152;
export function cellKey(gx: number, gy: number): number {
return gx * KEY_SHIFT + gy;
}
/**
* 点落在哪一格:`floor((经度 + 180) / dLng)`,商就是格子编号,不需要知道格子边界在哪。
*
* ⚠️ 这一步的输入必须是**底图自己给的那个经纬度**(`map.containerToLngLat` 的结果),
* 内核不做屏幕 → 经纬度的反算:反算一旦另写一套,边界上的点就会在两套换算里归给隔壁格,
* 于是「圆圈 336、清单 337」,两个数并排摆在同一屏上,读起来是统计错了。
*/
export function cellAt(pos: GeoPoint, cell: GridCell): { gx: number; gy: number } {
return {
gx: Math.floor((pos.lng + 180) / cell.dLng),
gy: Math.floor((pos.lat + 90) / cell.dLat),
};
}
/** 并列的两列点(度)。类型数组和普通数组都能进来 */
export interface PointColumns {
lng: ArrayLike<number>;
lat: ArrayLike<number>;
}
/** 分桶结果:与输入一样是并列列,长度 = 桶数 */
export interface BucketColumns {
/** 桶中心(度) */
lng: Float64Array;
lat: Float64Array;
/** 桶里的点数 */
count: Int32Array;
gx: Int32Array;
gy: Int32Array;
/** 最大的那一桶有多少点。深浅档位的常用分母 */
maxCount: number;
}
/**
* 把一批点按格子收成桶:单次遍历,每桶中心取成员点的均值。
*
* 为什么是均值而不是格子几何中心:点在一格里极少均匀分布,均值让圆圈落在真实重心上,
* 视觉上贴得住密集成片的那一头;用格心则会出现「一片点挤在格子左下角、数字却写在格心」。
*
* 这是纯计算:要处理几十万点就把它搬进 Worker(这里不碰 DOM),
* 或先按视口过滤再进来 —— 屏幕上只需要那几百个桶。
*
* ⚠️ 分格口径与 `cellAt` 同一条表达式。改一处必须改两处,否则命中判定与统计会给出不同的答案。
*/
export function bucketize(points: PointColumns, cell: GridCell): BucketColumns {
const n = points.lng.length;
const keyToIdx = new Map<number, number>();
const lng: number[] = [];
const lat: number[] = [];
const count: number[] = [];
const gx: number[] = [];
const gy: number[] = [];
const invLng = 1 / cell.dLng;
const invLat = 1 / cell.dLat;
let maxCount = 0;
for (let i = 0; i < n; i += 1) {
const x = points.lng[i];
const y = points.lat[i];
// 与 cellAt 同一句 floor:+180/+90 把定义域挪到非负,负数取整才不会偏一格
const cx = Math.floor((x + 180) * invLng);
const cy = Math.floor((y + 90) * invLat);
const key = cellKey(cx, cy);
let idx = keyToIdx.get(key);
if (idx === undefined) {
idx = lng.length;
keyToIdx.set(key, idx);
lng.push(x);
lat.push(y);
count.push(1);
gx.push(cx);
gy.push(cy);
if (maxCount < 1) maxCount = 1;
} else {
lng[idx] += x;
lat[idx] += y;
const c = count[idx] + 1;
count[idx] = c;
if (c > maxCount) maxCount = c;
}
}
const out = lng.length;
const centerLng = new Float64Array(out);
const centerLat = new Float64Array(out);
const counts = new Int32Array(out);
const cellGx = new Int32Array(out);
const cellGy = new Int32Array(out);
for (let i = 0; i < out; i += 1) {
centerLng[i] = lng[i] / count[i];
centerLat[i] = lat[i] / count[i];
counts[i] = count[i];
cellGx[i] = gx[i];
cellGy[i] = gy[i];
}
return { lng: centerLng, lat: centerLat, count: counts, gx: cellGx, gy: cellGy, maxCount };
}
/**
* 屏幕上的命中检测:以**画出来的那一笔**为准,比屏幕距离。
*
* 为什么只做距离判定:屏幕上那个圆/那块牌子的外沿就是用户看到的可点范围,
* 按形状外沿判才和直觉一致;而"这一格有几个"是另一路(见 grid.ts 的 `cellAt`),
* 两路各有各的用途,都要说清用的是哪一种。
*
* ⚠️ 屏幕坐标 → 经纬度这一步不在内核里做。它必须与喂进来统计的那一路同源
* (底图自己给的 `map.containerToLngLat`),内核要是另写一套反投影,边界上的点就会在
* 两套换算里归给隔壁格 —— 于是"圆圈 336、清单 337",这两个数并排摆在同一屏上,
* 读起来就是统计错了。调用方把反算结果交给 `cellAt` 即可。
*
* ⚠️ 三列坐标(`sx/sy/r`)由绘制那一帧顺手填,点击时只比距离、不再投影一遍。
* 减载帧也要填:摘掉的是画笔,不是命中缓存,否则松手那一下的点击会指着上一帧的过期坐标。
* `r` 归零即"这一笔不可点"(被压住让位、或裁到屏幕外)。
*/
/** 屏幕上画出来的那些形状:中心 + 半径。长度一致,下标一一对应 */
export interface ScreenColumns {
sx: ArrayLike<number>;
sy: ArrayLike<number>;
r: ArrayLike<number>;
}
export interface RadiusHitOptions {
/** 半径之外再放的余量(像素):外沿还挂着牌子时,得连牌子一起可点 */
pad?: number;
/**
* 每个形状自己的量(通常是案量)。给了就"压住同一点时取量最大的那个"——
* 大圆压小圆符合直觉;不给则取屏幕距离最近的那个。
*/
weight?: ArrayLike<number>;
/**
* 这一笔算不算命中这个形状。`d2` 是到中心的距离平方,`r` 是半径。
* 例如"小盘只认环带和盘心、大盘整个都认"这类规则:整个盘都认的话,
* 密集处十几个盘会把点击全吃掉,底下的东西再也点不开。
*/
accept?: (d2: number, r: number) => boolean;
}
/** 命中的下标,未命中 -1 */
export function hitByRadius(
cols: ScreenColumns,
x: number,
y: number,
opts: RadiusHitOptions = {},
): number {
const pad = opts.pad ?? 0;
const weight = opts.weight;
let best = -1;
let bestD2 = Number.POSITIVE_INFINITY;
let bestW = Number.NEGATIVE_INFINITY;
for (let i = 0; i < cols.r.length; i += 1) {
const r = cols.r[i];
if (r <= 0) continue;
const dx = x - cols.sx[i];
const dy = y - cols.sy[i];
const d2 = dx * dx + dy * dy;
const reach = r + pad;
if (d2 > reach * reach) continue;
if (opts.accept && !opts.accept(d2, r)) continue;
if (weight) {
// 先比量(大圆压小圆符合直觉),同量再比屏幕距离 —— 直接把两个量加权成一个数
// 会在 MAX_SAFE_INTEGER 那一档丢精度,同量的两个形状谁赢就不稳定
const w = weight[i];
if (best < 0 || w > bestW || (w === bestW && d2 < bestD2)) {
bestW = w;
bestD2 = d2;
best = i;
}
} else if (d2 < bestD2) {
bestD2 = d2;
best = i;
}
}
return best;
}
/**
* `@hm/map-overlay` —— 自绘地图图层内核。
*
* 面向**不旋转、不倾斜的 2D 墨卡托底图**:整套屏幕换算按这一条前提写(见 frame.ts),
* 换底图时只要它也是球形墨卡托(AMap 2D / MapLibre / Leaflet 的 EPSG:3857),数就还是同一套。
*
* 内核里只有四件事:投影与出帧(frame / surface / overlay)、手势减载的标记(gesture / viewPos)、
* 与屏幕无关的绘制小件(text / plate / hit / grid)、以及一个传数据就能用的示例层(layers/buckets)。
* 配色、分格粗细的业务口径、数据契约、显著性与热点分析都不在这里 —— 那些换个项目就要改,
* 而上面那四件事换项目也不改。
*
* 最小用法:
* ```ts
* import { createBucketsLayer, bucketize, cellAtZoom } from '@hm/map-overlay';
*
* const cell = cellAtZoom(map.getZoom(), 48, centerLat);
* const buckets = bucketize(points, cell); // 或直接喂自己算好的桶
* const layer = createBucketsLayer(map, {
* zIndex: 130,
* scale: { tileSize: 256, referenceLat: 22.5 },
* gesture, // 可选:给了才有快拖减载
* style: { font: 'bold 11px sans-serif', ink: '#222B5F', plate: 'rgba(255,255,255,.4)' },
* });
* layer.setData(buckets);
* ```
*
* 要自己定义图层就只用骨架那一层:`defineOverlay(map, { canPaint, paint })` ——
* 内核负责建画布、挂图、出帧、跳过、收起交还,层里只留「这一帧画什么、画了几笔」。
*/
export * from './constants';
export * from './frame';
export * from './grid';
export * from './hit';
export * from './plate';
export * from './text';
export * from './viewPos';
export { CanvasSurface, type SurfaceOptions, type SurfaceReadout } from './surface';
export {
defineOverlay,
type DefineOverlay,
type Overlay,
type OverlayLayerLike,
type OverlayRuntime,
type OverlaySpec,
type PaintEnv,
} from './overlay';
export { createGestureState, type GestureState } from './gesture';
export {
createBucketsLayer,
type BucketsData,
type BucketsHit,
type BucketsLayer,
type BucketsOptions,
type BucketsStyle,
} from './layers/buckets';
import { ellipsizeBy } from './text';
/**
* 圆角牌子:底衬 + 一行居中的字。
*
* 为什么内核要带这一块:聚合数字、黑点排名牌、定位标记的地址牌、聚焦展示的档位牌共用同一种长相,
* 原先这几处在三个文件里各写了一份圆角路径、两份截断,而「同一个位置只有一种长相」正是这类界面
* 一直在守的东西 —— 少一处各写一遍,就多一处「同屏出现两种牌子」的口子。
*
* 尺寸与文字(`fitPlate`)和落笔(`drawPlate`)分两步:一次截断要逐字量一遍,
* 而字宽只由「字体 + 文字本身」决定,跟缩放、屏幕都无关,所以能在喂数据时算完就不该在帧里算。
*/
/** 量字。用专门的量字画布(见 frame.ts 的 textWidth),别用正在画的这块 */
export type TextMeasurer = (font: string, text: string) => number;
/** 一块牌子的文字与外框:算一次,沿用到底 */
export interface PlateLayout {
text: string;
w: number;
}
/** 牌子的长相。颜色都是画布上真实存在的 CSS 色串,不在这里解析 hex */
export interface PlateStyle {
font: string;
/** 底衬色 */
fill: string;
/** 描边色。不给就不描 */
stroke?: string;
lineWidth?: number;
/** 字色 */
ink: string;
/** 牌子高(CSS 像素) */
height: number;
/** 圆角半径 */
radius?: number;
}
/**
* 圆角矩形路径。调用方自己 fill / stroke,所以这里只建路径、不落笔。
*
* 用 arcTo 而不是 ctx.roundRect:后者在部分浏览器/WebView 上还没有,
* 自绘层拿不到报错、只会看到牌子变成直角,那种差异没人会去查。
*/
export function roundRectPath(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
w: number,
h: number,
r: number,
): void {
const rr = Math.min(r, w / 2, h / 2);
ctx.beginPath();
ctx.moveTo(x + rr, y);
ctx.arcTo(x + w, y, x + w, y + h, rr);
ctx.arcTo(x + w, y + h, x, y + h, rr);
ctx.arcTo(x, y + h, x, y, rr);
ctx.arcTo(x, y, x + w, y, rr);
ctx.closePath();
}
/**
* 算出这块牌子上那一行字与它的宽度。
*
* `maxTextW` 是文字宽度上限:超出就截断加省略号。上限同时也按画布宽度收过再传进来 ——
* 小窗口里牌子不该横穿整屏。
*/
export function fitPlate(
measure: TextMeasurer,
text: string,
maxTextW: number,
font: string,
padX: number,
): PlateLayout {
const shown = ellipsizeBy((t) => measure(font, t), text, maxTextW);
return { text: shown, w: Math.min(maxTextW + padX * 2, measure(font, shown) + padX * 2) };
}
/**
* 落一块牌子:按中心点摆,贴屏幕边时整块收进来。
*
* 不收的话用户会看到「有个标记但牌子跑出去了」;收完要把真正占住的那块报回去,
* 局部擦除的范围才按得上(照理论位置取会擦不干净,留下一条边)。
*
* @param bounds 画布的 CSS 尺寸。给了才做贴边收拢
* @param inset 离画布边缘的最小间距,默认 4
*/
export function drawPlate(
ctx: CanvasRenderingContext2D,
plate: PlateLayout,
cx: number,
cy: number,
style: PlateStyle,
bounds?: { width: number; height: number },
inset = 4,
): { left: number; top: number; w: number; h: number } {
const w = plate.w;
const h = style.height;
let left = cx - w / 2;
let top = cy - h / 2;
if (bounds) {
left = Math.max(inset, Math.min(left, bounds.width - w - inset));
top = Math.max(inset, Math.min(top, bounds.height - h - inset));
}
roundRectPath(ctx, left, top, w, h, style.radius ?? 5);
ctx.fillStyle = style.fill;
ctx.fill();
if (style.stroke) {
ctx.lineWidth = style.lineWidth ?? 1;
ctx.strokeStyle = style.stroke;
ctx.stroke();
}
ctx.font = style.font;
ctx.fillStyle = style.ink;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(plate.text, left + w / 2, top + h / 2 + 0.5);
return { left, top, w, h };
}
/**
* 屏幕上那一串文字的两个通用件:按缩放选字号档、按像素截断。
*
* 「读得出」这件事有两个来源,一个是字号,一个是缩放 —— 同一个数在屏幕上占多少像素,
* 由「字号 px」与「这一级缩放下多少像素代表一度」共同决定。数字要是只在「格子够宽」时
* 出现、字体却永远 11px,那么拖到远景时它挤成一团,拖到近景时又小得没必要。
*
* 内核只留这两件事。具体几档、阈值取哪儿、用哪支字体是样式口径,由宿主传进来。
*/
/**
* 按缩放选字号档位:`levels` 是升序的缩放阈值,返回「zoom ≥ 最后一档不超过它的」下标。
*
* 空数组给 0(只有一档的层不必特判)。
*/
export function fontLevelIndex(zoom: number, levels: readonly number[]): number {
let idx = 0;
for (let i = 0; i < levels.length; i += 1) {
if (zoom >= levels[i]) idx = i;
}
return idx;
}
/**
* 按像素宽度截断文字并加省略号。
*
* 从后往前一个字一个字地退,而不是按字数切:中文地址里既有汉字也有数字和字母,
* 按字数切会在同样宽度下截出长短不一的两截,牌子看着就在抖。
*
* `measure` 由调用方给:可以在喂数据时用专门的量字画布先量一遍(见 frame.ts 的 textWidth),
* 不必每帧现算 —— 一次截断要把每个前缀都量一遍,几十个字就是几十次 measureText,
* 而画布上的字宽只与字体和文字本身有关(跟缩放、屏幕都无关)。
* 画布拿不到时(无 canvas 的环境)传一个按字数估的函数,截出来的牌子只是长短略有差别。
*/
export function ellipsizeBy(measure: (text: string) => number, text: string, maxW: number): string {
if (maxW <= 0 || measure(text) <= maxW) return text;
const dots = '…';
const dotsW = measure(dots);
let end = text.length;
while (end > 1 && measure(text.slice(0, end)) + dotsW > maxW) end -= 1;
return `${text.slice(0, end)}${dots}`;
}
/** 同一件事的「拿画布量」版本 */
export function ellipsize(ctx: CanvasRenderingContext2D, text: string, maxW: number): string {
return ellipsizeBy((t) => ctx.measureText(t).width, text, maxW);
}
import { TILE_SIZE } from './constants';
import { mercY, worldPx, type OverlayMap } from './frame';
/** 一次视图读数:缩放 + 中心。判断「这一帧挪得多快」只要这三个数 */
export interface ViewPos {
zoom: number;
lng: number;
lat: number;
}
/** 读一次当前视图位置。每帧一次就够(见 viewShiftPx 里那段按事件量的坑) */
export function viewPos(map: OverlayMap): ViewPos {
const c = map.getCenter();
return { zoom: map.getZoom(), lng: c.getLng(), lat: c.getLat() };
}
/**
* 两个视图读数之间挪了多少屏幕像素(缩放一变就直接算「无穷大」)。
*
* 手势期减载(快拖时简笔、甚至整层摘掉)省下的是这一层最贵的那几笔,代价却是那一段屏幕上读不到数 ——
* 慢速拖动本来就不卡,把数字一起抹掉属于「用不上的省法」,读图还被打断。
* 所以判据不是「手按住没有」,而是「这一帧真的挪了不少」:
* 60 帧一秒下 8 CSS px/帧约合 480px/s,比这个慢的拖动都站得稳读数(门限见 FAST_MOVE_PX)。
* 缩放另算:缩放级别一动就一律按快处理(缩放帧的绘制量随半径平方涨,不是线性那一档)。
*
* ⚠️ 这一支换算与 Frame 用的是同一套(每度经度、每单位墨卡托纬度各占多少屏幕像素),
* 两边不一致就会出现「格子跟着走、判据却不认」那种对不上的减载。
*
* ⚠️ 调用方必须**按帧**累计再比门限,不能按事件比:底图一帧里可能连发好几个 drag / mapmove,
* 按事件量会把一帧的位移拆成几小段,于是「明明甩得很快却判成不快」(减载整个失效)。
* 起点没有参照(`prev.zoom` 为 NaN)时给 0 —— 首屏、以及刚按下那一下都不该判成快。
*/
export function viewShiftPx(next: ViewPos, prev: ViewPos, tileSize: number = TILE_SIZE): number {
if (Number.isNaN(prev.zoom)) return 0;
if (next.zoom !== prev.zoom) return Infinity;
const world = worldPx(next.zoom, tileSize);
const dLngPx = Math.abs(next.lng - prev.lng) * (world / 360);
const dMercPx = Math.abs(mercY(next.lat) - mercY(prev.lat)) * (world / (2 * Math.PI));
return Math.hypot(dLngPx, dMercPx);
}
/**
* `viewShiftPx` 的门限:一帧挪过这么多 CSS 像素才算快。
*
* ⚠️ 这里只回答「这一帧快不快」,不回答「该不该减载」—— 后者由宿主定档:
* 要连续两帧过门限才进入,进入之后整趟保持,直到真的停下。单帧一比会闪,
* 加一段退出时长也照样闪(人手拖动忽快忽慢,任何时长都会被下一段抖动跨过)。
*/
export const FAST_MOVE_PX = 8;
/** 连续几帧过门限才定档为快拖(宿主按这个数累计,见上面那句「单帧一比会闪」) */
export const FAST_LATCH_FRAMES = 2;
import { mercY } from '../src/frame';
/**
* 包内测试的假现场:一块记账的 2d 上下文、一个假的 CustomLayer、一张按球形墨卡托投影的地图。
*
* 为什么要自己写投影而不是给个常数:`Frame` 的换算是否与分格几何同源,只有拿真实投影去比才看得出来
* —— 断言「格子在屏幕上就是那个像素边长」用的必须是同一条墨卡托曲线,不然两边各错一点也能对上数。
*/
/** 假 2d 上下文:方法只管记账,属性随便写 */
export interface FakeCtx {
calls: Map<string, number>;
/** 落过笔的那一串字(fillText 的第一个参数):断言"写的就是这个数"用它 */
texts: string[];
reset(): void;
[key: string]: unknown;
}
export function fakeCtx(): FakeCtx {
const calls = new Map<string, number>();
const texts: string[] = [];
const hit = (name: string) => {
calls.set(name, (calls.get(name) ?? 0) + 1);
};
const ctx: FakeCtx = {
calls,
texts,
reset: () => {
calls.clear();
texts.length = 0;
},
};
for (const name of [
'setTransform',
'clearRect',
'beginPath',
'closePath',
'moveTo',
'lineTo',
'arc',
'arcTo',
'fill',
'stroke',
'fillRect',
'strokeRect',
'fillText',
'strokeText',
'save',
'restore',
'translate',
'setLineDash',
]) {
ctx[name] = () => hit(name);
}
ctx.fillText = (text: string) => {
hit('fillText');
texts.push(String(text));
};
// 一字 6px:够把「按宽度算底衬」跑起来,数字长短也分得开
ctx.measureText = (text: string) => {
hit('measureText');
return { width: String(text).length * 6 };
};
return ctx;
}
/** 假 CustomLayer:留下 render 回调供测试按帧点名,并数建了几层 */
export class FakeCustomLayer {
static created: FakeCustomLayer[] = [];
render: (() => void) | null = null;
constructor(
readonly canvas: HTMLCanvasElement,
readonly opts: { zIndex: number; zooms: [number, number]; alwaysRender: boolean },
) {
FakeCustomLayer.created.push(this);
}
setMap() {}
show() {}
hide() {}
}
export interface FakeView {
zoom: number;
lng: number;
lat: number;
w: number;
h: number;
}
/** 球形墨卡托的世界像素坐标(左上角为原点:赤道在 world/2,北纬往上走) */
export function worldPxOf(lng: number, lat: number, zoom: number, tileSize = 256) {
const world = tileSize * Math.pow(2, zoom);
return {
x: ((lng + 180) / 360) * world,
y: (0.5 - mercY(lat) / (2 * Math.PI)) * world,
};
}
/**
* 一张会真的投影的假地图。
*
* 中心点画在容器正中(`Frame` 不假设这件事,它照旧向底图要一次原点)。
*/
export function fakeMap(view: FakeView) {
const project = (lng: number, lat: number) => {
const p = worldPxOf(lng, lat, view.zoom);
const c = worldPxOf(view.lng, view.lat, view.zoom);
return { x: p.x - c.x + view.w / 2, y: p.y - c.y + view.h / 2 };
};
const map = {
getSize: () => ({ width: view.w, height: view.h }),
getCenter: () => ({ getLng: () => view.lng, getLat: () => view.lat }),
getZoom: () => view.zoom,
lngLatToContainer: (lnglat: [number, number]) => project(lnglat[0], lnglat[1]),
containerToLngLat: (px: { x: number; y: number }) => {
const world = 256 * Math.pow(2, view.zoom);
const c = worldPxOf(view.lng, view.lat, view.zoom);
const lng = ((c.x + px.x - view.w / 2) / world) * 360 - 180;
const merc = 2 * Math.PI * (0.5 - (c.y + px.y - view.h / 2) / world);
const lat = (2 * Math.atan(Math.exp(merc)) - Math.PI / 2) * (180 / Math.PI);
return { getLng: () => lng, getLat: () => lat };
},
};
return { map, project };
}
/**
* 分格几何的守卫。
*
* 这一组盯的是「分格与投影是不是同一套换算」。这件事失效的方式很安静:
* 两边各按各的比例尺算,点照样落在屏幕上、数字照样写得出,只是格子集体偏一角 ——
* 于是「点压在线边上」「圆圈不在重心」这类现象没人能一眼看出根因,也没有构建期检查会报。
* 所以这里全部拿**真实球形墨卡托投影**去比,而不是比一个手算的常数。
*/
import { describe, expect, it } from 'vitest';
import { Frame, mercY, pxPerDegLng } from '../src/frame';
import {
bucketize,
cellAt,
cellAtZoom,
cellKey,
cellWidthPx,
KEY_SHIFT,
pxPerDegLat,
type GridCell,
} from '../src/grid';
import { fakeMap, worldPxOf } from './fakes';
/** 用底图自己的投影算两点的屏幕竖直距离 */
function pixelHeight(lng: number, lat: number, dLat: number, zoom: number): number {
const a = worldPxOf(lng, lat, zoom).y;
const b = worldPxOf(lng, lat + dLat, zoom).y;
return Math.abs(a - b);
}
describe('分格几何 · 格子在屏幕上就是那个像素边长', () => {
for (const zoom of [8, 12, 16, 18]) {
for (const lat of [0, 22.5, 45]) {
it(`z${zoom} · 纬度 ${lat}°:横向与纵向都回到 48 像素`, () => {
const cell = cellAtZoom(zoom, 48, lat);
expect(cellWidthPx(zoom, cell)).toBeCloseTo(48, 6);
// 纵向按墨卡托换算:一阶近似,跨的度数极小,与真实投影比到 1% 以内
const exact = pixelHeight(114.05, lat, cell.dLat, zoom);
expect(Math.abs(exact - 48) / 48).toBeLessThan(0.01);
});
}
}
it('缩放翻一级,经度边长减半 —— 屏幕疏密因此不随缩放突变', () => {
const at = (zoom: number) => cellAtZoom(zoom, 48, 22.5).dLng;
expect(at(13)).toBeCloseTo(at(12) / 2, 12);
expect(at(16)).toBeCloseTo(at(12) / 16, 12);
});
it('纬度方向比经度方向宽 1/cos(纬度):这就是纬度越高格子越"扁"的那一条换算', () => {
const ratio = pxPerDegLat(12, 60) / pxPerDegLng(12);
expect(ratio).toBeCloseTo(2, 8);
});
});
describe('分格几何 · 与生产投影同源', () => {
it('用 Frame 走一遍:一格的横向像素数与 cellWidthPx 分毫不差,纵向回到 48', () => {
const view = { zoom: 12, lng: 114.05, lat: 22.54, w: 800, h: 600 };
const { map } = fakeMap(view);
const frame = new Frame();
frame.set(map, view.zoom, view.lng, view.lat, { tileSize: 256, referenceLat: 22.5 });
const cell = cellAtZoom(view.zoom, 48, view.lat);
// 横轴是线性的:这一条应当完全相等,不是"近似相等"
expect(frame.x(114 + cell.dLng) - frame.x(114)).toBeCloseTo(cellWidthPx(view.zoom, cell), 9);
// 纵轴走同一支墨卡托纬度:这一格在视图中心那一带的真实高度就是 48
const mid = view.lat;
const top = frame.y(mercY(mid + cell.dLat / 2));
const bottom = frame.y(mercY(mid - cell.dLat / 2));
expect(Math.abs(bottom - top)).toBeCloseTo(48, 1);
});
it('米制口径也同源:参考纬度上,frame.pxPerMeter × 一度经度的米数 = pxPerDegLng', () => {
const view = { zoom: 12, lng: 114.05, lat: 22.54, w: 800, h: 600 };
const { map } = fakeMap(view);
const frame = new Frame();
const referenceLat = 22.5;
frame.set(map, view.zoom, view.lng, view.lat, { tileSize: 256, referenceLat });
// 赤道 1° 经线 × cos(参考纬度) = 这一纬度上 1° 经线实际多少米
const metersPerDegLng = 111_195 * Math.cos((referenceLat * Math.PI) / 180);
expect(frame.pxPerMeter * metersPerDegLng).toBeCloseTo(pxPerDegLng(view.zoom), 6);
});
});
describe('分格 · 格子编号与归属', () => {
const cell: GridCell = { dLng: 0.25, dLat: 0.2 };
it('边界上的点归右/上那一格:半开区间,相邻两格不重复计', () => {
expect(cellAt({ lng: -180, lat: -90 }, cell)).toEqual({ gx: 0, gy: 0 });
expect(cellAt({ lng: -179.999, lat: -89.999 }, cell)).toEqual({ gx: 0, gy: 0 });
expect(cellAt({ lng: -179.75, lat: -89.9 }, cell)).toEqual({ gx: 1, gy: 0 });
expect(cellAt({ lng: -179.7500001, lat: -89.9 }, cell)).toEqual({ gx: 0, gy: 0 });
});
it('格子编号拼成单值 key 不串位,且能按 KEY_SHIFT 反解回来', () => {
const seen = new Set<number>();
for (let gx = 0; gx < 2000; gx += 37) {
for (let gy = 0; gy < 2000; gy += 53) {
const key = cellKey(gx, gy);
expect(seen.has(key)).toBe(false);
seen.add(key);
expect(key % KEY_SHIFT).toBe(gy);
}
}
});
});
describe('分桶', () => {
const cell: GridCell = { dLng: 0.1, dLat: 0.1 };
it('每个点归到的格子,与它所在桶的格子编号是同一个 —— 圆圈里的数才等于清单里的行数', () => {
const pts = [
{ lng: 114.02, lat: 22.51 },
{ lng: 114.021, lat: 22.512 },
{ lng: 114.029, lat: 22.519 },
{ lng: 114.13, lat: 22.51 },
{ lng: 113.91, lat: 22.62 },
];
const out = bucketize({ lng: pts.map((p) => p.lng), lat: pts.map((p) => p.lat) }, cell);
expect(out.count.length).toBe(3);
for (const p of pts) {
const at = cellAt(p, cell);
const idx = out.gx.findIndex((gx, i) => gx === at.gx && out.gy[i] === at.gy);
expect(idx).toBeGreaterThanOrEqual(0);
expect(out.gx[idx]).toBe(at.gx);
expect(out.gy[idx]).toBe(at.gy);
}
});
it('桶心取成员均值,不取格子几何中心:点在一格里从不均匀分布,均值才贴得住重心', () => {
const out = bucketize({ lng: [114.01, 114.01, 114.012], lat: [22.51, 22.511, 22.513] }, cell);
expect(out.count.length).toBe(1);
expect(out.lng[0]).toBeCloseTo((114.01 + 114.01 + 114.012) / 3, 12);
expect(out.lat[0]).toBeCloseTo((22.51 + 22.511 + 22.513) / 3, 12);
expect(out.maxCount).toBe(3);
});
it('跨半球、跨赤道的点不会并到同一桶(floor 前先 +180/+90 挪到非负)', () => {
const out = bucketize({ lng: [-0.05], lat: [-0.05] }, cell);
const at = cellAt({ lng: -0.05, lat: -0.05 }, cell);
expect(out.gx[0]).toBe(at.gx);
expect(out.gy[0]).toBe(at.gy);
expect(at.gx).toBe(1799);
expect(at.gy).toBe(899);
});
it('空输入给空桶,不炸', () => {
const out = bucketize({ lng: [], lat: [] }, cell);
expect(out.count.length).toBe(0);
expect(out.maxCount).toBe(0);
});
});
/**
* 投影换算的守卫。
*
* 自绘层原先逐帧调用 map.lngLatToContainer 求屏幕位置,现在改成「每一点的墨卡托纬度
* 在喂数据时算一次,每帧只做乘加」。这个替换只有在**两者是同一种投影**时才不会让
* 屏幕上的方格、黑点盘、聚焦形状整体错位一截 —— 而观感问题在构建期测不出来,所以钉在这里。
*
* 拿包内那份网格公式(`grid.ts` 的 `pxPerDegLat`)当基准:聚合网格、热力半径、覆盖物半径
* 全部由它换算,也就是界面上「48 像素一格」这套直觉的尺子。`mercY` 是同一投影的积分形式,
* 两者必须对得上:把 mercY 在某个纬度上做微分,得到的像素/度数应与 pxPerDegLat 一致。
*/
import { describe, expect, it } from 'vitest';
import { mercY, pxPerDegLng } from '../src/frame';
import { pxPerDegLat } from '../src/grid';
const TILE = 256;
const ZOOM = 12;
/** 球形墨卡托的瓦片坐标 y:与高德 / OSM 那一套同一个式子 */
function pixelY(latDeg: number): number {
const world = TILE * Math.pow(2, ZOOM);
return ((1 - mercY(latDeg) / Math.PI) * world) / 2;
}
describe('mercY 与分格用的是同一支墨卡托', () => {
it('中心纬度上下各取一点,像素差除以纬度差就是每度像素', () => {
const lat = 22.55;
const d = 0.01;
const measured = (pixelY(lat - d) - pixelY(lat + d)) / (2 * d);
const expected = pxPerDegLat(ZOOM, lat, TILE);
// 中心差分对 0.01° 的量级误差远小于 0.1%
expect(measured).toBeCloseTo(expected, 2);
});
it('纬度越高,同一纬度差占的像素越多(墨卡托拉伸)', () => {
const span = (a: number, b: number) => Math.abs(pixelY(a) - pixelY(b));
expect(span(20, 21)).toBeLessThan(span(30, 31));
expect(span(30, 31)).toBeLessThan(span(40, 41));
});
it('纬度增大时屏幕 y 减小(北上、下为正向)', () => {
expect(pixelY(22.6)).toBeLessThan(pixelY(22.5));
});
it('经度方向是线性的:每度像素 = 那一级的世界宽度 ÷ 360', () => {
expect(pxPerDegLng(ZOOM, TILE)).toBe((TILE * Math.pow(2, ZOOM)) / 360);
});
it('超出墨卡托区间时按 ±85° 封顶,不会算出无穷大', () => {
expect(Number.isFinite(mercY(89))).toBe(true);
expect(mercY(89)).toBe(mercY(85));
expect(mercY(-89)).toBe(mercY(-85));
});
});
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"types": []
},
"include": ["src"]
}
{
"name": "@hm/server",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "风险热力图 · 登录后台服务(Hono + jose,仅负责鉴权)",
"scripts": {
"dev": "tsx src/index.ts",
"start": "tsx src/index.ts",
"typecheck": "tsc --noEmit",
"gen:account": "tsx scripts/gen-account.mjs",
"add:account": "tsx scripts/add-account.mjs",
"list:accounts": "tsx scripts/list-accounts.mjs",
"remove:account": "tsx scripts/remove-account.mjs"
},
"dependencies": {
"@hono/node-server": "^1.13.0",
"dotenv": "^16.4.0",
"hono": "^4.6.0",
"jose": "^5.9.0",
"tsx": "^4.19.0"
},
"devDependencies": {
"@types/node": "^22.0.0"
}
}
// 交互式添加/更新账号。密码读入不回显,避免明文进 shell 历史 / 进程列表。
// 用法: pnpm --filter @hm/server add:account [用户名]
// 省略用户名则交互询问;密码一律交互输入(不回显)。
import { scryptSync, randomBytes } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync, renameSync, mkdirSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { createInterface } from 'node:readline/promises';
import { stdin, stdout } from 'node:process';
const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');
/** 读一行(非 TTY 时按行读,便于管道测试) */
async function ask(prompt) {
const rl = createInterface({ input: stdin, output: stdout });
const ans = (await rl.question(prompt)).trim();
rl.close();
return ans;
}
/** 不回显读密码(TTY 走 raw mode;管道/非 TTY 降级为读一行) */
function askHidden(prompt) {
return new Promise((resolve) => {
if (!stdin.isTTY) {
const rl = createInterface({ input: stdin });
rl.once('line', (line) => {
rl.close();
stdout.write('\n');
resolve(line);
});
stdout.write(prompt);
return;
}
stdout.write(prompt);
stdin.setRawMode(true);
stdin.resume();
let buf = '';
const onData = (d) => {
const s = d.toString();
if (s === '\r' || s === '\n') {
stdin.setRawMode(false);
stdin.pause();
stdin.removeListener('data', onData);
stdout.write('\n');
resolve(buf);
} else if (s === '\u0003') {
// Ctrl-C
stdout.write('\n');
process.exit(1);
} else if (s === '\u007f' || s === '\b') {
buf = buf.slice(0, -1);
} else if (s >= ' ') {
buf += s;
}
};
stdin.on('data', onData);
});
}
const argUser = process.argv[2];
const username = argUser ?? (await ask('用户名: '));
if (!username) {
console.error('用户名不能为空');
process.exit(1);
}
const password = await askHidden('密码: ');
if (!password) {
console.error('密码不能为空');
process.exit(1);
}
mkdirSync(path.dirname(ACCOUNTS_PATH), { recursive: true });
const accounts = existsSync(ACCOUNTS_PATH)
? JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))
: [];
const salt = randomBytes(16);
const derived = scryptSync(password, salt, 64).toString('hex');
const entry = { username, hash: `${salt.toString('hex')}:${derived}` };
const idx = accounts.findIndex((a) => a.username === username);
const mode = idx >= 0 ? '更新' : '新增';
if (idx >= 0) accounts[idx] = entry;
else accounts.push(entry);
// 原子写:先写临时文件再 rename,避免写到一半进程退出损坏数据
const tmp = ACCOUNTS_PATH + '.tmp';
writeFileSync(tmp, JSON.stringify(accounts, null, 2) + '\n', 'utf-8');
renameSync(tmp, ACCOUNTS_PATH);
console.log(`${mode}账号 "${username}" 成功 -> ${ACCOUNTS_PATH}`);
import { scrypt, randomBytes } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');
const [username, password] = process.argv.slice(2);
if (!username || !password) {
console.error('用法: pnpm --filter @hm/server gen:account <用户名> <密码>');
process.exit(1);
}
const salt = randomBytes(16);
const derived = scrypt(password, salt, 64).toString('hex');
const entry = { username, hash: `${salt.toString('hex')}:${derived}` };
const accounts = existsSync(ACCOUNTS_PATH)
? JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'))
: [];
const idx = accounts.findIndex((a) => a.username === username);
if (idx >= 0) accounts[idx] = entry;
else accounts.push(entry);
writeFileSync(ACCOUNTS_PATH, JSON.stringify(accounts, null, 2) + '\n', 'utf-8');
console.log(`已写入账号 "${username}" -> ${ACCOUNTS_PATH}`);
// 列出所有账号用户名(不打印哈希,哈希不可用于登录,仅作存在性核对)。
// 用法: pnpm --filter @hm/server list:accounts
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');
if (!existsSync(ACCOUNTS_PATH)) {
console.log('(无账号文件)');
process.exit(0);
}
const accounts = JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'));
if (!accounts.length) {
console.log('(无账号)');
process.exit(0);
}
console.log(`共 ${accounts.length} 个账号:`);
for (const a of accounts) console.log(` - ${a.username}`);
// 删除账号。
// 用法: pnpm --filter @hm/server remove:account <用户名>
import { existsSync, readFileSync, writeFileSync, renameSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');
const username = process.argv[2];
if (!username) {
console.error('用法: pnpm --filter @hm/server remove:account <用户名>');
process.exit(1);
}
if (!existsSync(ACCOUNTS_PATH)) {
console.error('账号文件不存在');
process.exit(1);
}
const accounts = JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8'));
const next = accounts.filter((a) => a.username !== username);
if (next.length === accounts.length) {
console.error(`未找到账号 "${username}"`);
process.exit(1);
}
const tmp = ACCOUNTS_PATH + '.tmp';
writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n', 'utf-8');
renameSync(tmp, ACCOUNTS_PATH);
console.log(`已删除账号 "${username}"(剩余 ${next.length} 个)`);
import { scryptSync, timingSafeEqual } from 'node:crypto';
import { existsSync, readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');
export interface Account {
username: string;
/** scrypt 哈希,格式 `salt(hex):derived(hex)`,salt 16 字节 / derived 64 字节 */
hash: string;
}
function splitHash(stored: string): { salt: Buffer; derived: Buffer } {
const [saltHex, derivedHex] = stored.split(':');
if (!saltHex || !derivedHex) throw new Error('账号哈希格式非法');
return { salt: Buffer.from(saltHex, 'hex'), derived: Buffer.from(derivedHex, 'hex') };
}
/** 用账号里存的 salt 对输入密码做 scrypt,timingSafeEqual 防时序侧信道 */
export function verifyPassword(password: string, stored: string): boolean {
const { salt, derived } = splitHash(stored);
const tryDerived = scryptSync(password, salt, derived.length);
return timingSafeEqual(derived, tryDerived);
}
export function loadAccounts(): Account[] {
if (!existsSync(ACCOUNTS_PATH)) return [];
return JSON.parse(readFileSync(ACCOUNTS_PATH, 'utf-8')) as Account[];
}
export function findAccount(username: string): Account | undefined {
return loadAccounts().find((a) => a.username === username);
}
// 容器首次启动初始化默认账号:仅当账号文件不存在、且配了 BOOTSTRAP_USER/BOOTSTRAP_PASSWORD 时。
// 已有账号文件则跳过(不覆盖,保护 volume 中已有数据)。哈希算法与 src/auth.ts 的 verifyPassword 一致。
import { scryptSync, randomBytes } from 'node:crypto';
import { existsSync, mkdirSync, writeFileSync, renameSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
export function ensureBootstrapAccount(): void {
const here = path.dirname(fileURLToPath(import.meta.url));
const ACCOUNTS_PATH = path.resolve(here, '../data/accounts.json');
// 已有账号文件(宿主机挂 volume 或之前初始化过)→ 不覆盖
if (existsSync(ACCOUNTS_PATH)) return;
const user = process.env.BOOTSTRAP_USER;
const pwd = process.env.BOOTSTRAP_PASSWORD;
if (!user || !pwd) return; // 未提供 env → 不建账号,由运维挂 volume 或后续 add:account
const salt = randomBytes(16);
const derived = scryptSync(pwd, salt, 64).toString('hex');
mkdirSync(path.dirname(ACCOUNTS_PATH), { recursive: true });
const tmp = ACCOUNTS_PATH + '.tmp';
writeFileSync(
tmp,
JSON.stringify([{ username: user, hash: `${salt.toString('hex')}:${derived}` }], null, 2) +
'\n',
);
renameSync(tmp, ACCOUNTS_PATH);
console.log(`[auth] 已从 BOOTSTRAP_USER 初始化账号 "${user}"`);
}
import { randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
/**
* 图形验证码(服务端签发 + 服务端校验)。
*
* 设计要点,逐条都对应一种真实攻击:
*
* 1. **码只存在服务端**。接口回给前端的是 `{ id, image }`,`image` 是服务端渲染好的
* SVG data URI。前端拿不到明文码,也就没法「本地比对」——那种写法(把答案塞进
* JS 变量再在浏览器里比)等于没做验证码,任何人看一眼源码就能绕。
* 2. **一次性 + 有 TTL**。验证成功即销毁;错满 MAX_TRIES 次也销毁。否则一张图可以被
* 无限次试(32^4 的空间,慢慢试总能中)。
* 3. **按 IP 限流签发**。防止有人写脚本狂拉 /api/captcha 把内存撑爆,也顺手把
* 自动化爆破的单 IP 吞吐压到没有意义。
* 4. **常量时间比较**。用 timingSafeEqual,避免按字节提前返回泄露信息(这里是 4 位码,
* 收益有限,但成本为零)。
*
* 注意:验证码不是密码的替代品。它挡的是「脚本批量撞库」,挡不住「针对单个账号的
* 人工社工」。登录失败计数(index.ts 里的 rateLimit)是另一层,两者都要有。
*/
/** 去掉易混字符:0/O、1/I/l、2/Z、5/S、8/B 在噪点图里会被看错 */
const ALPHABET = '346789ACDEFGHJKMNPQRTUVWXY';
const CODE_LENGTH = 4;
const TTL_MS = 2 * 60 * 1000;
/** 同一张图允许试错次数,超了必须换图 */
const MAX_TRIES = 3;
/** 内存里最多同时挂多少张未使用的图,超了淘汰最早的(Map 保持插入序) */
const MAX_PENDING = 3000;
/** 单 IP 每分钟签发上限 */
const ISSUE_LIMIT = 40;
interface Entry {
code: string;
expiresAt: number;
tries: number;
}
const store = new Map<string, Entry>();
const issueWindow = new Map<string, { count: number; resetAt: number }>();
export interface CaptchaChallenge {
id: string;
/** `data:image/svg+xml;base64,...`,可直接塞进 <img src> */
image: string;
/** 秒,给前端做倒计时提示用 */
expiresIn: number;
}
export type CaptchaVerdict = 'ok' | 'invalid' | 'expired' | 'missing';
export class CaptchaRateLimited extends Error {
constructor() {
super('captcha_rate_limited');
}
}
function issueAllowed(ip: string): boolean {
const now = Date.now();
const rec = issueWindow.get(ip);
if (!rec || now >= rec.resetAt) {
issueWindow.set(ip, { count: 1, resetAt: now + 60_000 });
return true;
}
if (rec.count >= ISSUE_LIMIT) return false;
rec.count += 1;
return true;
}
function sweep(now: number): void {
for (const [id, entry] of store) {
if (entry.expiresAt <= now) store.delete(id);
}
for (const [ip, rec] of issueWindow) {
if (rec.resetAt <= now) issueWindow.delete(ip);
}
}
/**
* 定时清理。`unref()` 很关键:不然这个 interval 会把 Node 进程钉死,
* 容器里 `docker stop` 要等到超时才退,本地 tsx 也会挂住终端。
*/
const sweeper = setInterval(() => sweep(Date.now()), 60_000);
sweeper.unref();
function pick<T>(arr: readonly T[]): T {
return arr[randomInt(0, arr.length)];
}
function rand(min: number, max: number): number {
return min + Math.random() * (max - min);
}
function buildCode(): string {
let out = '';
for (let i = 0; i < CODE_LENGTH; i += 1) out += ALPHABET[randomInt(0, ALPHABET.length)];
return out;
}
/** 噪点颜色都偏深偏灰蓝,保证在黑字与浅底之间有足够对比,不做成「一片糊」 */
const INK = ['#1f2a5e', '#2b3a7a', '#39406b', '#4653a2', '#243049', '#3c2f5e'];
const NOISE = ['#8f9bc4', '#a9b4d6', '#6f7bab', '#c0c8e0'];
function buildSvg(code: string): string {
const W = 132;
const H = 44;
const chars = [...code].map((ch, i) => {
// 字符故意轻微重叠(步长 26 < 字宽 ~27),配合旋转就断开了「逐字切分」这条路。
// 字号取 25~29:图在登录框里只显示 108×36,源图字号再小一档,缩放后 4 个字符就
// 挤成一条毛边(实测 23~27 时第 4 位最容易认错)。
const x = 15 + i * 26 + rand(-2.5, 2.5);
const y = 31 + rand(-2.5, 2.5);
const rot = rand(-24, 24);
const size = rand(25, 29);
return `<text x="${x.toFixed(1)}" y="${y.toFixed(1)}" font-size="${size.toFixed(
1,
)}" font-weight="700" fill="${pick(INK)}" transform="rotate(${rot.toFixed(
1,
)} ${x.toFixed(1)} ${y.toFixed(1)})">${ch}</text>`;
});
const curves = Array.from({ length: 3 }, () => {
const y1 = rand(6, H - 6);
const y2 = rand(6, H - 6);
return `<path d="M${rand(-8, 4).toFixed(1)} ${y1.toFixed(1)} C ${rand(24, 48).toFixed(
1,
)} ${rand(-4, H + 4).toFixed(1)}, ${rand(84, 108).toFixed(1)} ${rand(-4, H + 4).toFixed(
1,
)}, ${rand(W - 4, W + 8).toFixed(1)} ${y2.toFixed(
1,
)}" fill="none" stroke="${pick(NOISE)}" stroke-width="${rand(0.8, 1.5).toFixed(
2,
)}" stroke-linecap="round" opacity="${rand(0.5, 0.9).toFixed(2)}"/>`;
}).join('');
const dots = Array.from({ length: 34 }, () => {
return `<circle cx="${rand(0, W).toFixed(1)}" cy="${rand(0, H).toFixed(
1,
)}" r="${rand(0.5, 1.4).toFixed(2)}" fill="${pick(NOISE)}" opacity="${rand(
0.35,
0.8,
).toFixed(2)}"/>`;
}).join('');
// 中间横穿一条干扰线:专门打掉「按行投影切字符」的简单 OCR
const strikeY = rand(14, 30).toFixed(1);
return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" role="img">
<defs>
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#f6f8fd"/><stop offset="52%" stop-color="#eaeef9"/><stop offset="100%" stop-color="#dde4f4"/>
</linearGradient>
<filter id="warp" x="-10%" y="-10%" width="120%" height="120%">
<feTurbulence type="fractalNoise" baseFrequency="0.035" numOctaves="2" seed="${randomInt(
1,
99,
)}" result="n"/>
<feDisplacementMap in="SourceGraphic" in2="n" scale="1.6" xChannelSelector="R" yChannelSelector="G"/>
</filter>
</defs>
<rect width="${W}" height="${H}" fill="url(#bg)"/>
<g opacity="0.55">${dots}</g>
<g>${curves}</g>
<g filter="url(#warp)" font-family="'DejaVu Sans Mono','Liberation Mono',Consolas,'Courier New',monospace" letter-spacing="0.5">${chars}</g>
<line x1="${rand(4, 14).toFixed(1)}" y1="${strikeY}" x2="${rand(W - 14, W - 4).toFixed(
1,
)}" y2="${rand(14, 30).toFixed(1)}" stroke="${pick(NOISE)}" stroke-width="1.1" opacity="0.75"/>
</svg>`;
}
export function createCaptcha(ip: string): CaptchaChallenge {
if (!issueAllowed(ip)) throw new CaptchaRateLimited();
const now = Date.now();
if (store.size >= MAX_PENDING) sweep(now);
while (store.size >= MAX_PENDING) {
const oldest = store.keys().next();
if (oldest.done) break;
store.delete(oldest.value);
}
const id = randomBytes(16).toString('hex');
const code = buildCode();
store.set(id, { code, expiresAt: now + TTL_MS, tries: 0 });
return {
id,
image: `data:image/svg+xml;base64,${Buffer.from(buildSvg(code), 'utf-8').toString('base64')}`,
expiresIn: Math.floor(TTL_MS / 1000),
};
}
/**
* 校验并消耗。返回值刻意区分 expired / invalid:
* 前端据此决定提示语(「已过期,已换一张」vs「填错了」),但两者都不是安全信息,
* 攻击者本来就知道自己的码有没有过期。
*/
export function verifyCaptcha(id: string | undefined, input: string | undefined): CaptchaVerdict {
if (!id || !input) return 'missing';
const entry = store.get(id);
if (!entry) return 'expired';
if (entry.expiresAt <= Date.now()) {
store.delete(id);
return 'expired';
}
entry.tries += 1;
const normalized = input.trim().toUpperCase();
const expected = Buffer.from(entry.code, 'utf-8');
const actual = Buffer.from(normalized, 'utf-8');
const matched =
expected.length === actual.length && timingSafeEqual(expected, actual);
if (matched) {
store.delete(id);
return 'ok';
}
if (entry.tries >= MAX_TRIES) store.delete(id);
return 'invalid';
}
/** 仅测试用:清空所有未使用的挑战 */
export function __resetCaptchaStore(): void {
store.clear();
issueWindow.clear();
}
import 'dotenv/config';
import { existsSync, readFileSync, statSync } from 'node:fs';
import { extname, join, normalize } from 'node:path';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { Hono } from 'hono';
import type { Context } from 'hono';
import { serve } from '@hono/node-server';
import { getConnInfo } from '@hono/node-server/conninfo';
import { findAccount, verifyPassword } from './auth';
import { signToken, verifyToken } from './jwt';
import { ensureBootstrapAccount } from './bootstrap';
import { CaptchaRateLimited, createCaptcha, verifyCaptcha } from './captcha';
const app = new Hono();
const PORT = Number(process.env.SERVER_PORT ?? 8787);
// 前端 vite build 产物在仓库根 dist/。生产全栈模式下由本服务同源托管。
// 三层 .. 是本文件所在深度:packages/server/src → 仓库根。少一层就变成 packages/dist,静态永远找不到。
const here = path.dirname(fileURLToPath(import.meta.url));
const DIST = path.resolve(here, '../../../dist');
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.woff2': 'font/woff2',
'.woff': 'font/woff',
'.ttf': 'font/ttf',
'.geojson': 'application/json',
'.map': 'application/json',
};
if (!process.env.AUTH_SECRET) {
console.warn('[auth] 未设置 AUTH_SECRET,使用不安全的开发默认密钥;生产环境务必在 .env 配置');
}
app.get('/api/health', (c) => c.json({ ok: true }));
/**
* 客户端 IP。反代在就信 `X-Forwarded-For` 的第一段(Nginx `$proxy_add_x_forwarded_for`
* 会把真实来源放最前),没有再退回 socket 地址。
*
* 为什么不一律用 socket 地址:容器里若前面挂了一层 Nginx,所有请求的来源都是那个
* 内网 IP,按 IP 限流就退化成「全站共用一个额度」,10 次失败能把所有人一起锁住。
* 为什么不一律信 XFF:没有反代时这个头是客户端随便写的,等于没限流。两种部署形态
* 都要能跑,所以先信头、再退回 socket —— 被伪造的风险由「限流只是第二层」兜底。
*/
function clientIp(c: Context): string {
const xff = c.req.header('x-forwarded-for');
if (xff) {
const first = xff.split(',')[0]?.trim();
if (first) return first;
}
try {
return getConnInfo(c).remote.address ?? 'unknown';
} catch {
return 'unknown';
}
}
/**
* 登录失败计数(第二层防线,第一层是图形验证码)。
*
* 语义:同一 IP 在 10 分钟内失败 10 次后,后续登录直接 429,直到窗口滑过去。
* 只在「密码错」时记失败,成功即清零;验证码错不算(那属于填错图,不该让人锁账号,
* 而且验证码本身就是一次性的,已经限了速率)。
*/
const LOGIN_FAIL_LIMIT = 10;
const LOGIN_FAIL_WINDOW_MS = 10 * 60 * 1000;
const loginFails = new Map<string, { count: number; resetAt: number }>();
function loginBlocked(ip: string): boolean {
const rec = loginFails.get(ip);
if (!rec) return false;
if (Date.now() >= rec.resetAt) {
loginFails.delete(ip);
return false;
}
return rec.count >= LOGIN_FAIL_LIMIT;
}
function noteLoginFail(ip: string): void {
const now = Date.now();
const rec = loginFails.get(ip);
if (!rec || now >= rec.resetAt) {
loginFails.set(ip, { count: 1, resetAt: now + LOGIN_FAIL_WINDOW_MS });
} else {
rec.count += 1;
}
}
/** 图形验证码:服务端渲染 SVG,只把 id 与图片给前端,明文码留在服务端 */
app.get('/api/captcha', (c) => {
try {
const challenge = createCaptcha(clientIp(c));
// no-store:验证码必须每次都是新的,任何一层缓存都会让人反复看到同一张图
return c.json(challenge, 200, { 'Cache-Control': 'no-store, max-age=0' });
} catch (err) {
if (err instanceof CaptchaRateLimited) {
return c.json({ error: 'too_many_requests', message: '验证码请求过于频繁,请稍后再试' }, 429);
}
throw err;
}
});
app.post('/api/login', async (c) => {
let body: {
username?: string;
password?: string;
captchaId?: string;
captchaCode?: string;
};
try {
body = await c.req.json();
} catch {
return c.json({ error: 'bad_request' }, 400);
}
const { username, password, captchaId, captchaCode } = body;
const ip = clientIp(c);
if (loginBlocked(ip)) {
return c.json({ error: 'too_many_attempts', message: '尝试次数过多,请 10 分钟后再试' }, 429);
}
// 验证码先于密码校验:这一步很便宜,且能在做 scrypt(有意慢)之前挡掉自动化请求
const verdict = verifyCaptcha(captchaId, captchaCode);
if (verdict !== 'ok') {
return c.json(
{
error: verdict === 'missing' ? 'captcha_required' : 'captcha_invalid',
message:
verdict === 'expired'
? '验证码已过期,请点击图片换一张'
: '验证码不正确,请重新输入',
},
400,
);
}
if (!username || !password) return c.json({ error: 'bad_request' }, 400);
const acct = findAccount(username);
// 账号不存在与密码错误返回同一错误,避免暴露账号是否存在
if (!acct || !verifyPassword(password, acct.hash)) {
noteLoginFail(ip);
return c.json({ error: 'invalid_credentials', message: '用户名或密码错误' }, 401);
}
loginFails.delete(ip);
const token = await signToken(username);
return c.json({ token, user: { username } });
});
app.get('/api/me', async (c) => {
const auth = c.req.header('Authorization');
if (!auth?.startsWith('Bearer ')) return c.json({ error: 'no_token' }, 401);
const payload = await verifyToken(auth.slice(7));
if (!payload) return c.json({ error: 'invalid_token' }, 401);
return c.json({ user: { username: payload.username } });
});
// 无状态 JWT:后端不留存会话,登出由前端丢弃 token 完成
app.post('/api/logout', (c) => c.json({ ok: true }));
// 生产全栈模式:同源托管前端静态产物(dist/)并兜底 SPA 路由。
// dev 下 dist 不存在,此兜底返回 503 提示先 build;/api 已由上方路由处理,不会落入此处。
app.get('*', (c) => {
const { pathname } = new URL(c.req.url);
if (pathname.startsWith('/api')) return c.json({ error: 'not_found' }, 404);
const rel = pathname === '/' ? '/index.html' : pathname;
const filePath = normalize(join(DIST, decodeURIComponent(rel)));
if (
!filePath.startsWith(DIST) || // 防目录穿越
!existsSync(filePath) ||
!statSync(filePath).isFile()
) {
const index = join(DIST, 'index.html');
if (existsSync(index)) {
return c.body(readFileSync(index), 200, { 'Content-Type': 'text/html; charset=utf-8' });
}
return c.body('前端未构建:请先运行 pnpm build', 503);
}
const mime = MIME[extname(filePath)] ?? 'application/octet-stream';
return c.body(readFileSync(filePath), 200, { 'Content-Type': mime });
});
// 容器首次启动:无账号文件且配了 BOOTSTRAP_USER/PASSWORD 时初始化默认账号
ensureBootstrapAccount();
serve({ fetch: app.fetch, port: PORT }, (info) => {
console.log(`[auth] 登录服务已启动: http://localhost:${info.port}`);
});
import { SignJWT, jwtVerify } from 'jose';
const secret = new TextEncoder().encode(
process.env.AUTH_SECRET ?? 'dev-only-insecure-secret-change-me',
);
const EXP = '12h';
export async function signToken(username: string): Promise<string> {
return await new SignJWT({ username })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(EXP)
.sign(secret);
}
export async function verifyToken(token: string): Promise<{ username: string } | null> {
try {
const { payload } = await jwtVerify(token, secret);
if (typeof payload.username === 'string') return { username: payload.username };
return null;
} catch {
return null;
}
}
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "Bundler",
"lib": ["ES2022"],
"types": ["node"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"noEmit": true,
"resolveJsonModule": true
},
"include": ["src", "scripts"]
}
{
"input": "",
"output": "",
"cache": "",
"workers": 20,
"qps": 100,
"limit": null,
"sort_incomplete_last": true,
"infer_nearby": false
}
{
"input": "",
"output": "",
"cache": "",
"workers": 20,
"qps": 100,
"limit": null,
"sort_incomplete_last": true,
"infer_nearby": false
}
案件号,出险地点,报案时间,经度,纬度
00000000000000000001,广东省-深圳市-南山区-科技园南路18号,2026-01-01 10:00:00,113.942000,22.536000
00000000000000000002,广东省-深圳市-宝安区,2026-01-01 11:00:00,113.883000,22.558000
00000000000000000003,工业二路20号,2026-01-01 12:00:00,113.936672,22.740500
00000000000000000004,广东省-深圳市-光明区-凤凰街道光源四路贝特瑞新能源科技大厦,2026-01-01 13:00:00,113.936672,22.740500
No preview for this file type
{
"name": "data-complete-ts",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "data-complete-ts",
"version": "1.0.0",
"dependencies": {
"csv-parse": "^5.6.0",
"csv-stringify": "^6.5.2",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@types/node": "^22.10.0",
"typescript": "^5.7.0"
},
"engines": {
"node": ">=22.18.0"
}
},
"node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmmirror.com/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/adler-32": {
"version": "1.3.1",
"resolved": "https://registry.npmmirror.com/adler-32/-/adler-32-1.3.1.tgz",
"integrity": "sha512-ynZ4w/nUUv5rrsR8UUGoe1VC9hZj6V5hU9Qw1HlMDJGEJw5S7TfTErWTjMys6M7vr0YWcPqs3qAr4ss0nDfP+A==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/cfb": {
"version": "1.2.2",
"resolved": "https://registry.npmmirror.com/cfb/-/cfb-1.2.2.tgz",
"integrity": "sha512-KfdUZsSOw19/ObEWasvBP/Ac4reZvAGauZhs6S/gqNhXhI7cKwvlH7ulj+dOEYnca4bm4SGo8C1bTAQvnTjgQA==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"crc-32": "~1.2.0"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/codepage": {
"version": "1.15.0",
"resolved": "https://registry.npmmirror.com/codepage/-/codepage-1.15.0.tgz",
"integrity": "sha512-3g6NUTPd/YtuuGrhMnOMRjFc+LJw/bnMp3+0r/Wcz3IXUuCosKRJvMphm5+Q+bvTVGcJJuRvVLuYba+WojaFaA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/crc-32": {
"version": "1.2.2",
"resolved": "https://registry.npmmirror.com/crc-32/-/crc-32-1.2.2.tgz",
"integrity": "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ==",
"license": "Apache-2.0",
"bin": {
"crc32": "bin/crc32.njs"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/csv-parse": {
"version": "5.6.0",
"resolved": "https://registry.npmmirror.com/csv-parse/-/csv-parse-5.6.0.tgz",
"integrity": "sha512-l3nz3euub2QMg5ouu5U09Ew9Wf6/wQ8I++ch1loQ0ljmzhmfZYrH9fflS22i/PQEvsPvxCwxgz5q7UB8K1JO4Q==",
"license": "MIT"
},
"node_modules/csv-stringify": {
"version": "6.9.0",
"resolved": "https://registry.npmmirror.com/csv-stringify/-/csv-stringify-6.9.0.tgz",
"integrity": "sha512-6b3e29CILFfSQ2nDRuZMRROzQOpPuJ+s8zPB5H7eK5ncXBbFOyVuRLU5Sx/zAUmVri3Ly49GyC8NEme4SVSAbA==",
"license": "MIT"
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://registry.npmmirror.com/frac/-/frac-1.1.2.tgz",
"integrity": "sha512-w/XBfkibaTl3YDqASwfDUqkna4Z2p9cFSr1aHDt0WoMTECnRfBOv2WArlZILlqgWlmdIlALXGpM2AOhEk5W3IA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/ssf": {
"version": "0.11.2",
"resolved": "https://registry.npmmirror.com/ssf/-/ssf-0.11.2.tgz",
"integrity": "sha512-+idbmIXoYET47hH+d7dfm2epdOMUDjqcB4648sTZ+t2JwoyBFL/insLfB/racrDmsKB3diwsDA696pZMieAC5g==",
"license": "Apache-2.0",
"dependencies": {
"frac": "~1.1.2"
},
"engines": {
"node": ">=0.8"
}
},
"node_modules/typescript": {
"version": "5.9.3",
"resolved": "https://registry.npmmirror.com/typescript/-/typescript-5.9.3.tgz",
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmmirror.com/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT"
},
"node_modules/wmf": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/wmf/-/wmf-1.0.2.tgz",
"integrity": "sha512-/p9K7bEh0Dj6WbXg4JG0xvLQmIadrner1bi45VMJTfnbVHsc7yIajZyoSoK60/dtVBs12Fm6WkUI5/3WAVsNMw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/word": {
"version": "0.3.0",
"resolved": "https://registry.npmmirror.com/word/-/word-0.3.0.tgz",
"integrity": "sha512-OELeY0Q61OXpdUfTp+oweA/vtLVg5VDOXh+3he3PNzLGG/y0oylSOC1xRVj0+l4vQ3tj/bB1HVHv1ocXkQceFA==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.8"
}
},
"node_modules/xlsx": {
"version": "0.18.5",
"resolved": "https://registry.npmmirror.com/xlsx/-/xlsx-0.18.5.tgz",
"integrity": "sha512-dmg3LCjBPHZnQp5/F/+nnTa+miPJxUXB6vtk42YjBBKayDNagxGEeIdWApkYPOf3Z3pm3k62Knjzp7lMeTEtFQ==",
"license": "Apache-2.0",
"dependencies": {
"adler-32": "~1.3.0",
"cfb": "~1.2.1",
"codepage": "~1.15.0",
"crc-32": "~1.2.1",
"ssf": "~0.11.2",
"wmf": "~1.0.1",
"word": "~0.3.0"
},
"bin": {
"xlsx": "bin/xlsx.njs"
},
"engines": {
"node": ">=0.8"
}
}
}
}
{
"name": "data-complete-ts",
"version": "1.0.0",
"private": true,
"description": "高德 GCJ-02 坐标补全 CSV(TypeScript 版,Node 直接运行 .ts,无需构建)",
"type": "module",
"engines": {
"node": ">=22.18.0"
},
"scripts": {
"start": "node --disable-warning=ExperimentalWarning src/run-tool.ts",
"ui": "node --disable-warning=ExperimentalWarning src/desktop.ts",
"core": "node --disable-warning=ExperimentalWarning src/amap-fill.ts",
"check": "node --disable-warning=ExperimentalWarning src/run-tool.ts --check",
"test": "node --disable-warning=ExperimentalWarning --test-reporter=spec --test \"test/*.test.ts\"",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"csv-parse": "^5.6.0",
"csv-stringify": "^6.5.2",
"xlsx": "^0.18.5"
},
"devDependencies": {
"@types/node": "^22.10.0",
"typescript": "^5.7.0"
}
}
@echo off
setlocal DisableDelayedExpansion
chcp 65001 >nul
rem Amap reverse-geocoding fill tool (TypeScript) Windows launcher.
rem Keep this file pure ASCII with CRLF endings: cmd.exe mis-parses batch
rem files that contain non-ASCII bytes or bare LF line endings.
if defined NODE_EXE goto explicit_node
where node >nul 2>&1
if errorlevel 1 goto missing_node
set "NODE_CMD=node"
goto check_version
:explicit_node
if not exist "%NODE_EXE%" goto invalid_node
set "NODE_CMD=%NODE_EXE%"
:check_version
"%NODE_CMD%" -e "const [a,b]=process.versions.node.split('.').map(Number);process.exit(a>22||(a===22&&b>=18)?0:1)" >nul 2>&1
if errorlevel 1 goto old_node
if not exist "%~dp0node_modules\csv-parse" goto missing_modules
if not exist "%~dp0node_modules\xlsx" goto missing_modules
"%NODE_CMD%" --disable-warning=ExperimentalWarning "%~dp0src\run-tool.ts" %*
set "AMAP_EXIT_CODE=%errorlevel%"
goto finish
:old_node
echo Node.js 22.18 or newer is required. Install it and enable Add to PATH,
echo or set NODE_EXE to the full path of node.exe before running this file.
set "AMAP_EXIT_CODE=1"
goto finish
:invalid_node
echo NODE_EXE does not point to a readable node.exe.
set "AMAP_EXIT_CODE=1"
goto finish
:missing_node
echo Node.js was not found in PATH.
echo Install Node.js 22.18 or newer, or set NODE_EXE to the full path of node.exe.
set "AMAP_EXIT_CODE=1"
goto finish
:missing_modules
echo node_modules is missing. Run: npm install --omit=dev
echo in this tool folder, or use the package that already contains node_modules.
set "AMAP_EXIT_CODE=1"
goto finish
:finish
echo.
echo Exit code: %AMAP_EXIT_CODE% (0=complete, 2=output with missing fields, 130=interrupted)
if not defined AMAP_NO_PAUSE pause
exit /b %AMAP_EXIT_CODE%
/**
* 从「出险地点」文本读出 行政区 / 街道 / 道路。
*
* 三条口径,都是从主程序搬过来的(改动必须两边同步,否则工具写出的列值会盖住主程序的解析):
* 1) 行政区按模板位置取第 3 段,段首剥名 + 旧名归并 + 短名兜底,见 splitAddress;
* 2) 街道只在「本区街道词表 + 具体地址段开头」认,不做全文扫描;
* 3) 道路只认地址里明写的路名后缀,不猜、不做坐标吸附,见 roadOfAddress。
* 认不出就留空,交给坐标去查接口 —— 宁缺勿错。
*/
import { DISTRICT_TAIL, ROAD_HEAD, type Vocab, canonicalDistrict } from './vocab.ts';
/** 模板四层「省-市-区-具体地址」;具体地址内部的 '-' 由 joinRest 回接 */
export function splitParts(address: string): string[] {
return address.split('-').map((part) => part.trim()).filter(Boolean);
}
/**
* 区按位置取第 3 段、具体地址取第 4 段起。四处兜底与主程序一致:
* 区名粘了别的字、功能区旧名、只写短名、整行缺省/市前缀(退回扫描)。
*/
export function splitAddress(
parts: readonly string[],
vocab: Vocab,
): { district: string; rest: string } {
/** `allowTail` 只给第 3 段用:位置对上了才敢靠「××区」尾巴认名 */
const peel = (
seg: string,
tailRest: string,
allowTail: boolean,
): { district: string; rest: string } | null => {
if (!seg) return null;
const known = vocab.districtsByLen.find((n) => seg.startsWith(n));
if (known) return { district: known, rest: joinRest(seg.slice(known.length), tailRest) };
const alias = vocab.aliases.find(([from]) => seg.startsWith(from));
if (alias) return { district: alias[1], rest: joinRest(seg.slice(alias[0].length), tailRest) };
const short = vocab.shortNames.find(([from]) => seg.startsWith(from));
if (short) {
const [word, district] = short;
const rest = seg.slice(word.length);
// 「宝安大道」不是「宝安」+「大道」:短名后面紧跟路名尾巴,这一段写的就是路
if (!ROAD_HEAD.test(rest)) return { district, rest: joinRest(rest, tailRest) };
// 例外是「南山街道」:本区街道词表里真有这个名字,认下区但整段原样留给街道识别
const street = (vocab.streetsByDistrict.get(district) ?? [])
.find((s) => s.length > word.length && seg.startsWith(s));
if (street) return { district, rest: joinRest(seg, tailRest) };
}
if (allowTail && DISTRICT_TAIL.test(seg)) {
return { district: canonicalDistrict(seg), rest: tailRest };
}
return null;
};
const head = peel(parts[2] ?? '', parts.slice(3).join('-'), true);
if (head) return head;
for (let i = 0; i < parts.length; i += 1) {
const hit = peel(parts[i], parts.slice(i + 1).join('-'), false);
if (hit) return hit;
}
return { district: '', rest: parts.join('-') };
}
function joinRest(head: string, tail: string): string {
if (!head) return tail;
return tail ? `${head}-${tail}` : head;
}
/** 道路后缀,按长度从长到短排:同一位置先试长的,否则「人民大道」会被切错 */
const ROAD_SUFFIXES = [
'高速公路', '城市快速路', '快速路', '高架桥', '立交桥', '立交', '匝道', '隧道',
'大桥', '辅路', '环路', '大道', '公路', '国道', '省道', '县道', '乡道', '高速',
'街', '路', '巷',
];
/** 主名不许跨过去的字:地址层级、门牌、楼层都不是路名的一部分 */
const NAME_BREAK = '省市区县号栋幢座层室街道路巷';
/** 写着「这条路没有名字」的开头:读得出后缀,读不出是哪条路 */
const NAMELESS = ['无名', '未命名', '未名', '暂无'];
function isNameChar(c: string): boolean {
return /[一-鿿A-Za-z0-9]/.test(c);
}
function suffixAt(text: string, pos: number): number {
for (const s of ROAD_SUFFIXES) {
if (text.startsWith(s, pos)) {
// 「街道」是行政单位不是路段:街后面跟道时整档跳过
if (s === '街' && text.startsWith('道', pos + 1)) continue;
return s.length;
}
}
return 0;
}
/** 取地址里第一个写得完整的道路名,取不到返回空串 */
export function roadOfAddress(detail: string): string {
if (!detail) return '';
const len = detail.length;
for (let pos = 0; pos < len; pos += 1) {
const sl = suffixAt(detail, pos);
if (sl === 0) continue;
const floor = Math.max(0, pos - 10);
let start = pos;
for (let k = pos - 1; k >= floor; k -= 1) {
const c = detail[k];
if (NAME_BREAK.indexOf(c) >= 0 || !isNameChar(c)) break;
start = k;
}
const name = detail.slice(start, pos);
if (name.length === 0 || name.length + sl < 3) {
pos += sl - 1;
continue;
}
const road = name + detail.slice(pos, pos + sl);
if (NAMELESS.some((p) => road.startsWith(p))) {
pos += sl - 1;
continue;
}
return road;
}
return '';
}
export type ParsedAddress = {
district: string;
street: string;
road: string;
/** 剥掉区名之后的具体地址(第 4 段起,'-' 回接) */
rest: string;
/** 再剥掉街道名之后的详细地点 */
detail: string;
};
/** 一行地址的三项解析结果;空串表示「这一档地址里读不出来」 */
export function parseAddress(address: string, vocab: Vocab): ParsedAddress {
const parts = splitParts(address ?? '');
const split = splitAddress(parts, vocab);
const street = (vocab.streetsByDistrict.get(split.district) ?? [])
.find((s) => split.rest.startsWith(s)) ?? '';
const detail = street ? split.rest.slice(street.length) : split.rest;
return {
district: split.district,
street,
road: roadOfAddress(detail),
rest: split.rest,
detail,
};
}
#!/usr/bin/env node
/**
* 命令行入口:解析参数、取用 Key、发出中断信号,然后把活交给 fill.runJob。
* Node 22.18+ 直接运行本文件,无需构建。
*
* 这一层只做「人怎么用它」的事,取值口径全在 fill.ts / address.ts / client.ts 里;
* 交付时只带 --input/--output/--cache 三个路径也能跑起来。
*/
import path from 'node:path';
import process from 'node:process';
import { fileURLToPath } from 'node:url';
import { interruptSignal, reportFailure, withSuffix } from './cli.ts';
import { isExcel } from './excel-store.ts';
import { runJob } from './fill.ts';
const USAGE = [
'用法: node amap-fill.ts --input <csv|xlsx> [选项]',
'按「地址解析 → 接口缓存 → 地图接口」的顺序补齐空白的行政区、街道、道路;表头缺这三列时自动追加。',
'能靠地址文本补齐的行不会调用接口,读出来可疑的同样不采用;一次运行的花费只等于地址补不齐或不可信的那些坐标。',
'',
' --input PATH 输入 UTF-8 CSV 或 Excel(必需)',
' --output PATH 输出新表格,默认写到源文件旁的 out/ 下,沿用源格式并加 .已补全;Excel 输出仅支持 .xlsx/.xlsm',
' --cache PATH SQLite 缓存路径,默认源文件旁的 cache/;重跑使用相同路径可续跑',
' --limit N 仅处理并输出前 N 行数据,用于样例验证',
' --workers N 最大并发请求数,默认 20',
' --qps N 全局每秒请求上限,默认 100;0 为不限',
' --infer-nearby 允许用附近已知点的归属补空白(默认关闭;半径见 targets.ts)',
' --sort-last 把仍有空白的记录排到末尾,完整记录在前(默认开启);--sort-last=false 关闭',
' --only-list PATH 只跑这份清单里的行:清单外的行本次不许问接口,输出仍是完整表格',
' --help 显示本帮助',
'',
'处理日志与三份清单(限流待重试、补不出、待复核)写在源文件旁的 .temp/ 下,out/ 只放正式表格;空白的类别不写文件。',
'把清单里的行单独再跑一次:--only-list "上一次的清单.csv",配合同一个 --input 与 --cache。',
'',
'Key 只从环境变量 AMAP_KEY 或终端隐藏输入取得,不写入配置、日志与缓存。',
'退出码:0 全部补齐;2 仍有缺失或失败;130 已中断;1 参数或文件错误。',
].join('\n');
type Flags = {
options: Map<string, string>;
inferNearby: boolean;
sortIncompleteLast: boolean;
help: boolean;
error: string;
};
const VALUE_NAMES = ['input', 'output', 'cache', 'limit', 'workers', 'qps', 'only-list'];
const BOOL_NAMES = ['infer-nearby', 'sort-last'];
/** 值选项必须带值,开关选项可写 --sort-last=false;未知选项一律拒绝而不是忽略。 */
export function parseCoreArgs(argv: string[]): Flags {
const options = new Map<string, string>();
let inferNearby = false;
let sortIncompleteLast = true;
let help = false;
for (let i = 0; i < argv.length; i += 1) {
const token = argv[i];
if (token === '--help' || token === '-h') {
help = true;
continue;
}
if (!token.startsWith('--')) return { options, inferNearby, sortIncompleteLast, help, error: `无法识别的参数:${token}` };
const [rawName, inline] = token.slice(2).split(/=(.*)/s);
if (VALUE_NAMES.includes(rawName)) {
const value = inline ?? argv[i + 1];
if (value === undefined || (inline === undefined && value.startsWith('--'))) {
return { options, inferNearby, sortIncompleteLast, help, error: `选项 ${token} 需要一个值` };
}
if (inline === undefined) i += 1;
options.set(rawName, value);
continue;
}
if (BOOL_NAMES.includes(rawName)) {
const value = inline === undefined ? 'true' : inline;
if (value !== 'true' && value !== 'false') {
return { options, inferNearby, sortIncompleteLast, help, error: `选项 --${rawName} 只能写 true 或 false` };
}
if (rawName === 'infer-nearby') inferNearby = value === 'true';
else sortIncompleteLast = value === 'true';
continue;
}
return { options, inferNearby, sortIncompleteLast, help, error: `无法识别的选项:${token}` };
}
return { options, inferNearby, sortIncompleteLast, help, error: '' };
}
function readNumber(options: Map<string, string>, name: string, fallback: number,
integer: boolean): { value: number; error: string } {
const raw = options.get(name);
if (raw === undefined) return { value: fallback, error: '' };
const value = Number(raw);
const valid = integer ? /^\d+$/.test(raw) && Number.isSafeInteger(value) : /^\d+(\.\d+)?$/.test(raw);
if (!valid) return { value: 0, error: `选项 --${name} 需要${integer ? '整数' : '数字'},得到 ${raw}` };
return { value, error: '' };
}
export async function main(argv: string[] = process.argv.slice(2)): Promise<number> {
const flags = parseCoreArgs(argv);
if (flags.help) {
process.stdout.write(`${USAGE}\n`);
return 0;
}
if (flags.error !== '') {
process.stderr.write(`${flags.error}\n${USAGE}\n`);
return 2;
}
const input = flags.options.get('input');
if (input === undefined) {
process.stderr.write(`以下参数必需: --input\n${USAGE}\n`);
return 2;
}
const limit = readNumber(flags.options, 'limit', 0, true);
const workers = readNumber(flags.options, 'workers', 20, true);
const qps = readNumber(flags.options, 'qps', 100, false);
const bad = [limit, workers, qps].find((item) => item.error !== '');
if (bad !== undefined) {
process.stderr.write(`${bad.error}\n`);
return 2;
}
const sourceFile = path.resolve(input);
const output = flags.options.get('output')
?? withSuffix(input, isExcel(input) ? '.已补全.xlsx' : '.已补全.csv',
path.join(path.dirname(sourceFile), 'out'));
// 三样产物都跟着源文件走:out/ 放表格,.temp/ 放过程文件,cache/ 放已查坐标
const cache = flags.options.get('cache')
?? path.join(path.dirname(sourceFile), 'cache', 'amap_regeo_cache.sqlite3');
const tempDir = path.join(path.dirname(sourceFile), '.temp');
const interrupt = interruptSignal();
try {
const report = await runJob(input, output, cache, {
limit: limit.value > 0 ? limit.value : null,
workers: workers.value,
qps: qps.value,
inferNearby: flags.inferNearby,
sortIncompleteLast: flags.sortIncompleteLast,
onlyList: flags.options.get('only-list') ?? '',
tempDir,
progress: (message) => process.stdout.write(`${message}\n`),
signal: interrupt.signal,
});
process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
return report.exit_code;
} catch (exc) {
if (interrupt.signal.aborted) {
process.stderr.write('已中断;再次使用相同输入和缓存路径即可继续。\n');
return 130;
}
return reportFailure(exc);
} finally {
interrupt.dispose();
}
}
const invokedDirectly = process.argv[1] !== undefined
&& path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
if (invokedDirectly) process.exitCode = await main();
/** CLI 共用的外壳:错误措辞、输出路径派生、Ctrl+C 转中断信号。命令行入口与启动器都用它。 */
import path from 'node:path';
import process from 'node:process';
import { QueryError } from './client.ts';
import { UserError } from './errors.ts';
/**
* 只原样打印经过审核的消息;其余错误仅报告类型,避免泄露凭证。
*
* 审核过的消息本身就写着下一步该做什么(缺 Key、路径不存在、限流等),
* 再补一句「文件是否被 Excel 占用」只会把人往错的方向引 —— 那句排查提示
* 只给没审核过的错误(多半是读写文件的系统错误)。
*/
export function reportFailure(exc: unknown, prefix = '无法完成'): number {
const reviewed = exc instanceof UserError || exc instanceof QueryError;
const detail = reviewed ? exc.message
: exc instanceof Error ? exc.name : '未知错误';
const hint = reviewed ? '' : '(请检查配置、路径权限,以及表格文件是否正被 Excel 占用)';
process.stderr.write(`${prefix}:${detail}${hint}\n`);
return 1;
}
/**
* 默认输出名:沿用源文件名与扩展名,只在尾部加标记。
* `directory` 不给时与源文件同目录;给了就落到那个目录(工具默认落在 out/)。
*/
export function withSuffix(file: string, suffix: string,
directory: string = path.dirname(file)): string {
const stem = path.basename(file, path.extname(file));
return path.join(directory, `${stem}${suffix}`);
}
/** Ctrl+C 时转为中断信号:保留已完成结果并写出文件,退出码 130。 */
export function interruptSignal(): { signal: AbortSignal; dispose(): void } {
const controller = new AbortController();
const onSigint = () => controller.abort();
process.on('SIGINT', onSigint);
return { signal: controller.signal, dispose: () => process.off('SIGINT', onSigint) };
}
/**
* 坐标规范化:把原始文本按十进制读到六位小数(四舍五入),并给出接口/缓存/合理盒要用的形态。
*
* 为什么不用 double 直接 toFixed:`Number('113.0000005')` 落在 113.0000005 略下方,
* toFixed 会给成 …000000,同一坐标在两台机器上算出不同缓存键就会重复付费。
* 这里在数字字符串上做舍入,不引入通用十进制类。
*/
import { UserError } from './errors.ts';
/** 与主程序 ingestCore 的合理盒同一组数:盒外的点主程序导入时必拒,先在这里挡掉就不必付费查 */
export const SANITY_BOX = { minLng: 113.6, maxLng: 114.7, minLat: 22.3, maxLat: 23.0 };
/** 六位小数的规范化坐标,接口与日志用的文本形态 */
export type Coords = readonly [string, string];
const DECIMAL = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/;
/** 整数部分(去前导零);先粗筛量级,避免把 1e9999999 这种写成定点串 */
function integerDigits(digits: string, point: number): string {
if (point <= 0) return '';
return digits.slice(0, point).replace(/^0+/, '');
}
/**
* 四舍五入到六位小数后的定点文本(不含符号)。
* digits 是小数点前后的数字串,point 是小数点位置(可为 0 或负)。
*/
function roundSix(digits: string, point: number): string {
const keep = point + 6;
if (keep <= 0) return '0.000000';
let head = digits.slice(0, keep).padEnd(keep, '0');
const firstDropped = digits.length > keep ? digits[keep] : '0';
if (firstDropped >= '5') {
let carry = 1;
const chars = head.split('');
for (let i = chars.length - 1; i >= 0 && carry > 0; i -= 1) {
const sum = Number(chars[i]) + carry;
chars[i] = String(sum % 10);
carry = Math.floor(sum / 10);
}
head = carry > 0 ? `${carry}${chars.join('')}` : chars.join('');
}
head = head.replace(/^0+/, '');
if (head === '') return '0.000000';
const padded = head.padStart(7, '0');
return `${padded.slice(0, padded.length - 6)}.${padded.slice(padded.length - 6)}`;
}
/** 读到六位小数;越界、非数、空值都抛 UserError */
export function normalizeCoordinate(raw: unknown, bound: number, name: string): string {
const text = typeof raw === 'number' ? (Number.isFinite(raw) ? String(raw) : '')
: typeof raw === 'string' ? raw.trim() : '';
const match = DECIMAL.exec(text);
if (match === null || (match[2] === '' && (match[3] === undefined || match[3] === ''))) {
throw new UserError(`${name}缺失、非数值或格式非法`);
}
const [, sign, integer, fraction, exponent] = match;
const point = integer.length + (exponent === undefined ? 0 : Number(exponent));
if (!Number.isSafeInteger(point) || point > 12) throw new UserError(`${name}超出可处理范围`);
const intDigits = integerDigits(`${integer}${fraction ?? ''}`, point);
if (intDigits.length > String(bound).length
|| (intDigits.length === String(bound).length && intDigits > String(bound))) {
throw new UserError(`${name}越界(绝对值需 ≤ ${bound})`);
}
const rounded = roundSix(`${integer}${fraction ?? ''}`, point);
// 舍入后再比一次:整位相等但带小数尾巴的(180.0000004)已不在合法范围内
if (Math.abs(Number(rounded)) > bound) throw new UserError(`${name}越界(绝对值需 ≤ ${bound})`);
return sign === '-' && rounded !== '0.000000' ? `-${rounded}` : rounded;
}
export function normalizeCoordinates(lng: unknown, lat: unknown): [string, string] {
return [normalizeCoordinate(lng, 180, '经度'), normalizeCoordinate(lat, 90, '纬度')];
}
/** 六位文本 → 微度整数(缓存主键);同一文本在任何机器上都得同一个数 */
export function toMicroDegrees(six: string): number {
const negative = six.startsWith('-');
const [whole, frac = ''] = six.replace('-', '').split('.');
const value = Number(`${whole}${frac.padEnd(6, '0').slice(0, 6)}`);
return negative ? -value : value;
}
export function insideSanityBox(coords: Coords): boolean {
const lng = Number(coords[0]);
const lat = Number(coords[1]);
return lng >= SANITY_BOX.minLng && lng <= SANITY_BOX.maxLng
&& lat >= SANITY_BOX.minLat && lat <= SANITY_BOX.maxLat;
}
/** CSV 读写与防覆盖路径校验;输出为 UTF-8 BOM、CRLF 行尾。 */
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { parse as parseCsv } from 'csv-parse/sync';
import { stringify as stringifyCsv } from 'csv-stringify/sync';
import { UserError } from './errors.ts';
import { COORDINATE_COLUMNS } from './targets.ts';
const BOM = '';
/** UTF-8 / UTF-8 BOM CSV:表头无重名,每条记录列数与表头一致。清单这类辅助文件用这个。 */
export function readTable(file: string, limit: number | null): { header: string[]; rows: string[][] } {
const content = fs.readFileSync(file, 'utf8');
const records = parseCsv(content, {
bom: true,
skip_empty_lines: false,
relax_quotes: false,
relax_column_count: true,
trim: false,
}) as string[][];
const header = records.shift() ?? [];
if (header.length === 0 || new Set(header).size !== header.length) {
throw new UserError('CSV 表头为空或含重名列');
}
const rows = limit === null ? records : records.slice(0, limit);
rows.forEach((row, position) => {
if (row.length !== header.length) {
throw new UserError(`第 ${position + 2} 条 CSV 记录列数与表头不一致`);
}
});
return { header, rows };
}
/** 数据源用的 CSV:在通用校验之上再要求经纬度列。 */
export function readCsv(file: string, limit: number | null): { header: string[]; rows: string[][] } {
const table = readTable(file, limit);
if (COORDINATE_COLUMNS.some((name) => !table.header.includes(name))) {
throw new UserError('CSV 必须包含经度、纬度列');
}
return table;
}
function pathKeys(file: string): string[] {
const resolved = path.resolve(file);
const keys = [process.platform === 'win32' ? resolved.toLowerCase() : resolved];
try {
const stat = fs.statSync(resolved);
keys.push(`${stat.dev}:${stat.ino}`);
} catch {
// 文件尚不存在(SQLite sidecar 常见):只比较规范化路径。
}
return keys;
}
/** 输入、输出、缓存与日志必须互不相同,禁止覆盖源文件。 */
export function validatePaths(source: string, output: string, cache: string,
tempDir: string): string {
const log = logPathFor(output, tempDir);
const names = [source, output, cache, log,
...['-journal', '-wal', '-shm'].map((suffix) => `${cache}${suffix}`)];
const keys = names.map(pathKeys);
for (let i = 0; i < keys.length; i += 1) {
for (let j = i + 1; j < keys.length; j += 1) {
if (keys[i].some((key) => keys[j].includes(key))) {
throw new UserError('输入、输出、缓存及日志路径必须不同,禁止覆盖源文件');
}
}
}
return log;
}
/**
* 处理日志落在临时目录:文件名跟着输出走,便于对上是哪一次运行。
* 输出目录只放正式交付的表格;日志、清单这类过程文件一律进 .temp。
*/
export function logPathFor(output: string, tempDir: string): string {
return path.join(tempDir, `${path.basename(output, path.extname(output))}.处理日志.csv`);
}
/** 先写同目录临时文件并 fsync,再原子替换,避免中断留下半份文件。 */
export function atomicWrite(file: string, body: string | Uint8Array): void {
const target = path.resolve(file);
const directory = path.dirname(target);
fs.mkdirSync(directory, { recursive: true });
const temporary = path.join(directory,
`${path.basename(target)}.${crypto.randomBytes(6).toString('hex')}.tmp`);
try {
const handle = fs.openSync(temporary, 'w');
try {
fs.writeFileSync(handle, body, 'utf8');
fs.fsyncSync(handle);
} finally {
fs.closeSync(handle);
}
fs.renameSync(temporary, target);
} finally {
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
}
}
/** UTF-8 BOM + CRLF 行尾的 CSV 输出。 */
export function atomicCsv(file: string, header: readonly string[], rows: readonly string[][]): void {
atomicWrite(file, BOM + stringifyCsv([header as string[], ...rows.map((row) => row as string[])],
{ record_delimiter: '\r\n' }));
}
/**
* 图形界面的一次运行:在 worker 线程里跑 runJob,把「正在做什么」实时送回界面。
*
* 放在 worker 里有两个理由:读表与写表那几段是同步的,主线程不能被它们占住 ——
* 否则页面连「停止」都点不动;另外整张表会吃掉几百 MB,跑完可以让线程连同堆一起还给系统。
* Key 只走 workerData 或一次消息,不进环境变量、不进配置、不进日志。
*/
import { runJob, type Report, type Stage } from './fill.ts';
import { AmapClient } from './client.ts';
import { UserError } from './errors.ts';
import type { Job } from './desktop-core.ts';
import { parentPort, workerData } from 'node:worker_threads';
export type WorkerIn = { type: 'stop' } | { type: 'key'; value: string };
export type WorkerOut =
| ({ type: 'stage' } & Stage)
| { type: 'log'; message: string }
| { type: 'key-needed' }
| { type: 'done'; report: Report }
/** detail 是给终端与维护者的技术原文;页面只显示 message 这一句人话 */
| { type: 'error'; message: string; detail?: string };
const port = parentPort;
if (port === null) throw new Error('desktop-worker.ts 只能作为 worker 线程运行');
const job = workerData as { job: Job; key: string };
const post = (message: WorkerOut): void => { port.postMessage(message); };
const controller = new AbortController();
let waitingFor = '';
let resolver: (value: string) => void = () => {};
port.on('message', (message: WorkerIn) => {
if (message.type === 'stop') {
controller.abort();
// 正在等人填 Key 时被停下:把人叫醒,否则线程会一直挂在等 Key 上
if (waitingFor === 'key') resolver('');
} else if (waitingFor === 'key') {
resolver(message.value);
}
});
/** 界面上没填 Key 时才问一次:问到之后只活在这一次运行里。 */
async function client(qps: number): Promise<AmapClient> {
const trimmed = job.key.trim();
if (trimmed !== '') return new AmapClient(trimmed, qps);
const given = await new Promise<string>((resolve) => {
resolver = resolve;
waitingFor = 'key';
post({ type: 'key-needed' });
});
waitingFor = '';
if (given.trim() === '') {
// 没 Key 时 runJob 会在这里中止,什么文件都还没写 —— 别让人以为表格已经出来了
throw new UserError(controller.signal.aborted
? '已按你的意思停下:还没有填高德 Key,接口一次都没问,本次没有写出文件'
: '界面上没填高德 Key,接口问不了,本次没有写出文件;填上 Key 再点一次开始,已查过的坐标不会再花钱');
}
return new AmapClient(given, qps);
}
try {
const report = await runJob(job.job.input, job.job.output, job.job.cache, {
...job.job.options,
clientFactory: client,
progress: (message) => post({ type: 'log', message }),
stage: (stage) => post({ type: 'stage', ...stage }),
signal: controller.signal,
});
post({ type: 'done', report });
} catch (exc) {
// 只把人话交给页面;未审核的错误留着完整原文给终端与维护者,绝不吞成一句「Error」
if (exc instanceof UserError) post({ type: 'error', message: exc.message });
else if (exc instanceof Error) {
post({ type: 'error', message: '程序内部错误', detail: `${exc.name}: ${exc.message}\n${exc.stack ?? ''}` });
} else {
post({ type: 'error', message: '程序内部错误', detail: String(exc) });
}
}
// 交完卷就松开通信口:线程连同它读过的那几百 MB 表格一起还给系统,界面下次运行再开一个新的
port.close();
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
No preview for this file type
No preview for this file type
No preview for this file type
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!