出站回调:
- 新增 warehouse_notify.json 文档(notify.ping/notify.reply),与 warehouse.json 互跳
- 回调体统一 { method, code, data },method 放 query,body 为业务数据
- MD5 签名: sign=MD5(appSecret+timestamp+bodyJson)
- 回调响应: {code:200} 成功,非200/非code:200 视为失败
- docs 页面支持模拟推送调试
搜索增强(searchStock/searchWarehouseStock):
- 直接查 stock_warehouse,不再依赖 stock_store
- 新增字段: gross_weight/box_spec/packing_requirements/prohibited_type
- 管理标识: is_sn_mgmt/is_shelf_life_mgmt/is_batch_mgmt
- 条码关联: wms_stock_barcodes
- 图片: wms_file_reference(business_type=stock)+wms_file,返回数组
- id 修正为 stock_warehouse.id
推送状态完善:
- handleApiMessage 增加 push_status 更新(2成功/3失败)
- 未配回调地址 → push_status=3 + error 原因
- 回调异常 catch 也更新 push_status=3 + 写日志
- 出站日志写入 wms_warehouse_log 表(WN-前缀)
消息列表:
- keyword 兼容 content/keyword,支持数组
- keyword 搜索 content/group_name/user_name 三列
- 支持 where+operator 结构化查询(parseWhereConditions)
- storeId=-1 查询无货主消息; storeId=0→IS NULL
- 日期范围: startDate/endDate
其他:
- silent 动作: AI 识别无需回复时跳过回执
- ai_enabled 灰度开关(群级)
- bindCode 文档修正
- store_name 改用 StoreWarehouse.store_remask
2288 lines
73 KiB
JavaScript
2288 lines
73 KiB
JavaScript
const {
|
||
Controller,
|
||
} = require('egg');
|
||
const fs = require('fs').promises;
|
||
const path = require('path');
|
||
|
||
function escapeHtml(value) {
|
||
return String(value || '')
|
||
.replace(/&/g, '&')
|
||
.replace(/</g, '<')
|
||
.replace(/>/g, '>')
|
||
.replace(/"/g, '"')
|
||
.replace(/'/g, ''');
|
||
}
|
||
|
||
/**
|
||
* 清洗 window 标签使用的跳转地址,避免注入危险协议或控制字符。
|
||
* @param {string} value 待清洗的地址。
|
||
* @return {string} 允许使用的地址,非法时返回空字符串。
|
||
*/
|
||
function sanitizeWindowHref(value) {
|
||
const href = String(value || '').trim();
|
||
if (!href) {
|
||
return '';
|
||
}
|
||
|
||
const hasControlCharacter = Array.from(href).some(character => {
|
||
const code = character.charCodeAt(0);
|
||
return code <= 0x1f || code === 0x7f;
|
||
});
|
||
if (hasControlCharacter || /^(javascript|data|vbscript):/i.test(href)) {
|
||
return '';
|
||
}
|
||
|
||
return href;
|
||
}
|
||
|
||
/**
|
||
* 从 window 标签属性中提取跳转地址。
|
||
* @param {string} attributeText 标签属性文本。
|
||
* @return {string} 提取到的地址,未找到时返回空字符串。
|
||
*/
|
||
function extractWindowHref(attributeText) {
|
||
const attributes = String(attributeText || '');
|
||
const match = attributes.match(/(?:href|data-href|data-window-href)\s*=\s*("([^"]*)"|'([^']*)')/i);
|
||
if (!match) {
|
||
return '';
|
||
}
|
||
|
||
return match[2] || match[3] || '';
|
||
}
|
||
|
||
/**
|
||
* 渲染可点击的 window 自定义元素。
|
||
* @param {string} label 元素展示文案。
|
||
* @param {string} href 点击后打开的地址。
|
||
* @param {string} [className] 额外样式类名。
|
||
* @return {string} 生成的 HTML 片段。
|
||
*/
|
||
function renderWindowElement(label, href, className = '') {
|
||
const safeHref = sanitizeWindowHref(href);
|
||
const safeLabel = escapeHtml(label || safeHref);
|
||
if (!safeHref) {
|
||
return safeLabel;
|
||
}
|
||
|
||
const classes = [ 'window-link' ];
|
||
if (className) {
|
||
classes.push(className);
|
||
}
|
||
|
||
return `<window class="${classes.join(' ')}" role="link" tabindex="0" data-window-href="${escapeHtml(safeHref)}">${safeLabel}</window>`;
|
||
}
|
||
|
||
/**
|
||
* 将文本中的 <window> 标签安全渲染为可点击元素。
|
||
* @param {string} value 原始文本。
|
||
* @return {string} 处理后的 HTML。
|
||
*/
|
||
function renderTextWithWindowTags(value) {
|
||
const text = String(value || '');
|
||
if (!text.includes('<window')) {
|
||
return escapeHtml(text);
|
||
}
|
||
|
||
const pattern = /<window\b([^>]*)>([\s\S]*?)<\/window>/gi;
|
||
let lastIndex = 0;
|
||
let rendered = '';
|
||
let match;
|
||
|
||
while ((match = pattern.exec(text)) !== null) {
|
||
rendered += escapeHtml(text.slice(lastIndex, match.index));
|
||
|
||
const attributes = match[1] || '';
|
||
const content = match[2] || '';
|
||
const href = sanitizeWindowHref(extractWindowHref(attributes) || content.trim());
|
||
const label = content.trim() || href;
|
||
|
||
rendered += renderWindowElement(label, href);
|
||
lastIndex = pattern.lastIndex;
|
||
}
|
||
|
||
rendered += escapeHtml(text.slice(lastIndex));
|
||
return rendered;
|
||
}
|
||
|
||
function toArray(value) {
|
||
return Array.isArray(value) ? value : [];
|
||
}
|
||
|
||
function slugify(value) {
|
||
return String(value || '')
|
||
.toLowerCase()
|
||
.replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
|
||
.replace(/(^-|-$)/g, '');
|
||
}
|
||
|
||
function isValidDocName(docName) {
|
||
return /^[a-zA-Z0-9_-]+$/.test(docName || '');
|
||
}
|
||
|
||
function getDocFilePath(app, docName) {
|
||
return path.join(app.baseDir, 'methods', `${docName}.json`);
|
||
}
|
||
|
||
function getDocChangesFilePath(app, docName) {
|
||
return path.join(app.baseDir, 'methods', 'changes', `${docName}.json`);
|
||
}
|
||
|
||
/**
|
||
* 获取 docs 目录的绝对路径。
|
||
* @param {Egg.Application} app Egg 应用实例。
|
||
* @return {string} docs 根目录绝对路径。
|
||
*/
|
||
function getDocsRootPath(app) {
|
||
return path.resolve(app.baseDir, 'docs');
|
||
}
|
||
|
||
/**
|
||
* 递归解码 URL 路径片段,尽量还原编码穿越路径。
|
||
* @param {string} input 待解码的路径片段。
|
||
* @return {string|null} 解码后的路径片段,解码失败时返回 null。
|
||
*/
|
||
function decodeDocsPath(input) {
|
||
let value = String(input || '').trim();
|
||
if (!value) {
|
||
return '';
|
||
}
|
||
|
||
for (let index = 0; index < 3; index += 1) {
|
||
try {
|
||
const decoded = decodeURIComponent(value);
|
||
if (decoded === value) {
|
||
break;
|
||
}
|
||
value = decoded;
|
||
} catch (error) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
return value;
|
||
}
|
||
|
||
/**
|
||
* 将 docs 相对路径转换为可访问 URL。
|
||
* @param {string} relativePath docs 相对路径。
|
||
* @return {string} 可直接用于 href 的路径。
|
||
*/
|
||
function toDocsHref(relativePath) {
|
||
return String(relativePath || '')
|
||
.split(/[\\/]+/)
|
||
.filter(Boolean)
|
||
.map(segment => encodeURIComponent(segment))
|
||
.join('/');
|
||
}
|
||
|
||
/**
|
||
* 按扩展名返回 docs 文件的响应类型。
|
||
* @param {string} filePath 文件绝对路径。
|
||
* @return {string} Content-Type 值。
|
||
*/
|
||
function getDocsContentType(filePath) {
|
||
const ext = path.extname(filePath).toLowerCase();
|
||
if (ext === '.md' || ext === '.markdown') {
|
||
return 'text/markdown; charset=utf-8';
|
||
}
|
||
|
||
if (ext === '.json') {
|
||
return 'application/json; charset=utf-8';
|
||
}
|
||
|
||
return 'text/plain; charset=utf-8';
|
||
}
|
||
|
||
/**
|
||
* 解析并校验 docs 文件路径,阻止路径穿越。
|
||
* @param {Egg.Application} app Egg 应用实例。
|
||
* @param {string} relativePath docs 相对路径。
|
||
* @return {{ ok: boolean, filePath?: string, relativePath?: string, message?: string }} 解析结果。
|
||
*/
|
||
function resolveDocsFilePath(app, relativePath) {
|
||
const decodedPath = decodeDocsPath(relativePath);
|
||
if (decodedPath === null || !decodedPath) {
|
||
return {
|
||
ok: false,
|
||
message: '无效文档路径',
|
||
};
|
||
}
|
||
|
||
if (decodedPath.includes('\\') || path.isAbsolute(decodedPath)) {
|
||
return {
|
||
ok: false,
|
||
message: '无效文档路径',
|
||
};
|
||
}
|
||
|
||
const docsRootPath = getDocsRootPath(app);
|
||
const filePath = path.resolve(docsRootPath, decodedPath);
|
||
const relativeToRoot = path.relative(docsRootPath, filePath);
|
||
|
||
if (relativeToRoot.startsWith('..') || path.isAbsolute(relativeToRoot)) {
|
||
return {
|
||
ok: false,
|
||
message: '路径越界',
|
||
};
|
||
}
|
||
|
||
return {
|
||
ok: true,
|
||
filePath,
|
||
relativePath: decodedPath,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 递归收集 docs 目录下的所有文件。
|
||
* @param {string} dirPath 当前扫描目录。
|
||
* @param {string} baseDir docs 根目录。
|
||
* @return {Promise<Array<{ relativePath: string, filePath: string }>>} 文件列表。
|
||
*/
|
||
async function collectDocsFiles(dirPath, baseDir) {
|
||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||
const files = [];
|
||
|
||
for (const entry of entries) {
|
||
const entryPath = path.join(dirPath, entry.name);
|
||
if (entry.isDirectory()) {
|
||
const nestedFiles = await collectDocsFiles(entryPath, baseDir);
|
||
files.push(...nestedFiles);
|
||
continue;
|
||
}
|
||
|
||
if (entry.isFile()) {
|
||
files.push({
|
||
relativePath: path.relative(baseDir, entryPath),
|
||
filePath: entryPath,
|
||
});
|
||
}
|
||
}
|
||
|
||
return files;
|
||
}
|
||
|
||
/**
|
||
* 生成 docs 索引页 HTML。
|
||
* @param {Array<{ relativePath: string }>} files docs 文件列表。
|
||
* @return {string} HTML 文档。
|
||
*/
|
||
function renderDocsIndexPage(files) {
|
||
const listHtml = files.length
|
||
? files.map(file => {
|
||
const href = `/docs/${toDocsHref(file.relativePath)}`;
|
||
return `<li>${renderWindowElement(file.relativePath, href, 'doc-file-link')}</li>`;
|
||
}).join('')
|
||
: '<li class="muted">docs 目录下暂无文件</li>';
|
||
|
||
return `<!doctype html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="UTF-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||
<title>Docs 索引</title>
|
||
<style>
|
||
:root {
|
||
color-scheme: light;
|
||
--bg: #f5f7fb;
|
||
--panel: #ffffff;
|
||
--text: #182230;
|
||
--muted: #637083;
|
||
--line: #d9e1ec;
|
||
--accent: #1756b3;
|
||
}
|
||
* { box-sizing: border-box; }
|
||
body {
|
||
margin: 0;
|
||
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||
color: var(--text);
|
||
background: linear-gradient(180deg, #eef4ff 0%, var(--bg) 220px, var(--bg) 100%);
|
||
}
|
||
main {
|
||
max-width: 1080px;
|
||
margin: 0 auto;
|
||
padding: 32px 20px 40px;
|
||
}
|
||
.hero {
|
||
background: var(--panel);
|
||
border: 1px solid var(--line);
|
||
border-radius: 16px;
|
||
padding: 24px;
|
||
box-shadow: 0 10px 30px rgba(22, 50, 98, 0.08);
|
||
}
|
||
h1 {
|
||
margin: 0 0 8px;
|
||
font-size: 28px;
|
||
}
|
||
p {
|
||
margin: 0;
|
||
color: var(--muted);
|
||
line-height: 1.6;
|
||
}
|
||
ul {
|
||
list-style: none;
|
||
padding: 0;
|
||
margin: 22px 0 0;
|
||
display: grid;
|
||
gap: 10px;
|
||
}
|
||
li a {
|
||
display: block;
|
||
padding: 12px 14px;
|
||
border-radius: 12px;
|
||
border: 1px solid var(--line);
|
||
background: #fbfcff;
|
||
color: var(--accent);
|
||
text-decoration: none;
|
||
word-break: break-all;
|
||
}
|
||
window.window-link {
|
||
display: block;
|
||
padding: 12px 14px;
|
||
border-radius: 12px;
|
||
border: 1px solid var(--line);
|
||
background: #fbfcff;
|
||
color: var(--accent);
|
||
text-decoration: none;
|
||
word-break: break-all;
|
||
}
|
||
window.window-link:hover {
|
||
border-color: #b9cdf0;
|
||
background: #f2f7ff;
|
||
}
|
||
window.window-link:focus {
|
||
outline: 2px solid #8fb4ea;
|
||
outline-offset: 2px;
|
||
}
|
||
.muted {
|
||
color: var(--muted);
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<main>
|
||
<section class="hero">
|
||
<h1>docs 目录索引</h1>
|
||
<p>以下文件来自 docs 根目录,点击即可直接查看对应内容。</p>
|
||
<ul>${listHtml}</ul>
|
||
</section>
|
||
</main>
|
||
<script>
|
||
(function() {
|
||
function openWindowHref(target) {
|
||
var href = target && target.getAttribute('data-window-href');
|
||
if (!href) {
|
||
return;
|
||
}
|
||
|
||
var popup = window.open(href, '_blank', 'noopener,noreferrer');
|
||
if (popup) {
|
||
popup.opener = null;
|
||
popup.focus();
|
||
}
|
||
}
|
||
|
||
document.addEventListener('click', function(event) {
|
||
var target = event.target.closest('[data-window-href]');
|
||
if (!target) {
|
||
return;
|
||
}
|
||
|
||
event.preventDefault();
|
||
openWindowHref(target);
|
||
});
|
||
|
||
document.addEventListener('keydown', function(event) {
|
||
var target = event.target.closest('[data-window-href]');
|
||
if (!target) {
|
||
return;
|
||
}
|
||
|
||
if (event.key !== 'Enter' && event.key !== ' ') {
|
||
return;
|
||
}
|
||
|
||
event.preventDefault();
|
||
openWindowHref(target);
|
||
});
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>`;
|
||
}
|
||
|
||
/**
|
||
* 生成 docs 文件内容响应。
|
||
* @param {Egg.Context} ctx 当前请求上下文。
|
||
* @param {string} filePath 文件绝对路径。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async function sendDocsFile(ctx, filePath) {
|
||
const content = await fs.readFile(filePath, 'utf8');
|
||
ctx.set('Content-Type', getDocsContentType(filePath));
|
||
ctx.body = content;
|
||
}
|
||
|
||
function normalizeGroups(docData) {
|
||
if (docData && docData.methods && Array.isArray(docData.methods.groups)) {
|
||
return docData.methods.groups.map(group => ({
|
||
groupName: group.groupName || group.module || 'Default',
|
||
module: group.module || '',
|
||
list: toArray(group.list),
|
||
}));
|
||
}
|
||
|
||
if (docData && Array.isArray(docData.endpoints)) {
|
||
return [{
|
||
groupName: docData.groupName || 'Endpoints',
|
||
module: docData.module || '',
|
||
list: docData.endpoints,
|
||
}];
|
||
}
|
||
|
||
return [];
|
||
}
|
||
|
||
/**
|
||
* 解析文档对应的统一入口路径,优先使用文档内声明的 http.path。
|
||
* @param {object} docData 文档 JSON 数据。
|
||
* @return {string} 统一入口路径。
|
||
*/
|
||
function resolveDocEntryPath(docData) {
|
||
const httpPath = String(docData?.http?.path || '').trim();
|
||
if (httpPath.startsWith('/')) {
|
||
return httpPath;
|
||
}
|
||
|
||
if (docData?.module === 'qimen') {
|
||
return '/qimen';
|
||
}
|
||
|
||
if (docData?.module === 'gateway') {
|
||
return '/internal/v1/gateway';
|
||
}
|
||
|
||
return '/system';
|
||
}
|
||
|
||
/**
|
||
* 渲染 seeAlso 交叉引用链接。
|
||
* @param {Array<{name: string, path: string, description: string}>|undefined} seeAlso 交叉引用列表。
|
||
* @return {string} HTML 片段。
|
||
*/
|
||
function renderSeeAlsoLinks(seeAlso) {
|
||
if (!Array.isArray(seeAlso) || seeAlso.length === 0) return '';
|
||
const links = seeAlso.map(item => {
|
||
const href = `/api/docs/${(item.path || '').replace(/^\/?methods\//, '').replace(/\.json$/, '')}`;
|
||
return `<a href="${escapeHtml(href)}" class="see-also-link">${escapeHtml(item.name)}</a>`;
|
||
}).join('');
|
||
return `<div class="see-also"><span class="see-also-label">关联文档:</span>${links}</div>`;
|
||
}
|
||
|
||
/**
|
||
* 渲染键值表格。
|
||
* @param {Array<object>} items 数据项列表。
|
||
* @param {{ name: string, type: string, required: string, description: string }} keyMap 字段映射。
|
||
* @return {string} 表格行 HTML。
|
||
*/
|
||
function renderKeyValueRows(items, keyMap) {
|
||
if (!items.length) {
|
||
return '<tr><td colspan="4" class="muted">暂无数据</td></tr>';
|
||
}
|
||
|
||
return items.map(item => {
|
||
return `<tr>
|
||
<td>${escapeHtml(item[keyMap.name] || '')}</td>
|
||
<td>${escapeHtml(item[keyMap.type] || '')}</td>
|
||
<td>${item[keyMap.required] ? '是' : '否'}</td>
|
||
<td>${renderTextWithWindowTags(item[keyMap.description] || '')}</td>
|
||
</tr>`;
|
||
}).join('');
|
||
}
|
||
|
||
/**
|
||
* 渲染全局 Header 控件区域。
|
||
* @param {Array<object>} globalHeaders 全局 Header 定义。
|
||
* @return {string} HTML 片段。
|
||
*/
|
||
function renderGlobalHeadersControls(globalHeaders) {
|
||
const headers = toArray(globalHeaders);
|
||
if (!headers.length) {
|
||
return '<p class="muted">当前文档未定义额外全局 Header</p>';
|
||
}
|
||
|
||
return `<div class="global-headers-grid">${headers.map(item => {
|
||
const name = item.name || '';
|
||
const type = item.type || 'string';
|
||
const required = !!item.required;
|
||
const description = item.description || '';
|
||
const options = toArray(item.list);
|
||
|
||
const field = options.length
|
||
? `<select class="global-header-control" data-header-name="${escapeHtml(name)}" data-required="${required ? 'true' : 'false'}">
|
||
<option value="">请选择</option>
|
||
${options.map(option => `<option value="${escapeHtml(option.value || '')}">${escapeHtml(option.name || option.value || '')}</option>`).join('')}
|
||
</select>`
|
||
: `<input class="global-header-control" type="text" data-header-name="${escapeHtml(name)}" data-required="${required ? 'true' : 'false'}" placeholder="请输入 ${escapeHtml(name)}" />`;
|
||
|
||
return `<label class="global-header-item">
|
||
<span>${escapeHtml(name)}${required ? ' *' : ''}</span>
|
||
${field}
|
||
<small class="muted">${renderTextWithWindowTags(description)} (${escapeHtml(type)})</small>
|
||
</label>`;
|
||
}).join('')}</div>`;
|
||
}
|
||
|
||
/**
|
||
* 渲染单个接口卡片。
|
||
* @param {object} item 接口定义。
|
||
* @param {string} entryPath 统一入口路径。
|
||
* @param {string} moduleName 文档所属模块名。
|
||
* @return {string} HTML 片段。
|
||
*/
|
||
function renderMethodCard(item, entryPath, moduleName) {
|
||
const headers = toArray(item.headers);
|
||
const params = toArray(item.params);
|
||
const response = toArray(item.response);
|
||
const errors = toArray(item.errors);
|
||
const methodName = item.method || item.name || 'unknown';
|
||
const description = item.description || '';
|
||
const isQimen = moduleName === 'qimen';
|
||
const isOpenapi = moduleName === 'openapi';
|
||
const isWarehouse = moduleName === 'warehouse' || moduleName === 'warehouse_notify';
|
||
const isExternalApi = isOpenapi || isWarehouse;
|
||
const queryHint = isQimen
|
||
? 'app_key=xxx&method=...&v=2.0&format=json&sign_method=md5&sign=xxx×tamp=1700000000'
|
||
: isExternalApi
|
||
? `app_key=&method=${methodName}&v=1.0×tamp=1700000000`
|
||
: `method=${methodName}&v=1.0×tamp=1700000000`;
|
||
const queryLabel = isExternalApi ? 'Query 参数(自动生成)' : 'Query 参数';
|
||
const queryReadonlyAttr = isExternalApi ? ' readonly data-auto-generated="true" aria-label="自动生成"' : '';
|
||
|
||
return `<section class="method-card" id="${escapeHtml(methodName)}" data-method="${escapeHtml(methodName)}" data-desc="${escapeHtml(description)}" data-module="${escapeHtml(moduleName || '')}" data-endpoint="${escapeHtml(entryPath)}" data-login-required="${item.isNeedLogin ? 'true' : 'false'}">
|
||
<div class="method-header">
|
||
<div>
|
||
<h3>${escapeHtml(methodName)}</h3>
|
||
<p class="method-desc">${renderTextWithWindowTags(description)}</p>
|
||
</div>
|
||
<div class="badges">
|
||
<span class="badge">入口: ${escapeHtml(entryPath)}</span>
|
||
<span class="badge">鉴权: ${item.isNeedAuth ? '是' : '否'}</span>
|
||
<span class="badge">登录: ${item.isNeedLogin ? '是' : '否'}</span>
|
||
</div>
|
||
</div>
|
||
|
||
<details>
|
||
<summary>Headers (${headers.length})</summary>
|
||
<table>
|
||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||
<tbody>${renderKeyValueRows(headers, {
|
||
name: 'name',
|
||
type: 'type',
|
||
required: 'required',
|
||
description: 'description',
|
||
})}</tbody>
|
||
</table>
|
||
</details>
|
||
|
||
<details>
|
||
<summary>Params (${params.length})</summary>
|
||
<table>
|
||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||
<tbody>${renderKeyValueRows(params, {
|
||
name: 'name',
|
||
type: 'type',
|
||
required: 'required',
|
||
description: 'description',
|
||
})}</tbody>
|
||
</table>
|
||
</details>
|
||
|
||
<details>
|
||
<summary>Response (${response.length})</summary>
|
||
<table>
|
||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||
<tbody>${renderKeyValueRows(response, {
|
||
name: 'name',
|
||
type: 'type',
|
||
required: 'required',
|
||
description: 'description',
|
||
})}</tbody>
|
||
</table>
|
||
</details>
|
||
|
||
<details>
|
||
<summary>Errors (${errors.length})</summary>
|
||
<table>
|
||
<thead><tr><th>名称</th><th>类型</th><th>必填</th><th>说明</th></tr></thead>
|
||
<tbody>${renderKeyValueRows(errors, {
|
||
name: 'code',
|
||
type: 'type',
|
||
required: 'required',
|
||
description: 'message',
|
||
})}</tbody>
|
||
</table>
|
||
</details>
|
||
|
||
${moduleName === 'warehouse_notify' ? `<details class="debug-panel">
|
||
<summary>模拟推送</summary>
|
||
<div class="debug-form">
|
||
<label>notify_url(目标回调地址)</label>
|
||
<input class="req-query notify-url-input" type="text" placeholder="http://your-server.com/notify" />
|
||
<label>app_key</label>
|
||
<input class="req-app-key" type="text" placeholder="AK20260807001" autocomplete="off" />
|
||
<label>self_app_secret</label>
|
||
<input class="req-self-app-secret" type="password" placeholder="密钥" autocomplete="off" />
|
||
<label>Body (JSON) — 预填示例,可修改</label>
|
||
<textarea class="req-body" rows="8" placeholder='{}'>${escapeHtml(JSON.stringify(item.example && item.example.data ? { code: 200, data: item.example.data } : {}, null, 2))}</textarea>
|
||
<div class="debug-actions">
|
||
<button type="button" class="send-btn notify-send-btn" data-method="${escapeHtml(methodName)}">发送模拟推送</button>
|
||
<span class="muted">模拟 WMS 向 notify_url 推送通知,sign 在浏览器端 MD5 计算</span>
|
||
</div>
|
||
<pre class="req-result muted">点击发送后显示响应</pre>
|
||
</div>
|
||
</details>` : `<details class="debug-panel">
|
||
<summary>在线调试</summary>
|
||
<div class="debug-form">
|
||
<label>${queryLabel}</label>
|
||
<input class="req-query" type="text" placeholder="${escapeHtml(queryHint)}"${queryReadonlyAttr} />
|
||
|
||
${isExternalApi ? `<label>app_key(仅外部 API 页面本地保存)</label>
|
||
<input class="req-app-key" type="text" placeholder="请输入 app_key" autocomplete="off" />
|
||
<label>self_app_secret(仅本地签名计算,不会发送)</label>
|
||
<input class="req-self-app-secret" type="password" placeholder="请输入 self_app_secret" autocomplete="off" />` : ''}
|
||
|
||
<label>Body (JSON)</label>
|
||
<textarea class="req-body" rows="6" placeholder='{}'></textarea>
|
||
|
||
<div class="debug-actions">
|
||
<button type="button" class="send-btn">发送 POST 请求</button>
|
||
<span class="muted">${item.isNeedLogin ? '该接口需要登录,未设置 Token 将阻止请求' : '该接口无需登录,可不设置 Token 直接调试'}</span>
|
||
</div>
|
||
|
||
<pre class="req-result muted">点击发送后显示响应</pre>
|
||
</div>
|
||
</details>`}
|
||
</section>`;
|
||
}
|
||
|
||
/**
|
||
* 渲染 API 文档页面。
|
||
* @param {{ docName: string, docData: object, groups: Array<object>, docs: Array<string>, entryPath: string }} options 渲染参数。
|
||
* @return {string} HTML 文档。
|
||
*/
|
||
function renderHtmlPage({
|
||
docName,
|
||
docData,
|
||
groups,
|
||
docs,
|
||
entryPath,
|
||
}) {
|
||
const isOpenapi = docData.module === 'openapi';
|
||
const isWarehouse = docData.module === 'warehouse' || docData.module === 'warehouse_notify';
|
||
const isExternalApi = isOpenapi || isWarehouse;
|
||
const methodsCount = groups.reduce((sum, group) => sum + toArray(group.list).length, 0);
|
||
const globalHeaders = toArray(docData.headers);
|
||
const globalHeadersControls = renderGlobalHeadersControls(globalHeaders);
|
||
const rawUrl = `/api/docs/${encodeURIComponent(docName)}/raw`;
|
||
const changesUrl = `/api/docs/${encodeURIComponent(docName)}/changes`;
|
||
const navHtml = isExternalApi ? '' : docs.filter(name => name !== 'openapi' && name !== 'warehouse' && name !== 'warehouse_notify').map(name => {
|
||
const activeClass = name === docName ? 'active' : '';
|
||
return `<a class="tab ${activeClass}" href="/api/docs/${encodeURIComponent(name)}">${escapeHtml(name)}</a>`;
|
||
}).join('');
|
||
|
||
const sidebarHtml = groups.map((group, index) => {
|
||
const list = toArray(group.list);
|
||
const groupKey = slugify(group.module || group.groupName || `group-${index}`) || `group-${index}`;
|
||
const methodsHtml = list.map(item => {
|
||
const methodName = item.method || item.name || 'unknown';
|
||
const desc = item.description || '';
|
||
return `<li class="nav-item" data-method="${escapeHtml(methodName)}" data-desc="${escapeHtml(desc)}">
|
||
<a href="#${escapeHtml(methodName)}" title="${escapeHtml(desc)}">${escapeHtml(methodName)}</a>
|
||
</li>`;
|
||
}).join('');
|
||
|
||
return `<details class="nav-group" data-group-key="${escapeHtml(groupKey)}" ${index === 0 ? 'open' : ''}>
|
||
<summary>${escapeHtml(group.groupName)} <span class="count">${list.length}</span></summary>
|
||
<ul>${methodsHtml || '<li class="muted">暂无方法</li>'}</ul>
|
||
</details>`;
|
||
}).join('');
|
||
|
||
const groupHtml = groups.map(group => {
|
||
const list = toArray(group.list);
|
||
const groupKey = slugify(group.module || group.groupName) || 'group';
|
||
const cards = list.map(item => renderMethodCard(item, entryPath, docData.module)).join('');
|
||
return `<section class="group-block" data-group-key="${escapeHtml(groupKey)}">
|
||
<h2>${escapeHtml(group.groupName)} <small>${escapeHtml(group.module || '')}</small></h2>
|
||
${cards || '<p class="muted">该分组暂无方法定义</p>'}
|
||
</section>`;
|
||
}).join('');
|
||
|
||
return `<!doctype html>
|
||
<html lang="zh-CN">
|
||
<head>
|
||
<meta charset="UTF-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||
<title>${escapeHtml(docName)} API 文档</title>
|
||
<style>
|
||
:root {
|
||
--bg: #f4f6fb;
|
||
--card: #ffffff;
|
||
--line: #dbe1ee;
|
||
--text: #1f2a44;
|
||
--muted: #62708a;
|
||
--accent: #1565c0;
|
||
--accent-soft: #e8f1fc;
|
||
}
|
||
* { box-sizing: border-box; }
|
||
body {
|
||
margin: 0;
|
||
font-family: "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
|
||
color: var(--text);
|
||
background: radial-gradient(circle at 20% 0%, #e9f2ff 0, var(--bg) 45%), var(--bg);
|
||
}
|
||
.container { max-width: 1180px; margin: 0 auto; padding: 24px; }
|
||
.hero {
|
||
background: var(--card);
|
||
border: 1px solid var(--line);
|
||
border-radius: 12px;
|
||
padding: 20px;
|
||
box-shadow: 0 6px 20px rgba(18, 48, 102, 0.08);
|
||
}
|
||
.hero h1 { margin: 0 0 8px; }
|
||
.meta { color: var(--muted); display: flex; gap: 16px; flex-wrap: wrap; }
|
||
.tabs { margin-top: 16px; display: flex; gap: 10px; flex-wrap: wrap; }
|
||
.tab {
|
||
text-decoration: none;
|
||
color: var(--accent);
|
||
border: 1px solid #b9d4f3;
|
||
background: #f5faff;
|
||
padding: 7px 12px;
|
||
border-radius: 999px;
|
||
font-size: 14px;
|
||
}
|
||
.tab.active { background: var(--accent); color: white; border-color: var(--accent); }
|
||
.global-auth {
|
||
margin-top: 14px;
|
||
border: 1px solid #c9dbf3;
|
||
background: #f6faff;
|
||
border-radius: 10px;
|
||
padding: 12px;
|
||
}
|
||
.global-auth h3 { margin: 0 0 8px; font-size: 15px; }
|
||
.global-auth .row {
|
||
display: flex;
|
||
gap: 10px;
|
||
flex-wrap: wrap;
|
||
align-items: center;
|
||
}
|
||
.global-auth input {
|
||
flex: 1;
|
||
min-width: 300px;
|
||
padding: 8px 10px;
|
||
border: 1px solid #b5ccec;
|
||
border-radius: 8px;
|
||
font-size: 13px;
|
||
}
|
||
.global-auth button,
|
||
.doc-tools button {
|
||
border: 1px solid #9fc2eb;
|
||
background: #fff;
|
||
color: #174c94;
|
||
border-radius: 8px;
|
||
padding: 8px 12px;
|
||
cursor: pointer;
|
||
}
|
||
.doc-tools {
|
||
margin-top: 14px;
|
||
border: 1px solid #d7e4f7;
|
||
background: #fcfdff;
|
||
border-radius: 10px;
|
||
padding: 12px;
|
||
}
|
||
.doc-tools h3 { margin: 0 0 8px; font-size: 15px; }
|
||
.doc-tools-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
flex-wrap: wrap;
|
||
margin-bottom: 8px;
|
||
}
|
||
.global-headers-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||
gap: 10px;
|
||
margin-bottom: 8px;
|
||
}
|
||
.global-header-item {
|
||
display: grid;
|
||
gap: 6px;
|
||
font-size: 13px;
|
||
color: #21466f;
|
||
}
|
||
.global-header-item span {
|
||
font-weight: 600;
|
||
}
|
||
.global-header-item input,
|
||
.global-header-item select {
|
||
border: 1px solid #b5ccec;
|
||
border-radius: 8px;
|
||
padding: 8px 10px;
|
||
font-size: 13px;
|
||
background: #fff;
|
||
color: #1f2a44;
|
||
}
|
||
.global-header-item small {
|
||
line-height: 1.2;
|
||
}
|
||
.group-block { margin-top: 18px; }
|
||
.layout {
|
||
margin-top: 16px;
|
||
display: grid;
|
||
grid-template-columns: 320px 1fr;
|
||
gap: 16px;
|
||
align-items: start;
|
||
}
|
||
.sidebar {
|
||
position: sticky;
|
||
top: 12px;
|
||
background: var(--card);
|
||
border: 1px solid var(--line);
|
||
border-radius: 12px;
|
||
padding: 12px;
|
||
max-height: calc(100vh - 24px);
|
||
overflow: auto;
|
||
box-shadow: 0 6px 20px rgba(18, 48, 102, 0.06);
|
||
}
|
||
.search-box {
|
||
display: grid;
|
||
gap: 8px;
|
||
margin-bottom: 10px;
|
||
}
|
||
.search-box input {
|
||
width: 100%;
|
||
border: 1px solid #b5ccec;
|
||
border-radius: 8px;
|
||
padding: 8px 10px;
|
||
font-size: 13px;
|
||
}
|
||
.search-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.search-actions button {
|
||
border: 1px solid #b5ccec;
|
||
border-radius: 8px;
|
||
background: #fff;
|
||
color: #174c94;
|
||
padding: 6px 10px;
|
||
cursor: pointer;
|
||
font-size: 12px;
|
||
}
|
||
.nav-group {
|
||
border: 1px solid #d7e4f7;
|
||
border-radius: 8px;
|
||
background: #fcfdff;
|
||
padding: 8px;
|
||
margin-bottom: 8px;
|
||
}
|
||
.nav-group summary {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
align-items: center;
|
||
color: #1a4c8f;
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
}
|
||
.nav-group .count {
|
||
background: #e9f2ff;
|
||
border: 1px solid #c7dbf5;
|
||
border-radius: 999px;
|
||
padding: 2px 8px;
|
||
font-size: 11px;
|
||
color: #174c94;
|
||
}
|
||
.nav-group ul {
|
||
list-style: none;
|
||
padding: 8px 0 0;
|
||
margin: 0;
|
||
}
|
||
.nav-item {
|
||
margin-bottom: 4px;
|
||
border-radius: 6px;
|
||
}
|
||
.nav-item a {
|
||
display: block;
|
||
color: #32547f;
|
||
text-decoration: none;
|
||
font-size: 12px;
|
||
padding: 6px 8px;
|
||
border-radius: 6px;
|
||
word-break: break-all;
|
||
}
|
||
.nav-item a:hover {
|
||
background: #eef5ff;
|
||
color: #123e79;
|
||
}
|
||
.window-link {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
cursor: pointer;
|
||
user-select: none;
|
||
}
|
||
.window-link:hover {
|
||
text-decoration: underline;
|
||
}
|
||
.window-link:focus {
|
||
outline: 2px solid #8fb4ea;
|
||
outline-offset: 2px;
|
||
}
|
||
.doc-content {
|
||
min-width: 0;
|
||
}
|
||
.group-block h2 { margin: 0 0 12px; }
|
||
.group-block small { color: var(--muted); font-weight: normal; }
|
||
.method-card {
|
||
background: var(--card);
|
||
border: 1px solid var(--line);
|
||
border-radius: 10px;
|
||
padding: 16px;
|
||
margin-bottom: 14px;
|
||
}
|
||
.method-header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
gap: 12px;
|
||
flex-wrap: wrap;
|
||
align-items: flex-start;
|
||
}
|
||
.method-header h3 { margin: 0 0 8px; }
|
||
.method-header p { margin: 0; color: var(--muted); }
|
||
.badges { display: flex; gap: 8px; flex-wrap: wrap; }
|
||
.badge {
|
||
border-radius: 999px;
|
||
padding: 5px 10px;
|
||
background: var(--accent-soft);
|
||
color: #174c94;
|
||
font-size: 12px;
|
||
border: 1px solid #c8def6;
|
||
white-space: nowrap;
|
||
}
|
||
details { margin-top: 12px; }
|
||
summary { cursor: pointer; color: #103f7a; font-weight: 600; }
|
||
.debug-panel {
|
||
border: 1px dashed #c6d9f2;
|
||
border-radius: 8px;
|
||
padding: 10px;
|
||
background: #fbfdff;
|
||
}
|
||
.debug-form {
|
||
display: grid;
|
||
gap: 8px;
|
||
margin-top: 10px;
|
||
}
|
||
.debug-form label {
|
||
color: #254974;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
}
|
||
.debug-form input,
|
||
.debug-form textarea {
|
||
width: 100%;
|
||
border: 1px solid #b5ccec;
|
||
border-radius: 8px;
|
||
padding: 8px 10px;
|
||
font-size: 13px;
|
||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||
background: #fff;
|
||
}
|
||
.debug-actions {
|
||
display: flex;
|
||
gap: 10px;
|
||
align-items: center;
|
||
flex-wrap: wrap;
|
||
}
|
||
.send-btn {
|
||
border: 1px solid #0f5cb2;
|
||
background: #1565c0;
|
||
color: #fff;
|
||
border-radius: 8px;
|
||
padding: 8px 12px;
|
||
cursor: pointer;
|
||
}
|
||
.send-btn:disabled {
|
||
opacity: 0.6;
|
||
cursor: not-allowed;
|
||
}
|
||
.req-result {
|
||
margin: 0;
|
||
min-height: 80px;
|
||
max-height: 260px;
|
||
overflow: auto;
|
||
background: #0d1d33;
|
||
color: #d8e7ff;
|
||
border-radius: 8px;
|
||
padding: 10px;
|
||
font-size: 12px;
|
||
}
|
||
table {
|
||
width: 100%;
|
||
border-collapse: collapse;
|
||
margin-top: 8px;
|
||
background: #fff;
|
||
}
|
||
th, td {
|
||
border: 1px solid var(--line);
|
||
padding: 8px 10px;
|
||
text-align: left;
|
||
vertical-align: top;
|
||
font-size: 13px;
|
||
}
|
||
th { background: #f6f9ff; }
|
||
.muted { color: var(--muted); }
|
||
.openapi-guide {
|
||
margin-top: 14px;
|
||
border: 1px solid #d7e4f7;
|
||
background: #fcfdff;
|
||
border-radius: 10px;
|
||
padding: 16px;
|
||
}
|
||
.openapi-guide h3 {
|
||
margin: 12px 0 8px;
|
||
font-size: 15px;
|
||
color: #1a4c8f;
|
||
}
|
||
.openapi-guide h3:first-child {
|
||
margin-top: 0;
|
||
}
|
||
.guide-code {
|
||
background: #0d1d33;
|
||
color: #d8e7ff;
|
||
border-radius: 8px;
|
||
padding: 12px;
|
||
font-size: 13px;
|
||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||
overflow-x: auto;
|
||
white-space: pre-wrap;
|
||
word-break: break-all;
|
||
line-height: 1.6;
|
||
margin: 4px 0 0;
|
||
}
|
||
.guide-notes {
|
||
list-style: disc;
|
||
padding-left: 20px;
|
||
margin: 4px 0 0;
|
||
color: var(--muted);
|
||
font-size: 13px;
|
||
line-height: 1.8;
|
||
}
|
||
.guide-notes code {
|
||
background: #e8f1fc;
|
||
padding: 1px 6px;
|
||
border-radius: 4px;
|
||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
||
font-size: 12px;
|
||
}
|
||
@media (max-width: 768px) {
|
||
.container { padding: 14px; }
|
||
.method-card { padding: 12px; }
|
||
.layout { grid-template-columns: 1fr; }
|
||
.sidebar {
|
||
position: static;
|
||
max-height: none;
|
||
}
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<main class="container">
|
||
<section class="hero">
|
||
<h1>${escapeHtml(docData.module || docName)} API 文档</h1>
|
||
<div class="meta">
|
||
<span>说明: ${escapeHtml(docData.description || '无')}</span>
|
||
<span>版本: ${escapeHtml(docData.version || 'N/A')}</span>
|
||
<span>更新: ${escapeHtml(docData.updatedAt || 'N/A')}</span>
|
||
<span>方法数: ${methodsCount}</span>
|
||
<span>统一入口: <strong>${escapeHtml(entryPath)}</strong></span>
|
||
${renderSeeAlsoLinks(docData.seeAlso)}
|
||
</div>
|
||
<div class="tabs">
|
||
${navHtml}
|
||
<a class="tab" href="${escapeHtml(changesUrl)}">查看变更记录</a>
|
||
<a class="tab" href="${escapeHtml(rawUrl)}">查看 JSON</a>
|
||
</div>
|
||
${isExternalApi ? '' : `<div class="global-auth">
|
||
<h3>全局 Authorization</h3>
|
||
<div class="row">
|
||
<input id="globalAuth" type="text" placeholder="Bearer xxxxx" />
|
||
<button type="button" id="clearAuthBtn">清空</button>
|
||
</div>
|
||
<p class="muted">设置后会自动注入所有“在线调试”请求头,保存在浏览器本地。</p>
|
||
<h3>全局业务 Header</h3>
|
||
${globalHeadersControls}
|
||
<p class="muted">来自 JSON 的 headers 定义;带 * 的字段为必填,支持下拉 list 选择。</p>
|
||
</div>`}
|
||
${isExternalApi ? '' : `<div class="doc-tools">
|
||
<h3>文档资源</h3>
|
||
<div class="doc-tools-actions">
|
||
${renderWindowElement('打开变更记录', changesUrl, 'doc-resource-link')}
|
||
${renderWindowElement('打开原文 JSON', rawUrl, 'doc-resource-link')}
|
||
<button type="button" id="previewChangesBtn">预览变更记录</button>
|
||
<button type="button" id="previewRawBtn">预览原文 JSON</button>
|
||
</div>
|
||
<pre id="docResourcePreview" class="req-result muted">点击上方按钮后,可直接预览当前文档的变更记录或原文 JSON。</pre>
|
||
</div>`}
|
||
${isExternalApi ? (docData.module === 'warehouse_notify' ? `<div class="openapi-guide">
|
||
<h3>请求方式</h3>
|
||
<pre class="guide-code">POST {notify_url}?app_key={app_key}&method={方法名}&timestamp={时间戳}&sign={签名}
|
||
Content-Type: application/json
|
||
|
||
{
|
||
"code": 200,
|
||
"data": { ... }
|
||
}</pre>
|
||
|
||
<h3>签名算法(MD5)</h3>
|
||
<pre class="guide-code">sign = MD5(self_app_secret + timestamp + bodyJson).toLowerCase()
|
||
|
||
其中:
|
||
self_app_secret = 平台分配的密钥
|
||
timestamp = Unix 秒级时间戳
|
||
bodyJson = JSON.stringify(请求体)
|
||
|
||
示例(假设 self_app_secret=abc123,请求体={"code":200,"data":{...}}):
|
||
bodyJson = {"code":200,"data":{...}}
|
||
timestamp = 1700000000
|
||
signText = abc1231700000000{"code":200,"data":{...}}
|
||
sign = md5(signText).toLowerCase() = ...</pre>
|
||
|
||
<h3>注意事项(外部系统接收方)</h3>
|
||
<ul class="guide-notes">
|
||
<li>通知由<strong> WMS 主动推送</strong>到您配置的 notify_url,外部系统<strong>接收并返回 HTTP 200</strong>即可</li>
|
||
<li>根据 query 中的 <code>method</code> 字段路由到不同处理逻辑(<code>notify.ping</code> / <code>notify.reply</code>)</li>
|
||
<li>根据 <code>data.type</code> 区分消息类别(<code>ai</code> / <code>bind</code> / <code>balance</code> / <code>error</code>)</li>
|
||
<li>验签时从 query 取 <code>sign</code>,本地计算 <code>MD5(self_app_secret + timestamp + bodyJson)</code> 比对</li>
|
||
<li>时间戳 <strong>timestamp</strong> 为 Unix 秒级时间戳,校验 ±10 分钟时效</li>
|
||
<li>签名结果为 32 位小写十六进制字符串</li>
|
||
<li>接收成功返回 <code>{"code":200}</code>,非 200 或 HTTP 状态码非 200 视为推送失败</li>
|
||
<li>WMS 推送超时 10 秒,失败<strong>不重试</strong>,仅记录日志</li>
|
||
</ul>
|
||
</div>` : `<div class="openapi-guide">
|
||
<h3>请求方式</h3>
|
||
<pre class="guide-code">POST ${isOpenapi ? '/openapi' : '/warehouse'}?method={方法名}&v=1.0×tamp={时间戳}&app_key={app_key}&sign={签名}
|
||
Content-Type: application/json
|
||
|
||
{请求体 JSON}</pre>
|
||
|
||
<h3>签名算法(MD5)</h3>
|
||
<pre class="guide-code">参与签名字符串 = canonicalQuery + self_app_secret + bodySign
|
||
最终签名 sign = md5(参与签名字符串).toLowerCase()
|
||
|
||
其中:
|
||
canonicalQuery = 将 query 参数(排除 sign/signature)按 key 字母序升序排列,
|
||
拼接为 key1=value1&key2=value2 格式。
|
||
参数值序列化规则:undefined/null → 空字符串,
|
||
对象类型 → stableStringify 序列化,其他 → String(value)。
|
||
bodySign = md5(stableStringify(请求体))
|
||
stableStringify = 递归排序对象 key 的稳定序列化:
|
||
- 对普通对象,按 key 字母序递归序列化每个字段
|
||
- 对数组,按顺序递归序列化每个元素
|
||
- 对非普通对象(Date 等),使用 JSON.stringify
|
||
- undefined 返回空字符串,null 返回 "null"
|
||
self_app_secret = 平台分配的密钥
|
||
|
||
示例(假设 self_app_secret=abc123,请求体={"id":1}):
|
||
query: app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0
|
||
canonicalQuery = app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0
|
||
stableStringify({"id":1}) = {"id":1}
|
||
bodySign = md5({"id":1}) = 0a5b3e...
|
||
signText = app_key=myapp&method=index.ping&timestamp=1700000000&v=1.0abc1230a5b3e...
|
||
sign = md5(signText) = ...</pre>
|
||
|
||
<h3>注意事项</h3>
|
||
<ul class="guide-notes">
|
||
<li><strong>method</strong> 格式为 <code>模块.方法</code>,如 <code>index.ping</code></li>
|
||
<li><strong>app_key</strong> / <strong>self_app_secret</strong> 由仓库申请配置,请联系仓库管理员获取</li>
|
||
<li>请求体必须为合法 JSON,空 body 传 <code>{}</code></li>
|
||
<li>时间戳 <strong>timestamp</strong> 为 Unix 秒级时间戳(数字类型)</li>
|
||
<li>时间戳 <strong>timestamp</strong> 时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),超时返回 400</li>
|
||
<li>签名结果为 32 位小写十六进制字符串</li>
|
||
</ul>
|
||
${isOpenapi ? `<p style="margin-top:12px;font-size:13px;">
|
||
<a href="/docs/api/openapi/callback-test" style="color:#1565c0;">→ 回调测试工具</a>
|
||
<span class="muted">(模拟接收回调通知,验证回调链路)</span>
|
||
</p>` : ''}
|
||
</div>`) : ''}
|
||
</section>
|
||
|
||
<section class="layout">
|
||
<aside class="sidebar">
|
||
<div class="search-box">
|
||
<input id="methodSearch" type="text" placeholder="快速搜索: 方法名 / 描述" />
|
||
<div class="search-actions">
|
||
<button type="button" id="expandAllBtn">展开全部</button>
|
||
<button type="button" id="collapseAllBtn">折叠全部</button>
|
||
</div>
|
||
<p id="searchStats" class="muted">共 ${methodsCount} 个方法</p>
|
||
</div>
|
||
${sidebarHtml || '<p class="muted">暂无导航数据</p>'}
|
||
</aside>
|
||
|
||
<section class="doc-content">
|
||
${groupHtml || '<p class="muted">暂无可展示的方法定义</p>'}
|
||
</section>
|
||
</section>
|
||
</main>
|
||
<script>
|
||
(function() {
|
||
var DOC_NAME = ${JSON.stringify(docName)};
|
||
var IS_OPENAPI_DOC = DOC_NAME === 'openapi';
|
||
var IS_EXTERNAL_API_DOC = DOC_NAME === 'openapi' || DOC_NAME === 'warehouse' || DOC_NAME === 'warehouse_notify';
|
||
var AUTH_KEY = 'wms_docs_global_auth';
|
||
var HEADER_STORE_KEY = 'wms_docs_global_headers_' + ${JSON.stringify(docName)};
|
||
var OPENAPI_APP_KEY_STORE_KEY = 'wms_docs_' + DOC_NAME + '_app_key';
|
||
var authInput = document.getElementById('globalAuth');
|
||
var clearBtn = document.getElementById('clearAuthBtn');
|
||
var searchInput = document.getElementById('methodSearch');
|
||
var searchStats = document.getElementById('searchStats');
|
||
var expandAllBtn = document.getElementById('expandAllBtn');
|
||
var collapseAllBtn = document.getElementById('collapseAllBtn');
|
||
var previewChangesBtn = document.getElementById('previewChangesBtn');
|
||
var previewRawBtn = document.getElementById('previewRawBtn');
|
||
var resourcePreview = document.getElementById('docResourcePreview');
|
||
var changesUrl = ${JSON.stringify(changesUrl)};
|
||
var rawUrl = ${JSON.stringify(rawUrl)};
|
||
var defaultEntryPath = ${JSON.stringify(entryPath)};
|
||
|
||
function openWindowHref(target) {
|
||
var href = target && target.getAttribute('data-window-href');
|
||
if (!href) {
|
||
return;
|
||
}
|
||
|
||
var popup = window.open(href, '_blank', 'noopener,noreferrer');
|
||
if (popup) {
|
||
popup.opener = null;
|
||
popup.focus();
|
||
}
|
||
}
|
||
|
||
function nowTimestamp() {
|
||
return Math.floor(Date.now() / 1000);
|
||
}
|
||
|
||
/**
|
||
* 计算字符串 MD5(小写十六进制)。
|
||
* @param {string} value 待计算字符串。
|
||
* @return {string} MD5 结果。
|
||
*/
|
||
function md5(value) {
|
||
function add32(a, b) {
|
||
return (a + b) & 0xFFFFFFFF;
|
||
}
|
||
|
||
function cmn(q, a, b, x, s, t) {
|
||
a = add32(add32(a, q), add32(x, t));
|
||
return add32((a << s) | (a >>> (32 - s)), b);
|
||
}
|
||
|
||
function ff(a, b, c, d, x, s, t) {
|
||
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
|
||
}
|
||
|
||
function gg(a, b, c, d, x, s, t) {
|
||
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
|
||
}
|
||
|
||
function hh(a, b, c, d, x, s, t) {
|
||
return cmn(b ^ c ^ d, a, b, x, s, t);
|
||
}
|
||
|
||
function ii(a, b, c, d, x, s, t) {
|
||
return cmn(c ^ (b | (~d)), a, b, x, s, t);
|
||
}
|
||
|
||
function md5cycle(state, block) {
|
||
var a = state[0];
|
||
var b = state[1];
|
||
var c = state[2];
|
||
var d = state[3];
|
||
|
||
a = ff(a, b, c, d, block[0], 7, -680876936);
|
||
d = ff(d, a, b, c, block[1], 12, -389564586);
|
||
c = ff(c, d, a, b, block[2], 17, 606105819);
|
||
b = ff(b, c, d, a, block[3], 22, -1044525330);
|
||
a = ff(a, b, c, d, block[4], 7, -176418897);
|
||
d = ff(d, a, b, c, block[5], 12, 1200080426);
|
||
c = ff(c, d, a, b, block[6], 17, -1473231341);
|
||
b = ff(b, c, d, a, block[7], 22, -45705983);
|
||
a = ff(a, b, c, d, block[8], 7, 1770035416);
|
||
d = ff(d, a, b, c, block[9], 12, -1958414417);
|
||
c = ff(c, d, a, b, block[10], 17, -42063);
|
||
b = ff(b, c, d, a, block[11], 22, -1990404162);
|
||
a = ff(a, b, c, d, block[12], 7, 1804603682);
|
||
d = ff(d, a, b, c, block[13], 12, -40341101);
|
||
c = ff(c, d, a, b, block[14], 17, -1502002290);
|
||
b = ff(b, c, d, a, block[15], 22, 1236535329);
|
||
|
||
a = gg(a, b, c, d, block[1], 5, -165796510);
|
||
d = gg(d, a, b, c, block[6], 9, -1069501632);
|
||
c = gg(c, d, a, b, block[11], 14, 643717713);
|
||
b = gg(b, c, d, a, block[0], 20, -373897302);
|
||
a = gg(a, b, c, d, block[5], 5, -701558691);
|
||
d = gg(d, a, b, c, block[10], 9, 38016083);
|
||
c = gg(c, d, a, b, block[15], 14, -660478335);
|
||
b = gg(b, c, d, a, block[4], 20, -405537848);
|
||
a = gg(a, b, c, d, block[9], 5, 568446438);
|
||
d = gg(d, a, b, c, block[14], 9, -1019803690);
|
||
c = gg(c, d, a, b, block[3], 14, -187363961);
|
||
b = gg(b, c, d, a, block[8], 20, 1163531501);
|
||
a = gg(a, b, c, d, block[13], 5, -1444681467);
|
||
d = gg(d, a, b, c, block[2], 9, -51403784);
|
||
c = gg(c, d, a, b, block[7], 14, 1735328473);
|
||
b = gg(b, c, d, a, block[12], 20, -1926607734);
|
||
|
||
a = hh(a, b, c, d, block[5], 4, -378558);
|
||
d = hh(d, a, b, c, block[8], 11, -2022574463);
|
||
c = hh(c, d, a, b, block[11], 16, 1839030562);
|
||
b = hh(b, c, d, a, block[14], 23, -35309556);
|
||
a = hh(a, b, c, d, block[1], 4, -1530992060);
|
||
d = hh(d, a, b, c, block[4], 11, 1272893353);
|
||
c = hh(c, d, a, b, block[7], 16, -155497632);
|
||
b = hh(b, c, d, a, block[10], 23, -1094730640);
|
||
a = hh(a, b, c, d, block[13], 4, 681279174);
|
||
d = hh(d, a, b, c, block[0], 11, -358537222);
|
||
c = hh(c, d, a, b, block[3], 16, -722521979);
|
||
b = hh(b, c, d, a, block[6], 23, 76029189);
|
||
a = hh(a, b, c, d, block[9], 4, -640364487);
|
||
d = hh(d, a, b, c, block[12], 11, -421815835);
|
||
c = hh(c, d, a, b, block[15], 16, 530742520);
|
||
b = hh(b, c, d, a, block[2], 23, -995338651);
|
||
|
||
a = ii(a, b, c, d, block[0], 6, -198630844);
|
||
d = ii(d, a, b, c, block[7], 10, 1126891415);
|
||
c = ii(c, d, a, b, block[14], 15, -1416354905);
|
||
b = ii(b, c, d, a, block[5], 21, -57434055);
|
||
a = ii(a, b, c, d, block[12], 6, 1700485571);
|
||
d = ii(d, a, b, c, block[3], 10, -1894986606);
|
||
c = ii(c, d, a, b, block[10], 15, -1051523);
|
||
b = ii(b, c, d, a, block[1], 21, -2054922799);
|
||
a = ii(a, b, c, d, block[8], 6, 1873313359);
|
||
d = ii(d, a, b, c, block[15], 10, -30611744);
|
||
c = ii(c, d, a, b, block[6], 15, -1560198380);
|
||
b = ii(b, c, d, a, block[13], 21, 1309151649);
|
||
a = ii(a, b, c, d, block[4], 6, -145523070);
|
||
d = ii(d, a, b, c, block[11], 10, -1120210379);
|
||
c = ii(c, d, a, b, block[2], 15, 718787259);
|
||
b = ii(b, c, d, a, block[9], 21, -343485551);
|
||
|
||
state[0] = add32(a, state[0]);
|
||
state[1] = add32(b, state[1]);
|
||
state[2] = add32(c, state[2]);
|
||
state[3] = add32(d, state[3]);
|
||
}
|
||
|
||
function md5blk(str) {
|
||
var block = [];
|
||
for (var i = 0; i < 64; i += 4) {
|
||
block[i >> 2] = str.charCodeAt(i)
|
||
+ (str.charCodeAt(i + 1) << 8)
|
||
+ (str.charCodeAt(i + 2) << 16)
|
||
+ (str.charCodeAt(i + 3) << 24);
|
||
}
|
||
return block;
|
||
}
|
||
|
||
function md51(str) {
|
||
var state = [ 1732584193, -271733879, -1732584194, 271733878 ];
|
||
var originalLength = str.length;
|
||
var i;
|
||
for (i = 64; i <= str.length; i += 64) {
|
||
md5cycle(state, md5blk(str.substring(i - 64, i)));
|
||
}
|
||
str = str.substring(i - 64);
|
||
var tail = new Array(16).fill(0);
|
||
for (i = 0; i < str.length; i += 1) {
|
||
tail[i >> 2] |= str.charCodeAt(i) << ((i % 4) << 3);
|
||
}
|
||
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
|
||
if (i > 55) {
|
||
md5cycle(state, tail);
|
||
tail = new Array(16).fill(0);
|
||
}
|
||
tail[14] = originalLength * 8;
|
||
md5cycle(state, tail);
|
||
return state;
|
||
}
|
||
|
||
function rhex(n) {
|
||
var hex = '0123456789abcdef';
|
||
var output = '';
|
||
for (var j = 0; j < 4; j += 1) {
|
||
output += hex.charAt((n >> (j * 8 + 4)) & 0x0F) + hex.charAt((n >> (j * 8)) & 0x0F);
|
||
}
|
||
return output;
|
||
}
|
||
|
||
function hex(x) {
|
||
return x.map(rhex).join('');
|
||
}
|
||
|
||
return hex(md51(unescape(encodeURIComponent(String(value || '')))));
|
||
}
|
||
|
||
/**
|
||
* 判断输入是否为普通对象。
|
||
* @param {*} value 任意值。
|
||
* @return {boolean} 是否为普通对象。
|
||
*/
|
||
function isPlainObject(value) {
|
||
return Object.prototype.toString.call(value) === '[object Object]';
|
||
}
|
||
|
||
/**
|
||
* 以稳定顺序序列化对象,用于签名。
|
||
* @param {*} value 待序列化值。
|
||
* @return {string} 序列化字符串。
|
||
*/
|
||
function stableStringify(value) {
|
||
if (value === undefined) {
|
||
return '';
|
||
}
|
||
|
||
if (value === null || typeof value !== 'object') {
|
||
return JSON.stringify(value);
|
||
}
|
||
|
||
if (Array.isArray(value)) {
|
||
return '[' + value.map(function(item) {
|
||
return stableStringify(item);
|
||
}).join(',') + ']';
|
||
}
|
||
|
||
if (!isPlainObject(value)) {
|
||
return JSON.stringify(value);
|
||
}
|
||
|
||
var keys = Object.keys(value).sort();
|
||
return '{' + keys.map(function(key) {
|
||
return JSON.stringify(key) + ':' + stableStringify(value[key]);
|
||
}).join(',') + '}';
|
||
}
|
||
|
||
/**
|
||
* 将 query 字符串解析为对象。
|
||
* @param {string} queryText query 文本。
|
||
* @return {Object} query 对象。
|
||
*/
|
||
function parseQueryString(queryText) {
|
||
var result = {};
|
||
var raw = String(queryText || '').trim();
|
||
if (raw.startsWith('?')) {
|
||
raw = raw.slice(1);
|
||
}
|
||
if (!raw) {
|
||
return result;
|
||
}
|
||
|
||
raw.split('&').forEach(function(part) {
|
||
if (!part) {
|
||
return;
|
||
}
|
||
|
||
var eqIndex = part.indexOf('=');
|
||
var rawKey = eqIndex >= 0 ? part.slice(0, eqIndex) : part;
|
||
var rawValue = eqIndex >= 0 ? part.slice(eqIndex + 1) : '';
|
||
var key = decodeURIComponent(rawKey || '').trim();
|
||
if (!key) {
|
||
return;
|
||
}
|
||
|
||
var value = decodeURIComponent(rawValue || '');
|
||
result[key] = value;
|
||
});
|
||
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 把 query 对象按 key 排序后编码为字符串。
|
||
* @param {Object} params query 对象。
|
||
* @return {string} query 字符串。
|
||
*/
|
||
function buildSortedQueryString(params) {
|
||
return Object.keys(params || {}).filter(function(key) {
|
||
return params[key] !== undefined;
|
||
}).sort().map(function(key) {
|
||
return encodeURIComponent(key) + '=' + encodeURIComponent(String(params[key] == null ? '' : params[key]));
|
||
}).join('&');
|
||
}
|
||
|
||
/**
|
||
* 归一化 query 参数值,规则与后端签名保持一致。
|
||
* @param {*} value 参数值。
|
||
* @return {string} 可用于签名拼接的字符串。
|
||
*/
|
||
function normalizeParamValue(value) {
|
||
if (value === undefined || value === null) {
|
||
return '';
|
||
}
|
||
|
||
if (typeof value === 'object') {
|
||
return stableStringify(value);
|
||
}
|
||
|
||
return String(value);
|
||
}
|
||
|
||
/**
|
||
* 构建参与签名的 canonical query。
|
||
* @param {Object} queryParams query 对象。
|
||
* @return {string} canonical query。
|
||
*/
|
||
function buildCanonicalQuery(queryParams) {
|
||
var ignoredSet = {
|
||
sign: true,
|
||
signature: true,
|
||
};
|
||
|
||
return Object.keys(queryParams || {}).filter(function(key) {
|
||
return !ignoredSet[String(key).toLowerCase()] && queryParams[key] !== undefined;
|
||
}).sort().map(function(key) {
|
||
return key + '=' + normalizeParamValue(queryParams[key]);
|
||
}).join('&');
|
||
}
|
||
|
||
/**
|
||
* 对 openapi 请求计算签名并回填 sign 字段。
|
||
* @param {string} queryText 原始 query 文本。
|
||
* @param {Object} requestBody 已解析的 body 对象。
|
||
* @param {string} selfAppSecret 本地输入密钥。
|
||
* @return {{ queryText: string, sign: string, bodySign: string }} 签名结果。
|
||
*/
|
||
function applyOpenapiSign(queryText, requestBody, selfAppSecret) {
|
||
var normalizedSecret = String(selfAppSecret || '').trim();
|
||
if (!normalizedSecret) {
|
||
throw new Error('openapi 签名失败: self_app_secret 不能为空');
|
||
}
|
||
|
||
var queryParams = parseQueryString(queryText);
|
||
var canonicalQuery = buildCanonicalQuery(queryParams);
|
||
var bodySign = md5(stableStringify(requestBody));
|
||
var sign = md5(canonicalQuery + normalizedSecret + bodySign);
|
||
queryParams.sign = sign;
|
||
|
||
return {
|
||
queryText: buildSortedQueryString(queryParams),
|
||
sign: sign,
|
||
bodySign: bodySign,
|
||
};
|
||
}
|
||
|
||
function formatPretty(text) {
|
||
try {
|
||
return JSON.stringify(JSON.parse(text), null, 2);
|
||
} catch (e) {
|
||
return text;
|
||
}
|
||
}
|
||
|
||
async function previewDocResource(url, title) {
|
||
if (resourcePreview) {
|
||
resourcePreview.textContent = title + ' 加载中...';
|
||
}
|
||
|
||
try {
|
||
var response = await fetch(url);
|
||
var text = await response.text();
|
||
var pretty = formatPretty(text);
|
||
if (resourcePreview) {
|
||
resourcePreview.textContent = title + ' (HTTP ' + response.status + ')' + pretty;
|
||
}
|
||
} catch (error) {
|
||
if (resourcePreview) {
|
||
resourcePreview.textContent = title + ' 加载失败: ' + error.message;
|
||
}
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 生成在线调试默认 Query 字符串。
|
||
* @param {HTMLElement} card 接口卡片节点。
|
||
* @return {string} 默认 Query 参数。
|
||
*/
|
||
function buildDefaultQuery(card) {
|
||
var moduleName = card.getAttribute('data-module') || '';
|
||
var methodName = card.getAttribute('data-method') || '';
|
||
if (moduleName === 'qimen') {
|
||
return 'app_key=&method=' + encodeURIComponent(methodName)
|
||
+ '&v=2.0&format=json&sign_method=md5&sign=×tamp=' + nowTimestamp();
|
||
}
|
||
if (moduleName === 'openapi' || moduleName === 'warehouse') {
|
||
return buildOpenapiQuery(card, '');
|
||
}
|
||
return 'method=' + encodeURIComponent(methodName) + '&v=1.0×tamp=' + nowTimestamp();
|
||
}
|
||
|
||
/**
|
||
* 根据 openapi method 与 app_key 生成 query 展示值。
|
||
* @param {HTMLElement} card 接口卡片节点。
|
||
* @param {string} appKey openapi app_key。
|
||
* @return {string} 生成后的 query。
|
||
*/
|
||
function buildOpenapiQuery(card, appKey) {
|
||
var methodName = card.getAttribute('data-method') || '';
|
||
return 'app_key=' + encodeURIComponent(String(appKey || '').trim())
|
||
+ '&method=' + encodeURIComponent(methodName)
|
||
+ '&v=1.0×tamp=' + nowTimestamp();
|
||
}
|
||
|
||
function initDefaultQueries() {
|
||
var cards = document.querySelectorAll('.method-card');
|
||
cards.forEach(function(card) {
|
||
var queryInput = card.querySelector('.req-query');
|
||
var bodyInput = card.querySelector('.req-body');
|
||
var moduleName = card.getAttribute('data-module') || '';
|
||
if (queryInput) {
|
||
if (moduleName === 'openapi' || moduleName === 'warehouse') {
|
||
var appKeyInput = card.querySelector('.req-app-key');
|
||
var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || '';
|
||
queryInput.value = buildOpenapiQuery(card, openapiAppKey);
|
||
} else if (!queryInput.value.trim()) {
|
||
queryInput.value = buildDefaultQuery(card);
|
||
}
|
||
}
|
||
if (bodyInput && !bodyInput.value.trim()) {
|
||
bodyInput.value = '{}';
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 刷新 openapi 页面所有卡片的只读 query 展示。
|
||
* @param {string} appKey 当前 app_key。
|
||
* @return {void}
|
||
*/
|
||
function refreshOpenapiQueryDisplays(appKey) {
|
||
if (!IS_EXTERNAL_API_DOC) {
|
||
return;
|
||
}
|
||
|
||
var cards = document.querySelectorAll('.method-card[data-module="openapi"], .method-card[data-module="warehouse"]');
|
||
cards.forEach(function(card) {
|
||
var queryInput = card.querySelector('.req-query');
|
||
if (!queryInput) {
|
||
return;
|
||
}
|
||
|
||
queryInput.value = buildOpenapiQuery(card, appKey);
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 加载 openapi 专用 app_key,并绑定输入变化自动持久化。
|
||
* @return {void}
|
||
*/
|
||
function initOpenapiAppKeyInputs() {
|
||
if (!IS_EXTERNAL_API_DOC) {
|
||
return;
|
||
}
|
||
|
||
var appKeyInputs = document.querySelectorAll('.req-app-key');
|
||
if (!appKeyInputs.length) {
|
||
return;
|
||
}
|
||
|
||
var storedAppKey = localStorage.getItem(OPENAPI_APP_KEY_STORE_KEY) || '';
|
||
appKeyInputs.forEach(function(input) {
|
||
input.value = storedAppKey;
|
||
input.addEventListener('input', function() {
|
||
var value = input.value.trim();
|
||
localStorage.setItem(OPENAPI_APP_KEY_STORE_KEY, value);
|
||
appKeyInputs.forEach(function(otherInput) {
|
||
if (otherInput !== input) {
|
||
otherInput.value = value;
|
||
}
|
||
});
|
||
refreshOpenapiQueryDisplays(value);
|
||
});
|
||
});
|
||
|
||
refreshOpenapiQueryDisplays(storedAppKey);
|
||
}
|
||
|
||
function normalizeText(text) {
|
||
return String(text || '').toLowerCase();
|
||
}
|
||
|
||
function getGlobalHeaderControls() {
|
||
return document.querySelectorAll('.global-header-control');
|
||
}
|
||
|
||
function saveGlobalHeaders() {
|
||
var payload = {};
|
||
getGlobalHeaderControls().forEach(function(control) {
|
||
var name = control.getAttribute('data-header-name');
|
||
if (!name) return;
|
||
payload[name] = control.value || '';
|
||
});
|
||
localStorage.setItem(HEADER_STORE_KEY, JSON.stringify(payload));
|
||
}
|
||
|
||
function loadGlobalHeaders() {
|
||
var raw = localStorage.getItem(HEADER_STORE_KEY) || '{}';
|
||
var data = {};
|
||
try {
|
||
data = JSON.parse(raw);
|
||
} catch (e) {
|
||
data = {};
|
||
}
|
||
|
||
getGlobalHeaderControls().forEach(function(control) {
|
||
var name = control.getAttribute('data-header-name');
|
||
if (!name) return;
|
||
if (Object.prototype.hasOwnProperty.call(data, name)) {
|
||
control.value = data[name] || '';
|
||
}
|
||
control.addEventListener('change', saveGlobalHeaders);
|
||
control.addEventListener('input', saveGlobalHeaders);
|
||
});
|
||
}
|
||
|
||
function collectGlobalHeaders() {
|
||
var headers = {};
|
||
var missingRequired = [];
|
||
|
||
getGlobalHeaderControls().forEach(function(control) {
|
||
var name = control.getAttribute('data-header-name');
|
||
var required = control.getAttribute('data-required') === 'true';
|
||
var value = (control.value || '').trim();
|
||
if (!name) return;
|
||
|
||
if (value) {
|
||
headers[name] = value;
|
||
} else if (required) {
|
||
missingRequired.push(name);
|
||
}
|
||
});
|
||
|
||
return {
|
||
headers: headers,
|
||
missingRequired: missingRequired,
|
||
};
|
||
}
|
||
|
||
function applySearch(keyword) {
|
||
var key = normalizeText(keyword).trim();
|
||
var cards = document.querySelectorAll('.method-card');
|
||
var groups = document.querySelectorAll('.group-block');
|
||
var navGroups = document.querySelectorAll('.nav-group');
|
||
var navItems = document.querySelectorAll('.nav-item');
|
||
var visibleCount = 0;
|
||
|
||
cards.forEach(function(card) {
|
||
var method = normalizeText(card.getAttribute('data-method'));
|
||
var desc = normalizeText(card.getAttribute('data-desc'));
|
||
var matched = !key || method.indexOf(key) >= 0 || desc.indexOf(key) >= 0;
|
||
card.style.display = matched ? '' : 'none';
|
||
if (matched) {
|
||
visibleCount += 1;
|
||
}
|
||
});
|
||
|
||
groups.forEach(function(group) {
|
||
var visibleCards = group.querySelectorAll('.method-card:not([style*="display: none"])').length;
|
||
group.style.display = visibleCards > 0 ? '' : 'none';
|
||
});
|
||
|
||
navItems.forEach(function(item) {
|
||
var method = normalizeText(item.getAttribute('data-method'));
|
||
var desc = normalizeText(item.getAttribute('data-desc'));
|
||
var matched = !key || method.indexOf(key) >= 0 || desc.indexOf(key) >= 0;
|
||
item.style.display = matched ? '' : 'none';
|
||
});
|
||
|
||
navGroups.forEach(function(group) {
|
||
var visibleItems = group.querySelectorAll('.nav-item:not([style*="display: none"])').length;
|
||
group.style.display = visibleItems > 0 ? '' : 'none';
|
||
if (key && visibleItems > 0) {
|
||
group.open = true;
|
||
}
|
||
});
|
||
|
||
if (searchStats) {
|
||
if (key) {
|
||
searchStats.textContent = '匹配 ' + visibleCount + ' / ${methodsCount} 个方法';
|
||
} else {
|
||
searchStats.textContent = '共 ${methodsCount} 个方法';
|
||
}
|
||
}
|
||
}
|
||
|
||
if (authInput) {
|
||
authInput.value = localStorage.getItem(AUTH_KEY) || '';
|
||
authInput.addEventListener('input', function() {
|
||
localStorage.setItem(AUTH_KEY, authInput.value.trim());
|
||
});
|
||
}
|
||
|
||
if (clearBtn) {
|
||
clearBtn.addEventListener('click', function() {
|
||
localStorage.removeItem(AUTH_KEY);
|
||
if (authInput) {
|
||
authInput.value = '';
|
||
}
|
||
});
|
||
}
|
||
|
||
loadGlobalHeaders();
|
||
initOpenapiAppKeyInputs();
|
||
|
||
if (searchInput) {
|
||
searchInput.addEventListener('input', function() {
|
||
applySearch(searchInput.value);
|
||
});
|
||
}
|
||
|
||
if (expandAllBtn) {
|
||
expandAllBtn.addEventListener('click', function() {
|
||
document.querySelectorAll('.nav-group').forEach(function(group) {
|
||
if (group.style.display !== 'none') {
|
||
group.open = true;
|
||
}
|
||
});
|
||
});
|
||
}
|
||
|
||
if (collapseAllBtn) {
|
||
collapseAllBtn.addEventListener('click', function() {
|
||
document.querySelectorAll('.nav-group').forEach(function(group) {
|
||
group.open = false;
|
||
});
|
||
});
|
||
}
|
||
|
||
if (previewChangesBtn) {
|
||
previewChangesBtn.addEventListener('click', function() {
|
||
previewDocResource(changesUrl, '变更记录');
|
||
});
|
||
}
|
||
|
||
if (previewRawBtn) {
|
||
previewRawBtn.addEventListener('click', function() {
|
||
previewDocResource(rawUrl, '原文 JSON');
|
||
});
|
||
}
|
||
|
||
document.addEventListener('click', function(event) {
|
||
var target = event.target.closest('[data-window-href]');
|
||
if (!target) {
|
||
return;
|
||
}
|
||
|
||
event.preventDefault();
|
||
openWindowHref(target);
|
||
});
|
||
|
||
document.addEventListener('keydown', function(event) {
|
||
var target = event.target.closest('[data-window-href]');
|
||
if (!target) {
|
||
return;
|
||
}
|
||
|
||
if (event.key !== 'Enter' && event.key !== ' ') {
|
||
return;
|
||
}
|
||
|
||
event.preventDefault();
|
||
openWindowHref(target);
|
||
});
|
||
|
||
document.addEventListener('click', async function(event) {
|
||
var btn = event.target.closest('.send-btn');
|
||
if (!btn) return;
|
||
|
||
var card = btn.closest('.method-card');
|
||
if (!card) return;
|
||
|
||
var queryInput = card.querySelector('.req-query');
|
||
var bodyInput = card.querySelector('.req-body');
|
||
var resultEl = card.querySelector('.req-result');
|
||
var endpoint = card.getAttribute('data-endpoint') || defaultEntryPath;
|
||
var moduleName = card.getAttribute('data-module') || '';
|
||
var loginRequired = card.getAttribute('data-login-required') === 'true';
|
||
|
||
var query = (queryInput && queryInput.value.trim()) || '';
|
||
var auth = (authInput && authInput.value.trim()) || localStorage.getItem(AUTH_KEY) || '';
|
||
var rawBody = (bodyInput && bodyInput.value.trim()) || '{}';
|
||
var globalHeaderData = collectGlobalHeaders();
|
||
var requestBody = null;
|
||
|
||
try {
|
||
requestBody = JSON.parse(rawBody);
|
||
} catch (error) {
|
||
if (resultEl) {
|
||
resultEl.textContent = '请求已阻止: Body 必须是合法 JSON。';
|
||
}
|
||
return;
|
||
}
|
||
|
||
if (moduleName === 'openapi' || moduleName === 'warehouse') {
|
||
var appKeyInput = card.querySelector('.req-app-key');
|
||
var openapiAppKey = (appKeyInput && appKeyInput.value.trim()) || '';
|
||
query = buildOpenapiQuery(card, openapiAppKey);
|
||
if (queryInput) {
|
||
queryInput.value = query;
|
||
}
|
||
|
||
var selfSecretInput = card.querySelector('.req-self-app-secret');
|
||
var selfAppSecret = (selfSecretInput && selfSecretInput.value.trim()) || '';
|
||
|
||
try {
|
||
var signed = applyOpenapiSign(query, requestBody, selfAppSecret);
|
||
query = signed.queryText;
|
||
if (queryInput) {
|
||
queryInput.value = query;
|
||
}
|
||
} catch (error) {
|
||
if (resultEl) {
|
||
resultEl.textContent = error.message;
|
||
}
|
||
return;
|
||
}
|
||
}
|
||
|
||
var url = query ? (endpoint + '?' + query) : endpoint;
|
||
|
||
var headers = {
|
||
'Content-Type': 'application/json',
|
||
};
|
||
Object.assign(headers, globalHeaderData.headers);
|
||
if (auth) {
|
||
headers.Authorization = auth;
|
||
}
|
||
|
||
if (globalHeaderData.missingRequired.length) {
|
||
if (resultEl) {
|
||
resultEl.textContent = '请求已阻止: 全局 Header 缺少必填项 -> ' + globalHeaderData.missingRequired.join(', ');
|
||
}
|
||
return;
|
||
}
|
||
|
||
var effectiveAuth = headers.Authorization || '';
|
||
|
||
if (loginRequired && !effectiveAuth) {
|
||
if (resultEl) {
|
||
resultEl.textContent = '请求已阻止: 当前接口 isNeedLogin=true,请先在页面顶部设置全局 Authorization。';
|
||
}
|
||
return;
|
||
}
|
||
|
||
btn.disabled = true;
|
||
if (resultEl) {
|
||
resultEl.textContent = '请求中...';
|
||
}
|
||
|
||
try {
|
||
var response = await fetch(url, {
|
||
method: 'POST',
|
||
headers: headers,
|
||
body: rawBody,
|
||
});
|
||
var text = await response.text();
|
||
var pretty = formatPretty(text);
|
||
if (resultEl) {
|
||
resultEl.textContent = 'HTTP ' + response.status + '\\n\\n' + pretty;
|
||
}
|
||
} catch (error) {
|
||
if (resultEl) {
|
||
resultEl.textContent = '请求失败: ' + error.message;
|
||
}
|
||
} finally {
|
||
btn.disabled = false;
|
||
}
|
||
});
|
||
|
||
initDefaultQueries();
|
||
applySearch('');
|
||
|
||
// ── warehouse_notify 模拟推送(每个方法卡上的按钮)──
|
||
document.querySelectorAll('.notify-send-btn').forEach(function(btn) {
|
||
btn.addEventListener('click', function() {
|
||
var card = btn.closest('.method-card');
|
||
var methodName = btn.getAttribute('data-method');
|
||
var notifyUrlInput = card.querySelector('.notify-url-input');
|
||
var appKeyInput = card.querySelector('.req-app-key');
|
||
var appSecretInput = card.querySelector('.req-self-app-secret');
|
||
var bodyTextarea = card.querySelector('.req-body');
|
||
var resultEl = card.querySelector('.req-result');
|
||
|
||
var url = (notifyUrlInput && notifyUrlInput.value || '').trim();
|
||
var appKey = (appKeyInput && appKeyInput.value || '').trim();
|
||
var appSecret = (appSecretInput && appSecretInput.value || '').trim();
|
||
var bodyStr = (bodyTextarea && bodyTextarea.value || '{}').trim();
|
||
|
||
if (!url) { resultEl.textContent = '请填写 notify_url'; resultEl.className = 'req-result error'; return; }
|
||
if (!appKey) { resultEl.textContent = '请填写 app_key'; resultEl.className = 'req-result error'; return; }
|
||
if (!appSecret) { resultEl.textContent = '请填写 self_app_secret'; resultEl.className = 'req-result error'; return; }
|
||
|
||
var bodyJson;
|
||
try { bodyJson = JSON.stringify(JSON.parse(bodyStr)); } catch (e) { resultEl.textContent = 'Body JSON 格式错误'; resultEl.className = 'req-result error'; return; }
|
||
|
||
var ts = Math.floor(Date.now() / 1000);
|
||
var sign = md5(appSecret + ts + bodyJson);
|
||
|
||
resultEl.textContent = '发送中...';
|
||
resultEl.className = 'req-result';
|
||
|
||
fetch(url + '?app_key=' + encodeURIComponent(appKey) + '&method=' + encodeURIComponent(methodName) + '×tamp=' + ts + '&sign=' + sign, {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' },
|
||
body: bodyJson,
|
||
}).then(function(res) {
|
||
return res.text().then(function(txt) { return { status: res.status, body: txt }; });
|
||
}).then(function(r) {
|
||
resultEl.textContent = 'HTTP ' + r.status + '\n' + r.body;
|
||
resultEl.className = r.status === 200 ? 'req-result success' : 'req-result error';
|
||
}).catch(function(err) {
|
||
resultEl.textContent = '推送失败: ' + err.message;
|
||
resultEl.className = 'req-result error';
|
||
});
|
||
});
|
||
});
|
||
})();
|
||
</script>
|
||
</body>
|
||
</html>`;
|
||
}
|
||
|
||
class DocsController extends Controller {
|
||
/**
|
||
* 返回 docs 目录索引页面。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async docsIndex() {
|
||
const { ctx } = this;
|
||
|
||
try {
|
||
const docsRootPath = getDocsRootPath(this.app);
|
||
const files = await collectDocsFiles(docsRootPath, docsRootPath);
|
||
files.sort((left, right) => left.relativePath.localeCompare(right.relativePath, 'zh-Hans-CN'));
|
||
ctx.set('Content-Type', 'text/html; charset=utf-8');
|
||
ctx.body = renderDocsIndexPage(files);
|
||
} catch (error) {
|
||
ctx.status = 500;
|
||
ctx.body = {
|
||
code: 500,
|
||
message: '读取 docs 目录失败',
|
||
error: error.message,
|
||
};
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 读取 docs 目录下的指定文件。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async docsFile() {
|
||
const { ctx } = this;
|
||
const rawRelativePath = ctx.params[0] || ctx.params.relPath || ctx.params.path || '';
|
||
const resolved = resolveDocsFilePath(this.app, rawRelativePath);
|
||
|
||
if (!resolved.ok) {
|
||
ctx.status = 400;
|
||
ctx.body = {
|
||
code: 400,
|
||
message: resolved.message || '无效文档路径',
|
||
};
|
||
return;
|
||
}
|
||
|
||
try {
|
||
await sendDocsFile(ctx, resolved.filePath);
|
||
} catch (error) {
|
||
if (error.code === 'ENOENT') {
|
||
ctx.status = 404;
|
||
ctx.body = {
|
||
code: 404,
|
||
message: `未找到 docs 文件: ${resolved.relativePath}`,
|
||
};
|
||
return;
|
||
}
|
||
|
||
ctx.status = 500;
|
||
ctx.body = {
|
||
code: 500,
|
||
message: '读取 docs 文件失败',
|
||
error: error.message,
|
||
};
|
||
}
|
||
}
|
||
|
||
async list() {
|
||
const { ctx } = this;
|
||
try {
|
||
const docs = await this.getDocNames();
|
||
if (!docs.length) {
|
||
ctx.status = 404;
|
||
ctx.body = {
|
||
code: 404,
|
||
message: 'methods 目录下没有可用的 JSON 文档',
|
||
};
|
||
return;
|
||
}
|
||
|
||
const fallback = docs.includes('system') ? 'system' : docs[0];
|
||
await this.renderDoc(fallback);
|
||
} catch (error) {
|
||
ctx.status = 500;
|
||
ctx.body = {
|
||
code: 500,
|
||
message: '读取文档失败',
|
||
error: error.message,
|
||
};
|
||
}
|
||
}
|
||
|
||
async api() {
|
||
await this.list();
|
||
}
|
||
|
||
/**
|
||
* 渲染 OpenAPI 文档独立页面。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async openapi() {
|
||
await this.renderDoc('openapi');
|
||
}
|
||
|
||
/**
|
||
* 渲染仓库开放 API 文档独立页面。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async warehouse() {
|
||
await this.renderDoc('warehouse');
|
||
}
|
||
|
||
async detail() {
|
||
const { ctx } = this;
|
||
const docName = ctx.params.docName;
|
||
await this.renderDoc(docName);
|
||
}
|
||
|
||
async raw() {
|
||
const { ctx } = this;
|
||
const docName = ctx.params.docName;
|
||
|
||
if (!isValidDocName(docName)) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '无效文档名' };
|
||
return;
|
||
}
|
||
|
||
const filePath = getDocFilePath(this.app, docName);
|
||
|
||
try {
|
||
const content = await fs.readFile(filePath, 'utf8');
|
||
ctx.type = 'application/json; charset=utf-8';
|
||
ctx.body = content;
|
||
} catch (error) {
|
||
ctx.status = 404;
|
||
ctx.body = {
|
||
code: 404,
|
||
message: `未找到文档: ${docName}`,
|
||
};
|
||
}
|
||
}
|
||
|
||
async changes() {
|
||
const { ctx } = this;
|
||
const docName = ctx.params.docName;
|
||
|
||
if (!isValidDocName(docName)) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '无效文档名' };
|
||
return;
|
||
}
|
||
|
||
const filePath = getDocChangesFilePath(this.app, docName);
|
||
|
||
try {
|
||
const content = await fs.readFile(filePath, 'utf8');
|
||
ctx.type = 'application/json; charset=utf-8';
|
||
ctx.body = toArray(JSON.parse(content));
|
||
} catch (error) {
|
||
if (error.code === 'ENOENT') {
|
||
ctx.type = 'application/json; charset=utf-8';
|
||
ctx.body = [];
|
||
return;
|
||
}
|
||
|
||
ctx.status = 500;
|
||
ctx.body = {
|
||
code: 500,
|
||
message: `读取变更记录失败: ${docName}`,
|
||
error: error.message,
|
||
};
|
||
}
|
||
}
|
||
|
||
async getDocNames() {
|
||
const docsDir = path.join(this.app.baseDir, 'methods');
|
||
const entries = await fs.readdir(docsDir, { withFileTypes: true });
|
||
|
||
return entries
|
||
.filter(entry => entry.isFile() && entry.name.endsWith('.json'))
|
||
.map(entry => entry.name.replace(/\.json$/i, ''))
|
||
.sort();
|
||
}
|
||
|
||
/**
|
||
* 渲染指定 API 文档详情页。
|
||
* @param {string} docName 文档名称(不含 .json 后缀)。
|
||
* @return {Promise<void>} 无返回值。
|
||
*/
|
||
async renderDoc(docName) {
|
||
const { ctx, app } = this;
|
||
|
||
if (!isValidDocName(docName)) {
|
||
ctx.status = 400;
|
||
ctx.body = { code: 400, message: '无效文档名' };
|
||
return;
|
||
}
|
||
|
||
const filePath = getDocFilePath(app, docName);
|
||
|
||
try {
|
||
const [ content, docs ] = await Promise.all([
|
||
fs.readFile(filePath, 'utf8'),
|
||
this.getDocNames(),
|
||
]);
|
||
|
||
const docData = JSON.parse(content);
|
||
const groups = normalizeGroups(docData);
|
||
const entryPath = resolveDocEntryPath(docData);
|
||
const html = renderHtmlPage({
|
||
docName,
|
||
docData,
|
||
groups,
|
||
docs,
|
||
entryPath,
|
||
});
|
||
|
||
ctx.type = 'text/html; charset=utf-8';
|
||
ctx.body = html;
|
||
} catch (error) {
|
||
ctx.status = 404;
|
||
ctx.body = {
|
||
code: 404,
|
||
message: `未找到文档或 JSON 格式错误: ${docName}`,
|
||
error: error.message,
|
||
};
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = DocsController;
|