- 回调 method 由 snake_case 事件名改为 模块.动作:entryorder.confirm / entryorder.match / deliveryorder.confirm / stockout.confirm / deliveryorder.cancel(原 order.cancel 与入站方法同名,改名避免 callback_url 误指向 /openapi 时被路由到取消单据接口)。
- 时间戳统一为秒级(String(Math.floor(Date.now()/1000))),与 /openapi 入站 ±600 秒时效校验及回调调试页一致。
- 报文体由 { event, data, metadata } 改为奇门同层级 { request: {...} }(移除 metadata,事件标识只靠 query 的 method);入库类回调与奇门侧共用同一份报文组装。
- deliveryorder.confirm 改为逐单发送(仅同步成功的订单);stockout.confirm 直接复用 buildStockoutConfirmDataInternal 结果。
- 修复 entryorder.match 死代码:绑定成功且本次新建绑定时回传,重复触发不重复通知,回传失败不影响绑定。
- 调试页 /docs/api/openapi/callback-test 按真实报文预填;新增出站回调文档页 /docs/api/openapi_callback 及入口链接。
- script/update-api-doc.cjs 支持 spec.newDoc 新建文档与 docMeta.description(附单测)。
- 文档:methods/openapi_callback.json、AI_METHOD_ROUTING.md 5.6 节、docs/openapi-callback-events.md、docs/api-doc-update-workflow.md 等。
579 lines
21 KiB
JavaScript
579 lines
21 KiB
JavaScript
const fs = require('fs');
|
||
const path = require('path');
|
||
|
||
const ROOT = process.cwd();
|
||
// 测试覆盖钩子:允许通过环境变量覆盖目标目录(未设置时保持原有 methods/ 与 methods/changes/ 默认值不变)
|
||
const METHODS_DIR = process.env.WMS_API_DOC_METHODS_DIR
|
||
? path.resolve(process.env.WMS_API_DOC_METHODS_DIR)
|
||
: path.join(ROOT, 'methods');
|
||
const CHANGES_DIR = process.env.WMS_API_DOC_CHANGES_DIR
|
||
? path.resolve(process.env.WMS_API_DOC_CHANGES_DIR)
|
||
: path.join(METHODS_DIR, 'changes');
|
||
|
||
function parseArgs(argv) {
|
||
const args = {
|
||
specPath: '',
|
||
dryRun: false,
|
||
docOnly: false,
|
||
help: false,
|
||
};
|
||
|
||
for (const item of argv) {
|
||
if (item === '--dry-run') {
|
||
args.dryRun = true;
|
||
continue;
|
||
}
|
||
|
||
if (item === '--doc-only') {
|
||
args.docOnly = true;
|
||
continue;
|
||
}
|
||
|
||
if (item === '--help' || item === '-h') {
|
||
args.help = true;
|
||
continue;
|
||
}
|
||
|
||
if (item.startsWith('--spec=')) {
|
||
const raw = String(item.slice('--spec='.length)).trim();
|
||
args.specPath = raw ? path.resolve(ROOT, raw) : '';
|
||
continue;
|
||
}
|
||
}
|
||
|
||
if (!args.help && !args.specPath) {
|
||
throw new Error('Missing required --spec=<path> argument.');
|
||
}
|
||
|
||
return args;
|
||
}
|
||
|
||
/**
|
||
* 打印脚本帮助文案(用法、选项、spec.newDoc 字段说明与新建文档示例命令)
|
||
*/
|
||
function printHelp() {
|
||
console.log([
|
||
'Usage:',
|
||
' npm run doc:api:update -- --spec=temp/api-doc-update.json',
|
||
' npm run doc:api:update -- --spec=temp/api-doc-update.json --dry-run',
|
||
' npm run doc:api:update -- --spec=temp/api-doc-update.json --doc-only',
|
||
'',
|
||
'Options:',
|
||
' --spec=<path> Path to the fixed update spec JSON file.',
|
||
' --dry-run Validate and print the planned changes without writing files.',
|
||
' --doc-only Update methods/<docName>.json only and skip methods/changes/<docName>.json.',
|
||
'',
|
||
'spec.newDoc (optional spec field, only used when methods/<docName>.json does not exist):',
|
||
' module Required, non-empty string. New doc root "module".',
|
||
' description Optional string, default "".',
|
||
' http Optional object, default { "path": "", "method": "POST" }.',
|
||
' headers Optional array, default [].',
|
||
' Other fields are passed through for future use (plain JSON values only).',
|
||
' Ignored when methods/<docName>.json already exists.',
|
||
'',
|
||
'Examples:',
|
||
' Create a new doc skeleton and write group/methods in one shot:',
|
||
' npm run doc:api:update -- --spec=temp/api-doc-create.json --dry-run',
|
||
' npm run doc:api:update -- --spec=temp/api-doc-create.json',
|
||
].join('\n'));
|
||
}
|
||
|
||
function isPlainObject(value) {
|
||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||
}
|
||
|
||
function assert(condition, message) {
|
||
if (!condition) {
|
||
throw new Error(message);
|
||
}
|
||
}
|
||
|
||
function readJsonFile(filePath) {
|
||
const raw = fs.readFileSync(filePath, 'utf8');
|
||
return {
|
||
json: JSON.parse(raw),
|
||
indent: detectIndent(raw),
|
||
eol: detectEol(raw),
|
||
};
|
||
}
|
||
|
||
function detectIndent(raw) {
|
||
// 取第一个带缩进的值行(对象键、数组元素对象 `{` 或字符串元素)作为单层缩进;
|
||
// 根为数组的文档(methods/changes/*.json)首行 `[` 后紧跟元素 `{`,
|
||
// 避免把第二层缩进误判为单层缩进,导致全文件重排
|
||
const match = raw.match(/^([ \t]+)[\[{"]/m);
|
||
return match ? match[1] : ' ';
|
||
}
|
||
|
||
function detectEol(raw) {
|
||
return raw.includes('\r\n') ? '\r\n' : '\n';
|
||
}
|
||
|
||
/**
|
||
* 返回本地时区的今天日期(YYYY-MM-DD,如 2026-09-12)
|
||
* @return {string} 今天日期字符串
|
||
*/
|
||
function formatLocalDate() {
|
||
const now = new Date();
|
||
const pad = value => String(value).padStart(2, '0');
|
||
return `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
|
||
}
|
||
|
||
function writeJsonFile(filePath, value, indent, eol) {
|
||
const formatted = JSON.stringify(value, null, indent).replace(/\n/g, eol);
|
||
fs.writeFileSync(filePath, `${formatted}${eol}`, 'utf8');
|
||
}
|
||
|
||
function ensureString(value, fieldPath) {
|
||
assert(typeof value === 'string' && value.trim(), `${fieldPath} must be a non-empty string.`);
|
||
}
|
||
|
||
function ensureBoolean(value, fieldPath) {
|
||
assert(typeof value === 'boolean', `${fieldPath} must be a boolean.`);
|
||
}
|
||
|
||
function ensureArray(value, fieldPath) {
|
||
assert(Array.isArray(value), `${fieldPath} must be an array.`);
|
||
}
|
||
|
||
function ensureStringArray(value, fieldPath) {
|
||
ensureArray(value, fieldPath);
|
||
value.forEach((item, index) => ensureString(item, `${fieldPath}[${index}]`));
|
||
}
|
||
|
||
/**
|
||
* 校验值必须是可 JSON 序列化的 plain 值(null / 字符串 / 数字 / 布尔 / plain 对象 / 数组,递归校验)
|
||
* @param {*} value 待校验值
|
||
* @param {string} fieldPath 字段路径(用于报错文案)
|
||
*/
|
||
function ensurePlainJson(value, fieldPath) {
|
||
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
||
return;
|
||
}
|
||
|
||
if (Array.isArray(value)) {
|
||
value.forEach((item, index) => ensurePlainJson(item, `${fieldPath}[${index}]`));
|
||
return;
|
||
}
|
||
|
||
assert(isPlainObject(value), `${fieldPath} must be a plain JSON value.`);
|
||
Object.keys(value).forEach(key => ensurePlainJson(value[key], `${fieldPath}.${key}`));
|
||
}
|
||
|
||
function validateListOption(option, fieldPath) {
|
||
assert(isPlainObject(option), `${fieldPath} must be an object.`);
|
||
const hasValue = Object.prototype.hasOwnProperty.call(option, 'value');
|
||
assert(hasValue, `${fieldPath}.value is required.`);
|
||
}
|
||
|
||
function validateNamedField(field, fieldPath, allowSource) {
|
||
assert(isPlainObject(field), `${fieldPath} must be an object.`);
|
||
ensureString(field.name, `${fieldPath}.name`);
|
||
ensureString(field.type, `${fieldPath}.type`);
|
||
ensureBoolean(field.required, `${fieldPath}.required`);
|
||
ensureString(field.description, `${fieldPath}.description`);
|
||
|
||
if (allowSource && Object.prototype.hasOwnProperty.call(field, 'source')) {
|
||
ensureString(field.source, `${fieldPath}.source`);
|
||
}
|
||
|
||
if (Object.prototype.hasOwnProperty.call(field, 'list')) {
|
||
ensureArray(field.list, `${fieldPath}.list`);
|
||
field.list.forEach((item, index) => validateListOption(item, `${fieldPath}.list[${index}]`));
|
||
}
|
||
}
|
||
|
||
function validateErrorField(field, fieldPath) {
|
||
assert(isPlainObject(field), `${fieldPath} must be an object.`);
|
||
assert(Object.prototype.hasOwnProperty.call(field, 'code'), `${fieldPath}.code is required.`);
|
||
ensureString(field.message, `${fieldPath}.message`);
|
||
}
|
||
|
||
function validateMethodDoc(methodDoc, fieldPath) {
|
||
assert(isPlainObject(methodDoc), `${fieldPath} must be an object.`);
|
||
ensureString(methodDoc.method, `${fieldPath}.method`);
|
||
ensureString(methodDoc.description, `${fieldPath}.description`);
|
||
ensureBoolean(methodDoc.isNeedAuth, `${fieldPath}.isNeedAuth`);
|
||
ensureBoolean(methodDoc.isNeedLogin, `${fieldPath}.isNeedLogin`);
|
||
ensureArray(methodDoc.headers, `${fieldPath}.headers`);
|
||
ensureArray(methodDoc.params, `${fieldPath}.params`);
|
||
ensureArray(methodDoc.response, `${fieldPath}.response`);
|
||
ensureArray(methodDoc.errors, `${fieldPath}.errors`);
|
||
|
||
methodDoc.headers.forEach((item, index) => validateNamedField(item, `${fieldPath}.headers[${index}]`, false));
|
||
methodDoc.params.forEach((item, index) => validateNamedField(item, `${fieldPath}.params[${index}]`, true));
|
||
methodDoc.response.forEach((item, index) => validateNamedField(item, `${fieldPath}.response[${index}]`, false));
|
||
methodDoc.errors.forEach((item, index) => validateErrorField(item, `${fieldPath}.errors[${index}]`));
|
||
}
|
||
|
||
function validateChange(change, fieldPath) {
|
||
assert(isPlainObject(change), `${fieldPath} must be an object.`);
|
||
ensureString(change.version, `${fieldPath}.version`);
|
||
ensureString(change.date, `${fieldPath}.date`);
|
||
ensureString(change.summary, `${fieldPath}.summary`);
|
||
ensureStringArray(change.methods, `${fieldPath}.methods`);
|
||
ensureStringArray(change.notes, `${fieldPath}.notes`);
|
||
|
||
if (Object.prototype.hasOwnProperty.call(change, 'type')) {
|
||
ensureString(change.type, `${fieldPath}.type`);
|
||
}
|
||
}
|
||
|
||
function validateCurrentDoc(doc, fieldPath) {
|
||
assert(isPlainObject(doc), `${fieldPath} must be an object.`);
|
||
assert(isPlainObject(doc.methods), `${fieldPath}.methods must be an object.`);
|
||
ensureArray(doc.methods.groups, `${fieldPath}.methods.groups`);
|
||
}
|
||
|
||
function validateCurrentChanges(changes, fieldPath) {
|
||
ensureArray(changes, fieldPath);
|
||
}
|
||
|
||
// spec.newDoc 保留键:module/description/http/headers 由骨架消费,version/updatedAt/methods 由骨架统一管理,不参与透传
|
||
const NEW_DOC_RESERVED_KEYS = new Set([ 'module', 'description', 'http', 'headers', 'version', 'updatedAt', 'methods' ]);
|
||
|
||
/**
|
||
* 校验 spec.newDoc(仅当目标文档不存在、需要自动创建骨架时调用)
|
||
* @param {object} newDoc 新建文档骨架配置
|
||
* @param {string} fieldPath 字段路径(用于报错文案)
|
||
*/
|
||
function validateNewDoc(newDoc, fieldPath) {
|
||
assert(isPlainObject(newDoc), `${fieldPath} must be an object.`);
|
||
ensureString(newDoc.module, `${fieldPath}.module`);
|
||
|
||
if (Object.prototype.hasOwnProperty.call(newDoc, 'description')) {
|
||
assert(typeof newDoc.description === 'string', `${fieldPath}.description must be a string.`);
|
||
}
|
||
|
||
if (Object.prototype.hasOwnProperty.call(newDoc, 'http')) {
|
||
assert(isPlainObject(newDoc.http), `${fieldPath}.http must be an object.`);
|
||
}
|
||
|
||
if (Object.prototype.hasOwnProperty.call(newDoc, 'headers')) {
|
||
ensureArray(newDoc.headers, `${fieldPath}.headers`);
|
||
}
|
||
|
||
// 未来扩展字段:跳过保留键,其余字段仅接受 plain JSON 值并原样透传
|
||
Object.keys(newDoc).forEach(key => {
|
||
if (!NEW_DOC_RESERVED_KEYS.has(key)) {
|
||
ensurePlainJson(newDoc[key], `${fieldPath}.${key}`);
|
||
}
|
||
});
|
||
}
|
||
|
||
/**
|
||
* 依据 spec.newDoc 与 spec.docMeta 生成新文档骨架(module/description/version/updatedAt/http/headers/methods.groups)
|
||
* @param {object} newDoc 已校验的 spec.newDoc
|
||
* @param {object} docMeta 已校验的 spec.docMeta(未提供时为 {})
|
||
* @return {object} 新文档骨架对象
|
||
*/
|
||
function buildNewDoc(newDoc, docMeta) {
|
||
const doc = {
|
||
module: newDoc.module,
|
||
description: newDoc.description || '',
|
||
version: (docMeta && docMeta.version) || '0.0.0',
|
||
updatedAt: (docMeta && docMeta.updatedAt) || formatLocalDate(),
|
||
http: newDoc.http || { path: '', method: 'POST' },
|
||
headers: newDoc.headers || [],
|
||
methods: { groups: [] },
|
||
};
|
||
|
||
// 未来扩展字段原样透传(保留键除外,已在校验阶段限制为 plain JSON 值)
|
||
Object.keys(newDoc).forEach(key => {
|
||
if (!NEW_DOC_RESERVED_KEYS.has(key)) {
|
||
doc[key] = cloneJson(newDoc[key]);
|
||
}
|
||
});
|
||
|
||
return doc;
|
||
}
|
||
|
||
/**
|
||
* 校验并规范化更新 spec(含新建文档 spec.newDoc 的判定与校验),返回执行计划所需的结构化信息
|
||
* @param {object} spec 更新 spec 对象
|
||
* @param {object} args 命令行参数(dryRun / docOnly)
|
||
* @return {object} 规范化结果(docName/docPath/changePath/docExists/changeExists/docMeta/group/methods/deleteMethods/change/newDoc)
|
||
*/
|
||
function validateSpec(spec, args) {
|
||
assert(isPlainObject(spec), 'Spec root must be an object.');
|
||
ensureString(spec.docName, 'spec.docName');
|
||
assert(/^[a-z0-9_-]+$/i.test(spec.docName), 'spec.docName must contain only letters, numbers, underscore, or dash.');
|
||
|
||
const docPath = path.join(METHODS_DIR, `${spec.docName}.json`);
|
||
const changePath = path.join(CHANGES_DIR, `${spec.docName}.json`);
|
||
|
||
const docExists = fs.existsSync(docPath);
|
||
if (!docExists) {
|
||
// 目标文档不存在时必须提供 spec.newDoc,否则给出可操作提示
|
||
assert(
|
||
Object.prototype.hasOwnProperty.call(spec, 'newDoc'),
|
||
`Target doc file not found: ${docPath} (provide spec.newDoc to create it)`
|
||
);
|
||
validateNewDoc(spec.newDoc, 'spec.newDoc');
|
||
}
|
||
|
||
const changeExists = fs.existsSync(changePath);
|
||
|
||
if (Object.prototype.hasOwnProperty.call(spec, 'docMeta')) {
|
||
assert(isPlainObject(spec.docMeta), 'spec.docMeta must be an object.');
|
||
if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'updatedAt')) {
|
||
ensureString(spec.docMeta.updatedAt, 'spec.docMeta.updatedAt');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'version')) {
|
||
ensureString(spec.docMeta.version, 'spec.docMeta.version');
|
||
}
|
||
if (Object.prototype.hasOwnProperty.call(spec.docMeta, 'description')) {
|
||
assert(typeof spec.docMeta.description === 'string', 'spec.docMeta.description must be a string.');
|
||
}
|
||
}
|
||
|
||
assert(isPlainObject(spec.group), 'spec.group must be an object.');
|
||
ensureString(spec.group.groupName, 'spec.group.groupName');
|
||
ensureString(spec.group.module, 'spec.group.module');
|
||
|
||
ensureArray(spec.methods, 'spec.methods');
|
||
assert(spec.methods.length > 0, 'spec.methods must contain at least one method doc.');
|
||
const methodNames = new Set();
|
||
spec.methods.forEach((item, index) => {
|
||
validateMethodDoc(item, `spec.methods[${index}]`);
|
||
assert(!methodNames.has(item.method), `Duplicate method in spec.methods: ${item.method}`);
|
||
methodNames.add(item.method);
|
||
});
|
||
|
||
let deleteMethods = [];
|
||
if (Object.prototype.hasOwnProperty.call(spec, 'deleteMethods')) {
|
||
ensureStringArray(spec.deleteMethods, 'spec.deleteMethods');
|
||
deleteMethods = spec.deleteMethods;
|
||
}
|
||
deleteMethods.forEach(item => {
|
||
assert(!methodNames.has(item), `Method conflict: ${item} appears in both spec.methods and spec.deleteMethods.`);
|
||
});
|
||
|
||
if (!args.docOnly) {
|
||
validateChange(spec.change, 'spec.change');
|
||
} else if (Object.prototype.hasOwnProperty.call(spec, 'change')) {
|
||
validateChange(spec.change, 'spec.change');
|
||
}
|
||
|
||
return {
|
||
docName: spec.docName,
|
||
docPath,
|
||
changePath,
|
||
docExists,
|
||
changeExists,
|
||
docMeta: spec.docMeta || {},
|
||
group: spec.group,
|
||
methods: spec.methods,
|
||
deleteMethods,
|
||
change: spec.change || null,
|
||
newDoc: spec.newDoc || null,
|
||
};
|
||
}
|
||
|
||
function findGroupIndex(groups, groupSpec) {
|
||
const byModule = groups.findIndex(group => group && group.module === groupSpec.module);
|
||
if (byModule >= 0) return byModule;
|
||
return groups.findIndex(group => group && group.groupName === groupSpec.groupName);
|
||
}
|
||
|
||
function findMethodLocation(groups, methodName) {
|
||
for (let groupIndex = 0; groupIndex < groups.length; groupIndex += 1) {
|
||
const group = groups[groupIndex];
|
||
const list = group && Array.isArray(group.list) ? group.list : [];
|
||
const methodIndex = list.findIndex(item => item && item.method === methodName);
|
||
if (methodIndex >= 0) {
|
||
return { groupIndex, methodIndex };
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
function cloneJson(value) {
|
||
return JSON.parse(JSON.stringify(value));
|
||
}
|
||
|
||
function applyDocUpdate(doc, groupSpec, methods, docMeta, deleteMethods = []) {
|
||
const groups = doc.methods.groups;
|
||
let groupIndex = findGroupIndex(groups, groupSpec);
|
||
|
||
if (groupIndex < 0) {
|
||
groups.push({
|
||
groupName: groupSpec.groupName,
|
||
module: groupSpec.module,
|
||
list: [],
|
||
});
|
||
groupIndex = groups.length - 1;
|
||
}
|
||
|
||
const targetGroup = groups[groupIndex];
|
||
targetGroup.groupName = groupSpec.groupName;
|
||
targetGroup.module = groupSpec.module;
|
||
if (!Array.isArray(targetGroup.list)) {
|
||
targetGroup.list = [];
|
||
}
|
||
|
||
const summary = {
|
||
inserted: [],
|
||
updated: [],
|
||
moved: [],
|
||
deleted: [],
|
||
deleteNotFound: [],
|
||
};
|
||
|
||
for (const methodDoc of methods) {
|
||
const nextMethod = cloneJson(methodDoc);
|
||
const existingLocation = findMethodLocation(groups, methodDoc.method);
|
||
|
||
if (!existingLocation) {
|
||
targetGroup.list.push(nextMethod);
|
||
summary.inserted.push(methodDoc.method);
|
||
continue;
|
||
}
|
||
|
||
if (existingLocation.groupIndex === groupIndex) {
|
||
targetGroup.list[existingLocation.methodIndex] = nextMethod;
|
||
summary.updated.push(methodDoc.method);
|
||
continue;
|
||
}
|
||
|
||
groups[existingLocation.groupIndex].list.splice(existingLocation.methodIndex, 1);
|
||
targetGroup.list.push(nextMethod);
|
||
summary.moved.push(methodDoc.method);
|
||
}
|
||
|
||
for (const methodName of deleteMethods) {
|
||
const location = findMethodLocation(groups, methodName);
|
||
if (!location) {
|
||
summary.deleteNotFound.push(methodName);
|
||
continue;
|
||
}
|
||
groups[location.groupIndex].list.splice(location.methodIndex, 1);
|
||
summary.deleted.push(methodName);
|
||
}
|
||
|
||
if (docMeta.updatedAt) {
|
||
doc.updatedAt = docMeta.updatedAt;
|
||
}
|
||
|
||
if (docMeta.version) {
|
||
doc.version = docMeta.version;
|
||
}
|
||
|
||
if (typeof docMeta.description === 'string') {
|
||
doc.description = docMeta.description;
|
||
}
|
||
|
||
return summary;
|
||
}
|
||
|
||
function appendChange(changes, change) {
|
||
const exists = changes.some(item => item && item.version === change.version);
|
||
assert(!exists, `Duplicate change version detected: ${change.version}`);
|
||
// 变更记录保持“新记录在数组开头”的顺序(与 methods/changes/*.json 现有约定一致)
|
||
changes.unshift(cloneJson(change));
|
||
}
|
||
|
||
/**
|
||
* 主流程:解析参数 → 校验 spec → 读取既有文档或按 spec.newDoc 生成骨架 → 应用更新 → 输出计划 → 写盘
|
||
* 新建场景:目标文档不存在时依据 spec.newDoc 生成骨架(2 空格缩进 + LF);变更文件不存在时视为空数组并自动创建
|
||
*/
|
||
function main() {
|
||
const args = parseArgs(process.argv.slice(2));
|
||
if (args.help) {
|
||
printHelp();
|
||
return;
|
||
}
|
||
|
||
assert(fs.existsSync(args.specPath), `Spec file not found: ${args.specPath}`);
|
||
|
||
const specRaw = fs.readFileSync(args.specPath, 'utf8');
|
||
const spec = JSON.parse(specRaw);
|
||
const normalized = validateSpec(spec, args);
|
||
|
||
// 目标文档不存在:依据 spec.newDoc 生成骨架(默认 2 空格缩进 + LF,与 methods/ 下多数文件风格一致)
|
||
const docState = normalized.docExists
|
||
? readJsonFile(normalized.docPath)
|
||
: { json: buildNewDoc(normalized.newDoc, normalized.docMeta), indent: ' ', eol: '\n' };
|
||
validateCurrentDoc(docState.json, normalized.docPath);
|
||
|
||
let changeState = null;
|
||
if (!args.docOnly) {
|
||
// 变更文件不存在:视为空数组,正式写入阶段自动创建(默认 2 空格缩进 + LF)
|
||
changeState = normalized.changeExists
|
||
? readJsonFile(normalized.changePath)
|
||
: { json: [], indent: ' ', eol: '\n' };
|
||
validateCurrentChanges(changeState.json, normalized.changePath);
|
||
}
|
||
|
||
const docNext = cloneJson(docState.json);
|
||
const summary = applyDocUpdate(docNext, normalized.group, normalized.methods, normalized.docMeta, normalized.deleteMethods);
|
||
JSON.parse(JSON.stringify(docNext));
|
||
|
||
let changeNext = null;
|
||
if (!args.docOnly) {
|
||
changeNext = cloneJson(changeState.json);
|
||
appendChange(changeNext, normalized.change);
|
||
JSON.parse(JSON.stringify(changeNext));
|
||
}
|
||
|
||
console.log(`docName: ${normalized.docName}`);
|
||
console.log(`group: ${normalized.group.module} (${normalized.group.groupName})`);
|
||
console.log(`inserted: ${summary.inserted.length ? summary.inserted.join(', ') : '-'}`);
|
||
console.log(`updated: ${summary.updated.length ? summary.updated.join(', ') : '-'}`);
|
||
console.log(`moved: ${summary.moved.length ? summary.moved.join(', ') : '-'}`);
|
||
console.log(`deleted: ${summary.deleted.length ? summary.deleted.join(', ') : '-'}`);
|
||
console.log(`delete-not-found: ${summary.deleteNotFound.length ? summary.deleteNotFound.join(', ') : '-'}`);
|
||
if (!args.docOnly && normalized.change) {
|
||
console.log(`change version: ${normalized.change.version}`);
|
||
}
|
||
|
||
if (args.dryRun) {
|
||
// dry-run 只打印计划(created 行标识将要新建的文件),绝不写盘
|
||
if (!normalized.docExists) {
|
||
console.log(`created: ${path.relative(ROOT, normalized.docPath)}`);
|
||
}
|
||
if (!args.docOnly && !normalized.changeExists) {
|
||
console.log(`created: ${path.relative(ROOT, normalized.changePath)}`);
|
||
}
|
||
console.log('dry-run: validated successfully, no files were written.');
|
||
return;
|
||
}
|
||
|
||
if (normalized.docExists) {
|
||
writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol);
|
||
console.log(`wrote: ${path.relative(ROOT, normalized.docPath)}`);
|
||
} else {
|
||
writeJsonFile(normalized.docPath, docNext, docState.indent, docState.eol);
|
||
console.log(`created: ${path.relative(ROOT, normalized.docPath)}`);
|
||
}
|
||
|
||
if (!args.docOnly) {
|
||
if (normalized.changeExists) {
|
||
writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol);
|
||
console.log(`wrote: ${path.relative(ROOT, normalized.changePath)}`);
|
||
} else {
|
||
// 变更文件不存在:兜底递归创建目录后新建文件
|
||
fs.mkdirSync(path.dirname(normalized.changePath), { recursive: true });
|
||
writeJsonFile(normalized.changePath, changeNext, changeState.indent, changeState.eol);
|
||
console.log(`created: ${path.relative(ROOT, normalized.changePath)}`);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (require.main === module) {
|
||
try {
|
||
main();
|
||
} catch (error) {
|
||
console.error(error.message || error);
|
||
process.exitCode = 1;
|
||
}
|
||
}
|
||
|
||
module.exports = {
|
||
applyDocUpdate,
|
||
buildNewDoc,
|
||
parseArgs,
|
||
validateNewDoc,
|
||
validateSpec,
|
||
};
|